adk_payments/wallet/
kpi.rs1use std::sync::{Arc, Mutex};
5
6use adk_core::Result;
7use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use uuid::Uuid;
10
11use super::engine::Wallet;
12use super::error::{WALLET_WRONG_SITE_CODE, refused};
13use super::policy::{SpendCategory, category_name};
14
15pub const SPEND_METRIC: &str = "spend";
17pub const REVENUE_METRIC: &str = "revenue";
19pub const PROFIT_METRIC: &str = "profit";
21pub const COST_PER_LEAD_METRIC: &str = "cost_per_lead";
23pub const COST_PER_SALE_METRIC: &str = "cost_per_sale";
25
26#[async_trait]
29pub trait CommerceOutcomes: Send + Sync {
30 async fn revenue(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64>;
36
37 async fn leads(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64>;
43
44 async fn sales(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64>;
50}
51
52#[derive(Debug, Clone, Copy)]
53enum Outcome {
54 Revenue(u64),
55 Lead,
56 Sale(u64),
57}
58
59type OutcomeLog = Arc<Mutex<Vec<(DateTime<Utc>, Outcome)>>>;
61
62#[derive(Debug, Clone, Default)]
74pub struct InMemoryCommerceOutcomes {
75 events: OutcomeLog,
76}
77
78impl InMemoryCommerceOutcomes {
79 pub fn new() -> Self {
81 Self::default()
82 }
83
84 fn push(&self, at: DateTime<Utc>, outcome: Outcome) {
85 self.events.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((at, outcome));
86 }
87
88 pub fn record_lead(&self, at: DateTime<Utc>) {
90 self.push(at, Outcome::Lead);
91 }
92
93 pub fn record_sale(&self, at: DateTime<Utc>, amount: u64) {
95 self.push(at, Outcome::Sale(amount));
96 }
97
98 pub fn record_revenue(&self, at: DateTime<Utc>, amount: u64) {
100 self.push(at, Outcome::Revenue(amount));
101 }
102
103 fn sum(&self, from: DateTime<Utc>, to: DateTime<Utc>, pick: impl Fn(Outcome) -> u64) -> u64 {
104 self.events
105 .lock()
106 .unwrap_or_else(std::sync::PoisonError::into_inner)
107 .iter()
108 .filter(|(at, _)| *at >= from && *at < to)
109 .fold(0u64, |total, (_, outcome)| total.saturating_add(pick(*outcome)))
110 }
111}
112
113#[async_trait]
114impl CommerceOutcomes for InMemoryCommerceOutcomes {
115 async fn revenue(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64> {
116 Ok(self.sum(from, to, |outcome| match outcome {
117 Outcome::Revenue(amount) | Outcome::Sale(amount) => amount,
118 Outcome::Lead => 0,
119 }))
120 }
121
122 async fn leads(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64> {
123 Ok(self.sum(from, to, |outcome| u64::from(matches!(outcome, Outcome::Lead))))
124 }
125
126 async fn sales(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64> {
127 Ok(self.sum(from, to, |outcome| u64::from(matches!(outcome, Outcome::Sale(_)))))
128 }
129}
130
131pub struct WalletKpiSource {
153 wallet: Wallet,
154 site: Uuid,
155 outcomes: Option<Arc<dyn CommerceOutcomes>>,
156 name: String,
157}
158
159impl WalletKpiSource {
160 pub fn new(wallet: Wallet, site: Uuid) -> Self {
162 Self { wallet, site, outcomes: None, name: "spend".to_string() }
163 }
164
165 #[must_use]
167 pub fn with_outcomes(mut self, outcomes: Arc<dyn CommerceOutcomes>) -> Self {
168 self.outcomes = Some(outcomes);
169 self
170 }
171
172 #[must_use]
174 pub fn named(mut self, name: impl Into<String>) -> Self {
175 self.name = name.into();
176 self
177 }
178
179 pub fn name(&self) -> &str {
181 &self.name
182 }
183
184 pub async fn read(
192 &self,
193 site: Uuid,
194 metric: &str,
195 from: DateTime<Utc>,
196 to: DateTime<Utc>,
197 ) -> Result<Option<f64>> {
198 if site != self.site {
199 return Err(refused(
200 WALLET_WRONG_SITE_CODE,
201 format!("wallet {} serves another site than {site}", self.wallet.id()),
202 ));
203 }
204 let policy = self.wallet.policy();
205 let spend = |category| self.wallet.spent_between(category, from, to);
206 if metric == SPEND_METRIC {
207 return Ok(Some(policy.to_major(spend(None).await?)));
208 }
209 if let Some(name) = metric.strip_prefix("spend.") {
210 let category: Option<SpendCategory> =
211 serde_json::from_value(serde_json::Value::String(name.to_string())).ok();
212 return match category {
213 Some(category) if category_name(category) == name => {
214 Ok(Some(policy.to_major(spend(Some(category)).await?)))
215 }
216 _ => Ok(None),
217 };
218 }
219 let Some(outcomes) = &self.outcomes else {
220 return Ok(None);
221 };
222 let total = spend(None).await?;
223 let per = |count: u64| (count > 0).then(|| policy.to_major(total) / count as f64);
224 Ok(match metric {
225 REVENUE_METRIC => Some(policy.to_major(outcomes.revenue(from, to).await?)),
226 PROFIT_METRIC => {
227 let revenue = outcomes.revenue(from, to).await?;
228 Some(policy.to_major(revenue) - policy.to_major(total))
229 }
230 COST_PER_LEAD_METRIC => per(outcomes.leads(from, to).await?),
231 COST_PER_SALE_METRIC => per(outcomes.sales(from, to).await?),
232 _ => None,
233 })
234 }
235}