[insight] Subscriptions: cadence, price change, trials, review, cancel kit; seeded month-end forecast
This commit is contained in:
@@ -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()
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user