Skip to main content

adk_payments/wallet/
kpi.rs

1//! Profit and loss, cost per lead and cost per sale as KPI sources (spec 3.5 §7.11,
2//! §7.12, §7.14).
3
4use 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
15/// Total settled spend, in major units of the wallet's currency.
16pub const SPEND_METRIC: &str = "spend";
17/// Revenue, in major units.
18pub const REVENUE_METRIC: &str = "revenue";
19/// Revenue less spend, in major units.
20pub const PROFIT_METRIC: &str = "profit";
21/// Spend per lead, in major units.
22pub const COST_PER_LEAD_METRIC: &str = "cost_per_lead";
23/// Spend per sale, in major units.
24pub const COST_PER_SALE_METRIC: &str = "cost_per_sale";
25
26/// The commerce side of profit and loss: what the site earned and the leads and sales it
27/// produced (spec 3.5 §7.12: the commerce ledger and the lead records).
28#[async_trait]
29pub trait CommerceOutcomes: Send + Sync {
30    /// Revenue in `[from, to)`, in minor units of the wallet's currency.
31    ///
32    /// # Errors
33    ///
34    /// Returns the source's error.
35    async fn revenue(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64>;
36
37    /// Leads in `[from, to)`.
38    ///
39    /// # Errors
40    ///
41    /// Returns the source's error.
42    async fn leads(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64>;
43
44    /// Sales in `[from, to)`.
45    ///
46    /// # Errors
47    ///
48    /// Returns the source's error.
49    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
59/// Outcomes in the order they were recorded.
60type OutcomeLog = Arc<Mutex<Vec<(DateTime<Utc>, Outcome)>>>;
61
62/// [`CommerceOutcomes`] kept in memory, for tests and fixtures.
63///
64/// # Example
65///
66/// ```
67/// use adk_payments::wallet::InMemoryCommerceOutcomes;
68///
69/// let outcomes = InMemoryCommerceOutcomes::new();
70/// outcomes.record_lead(chrono::Utc::now());
71/// outcomes.record_sale(chrono::Utc::now(), 4_900);
72/// ```
73#[derive(Debug, Clone, Default)]
74pub struct InMemoryCommerceOutcomes {
75    events: OutcomeLog,
76}
77
78impl InMemoryCommerceOutcomes {
79    /// No outcomes yet.
80    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    /// Records a lead at `at`.
89    pub fn record_lead(&self, at: DateTime<Utc>) {
90        self.push(at, Outcome::Lead);
91    }
92
93    /// Records a sale of `amount` minor units at `at`; it counts as revenue too.
94    pub fn record_sale(&self, at: DateTime<Utc>, amount: u64) {
95        self.push(at, Outcome::Sale(amount));
96    }
97
98    /// Records revenue that is not a sale, such as a donation, at `at`.
99    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
131/// The wallet as a KPI source for the KPI tracker (spec 3.5 §7.11, §7.12, §7.14): the
132/// `spend` source.
133///
134/// | Metric | Value over `[from, to)`, in major units | Needs |
135/// |--------|-------------------------------------------|-------|
136/// | `spend` | settled spend | — |
137/// | `spend.{category}` | settled spend in the category, such as `spend.models` | — |
138/// | `revenue` | revenue | [`CommerceOutcomes`] |
139/// | `profit` | revenue less spend | [`CommerceOutcomes`] |
140/// | `cost_per_lead` | spend per lead; none without leads | [`CommerceOutcomes`] |
141/// | `cost_per_sale` | spend per sale; none without sales | [`CommerceOutcomes`] |
142///
143/// [`read`](Self::read) has the signature of the kernel's `KpiSource::read`, so the
144/// tracker's adapter forwards to it. A wallet answers only for its own site (A-I22).
145///
146/// # Example
147///
148/// ```rust,ignore
149/// let source = WalletKpiSource::new(wallet, site_id).with_outcomes(Arc::new(outcomes));
150/// let profit = source.read(site_id, "profit", month_start, month_end).await?;
151/// ```
152pub struct WalletKpiSource {
153    wallet: Wallet,
154    site: Uuid,
155    outcomes: Option<Arc<dyn CommerceOutcomes>>,
156    name: String,
157}
158
159impl WalletKpiSource {
160    /// The `spend` source for `wallet`, which serves `site`.
161    pub fn new(wallet: Wallet, site: Uuid) -> Self {
162        Self { wallet, site, outcomes: None, name: "spend".to_string() }
163    }
164
165    /// Adds revenue, leads and sales for `revenue`, `profit` and the costs per outcome.
166    #[must_use]
167    pub fn with_outcomes(mut self, outcomes: Arc<dyn CommerceOutcomes>) -> Self {
168        self.outcomes = Some(outcomes);
169        self
170    }
171
172    /// Answers under another source name, such as `commerce`.
173    #[must_use]
174    pub fn named(mut self, name: impl Into<String>) -> Self {
175        self.name = name.into();
176        self
177    }
178
179    /// The source's name, as KPIs name it in their `source`.
180    pub fn name(&self) -> &str {
181        &self.name
182    }
183
184    /// The value of `metric` for `site` over `[from, to)`; `None` for a metric the source
185    /// cannot compute, such as a cost per lead with no leads.
186    ///
187    /// # Errors
188    ///
189    /// Returns `wallet.wrong_site` for another site's request, or the wallet's or
190    /// outcomes' error.
191    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}