279 lines
16 KiB
Rust
279 lines
16 KiB
Rust
//! Savings goals this month and the rewards: round-ups to the haléř, what last month's plans left, a share of
|
|
//! income, the split capped at what a goal still needs, the pace and the month you get there, where the money
|
|
//! could come from; medals only for complete periods, and challenges won, lost or given up.
|
|
|
|
use fiscus_insight::goals::{goals_month, round_ups, Source};
|
|
use fiscus_insight::rewards::{rewards, Medal, Outcome};
|
|
use fiscus_insight::subscriptions::analyse;
|
|
use fiscus_ledger::goal::{ChallengeGoal, Colour, Way, WayKind};
|
|
use fiscus_ledger::{Date, Decision, Event, EventBody, Haler, State, Timestamp};
|
|
use std::collections::BTreeSet;
|
|
|
|
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> = vec![Event::new("b", Timestamp(0), EventBody::BudgetCreated { budget: "home".into(), name: "Home".into(), limit: Haler(1_000_000) })];
|
|
log.extend(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,
|
|
},
|
|
)
|
|
}));
|
|
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 goal(id: &str, target: i64, by: Option<&str>) -> EventBody {
|
|
EventBody::GoalCreated { goal: id.into(), name: format!("Goal {id}"), target: Haler(target), by: by.map(d), colour: Colour::Amber }
|
|
}
|
|
|
|
fn saved(goal: &str, saving: &str, amount: i64, on: &str, way: Option<WayKind>) -> EventBody {
|
|
EventBody::GoalSaved { goal: goal.into(), saving: saving.into(), amount: Haler(amount), on: d(on), way }
|
|
}
|
|
|
|
#[test]
|
|
fn round_ups_add_the_differences_to_the_next_10_50_or_100_kc() {
|
|
let today = d("2026-11-07");
|
|
let s = ledger(
|
|
&[
|
|
("2026-11-02", -12_900, "Albert", "groceries"),
|
|
("2026-11-03", -25_000, "Lokál", "eating-out"),
|
|
("2026-11-04", -8_750, "Trafika", ""),
|
|
("2026-11-05", -100_000, "To savings", "transfers"),
|
|
("2026-11-05", 5_000_000, "Salary", "income"),
|
|
("2026-10-30", -12_345, "Albert", "groceries"),
|
|
],
|
|
vec![],
|
|
);
|
|
// 129 → 130, 250 stays, 87,50 → 90: 1 + 0 + 2,50. Transfers, money in and last month are not rounded.
|
|
assert_eq!(round_ups(&s, Haler(1_000), today), (Haler(350), 2));
|
|
assert_eq!(round_ups(&s, Haler(10_000), today), (Haler(7_100 + 5_000 + 1_250), 3));
|
|
}
|
|
|
|
#[test]
|
|
fn a_goal_month_splits_its_saving_between_its_ways() {
|
|
let today = d("2026-11-07");
|
|
let s = ledger(
|
|
&[
|
|
// October: groceries under plan by 1 500 Kč, eating out over (leftover 0, not negative); 40 000 in.
|
|
("2026-10-05", -650_000, "Albert", "groceries"),
|
|
("2026-10-06", -250_000, "Lokál", "eating-out"),
|
|
("2026-10-10", 4_000_000, "Salary", "income"),
|
|
// November so far.
|
|
("2026-11-02", -12_900, "Albert", "groceries"),
|
|
],
|
|
vec![
|
|
EventBody::CategoryPlanned { category: "groceries".into(), amount: Haler(800_000), from: d("2026-10-01") },
|
|
EventBody::CategoryPlanned { category: "eating-out".into(), amount: Haler(200_000), from: d("2026-10-01") },
|
|
goal("g1", 4_000_000, Some("2027-06-30")),
|
|
EventBody::GoalWaysSet {
|
|
goal: "g1".into(),
|
|
ways: vec![Way::Fixed { amount: Haler(200_000) }, Way::RoundUp { to: Haler(1_000) }, Way::Leftover { permille: 500 }, Way::Income { permille: 100 }],
|
|
},
|
|
saved("g1", "s1", 300_000, "2026-08-10", None),
|
|
saved("g1", "s2", 300_000, "2026-09-10", None),
|
|
saved("g1", "s3", 300_000, "2026-10-10", None),
|
|
saved("g1", "s4", 100_000, "2026-11-03", Some(WayKind::Fixed)),
|
|
],
|
|
);
|
|
let m = goals_month(&s, &analyse(&s, today), today);
|
|
assert_eq!((m.leftover, m.income, m.leftover_given, m.income_given), (Haler(150_000), Haler(4_000_000), 500, 100));
|
|
let g = &m.goals[0];
|
|
assert_eq!((g.saved, g.permille, g.reached), (Haler(1_000_000), 250, false));
|
|
let parts: Vec<(WayKind, Haler, Haler, Haler)> = g.parts.iter().map(|p| (p.way.kind(), p.amount, p.saved, p.left)).collect();
|
|
assert_eq!(
|
|
parts,
|
|
[
|
|
(WayKind::Fixed, Haler(200_000), Haler(100_000), Haler(100_000)),
|
|
(WayKind::RoundUp, Haler(100), Haler::ZERO, Haler(100)),
|
|
(WayKind::Leftover, Haler(75_000), Haler::ZERO, Haler(75_000)),
|
|
(WayKind::Income, Haler(400_000), Haler::ZERO, Haler(400_000)),
|
|
]
|
|
);
|
|
assert_eq!((g.left_this_month, g.saved_this_month), (Haler(575_100), Haler(100_000)));
|
|
// November to June is 8 months: 30 000 Kč still needed, 3 750 Kč a month.
|
|
assert_eq!((g.months_left, g.needed_per_month), (Some(8), Some(Haler(375_000))));
|
|
// August to October at 3 000 Kč a month: 30 000 Kč more is 10 months on, in September 2027.
|
|
assert_eq!((g.pace, g.reach_month), (Haler(300_000), Some(d("2027-09-01"))));
|
|
}
|
|
|
|
#[test]
|
|
fn the_split_never_asks_for_more_than_the_goal_still_needs() {
|
|
let today = d("2026-11-07");
|
|
let s = ledger(
|
|
&[],
|
|
vec![
|
|
goal("g1", 300_000, None),
|
|
EventBody::GoalWaysSet { goal: "g1".into(), ways: vec![Way::Fixed { amount: Haler(200_000) }, Way::Fixed { amount: Haler(100) }].into_iter().take(1).collect() },
|
|
saved("g1", "s1", 250_000, "2026-10-01", None),
|
|
],
|
|
);
|
|
let g = &goals_month(&s, &analyse(&s, today), today).goals[0];
|
|
assert_eq!((g.parts[0].amount, g.parts[0].left, g.needed_per_month, g.months_left), (Haler(200_000), Haler(50_000), None, None));
|
|
let s = ledger(&[], vec![goal("g1", 300_000, Some("2026-09-30")), saved("g1", "s1", 300_000, "2026-10-01", None), EventBody::GoalClosed { goal: "g1".into(), on: d("2026-10-02") }]);
|
|
let g = &goals_month(&s, &analyse(&s, today), today).goals[0];
|
|
assert!(g.reached && g.parts.is_empty() && g.reach_month.is_none() && g.needed_per_month.is_none());
|
|
let s = ledger(&[], vec![goal("g1", 300_000, Some("2026-09-30"))]);
|
|
let g = &goals_month(&s, &analyse(&s, today), today).goals[0];
|
|
assert_eq!((g.months_left, g.needed_per_month), (Some(0), Some(Haler(300_000))), "its date has passed: all of it");
|
|
}
|
|
|
|
#[test]
|
|
fn where_the_money_could_come_from() {
|
|
let today = d("2026-11-07");
|
|
let mut payments = Vec::new();
|
|
for m in ["2026-07", "2026-08", "2026-09", "2026-10"] {
|
|
payments.push((format!("{m}-03"), -19_900, "NETFLIX.COM", "subscriptions"));
|
|
payments.push((format!("{m}-12"), -200_000, "Lokál", "eating-out"));
|
|
}
|
|
payments.push(("2026-10-20".into(), -150_000, "Lokál", "eating-out"));
|
|
let rows: Vec<(&str, i64, &str, &str)> = payments.iter().map(|(a, b, c, e)| (a.as_str(), *b, *c, *e)).collect();
|
|
let s = ledger(&rows, vec![]);
|
|
let sources = goals_month(&s, &analyse(&s, today), today).sources;
|
|
assert!(
|
|
sources.iter().any(|x| matches!(x, Source::Subscription { merchant, monthly, .. } if merchant.contains("NETFLIX") && *monthly == Haler(19_900))),
|
|
"{sources:?}"
|
|
);
|
|
assert!(
|
|
sources.iter().any(|x| matches!(x, Source::Category { category, last, average, extra } if category == "eating-out" && *last == Haler(350_000) && *average == Haler(200_000) && *extra == Haler(150_000))),
|
|
"{sources:?}"
|
|
);
|
|
// Decided "keep": not pointed at.
|
|
let key = analyse(&s, today).subscriptions[0].key.clone();
|
|
let s = ledger(&rows, vec![EventBody::SubscriptionDecided { subscription: key, decision: Decision::Keep, amount: Haler(19_900), on: d("2026-11-01") }]);
|
|
assert!(!goals_month(&s, &analyse(&s, today), today).sources.iter().any(|x| matches!(x, Source::Subscription { .. })));
|
|
}
|
|
|
|
#[test]
|
|
fn medals_for_goals_and_months_running_with_money_put_aside() {
|
|
let today = d("2026-11-07");
|
|
let s = ledger(
|
|
&[("2026-08-01", -10_000, "Albert", "groceries")],
|
|
vec![
|
|
goal("g1", 100_000, None),
|
|
saved("g1", "s1", 30_000, "2026-08-10", None),
|
|
saved("g1", "s2", 30_000, "2026-09-10", None),
|
|
saved("g1", "s3", 50_000, "2026-10-10", None),
|
|
saved("g1", "s4", -20_000, "2026-10-20", None),
|
|
],
|
|
);
|
|
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
|
let milestones: Vec<(u32, Date)> = r.medals.iter().filter_map(|e| match &e.medal { Medal::GoalMilestone { permille, .. } => Some((*permille, e.on)), _ => None }).collect();
|
|
assert_eq!(milestones, [(750, d("2026-10-10")), (1000, d("2026-10-10")), (500, d("2026-09-10")), (250, d("2026-08-10"))]);
|
|
assert!(r.medals.iter().any(|e| e.medal == Medal::SavingStreak { months: 3, until: d("2026-10-01") }));
|
|
assert_eq!((r.progress.saving_months, r.progress.saved_this_month), (3, false));
|
|
assert!(r.progress.goals.iter().any(|(id, _, level, next)| id == "g1" && *level == 900 && *next == 1000), "{:?}", r.progress.goals);
|
|
|
|
// Two months are not a streak; this month does not count until it is over.
|
|
let s = ledger(&[("2026-09-01", -10_000, "Albert", "groceries")], vec![goal("g1", 100_000, None), saved("g1", "s1", 1_000, "2026-09-10", None), saved("g1", "s2", 1_000, "2026-10-10", None), saved("g1", "s3", 1_000, "2026-11-02", None)]);
|
|
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
|
assert!(!r.medals.iter().any(|e| matches!(e.medal, Medal::SavingStreak { .. })));
|
|
assert_eq!((r.progress.saving_months, r.progress.saved_this_month), (2, true));
|
|
}
|
|
|
|
#[test]
|
|
fn medals_for_budgets_and_plans_kept_in_complete_months_only() {
|
|
let today = d("2026-11-07");
|
|
let s = ledger(
|
|
&[
|
|
("2026-07-05", -400_000, "Albert", "groceries"),
|
|
("2026-08-05", -900_000, "Albert", "groceries"),
|
|
("2026-09-05", -900_000, "Albert", "groceries"),
|
|
("2026-10-05", -1_000_000, "Albert", "groceries"),
|
|
("2026-11-05", -5_000_000, "Albert", "groceries"),
|
|
],
|
|
vec![EventBody::CategoryPlanned { category: "groceries".into(), amount: Haler(950_000), from: d("2026-09-01") }],
|
|
);
|
|
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
|
assert!(r.medals.iter().any(|e| e.medal == Medal::UnderBudget { budget: "home".into(), name: "Home".into(), months: 4, until: d("2026-10-01") }), "{:?}", r.medals);
|
|
let kept: Vec<Date> = r.medals.iter().filter_map(|e| match e.medal { Medal::PlansKept { month } => Some(month), _ => None }).collect();
|
|
assert_eq!(kept, [d("2026-09-01")], "October went over its plan; November is not over");
|
|
assert_eq!(r.progress.budgets, [("home".to_string(), "Home".to_string(), 4)]);
|
|
// A shared budget earns none: only your own payments are counted, its limit is everyone's.
|
|
let r = rewards(&s, &analyse(&s, today), &BTreeSet::from(["home".to_string()]), today);
|
|
assert!(!r.medals.iter().any(|e| matches!(e.medal, Medal::UnderBudget { .. })) && r.progress.budgets.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn challenges_run_are_won_lost_or_given_up() {
|
|
let start = |id: &str, goal: ChallengeGoal, starts: &str, ends: &str| EventBody::ChallengeStarted { challenge: id.into(), goal, starts: d(starts), ends: d(ends) };
|
|
let s = ledger(
|
|
&[("2026-10-10", -100_000, "Lokál", "eating-out"), ("2026-10-20", -50_000, "Kino", "fun"), ("2026-11-03", -100_000, "Lokál", "eating-out")],
|
|
vec![
|
|
goal("g1", 1_000_000, None),
|
|
start("c-under", ChallengeGoal::SpendUnder { category: "eating-out".into(), amount: Haler(300_000) }, "2026-11-01", "2026-11-30"),
|
|
start("c-oct", ChallengeGoal::SpendUnder { category: "eating-out".into(), amount: Haler(200_000) }, "2026-10-01", "2026-10-31"),
|
|
start("c-none", ChallengeGoal::NoSpend { category: "fun".into() }, "2026-10-01", "2026-10-31"),
|
|
start("c-save", ChallengeGoal::Save { goal: "g1".into(), amount: Haler(200_000) }, "2026-11-01", "2026-11-30"),
|
|
saved("g1", "s1", 250_000, "2026-11-04", None),
|
|
start("c-quit", ChallengeGoal::NoSpend { category: "travel".into() }, "2026-11-01", "2026-11-30"),
|
|
EventBody::ChallengeAbandoned { challenge: "c-quit".into(), on: d("2026-11-05") },
|
|
],
|
|
);
|
|
let today = d("2026-11-07");
|
|
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
|
let by = |id: &str| r.challenges.iter().find(|c| c.id == id).unwrap();
|
|
assert_eq!((by("c-under").outcome, by("c-under").so_far, by("c-under").permille, by("c-under").days_left), (Outcome::Running, Haler(100_000), 666, 23));
|
|
assert_eq!((by("c-oct").outcome, by("c-oct").permille), (Outcome::Won, 500));
|
|
assert_eq!((by("c-none").outcome, by("c-none").permille), (Outcome::Lost, 0));
|
|
assert_eq!((by("c-save").outcome, by("c-save").permille), (Outcome::Won, 1000), "won the day it was reached");
|
|
assert_eq!(by("c-quit").outcome, Outcome::Abandoned);
|
|
let won: Vec<(&str, Date)> = r.medals.iter().filter_map(|e| match &e.medal { Medal::ChallengeWon { challenge, .. } => Some((challenge.as_str(), e.on)), _ => None }).collect();
|
|
assert_eq!(won, [("c-save", d("2026-11-04")), ("c-oct", d("2026-10-31"))]);
|
|
assert_eq!(r.challenges[0].outcome, Outcome::Running, "running first");
|
|
|
|
// Over the limit before the end: lost at once.
|
|
let s2 = ledger(&[("2026-11-03", -400_000, "Lokál", "eating-out")], vec![start("c", ChallengeGoal::SpendUnder { category: "eating-out".into(), amount: Haler(300_000) }, "2026-11-01", "2026-11-30")]);
|
|
assert_eq!(rewards(&s2, &analyse(&s2, today), &BTreeSet::new(), today).challenges[0].outcome, Outcome::Lost);
|
|
}
|
|
|
|
#[test]
|
|
fn a_quarter_with_every_invoice_paid_by_its_due_date() {
|
|
use fiscus_ledger::invoice::{Invoice, InvoiceLine, Language, Party, Supplier};
|
|
let party = |name: &str, ico: &str| Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some(ico.into()), dic: None };
|
|
let invoice = |id: &str, number: &str, issued: &str| Invoice {
|
|
id: id.into(),
|
|
number: number.into(),
|
|
issued: d(issued),
|
|
due: d(issued).add_days(14),
|
|
taxable: None,
|
|
customer: party("Odběratel s.r.o.", "45244782"),
|
|
lines: vec![InvoiceLine { text: "Work".into(), quantity: 1000, unit: "h".into(), unit_price: Haler(100_000), vat: None }],
|
|
budget: None,
|
|
language: Language::Cs,
|
|
};
|
|
let paid = |id: &str, on: &str| EventBody::InvoicePaid { invoice: id.into(), payment: None, on: d(on) };
|
|
let s = ledger(
|
|
&[],
|
|
vec![
|
|
EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } },
|
|
// Q2: both paid in time. Q3: one paid late.
|
|
EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-04-02") },
|
|
EventBody::InvoiceIssued { invoice: invoice("i2", "20260002", "2026-05-10") },
|
|
EventBody::InvoiceIssued { invoice: invoice("i3", "20260003", "2026-07-01") },
|
|
EventBody::InvoiceIssued { invoice: invoice("i4", "20260004", "2026-10-20") },
|
|
paid("i1", "2026-04-10"),
|
|
paid("i2", "2026-05-24"),
|
|
paid("i3", "2026-07-30"),
|
|
paid("i4", "2026-10-25"),
|
|
],
|
|
);
|
|
let today = d("2026-11-07");
|
|
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
|
let quarters: Vec<(i32, u32)> = r.medals.iter().filter_map(|e| match e.medal { Medal::InvoicesOnTime { year, quarter } => Some((year, quarter)), _ => None }).collect();
|
|
assert_eq!(quarters, [(2026, 2)], "Q3 had one paid late; Q4 is not over");
|
|
}
|