Files

161 lines
11 KiB
Rust

//! Savings goals and challenges in the ledger: what is accepted, and every refusal changing nothing. A goal never
//! holds less than nothing, the shares of "what's left" and "income" never add up to more than all of it, and a
//! closed goal takes no more money.
use fiscus_ledger::goal::{ChallengeGoal, Colour, Way, WayKind};
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
fn ev(id: &str, body: EventBody) -> Event {
Event::new(id, Timestamp(0), body)
}
fn goal(id: &str, name: &str, target: i64) -> EventBody {
EventBody::GoalCreated { goal: id.into(), name: name.into(), target: Haler(target), by: Some(d("2027-06-30")), colour: Colour::Teal }
}
fn saved(goal: &str, saving: &str, amount: i64, way: Option<WayKind>) -> EventBody {
EventBody::GoalSaved { goal: goal.into(), saving: saving.into(), amount: Haler(amount), on: d("2026-11-05"), way }
}
fn ways(goal: &str, ways: Vec<Way>) -> EventBody {
EventBody::GoalWaysSet { goal: goal.into(), ways }
}
/// The base ledger, then `body`: the reason it was refused, or `None` when it was accepted.
fn refusal(base: &[EventBody], body: EventBody) -> Option<String> {
let mut log: Vec<Event> = base.iter().enumerate().map(|(i, b)| ev(&format!("b{i}"), b.clone())).collect();
let before = State::replay(&log);
assert!(before.rejected.is_empty(), "{:?}", before.rejected);
log.push(ev("x", body));
let after = State::replay(&log);
match after.rejected.last() {
Some(r) => {
assert_eq!(after.goals, before.goals, "a refusal changes no goal");
assert_eq!(after.challenges, before.challenges, "a refusal changes no challenge");
Some(r.reason.clone())
}
None => None,
}
}
#[test]
fn a_goal_fills_with_what_you_put_aside_and_empties_only_to_zero() {
let s = State::replay(&[
ev("e1", goal("g1", "Holiday", 4_000_000)),
ev("e2", ways("g1", vec![Way::Fixed { amount: Haler(200_000) }, Way::RoundUp { to: Haler(5_000) }])),
ev("e3", saved("g1", "s1", 200_000, Some(WayKind::Fixed))),
ev("e4", saved("g1", "s2", 31_200, Some(WayKind::RoundUp))),
ev("e5", saved("g1", "s3", -50_000, None)),
]);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
let g = &s.goals["g1"];
assert_eq!(g.saved(), Haler(181_200));
assert_eq!(g.ways.len(), 2);
assert!(g.is_open());
let base = [goal("g1", "Holiday", 4_000_000), saved("g1", "s1", 100_000, None)];
assert_eq!(refusal(&base, saved("g1", "s2", -100_001, None)).as_deref(), Some("more than the goal holds"));
assert_eq!(refusal(&base, saved("g1", "s1", 5_000, None)).as_deref(), Some("a saving with this id exists"), "counted once");
assert_eq!(refusal(&base, saved("g1", "s2", 0, None)).as_deref(), Some("an amount saved is 0,01-100 000 000 CZK either way"));
assert_eq!(refusal(&base, saved("g1", "s2", 5_000, Some(WayKind::Income))).as_deref(), Some("the goal is not saved for that way"));
assert_eq!(refusal(&base, saved("nope", "s2", 5_000, None)).as_deref(), Some("no such goal"));
assert_eq!(refusal(&base, saved("g1", "s2", -100_000, None)), None, "down to exactly zero");
}
#[test]
fn a_goal_is_checked_when_made_and_changed() {
assert_eq!(refusal(&[], goal("g1", "", 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
assert_eq!(refusal(&[], goal("g1", " Holiday", 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
assert_eq!(refusal(&[], goal("g1", &"x".repeat(61), 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
assert_eq!(refusal(&[], goal("g1", "Bad\u{7}", 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
assert_eq!(refusal(&[], goal("g1", "Holiday", 99)).as_deref(), Some("a goal target is 1-100 000 000 CZK"));
assert_eq!(refusal(&[], goal("g1", "Holiday", 10_000_000_001)).as_deref(), Some("a goal target is 1-100 000 000 CZK"));
assert_eq!(refusal(&[goal("g1", "Holiday", 100_000)], goal("g1", "Car", 100_000)).as_deref(), Some("a goal with this id exists"));
let twenty: Vec<EventBody> = (0..20).map(|i| goal(&format!("g{i}"), "Goal", 100_000)).collect();
assert_eq!(refusal(&twenty, goal("g20", "One more", 100_000)).as_deref(), Some("at most 20 goals are open at once"));
let mut closed_one = twenty.clone();
closed_one.push(EventBody::GoalClosed { goal: "g3".into(), on: d("2026-11-05") });
assert_eq!(refusal(&closed_one, goal("g20", "One more", 100_000)), None, "a closed goal frees its place");
let base = [goal("g1", "Holiday", 100_000)];
let change = |name: &str, target: i64| EventBody::GoalChanged { goal: "g1".into(), name: name.into(), target: Haler(target), by: None, colour: Colour::Coral };
assert_eq!(refusal(&base, change("Summer", 200_000)), None);
assert_eq!(refusal(&base, change("", 200_000)).as_deref(), Some("a goal name must be 1-60 characters"));
let s = State::replay(&[ev("a", base[0].clone()), ev("b", change("Summer", 200_000))]);
assert_eq!((s.goals["g1"].name.as_str(), s.goals["g1"].target, s.goals["g1"].colour, s.goals["g1"].by), ("Summer", Haler(200_000), Colour::Coral, None));
}
#[test]
fn ways_are_one_of_each_kind_and_shares_never_add_up_to_more_than_all() {
let base = [goal("g1", "Holiday", 4_000_000), goal("g2", "Car", 9_000_000)];
assert_eq!(refusal(&base, ways("g1", vec![Way::Fixed { amount: Haler(100) }, Way::Fixed { amount: Haler(200) }])).as_deref(), Some("a goal has at most one way of each kind"));
assert_eq!(refusal(&base, ways("g1", vec![Way::Fixed { amount: Haler(99) }])).as_deref(), Some("a fixed amount is 1-100 000 000 CZK"));
assert_eq!(refusal(&base, ways("g1", vec![Way::RoundUp { to: Haler(2_000) }])).as_deref(), Some("round-ups go to 10, 50 or 100 CZK"));
assert_eq!(refusal(&base, ways("g1", vec![Way::Income { permille: 0 }])).as_deref(), Some("a share is 1-1000 thousandths"));
assert_eq!(refusal(&base, ways("g1", vec![Way::Leftover { permille: 1001 }])).as_deref(), Some("a share is 1-1000 thousandths"));
let mut split = base.to_vec();
split.push(ways("g1", vec![Way::Leftover { permille: 600 }, Way::Income { permille: 100 }]));
assert_eq!(refusal(&split, ways("g2", vec![Way::Leftover { permille: 401 }])).as_deref(), Some("the shares of one way across the goals add up to more than all of it"));
assert_eq!(refusal(&split, ways("g2", vec![Way::Leftover { permille: 400 }, Way::Income { permille: 900 }])), None, "exactly all of it");
assert_eq!(refusal(&split, ways("g1", vec![Way::Leftover { permille: 1000 }])), None, "a goal's own earlier share is replaced, not added");
let mut closed = split.clone();
closed.push(EventBody::GoalClosed { goal: "g1".into(), on: d("2026-11-05") });
assert_eq!(refusal(&closed, ways("g2", vec![Way::Leftover { permille: 1000 }])), None, "a closed goal gives its share back");
}
#[test]
fn a_closed_goal_takes_no_more_and_keeps_its_history() {
let base = [goal("g1", "Holiday", 100_000), saved("g1", "s1", 100_000, None), EventBody::GoalClosed { goal: "g1".into(), on: d("2026-11-06") }];
assert_eq!(refusal(&base, saved("g1", "s2", 5_000, None)).as_deref(), Some("the goal is closed"));
assert_eq!(refusal(&base, ways("g1", vec![])).as_deref(), Some("the goal is closed"));
assert_eq!(refusal(&base, EventBody::GoalClosed { goal: "g1".into(), on: d("2026-11-07") }).as_deref(), Some("the goal is closed"));
let s = State::replay(&base.iter().enumerate().map(|(i, b)| ev(&format!("e{i}"), b.clone())).collect::<Vec<_>>());
assert_eq!((s.goals["g1"].saved(), s.goals["g1"].closed), (Haler(100_000), Some(d("2026-11-06"))));
}
#[test]
fn a_challenge_is_checked_and_given_up_once() {
let start = |goal: ChallengeGoal, starts: &str, ends: &str| EventBody::ChallengeStarted { challenge: "c1".into(), goal, starts: d(starts), ends: d(ends) };
let under = |category: &str, amount: i64| ChallengeGoal::SpendUnder { category: category.into(), amount: Haler(amount) };
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-01", "2026-11-30")), None);
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-01", "2027-01-31")), None, "92 days");
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-01", "2027-02-01")).as_deref(), Some("a challenge lasts 1-92 days"));
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-02", "2026-11-01")).as_deref(), Some("a challenge lasts 1-92 days"));
assert_eq!(refusal(&[], start(under("income", 300_000), "2026-11-01", "2026-11-30")).as_deref(), Some("not a category you spend in"));
assert_eq!(refusal(&[], start(under("nope", 300_000), "2026-11-01", "2026-11-30")).as_deref(), Some("not a category you spend in"));
assert_eq!(refusal(&[], start(under("fun", 0), "2026-11-01", "2026-11-30")).as_deref(), Some("the amount of a challenge is 1-100 000 000 CZK"));
assert_eq!(refusal(&[], start(ChallengeGoal::NoSpend { category: "transfers".into() }, "2026-11-01", "2026-11-30")).as_deref(), Some("not a category you spend in"));
assert_eq!(refusal(&[], start(ChallengeGoal::Cancel { subscription: String::new() }, "2026-11-01", "2026-11-30")).as_deref(), Some("not a subscription key"));
let save = ChallengeGoal::Save { goal: "g1".into(), amount: Haler(500_000) };
assert_eq!(refusal(&[], start(save.clone(), "2026-11-01", "2026-11-30")).as_deref(), Some("no such open goal"));
assert_eq!(refusal(&[goal("g1", "Holiday", 4_000_000)], start(save.clone(), "2026-11-01", "2026-11-30")), None);
let base = [start(under("fun", 100_000), "2026-11-01", "2026-11-30")];
assert_eq!(refusal(&base, start(under("fun", 100_000), "2026-11-01", "2026-11-30")).as_deref(), Some("a challenge with this id exists"));
let give_up = EventBody::ChallengeAbandoned { challenge: "c1".into(), on: d("2026-11-10") };
assert_eq!(refusal(&base, give_up.clone()), None);
let mut given_up = base.to_vec();
given_up.push(give_up.clone());
assert_eq!(refusal(&given_up, give_up).as_deref(), Some("already given up"));
assert_eq!(refusal(&base, EventBody::ChallengeAbandoned { challenge: "c2".into(), on: d("2026-11-10") }).as_deref(), Some("no such challenge"));
}
#[test]
fn hostile_ways_and_goals_do_not_parse() {
for bad in [
r#"{"id":"x","at":0,"type":"goal.ways_set","goal":"g1","ways":[{"kind":"fixed","amount":100,"extra":1}]}"#,
r#"{"id":"x","at":0,"type":"goal.ways_set","goal":"g1","ways":[{"kind":"lottery"}]}"#,
r#"{"id":"x","at":0,"type":"goal.ways_set","goal":"g1","ways":[{"kind":"income","permille":1.5}]}"#,
r#"{"id":"x","at":0,"type":"goal.created","goal":"g1","name":"A","target":100.0,"by":null,"colour":"teal"}"#,
r#"{"id":"x","at":0,"type":"goal.created","goal":"g1","name":"A","target":100,"by":null,"colour":"pink"}"#,
r#"{"id":"x","at":0,"type":"challenge.started","challenge":"c","goal":{"kind":"no_spend","category":"fun","amount":5},"starts":"2026-11-01","ends":"2026-11-30"}"#,
] {
assert!(serde_json::from_str::<Event>(bad).is_err(), "{bad}");
}
}