[insight] Subscriptions: cadence, price change, trials, review, cancel kit; seeded month-end forecast

This commit is contained in:
2026-11-03 18:52:36 +01:00
parent 397f9ff00e
commit 9edbae37c1
8 changed files with 873 additions and 0 deletions
+57
View File
@@ -0,0 +1,57 @@
//! Mandatory test 6: the forecast is a pure function of its inputs and seed.
use fiscus_insight::forecast::{forecast, ForecastInput};
use fiscus_ledger::Haler;
fn input() -> ForecastInput {
ForecastInput {
history: (0..90).map(|i| Haler(((i * 7919) % 120_000) as i64)).collect(),
spent: Haler(800_000),
days_left: 17,
limit: Haler(2_000_000),
known: Haler(19_900),
}
}
#[test]
fn same_seed_same_output() {
let a = forecast(&input(), 42, 5_000);
let b = forecast(&input(), 42, 5_000);
assert_eq!(a, b);
assert_eq!(format!("{a:?}"), format!("{b:?}"));
// Another seed is another sample (the chance moves a little, the shape not much).
let c = forecast(&input(), 43, 5_000);
assert_ne!((a.p10, a.p50, a.p90), (c.p10, c.p50, c.p90));
assert!(a.chance_bp.abs_diff(c.chance_bp) < 500);
}
#[test]
fn the_obvious_cases() {
// Every day costs exactly 100 CZK: ten days left from zero lands on 1 000 CZK in every run.
let flat = ForecastInput { history: vec![Haler(10_000); 30], spent: Haler(0), days_left: 10, limit: Haler(100_000), known: Haler(0) };
let f = forecast(&flat, 1, 1_000);
assert_eq!((f.chance_bp, f.p10, f.p50, f.p90), (10_000, Haler(100_000), Haler(100_000), Haler(100_000)));
let f = forecast(&ForecastInput { limit: Haler(99_999), ..flat.clone() }, 1, 1_000);
assert_eq!(f.chance_bp, 0);
// Already over the limit.
let over = ForecastInput { spent: Haler(200_000), ..flat.clone() };
assert_eq!(forecast(&over, 1, 1_000).chance_bp, 0);
// No history yet: what is spent plus what is known to come.
let fresh = ForecastInput { history: vec![], spent: Haler(50_000), days_left: 10, limit: Haler(60_000), known: Haler(5_000) };
let f = forecast(&fresh, 1, 100);
assert_eq!((f.chance_bp, f.p50, f.history_days), (10_000, Haler(55_000), 0));
// The last day of the month: nothing left to draw.
let last = ForecastInput { days_left: 0, ..flat };
assert_eq!(forecast(&last, 9, 10).p90, Haler(0));
}
#[test]
fn the_chance_tracks_the_limit() {
let mut prev = 0;
for limit in (1_000_000..4_000_000).step_by(250_000) {
let f = forecast(&ForecastInput { limit: Haler(limit), ..input() }, 7, 4_000);
assert!(f.chance_bp >= prev, "a higher limit is never less likely to hold");
prev = f.chance_bp;
}
assert_eq!(prev, 10_000);
}
@@ -0,0 +1,103 @@
# A synthetic household year (not any bank's format): date;amount in haléře;merchant;category
# Known: Spotify monthly (169 -> 199 in July, decided keep), Netflix monthly (199 -> 259 in October),
# iCloud and Apple Music under one merchant, YouTube after a converted 1 CZK check, WEDOS yearly,
# a Disney+ trial (1 CZK on 28 Oct), rent (housing, never a subscription), Albert weekly (never).
2025-03-10;-39900;WEDOS INTERNET A.S.;
2026-01-05;-16900;PAYPAL *SPOTIFY;
2026-01-12;-19900;NETFLIX.COM;
2026-01-08;-2500;APPLE.COM/BILL;
2026-01-20;-16900;APPLE.COM/BILL;
2026-01-01;-1500000;PRONAJEM BYTU;housing
2026-02-05;-16900;PAYPAL *SPOTIFY;
2026-02-12;-19900;NETFLIX.COM;
2026-02-08;-2500;APPLE.COM/BILL;
2026-02-20;-16900;APPLE.COM/BILL;
2026-02-01;-1500000;PRONAJEM BYTU;housing
2026-03-05;-16900;PAYPAL *SPOTIFY;
2026-03-12;-19900;NETFLIX.COM;
2026-03-08;-2500;APPLE.COM/BILL;
2026-03-20;-16900;APPLE.COM/BILL;
2026-03-01;-1500000;PRONAJEM BYTU;housing
2026-04-05;-16900;PAYPAL *SPOTIFY;
2026-04-12;-19900;NETFLIX.COM;
2026-04-08;-2500;APPLE.COM/BILL;
2026-04-20;-16900;APPLE.COM/BILL;
2026-04-01;-1500000;PRONAJEM BYTU;housing
2026-05-05;-16900;PAYPAL *SPOTIFY;
2026-05-12;-19900;NETFLIX.COM;
2026-05-08;-2500;APPLE.COM/BILL;
2026-05-20;-16900;APPLE.COM/BILL;
2026-05-01;-1500000;PRONAJEM BYTU;housing
2026-06-05;-16900;PAYPAL *SPOTIFY;
2026-06-12;-19900;NETFLIX.COM;
2026-06-08;-2500;APPLE.COM/BILL;
2026-06-20;-16900;APPLE.COM/BILL;
2026-06-01;-1500000;PRONAJEM BYTU;housing
2026-07-05;-19900;PAYPAL *SPOTIFY;
2026-07-12;-19900;NETFLIX.COM;
2026-07-08;-2500;APPLE.COM/BILL;
2026-07-20;-16900;APPLE.COM/BILL;
2026-07-01;-1500000;PRONAJEM BYTU;housing
2026-08-05;-19900;PAYPAL *SPOTIFY;
2026-08-12;-19900;NETFLIX.COM;
2026-08-08;-2500;APPLE.COM/BILL;
2026-08-20;-16900;APPLE.COM/BILL;
2026-08-01;-1500000;PRONAJEM BYTU;housing
2026-09-05;-19900;PAYPAL *SPOTIFY;
2026-09-12;-19900;NETFLIX.COM;
2026-09-08;-2500;APPLE.COM/BILL;
2026-09-20;-16900;APPLE.COM/BILL;
2026-09-01;-1500000;PRONAJEM BYTU;housing
2026-10-05;-19900;PAYPAL *SPOTIFY;
2026-10-12;-25900;NETFLIX.COM;
2026-10-08;-2500;APPLE.COM/BILL;
2026-10-20;-16900;APPLE.COM/BILL;
2026-10-01;-1500000;PRONAJEM BYTU;housing
2026-03-10;-39900;WEDOS INTERNET A.S.;
2026-08-01;-100;GOOGLE *YouTube Premium;
2026-09-01;-23900;GOOGLE *YouTube Premium;
2026-10-01;-23900;GOOGLE *YouTube Premium;
2026-10-28;-100;DISNEY PLUS;
2026-01-03;-31700;ALBERT 0412 PRAHA;groceries
2026-01-10;-135245;ALBERT 0412 PRAHA;groceries
2026-01-17;-126410;ALBERT 0412 PRAHA;groceries
2026-01-24;-39515;ALBERT 0412 PRAHA;groceries
2026-01-31;-64400;ALBERT 0412 PRAHA;groceries
2026-02-07;-145145;ALBERT 0412 PRAHA;groceries
2026-02-14;-132710;ALBERT 0412 PRAHA;groceries
2026-02-21;-32615;ALBERT 0412 PRAHA;groceries
2026-02-28;-49100;ALBERT 0412 PRAHA;groceries
2026-03-07;-59045;ALBERT 0412 PRAHA;groceries
2026-03-14;-67010;ALBERT 0412 PRAHA;groceries
2026-03-21;-121715;ALBERT 0412 PRAHA;groceries
2026-03-28;-105800;ALBERT 0412 PRAHA;groceries
2026-04-04;-116945;ALBERT 0412 PRAHA;groceries
2026-04-11;-49310;ALBERT 0412 PRAHA;groceries
2026-04-18;-66815;ALBERT 0412 PRAHA;groceries
2026-04-25;-114500;ALBERT 0412 PRAHA;groceries
2026-05-02;-78845;ALBERT 0412 PRAHA;groceries
2026-05-09;-79610;ALBERT 0412 PRAHA;groceries
2026-05-16;-107915;ALBERT 0412 PRAHA;groceries
2026-05-23;-75200;ALBERT 0412 PRAHA;groceries
2026-05-30;-64745;ALBERT 0412 PRAHA;groceries
2026-06-06;-37910;ALBERT 0412 PRAHA;groceries
2026-06-13;-125015;ALBERT 0412 PRAHA;groceries
2026-06-20;-107900;ALBERT 0412 PRAHA;groceries
2026-06-27;-74645;ALBERT 0412 PRAHA;groceries
2026-07-04;-44210;ALBERT 0412 PRAHA;groceries
2026-07-11;-118115;ALBERT 0412 PRAHA;groceries
2026-07-18;-92600;ALBERT 0412 PRAHA;groceries
2026-07-25;-108545;ALBERT 0412 PRAHA;groceries
2026-08-01;-98510;ALBERT 0412 PRAHA;groceries
2026-08-08;-87215;ALBERT 0412 PRAHA;groceries
2026-08-15;-149300;ALBERT 0412 PRAHA;groceries
2026-08-22;-46445;ALBERT 0412 PRAHA;groceries
2026-08-29;-80810;ALBERT 0412 PRAHA;groceries
2026-09-05;-32315;ALBERT 0412 PRAHA;groceries
2026-09-12;-38000;ALBERT 0412 PRAHA;groceries
2026-09-19;-128345;ALBERT 0412 PRAHA;groceries
2026-09-26;-111110;ALBERT 0412 PRAHA;groceries
2026-10-03;-73415;ALBERT 0412 PRAHA;groceries
2026-10-10;-118700;ALBERT 0412 PRAHA;groceries
2026-10-17;-114245;ALBERT 0412 PRAHA;groceries
2026-10-24;-69410;ALBERT 0412 PRAHA;groceries
@@ -0,0 +1,225 @@
//! 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());
}