Compare commits

..

4 Commits

18 changed files with 1546 additions and 27 deletions
Generated
+4 -4
View File
@@ -139,7 +139,7 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]] [[package]]
name = "fiscus-capture" name = "fiscus-capture"
version = "0.5.0" version = "0.6.0"
dependencies = [ dependencies = [
"fiscus-ledger", "fiscus-ledger",
"proptest", "proptest",
@@ -150,7 +150,7 @@ dependencies = [
[[package]] [[package]]
name = "fiscus-insight" name = "fiscus-insight"
version = "0.5.0" version = "0.6.0"
dependencies = [ dependencies = [
"fiscus-ledger", "fiscus-ledger",
"serde", "serde",
@@ -159,7 +159,7 @@ dependencies = [
[[package]] [[package]]
name = "fiscus-ledger" name = "fiscus-ledger"
version = "0.5.0" version = "0.6.0"
dependencies = [ dependencies = [
"proptest", "proptest",
"serde", "serde",
@@ -169,7 +169,7 @@ dependencies = [
[[package]] [[package]]
name = "fiscus-statement" name = "fiscus-statement"
version = "0.5.0" version = "0.6.0"
dependencies = [ dependencies = [
"encoding_rs", "encoding_rs",
"fiscus-ledger", "fiscus-ledger",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"] members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
[workspace.package] [workspace.package]
version = "0.5.0" version = "0.6.0"
edition = "2021" edition = "2021"
license = "MPL-2.0" license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic" repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
+3 -3
View File
@@ -6,10 +6,10 @@ subscription / price-change / trial detection and a seeded month-end forecast. N
| Crate | | | Crate | |
|:--|:--| |:--|:--|
| `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning, invoices, category plans | | `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning, invoices, category plans, savings goals and challenges |
| `fiscus-statement` | strict CSV, Czech amount and date fields, decoding; bank parsers only from real samples | | `fiscus-statement` | strict CSV, Czech amount and date fields, decoding; bank parsers only from real samples |
| `fiscus-insight` | subscriptions, cancel kits, the forecast, spending, the month against its plan, the month in numbers | | `fiscus-insight` | subscriptions, cancel kits, the forecast, spending, the month against its plan, the month in numbers, goals and their ways to save, medals |
Design: [docs/01_core.md](docs/01_core.md), [02](docs/02_capture_sharing.md), [03 invoices](docs/03_invoices.md), [04 plans and statistics](docs/04_plans_stats.md). Tests: `cargo test --workspace`. Design: [docs/01_core.md](docs/01_core.md), [02](docs/02_capture_sharing.md), [03 invoices](docs/03_invoices.md), [04 plans and statistics](docs/04_plans_stats.md), [05 goals and rewards](docs/05_goals_rewards.md). Tests: `cargo test --workspace`.
Licence: MPL-2.0. Licence: MPL-2.0.
+44 -15
View File
@@ -1,6 +1,7 @@
//! The cancel kit: where to cancel a known provider, and a polite email to send when there is no page. //! 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 crate::subscriptions::Subscription;
use fiscus_ledger::invoice::Language;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// `(a word in the merchant key, provider, the page where its subscription is cancelled)`. /// `(a word in the merchant key, provider, the page where its subscription is cancelled)`.
@@ -46,24 +47,52 @@ fn percent(s: &str) -> String {
out out
} }
/// The kit with its email in English.
pub fn cancel_kit(sub: &Subscription) -> CancelKit { pub fn cancel_kit(sub: &Subscription) -> CancelKit {
cancel_kit_in(sub, Language::En)
}
/// The kit with its email in Czech or English (the app's language: most Czech providers read Czech).
pub fn cancel_kit_in(sub: &Subscription, language: Language) -> CancelKit {
let words: Vec<&str> = sub.merchant_key.split(' ').collect(); let words: Vec<&str> = sub.merchant_key.split(' ').collect();
let known = PROVIDERS.iter().find(|(w, _, _)| words.contains(w)); let known = PROVIDERS.iter().find(|(w, _, _)| words.contains(w));
let name = known.map(|(_, p, _)| p.to_string()).unwrap_or_else(|| sub.merchant.clone()); let name = known.map(|(_, p, _)| p.to_string()).unwrap_or_else(|| sub.merchant.clone());
let cadence = match sub.cadence { let monthly = sub.cadence == crate::subscriptions::Cadence::Monthly;
crate::subscriptions::Cadence::Monthly => "monthly", let last = sub.charges.last().map(|c| c.date);
crate::subscriptions::Cadence::Yearly => "yearly", let cost = sub.cost.to_czk();
}; let (email_subject, email_body) = match language {
let last = sub.charges.last().map(|c| c.date.to_string()).unwrap_or_default(); Language::En => (
CancelKit { format!("Cancel my {name} subscription"),
provider: known.map(|(_, p, _)| p.to_string()), format!(
url: known.map(|(_, _, u)| u.to_string()), "Hello,
email_subject: format!("Cancel my {name} subscription"),
email_body: format!( please cancel my {name} subscription ({}, {cost} CZK, last charged on {}) with effect from the end of the current period, and confirm the cancellation by email.
"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.
Please do not charge my card again.\n\nThank you.",
sub.cost.to_czk() Thank you.",
if monthly { "monthly" } else { "yearly" },
last.map(|d| d.to_string()).unwrap_or_default(),
),
), ),
} Language::Cs => (
format!("Zrušení předplatného {name}"),
format!(
"Dobrý den,
prosím o zrušení mého předplatného {name} ({}, {cost} Kč, naposledy strženo {}) ke konci aktuálního období a o potvrzení zrušení e-mailem.
Prosím, dále mi nestrhávejte platby z karty.
Děkuji.",
if monthly { "měsíční" } else { "roční" },
last.map(|d| {
let (y, m, day) = d.ymd();
format!("{day}. {m}. {y}")
})
.unwrap_or_default(),
),
),
};
CancelKit { provider: known.map(|(_, p, _)| p.to_string()), url: known.map(|(_, _, u)| u.to_string()), email_subject, email_body }
} }
+293
View File
@@ -0,0 +1,293 @@
//! Savings goals this month: how full each one is, what is still needed each month to make its date, the month
//! you get there at your pace, this month's saving split between the goal's ways, and where the money could come
//! from. Fiscus never moves money; these are suggestions, and a goal fills only with what you say you put aside.
use crate::plan::month_plan;
use crate::spending::{between, category_of, inflow, is_spending, outflows};
use crate::subscriptions::{Cadence, Insight, Status};
use fiscus_ledger::categories::NOT_PLANNABLE;
use fiscus_ledger::goal::{Colour, GoalRecord, Way, WayKind};
use fiscus_ledger::{Category, Date, Decision, Haler, State};
use serde::Serialize;
/// One way's part of this month's saving.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct WayPart {
pub way: Way,
/// What the way comes to this month (before what you already put aside by it).
pub amount: Haler,
/// Put aside by this way this month.
pub saved: Haler,
/// Still to put aside by it this month: `amount - saved`, never more than the goal still needs.
pub left: Haler,
/// Round-ups: the card payments rounded up. Leftover / income: the whole amount the share is of.
pub basis: Haler,
pub payments: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct GoalStatus {
pub id: String,
pub name: String,
pub colour: Colour,
pub target: Haler,
pub saved: Haler,
/// Saved of the target in thousandths, at most 1000: the tank's level.
pub permille: u32,
pub reached: bool,
pub closed: Option<Date>,
pub by: Option<Date>,
/// Months from this one to the month of `by`, both included; 0 once it has passed.
pub months_left: Option<u32>,
/// What is still needed each month to make `by`, rounded up to whole crowns.
pub needed_per_month: Option<Haler>,
/// Put aside per month on average over the last three complete months the goal had savings in reach of.
pub pace: Haler,
/// The month you get there at that pace; `None` without a pace (or when reached).
pub reach_month: Option<Date>,
pub parts: Vec<WayPart>,
/// All the parts still to put aside this month.
pub left_this_month: Haler,
pub saved_this_month: Haler,
}
/// Where the money could come from: it only points, it changes nothing.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Source {
/// A subscription still charging that you have not decided to keep: what it costs a month.
Subscription { key: String, merchant: String, monthly: Haler },
/// A category that cost more last month than its average of the three months before.
Category { category: Category, last: Haler, average: Haler, extra: Haler },
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct GoalsMonth {
/// The 1st of this month.
pub month: Date,
/// Open goals in the order made, then the closed ones, the latest closed first.
pub goals: Vec<GoalStatus>,
/// What last month's plans did not use (what "leftover" shares are of).
pub leftover: Haler,
/// Last month's money in (what "income" shares are of).
pub income: Haler,
/// Leftover and income already given to goals, in thousandths.
pub leftover_given: u32,
pub income_given: u32,
/// Everything in open goals.
pub saved: Haler,
pub sources: Vec<Source>,
}
/// `a / b` rounded up, both positive.
fn div_up(a: i64, b: i64) -> i64 {
(a + b - 1) / b
}
fn share(of: Haler, permille: u32) -> Haler {
Haler((i128::from(of.0.max(0)) * i128::from(permille) / 1000) as i64)
}
fn months_between(from: Date, to: Date) -> i64 {
let (fy, fm, _) = from.ymd();
let (ty, tm, _) = to.ymd();
i64::from(ty - fy) * 12 + i64::from(tm) - i64::from(fm)
}
/// Round-ups this month: each spending payment rounded up to the next `to`; a payment already a multiple adds 0.
pub fn round_ups(state: &State, to: Haler, today: Date) -> (Haler, usize) {
if to.0 <= 0 {
return (Haler::ZERO, 0);
}
let mut sum = 0i64;
let mut n = 0;
for p in between(state, today.month_start(), today).iter().filter(|p| is_spending(p)) {
let paid = p.amount.0.saturating_neg();
let r = paid % to.0;
if r != 0 {
sum = sum.saturating_add(to.0 - r);
n += 1;
}
}
(Haler(sum), n)
}
/// What last month's plans did not use: for each planned category, the plan less what was spent, never below 0.
pub fn leftover(state: &State, today: Date) -> Haler {
let last = today.month_start().add_months(-1);
let Some(p) = month_plan(state, last, today) else { return Haler::ZERO };
Haler(p.rows.iter().filter_map(|r| r.left).fold(0i64, |s, l| s.saturating_add(l.0.max(0))))
}
/// Last month's money in, not counting transfers.
pub fn last_income(state: &State, today: Date) -> Haler {
let last = today.month_start().add_months(-1);
inflow(&between(state, last, last.month_end())).unwrap_or(Haler::ZERO)
}
fn saved_in(g: &GoalRecord, from: Date, to: Date, way: Option<WayKind>) -> Haler {
Haler(
g.savings
.iter()
.filter(|s| s.on >= from && s.on <= to && (way.is_none() || s.way == way))
.fold(0i64, |sum, s| sum.saturating_add(s.amount.0)),
)
}
fn status(g: &GoalRecord, today: Date, leftover: Haler, income: Haler, rounds: &mut dyn FnMut(Haler) -> (Haler, usize)) -> GoalStatus {
let month = today.month_start();
let saved = g.saved();
let remaining = Haler(g.target.0.saturating_sub(saved.0).max(0));
let reached = remaining.0 == 0;
let permille = if g.target.0 > 0 { (i128::from(saved.0.max(0)) * 1000 / i128::from(g.target.0)).min(1000) as u32 } else { 0 };
let months_left = g.by.map(|by| (months_between(month, by.month_start()) + 1).max(0) as u32);
let needed_per_month = match (months_left, reached) {
(_, true) | (None, _) => None,
(Some(0), false) => Some(remaining),
(Some(n), false) => Some(Haler(div_up(div_up(remaining.0, i64::from(n)), 100) * 100)),
};
// The pace: the last three complete months, from the month of the first saving on.
let first = g.savings.iter().map(|s| s.on.month_start()).min();
let pace = match first {
Some(first) if first < month => {
let from = month.add_months(-3).max(first);
let n = months_between(from, month).max(1);
Haler(saved_in(g, from, month.add_days(-1), None).0 / n)
}
_ => Haler::ZERO,
};
let reach_month = (!reached && pace.0 > 0 && g.is_open()).then(|| {
let n = div_up(remaining.0, pace.0).min(1200) as i32;
month.add_months(n)
});
let mut budget = remaining.0;
let parts: Vec<WayPart> = if g.is_open() {
g.ways
.iter()
.map(|w| {
let (amount, basis, payments) = match *w {
Way::Fixed { amount } => (amount, amount, 0),
Way::RoundUp { to } => {
let (sum, n) = rounds(to);
(sum, sum, n)
}
Way::Leftover { permille } => (share(leftover, u32::from(permille)), leftover, 0),
Way::Income { permille } => (share(income, u32::from(permille)), income, 0),
};
let saved = saved_in(g, month, month.month_end(), Some(w.kind()));
let left = amount.0.saturating_sub(saved.0).clamp(0, budget.max(0));
budget -= left;
WayPart { way: *w, amount, saved, left: Haler(left), basis, payments }
})
.collect()
} else {
Vec::new()
};
let left_this_month = Haler(parts.iter().map(|p| p.left.0).sum());
GoalStatus {
id: g.id.clone(),
name: g.name.clone(),
colour: g.colour,
target: g.target,
saved,
permille,
reached,
closed: g.closed,
by: g.by,
months_left,
needed_per_month,
pace,
reach_month,
parts,
left_this_month,
saved_this_month: saved_in(g, month, month.month_end(), None),
}
}
/// Subscriptions still charging and not decided "keep", the costliest a month first; then categories that cost
/// more last month than the three months before, by at least 10 % and 200 Kč.
pub fn sources(state: &State, insight: &Insight, today: Date) -> Vec<Source> {
let mut subs: Vec<Source> = insight
.subscriptions
.iter()
.filter(|s| s.status == Status::Active && s.decision.as_ref().map(|d| d.decision) != Some(Decision::Keep))
.map(|s| Source::Subscription {
key: s.key.clone(),
merchant: s.merchant.clone(),
monthly: match s.cadence {
Cadence::Monthly => s.cost,
Cadence::Yearly => Haler(div_up(s.cost.0, 12)),
},
})
.collect();
subs.sort_by_key(|s| match s {
Source::Subscription { monthly, .. } => std::cmp::Reverse(monthly.0),
_ => std::cmp::Reverse(0),
});
subs.truncate(5);
let last = today.month_start().add_months(-1);
let first = state.effective_payments().iter().map(|p| p.date.month_start()).min();
let mut cats = Vec::new();
if let Some(first) = first {
let earlier: Vec<Date> = (1..=3).map(|n| last.add_months(-n)).filter(|m| *m >= first).collect();
if let (Some(oldest), Some(spent_last)) = (earlier.last().copied(), outflows(&between(state, last, last.month_end()))) {
if let Some(spent_before) = outflows(&between(state, oldest, last.add_days(-1))) {
for (category, amount) in spent_last {
if NOT_PLANNABLE.contains(&category.as_str()) {
continue;
}
let average = Haler(spent_before.get(&category).map(|h| h.0).unwrap_or(0) / earlier.len() as i64);
let extra = amount.0.saturating_sub(average.0);
if average.0 > 0 && extra >= 20_000 && i128::from(amount.0) * 10 > i128::from(average.0) * 11 {
cats.push(Source::Category { category, last: amount, average, extra: Haler(extra) });
}
}
}
}
}
cats.sort_by_key(|s| match s {
Source::Category { extra, .. } => std::cmp::Reverse(extra.0),
_ => std::cmp::Reverse(0),
});
cats.truncate(3);
subs.extend(cats);
subs
}
pub fn goals_month(state: &State, insight: &Insight, today: Date) -> GoalsMonth {
let leftover = leftover(state, today);
let income = last_income(state, today);
let mut cache: Vec<(Haler, (Haler, usize))> = Vec::new();
let mut rounds = |to: Haler| {
if let Some((_, r)) = cache.iter().find(|(t, _)| *t == to) {
return *r;
}
let r = round_ups(state, to, today);
cache.push((to, r));
r
};
let mut open: Vec<&GoalRecord> = state.goals.values().filter(|g| g.is_open()).collect();
open.sort_by_key(|g| g.seq);
let mut closed: Vec<&GoalRecord> = state.goals.values().filter(|g| !g.is_open()).collect();
closed.sort_by_key(|g| std::cmp::Reverse((g.closed, g.seq)));
let given = |kind: WayKind| open.iter().flat_map(|g| g.ways.iter()).map(|w| w.share_of(kind)).sum::<u32>();
let (leftover_given, income_given) = (given(WayKind::Leftover), given(WayKind::Income));
let saved = Haler(open.iter().fold(0i64, |s, g| s.saturating_add(g.saved().0)));
let goals = open.iter().chain(closed.iter()).map(|g| status(g, today, leftover, income, &mut rounds)).collect();
GoalsMonth { month: today.month_start(), goals, leftover, income, leftover_given, income_given, saved, sources: sources(state, insight, today) }
}
/// What was spent in one category from `from` to `to`, both included (positive).
pub fn spent_in(state: &State, category: &str, from: Date, to: Date) -> Haler {
Haler(
between(state, from, to)
.iter()
.filter(|p| is_spending(p) && category_of(p) == category)
.fold(0i64, |s, p| s.saturating_add(p.amount.0.saturating_neg())),
)
}
+3 -1
View File
@@ -1,11 +1,13 @@
//! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge, //! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge,
//! how to cancel, whether the month will stay under its limit, where the money went and how it compares with //! how to cancel, whether the month will stay under its limit, where the money went and how it compares with
//! your plan. Pure: "today" and seeds are parameters. //! your plan, how your savings goals fill, and the medals and challenges you earn. Pure: "today" and seeds are parameters.
pub mod cancel; pub mod cancel;
pub mod forecast; pub mod forecast;
pub mod goals;
pub mod household; pub mod household;
pub mod plan; pub mod plan;
pub mod rewards;
pub mod spending; pub mod spending;
pub mod stats; pub mod stats;
pub mod subscriptions; pub mod subscriptions;
+348
View File
@@ -0,0 +1,348 @@
//! Medals and challenges, computed from the ledger and never stored. A medal is earned by a complete period
//! (a month, a quarter, a challenge's last day); what is still running shows how far it is.
use crate::goals::spent_in;
use crate::plan::month_plan;
use crate::spending::is_spending;
use crate::subscriptions::{Insight, Status};
use fiscus_ledger::goal::{ChallengeGoal, ChallengeRecord};
use fiscus_ledger::{BudgetId, Date, Decision, Haler, State};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
/// A run of months this long earns the streak medals.
pub const STREAK: u32 = 3;
/// A goal's milestones, in thousandths of its target.
pub const MILESTONES: [u32; 4] = [250, 500, 750, 1000];
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Medal {
/// A budget under its limit this many complete months running (3 or more), up to `until`'s month.
UnderBudget { budget: BudgetId, name: String, months: u32, until: Date },
/// Every category plan of a month kept (a month with at least one plan).
PlansKept { month: Date },
/// A subscription decided "cancel" and not charged since, past the day it would have charged.
Cancelled { subscription: String, merchant: String, since: Date },
/// A challenge won.
ChallengeWon { challenge: String, goal: ChallengeGoal },
/// Every invoice due in a quarter paid by its due date.
InvoicesOnTime { year: i32, quarter: u32 },
/// A goal reached a quarter, a half, three quarters, or all of its target.
GoalMilestone { goal: String, name: String, permille: u32 },
/// Money put aside in this many complete months running (3 or more), up to `until`'s month.
SavingStreak { months: u32, until: Date },
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Earned {
pub medal: Medal,
/// The day it was earned.
pub on: Date,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
Running,
Won,
Lost,
Abandoned,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ChallengeStatus {
pub id: String,
pub goal: ChallengeGoal,
pub starts: Date,
pub ends: Date,
pub outcome: Outcome,
/// Spent in the category (spending challenges) or put aside (saving), so far.
pub so_far: Haler,
/// The tank: what is left of a spending limit, or what is saved of the amount, in thousandths (at most 1000).
pub permille: u32,
/// Days to the last day, 0 on it and after.
pub days_left: i32,
}
/// How far the medals still to come are.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Progress {
/// Complete months running with money put aside, up to last month.
pub saving_months: u32,
pub saved_this_month: bool,
/// Each budget with a limit: complete months running under it, up to last month.
pub budgets: Vec<(BudgetId, String, u32)>,
/// Each open goal not yet full: its level and the next milestone.
pub goals: Vec<(String, String, u32, u32)>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Rewards {
/// The latest first.
pub medals: Vec<Earned>,
/// Running first (the soonest to end first), then the finished ones, the latest first.
pub challenges: Vec<ChallengeStatus>,
pub progress: Progress,
}
fn permille(part: i64, whole: i64) -> u32 {
if whole <= 0 {
return 0;
}
(i128::from(part.clamp(0, whole)) * 1000 / i128::from(whole)) as u32
}
/// Runs of `true` months: (length, last month of the run).
fn runs(months: &[(Date, bool)]) -> Vec<(u32, Date)> {
let mut out = Vec::new();
let mut n = 0u32;
for (i, (m, ok)) in months.iter().enumerate() {
if *ok {
n += 1;
}
let ends = !*ok || i + 1 == months.len();
if ends && n > 0 {
let last = if *ok { *m } else { months[i - 1].0 };
out.push((n, last));
n = 0;
}
}
out
}
/// The run that reaches the last month, if it does.
fn current(months: &[(Date, bool)]) -> u32 {
months.iter().rev().take_while(|(_, ok)| *ok).count() as u32
}
/// The complete months from the first payment's month to last month.
fn complete_months(state: &State, today: Date) -> Vec<Date> {
let last = today.month_start().add_months(-1);
let Some(first) = state.effective_payments().iter().map(|p| p.date.month_start()).min() else { return Vec::new() };
let mut out = Vec::new();
let mut m = first;
while m <= last && out.len() < 1200 {
out.push(m);
m = m.add_months(1);
}
out
}
fn challenge(state: &State, insight: &Insight, c: &ChallengeRecord, today: Date) -> ChallengeStatus {
let to = today.min(c.ends);
let over = today > c.ends;
let (so_far, level, outcome) = match &c.goal {
ChallengeGoal::SpendUnder { category, amount } => {
let spent = if today < c.starts { Haler::ZERO } else { spent_in(state, category, c.starts, to) };
let outcome = if spent > *amount {
Outcome::Lost
} else if over {
Outcome::Won
} else {
Outcome::Running
};
(spent, permille(amount.0.saturating_sub(spent.0), amount.0), outcome)
}
ChallengeGoal::NoSpend { category } => {
let spent = if today < c.starts { Haler::ZERO } else { spent_in(state, category, c.starts, to) };
let outcome = if spent.0 > 0 {
Outcome::Lost
} else if over {
Outcome::Won
} else {
Outcome::Running
};
(spent, if spent.0 > 0 { 0 } else { 1000 }, outcome)
}
ChallengeGoal::Cancel { subscription } => {
let decided = state
.decisions
.get(subscription)
.and_then(|ds| ds.iter().rev().find(|d| d.on >= c.starts && d.on <= c.ends))
.filter(|d| d.decision == Decision::Cancel);
let charged_after = decided.is_some_and(|d| {
insight
.subscriptions
.iter()
.filter(|s| &s.key == subscription)
.flat_map(|s| s.charges.iter())
.any(|ch| ch.date > d.on && ch.date <= to)
});
let outcome = match (decided.is_some(), charged_after, over) {
(_, true, _) => Outcome::Lost,
(true, false, true) => Outcome::Won,
(false, _, true) => Outcome::Lost,
_ => Outcome::Running,
};
(Haler::ZERO, if decided.is_some() && !charged_after { 1000 } else { 0 }, outcome)
}
ChallengeGoal::Save { goal, amount } => {
let saved = state.goals.get(goal).map(|g| g.savings.iter().filter(|s| s.on >= c.starts && s.on <= to).fold(0i64, |sum, s| sum.saturating_add(s.amount.0))).unwrap_or(0);
let outcome = if saved >= amount.0 {
Outcome::Won
} else if over {
Outcome::Lost
} else {
Outcome::Running
};
(Haler(saved), permille(saved, amount.0), outcome)
}
};
let outcome = match (c.abandoned, outcome) {
(Some(_), Outcome::Running | Outcome::Lost) => Outcome::Abandoned,
(Some(on), Outcome::Won) if on <= c.ends && !won_before(state, c, on) => Outcome::Abandoned,
(_, o) => o,
};
ChallengeStatus { id: c.id.clone(), goal: c.goal.clone(), starts: c.starts, ends: c.ends, outcome, so_far, permille: level, days_left: today.days_until(c.ends).max(0) }
}
/// A saving challenge reached before it was given up stays won.
fn won_before(state: &State, c: &ChallengeRecord, on: Date) -> bool {
match &c.goal {
ChallengeGoal::Save { goal, amount } => {
state.goals.get(goal).map(|g| g.savings.iter().filter(|s| s.on >= c.starts && s.on <= on).fold(0i64, |sum, s| sum.saturating_add(s.amount.0))).unwrap_or(0) >= amount.0
}
_ => false,
}
}
/// When a challenge was won: a saving challenge on the day it was reached, the others on their last day.
fn won_on(state: &State, c: &ChallengeRecord) -> Date {
if let ChallengeGoal::Save { goal, amount } = &c.goal {
if let Some(g) = state.goals.get(goal) {
let mut sum = 0i64;
let mut savings: Vec<_> = g.savings.iter().filter(|s| s.on >= c.starts && s.on <= c.ends).collect();
savings.sort_by_key(|s| (s.on, s.seq));
for s in savings {
sum = sum.saturating_add(s.amount.0);
if sum >= amount.0 {
return s.on;
}
}
}
}
c.ends
}
/// `shared`: the shared budgets in this log, which earn no budget medal (only your own payments are counted
/// here, the limit is everyone's).
pub fn rewards(state: &State, insight: &Insight, shared: &BTreeSet<BudgetId>, today: Date) -> Rewards {
let mut medals: Vec<Earned> = Vec::new();
let months = complete_months(state, today);
// Budgets under their limit (the latest limit), month by month.
let mut budgets = Vec::new();
let payments = state.effective_payments();
for b in state.budgets.values().filter(|b| b.limit.0 > 0 && !shared.contains(&b.id)) {
let flags: Vec<(Date, bool)> = months
.iter()
.map(|m| {
let spent = payments
.iter()
.filter(|p| p.budget.as_deref() == Some(b.id.as_str()) && p.date >= *m && p.date <= m.month_end() && is_spending(p))
.fold(0i64, |s, p| s.saturating_add(p.amount.0.saturating_neg()));
(*m, spent <= b.limit.0)
})
.collect();
for (n, last) in runs(&flags).into_iter().filter(|(n, _)| *n >= STREAK) {
medals.push(Earned { medal: Medal::UnderBudget { budget: b.id.clone(), name: b.name.clone(), months: n, until: last }, on: last.month_end() });
}
budgets.push((b.id.clone(), b.name.clone(), current(&flags)));
}
// Months with every plan kept.
for m in &months {
if let Some(p) = month_plan(state, *m, today) {
let planned: Vec<_> = p.rows.iter().filter(|r| r.planned.is_some_and(|x| x.0 > 0)).collect();
if !planned.is_empty() && planned.iter().all(|r| r.left.is_some_and(|l| l.0 >= 0)) {
medals.push(Earned { medal: Medal::PlansKept { month: *m }, on: m.month_end() });
}
}
}
// Cancelled and not charged since, past the day it would have charged.
for s in insight.subscriptions.iter().filter(|s| s.status == Status::Cancelled && s.next_charge < today) {
if let Some(d) = s.decision.as_ref().filter(|d| d.decision == Decision::Cancel) {
medals.push(Earned { medal: Medal::Cancelled { subscription: s.key.clone(), merchant: s.merchant.clone(), since: d.on }, on: s.next_charge });
}
}
// Challenges.
let mut challenges: Vec<ChallengeStatus> = Vec::new();
for c in state.challenges.values() {
let st = challenge(state, insight, c, today);
if st.outcome == Outcome::Won {
medals.push(Earned { medal: Medal::ChallengeWon { challenge: c.id.clone(), goal: c.goal.clone() }, on: won_on(state, c) });
}
challenges.push(st);
}
challenges.sort_by(|a, b| {
let running = |x: &ChallengeStatus| x.outcome == Outcome::Running;
running(b).cmp(&running(a)).then_with(|| if running(a) { a.ends.cmp(&b.ends) } else { b.ends.cmp(&a.ends) }).then_with(|| a.id.cmp(&b.id))
});
// Quarters with every invoice due in them paid by its due date.
let mut quarters: BTreeMap<(i32, u32), bool> = BTreeMap::new();
for r in state.invoices.values().filter(|r| !r.cancelled) {
let (y, m, _) = r.invoice.due.ymd();
let ok = r.paid.as_ref().is_some_and(|p| p.on <= r.invoice.due);
let slot = quarters.entry((y, (m - 1) / 3 + 1)).or_insert(true);
*slot &= ok;
}
for ((y, q), ok) in quarters {
let end = Date::from_ymd(y, q * 3, 1).map(Date::month_end);
if let Some(end) = end.filter(|e| ok && *e < today) {
medals.push(Earned { medal: Medal::InvoicesOnTime { year: y, quarter: q }, on: end });
}
}
// Goals: their milestones, the first day each was reached.
let mut goals_progress = Vec::new();
for g in state.goals.values() {
let mut savings: Vec<_> = g.savings.iter().collect();
savings.sort_by_key(|s| s.seq);
let mut sum = 0i64;
let mut reached = 0usize;
for s in savings {
sum = sum.saturating_add(s.amount.0);
let level = permille(sum, g.target.0);
while reached < MILESTONES.len() && level >= MILESTONES[reached] {
medals.push(Earned { medal: Medal::GoalMilestone { goal: g.id.clone(), name: g.name.clone(), permille: MILESTONES[reached] }, on: s.on });
reached += 1;
}
}
let level = permille(g.saved().0, g.target.0);
if g.is_open() && level < 1000 {
let next = MILESTONES.iter().copied().find(|m| *m > level).unwrap_or(1000);
goals_progress.push((g.id.clone(), g.name.clone(), level, next));
}
}
// Months running with money put aside (more in than out across the goals).
let saved_in = |from: Date, to: Date| {
state.goals.values().flat_map(|g| g.savings.iter()).filter(|s| s.on >= from && s.on <= to).fold(0i64, |sum, s| sum.saturating_add(s.amount.0))
};
let first_saving = state.goals.values().flat_map(|g| g.savings.iter()).map(|s| s.on.month_start()).min();
let saving_flags: Vec<(Date, bool)> = match first_saving {
Some(first) => months.iter().filter(|m| **m >= first).map(|m| (*m, saved_in(*m, m.month_end()) > 0)).collect(),
None => Vec::new(),
};
for (n, last) in runs(&saving_flags).into_iter().filter(|(n, _)| *n >= STREAK) {
medals.push(Earned { medal: Medal::SavingStreak { months: n, until: last }, on: last.month_end() });
}
medals.sort_by_key(|m| std::cmp::Reverse(m.on));
let month = today.month_start();
Rewards {
medals,
challenges,
progress: Progress {
saving_months: current(&saving_flags),
saved_this_month: saved_in(month, today) > 0,
budgets,
goals: goals_progress,
},
}
}
+1 -1
View File
@@ -149,7 +149,7 @@ pub fn analyse(state: &State, today: Date) -> Insight {
let full: Vec<&EffectivePayment> = charges.iter().copied().filter(|p| cost(p) > TRIAL_MAX).collect(); 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. // 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(); let last_check = charges.iter().rfind(|p| cost(p) <= TRIAL_MAX);
for p in charges.iter().filter(|p| p.trial_ends.is_some() || Some(*p) == last_check) { 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 converted = full.iter().any(|f| f.date > p.date && f.id != p.id);
let (ends, estimated) = match p.trial_ends { let (ends, estimated) = match p.trial_ends {
+278
View File
@@ -0,0 +1,278 @@
//! Savings goals this month and the rewards: round-ups to the haléř, what last month's plans left, a share of
//! income, the split capped at what a goal still needs, the pace and the month you get there, where the money
//! could come from; medals only for complete periods, and challenges won, lost or given up.
use fiscus_insight::goals::{goals_month, round_ups, Source};
use fiscus_insight::rewards::{rewards, Medal, Outcome};
use fiscus_insight::subscriptions::analyse;
use fiscus_ledger::goal::{ChallengeGoal, Colour, Way, WayKind};
use fiscus_ledger::{Date, Decision, Event, EventBody, Haler, State, Timestamp};
use std::collections::BTreeSet;
fn d(s: &str) -> Date {
s.parse().unwrap()
}
/// A ledger from `(date, amount in haléře, merchant, category)` added by hand, then `extra` events.
fn ledger(payments: &[(&str, i64, &str, &str)], extra: Vec<EventBody>) -> State {
let mut log: Vec<Event> = vec![Event::new("b", Timestamp(0), EventBody::BudgetCreated { budget: "home".into(), name: "Home".into(), limit: Haler(1_000_000) })];
log.extend(payments.iter().enumerate().map(|(i, (date, amount, merchant, category))| {
Event::new(
format!("e{i}"),
Timestamp(0),
EventBody::PaymentAdded {
payment: format!("p{i}"),
amount: Haler(*amount),
date: d(date),
merchant: merchant.to_string(),
category: (!category.is_empty()).then(|| category.to_string()),
note: None,
},
)
}));
log.extend(extra.into_iter().enumerate().map(|(i, b)| Event::new(format!("x{i}"), Timestamp(0), b)));
let s = State::replay(&log);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
s
}
fn goal(id: &str, target: i64, by: Option<&str>) -> EventBody {
EventBody::GoalCreated { goal: id.into(), name: format!("Goal {id}"), target: Haler(target), by: by.map(d), colour: Colour::Amber }
}
fn saved(goal: &str, saving: &str, amount: i64, on: &str, way: Option<WayKind>) -> EventBody {
EventBody::GoalSaved { goal: goal.into(), saving: saving.into(), amount: Haler(amount), on: d(on), way }
}
#[test]
fn round_ups_add_the_differences_to_the_next_10_50_or_100_kc() {
let today = d("2026-11-07");
let s = ledger(
&[
("2026-11-02", -12_900, "Albert", "groceries"),
("2026-11-03", -25_000, "Lokál", "eating-out"),
("2026-11-04", -8_750, "Trafika", ""),
("2026-11-05", -100_000, "To savings", "transfers"),
("2026-11-05", 5_000_000, "Salary", "income"),
("2026-10-30", -12_345, "Albert", "groceries"),
],
vec![],
);
// 129 → 130, 250 stays, 87,50 → 90: 1 + 0 + 2,50. Transfers, money in and last month are not rounded.
assert_eq!(round_ups(&s, Haler(1_000), today), (Haler(350), 2));
assert_eq!(round_ups(&s, Haler(10_000), today), (Haler(7_100 + 5_000 + 1_250), 3));
}
#[test]
fn a_goal_month_splits_its_saving_between_its_ways() {
let today = d("2026-11-07");
let s = ledger(
&[
// October: groceries under plan by 1 500 Kč, eating out over (leftover 0, not negative); 40 000 in.
("2026-10-05", -650_000, "Albert", "groceries"),
("2026-10-06", -250_000, "Lokál", "eating-out"),
("2026-10-10", 4_000_000, "Salary", "income"),
// November so far.
("2026-11-02", -12_900, "Albert", "groceries"),
],
vec![
EventBody::CategoryPlanned { category: "groceries".into(), amount: Haler(800_000), from: d("2026-10-01") },
EventBody::CategoryPlanned { category: "eating-out".into(), amount: Haler(200_000), from: d("2026-10-01") },
goal("g1", 4_000_000, Some("2027-06-30")),
EventBody::GoalWaysSet {
goal: "g1".into(),
ways: vec![Way::Fixed { amount: Haler(200_000) }, Way::RoundUp { to: Haler(1_000) }, Way::Leftover { permille: 500 }, Way::Income { permille: 100 }],
},
saved("g1", "s1", 300_000, "2026-08-10", None),
saved("g1", "s2", 300_000, "2026-09-10", None),
saved("g1", "s3", 300_000, "2026-10-10", None),
saved("g1", "s4", 100_000, "2026-11-03", Some(WayKind::Fixed)),
],
);
let m = goals_month(&s, &analyse(&s, today), today);
assert_eq!((m.leftover, m.income, m.leftover_given, m.income_given), (Haler(150_000), Haler(4_000_000), 500, 100));
let g = &m.goals[0];
assert_eq!((g.saved, g.permille, g.reached), (Haler(1_000_000), 250, false));
let parts: Vec<(WayKind, Haler, Haler, Haler)> = g.parts.iter().map(|p| (p.way.kind(), p.amount, p.saved, p.left)).collect();
assert_eq!(
parts,
[
(WayKind::Fixed, Haler(200_000), Haler(100_000), Haler(100_000)),
(WayKind::RoundUp, Haler(100), Haler::ZERO, Haler(100)),
(WayKind::Leftover, Haler(75_000), Haler::ZERO, Haler(75_000)),
(WayKind::Income, Haler(400_000), Haler::ZERO, Haler(400_000)),
]
);
assert_eq!((g.left_this_month, g.saved_this_month), (Haler(575_100), Haler(100_000)));
// November to June is 8 months: 30 000 Kč still needed, 3 750 Kč a month.
assert_eq!((g.months_left, g.needed_per_month), (Some(8), Some(Haler(375_000))));
// August to October at 3 000 Kč a month: 30 000 Kč more is 10 months on, in September 2027.
assert_eq!((g.pace, g.reach_month), (Haler(300_000), Some(d("2027-09-01"))));
}
#[test]
fn the_split_never_asks_for_more_than_the_goal_still_needs() {
let today = d("2026-11-07");
let s = ledger(
&[],
vec![
goal("g1", 300_000, None),
EventBody::GoalWaysSet { goal: "g1".into(), ways: vec![Way::Fixed { amount: Haler(200_000) }, Way::Fixed { amount: Haler(100) }].into_iter().take(1).collect() },
saved("g1", "s1", 250_000, "2026-10-01", None),
],
);
let g = &goals_month(&s, &analyse(&s, today), today).goals[0];
assert_eq!((g.parts[0].amount, g.parts[0].left, g.needed_per_month, g.months_left), (Haler(200_000), Haler(50_000), None, None));
let s = ledger(&[], vec![goal("g1", 300_000, Some("2026-09-30")), saved("g1", "s1", 300_000, "2026-10-01", None), EventBody::GoalClosed { goal: "g1".into(), on: d("2026-10-02") }]);
let g = &goals_month(&s, &analyse(&s, today), today).goals[0];
assert!(g.reached && g.parts.is_empty() && g.reach_month.is_none() && g.needed_per_month.is_none());
let s = ledger(&[], vec![goal("g1", 300_000, Some("2026-09-30"))]);
let g = &goals_month(&s, &analyse(&s, today), today).goals[0];
assert_eq!((g.months_left, g.needed_per_month), (Some(0), Some(Haler(300_000))), "its date has passed: all of it");
}
#[test]
fn where_the_money_could_come_from() {
let today = d("2026-11-07");
let mut payments = Vec::new();
for m in ["2026-07", "2026-08", "2026-09", "2026-10"] {
payments.push((format!("{m}-03"), -19_900, "NETFLIX.COM", "subscriptions"));
payments.push((format!("{m}-12"), -200_000, "Lokál", "eating-out"));
}
payments.push(("2026-10-20".into(), -150_000, "Lokál", "eating-out"));
let rows: Vec<(&str, i64, &str, &str)> = payments.iter().map(|(a, b, c, e)| (a.as_str(), *b, *c, *e)).collect();
let s = ledger(&rows, vec![]);
let sources = goals_month(&s, &analyse(&s, today), today).sources;
assert!(
sources.iter().any(|x| matches!(x, Source::Subscription { merchant, monthly, .. } if merchant.contains("NETFLIX") && *monthly == Haler(19_900))),
"{sources:?}"
);
assert!(
sources.iter().any(|x| matches!(x, Source::Category { category, last, average, extra } if category == "eating-out" && *last == Haler(350_000) && *average == Haler(200_000) && *extra == Haler(150_000))),
"{sources:?}"
);
// Decided "keep": not pointed at.
let key = analyse(&s, today).subscriptions[0].key.clone();
let s = ledger(&rows, vec![EventBody::SubscriptionDecided { subscription: key, decision: Decision::Keep, amount: Haler(19_900), on: d("2026-11-01") }]);
assert!(!goals_month(&s, &analyse(&s, today), today).sources.iter().any(|x| matches!(x, Source::Subscription { .. })));
}
#[test]
fn medals_for_goals_and_months_running_with_money_put_aside() {
let today = d("2026-11-07");
let s = ledger(
&[("2026-08-01", -10_000, "Albert", "groceries")],
vec![
goal("g1", 100_000, None),
saved("g1", "s1", 30_000, "2026-08-10", None),
saved("g1", "s2", 30_000, "2026-09-10", None),
saved("g1", "s3", 50_000, "2026-10-10", None),
saved("g1", "s4", -20_000, "2026-10-20", None),
],
);
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
let milestones: Vec<(u32, Date)> = r.medals.iter().filter_map(|e| match &e.medal { Medal::GoalMilestone { permille, .. } => Some((*permille, e.on)), _ => None }).collect();
assert_eq!(milestones, [(750, d("2026-10-10")), (1000, d("2026-10-10")), (500, d("2026-09-10")), (250, d("2026-08-10"))]);
assert!(r.medals.iter().any(|e| e.medal == Medal::SavingStreak { months: 3, until: d("2026-10-01") }));
assert_eq!((r.progress.saving_months, r.progress.saved_this_month), (3, false));
assert!(r.progress.goals.iter().any(|(id, _, level, next)| id == "g1" && *level == 900 && *next == 1000), "{:?}", r.progress.goals);
// Two months are not a streak; this month does not count until it is over.
let s = ledger(&[("2026-09-01", -10_000, "Albert", "groceries")], vec![goal("g1", 100_000, None), saved("g1", "s1", 1_000, "2026-09-10", None), saved("g1", "s2", 1_000, "2026-10-10", None), saved("g1", "s3", 1_000, "2026-11-02", None)]);
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
assert!(!r.medals.iter().any(|e| matches!(e.medal, Medal::SavingStreak { .. })));
assert_eq!((r.progress.saving_months, r.progress.saved_this_month), (2, true));
}
#[test]
fn medals_for_budgets_and_plans_kept_in_complete_months_only() {
let today = d("2026-11-07");
let s = ledger(
&[
("2026-07-05", -400_000, "Albert", "groceries"),
("2026-08-05", -900_000, "Albert", "groceries"),
("2026-09-05", -900_000, "Albert", "groceries"),
("2026-10-05", -1_000_000, "Albert", "groceries"),
("2026-11-05", -5_000_000, "Albert", "groceries"),
],
vec![EventBody::CategoryPlanned { category: "groceries".into(), amount: Haler(950_000), from: d("2026-09-01") }],
);
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
assert!(r.medals.iter().any(|e| e.medal == Medal::UnderBudget { budget: "home".into(), name: "Home".into(), months: 4, until: d("2026-10-01") }), "{:?}", r.medals);
let kept: Vec<Date> = r.medals.iter().filter_map(|e| match e.medal { Medal::PlansKept { month } => Some(month), _ => None }).collect();
assert_eq!(kept, [d("2026-09-01")], "October went over its plan; November is not over");
assert_eq!(r.progress.budgets, [("home".to_string(), "Home".to_string(), 4)]);
// A shared budget earns none: only your own payments are counted, its limit is everyone's.
let r = rewards(&s, &analyse(&s, today), &BTreeSet::from(["home".to_string()]), today);
assert!(!r.medals.iter().any(|e| matches!(e.medal, Medal::UnderBudget { .. })) && r.progress.budgets.is_empty());
}
#[test]
fn challenges_run_are_won_lost_or_given_up() {
let start = |id: &str, goal: ChallengeGoal, starts: &str, ends: &str| EventBody::ChallengeStarted { challenge: id.into(), goal, starts: d(starts), ends: d(ends) };
let s = ledger(
&[("2026-10-10", -100_000, "Lokál", "eating-out"), ("2026-10-20", -50_000, "Kino", "fun"), ("2026-11-03", -100_000, "Lokál", "eating-out")],
vec![
goal("g1", 1_000_000, None),
start("c-under", ChallengeGoal::SpendUnder { category: "eating-out".into(), amount: Haler(300_000) }, "2026-11-01", "2026-11-30"),
start("c-oct", ChallengeGoal::SpendUnder { category: "eating-out".into(), amount: Haler(200_000) }, "2026-10-01", "2026-10-31"),
start("c-none", ChallengeGoal::NoSpend { category: "fun".into() }, "2026-10-01", "2026-10-31"),
start("c-save", ChallengeGoal::Save { goal: "g1".into(), amount: Haler(200_000) }, "2026-11-01", "2026-11-30"),
saved("g1", "s1", 250_000, "2026-11-04", None),
start("c-quit", ChallengeGoal::NoSpend { category: "travel".into() }, "2026-11-01", "2026-11-30"),
EventBody::ChallengeAbandoned { challenge: "c-quit".into(), on: d("2026-11-05") },
],
);
let today = d("2026-11-07");
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
let by = |id: &str| r.challenges.iter().find(|c| c.id == id).unwrap();
assert_eq!((by("c-under").outcome, by("c-under").so_far, by("c-under").permille, by("c-under").days_left), (Outcome::Running, Haler(100_000), 666, 23));
assert_eq!((by("c-oct").outcome, by("c-oct").permille), (Outcome::Won, 500));
assert_eq!((by("c-none").outcome, by("c-none").permille), (Outcome::Lost, 0));
assert_eq!((by("c-save").outcome, by("c-save").permille), (Outcome::Won, 1000), "won the day it was reached");
assert_eq!(by("c-quit").outcome, Outcome::Abandoned);
let won: Vec<(&str, Date)> = r.medals.iter().filter_map(|e| match &e.medal { Medal::ChallengeWon { challenge, .. } => Some((challenge.as_str(), e.on)), _ => None }).collect();
assert_eq!(won, [("c-save", d("2026-11-04")), ("c-oct", d("2026-10-31"))]);
assert_eq!(r.challenges[0].outcome, Outcome::Running, "running first");
// Over the limit before the end: lost at once.
let s2 = ledger(&[("2026-11-03", -400_000, "Lokál", "eating-out")], vec![start("c", ChallengeGoal::SpendUnder { category: "eating-out".into(), amount: Haler(300_000) }, "2026-11-01", "2026-11-30")]);
assert_eq!(rewards(&s2, &analyse(&s2, today), &BTreeSet::new(), today).challenges[0].outcome, Outcome::Lost);
}
#[test]
fn a_quarter_with_every_invoice_paid_by_its_due_date() {
use fiscus_ledger::invoice::{Invoice, InvoiceLine, Language, Party, Supplier};
let party = |name: &str, ico: &str| Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some(ico.into()), dic: None };
let invoice = |id: &str, number: &str, issued: &str| Invoice {
id: id.into(),
number: number.into(),
issued: d(issued),
due: d(issued).add_days(14),
taxable: None,
customer: party("Odběratel s.r.o.", "45244782"),
lines: vec![InvoiceLine { text: "Work".into(), quantity: 1000, unit: "h".into(), unit_price: Haler(100_000), vat: None }],
budget: None,
language: Language::Cs,
};
let paid = |id: &str, on: &str| EventBody::InvoicePaid { invoice: id.into(), payment: None, on: d(on) };
let s = ledger(
&[],
vec![
EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } },
// Q2: both paid in time. Q3: one paid late.
EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-04-02") },
EventBody::InvoiceIssued { invoice: invoice("i2", "20260002", "2026-05-10") },
EventBody::InvoiceIssued { invoice: invoice("i3", "20260003", "2026-07-01") },
EventBody::InvoiceIssued { invoice: invoice("i4", "20260004", "2026-10-20") },
paid("i1", "2026-04-10"),
paid("i2", "2026-05-24"),
paid("i3", "2026-07-30"),
paid("i4", "2026-10-25"),
],
);
let today = d("2026-11-07");
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
let quarters: Vec<(i32, u32)> = r.medals.iter().filter_map(|e| match e.medal { Medal::InvoicesOnTime { year, quarter } => Some((year, quarter)), _ => None }).collect();
assert_eq!(quarters, [(2026, 2)], "Q3 had one paid late; Q4 is not over");
}
@@ -178,6 +178,10 @@ fn the_cancel_kit() {
let kit = cancel_kit(wedos); let kit = cancel_kit(wedos);
assert_eq!(kit.url, None, "an unknown provider gets the email only"); assert_eq!(kit.url, None, "an unknown provider gets the email only");
assert!(kit.mailto().starts_with("mailto:?subject=")); assert!(kit.mailto().starts_with("mailto:?subject="));
let kit = fiscus_insight::cancel::cancel_kit_in(netflix, fiscus_ledger::invoice::Language::Cs);
assert_eq!(kit.email_subject, "Zrušení předplatného Netflix");
assert!(kit.email_body.starts_with("Dobrý den,") && kit.email_body.contains("259,00 Kč") && kit.email_body.contains("měsíční"), "{}", kit.email_body);
assert_eq!(kit.url.as_deref(), Some("https://www.netflix.com/cancelplan"), "the same page in either language");
} }
#[test] #[test]
+22
View File
@@ -1,6 +1,7 @@
//! The event log. Append only: a correction is a new event, nothing is ever edited or removed. //! The event log. Append only: a correction is a new event, nothing is ever edited or removed.
use crate::date::{Date, Timestamp}; use crate::date::{Date, Timestamp};
use crate::goal::{ChallengeGoal, ChallengeId, Colour, GoalId, Way, WayKind};
use crate::import::StatementLine; use crate::import::StatementLine;
use crate::invoice::{Invoice, InvoiceId, Supplier}; use crate::invoice::{Invoice, InvoiceId, Supplier};
use crate::money::Haler; use crate::money::Haler;
@@ -165,4 +166,25 @@ pub enum EventBody {
/// A category of your own (an id as [`crate::categories::is_valid`]) and the name the app shows for it. /// A category of your own (an id as [`crate::categories::is_valid`]) and the name the app shows for it.
#[serde(rename = "category.created")] #[serde(rename = "category.created")]
CategoryCreated { category: Category, label: String }, CategoryCreated { category: Category, label: String },
/// A savings goal (see [`crate::goal`]): a name, a target, an optional date to reach it by, the tank's colour.
#[serde(rename = "goal.created")]
GoalCreated { goal: GoalId, name: String, target: Haler, by: Option<Date>, colour: Colour },
/// A goal's name, target, date or colour changed; the latest counts.
#[serde(rename = "goal.changed")]
GoalChanged { goal: GoalId, name: String, target: Haler, by: Option<Date>, colour: Colour },
/// How a goal is saved for: up to one way of each kind. Replaces the goal's earlier ways.
#[serde(rename = "goal.ways_set")]
GoalWaysSet { goal: GoalId, ways: Vec<Way> },
/// Money put aside for a goal (positive) or taken out (negative), by one of its ways or by hand (`None`).
#[serde(rename = "goal.saved")]
GoalSaved { goal: GoalId, saving: String, amount: Haler, on: Date, way: Option<WayKind> },
/// Reached or given up: no more saving into it. Its history stays.
#[serde(rename = "goal.closed")]
GoalClosed { goal: GoalId, on: Date },
/// A challenge you set yourself, from `starts` to `ends` (both included, at most 92 days).
#[serde(rename = "challenge.started")]
ChallengeStarted { challenge: ChallengeId, goal: ChallengeGoal, starts: Date, ends: Date },
/// Given up; a challenge is given up once.
#[serde(rename = "challenge.abandoned")]
ChallengeAbandoned { challenge: ChallengeId, on: Date },
} }
+136
View File
@@ -0,0 +1,136 @@
//! Savings goals and challenges: what you mean to put aside and how, and the challenges you set yourself. Fiscus
//! never moves money: a goal holds what you said you put aside (`goal.saved`), so it is never full unless you
//! filled it. Personal log only, like plans: a shared budget's members never see them.
use crate::event::Category;
use crate::money::Haler;
use crate::date::Date;
use serde::{Deserialize, Serialize};
pub type GoalId = String;
pub type ChallengeId = String;
/// At most this many goals open at once.
pub const MAX_OPEN_GOALS: usize = 20;
/// At most this many challenges running (not ended, not given up) at once.
pub const MAX_OPEN_CHALLENGES: usize = 20;
/// A goal's target, a fixed monthly amount, a challenge's amount: 1 Kč to 100 000 000 Kč.
pub const MIN_AMOUNT: Haler = Haler(100);
pub const MAX_AMOUNT: Haler = Haler(10_000_000_000);
/// A challenge lasts at most 92 days, its first and last day included.
pub const MAX_CHALLENGE_DAYS: i32 = 92;
/// Round-ups go to the next 10, 50 or 100 Kč.
pub const ROUND_UP_TO: [Haler; 3] = [Haler(1_000), Haler(5_000), Haler(10_000)];
/// The tank's colour, from the app's palette.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Colour {
Teal,
Amber,
Coral,
Blue,
Violet,
Green,
}
/// How a goal's monthly saving is found. A goal has at most one of each kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Way {
/// The same amount every month.
Fixed { amount: Haler },
/// Each card payment of the month rounded up to the next `to` (10, 50 or 100 Kč); the differences add up.
RoundUp { to: Haler },
/// This share (in thousandths) of what last month's category plans did not use.
Leftover { permille: u16 },
/// This share (in thousandths) of last month's money in.
Income { permille: u16 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WayKind {
Fixed,
RoundUp,
Leftover,
Income,
}
impl Way {
pub fn kind(&self) -> WayKind {
match self {
Way::Fixed { .. } => WayKind::Fixed,
Way::RoundUp { .. } => WayKind::RoundUp,
Way::Leftover { .. } => WayKind::Leftover,
Way::Income { .. } => WayKind::Income,
}
}
/// The share of the month's leftover or income this way takes, in thousandths (0 for the others).
pub fn share_of(&self, kind: WayKind) -> u32 {
match (self, kind) {
(Way::Leftover { permille }, WayKind::Leftover) | (Way::Income { permille }, WayKind::Income) => u32::from(*permille),
_ => 0,
}
}
}
/// What a challenge asks.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ChallengeGoal {
/// Spend less than `amount` in `category` from the first day to the last.
SpendUnder { category: Category, amount: Haler },
/// Spend nothing in `category`.
NoSpend { category: Category },
/// Decide to cancel this subscription (its key) and not be charged for it again before the end.
Cancel { subscription: String },
/// Put `amount` aside for this goal.
Save { goal: GoalId, amount: Haler },
}
/// One amount put aside (positive) or taken out (negative).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Saving {
pub id: String,
pub amount: Haler,
pub on: Date,
pub way: Option<WayKind>,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoalRecord {
pub id: GoalId,
pub name: String,
pub target: Haler,
pub by: Option<Date>,
pub colour: Colour,
pub ways: Vec<Way>,
/// In log order.
pub savings: Vec<Saving>,
pub closed: Option<Date>,
pub seq: u64,
}
impl GoalRecord {
/// Everything put aside less everything taken out; never negative (the ledger refuses that).
pub fn saved(&self) -> Haler {
Haler(self.savings.iter().fold(0i64, |s, x| s.saturating_add(x.amount.0)))
}
pub fn is_open(&self) -> bool {
self.closed.is_none()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChallengeRecord {
pub id: ChallengeId,
pub goal: ChallengeGoal,
pub starts: Date,
pub ends: Date,
pub abandoned: Option<Date>,
pub seq: u64,
}
+1
View File
@@ -5,6 +5,7 @@
pub mod categories; pub mod categories;
pub mod date; pub mod date;
pub mod event; pub mod event;
pub mod goal;
pub mod import; pub mod import;
pub mod invoice; pub mod invoice;
pub mod matching; pub mod matching;
+1 -1
View File
@@ -6,7 +6,7 @@ pub fn merchant_key(raw: &str) -> String {
let folded: String = raw.chars().flat_map(fold).collect::<String>().to_lowercase(); let folded: String = raw.chars().flat_map(fold).collect::<String>().to_lowercase();
// A processor's prefix before `*`: "paypal *spotify", "sumup *kavarna", "sq *bistro". // A processor's prefix before `*`: "paypal *spotify", "sumup *kavarna", "sq *bistro".
let rest = match folded.split_once('*') { let rest = match folded.split_once('*') {
Some((head, tail)) if !tail.trim().is_empty() && head.trim().split_whitespace().count() <= 2 => tail, Some((head, tail)) if !tail.trim().is_empty() && head.split_whitespace().count() <= 2 => tail,
_ => folded.as_str(), _ => folded.as_str(),
}; };
let cleaned: String = rest.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' }).collect(); let cleaned: String = rest.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' }).collect();
+1 -1
View File
@@ -49,7 +49,7 @@ impl Haler {
let whole = (abs / 100).to_string(); let whole = (abs / 100).to_string();
let mut grouped = String::with_capacity(whole.len() + whole.len() / 3); let mut grouped = String::with_capacity(whole.len() + whole.len() / 3);
for (i, c) in whole.chars().enumerate() { for (i, c) in whole.chars().enumerate() {
if i > 0 && (whole.len() - i) % 3 == 0 { if i > 0 && (whole.len() - i).is_multiple_of(3) {
grouped.push(' '); grouped.push(' ');
} }
grouped.push(c); grouped.push(c);
+141
View File
@@ -4,6 +4,7 @@
use crate::categories; use crate::categories;
use crate::date::Date; use crate::date::Date;
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId}; use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
use crate::goal::{self, ChallengeGoal, ChallengeId, ChallengeRecord, GoalId, GoalRecord, Saving, Way, WayKind};
use crate::import::StatementLine; use crate::import::StatementLine;
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals}; use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
use crate::merchant::merchant_key; use crate::merchant::merchant_key;
@@ -227,6 +228,12 @@ pub struct State {
pub category_plans: BTreeMap<Category, Vec<PlanRecord>>, pub category_plans: BTreeMap<Category, Vec<PlanRecord>>,
/// Your own categories: id → the name shown (`category.created`). /// Your own categories: id → the name shown (`category.created`).
pub custom_categories: BTreeMap<Category, String>, pub custom_categories: BTreeMap<Category, String>,
/// Savings goals by id (`goal.*`).
pub goals: BTreeMap<GoalId, GoalRecord>,
/// Every `goal.saved` id, so none is counted twice.
pub saving_ids: BTreeSet<String>,
/// Challenges by id (`challenge.*`).
pub challenges: BTreeMap<ChallengeId, ChallengeRecord>,
pub rejected: Vec<Rejection>, pub rejected: Vec<Rejection>,
} }
@@ -280,6 +287,17 @@ fn name_ok(s: &str, max: usize) -> bool {
!s.trim().is_empty() && s.chars().count() <= max && text_ok(s) !s.trim().is_empty() && s.chars().count() <= max && text_ok(s)
} }
/// A goal's name and target, for `goal.created` and `goal.changed`.
fn goal_fields(name: &str, target: Haler) -> Result<(), &'static str> {
if !name_ok(name, 60) || name.trim() != name {
return Err("a goal name must be 1-60 characters");
}
if target < goal::MIN_AMOUNT || target > goal::MAX_AMOUNT {
return Err("a goal target is 1-100 000 000 CZK");
}
Ok(())
}
fn id_ok(s: &str) -> bool { fn id_ok(s: &str) -> bool {
!s.is_empty() && s.len() <= 100 && text_ok(s) !s.is_empty() && s.len() <= 100 && text_ok(s)
} }
@@ -770,6 +788,129 @@ impl State {
return Err("a subscription name appears twice"); return Err("a subscription name appears twice");
} }
} }
EventBody::GoalCreated { goal, name, target, by, colour } => {
if !id_ok(goal) || self.goals.contains_key(goal) {
return Err("a goal with this id exists");
}
goal_fields(name, *target)?;
if self.goals.values().filter(|g| g.is_open()).count() >= goal::MAX_OPEN_GOALS {
return Err("at most 20 goals are open at once");
}
self.goals.insert(
goal.clone(),
GoalRecord { id: goal.clone(), name: name.clone(), target: *target, by: *by, colour: *colour, ways: Vec::new(), savings: Vec::new(), closed: None, seq },
);
}
EventBody::GoalChanged { goal, name, target, by, colour } => {
goal_fields(name, *target)?;
let g = self.goals.get_mut(goal).ok_or("no such goal")?;
if !g.is_open() {
return Err("the goal is closed");
}
(g.name, g.target, g.by, g.colour) = (name.clone(), *target, *by, *colour);
}
EventBody::GoalWaysSet { goal, ways } => {
let g = self.goals.get(goal).ok_or("no such goal")?;
if !g.is_open() {
return Err("the goal is closed");
}
if ways.iter().map(Way::kind).collect::<BTreeSet<_>>().len() != ways.len() {
return Err("a goal has at most one way of each kind");
}
for w in ways {
match w {
Way::Fixed { amount } if *amount < goal::MIN_AMOUNT || *amount > goal::MAX_AMOUNT => return Err("a fixed amount is 1-100 000 000 CZK"),
Way::RoundUp { to } if !goal::ROUND_UP_TO.contains(to) => return Err("round-ups go to 10, 50 or 100 CZK"),
Way::Leftover { permille } | Way::Income { permille } if *permille == 0 || *permille > 1000 => return Err("a share is 1-1000 thousandths"),
_ => {}
}
}
for kind in [WayKind::Leftover, WayKind::Income] {
let others: u32 = self.goals.values().filter(|o| o.is_open() && &o.id != goal).flat_map(|o| o.ways.iter()).map(|w| w.share_of(kind)).sum();
let mine: u32 = ways.iter().map(|w| w.share_of(kind)).sum();
if others + mine > 1000 {
return Err("the shares of one way across the goals add up to more than all of it");
}
}
self.goals.get_mut(goal).expect("checked").ways = ways.clone();
}
EventBody::GoalSaved { goal, saving, amount, on, way } => {
if !id_ok(saving) || self.saving_ids.contains(saving) {
return Err("a saving with this id exists");
}
let g = self.goals.get(goal).ok_or("no such goal")?;
if !g.is_open() {
return Err("the goal is closed");
}
if amount.0 == 0 || amount.0.unsigned_abs() > goal::MAX_AMOUNT.0 as u64 {
return Err("an amount saved is 0,01-100 000 000 CZK either way");
}
if g.saved().checked_add(*amount).map_err(|_| "the goal would not fit")?.0 < 0 {
return Err("more than the goal holds");
}
if let Some(k) = way {
if !g.ways.iter().any(|w| w.kind() == *k) {
return Err("the goal is not saved for that way");
}
}
self.saving_ids.insert(saving.clone());
self.goals.get_mut(goal).expect("checked").savings.push(Saving { id: saving.clone(), amount: *amount, on: *on, way: *way, seq });
}
EventBody::GoalClosed { goal, on } => {
let g = self.goals.get_mut(goal).ok_or("no such goal")?;
if !g.is_open() {
return Err("the goal is closed");
}
g.closed = Some(*on);
}
EventBody::ChallengeStarted { challenge, goal, starts, ends } => {
if !id_ok(challenge) || self.challenges.contains_key(challenge) {
return Err("a challenge with this id exists");
}
let days = starts.days_until(*ends);
if !(0..goal::MAX_CHALLENGE_DAYS as i64).contains(&(days as i64)) {
return Err("a challenge lasts 1-92 days");
}
match goal {
ChallengeGoal::SpendUnder { category, amount } => {
if !self.category_known(category) || categories::NOT_PLANNABLE.contains(&category.as_str()) {
return Err("not a category you spend in");
}
if *amount < goal::MIN_AMOUNT || *amount > goal::MAX_AMOUNT {
return Err("the amount of a challenge is 1-100 000 000 CZK");
}
}
ChallengeGoal::NoSpend { category } => {
if !self.category_known(category) || categories::NOT_PLANNABLE.contains(&category.as_str()) {
return Err("not a category you spend in");
}
}
ChallengeGoal::Cancel { subscription } => {
if subscription.is_empty() || subscription.len() > 100 || !text_ok(subscription) {
return Err("not a subscription key");
}
}
ChallengeGoal::Save { goal: g, amount } => {
if !self.goals.get(g).is_some_and(GoalRecord::is_open) {
return Err("no such open goal");
}
if *amount < goal::MIN_AMOUNT || *amount > goal::MAX_AMOUNT {
return Err("the amount of a challenge is 1-100 000 000 CZK");
}
}
}
if self.challenges.values().filter(|c| c.abandoned.is_none() && c.ends >= *starts).count() >= goal::MAX_OPEN_CHALLENGES {
return Err("at most 20 challenges run at once");
}
self.challenges.insert(challenge.clone(), ChallengeRecord { id: challenge.clone(), goal: goal.clone(), starts: *starts, ends: *ends, abandoned: None, seq });
}
EventBody::ChallengeAbandoned { challenge, on } => {
let c = self.challenges.get_mut(challenge).ok_or("no such challenge")?;
if c.abandoned.is_some() {
return Err("already given up");
}
c.abandoned = Some(*on);
}
} }
Ok(()) Ok(())
} }
+160
View File
@@ -0,0 +1,160 @@
//! 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}");
}
}
+105
View File
@@ -0,0 +1,105 @@
# 05: Savings goals, ways to save, challenges and medals (v0.6.0)
This works like the rest of the core: `today` is a parameter, money is in haléře, and every level is in whole
thousandths. **Fiscus never moves money.** A goal holds only what you said you put aside, so it is full only
when you filled it. Goals and challenges are in your personal log. They are never shared: the sharing boundary
(`share.rs`) builds only `payment.shared`.
## Goals (`fiscus-ledger::goal`)
| Event | What |
|:--|:--|
| `goal.created { goal, name, target, by?, colour }` | a goal |
| `goal.changed { goal, name, target, by?, colour }` | its new name, target, date or colour; the latest counts |
| `goal.ways_set { goal, ways }` | how it is saved for; replaces its earlier ways |
| `goal.saved { goal, saving, amount, on, way? }` | put aside (positive) or taken out (negative), by one of its ways or by hand |
| `goal.closed { goal, on }` | reached or given up; no more saving into it, the history stays |
**What a goal accepts:**
- a name of 1–60 characters, with no spaces around it and no control characters;
- a target of 1 Kč to 100 000 000 Kč;
- at most 20 open goals;
- a saving id used once, with an amount that is not zero, and never more taken out than the goal holds;
- savings only into an open goal;
- a saving made by a way only if the goal is saved for that way.
**Ways.** A goal has at most one way of each kind:
| Way | This month it comes to |
|:--|:--|
| `fixed { amount }` | the amount (1 Kč–100 000 000 Kč) |
| `round_up { to }` | each spending payment of the month rounded up to the next `to` (10, 50 or 100 Kč); a payment already a multiple adds nothing |
| `leftover { permille }` | that share of what last month's category plans did not use (per planned category, the plan less what was spent, never below 0) |
| `income { permille }` | that share of last month's money in (not transfers) |
A share is 1–1000 thousandths. The open goals' shares of `leftover`, and separately of `income`, add up to at
most 1000: together they can never take more than all of it. Closing a goal gives its shares back.
## A goal this month (`fiscus-insight::goals`)
`goals_month(state, insight, today)` returns the open goals in the order they were made, then the closed ones,
the latest closed first. Each goal has:
- **saved**, **target**, **permille** (the tank's level, at most 1000) and **reached**;
- **months_left** from this month to the month of `by`, both included, and **needed_per_month**: what is still
needed, divided by those months and rounded up to whole crowns. Once the date has passed, all of what is
still needed. Neither is set without a date, or once the goal is reached;
- **pace**: put aside per month over the last three complete months, from the month of the first saving on;
**reach_month**: the month it gets there at that pace;
- **parts**, one per way. Each part has:
- what the way comes to this month;
- what was already put aside by it this month;
- what is **left**. Together the parts never ask for more than the goal still needs: the parts take it in the
goal's order of ways.
The month also has the leftover and the income that the shares are of, how much of each is given to goals, and
**sources**, which point at money without changing anything:
- **subscriptions** still charging that you have not decided to keep, with their cost a month (a yearly one
divided by 12, rounded up). The 5 costliest;
- **categories** that cost more last month than their average of the three months before, by at least 10 % and
200 Kč. The 3 largest differences.
## Challenges
| Event | What |
|:--|:--|
| `challenge.started { challenge, goal, starts, ends }` | 1–92 days, both ends included; at most 20 running |
| `challenge.abandoned { challenge, on }` | given up, once |
The `goal` of a challenge is one of these:
- `spend_under { category, amount }`: a category you spend in (not income, transfers or uncategorised), 1 Kč or
more;
- `no_spend { category }`;
- `cancel { subscription }`: decide to cancel it in the window, and not be charged for it after the decision;
- `save { goal, amount }`: put this much aside for an open goal in the window.
## Rewards (`fiscus-insight::rewards`)
`rewards(state, insight, shared_budgets, today)` computes the medals and the challenges from the ledger.
Nothing is stored. A medal comes from a **complete** period only:
| Medal | Earned |
|:--|:--|
| `under_budget` | a budget under its (latest) limit 3+ complete months running; one medal per run. A shared budget earns none: only your own payments are counted, and its limit is everyone's |
| `plans_kept` | a complete month with at least one plan, every plan kept |
| `cancelled` | decided "cancel" and not charged since, past the day it would have charged |
| `challenge_won` | `spend_under`, `no_spend` and `cancel` on their last day; `save` on the day it was reached |
| `invoices_on_time` | a finished quarter in which every invoice due was paid by its due date |
| `goal_milestone` | a goal at ¼, ½, ¾ and all of its target, on the day of the saving that got it there |
| `saving_streak` | money put aside (more in than out across the goals) in 3+ complete months running |
The outcome of a challenge:
- **Lost** as soon as it cannot be won: spending over the limit, any spending in a `no_spend` category, or a
charge after the cancel decision;
- **Abandoned** when given up, except a `save` challenge already reached, which stays won.
Its tank:
- `spend_under`: what is left of the limit;
- `no_spend`: full until anything is spent;
- `cancel`: full once you decide to cancel and nothing has charged since;
- `save`: what is saved of the amount.
**Progress** shows how far the medals not yet earned are:
- months running with money put aside, and whether anything was put aside this month;
- each budget's months running under its limit;
- each open goal's level and its next milestone.
## The cancel kit in Czech
`cancel_kit_in(subscription, language)` writes the email in Czech or English. `cancel_kit` stays English.