[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
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "fiscus-insight"
description = "Fiscus Domi: subscriptions, price creep, trials, cancel kits, the month-end forecast"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
fiscus-ledger = { path = "../fiscus-ledger" }
serde.workspace = true
[dev-dependencies]
serde_json.workspace = true
+69
View File
@@ -0,0 +1,69 @@
//! The cancel kit: where to cancel a known provider, and a polite email to send when there is no page.
use crate::subscriptions::Subscription;
use serde::{Deserialize, Serialize};
/// `(a word in the merchant key, provider, the page where its subscription is cancelled)`.
/// Kept short on purpose: only pages that are the provider's own account or cancel page.
const PROVIDERS: &[(&str, &str, &str)] = &[
("netflix", "Netflix", "https://www.netflix.com/cancelplan"),
("spotify", "Spotify", "https://www.spotify.com/account/subscription/"),
("youtube", "YouTube", "https://www.youtube.com/paid_memberships"),
("disney", "Disney+", "https://www.disneyplus.com/account"),
("apple", "Apple", "https://apps.apple.com/account/subscriptions"),
("google", "Google Play", "https://play.google.com/store/account/subscriptions"),
("microsoft", "Microsoft", "https://account.microsoft.com/services"),
("xbox", "Microsoft", "https://account.microsoft.com/services"),
("adobe", "Adobe", "https://account.adobe.com/plans"),
];
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelKit {
pub provider: Option<String>,
pub url: Option<String>,
pub email_subject: String,
pub email_body: String,
}
impl CancelKit {
/// A `mailto:` link with the subject and body filled in and no recipient (the user adds the provider's
/// address).
pub fn mailto(&self) -> String {
format!("mailto:?subject={}&body={}", percent(&self.email_subject), percent(&self.email_body))
}
}
fn percent(s: &str) -> String {
let mut out = String::with_capacity(s.len() * 3);
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
pub fn cancel_kit(sub: &Subscription) -> CancelKit {
let words: Vec<&str> = sub.merchant_key.split(' ').collect();
let known = PROVIDERS.iter().find(|(w, _, _)| words.contains(w));
let name = known.map(|(_, p, _)| p.to_string()).unwrap_or_else(|| sub.merchant.clone());
let cadence = match sub.cadence {
crate::subscriptions::Cadence::Monthly => "monthly",
crate::subscriptions::Cadence::Yearly => "yearly",
};
let last = sub.charges.last().map(|c| c.date.to_string()).unwrap_or_default();
CancelKit {
provider: known.map(|(_, p, _)| p.to_string()),
url: known.map(|(_, _, u)| u.to_string()),
email_subject: format!("Cancel my {name} subscription"),
email_body: format!(
"Hello,\n\nplease cancel my {name} subscription ({cadence}, {} CZK, last charged on {last}) \
with effect from the end of the current period, and confirm the cancellation by email.\n\n\
Please do not charge my card again.\n\nThank you.",
sub.cost.to_czk()
),
}
}
+154
View File
@@ -0,0 +1,154 @@
//! The month-end forecast: a seeded bootstrap Monte Carlo over past daily spending, integers only.
//! Same inputs and seed → the same output, on every machine.
use crate::subscriptions::{Insight, Status};
use fiscus_ledger::{Date, Haler, State};
use serde::{Deserialize, Serialize};
/// Days of history the forecast draws from.
pub const HISTORY_DAYS: i32 = 90;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ForecastInput {
/// Spending (positive) on each past day; a day with nothing is a zero.
pub history: Vec<Haler>,
/// Spent so far this month.
pub spent: Haler,
/// Days after today until the month ends.
pub days_left: u32,
pub limit: Haler,
/// Known charges still due this month (subscriptions).
pub known: Haler,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Forecast {
/// The chance to stay at or under the limit, in basis points (10 000 = certain).
pub chance_bp: u32,
pub p10: Haler,
pub p50: Haler,
pub p90: Haler,
pub runs: u32,
pub history_days: u32,
}
/// xoshiro256** seeded through SplitMix64: small, fast, and fixed here so no dependency can change it.
struct Rng([u64; 4]);
impl Rng {
fn new(seed: u64) -> Rng {
let mut x = seed;
let mut next = || {
x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = x;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
};
Rng([next(), next(), next(), next()])
}
fn next(&mut self) -> u64 {
let s = &mut self.0;
let result = s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9);
let t = s[1] << 17;
s[2] ^= s[0];
s[3] ^= s[1];
s[1] ^= s[2];
s[0] ^= s[3];
s[2] ^= t;
s[3] = s[3].rotate_left(45);
result
}
/// Uniform in `0..n` without modulo bias (Lemire).
fn below(&mut self, n: u64) -> u64 {
let threshold = n.wrapping_neg() % n;
loop {
let m = (self.next() as u128) * (n as u128);
if (m as u64) >= threshold {
return (m >> 64) as u64;
}
}
}
}
pub fn forecast(input: &ForecastInput, seed: u64, runs: u32) -> Forecast {
let runs = runs.max(1);
let base = input.spent.0.saturating_add(input.known.0);
let mut rng = Rng::new(seed);
let mut ends: Vec<i64> = (0..runs)
.map(|_| {
let mut total = base;
if !input.history.is_empty() {
for _ in 0..input.days_left {
let i = rng.below(input.history.len() as u64) as usize;
total = total.saturating_add(input.history[i].0);
}
}
total
})
.collect();
ends.sort_unstable();
let under = ends.iter().filter(|e| **e <= input.limit.0).count() as u64;
let at = |pct: usize| Haler(ends[(ends.len() - 1) * pct / 100]);
Forecast {
chance_bp: (under * 10_000 / runs as u64) as u32,
p10: at(10),
p50: at(50),
p90: at(90),
runs,
history_days: input.history.len() as u32,
}
}
/// The forecast for one budget this month. Subscription charges are taken out of the history and added back
/// as known charges on their due dates, so they are neither missed nor counted twice.
pub fn budget_forecast(state: &State, insight: &Insight, budget: &str, today: Date, seed: u64, runs: u32) -> Option<Forecast> {
let limit = state.budgets.get(budget)?.limit;
let subscription_payments: std::collections::BTreeSet<&str> =
insight.subscriptions.iter().flat_map(|s| s.charges.iter().map(|c| c.payment.as_str())).collect();
let mine: Vec<_> = state
.effective_payments()
.into_iter()
.filter(|p| p.budget.as_deref() == Some(budget) && p.amount.0 < 0)
.collect();
let cost = |p: &fiscus_ledger::EffectivePayment| -p.amount.0;
let month_start = today.month_start();
let spent = Haler(mine.iter().filter(|p| p.date >= month_start && p.date <= today).map(cost).sum());
let first = mine.iter().map(|p| p.date).min();
let window_start = match first {
Some(f) if f > today.add_days(-HISTORY_DAYS) => f,
_ => today.add_days(-HISTORY_DAYS),
};
let days = window_start.days_until(today).max(0) as usize; // days before today
let mut history = vec![0i64; days];
for p in mine.iter().filter(|p| !subscription_payments.contains(p.id.as_str())) {
let i = window_start.days_until(p.date);
if i >= 0 && (i as usize) < days {
history[i as usize] += cost(p);
}
}
let month_end = today.month_end();
let known = Haler(
insight
.subscriptions
.iter()
.filter(|s| s.status == Status::Active && s.budget.as_deref() == Some(budget))
.filter(|s| s.next_charge > today && s.next_charge <= month_end)
.map(|s| s.cost.0)
.sum(),
);
let input = ForecastInput {
history: history.into_iter().map(Haler).collect(),
spent,
days_left: today.days_until(month_end).max(0) as u32,
limit,
known,
};
Some(forecast(&input, seed, runs))
}
+6
View File
@@ -0,0 +1,6 @@
//! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge,
//! how to cancel, and whether the month will stay under its limit. Pure: "today" and seeds are parameters.
pub mod cancel;
pub mod forecast;
pub mod subscriptions;
+245
View File
@@ -0,0 +1,245 @@
//! Subscriptions from the ledger: recurring charges at one merchant, their price changes, trials, the next
//! charge, and what the monthly keep-or-cancel review should ask.
use fiscus_ledger::state::DecisionRecord;
use fiscus_ledger::{Date, Decision, EffectivePayment, Haler, PaymentId, State};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// A charge of at most this much is a card check, not a payment for the service.
pub const TRIAL_MAX: Haler = Haler(1_000);
/// An automatically detected trial is assumed to end this many days after its card check.
pub const TRIAL_DAYS: i32 = 30;
/// A subscription that has not charged this many days after its due date has lapsed.
pub const GRACE_DAYS: i32 = 10;
/// Recurring payments in these categories (rent, energy, savings) are not subscriptions to review.
pub const NOT_SUBSCRIPTIONS: &[&str] = &["housing", "utilities", "transfers", "income"];
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Cadence {
Monthly,
Yearly,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Status {
Active,
/// Due more than [`GRACE_DAYS`] ago and no charge since.
Lapsed,
/// The last decision was "cancel" and it has not charged since.
Cancelled,
/// Cancelled, and charged anyway.
ChargedAfterCancel,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Charge {
pub payment: PaymentId,
pub date: Date,
/// What it cost (positive).
pub cost: Haler,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PriceChange {
pub from: Haler,
pub to: Haler,
pub on: Date,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Subscription {
/// Stable key for decisions: the merchant key, plus `#<first cost in CZK>` when one merchant bills
/// several subscriptions (iCloud and Apple Music both come from `APPLE.COM/BILL`).
pub key: String,
pub merchant: String,
pub merchant_key: String,
pub cadence: Cadence,
pub charges: Vec<Charge>,
/// The last charge.
pub cost: Haler,
/// The most recent change of price.
pub price_change: Option<PriceChange>,
/// The price changed and nobody has decided at the new price yet.
pub creep_alert: bool,
pub next_charge: Date,
pub status: Status,
pub decision: Option<DecisionRecord>,
/// Active and not decided this month (a yearly one: only in the 30 days before it charges).
pub needs_review: bool,
pub category: Option<String>,
pub budget: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Trial {
pub key: String,
pub merchant: String,
pub payment: PaymentId,
pub started: Date,
pub ends: Date,
/// `true` when the end is the 30-day guess, `false` when marked by hand.
pub estimated: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum UpcomingKind {
Charge,
TrialEnds,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Upcoming {
pub key: String,
pub merchant: String,
pub date: Date,
pub kind: UpcomingKind,
pub cost: Option<Haler>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Insight {
pub subscriptions: Vec<Subscription>,
pub trials: Vec<Trial>,
/// Charges and trial ends in `[today, today + 7]`, by date.
pub upcoming: Vec<Upcoming>,
}
/// `|a - b| ≤ 50 % of b`: a price rise stays with its subscription (Netflix went up 30 % at once).
fn near(a: Haler, b: Haler) -> bool {
(a.0 - b.0).unsigned_abs() * 2 <= b.0.unsigned_abs()
}
fn cadence_of(charges: &[&EffectivePayment]) -> Option<Cadence> {
if charges.len() < 2 {
return None;
}
let gaps: Vec<i32> = charges.windows(2).map(|w| w[0].date.days_until(w[1].date)).collect();
// Mostly one price: at most one change in every two steps (a shop's varying totals never pass).
let changes = charges.windows(2).filter(|w| w[0].amount != w[1].amount).count();
if changes * 2 > gaps.len() || (gaps.len() == 1 && changes == 1) {
return None;
}
if gaps.iter().all(|g| (26..=35).contains(g)) {
Some(Cadence::Monthly)
} else if gaps.iter().all(|g| (358..=373).contains(g)) {
Some(Cadence::Yearly)
} else {
None
}
}
pub fn analyse(state: &State, today: Date) -> Insight {
let payments = state.effective_payments();
let mut by_merchant: BTreeMap<&str, Vec<&EffectivePayment>> = BTreeMap::new();
for p in &payments {
let excluded = p.category.as_deref().is_some_and(|c| NOT_SUBSCRIPTIONS.contains(&c));
if p.amount.0 <= 0 && !p.merchant_key.is_empty() && !excluded {
by_merchant.entry(&p.merchant_key).or_default().push(p);
}
}
let mut insight = Insight::default();
for (key, charges) in &by_merchant {
let cost = |p: &EffectivePayment| Haler(-p.amount.0);
let full: Vec<&EffectivePayment> = charges.iter().copied().filter(|p| cost(p) > TRIAL_MAX).collect();
// Trials: the last card check with no full charge after it, or a payment marked by hand.
let last_check = charges.iter().filter(|p| cost(p) <= TRIAL_MAX).next_back();
for p in charges.iter().filter(|p| p.trial_ends.is_some() || Some(*p) == last_check) {
let converted = full.iter().any(|f| f.date > p.date && f.id != p.id);
let (ends, estimated) = match p.trial_ends {
Some(e) => (e, false),
None => (p.date.add_days(TRIAL_DAYS), true),
};
if !converted && ends >= today.add_days(-7) {
insight.trials.push(Trial { key: (*key).into(), merchant: p.merchant.clone(), payment: p.id.clone(), started: p.date, ends, estimated });
}
}
// Clusters of similar amounts, in date order: a price change stays in its cluster.
let mut clusters: Vec<Vec<&EffectivePayment>> = Vec::new();
for p in &full {
let last_cost = |c: &Vec<&EffectivePayment>| cost(c.last().expect("clusters are never empty"));
let best = clusters
.iter_mut()
.filter(|c| near(cost(p), last_cost(c)))
.min_by_key(|c| (cost(p).0 - last_cost(c).0).unsigned_abs());
match best {
Some(c) => c.push(p),
None => clusters.push(vec![p]),
}
}
let found: Vec<(Cadence, &Vec<&EffectivePayment>)> =
clusters.iter().filter_map(|c| cadence_of(c).map(|cad| (cad, c))).collect();
let several = found.len() > 1;
for (cadence, c) in found {
let first = c[0];
let last = c[c.len() - 1];
let sub_key = if several { format!("{key}#{}", cost(first).0 / 100) } else { (*key).to_string() };
let price_change = c
.windows(2)
.rev()
.find(|w| w[0].amount != w[1].amount)
.map(|w| PriceChange { from: cost(w[0]), to: cost(w[1]), on: w[1].date });
let decision = state.decisions.get(&sub_key).and_then(|d| d.last()).cloned();
let next_charge = match cadence {
Cadence::Monthly => last.date.add_months(1),
Cadence::Yearly => last.date.add_years(1),
};
let status = match &decision {
Some(d) if d.decision == Decision::Cancel => {
if c.iter().any(|p| p.date > d.on) {
Status::ChargedAfterCancel
} else {
Status::Cancelled
}
}
_ if today > next_charge.add_days(GRACE_DAYS) => Status::Lapsed,
_ => Status::Active,
};
let decided_at_cost = decision.as_ref().is_some_and(|d| d.amount == cost(last));
let decided_this_month = decision.as_ref().is_some_and(|d| d.on.month() == today.month());
let review_window = match cadence {
Cadence::Monthly => true,
Cadence::Yearly => today.days_until(next_charge) <= 30,
};
insight.subscriptions.push(Subscription {
key: sub_key,
merchant: last.merchant.clone(),
merchant_key: (*key).into(),
cadence,
charges: c.iter().map(|p| Charge { payment: p.id.clone(), date: p.date, cost: cost(p) }).collect(),
cost: cost(last),
creep_alert: price_change.is_some() && !decided_at_cost && status != Status::Cancelled,
price_change,
next_charge,
needs_review: status == Status::Active && !decided_this_month && review_window,
status,
decision,
category: last.category.clone(),
budget: last.budget.clone(),
});
}
}
let horizon = today.add_days(7);
for s in insight.subscriptions.iter().filter(|s| s.status == Status::Active) {
if (today..=horizon).contains(&s.next_charge) {
insight.upcoming.push(Upcoming { key: s.key.clone(), merchant: s.merchant.clone(), date: s.next_charge, kind: UpcomingKind::Charge, cost: Some(s.cost) });
}
}
for t in &insight.trials {
if (today..=horizon).contains(&t.ends) {
insight.upcoming.push(Upcoming { key: t.key.clone(), merchant: t.merchant.clone(), date: t.ends, kind: UpcomingKind::TrialEnds, cost: None });
}
}
insight.upcoming.sort_by(|a, b| a.date.cmp(&b.date).then(a.key.cmp(&b.key)));
insight.subscriptions.sort_by(|a, b| a.next_charge.cmp(&b.next_charge).then(a.key.cmp(&b.key)));
insight.trials.sort_by(|a, b| a.ends.cmp(&b.ends).then(a.key.cmp(&b.key)));
insight
}
+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());
}