[insight] Plans and statistics: category plans, categories of your own, one definition of spending, the month in numbers; v0.5.0

- category.planned (carries forward, zero removes it; spending categories only) and category.created
- fiscus-insight: spending (outflows, inflow, largest-remainder thousandths that add up to 1000), plan (the
  month against its plan with the pace, a suggested plan from the last three months), stats (pie slices, in,
  out, net, six months, same day last month, top merchants, subscriptions' share)
- docs/04_plans_stats.md; 11 new tests
This commit is contained in:
2026-11-06 13:02:39 +01:00
parent 4e8e80efb4
commit 03dc2061f9
13 changed files with 811 additions and 11 deletions
+5 -1
View File
@@ -1,7 +1,11 @@
//! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge,
//! how to cancel, and whether the month will stay under its limit. Pure: "today" and seeds are parameters.
//! how to cancel, whether the month will stay under its limit, where the money went and how it compares with
//! your plan. Pure: "today" and seeds are parameters.
pub mod cancel;
pub mod forecast;
pub mod household;
pub mod plan;
pub mod spending;
pub mod stats;
pub mod subscriptions;
+129
View File
@@ -0,0 +1,129 @@
//! The month against your plan: for each category, what you meant to spend (`category.planned`), what you
//! spent, what is left, and whether you are ahead of the pace the plan allows by today. Only your own payments
//! count, as in the forecast; what other members of a shared budget spend is theirs.
use crate::spending::{between, outflows};
use fiscus_ledger::categories::{self, NOT_PLANNABLE};
use fiscus_ledger::date::days_in_month;
use fiscus_ledger::{Category, Date, Haler, State};
use serde::Serialize;
/// How a planned category is doing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum Pace {
/// Below 90 % of what the plan allows by today (or, for a past month, within the plan).
Under,
OnPace,
/// Above 110 % of what the plan allows by today, not over the plan yet.
Ahead,
/// More than the whole month's plan.
Over,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct PlanRow {
pub category: Category,
pub planned: Option<Haler>,
pub spent: Haler,
/// Planned less spent; negative when over. `None` without a plan.
pub left: Option<Haler>,
/// Spent of the plan in thousandths, capped at 1000 (for a bar); 0 without a plan.
pub permille: u32,
/// `None` without a plan, and for a month that has not begun.
pub pace: Option<Pace>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct MonthPlan {
/// The 1st of the month.
pub month: Date,
/// The categories with a plan this month, in the app's order, then those spent on without a plan, the
/// largest first.
pub rows: Vec<PlanRow>,
/// All the plans of the month together.
pub planned: Haler,
/// Everything spent this month.
pub spent: Haler,
/// Of that, spent in categories without a plan.
pub unplanned: Haler,
}
fn pace(planned: Haler, spent: Haler, month: Date, today: Date) -> Option<Pace> {
if today < month {
return None;
}
if spent > planned {
return Some(Pace::Over);
}
if today > month.month_end() {
return Some(Pace::Under);
}
let (y, m, day) = today.ymd();
let allowed = i128::from(planned.0) * i128::from(day) / i128::from(days_in_month(y, m));
let spent = i128::from(spent.0) * 100;
Some(if spent > allowed * 110 {
Pace::Ahead
} else if spent < allowed * 90 {
Pace::Under
} else {
Pace::OnPace
})
}
/// The month of `month` against its plans. For this month, what is spent up to `today`; a later month has
/// nothing spent yet. `None` when a sum would not fit.
pub fn month_plan(state: &State, month: Date, today: Date) -> Option<MonthPlan> {
let start = month.month_start();
let end = start.month_end().min(today);
let spent_by = if end < start { Default::default() } else { outflows(&between(state, start, end))? };
let spent_in = |c: &str| spent_by.get(c).copied().unwrap_or(Haler::ZERO);
let mut rows = Vec::new();
for (category, _) in state.categories() {
let Some(planned) = state.plan_for(&category, start) else { continue };
let spent = spent_in(&category);
let permille = (i128::from(spent.0) * 1000 / i128::from(planned.0)).clamp(0, 1000) as u32;
rows.push(PlanRow { left: Some(planned.checked_sub(spent).ok()?), planned: Some(planned), permille, pace: pace(planned, spent, start, today), spent, category });
}
let mut extra: Vec<(&Category, &Haler)> = spent_by.iter().filter(|(c, _)| state.plan_for(c, start).is_none()).collect();
extra.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
let unplanned = Haler::sum(extra.iter().map(|(_, a)| **a)).ok()?;
rows.extend(extra.into_iter().map(|(c, a)| PlanRow { category: c.clone(), planned: None, spent: *a, left: None, permille: 0, pace: None }));
Some(MonthPlan {
month: start,
planned: Haler::sum(rows.iter().filter_map(|r| r.planned)).ok()?,
spent: Haler::sum(spent_by.values().copied()).ok()?,
unplanned,
rows,
})
}
/// A plan from your history: for each category you can plan, the average of what you spent on it over the last
/// three complete months, rounded **up** to whole hundreds of crowns. Only months since your first payment
/// count, so a ledger a month old is not divided by three. Categories you spent nothing on are left out.
pub fn suggest(state: &State, today: Date) -> Vec<(Category, Haler)> {
let this_month = today.month_start();
let Some(first) = state.effective_payments().first().map(|p| p.date.month_start()) else { return Vec::new() };
let months: Vec<Date> = (1..=3).map(|n| this_month.add_months(-n)).filter(|m| *m >= first).collect();
let Some(oldest) = months.last().copied() else { return Vec::new() };
let Some(spent) = outflows(&between(state, oldest, this_month.add_days(-1))) else { return Vec::new() };
let hundred = 10_000i128;
let mut out = Vec::new();
for (category, _) in state.categories() {
if NOT_PLANNABLE.contains(&category.as_str()) {
continue;
}
let Some(total) = spent.get(&category).filter(|t| t.0 > 0) else { continue };
// Both are positive: rounding up is (a + b - 1) / b.
let n = months.len() as i128;
let avg = (i128::from(total.0) + n - 1) / n;
let up = (avg + hundred - 1) / hundred * hundred;
match i64::try_from(up) {
Ok(v) if Haler(v) <= categories::MAX_PLAN => out.push((category, Haler(v))),
_ => out.push((category, categories::MAX_PLAN)),
}
}
out
}
+81
View File
@@ -0,0 +1,81 @@
//! One definition of spending, for every screen: money out of your own payments, as positive amounts, by
//! category. Money between your own accounts (`transfers`) is not spending; a payment nobody categorised counts
//! as `uncategorised`. Every sum is checked: `None` when one would not fit, never a wrong number.
use fiscus_ledger::categories::{TRANSFERS, UNCATEGORISED};
use fiscus_ledger::{Category, Date, EffectivePayment, Haler, State};
use std::collections::BTreeMap;
/// The payments dated in `[from, to]`, a confirmed pair as one.
pub fn between(state: &State, from: Date, to: Date) -> Vec<EffectivePayment> {
state.effective_payments().into_iter().filter(|p| p.date >= from && p.date <= to).collect()
}
/// The category a payment counts under.
pub fn category_of(p: &EffectivePayment) -> &str {
p.category.as_deref().unwrap_or(UNCATEGORISED)
}
/// A payment that is spending: money out, not a transfer.
pub fn is_spending(p: &EffectivePayment) -> bool {
p.amount.0 < 0 && category_of(p) != TRANSFERS
}
/// Money out by category, positive.
pub fn outflows(payments: &[EffectivePayment]) -> Option<BTreeMap<Category, Haler>> {
let mut by: BTreeMap<Category, Haler> = BTreeMap::new();
for p in payments.iter().filter(|p| is_spending(p)) {
let slot = by.entry(category_of(p).to_string()).or_insert(Haler::ZERO);
*slot = slot.checked_add(p.amount.checked_neg().ok()?).ok()?;
}
Some(by)
}
/// Money in, not a transfer.
pub fn inflow(payments: &[EffectivePayment]) -> Option<Haler> {
Haler::sum(payments.iter().filter(|p| p.amount.0 > 0 && category_of(p) != TRANSFERS).map(|p| p.amount)).ok()
}
/// Each part's share of their sum in thousandths, by the largest remainder: the shares add up to exactly 1000
/// whenever the sum is above zero (all zeros otherwise). A tie goes to the earlier part, so callers order the
/// parts first. A negative part counts as zero.
pub fn permille(parts: &[Haler]) -> Vec<u32> {
let parts: Vec<i128> = parts.iter().map(|h| i128::from(h.0.max(0))).collect();
let total: i128 = parts.iter().sum();
if total <= 0 {
return vec![0; parts.len()];
}
let mut shares: Vec<u32> = parts.iter().map(|p| (p * 1000 / total) as u32).collect();
let mut left = 1000 - shares.iter().sum::<u32>();
let mut order: Vec<usize> = (0..parts.len()).collect();
// Largest remainder first; the earlier part on a tie (the sort is stable).
order.sort_by_key(|&i| std::cmp::Reverse(parts[i] * 1000 % total));
for i in order {
if left == 0 {
break;
}
shares[i] += 1;
left -= 1;
}
shares
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shares_always_add_up_to_a_thousand() {
let h = |v: &[i64]| v.iter().map(|&x| Haler(x)).collect::<Vec<_>>();
assert_eq!(permille(&h(&[1, 1, 1])), [334, 333, 333]);
assert_eq!(permille(&h(&[2, 1])), [667, 333]);
assert_eq!(permille(&h(&[0, 0])), [0, 0]);
assert_eq!(permille(&h(&[])), Vec::<u32>::new());
assert_eq!(permille(&h(&[i64::MAX, i64::MAX, 1])), [500, 500, 0]);
assert_eq!(permille(&h(&[5, -3])), [1000, 0]);
for n in 1..40i64 {
let parts: Vec<Haler> = (1..=n).map(|i| Haler(i * 7919 % 1013 + 1)).collect();
assert_eq!(permille(&parts).iter().sum::<u32>(), 1000, "{n} parts");
}
}
}
+143
View File
@@ -0,0 +1,143 @@
//! 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<Category>,
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<Slice>,
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<MonthTotal>,
/// 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<MerchantTotal>,
/// 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> {
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<MonthStats> {
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<Category>, 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::<Vec<_>>());
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<MerchantTotal> = 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,
})
}