Files

226 lines
9.2 KiB
Rust

//! Mandatory test 5: on a fixture history, detection finds the known subscriptions, flags the known price
//! change and the known trial, and never calls the supermarket or the rent a subscription.
use fiscus_insight::cancel::cancel_kit;
use fiscus_insight::subscriptions::{analyse, Cadence, Status, UpcomingKind};
use fiscus_ledger::import::{plan_import, StatementLine};
use fiscus_ledger::{Date, Decision, Event, EventBody, Haler, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
fn household() -> State {
let text = include_str!("histories/household.txt");
let mut lines = Vec::new();
let mut categories = Vec::new();
for row in text.lines().filter(|l| !l.starts_with('#') && !l.trim().is_empty()) {
let f: Vec<&str> = row.split(';').collect();
lines.push(StatementLine {
bank: "test".into(),
account: "1/0000".into(),
booked: d(f[0]),
amount: Haler(f[1].parse().unwrap()),
merchant: f[2].into(),
counterparty: None,
variable_symbol: None,
message: None,
bank_ref: None,
});
categories.push(f[3].to_string());
}
let mut state = State::default();
let mut n = 0u64;
let plan = plan_import(&state, &lines, &mut || {
n += 1;
format!("i{n:05}")
}, Timestamp(0));
let mut log: Vec<Event> = plan.events.clone();
for (e, cat) in plan.events.iter().zip(&categories) {
if let (EventBody::PaymentImported { payment, .. }, false) = (&e.body, cat.is_empty()) {
n += 1;
log.push(Event::new(format!("c{n}"), Timestamp(0), EventBody::PaymentCategorised { payment: payment.clone(), category: cat.clone() }));
}
}
log.push(Event::new(
"decide-spotify",
Timestamp(0),
EventBody::SubscriptionDecided { subscription: "spotify".into(), decision: Decision::Keep, amount: Haler(19_900), on: d("2026-07-10") },
));
for e in &log {
state.apply(e);
}
assert!(state.rejected.is_empty(), "{:?}", state.rejected);
state
}
#[test]
fn finds_the_known_subscriptions_and_nothing_else() {
let insight = analyse(&household(), d("2026-11-03"));
let mut keys: Vec<(&str, Cadence)> = insight.subscriptions.iter().map(|s| (s.key.as_str(), s.cadence)).collect();
keys.sort();
assert_eq!(
keys,
vec![
("apple com bill#169", Cadence::Monthly),
("apple com bill#25", Cadence::Monthly),
("netflix com", Cadence::Monthly),
("spotify", Cadence::Monthly),
("wedos internet a s", Cadence::Yearly),
("youtube premium", Cadence::Monthly),
]
);
}
#[test]
fn flags_the_known_price_change_until_it_is_decided() {
let mut state = household();
let insight = analyse(&state, d("2026-11-03"));
let netflix = insight.subscriptions.iter().find(|s| s.key == "netflix com").unwrap();
let change = netflix.price_change.as_ref().unwrap();
assert_eq!((change.from, change.to, change.on), (Haler(19_900), Haler(25_900), d("2026-10-12")));
assert!(netflix.creep_alert);
// Spotify went up in July, and the change was decided: no alert.
let spotify = insight.subscriptions.iter().find(|s| s.key == "spotify").unwrap();
assert_eq!(spotify.price_change.as_ref().unwrap().to, Haler(19_900));
assert!(!spotify.creep_alert);
// Nobody else changed price.
assert_eq!(insight.subscriptions.iter().filter(|s| s.creep_alert).count(), 1);
state.apply(&Event::new(
"keep-netflix",
Timestamp(0),
EventBody::SubscriptionDecided { subscription: "netflix com".into(), decision: Decision::Keep, amount: Haler(25_900), on: d("2026-11-03") },
));
let after = analyse(&state, d("2026-11-03"));
let netflix = after.subscriptions.iter().find(|s| s.key == "netflix com").unwrap();
assert!(!netflix.creep_alert && !netflix.needs_review);
}
#[test]
fn flags_the_known_trial() {
let state = household();
let insight = analyse(&state, d("2026-11-03"));
assert_eq!(insight.trials.len(), 1, "{:#?}", insight.trials);
let t = &insight.trials[0];
assert_eq!(t.key, "disney plus");
assert_eq!((t.started, t.ends, t.estimated), (d("2026-10-28"), d("2026-11-27"), true));
// YouTube's 1 CZK check was followed by full charges: not a trial any more.
assert!(insight.trials.iter().all(|t| !t.key.starts_with("youtube")));
}
#[test]
fn a_trial_marked_by_hand_uses_its_end_date() {
let mut state = household();
let disney = state.effective_payments().into_iter().find(|p| p.merchant_key == "disney plus").unwrap();
state.apply(&Event::new("mark", Timestamp(0), EventBody::PaymentTrialMarked { payment: disney.id, ends: d("2026-11-07") }));
let insight = analyse(&state, d("2026-11-03"));
assert_eq!(insight.trials.len(), 1);
assert_eq!((insight.trials[0].ends, insight.trials[0].estimated), (d("2026-11-07"), false));
assert!(insight.upcoming.iter().any(|u| u.kind == UpcomingKind::TrialEnds && u.date == d("2026-11-07")));
}
#[test]
fn next_charges_and_the_seven_day_strip() {
let insight = analyse(&household(), d("2026-11-03"));
let next = |k: &str| insight.subscriptions.iter().find(|s| s.key == k).unwrap().next_charge;
assert_eq!(next("spotify"), d("2026-11-05"));
assert_eq!(next("wedos internet a s"), d("2027-03-10"));
let strip: Vec<(&str, Date)> = insight.upcoming.iter().map(|u| (u.key.as_str(), u.date)).collect();
assert_eq!(strip, vec![("spotify", d("2026-11-05")), ("apple com bill#25", d("2026-11-08"))]);
}
#[test]
fn monthly_review_and_cancel() {
let mut state = household();
let insight = analyse(&state, d("2026-11-03"));
assert!(insight.subscriptions.iter().filter(|s| s.status == Status::Active).all(|s| s.needs_review || s.cadence == Cadence::Yearly));
state.apply(&Event::new(
"cancel-yt",
Timestamp(0),
EventBody::SubscriptionDecided { subscription: "youtube premium".into(), decision: Decision::Cancel, amount: Haler(23_900), on: d("2026-10-15") },
));
let yt = |s: &State, today: &str| analyse(s, d(today)).subscriptions.into_iter().find(|s| s.key == "youtube premium").unwrap();
assert_eq!(yt(&state, "2026-11-03").status, Status::Cancelled);
// It charges again anyway.
let mut n = 0u64;
let line = StatementLine {
bank: "test".into(),
account: "1/0000".into(),
booked: d("2026-11-01"),
amount: Haler(-23_900),
merchant: "GOOGLE *YouTube Premium".into(),
counterparty: None,
variable_symbol: None,
message: None,
bank_ref: None,
};
let plan = plan_import(&state, &[line], &mut || {
n += 1;
format!("late{n}")
}, Timestamp(0));
for e in &plan.events {
state.apply(e);
}
assert_eq!(yt(&state, "2026-11-03").status, Status::ChargedAfterCancel);
}
#[test]
fn the_cancel_kit() {
let insight = analyse(&household(), d("2026-11-03"));
let netflix = insight.subscriptions.iter().find(|s| s.key == "netflix com").unwrap();
let kit = cancel_kit(netflix);
assert_eq!(kit.provider.as_deref(), Some("Netflix"));
assert_eq!(kit.url.as_deref(), Some("https://www.netflix.com/cancelplan"));
assert!(kit.email_subject.contains("Netflix"));
assert!(kit.email_body.contains("259,00"));
let wedos = insight.subscriptions.iter().find(|s| s.key == "wedos internet a s").unwrap();
let kit = cancel_kit(wedos);
assert_eq!(kit.url, None, "an unknown provider gets the email only");
assert!(kit.mailto().starts_with("mailto:?subject="));
}
#[test]
fn a_shop_visited_about_monthly_is_not_a_subscription() {
// Roughly monthly, different totals every time: the cadence fits, the price does not.
let visits = [("2026-01-10", -184_000), ("2026-02-09", -201_500), ("2026-03-11", -176_300), ("2026-04-10", -199_900), ("2026-05-09", -230_100)];
let lines: Vec<StatementLine> = visits
.iter()
.map(|(date, a)| StatementLine {
bank: "test".into(),
account: "1/0000".into(),
booked: d(date),
amount: Haler(*a),
merchant: "IKEA ZLICIN".into(),
counterparty: None,
variable_symbol: None,
message: None,
bank_ref: None,
})
.collect();
let mut state = State::default();
let mut n = 0u64;
for e in plan_import(&state.clone(), &lines, &mut || {
n += 1;
format!("k{n}")
}, Timestamp(0))
.events
{
state.apply(&e);
}
assert!(analyse(&state, d("2026-05-20")).subscriptions.is_empty());
}
#[test]
fn the_budget_forecast_runs_on_the_household() {
let mut state = household();
state.apply(&Event::new("b", Timestamp(0), EventBody::BudgetCreated { budget: "home".into(), name: "Home".into(), limit: Haler(5_000_000) }));
let today = d("2026-10-20");
let insight = analyse(&state, today);
let f = fiscus_insight::forecast::budget_forecast(&state, &insight, "home", today, 11, 2_000).unwrap();
assert_eq!(f, fiscus_insight::forecast::budget_forecast(&state, &insight, "home", today, 11, 2_000).unwrap());
assert_eq!(f.history_days, 90);
assert!(f.p10 <= f.p50 && f.p50 <= f.p90);
assert!(fiscus_insight::forecast::budget_forecast(&state, &insight, "nope", today, 11, 10).is_none());
}