//! A month in numbers: where the money went (the slices of a pie, in thousandths that add up to 1000), money //! in and out, the last six months, how far along you are compared with last month by the same day, the //! merchants you paid most, and what the subscriptions took. Your own payments; transfers are not spending. use crate::spending::{between, inflow, is_spending, outflows, permille}; use crate::subscriptions::Insight; use fiscus_ledger::{Category, Date, Haler, State}; use serde::Serialize; use std::collections::BTreeMap; /// The pie shows this many categories; the rest are one slice. pub const SLICES: usize = 7; /// Months in the bars, this one included. pub const MONTHS: i32 = 6; pub const TOP_MERCHANTS: usize = 5; #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct Slice { /// `None`: every other category, together. pub category: Option, pub amount: Haler, /// Its share of the month's spending; the slices add up to 1000. pub permille: u32, } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct MonthTotal { /// The 1st of the month. pub month: Date, pub out: Haler, pub inflow: Haler, } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct MerchantTotal { pub key: String, /// As the latest payment to it wrote it. pub merchant: String, pub amount: Haler, pub count: usize, } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct MonthStats { /// The 1st of the month. pub month: Date, /// Largest first; at most [`SLICES`], then the rest. pub slices: Vec, pub out: Haler, pub inflow: Haler, /// In less out; negative when more went out. pub net: Haler, /// The last [`MONTHS`] months, oldest first, ending with this one. pub months: Vec, /// Spent last month up to the same day of the month (all of last month for a past month). pub same_day_last_month: Haler, /// Largest first. pub top_merchants: Vec, /// What the subscriptions charged this month. pub subscriptions: Haler, /// Their share of the month's spending, in thousandths (at most 1000). pub subscriptions_permille: u32, } /// `[start, end]` of `month`, cut at `today`; `None` for a month that has not begun. fn span(month: Date, today: Date) -> Option<(Date, Date)> { let start = month.month_start(); (start <= today).then(|| (start, start.month_end().min(today))) } fn spent(state: &State, from: Date, to: Date) -> Option { Haler::sum(outflows(&between(state, from, to))?.into_values()).ok() } /// The month of `month`, up to `today`. `insight` is `analyse(state, today)`. `None` for a month that has not /// begun, or when a sum would not fit. pub fn month_stats(state: &State, insight: &Insight, month: Date, today: Date) -> Option { let (start, end) = span(month, today)?; let payments = between(state, start, end); let by = outflows(&payments)?; let out = Haler::sum(by.values().copied()).ok()?; let inflow = inflow(&payments)?; let mut parts: Vec<(Category, Haler)> = by.into_iter().collect(); parts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); let mut slices: Vec<(Option, Haler)> = parts.iter().take(SLICES).map(|(c, a)| (Some(c.clone()), *a)).collect(); if parts.len() > SLICES { slices.push((None, Haler::sum(parts[SLICES..].iter().map(|(_, a)| *a)).ok()?)); } let shares = permille(&slices.iter().map(|(_, a)| *a).collect::>()); let mut months = Vec::new(); for n in (0..MONTHS).rev() { let m = start.add_months(-n); let (from, to) = span(m, today)?; let ps = between(state, from, to); months.push(MonthTotal { month: m, out: Haler::sum(outflows(&ps)?.into_values()).ok()?, inflow: crate::spending::inflow(&ps)? }); } let last = start.add_months(-1); let last_end = if end == start.month_end() { last.month_end() } else { last.add_days(end.ymd().2 as i32 - 1).min(last.month_end()) }; let same_day_last_month = spent(state, last, last_end)?; let mut merchants: BTreeMap<&str, MerchantTotal> = BTreeMap::new(); for p in payments.iter().filter(|p| is_spending(p) && !p.merchant_key.is_empty()) { let t = merchants.entry(&p.merchant_key).or_insert(MerchantTotal { key: p.merchant_key.clone(), merchant: String::new(), amount: Haler::ZERO, count: 0 }); t.merchant = p.merchant.clone(); t.amount = t.amount.checked_add(p.amount.checked_neg().ok()?).ok()?; t.count += 1; } let mut top_merchants: Vec = merchants.into_values().collect(); top_merchants.sort_by(|a, b| b.amount.cmp(&a.amount).then(a.key.cmp(&b.key))); top_merchants.truncate(TOP_MERCHANTS); // A subscription charge counts once, by the payment it was, and only when it is spending this month. let spending_ids: BTreeMap<&str, Haler> = payments .iter() .filter(|p| is_spending(p)) .flat_map(|p| [Some(p.id.as_str()), p.line.as_deref(), p.captured.as_deref()].into_iter().flatten().map(move |id| (id, p.amount))) .collect(); let mut charged = std::collections::BTreeSet::new(); let mut subscriptions = Haler::ZERO; for c in insight.subscriptions.iter().flat_map(|s| &s.charges) { let Some(paid) = spending_ids.get(c.payment.as_str()) else { continue }; if charged.insert(c.payment.as_str()) { subscriptions = subscriptions.checked_add(paid.checked_neg().ok()?).ok()?; } } let subscriptions_permille = if out.0 > 0 { (i128::from(subscriptions.0) * 1000 / i128::from(out.0)).clamp(0, 1000) as u32 } else { 0 }; Some(MonthStats { month: start, slices: slices.into_iter().zip(shares).map(|((category, amount), permille)| Slice { category, amount, permille }).collect(), net: inflow.checked_sub(out).ok()?, out, inflow, months, same_day_last_month, top_merchants, subscriptions, subscriptions_permille, }) }