Files
FiscusPublic/crates/fiscus-insight/tests/stats.rs
T
mnovak 03dc2061f9 [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
2026-11-06 13:02:39 +01:00

189 lines
9.2 KiB
Rust

//! Spending, the month against its plan, and a month in numbers: one definition of spending everywhere,
//! shares that always add up to 1000, the pace by today, and the suggested plan rounded up.
use fiscus_insight::plan::{month_plan, suggest, Pace};
use fiscus_insight::stats::{month_stats, SLICES};
use fiscus_insight::subscriptions::analyse;
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
/// A ledger from `(date, amount in haléře, merchant, category)` added by hand, then `extra` events.
fn ledger(payments: &[(&str, i64, &str, &str)], extra: Vec<EventBody>) -> State {
let mut log: Vec<Event> = payments
.iter()
.enumerate()
.map(|(i, (date, amount, merchant, category))| {
Event::new(
format!("e{i}"),
Timestamp(0),
EventBody::PaymentAdded {
payment: format!("p{i}"),
amount: Haler(*amount),
date: d(date),
merchant: merchant.to_string(),
category: (!category.is_empty()).then(|| category.to_string()),
note: None,
},
)
})
.collect();
log.extend(extra.into_iter().enumerate().map(|(i, b)| Event::new(format!("x{i}"), Timestamp(0), b)));
let s = State::replay(&log);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
s
}
fn planned(category: &str, amount: i64, from: &str) -> EventBody {
EventBody::CategoryPlanned { category: category.into(), amount: Haler(amount), from: d(from) }
}
#[test]
fn the_month_against_its_plan() {
let today = d("2026-11-15");
let s = ledger(
&[
("2026-11-02", -300_000, "Albert", "groceries"),
("2026-11-10", -150_000, "Lidl", "groceries"),
("2026-11-12", -250_000, "Lokál", "eating-out"),
("2026-11-14", -40_000, "Trafika", ""),
("2026-11-03", -1_000_000, "To savings", "transfers"),
("2026-11-05", 5_000_000, "Salary", "income"),
("2026-11-20", -90_000, "Albert", "groceries"),
("2026-10-30", -999_999, "Albert", "groceries"),
("2026-11-08", -60_000, "Shell", "transport"),
],
vec![planned("groceries", 1_000_000, "2026-10-01"), planned("eating-out", 200_000, "2026-11-01"), planned("transport", 400_000, "2026-11-01")],
);
let p = month_plan(&s, today, today).unwrap();
assert_eq!(p.month, d("2026-11-01"));
type Row<'a> = (&'a str, Option<i64>, i64, Option<i64>, u32, Option<Pace>);
let rows: Vec<Row> =
p.rows.iter().map(|r| (r.category.as_str(), r.planned.map(|x| x.0), r.spent.0, r.left.map(|x| x.0), r.permille, r.pace)).collect();
assert_eq!(
rows,
[
// Half the month gone (15 of 30 days): 4 500 of 10 000 is 90 % of the pace, on pace.
("groceries", Some(1_000_000), 450_000, Some(550_000), 450, Some(Pace::OnPace)),
("eating-out", Some(200_000), 250_000, Some(-50_000), 1000, Some(Pace::Over)),
("transport", Some(400_000), 60_000, Some(340_000), 150, Some(Pace::Under)),
// Spent with no plan: uncategorised. Transfers, income, the future and last month do not count.
("uncategorised", None, 40_000, None, 0, None),
]
);
assert_eq!((p.planned, p.spent, p.unplanned), (Haler(1_600_000), Haler(800_000), Haler(40_000)));
// A past month is done: within the plan is Under, past it Over. A month to come has nothing spent.
let oct = month_plan(&s, d("2026-10-01"), today).unwrap();
assert_eq!(oct.rows[0].pace, Some(Pace::Under));
assert_eq!(oct.rows[0].spent, Haler(999_999));
let dec = month_plan(&s, d("2026-12-01"), today).unwrap();
assert_eq!(dec.spent, Haler::ZERO);
assert!(dec.rows.iter().all(|r| r.pace.is_none()), "not begun");
}
#[test]
fn ahead_of_the_pace() {
let s = ledger(&[("2026-11-03", -500_000, "Albert", "groceries")], vec![planned("groceries", 1_000_000, "2026-11-01")]);
// 5 days of 30 allow 1 666,66; 5 000 is far ahead, but not over the month's 10 000.
assert_eq!(month_plan(&s, d("2026-11-05"), d("2026-11-05")).unwrap().rows[0].pace, Some(Pace::Ahead));
assert_eq!(month_plan(&s, d("2026-11-30"), d("2026-11-30")).unwrap().rows[0].pace, Some(Pace::Under));
}
#[test]
fn the_suggested_plan_is_the_average_rounded_up_to_hundreds() {
let s = ledger(
&[
("2026-08-10", -100_000, "Albert", "groceries"),
("2026-09-10", -200_000, "Albert", "groceries"),
("2026-10-10", -300_001, "Albert", "groceries"),
("2026-10-11", -12_345, "Lokál", "eating-out"),
("2026-10-12", -50_000, "To savings", "transfers"),
("2026-10-13", -7_000, "?", ""),
("2026-11-01", -999_999, "Albert", "groceries"),
("2026-07-01", -5_000_000, "Albert", "groceries"),
],
vec![],
);
// Aug, Sep, Oct (not this November, not July): 6 000,01 / 3 = 2 000,0034 → 2 100.
let got = suggest(&s, d("2026-11-15"));
assert_eq!(got, [("groceries".to_string(), Haler(210_000)), ("eating-out".to_string(), Haler(10_000))]);
// A ledger only a month old is not divided by three.
let young = ledger(&[("2026-10-10", -150_000, "Albert", "groceries")], vec![]);
assert_eq!(suggest(&young, d("2026-11-15")), [("groceries".to_string(), Haler(150_000))]);
assert!(suggest(&State::default(), d("2026-11-15")).is_empty());
}
#[test]
fn a_month_in_numbers() {
let today = d("2026-11-15");
let mut payments = vec![
("2026-11-02", -300_000, "Albert Praha", "groceries"),
("2026-11-09", -100_000, "ALBERT PRAHA", "groceries"),
("2026-11-03", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
("2026-11-04", -50_000, "Lokál", "eating-out"),
("2026-11-05", 4_000_000, "Salary", "income"),
("2026-11-06", -1_000_000, "To savings", "transfers"),
("2026-11-07", -33_100, "", "fun"),
("2026-10-02", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
("2026-09-02", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
("2026-10-10", -200_000, "Albert Praha", "groceries"),
("2026-10-20", -500_000, "Albert Praha", "groceries"),
("2026-11-20", -77_700, "Albert Praha", "groceries"),
];
// Eight more categories, so the pie has a slice for the rest.
let more = ["transport", "housing", "utilities", "shopping", "health", "kids", "travel", "gifts"];
for (i, c) in more.iter().enumerate() {
payments.push(("2026-11-10", -(1_000 + i as i64), "Shop", c));
}
let s = ledger(&payments, vec![]);
let st = month_stats(&s, &analyse(&s, today), today, today).unwrap();
assert_eq!(st.month, d("2026-11-01"));
let spent = 300_000 + 100_000 + 16_900 + 50_000 + 33_100 + (1_000..1_008).sum::<i64>();
assert_eq!((st.out, st.inflow, st.net), (Haler(spent), Haler(4_000_000), Haler(4_000_000 - spent)));
assert_eq!(st.slices.len(), SLICES + 1);
assert_eq!(st.slices.iter().map(|s| s.permille).sum::<u32>(), 1000, "the slices add up");
assert_eq!(st.slices[0].category.as_deref(), Some("groceries"));
assert_eq!(st.slices[0].amount, Haler(400_000));
assert!(st.slices.last().unwrap().category.is_none(), "the rest");
assert!(st.slices.windows(2).take(SLICES - 1).all(|w| w[0].amount >= w[1].amount), "largest first");
// Six months, oldest first; October in full, November up to today.
let months: Vec<(Date, i64)> = st.months.iter().map(|m| (m.month, m.out.0)).collect();
assert_eq!(months.len(), 6);
assert_eq!(months[0].0, d("2026-06-01"));
assert_eq!(months[4], (d("2026-10-01"), 716_900));
assert_eq!(months[5], (d("2026-11-01"), spent));
// By 15 October: the Spotify charge and the first Albert.
assert_eq!(st.same_day_last_month, Haler(216_900));
let top: Vec<(&str, i64, usize)> = st.top_merchants.iter().map(|m| (m.key.as_str(), m.amount.0, m.count)).collect();
assert_eq!(top[0], ("albert praha", 400_000, 2), "one merchant however the bank writes it");
assert!(top.iter().all(|(k, _, _)| !k.is_empty()), "a payment without a merchant is not a merchant");
assert!(top.len() <= 5);
assert_eq!(st.subscriptions, Haler(16_900));
assert_eq!(st.subscriptions_permille, (16_900 * 1000 / spent) as u32);
// A past month: whole, compared with all of the month before.
let oct = month_stats(&s, &analyse(&s, today), d("2026-10-31"), today).unwrap();
assert_eq!((oct.out, oct.same_day_last_month), (Haler(716_900), Haler(16_900)));
// A month to come has no numbers yet; an empty month is zeros, not nothing.
assert!(month_stats(&s, &analyse(&s, today), d("2026-12-01"), today).is_none());
let empty = month_stats(&s, &analyse(&s, today), d("2026-03-01"), today).unwrap();
assert!(empty.slices.is_empty());
assert_eq!((empty.out, empty.subscriptions_permille), (Haler::ZERO, 0));
}
#[test]
fn a_sum_that_would_not_fit_gives_no_numbers() {
let s = ledger(&[("2026-11-02", i64::MIN + 1, "A", "fun"), ("2026-11-03", i64::MIN + 1, "B", "fun")], vec![]);
let today = d("2026-11-15");
assert!(month_stats(&s, &analyse(&s, today), today, today).is_none());
assert!(month_plan(&s, today, today).is_none());
}