//! Subscriptions from the ledger: recurring charges at one merchant, their price changes, trials, the next //! charge, and what the monthly keep-or-cancel review should ask. use fiscus_ledger::state::DecisionRecord; use fiscus_ledger::{Date, Decision, EffectivePayment, Haler, PaymentId, State}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; /// A charge of at most this much is a card check, not a payment for the service. pub const TRIAL_MAX: Haler = Haler(1_000); /// An automatically detected trial is assumed to end this many days after its card check. pub const TRIAL_DAYS: i32 = 30; /// A subscription that has not charged this many days after its due date has lapsed. pub const GRACE_DAYS: i32 = 10; /// Recurring payments in these categories (rent, energy, savings) are not subscriptions to review. pub const NOT_SUBSCRIPTIONS: &[&str] = &["housing", "utilities", "transfers", "income"]; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Cadence { Monthly, Yearly, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Status { Active, /// Due more than [`GRACE_DAYS`] ago and no charge since. Lapsed, /// The last decision was "cancel" and it has not charged since. Cancelled, /// Cancelled, and charged anyway. ChargedAfterCancel, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Charge { pub payment: PaymentId, pub date: Date, /// What it cost (positive). pub cost: Haler, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct PriceChange { pub from: Haler, pub to: Haler, pub on: Date, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Subscription { /// Stable key for decisions: the merchant key, plus `#` when one merchant bills /// several subscriptions (iCloud and Apple Music both come from `APPLE.COM/BILL`). pub key: String, pub merchant: String, pub merchant_key: String, pub cadence: Cadence, pub charges: Vec, /// The last charge. pub cost: Haler, /// The most recent change of price. pub price_change: Option, /// The price changed and nobody has decided at the new price yet. pub creep_alert: bool, pub next_charge: Date, pub status: Status, pub decision: Option, /// Active and not decided this month (a yearly one: only in the 30 days before it charges). pub needs_review: bool, pub category: Option, pub budget: Option, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Trial { pub key: String, pub merchant: String, pub payment: PaymentId, pub started: Date, pub ends: Date, /// `true` when the end is the 30-day guess, `false` when marked by hand. pub estimated: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum UpcomingKind { Charge, TrialEnds, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Upcoming { pub key: String, pub merchant: String, pub date: Date, pub kind: UpcomingKind, pub cost: Option, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Insight { pub subscriptions: Vec, pub trials: Vec, /// Charges and trial ends in `[today, today + 7]`, by date. pub upcoming: Vec, } /// `|a - b| ≤ 50 % of b`: a price rise stays with its subscription (Netflix went up 30 % at once). fn near(a: Haler, b: Haler) -> bool { (a.0 - b.0).unsigned_abs() * 2 <= b.0.unsigned_abs() } fn cadence_of(charges: &[&EffectivePayment]) -> Option { if charges.len() < 2 { return None; } let gaps: Vec = charges.windows(2).map(|w| w[0].date.days_until(w[1].date)).collect(); // Mostly one price: at most one change in every two steps (a shop's varying totals never pass). let changes = charges.windows(2).filter(|w| w[0].amount != w[1].amount).count(); if changes * 2 > gaps.len() || (gaps.len() == 1 && changes == 1) { return None; } if gaps.iter().all(|g| (26..=35).contains(g)) { Some(Cadence::Monthly) } else if gaps.iter().all(|g| (358..=373).contains(g)) { Some(Cadence::Yearly) } else { None } } pub fn analyse(state: &State, today: Date) -> Insight { let payments = state.effective_payments(); let mut by_merchant: BTreeMap<&str, Vec<&EffectivePayment>> = BTreeMap::new(); for p in &payments { let excluded = p.category.as_deref().is_some_and(|c| NOT_SUBSCRIPTIONS.contains(&c)); if p.amount.0 <= 0 && !p.merchant_key.is_empty() && !excluded { by_merchant.entry(&p.merchant_key).or_default().push(p); } } let mut insight = Insight::default(); for (key, charges) in &by_merchant { let cost = |p: &EffectivePayment| Haler(-p.amount.0); let full: Vec<&EffectivePayment> = charges.iter().copied().filter(|p| cost(p) > TRIAL_MAX).collect(); // Trials: the last card check with no full charge after it, or a payment marked by hand. let last_check = charges.iter().rfind(|p| cost(p) <= TRIAL_MAX); for p in charges.iter().filter(|p| p.trial_ends.is_some() || Some(*p) == last_check) { let converted = full.iter().any(|f| f.date > p.date && f.id != p.id); let (ends, estimated) = match p.trial_ends { Some(e) => (e, false), None => (p.date.add_days(TRIAL_DAYS), true), }; if !converted && ends >= today.add_days(-7) { insight.trials.push(Trial { key: (*key).into(), merchant: p.merchant.clone(), payment: p.id.clone(), started: p.date, ends, estimated }); } } // Clusters of similar amounts, in date order: a price change stays in its cluster. let mut clusters: Vec> = Vec::new(); for p in &full { let last_cost = |c: &Vec<&EffectivePayment>| cost(c.last().expect("clusters are never empty")); let best = clusters .iter_mut() .filter(|c| near(cost(p), last_cost(c))) .min_by_key(|c| (cost(p).0 - last_cost(c).0).unsigned_abs()); match best { Some(c) => c.push(p), None => clusters.push(vec![p]), } } let found: Vec<(Cadence, &Vec<&EffectivePayment>)> = clusters.iter().filter_map(|c| cadence_of(c).map(|cad| (cad, c))).collect(); let several = found.len() > 1; for (cadence, c) in found { let first = c[0]; let last = c[c.len() - 1]; let sub_key = if several { format!("{key}#{}", cost(first).0 / 100) } else { (*key).to_string() }; let price_change = c .windows(2) .rev() .find(|w| w[0].amount != w[1].amount) .map(|w| PriceChange { from: cost(w[0]), to: cost(w[1]), on: w[1].date }); let decision = state.decisions.get(&sub_key).and_then(|d| d.last()).cloned(); let next_charge = match cadence { Cadence::Monthly => last.date.add_months(1), Cadence::Yearly => last.date.add_years(1), }; let status = match &decision { Some(d) if d.decision == Decision::Cancel => { if c.iter().any(|p| p.date > d.on) { Status::ChargedAfterCancel } else { Status::Cancelled } } _ if today > next_charge.add_days(GRACE_DAYS) => Status::Lapsed, _ => Status::Active, }; let decided_at_cost = decision.as_ref().is_some_and(|d| d.amount == cost(last)); let decided_this_month = decision.as_ref().is_some_and(|d| d.on.month() == today.month()); let review_window = match cadence { Cadence::Monthly => true, Cadence::Yearly => today.days_until(next_charge) <= 30, }; insight.subscriptions.push(Subscription { key: sub_key, merchant: last.merchant.clone(), merchant_key: (*key).into(), cadence, charges: c.iter().map(|p| Charge { payment: p.id.clone(), date: p.date, cost: cost(p) }).collect(), cost: cost(last), creep_alert: price_change.is_some() && !decided_at_cost && status != Status::Cancelled, price_change, next_charge, needs_review: status == Status::Active && !decided_this_month && review_window, status, decision, category: last.category.clone(), budget: last.budget.clone(), }); } } let horizon = today.add_days(7); for s in insight.subscriptions.iter().filter(|s| s.status == Status::Active) { if (today..=horizon).contains(&s.next_charge) { insight.upcoming.push(Upcoming { key: s.key.clone(), merchant: s.merchant.clone(), date: s.next_charge, kind: UpcomingKind::Charge, cost: Some(s.cost) }); } } for t in &insight.trials { if (today..=horizon).contains(&t.ends) { insight.upcoming.push(Upcoming { key: t.key.clone(), merchant: t.merchant.clone(), date: t.ends, kind: UpcomingKind::TrialEnds, cost: None }); } } insight.upcoming.sort_by(|a, b| a.date.cmp(&b.date).then(a.key.cmp(&b.key))); insight.subscriptions.sort_by(|a, b| a.next_charge.cmp(&b.next_charge).then(a.key.cmp(&b.key))); insight.trials.sort_by(|a, b| a.ends.cmp(&b.ends).then(a.key.cmp(&b.key))); insight }