From 6572f31b1db1cf0d55af1887dbb2fa40acc8a72e Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 3 Nov 2026 18:52:36 +0100 Subject: [PATCH] =?UTF-8?q?[ledger]=20Core:=20hal=C3=A9=C5=99e,=20dates,?= =?UTF-8?q?=20the=20event=20log=20and=20apply(),=20merchant=20keys=20and?= =?UTF-8?q?=20rules,=20one-to-one=20matching,=20import=20planning?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/fiscus-ledger/Cargo.toml | 15 + crates/fiscus-ledger/src/categories.rs | 32 ++ crates/fiscus-ledger/src/date.rs | 192 +++++++++++ crates/fiscus-ledger/src/event.rs | 76 +++++ crates/fiscus-ledger/src/import.rs | 109 ++++++ crates/fiscus-ledger/src/lib.rs | 16 + crates/fiscus-ledger/src/matching.rs | 114 +++++++ crates/fiscus-ledger/src/merchant.rs | 107 ++++++ crates/fiscus-ledger/src/money.rs | 143 ++++++++ crates/fiscus-ledger/src/state.rs | 439 +++++++++++++++++++++++++ crates/fiscus-ledger/tests/matching.rs | 222 +++++++++++++ crates/fiscus-ledger/tests/money.rs | 97 ++++++ crates/fiscus-ledger/tests/no_float.rs | 40 +++ crates/fiscus-ledger/tests/replay.rs | 129 ++++++++ 14 files changed, 1731 insertions(+) create mode 100644 crates/fiscus-ledger/Cargo.toml create mode 100644 crates/fiscus-ledger/src/categories.rs create mode 100644 crates/fiscus-ledger/src/date.rs create mode 100644 crates/fiscus-ledger/src/event.rs create mode 100644 crates/fiscus-ledger/src/import.rs create mode 100644 crates/fiscus-ledger/src/lib.rs create mode 100644 crates/fiscus-ledger/src/matching.rs create mode 100644 crates/fiscus-ledger/src/merchant.rs create mode 100644 crates/fiscus-ledger/src/money.rs create mode 100644 crates/fiscus-ledger/src/state.rs create mode 100644 crates/fiscus-ledger/tests/matching.rs create mode 100644 crates/fiscus-ledger/tests/money.rs create mode 100644 crates/fiscus-ledger/tests/no_float.rs create mode 100644 crates/fiscus-ledger/tests/replay.rs diff --git a/crates/fiscus-ledger/Cargo.toml b/crates/fiscus-ledger/Cargo.toml new file mode 100644 index 0000000..31a8a7a --- /dev/null +++ b/crates/fiscus-ledger/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "fiscus-ledger" +description = "Fiscus Domi: money, dates, the event log and its state, merchant rules, matching" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true + +[dev-dependencies] +proptest.workspace = true diff --git a/crates/fiscus-ledger/src/categories.rs b/crates/fiscus-ledger/src/categories.rs new file mode 100644 index 0000000..f1f167e --- /dev/null +++ b/crates/fiscus-ledger/src/categories.rs @@ -0,0 +1,32 @@ +//! The categories the app offers. A category is an id; the label is what the app shows. + +pub const UNCATEGORISED: &str = "uncategorised"; + +/// `(id, label)` in the order the app lists them. +pub const DEFAULT: &[(&str, &str)] = &[ + ("groceries", "Groceries"), + ("eating-out", "Eating out"), + ("transport", "Transport"), + ("housing", "Housing"), + ("utilities", "Utilities"), + ("subscriptions", "Subscriptions"), + ("shopping", "Shopping"), + ("health", "Health"), + ("kids", "Kids"), + ("fun", "Fun"), + ("travel", "Travel"), + ("gifts", "Gifts"), + ("income", "Income"), + ("transfers", "Transfers"), + ("other", "Other"), + (UNCATEGORISED, "Uncategorised"), +]; + +/// A category id is lowercase ASCII letters, digits and `-`, 1–40 characters. +pub fn is_valid(id: &str) -> bool { + (1..=40).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +pub fn label(id: &str) -> &str { + DEFAULT.iter().find(|(i, _)| *i == id).map(|(_, l)| *l).unwrap_or(id) +} diff --git a/crates/fiscus-ledger/src/date.rs b/crates/fiscus-ledger/src/date.rs new file mode 100644 index 0000000..f9b240b --- /dev/null +++ b/crates/fiscus-ledger/src/date.rs @@ -0,0 +1,192 @@ +//! Civil dates as days since 1970-01-01 (proleptic Gregorian), and timestamps the app hands in. +//! There is no clock here: "today" is always a parameter. + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::fmt; +use std::str::FromStr; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Date(i32); + +/// Milliseconds since the Unix epoch, as given by the app. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct Timestamp(pub i64); + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("not a date (expected YYYY-MM-DD)")] +pub struct DateError; + +const MIN_YEAR: i32 = 1900; +const MAX_YEAR: i32 = 2200; + +pub fn is_leap(y: i32) -> bool { + (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 +} + +pub fn days_in_month(y: i32, m: u32) -> u32 { + match m { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if is_leap(y) => 29, + 2 => 28, + _ => 0, + } +} + +impl Date { + /// `None` for an impossible date or a year outside 1900–2200. + pub fn from_ymd(y: i32, m: u32, d: u32) -> Option { + if !(MIN_YEAR..=MAX_YEAR).contains(&y) || !(1..=12).contains(&m) || d == 0 || d > days_in_month(y, m) { + return None; + } + // Howard Hinnant's days_from_civil. + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = (m as i32 + 9) % 12; + let doy = (153 * mp + 2) / 5 + d as i32 - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + Some(Date(era * 146_097 + doe - 719_468)) + } + + pub fn from_days(days: i32) -> Date { + Date(days) + } + + pub fn days(self) -> i32 { + self.0 + } + + pub fn ymd(self) -> (i32, u32, u32) { + let z = self.0 + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (if m <= 2 { y + 1 } else { y }, m, d) + } + + pub fn add_days(self, n: i32) -> Date { + Date(self.0 + n) + } + + /// Days from `self` to `other` (positive when `other` is later). + pub fn days_until(self, other: Date) -> i32 { + other.0 - self.0 + } + + /// The same day `n` months later, clamped to the month's last day (31 Jan + 1 = 28/29 Feb). + pub fn add_months(self, n: i32) -> Date { + let (y, m, d) = self.ymd(); + let idx = y * 12 + (m as i32 - 1) + n; + let (ny, nm) = (idx.div_euclid(12), (idx.rem_euclid(12) + 1) as u32); + let nd = d.min(days_in_month(ny, nm)); + Date::from_ymd(ny, nm, nd).unwrap_or(self) + } + + pub fn add_years(self, n: i32) -> Date { + self.add_months(n * 12) + } + + pub fn month_start(self) -> Date { + let (y, m, _) = self.ymd(); + Date::from_ymd(y, m, 1).unwrap_or(self) + } + + pub fn month_end(self) -> Date { + let (y, m, _) = self.ymd(); + Date::from_ymd(y, m, days_in_month(y, m)).unwrap_or(self) + } + + /// `(year, month)` — the key of a monthly budget period. + pub fn month(self) -> (i32, u32) { + let (y, m, _) = self.ymd(); + (y, m) + } + + /// The civil date of a timestamp in UTC. The app passes local "today" as a `Date`; this is for the log. + pub fn from_timestamp_utc(t: Timestamp) -> Date { + Date(t.0.div_euclid(86_400_000) as i32) + } +} + +impl fmt::Display for Date { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (y, m, d) = self.ymd(); + write!(f, "{y:04}-{m:02}-{d:02}") + } +} + +impl FromStr for Date { + type Err = DateError; + + fn from_str(s: &str) -> Result { + let b = s.as_bytes(); + if b.len() != 10 || b[4] != b'-' || b[7] != b'-' { + return Err(DateError); + } + let num = |r: std::ops::Range| -> Result { + let part = &s[r]; + if !part.bytes().all(|c| c.is_ascii_digit()) { + return Err(DateError); + } + part.parse().map_err(|_| DateError) + }; + Date::from_ymd(num(0..4)? as i32, num(5..7)?, num(8..10)?).ok_or(DateError) + } +} + +impl Serialize for Date { + fn serialize(&self, s: S) -> Result { + s.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for Date { + fn deserialize>(d: D) -> Result { + let s = String::deserialize(d)?; + s.parse().map_err(serde::de::Error::custom) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_every_day_for_three_centuries() { + let start = Date::from_ymd(1900, 1, 1).unwrap(); + let end = Date::from_ymd(2200, 12, 31).unwrap(); + let mut day = start; + while day <= end { + let (y, m, d) = day.ymd(); + assert_eq!(Date::from_ymd(y, m, d), Some(day)); + assert_eq!(day.to_string().parse::(), Ok(day)); + day = day.add_days(1); + } + assert_eq!(Date::from_ymd(1970, 1, 1).unwrap().days(), 0); + } + + #[test] + fn months_clamp() { + let d = |s: &str| s.parse::().unwrap(); + assert_eq!(d("2026-01-31").add_months(1), d("2026-02-28")); + assert_eq!(d("2028-01-31").add_months(1), d("2028-02-29")); + assert_eq!(d("2026-12-15").add_months(1), d("2027-01-15")); + assert_eq!(d("2026-03-31").add_months(-1), d("2026-02-28")); + assert_eq!(d("2028-02-29").add_years(1), d("2029-02-28")); + assert_eq!(d("2026-11-03").month_end(), d("2026-11-30")); + } + + #[test] + fn refuses_what_is_not_a_date() { + for bad in ["2026-02-29", "2026-13-01", "2026-00-10", "26-01-01", "2026-1-01", "2026-01-01T", "+026-01-01", "1899-12-31"] { + assert!(bad.parse::().is_err(), "{bad}"); + } + } +} diff --git a/crates/fiscus-ledger/src/event.rs b/crates/fiscus-ledger/src/event.rs new file mode 100644 index 0000000..40184a2 --- /dev/null +++ b/crates/fiscus-ledger/src/event.rs @@ -0,0 +1,76 @@ +//! The event log. Append only: a correction is a new event, nothing is ever edited or removed. + +use crate::date::{Date, Timestamp}; +use crate::import::StatementLine; +use crate::money::Haler; +use serde::{Deserialize, Serialize}; + +/// Ids are opaque strings the app generates (random, unguessable); the core never makes one up. +pub type EventId = String; +pub type PaymentId = String; +pub type BudgetId = String; +pub type RuleId = String; +/// A category id, e.g. `groceries` (see [`crate::categories`]). +pub type Category = String; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Event { + pub id: EventId, + /// When the event was written (the app's clock), for display and sync; never for ordering. + pub at: Timestamp, + #[serde(flatten)] + pub body: EventBody, +} + +impl Event { + pub fn new(id: impl Into, at: Timestamp, body: EventBody) -> Event { + Event { id: id.into(), at, body } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Decision { + Keep, + Cancel, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum EventBody { + /// A phone saw a card payment (○). + #[serde(rename = "payment.captured")] + PaymentCaptured { payment: PaymentId, amount: Haler, date: Date, merchant: String, card: Option }, + /// One statement line (●). `line_key` identifies the line across imports. + #[serde(rename = "payment.imported")] + PaymentImported { payment: PaymentId, line: StatementLine, line_key: String }, + /// Added by hand (◆). The merchant may be empty (cash, "groceries"). + #[serde(rename = "payment.added")] + PaymentAdded { + payment: PaymentId, + amount: Haler, + date: Date, + merchant: String, + category: Option, + note: Option, + }, + /// A captured or hand-added payment and the statement line that confirms it are one payment. + #[serde(rename = "payment.confirmed")] + PaymentConfirmed { payment: PaymentId, line: PaymentId }, + #[serde(rename = "payment.categorised")] + PaymentCategorised { payment: PaymentId, category: Category }, + #[serde(rename = "payment.assigned")] + PaymentAssigned { payment: PaymentId, budget: BudgetId }, + #[serde(rename = "payment.trial_marked")] + PaymentTrialMarked { payment: PaymentId, ends: Date }, + #[serde(rename = "budget.created")] + BudgetCreated { budget: BudgetId, name: String, limit: Haler }, + #[serde(rename = "budget.limit_set")] + BudgetLimitSet { budget: BudgetId, limit: Haler }, + /// "Always → ". + #[serde(rename = "rule.created")] + RuleCreated { rule: RuleId, merchant_key: String, category: Category }, + /// Keep or cancel a subscription (by its key), seen at `amount` (a positive cost) on `on`. + #[serde(rename = "subscription.decided")] + SubscriptionDecided { subscription: String, decision: Decision, amount: Haler, on: Date }, +} diff --git a/crates/fiscus-ledger/src/import.rs b/crates/fiscus-ledger/src/import.rs new file mode 100644 index 0000000..8cb2737 --- /dev/null +++ b/crates/fiscus-ledger/src/import.rs @@ -0,0 +1,109 @@ +//! Turning parsed statement lines into events: new lines only, then the matches they make. + +use crate::date::{Date, Timestamp}; +use crate::event::{Event, EventBody}; +use crate::matching::{find_matches, MatchReport}; +use crate::money::Haler; +use crate::state::State; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; + +/// One line of a bank statement, as a bank parser produced it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct StatementLine { + /// The parser's bank id, e.g. `fio`. + pub bank: String, + /// The statement's own account, as the bank writes it. + pub account: String, + pub booked: Date, + pub amount: Haler, + /// The merchant or payee text; may be empty. + pub merchant: String, + pub counterparty: Option, + pub variable_symbol: Option, + pub message: Option, + /// The bank's own id for the transaction, when the format has one. + pub bank_ref: Option, +} + +impl StatementLine { + /// No control characters and nothing over 500 characters, in any text field. + pub fn is_clean(&self) -> bool { + let ok = |s: &str| s.chars().count() <= 500 && !s.chars().any(|c| c.is_control()); + [&self.bank, &self.account, &self.merchant].iter().all(|s| ok(s)) + && [&self.counterparty, &self.variable_symbol, &self.message, &self.bank_ref] + .iter() + .all(|s| s.as_deref().is_none_or(ok)) + } +} + +/// The identity of each line across imports. With the bank's own id: bank|account|id. Without one: the line's +/// fields plus how many identical lines came before it in this file, so two identical coffees stay two lines +/// and the same file imported again gives the same keys. +pub fn line_keys(lines: &[StatementLine]) -> Vec { + let mut seen: BTreeMap = BTreeMap::new(); + lines + .iter() + .map(|l| { + let base = match &l.bank_ref { + Some(r) => format!("{}|{}|ref:{}", l.bank, l.account, r), + None => format!( + "{}|{}|{}|{}|{}|{}|{}|{}", + l.bank, + l.account, + l.booked, + l.amount.0, + l.merchant, + l.counterparty.as_deref().unwrap_or(""), + l.variable_symbol.as_deref().unwrap_or(""), + l.message.as_deref().unwrap_or("") + ), + }; + let n = seen.entry(base.clone()).or_insert(0); + *n += 1; + if l.bank_ref.is_some() { + base + } else { + format!("{base}#{n}") + } + }) + .collect() +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ImportPlan { + /// One `payment.imported` per new line, in file order. + pub events: Vec, + /// One `payment.confirmed` per certain match, to append after `events` when the user confirms. + pub confirmations: Vec, + /// Lines already in the ledger (or repeated in the file under the same bank id), skipped. + pub duplicates: usize, + /// The matches as they would be with the new lines in. + pub report: MatchReport, +} + +/// Plans an import. Nothing is applied: the app appends `events`, then `confirmations`. +/// `ids` gives fresh ids: for each new line its payment id then its event id, then one per confirmation. +pub fn plan_import(state: &State, lines: &[StatementLine], ids: &mut dyn FnMut() -> String, at: Timestamp) -> ImportPlan { + let mut sim = state.clone(); + let mut plan = ImportPlan::default(); + let mut batch: BTreeSet = BTreeSet::new(); + for (line, key) in lines.iter().zip(line_keys(lines)) { + if state.line_keys.contains_key(&key) || !batch.insert(key.clone()) { + plan.duplicates += 1; + continue; + } + let payment = ids(); + let event = Event::new(ids(), at, EventBody::PaymentImported { payment, line: line.clone(), line_key: key }); + sim.apply(&event); + plan.events.push(event); + } + plan.report = find_matches(&sim); + plan.confirmations = plan + .report + .pairs + .iter() + .map(|(payment, line)| Event::new(ids(), at, EventBody::PaymentConfirmed { payment: payment.clone(), line: line.clone() })) + .collect(); + plan +} diff --git a/crates/fiscus-ledger/src/lib.rs b/crates/fiscus-ledger/src/lib.rs new file mode 100644 index 0000000..ace9378 --- /dev/null +++ b/crates/fiscus-ledger/src/lib.rs @@ -0,0 +1,16 @@ +//! Fiscus Domi's ledger: money in haléře, civil dates, the append-only event log and the state derived from +//! it, merchant keys and rules, and capture ↔ statement matching. Pure: no I/O, no clock, no randomness. + +pub mod categories; +pub mod date; +pub mod event; +pub mod import; +pub mod matching; +pub mod merchant; +pub mod money; +pub mod state; + +pub use date::{Date, Timestamp}; +pub use event::{BudgetId, Category, Decision, Event, EventBody, EventId, PaymentId}; +pub use money::Haler; +pub use state::{EffectivePayment, Glyph, Origin, State}; diff --git a/crates/fiscus-ledger/src/matching.rs b/crates/fiscus-ledger/src/matching.rs new file mode 100644 index 0000000..cdf7b28 --- /dev/null +++ b/crates/fiscus-ledger/src/matching.rs @@ -0,0 +1,114 @@ +//! Capture ↔ statement matching. One to one, never a guess: a pair is matched only when each side is the +//! other's single best candidate; everything else is reported for the user. + +use crate::event::PaymentId; +use crate::merchant::compatible; +use crate::state::{Origin, PaymentRecord, State}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// A statement line may be booked this many days before the capture … +pub const WINDOW_BEFORE: i32 = 1; +/// … and this many days after it. +pub const WINDOW_AFTER: i32 = 5; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Ambiguity { + /// The captured or hand-added payment. + pub payment: PaymentId, + /// Statement lines it could be, best first. + pub candidates: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct MatchReport { + /// `(captured or hand-added, statement line)`, matched with certainty. + pub pairs: Vec<(PaymentId, PaymentId)>, + /// Unmatched payments that have possible lines: the user picks. + pub ambiguous: Vec, + /// Every captured or hand-added payment not in `pairs`. + pub unmatched_captured: Vec, + /// Every statement line not in `pairs`. + pub unmatched_lines: Vec, +} + +/// How well a line fits a payment. `None`: it cannot be the same payment. +/// `Some((strong, exact, -gap))`, compared as a tuple; only strong fits are ever matched automatically. +fn fit(p: &PaymentRecord, l: &PaymentRecord) -> Option<(bool, bool, i32)> { + if p.amount != l.amount { + return None; + } + let gap = p.date.days_until(l.date); + if !(-WINDOW_BEFORE..=WINDOW_AFTER).contains(&gap) { + return None; + } + if p.merchant_key.is_empty() || l.merchant_key.is_empty() { + return Some((false, false, -gap.abs())); + } + if !compatible(&p.merchant_key, &l.merchant_key) { + return None; + } + Some((true, p.merchant_key == l.merchant_key, -gap.abs())) +} + +/// The single best candidate, if it is strictly better than the second. +fn unique_best<'a>(cands: impl Iterator) -> Option<&'a PaymentId> { + let mut v: Vec<_> = cands.filter(|(_, s)| s.0).collect(); + v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + match v.as_slice() { + [] => None, + [only] => Some(only.0), + [first, second, ..] if first.1 > second.1 => Some(first.0), + _ => None, + } +} + +pub fn find_matches(state: &State) -> MatchReport { + let mut left: Vec<&PaymentRecord> = + state.payments.values().filter(|p| p.origin != Origin::Imported && p.partner.is_none()).collect(); + let mut right: Vec<&PaymentRecord> = + state.payments.values().filter(|p| p.origin == Origin::Imported && p.partner.is_none()).collect(); + left.sort_by_key(|p| p.seq); + right.sort_by_key(|p| p.seq); + + let mut done_l: BTreeSet<&PaymentId> = BTreeSet::new(); + let mut done_r: BTreeSet<&PaymentId> = BTreeSet::new(); + let mut pairs: Vec<(u64, PaymentId, PaymentId)> = Vec::new(); + loop { + let mut found = Vec::new(); + for p in left.iter().filter(|p| !done_l.contains(&p.id)) { + let open_r = right.iter().filter(|l| !done_r.contains(&l.id)); + let Some(best) = unique_best(open_r.filter_map(|l| fit(p, l).map(|s| (&l.id, s)))) else { continue }; + let line = right.iter().find(|l| &l.id == best).expect("best comes from right"); + let open_l = left.iter().filter(|q| !done_l.contains(&q.id)); + if unique_best(open_l.filter_map(|q| fit(q, line).map(|s| (&q.id, s)))) == Some(&p.id) { + found.push((p.seq, &p.id, &line.id)); + } + } + if found.is_empty() { + break; + } + for (seq, p, l) in found { + done_l.insert(p); + done_r.insert(l); + pairs.push((seq, p.clone(), l.clone())); + } + } + pairs.sort(); + + let mut report = MatchReport { pairs: pairs.into_iter().map(|(_, p, l)| (p, l)).collect(), ..Default::default() }; + for p in left.iter().filter(|p| !done_l.contains(&p.id)) { + report.unmatched_captured.push(p.id.clone()); + let mut cands: Vec<_> = right + .iter() + .filter(|l| !done_r.contains(&l.id)) + .filter_map(|l| fit(p, l).map(|s| (s, &l.id))) + .collect(); + cands.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1))); + if !cands.is_empty() { + report.ambiguous.push(Ambiguity { payment: p.id.clone(), candidates: cands.into_iter().map(|(_, id)| id.clone()).collect() }); + } + } + report.unmatched_lines = right.iter().filter(|l| !done_r.contains(&l.id)).map(|l| l.id.clone()).collect(); + report +} diff --git a/crates/fiscus-ledger/src/merchant.rs b/crates/fiscus-ledger/src/merchant.rs new file mode 100644 index 0000000..a3c2f5a --- /dev/null +++ b/crates/fiscus-ledger/src/merchant.rs @@ -0,0 +1,107 @@ +//! Merchant keys: the same shop written differently by a phone, a bank and a person becomes one key. +//! Rules and subscriptions are keyed on it. + +/// `PAYPAL *SPOTIFY P1234` → `spotify`; `ALBERT 1234 PRAHA 4 CZ` → `albert praha`; `Žabka` → `zabka`. +pub fn merchant_key(raw: &str) -> String { + let folded: String = raw.chars().flat_map(fold).collect::().to_lowercase(); + // A processor's prefix before `*`: "paypal *spotify", "sumup *kavarna", "sq *bistro". + let rest = match folded.split_once('*') { + Some((head, tail)) if !tail.trim().is_empty() && head.trim().split_whitespace().count() <= 2 => tail, + _ => folded.as_str(), + }; + let cleaned: String = rest.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' }).collect(); + let mut words: Vec<&str> = cleaned + .split_whitespace() + .filter(|w| !w.bytes().any(|b| b.is_ascii_digit())) + .collect(); + while words.len() > 1 && matches!(words.last(), Some(&"cz") | Some(&"cze") | Some(&"czech")) { + words.pop(); + } + words.join(" ") +} + +/// Whether two merchant keys can be the same shop: equal, one inside the other, or the same first word of +/// at least three letters. An empty key is never compatible. +pub fn compatible(a: &str, b: &str) -> bool { + if a.is_empty() || b.is_empty() { + return false; + } + if a == b || contains_words(a, b) || contains_words(b, a) { + return true; + } + match (a.split(' ').next(), b.split(' ').next()) { + (Some(x), Some(y)) => x == y && x.len() >= 3, + _ => false, + } +} + +/// `needle`'s words appear in `hay` as a run of whole words. +fn contains_words(hay: &str, needle: &str) -> bool { + let h: Vec<&str> = hay.split(' ').collect(); + let n: Vec<&str> = needle.split(' ').collect(); + n.len() <= h.len() && h.windows(n.len()).any(|w| w == n.as_slice()) +} + +/// ASCII folding of the Latin letters a Czech (or Slovak, German, Polish) shop name uses. +fn fold(c: char) -> std::iter::Once { + let r = match c { + 'á' | 'ä' | 'à' | 'â' | 'ą' => 'a', + 'Á' | 'Ä' | 'À' | 'Â' | 'Ą' => 'A', + 'č' | 'ć' | 'ç' => 'c', + 'Č' | 'Ć' | 'Ç' => 'C', + 'ď' => 'd', + 'Ď' => 'D', + 'é' | 'ě' | 'ë' | 'è' | 'ê' | 'ę' => 'e', + 'É' | 'Ě' | 'Ë' | 'È' | 'Ê' | 'Ę' => 'E', + 'í' | 'ï' | 'î' => 'i', + 'Í' | 'Ï' | 'Î' => 'I', + 'ľ' | 'ĺ' | 'ł' => 'l', + 'Ľ' | 'Ĺ' | 'Ł' => 'L', + 'ň' | 'ń' => 'n', + 'Ň' | 'Ń' => 'N', + 'ó' | 'ö' | 'ô' | 'ő' => 'o', + 'Ó' | 'Ö' | 'Ô' | 'Ő' => 'O', + 'ř' | 'ŕ' => 'r', + 'Ř' | 'Ŕ' => 'R', + 'š' | 'ś' => 's', + 'Š' | 'Ś' => 'S', + 'ť' => 't', + 'Ť' => 'T', + 'ú' | 'ů' | 'ü' | 'ű' => 'u', + 'Ú' | 'Ů' | 'Ü' | 'Ű' => 'U', + 'ý' | 'ÿ' => 'y', + 'Ý' => 'Y', + 'ž' | 'ź' | 'ż' => 'z', + 'Ž' | 'Ź' | 'Ż' => 'Z', + 'ß' => 's', + other => other, + }; + std::iter::once(r) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys() { + assert_eq!(merchant_key("PAYPAL *SPOTIFY P1234"), "spotify"); + assert_eq!(merchant_key("ALBERT 1234 PRAHA 4 CZ"), "albert praha"); + assert_eq!(merchant_key("Žabka"), "zabka"); + assert_eq!(merchant_key("NETFLIX.COM"), "netflix com"); + assert_eq!(merchant_key("SumUp *Kavárna Dobrá"), "kavarna dobra"); + assert_eq!(merchant_key(" "), ""); + assert_eq!(merchant_key("123 456"), ""); + assert_eq!(merchant_key("Kč * "), "kc"); + } + + #[test] + fn compatibility() { + assert!(compatible("albert", "albert praha")); + assert!(compatible("albert praha", "albert brno")); + assert!(compatible("netflix com", "netflix")); + assert!(!compatible("lidl", "albert")); + assert!(!compatible("", "albert")); + assert!(!compatible("od praha", "od brno"), "a two-letter first word is not enough"); + } +} diff --git a/crates/fiscus-ledger/src/money.rs b/crates/fiscus-ledger/src/money.rs new file mode 100644 index 0000000..2f4767e --- /dev/null +++ b/crates/fiscus-ledger/src/money.rs @@ -0,0 +1,143 @@ +//! Money: whole haléře in an `i64`. Outflows are negative, as on a statement. Every operation is checked. + +use serde::{Deserialize, Serialize}; +use std::fmt; + +/// An amount in haléře (1 CZK = 100 haléřů). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct Haler(pub i64); + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum MoneyError { + #[error("the amount is too large")] + Overflow, + #[error("there is nobody to split between")] + NoWeight, + #[error("not an amount in CZK")] + NotAnAmount, +} + +impl Haler { + pub const ZERO: Haler = Haler(0); + + pub fn checked_add(self, other: Haler) -> Result { + self.0.checked_add(other.0).map(Haler).ok_or(MoneyError::Overflow) + } + + pub fn checked_sub(self, other: Haler) -> Result { + self.0.checked_sub(other.0).map(Haler).ok_or(MoneyError::Overflow) + } + + pub fn checked_neg(self) -> Result { + self.0.checked_neg().map(Haler).ok_or(MoneyError::Overflow) + } + + pub fn is_outflow(self) -> bool { + self.0 < 0 + } + + /// The sum, or `Overflow`. Integer addition is associative, so the order never matters. + pub fn sum>(items: I) -> Result { + items.into_iter().try_fold(Haler::ZERO, Haler::checked_add) + } + + /// `-1 234,50`: a space between thousands, a decimal comma, always two decimals, no currency. + pub fn to_czk(self) -> String { + let neg = self.0 < 0; + let abs = self.0.unsigned_abs(); + let whole = (abs / 100).to_string(); + let mut grouped = String::with_capacity(whole.len() + whole.len() / 3); + for (i, c) in whole.chars().enumerate() { + if i > 0 && (whole.len() - i) % 3 == 0 { + grouped.push(' '); + } + grouped.push(c); + } + format!("{}{},{:02}", if neg { "-" } else { "" }, grouped, abs % 100) + } + + /// The inverse of [`Haler::to_czk`], also taking a plain `1234`, `1234,5` or `1234.50` as typed by hand. + /// Strict: one optional leading minus, ASCII digits, spaces only between groups of three, at most two + /// decimals after one `,` or `.`. + pub fn parse_czk(text: &str) -> Result { + let t = text.trim(); + let (neg, t) = match t.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, t), + }; + let (int, frac) = match t.find([',', '.']) { + Some(i) => (&t[..i], Some(&t[i + 1..])), + None => (t, None), + }; + let groups: Vec<&str> = int.split(' ').collect(); + if groups.iter().any(|g| g.is_empty() || !g.bytes().all(|b| b.is_ascii_digit())) + || groups.iter().skip(1).any(|g| g.len() != 3) + || (groups.len() > 1 && groups[0].len() > 3) + { + return Err(MoneyError::NotAnAmount); + } + let digits: String = groups.concat(); + let cents = match frac { + None => 0, + Some(f) if (1..=2).contains(&f.len()) && f.bytes().all(|b| b.is_ascii_digit()) => { + let v: i64 = f.parse().map_err(|_| MoneyError::NotAnAmount)?; + if f.len() == 1 { + v * 10 + } else { + v + } + } + Some(_) => return Err(MoneyError::NotAnAmount), + }; + let whole: i64 = digits.parse().map_err(|_| MoneyError::Overflow)?; + let abs = whole.checked_mul(100).and_then(|w| w.checked_add(cents)).ok_or(MoneyError::Overflow)?; + Ok(Haler(if neg { -abs } else { abs })) + } +} + +impl fmt::Display for Haler { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} Kč", self.to_czk()) + } +} + +/// Splits `total` by `weights` so that the shares always sum to `total` exactly. +/// +/// Largest remainder: each share is `floor(|total|·w/Σw)`; the haléře left over go one each to the largest +/// remainders, ties to the lower index. A negative total is split as its absolute value, then mirrored. +pub fn split(total: Haler, weights: &[u64]) -> Result, MoneyError> { + let sum_w: u128 = weights.iter().map(|w| *w as u128).sum(); + if sum_w == 0 { + return Err(MoneyError::NoWeight); + } + let abs = total.0.unsigned_abs() as u128; + let mut shares: Vec = Vec::with_capacity(weights.len()); + let mut rems: Vec<(u128, usize)> = Vec::with_capacity(weights.len()); + for (i, w) in weights.iter().enumerate() { + let num = abs * (*w as u128); + shares.push(num / sum_w); + rems.push((num % sum_w, i)); + } + let given: u128 = shares.iter().sum(); + let mut left = abs - given; // < weights.len() + // Largest remainder first; equal remainders by index. + rems.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + for (rem, i) in rems { + if left == 0 { + break; + } + if rem == 0 && weights[i] == 0 { + continue; + } + shares[i] += 1; + left -= 1; + } + shares + .into_iter() + .map(|s| { + let s = i64::try_from(s).map_err(|_| MoneyError::Overflow)?; + Ok(Haler(if total.0 < 0 { -s } else { s })) + }) + .collect() +} diff --git a/crates/fiscus-ledger/src/state.rs b/crates/fiscus-ledger/src/state.rs new file mode 100644 index 0000000..259467a --- /dev/null +++ b/crates/fiscus-ledger/src/state.rs @@ -0,0 +1,439 @@ +//! State = `apply()` folded over the log. Deterministic: every collection is ordered, nothing depends on a +//! clock or a hash seed, and `apply()` is total (an event that does not fit is recorded as rejected). + +use crate::categories; +use crate::date::Date; +use crate::event::{BudgetId, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId}; +use crate::import::StatementLine; +use crate::merchant::merchant_key; +use crate::money::Haler; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; + +const MAX_TEXT: usize = 500; + +/// Where a payment record came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Origin { + Captured, + Imported, + Added, +} + +/// What the app shows next to a payment: ○ captured, ● on a statement, ◆ added by hand. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Glyph { + Captured, + Confirmed, + Hand, +} + +impl Glyph { + pub fn symbol(self) -> char { + match self { + Glyph::Captured => '○', + Glyph::Confirmed => '●', + Glyph::Hand => '◆', + } + } +} + +/// A value and the position in the log that set it: the later one wins. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Stamped { + pub seq: u64, + pub value: T, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PaymentRecord { + pub id: PaymentId, + pub origin: Origin, + pub seq: u64, + pub amount: Haler, + pub date: Date, + pub merchant: String, + pub merchant_key: String, + pub card: Option, + pub note: Option, + pub line: Option, + pub category: Option>, + pub budget: Option>, + pub trial_ends: Option>, + /// The other half of a confirmed pair. + pub partner: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Budget { + pub id: BudgetId, + pub name: String, + pub limit: Haler, + pub seq: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Rule { + pub id: RuleId, + pub category: Category, + pub seq: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct DecisionRecord { + pub decision: Decision, + pub amount: Haler, + pub on: Date, + pub seq: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Rejection { + pub event: EventId, + pub seq: u64, + pub reason: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct State { + /// Events seen, accepted or not. + pub seq: u64, + pub events: BTreeSet, + pub payments: BTreeMap, + pub line_keys: BTreeMap, + pub budgets: BTreeMap, + /// The first budget created: where a payment goes when nobody assigned it. + pub default_budget: Option, + /// Merchant key → the latest rule for it. + pub rules: BTreeMap, + /// Subscription key → its decisions, oldest first. + pub decisions: BTreeMap>, + pub rejected: Vec, +} + +/// Why a category is what it is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CategorySource { + Explicit, + Rule, + None, +} + +/// One payment as the user sees it: a confirmed pair is one payment. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EffectivePayment { + /// The captured or hand-added id when there is one (so a row keeps its id when confirmed), else the line's. + pub id: PaymentId, + pub captured: Option, + pub line: Option, + pub glyph: Glyph, + pub origin: Origin, + pub seq: u64, + pub amount: Haler, + pub date: Date, + pub merchant: String, + pub merchant_key: String, + pub card: Option, + pub note: Option, + pub counterparty: Option, + pub variable_symbol: Option, + pub message: Option, + pub category: Option, + pub category_source: CategorySource, + pub budget: Option, + pub trial_ends: Option, +} + +fn text_ok(s: &str) -> bool { + s.chars().count() <= MAX_TEXT && !s.chars().any(|c| c.is_control()) +} + +fn opt_text_ok(s: &Option) -> bool { + s.as_deref().is_none_or(text_ok) +} + +fn latest(a: &Option>, b: Option<&Option>>) -> Option { + let b = b.and_then(|b| b.as_ref()); + match (a.as_ref(), b) { + (Some(x), Some(y)) => Some(if x.seq >= y.seq { x.value.clone() } else { y.value.clone() }), + (Some(x), None) => Some(x.value.clone()), + (None, Some(y)) => Some(y.value.clone()), + (None, None) => None, + } +} + +impl State { + pub fn replay<'a, I: IntoIterator>(log: I) -> State { + let mut s = State::default(); + for e in log { + s.apply(e); + } + s + } + + /// Applies one event. Never panics; an event that does not fit is recorded in `rejected`. + pub fn apply(&mut self, e: &Event) { + self.seq += 1; + let seq = self.seq; + if !self.events.insert(e.id.clone()) { + self.reject(e, "the same event twice"); + return; + } + if let Err(reason) = self.try_apply(&e.body, seq) { + self.reject(e, reason); + } + } + + fn reject(&mut self, e: &Event, reason: &str) { + self.rejected.push(Rejection { event: e.id.clone(), seq: self.seq, reason: reason.into() }); + } + + fn new_payment(&self, id: &PaymentId, amount: Haler) -> Result<(), &'static str> { + if id.is_empty() || id.len() > 100 { + return Err("a payment id must be 1-100 characters"); + } + if self.payments.contains_key(id) { + return Err("a payment with this id exists"); + } + if amount == Haler::ZERO { + return Err("a payment of zero"); + } + Ok(()) + } + + fn payment_mut(&mut self, id: &PaymentId) -> Result<&mut PaymentRecord, &'static str> { + self.payments.get_mut(id).ok_or("no such payment") + } + + fn try_apply(&mut self, body: &EventBody, seq: u64) -> Result<(), &'static str> { + match body { + EventBody::PaymentCaptured { payment, amount, date, merchant, card } => { + self.new_payment(payment, *amount)?; + if !text_ok(merchant) || !opt_text_ok(card) { + return Err("a text field is too long or has control characters"); + } + self.payments.insert( + payment.clone(), + PaymentRecord { + id: payment.clone(), + origin: Origin::Captured, + seq, + amount: *amount, + date: *date, + merchant: merchant.clone(), + merchant_key: merchant_key(merchant), + card: card.clone(), + note: None, + line: None, + category: None, + budget: None, + trial_ends: None, + partner: None, + }, + ); + } + EventBody::PaymentImported { payment, line, line_key } => { + // A zero line (a card check) is still a line: allowed, unlike a zero capture. + self.new_payment(payment, Haler(1))?; + if line_key.is_empty() || self.line_keys.contains_key(line_key) { + return Err("this statement line was imported before"); + } + if !line.is_clean() { + return Err("a text field is too long or has control characters"); + } + self.line_keys.insert(line_key.clone(), payment.clone()); + self.payments.insert( + payment.clone(), + PaymentRecord { + id: payment.clone(), + origin: Origin::Imported, + seq, + amount: line.amount, + date: line.booked, + merchant: line.merchant.clone(), + merchant_key: merchant_key(&line.merchant), + card: None, + note: None, + line: Some(line.clone()), + category: None, + budget: None, + trial_ends: None, + partner: None, + }, + ); + } + EventBody::PaymentAdded { payment, amount, date, merchant, category, note } => { + self.new_payment(payment, *amount)?; + if !text_ok(merchant) || !opt_text_ok(note) { + return Err("a text field is too long or has control characters"); + } + if category.as_deref().is_some_and(|c| !categories::is_valid(c)) { + return Err("not a category id"); + } + self.payments.insert( + payment.clone(), + PaymentRecord { + id: payment.clone(), + origin: Origin::Added, + seq, + amount: *amount, + date: *date, + merchant: merchant.clone(), + merchant_key: merchant_key(merchant), + card: None, + note: note.clone(), + line: None, + category: category.clone().map(|value| Stamped { seq, value }), + budget: None, + trial_ends: None, + partner: None, + }, + ); + } + EventBody::PaymentConfirmed { payment, line } => { + let p = self.payments.get(payment).ok_or("no such payment")?; + let l = self.payments.get(line).ok_or("no such statement line")?; + if p.origin == Origin::Imported || l.origin != Origin::Imported { + return Err("a confirmation ties a captured or hand-added payment to a statement line"); + } + if p.partner.is_some() || l.partner.is_some() { + return Err("already confirmed"); + } + if p.amount != l.amount { + return Err("the amounts differ"); + } + self.payment_mut(payment)?.partner = Some(line.clone()); + self.payment_mut(line)?.partner = Some(payment.clone()); + } + EventBody::PaymentCategorised { payment, category } => { + if !categories::is_valid(category) { + return Err("not a category id"); + } + self.payment_mut(payment)?.category = Some(Stamped { seq, value: category.clone() }); + } + EventBody::PaymentAssigned { payment, budget } => { + if !self.budgets.contains_key(budget) { + return Err("no such budget"); + } + self.payment_mut(payment)?.budget = Some(Stamped { seq, value: budget.clone() }); + } + EventBody::PaymentTrialMarked { payment, ends } => { + self.payment_mut(payment)?.trial_ends = Some(Stamped { seq, value: *ends }); + } + EventBody::BudgetCreated { budget, name, limit } => { + if budget.is_empty() || self.budgets.contains_key(budget) { + return Err("a budget with this id exists"); + } + let name = name.trim(); + if name.is_empty() || name.chars().count() > 60 || !text_ok(name) { + return Err("a budget name must be 1-60 characters"); + } + if limit.0 < 0 { + return Err("a limit cannot be negative"); + } + self.budgets.insert(budget.clone(), Budget { id: budget.clone(), name: name.into(), limit: *limit, seq }); + if self.default_budget.is_none() { + self.default_budget = Some(budget.clone()); + } + } + EventBody::BudgetLimitSet { budget, limit } => { + if limit.0 < 0 { + return Err("a limit cannot be negative"); + } + self.budgets.get_mut(budget).ok_or("no such budget")?.limit = *limit; + } + EventBody::RuleCreated { rule, merchant_key: key, category } => { + if key.is_empty() || merchant_key(key) != *key { + return Err("not a merchant key"); + } + if !categories::is_valid(category) { + return Err("not a category id"); + } + self.rules.insert(key.clone(), Rule { id: rule.clone(), category: category.clone(), seq }); + } + EventBody::SubscriptionDecided { subscription, decision, amount, on } => { + if subscription.is_empty() || !text_ok(subscription) { + return Err("not a subscription key"); + } + if amount.0 < 0 { + return Err("a subscription's amount is a cost, not negative"); + } + self.decisions + .entry(subscription.clone()) + .or_default() + .push(DecisionRecord { decision: *decision, amount: *amount, on: *on, seq }); + } + } + Ok(()) + } + + /// Every payment as the user sees it, a confirmed pair as one, in date order (then log order). + pub fn effective_payments(&self) -> Vec { + let mut out: Vec = self + .payments + .values() + .filter(|p| !(p.origin == Origin::Imported && p.partner.is_some())) + .map(|p| self.effective(p)) + .collect(); + out.sort_by(|a, b| a.date.cmp(&b.date).then(a.seq.cmp(&b.seq))); + out + } + + /// The effective payment that contains `id` (either half of a pair). + pub fn effective_payment(&self, id: &str) -> Option { + let p = self.payments.get(id)?; + let primary = match (&p.origin, &p.partner) { + (Origin::Imported, Some(partner)) => self.payments.get(partner)?, + _ => p, + }; + Some(self.effective(primary)) + } + + fn effective(&self, p: &PaymentRecord) -> EffectivePayment { + let partner = p.partner.as_ref().and_then(|id| self.payments.get(id)); + let line_rec = if p.origin == Origin::Imported { Some(p) } else { partner }; + let line = line_rec.and_then(|r| r.line.as_ref()); + let merchant = match line { + Some(l) if !l.merchant.trim().is_empty() => l.merchant.clone(), + _ => p.merchant.clone(), + }; + let key = merchant_key(&merchant); + let explicit = latest(&p.category, partner.map(|q| &q.category)); + let (category, category_source) = match explicit { + Some(c) => (Some(c), CategorySource::Explicit), + None => match self.rules.get(&key) { + Some(r) => (Some(r.category.clone()), CategorySource::Rule), + None => (None, CategorySource::None), + }, + }; + let budget = latest(&p.budget, partner.map(|q| &q.budget)).or_else(|| self.default_budget.clone()); + EffectivePayment { + id: p.id.clone(), + captured: if p.origin == Origin::Imported { None } else { Some(p.id.clone()) }, + line: line_rec.map(|r| r.id.clone()), + glyph: match (line_rec.is_some(), p.origin) { + (true, _) => Glyph::Confirmed, + (false, Origin::Added) => Glyph::Hand, + (false, _) => Glyph::Captured, + }, + origin: p.origin, + seq: p.seq, + amount: line_rec.map(|r| r.amount).unwrap_or(p.amount), + date: line_rec.map(|r| r.date).unwrap_or(p.date), + merchant, + merchant_key: key, + card: p.card.clone(), + note: p.note.clone(), + counterparty: line.and_then(|l| l.counterparty.clone()), + variable_symbol: line.and_then(|l| l.variable_symbol.clone()), + message: line.and_then(|l| l.message.clone()), + category, + category_source, + budget, + trial_ends: latest(&p.trial_ends, partner.map(|q| &q.trial_ends)), + } + } +} diff --git a/crates/fiscus-ledger/tests/matching.rs b/crates/fiscus-ledger/tests/matching.rs new file mode 100644 index 0000000..e6bce1d --- /dev/null +++ b/crates/fiscus-ledger/tests/matching.rs @@ -0,0 +1,222 @@ +//! Mandatory test 3: matching captures to statement lines is one to one, a statement imported twice adds +//! nothing, and everything left over is reported on both sides. + +use fiscus_ledger::import::{plan_import, StatementLine}; +use fiscus_ledger::matching::find_matches; +use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp}; +use proptest::prelude::*; + +fn d(s: &str) -> Date { + s.parse().unwrap() +} + +struct Ids(u64); +impl Ids { + fn next(&mut self) -> String { + self.0 += 1; + format!("id{:04}", self.0) + } +} + +fn captured(ids: &mut Ids, amount: i64, date: &str, merchant: &str) -> Event { + Event::new( + ids.next(), + Timestamp(0), + EventBody::PaymentCaptured { + payment: ids.next(), + amount: Haler(amount), + date: d(date), + merchant: merchant.into(), + card: None, + }, + ) +} + +fn line(amount: i64, date: &str, merchant: &str) -> StatementLine { + StatementLine { + bank: "test".into(), + account: "123/0000".into(), + booked: d(date), + amount: Haler(amount), + merchant: merchant.into(), + counterparty: None, + variable_symbol: None, + message: None, + bank_ref: None, + } +} + +fn payment_of(e: &Event) -> String { + match &e.body { + EventBody::PaymentCaptured { payment, .. } | EventBody::PaymentImported { payment, .. } => payment.clone(), + _ => unreachable!(), + } +} + +fn import(state: &mut State, ids: &mut Ids, lines: &[StatementLine]) -> fiscus_ledger::import::ImportPlan { + let plan = plan_import(state, lines, &mut || ids.next(), Timestamp(1)); + for e in plan.events.iter().chain(&plan.confirmations) { + state.apply(e); + } + plan +} + +#[test] +fn a_capture_and_its_line_match() { + let mut ids = Ids(0); + let mut state = State::default(); + let c = captured(&mut ids, -12_900, "2026-10-02", "ALBERT 1234 PRAHA"); + state.apply(&c); + let plan = import(&mut state, &mut ids, &[line(-12_900, "2026-10-03", "Albert Praha")]); + assert_eq!(plan.events.len(), 1); + assert_eq!(plan.report.pairs.len(), 1); + assert_eq!(plan.report.pairs[0].0, payment_of(&c)); + assert!(plan.report.unmatched_captured.is_empty() && plan.report.unmatched_lines.is_empty()); + // Once confirmed, they are one payment and nothing is left to match. + assert_eq!(state.effective_payments().len(), 1); + let after = find_matches(&state); + assert!(after.pairs.is_empty() && after.unmatched_captured.is_empty() && after.unmatched_lines.is_empty()); +} + +#[test] +fn one_capture_never_matches_two_lines() { + let mut ids = Ids(0); + let mut state = State::default(); + let c = captured(&mut ids, -5_000, "2026-10-02", "Kavarna Dobra"); + state.apply(&c); + let twins = [line(-5_000, "2026-10-03", "KAVARNA DOBRA"), line(-5_000, "2026-10-03", "KAVARNA DOBRA")]; + let plan = import(&mut state, &mut ids, &twins); + // Two identical lines are two lines (two coffees), and the capture cannot pick one by itself. + assert_eq!(plan.events.len(), 2); + assert!(plan.report.pairs.is_empty()); + assert_eq!(plan.report.ambiguous.len(), 1); + assert_eq!(plan.report.ambiguous[0].candidates.len(), 2); + assert_eq!(plan.report.unmatched_captured, vec![payment_of(&c)]); + assert_eq!(plan.report.unmatched_lines.len(), 2); +} + +#[test] +fn a_second_confirmation_of_the_same_capture_is_rejected() { + let mut ids = Ids(0); + let mut state = State::default(); + let c = captured(&mut ids, -5_000, "2026-10-02", "Kavarna"); + state.apply(&c); + let plan = import(&mut state, &mut ids, &[line(-5_000, "2026-10-02", "Kavarna"), line(-5_000, "2026-10-04", "Kavarna")]); + assert_eq!(plan.report.pairs.len(), 1, "the line on the same day wins over the one two days later"); + let second_line = payment_of(&plan.events[1]); + let again = Event::new(ids.next(), Timestamp(2), EventBody::PaymentConfirmed { payment: payment_of(&c), line: second_line }); + let before = serde_json::to_string(&state.effective_payments()).unwrap(); + state.apply(&again); + assert_eq!(serde_json::to_string(&state.effective_payments()).unwrap(), before); + assert_eq!(state.rejected.len(), 1); +} + +#[test] +fn the_same_statement_imported_twice_adds_nothing() { + let mut ids = Ids(0); + let mut state = State::default(); + let lines = [ + line(-12_900, "2026-10-03", "Albert"), + line(-12_900, "2026-10-03", "Albert"), + line(-49_900, "2026-10-05", "Spotify"), + line(3_500_000, "2026-10-10", "Salary"), + ]; + let first = import(&mut state, &mut ids, &lines); + assert_eq!(first.events.len(), 4); + let snapshot = serde_json::to_vec(&state).unwrap(); + let second = import(&mut state, &mut ids, &lines); + assert!(second.events.is_empty() && second.confirmations.is_empty()); + assert_eq!(second.duplicates, 4); + assert_eq!(serde_json::to_vec(&state).unwrap(), snapshot); + // An overlapping statement adds only its new lines. + let mut overlap = lines.to_vec(); + overlap.push(line(-9_900, "2026-10-12", "Netflix")); + let third = import(&mut state, &mut ids, &overlap); + assert_eq!((third.events.len(), third.duplicates), (1, 4)); +} + +#[test] +fn unmatched_items_are_reported_on_both_sides() { + let mut ids = Ids(0); + let mut state = State::default(); + let c1 = captured(&mut ids, -12_900, "2026-10-02", "Albert"); + let c2 = captured(&mut ids, -7_000, "2026-10-02", "Rohlik"); // never on the statement + state.apply(&c1); + state.apply(&c2); + let plan = import( + &mut state, + &mut ids, + &[ + line(-12_900, "2026-10-03", "Albert"), + line(-7_001, "2026-10-03", "Rohlik"), // one haléř off: not the same payment + line(-7_000, "2026-10-20", "Rohlik"), // too late + line(-3_000, "2026-10-03", "Benzina"), // nothing captured + ], + ); + assert_eq!(plan.report.pairs, vec![(payment_of(&c1), payment_of(&plan.events[0]))]); + assert_eq!(plan.report.unmatched_captured, vec![payment_of(&c2)]); + assert_eq!(plan.report.unmatched_lines.len(), 3); +} + +#[test] +fn a_hand_added_payment_without_merchant_is_only_proposed() { + let mut ids = Ids(0); + let mut state = State::default(); + let added = Event::new( + ids.next(), + Timestamp(0), + EventBody::PaymentAdded { + payment: ids.next(), + amount: Haler(-25_000), + date: d("2026-10-02"), + merchant: String::new(), + category: Some("groceries".into()), + note: None, + }, + ); + state.apply(&added); + let plan = import(&mut state, &mut ids, &[line(-25_000, "2026-10-02", "Lidl")]); + assert!(plan.report.pairs.is_empty()); + assert_eq!(plan.report.ambiguous.len(), 1); +} + +proptest! { + #[test] + fn matching_is_always_one_to_one_and_complete( + caps in prop::collection::vec((0i64..4, 0i32..10, 0usize..3), 0..12), + lines in prop::collection::vec((0i64..4, 0i32..10, 0usize..3), 0..12), + ) { + let merchants = ["Albert", "Lidl", "Spotify"]; + let base = d("2026-10-01"); + let mut ids = Ids(0); + let mut state = State::default(); + for (a, day, m) in &caps { + let e = Event::new(ids.next(), Timestamp(0), EventBody::PaymentCaptured { + payment: ids.next(), amount: Haler(-(a + 1) * 1000), date: base.add_days(*day), + merchant: merchants[*m].into(), card: None, + }); + state.apply(&e); + } + let lines: Vec<_> = lines.iter().map(|(a, day, m)| StatementLine { + booked: base.add_days(*day), amount: Haler(-(a + 1) * 1000), merchant: merchants[*m].into(), + ..line(0, "2026-10-01", "") + }).collect(); + let plan = import(&mut state, &mut ids, &lines); + let r = &plan.report; + let mut seen_c = std::collections::BTreeSet::new(); + let mut seen_l = std::collections::BTreeSet::new(); + for (c, l) in &r.pairs { + prop_assert!(seen_c.insert(c.clone()), "capture matched twice"); + prop_assert!(seen_l.insert(l.clone()), "line matched twice"); + } + prop_assert_eq!(seen_c.len() + r.unmatched_captured.len(), caps.len()); + prop_assert_eq!(seen_l.len() + r.unmatched_lines.len(), lines.len()); + prop_assert!(state.rejected.is_empty()); + // Applying the plan leaves every capture in at most one pair and the totals unchanged. + let total_lines: i64 = lines.iter().map(|l| l.amount.0).sum(); + let total_unmatched_caps: i64 = state.effective_payments().iter() + .filter(|p| p.line.is_none()).map(|p| p.amount.0).sum(); + let total: i64 = state.effective_payments().iter().map(|p| p.amount.0).sum(); + prop_assert_eq!(total, total_lines + total_unmatched_caps); + } +} diff --git a/crates/fiscus-ledger/tests/money.rs b/crates/fiscus-ledger/tests/money.rs new file mode 100644 index 0000000..675126f --- /dev/null +++ b/crates/fiscus-ledger/tests/money.rs @@ -0,0 +1,97 @@ +//! Mandatory test 1: money never loses or creates a haléř. + +use fiscus_ledger::money::{split, Haler, MoneyError}; +use proptest::prelude::*; + +const BIG: i64 = 1_000_000_000_000; // ten billion CZK in haléře: far beyond any household + +proptest! { + #[test] + fn split_shares_sum_to_the_total(total in -BIG..BIG, weights in prop::collection::vec(0u64..10_000, 1..12)) { + prop_assume!(weights.iter().any(|w| *w > 0)); + let shares = split(Haler(total), &weights).unwrap(); + prop_assert_eq!(shares.len(), weights.len()); + prop_assert_eq!(Haler::sum(shares.iter().copied()).unwrap(), Haler(total)); + } + + #[test] + fn a_zero_weight_gets_nothing(total in -BIG..BIG, n in 1usize..8) { + let mut weights = vec![1u64; n]; + weights.push(0); + let shares = split(Haler(total), &weights).unwrap(); + prop_assert_eq!(*shares.last().unwrap(), Haler(0)); + } + + #[test] + fn shares_differ_by_at_most_one_haler_for_equal_weights(total in -BIG..BIG, n in 1usize..12) { + let shares = split(Haler(total), &vec![1u64; n]).unwrap(); + let min = shares.iter().map(|h| h.0).min().unwrap(); + let max = shares.iter().map(|h| h.0).max().unwrap(); + prop_assert!(max - min <= 1); + } + + #[test] + fn the_remainder_rule_is_deterministic(total in -BIG..BIG, weights in prop::collection::vec(1u64..100, 1..8)) { + prop_assert_eq!(split(Haler(total), &weights).unwrap(), split(Haler(total), &weights).unwrap()); + } + + #[test] + fn a_payment_and_its_refund_cancel_out(amount in 1i64..BIG, refunds in prop::collection::vec(1u64..100, 1..5)) { + // A refund split into parts: the parts plus the payment come back to zero exactly. + let parts = split(Haler(amount), &refunds).unwrap(); + let mut all = vec![Haler(-amount)]; + all.extend(parts); + prop_assert_eq!(Haler::sum(all).unwrap(), Haler(0)); + } + + #[test] + fn sums_are_order_independent(mut xs in prop::collection::vec(-BIG..BIG, 0..50)) { + let a = Haler::sum(xs.iter().copied().map(Haler)).unwrap(); + xs.reverse(); + let b = Haler::sum(xs.iter().copied().map(Haler)).unwrap(); + prop_assert_eq!(a, b); + } + + #[test] + fn czk_text_round_trips(h in -BIG..BIG) { + let text = Haler(h).to_czk(); + prop_assert_eq!(Haler::parse_czk(&text).unwrap(), Haler(h)); + } +} + +#[test] +fn overflow_is_an_error_never_a_wrap() { + assert_eq!(Haler(i64::MAX).checked_add(Haler(1)), Err(MoneyError::Overflow)); + assert_eq!(Haler(i64::MIN).checked_sub(Haler(1)), Err(MoneyError::Overflow)); + assert_eq!(Haler(i64::MIN).checked_neg(), Err(MoneyError::Overflow)); + assert_eq!(Haler::sum([Haler(i64::MAX), Haler(1)]), Err(MoneyError::Overflow)); +} + +#[test] +fn split_rejects_no_weight() { + assert_eq!(split(Haler(100), &[]), Err(MoneyError::NoWeight)); + assert_eq!(split(Haler(100), &[0, 0]), Err(MoneyError::NoWeight)); +} + +#[test] +fn split_known_cases() { + // 100,00 Kč in three: the first share takes the leftover haléř. + assert_eq!(split(Haler(10_000), &[1, 1, 1]).unwrap(), vec![Haler(3_334), Haler(3_333), Haler(3_333)]); + // A refund (negative) splits the same way, mirrored. + assert_eq!(split(Haler(-10_000), &[1, 1, 1]).unwrap(), vec![Haler(-3_334), Haler(-3_333), Haler(-3_333)]); + // Weighted 2:1. + assert_eq!(split(Haler(1_000), &[2, 1]).unwrap(), vec![Haler(667), Haler(333)]); +} + +#[test] +fn czk_text() { + assert_eq!(Haler(-123_450).to_czk(), "-1 234,50"); + assert_eq!(Haler(5).to_czk(), "0,05"); + assert_eq!(Haler(100_000_000).to_czk(), "1 000 000,00"); + assert_eq!(Haler::parse_czk("1234,5").unwrap(), Haler(123_450)); + assert_eq!(Haler::parse_czk("12").unwrap(), Haler(1_200)); + assert_eq!(Haler::parse_czk("-0,01").unwrap(), Haler(-1)); + for bad in ["", "-", "1,234", "1.5.2", "abc", "1,", ",5", "1e3", "١٢", "99999999999999999999"] { + assert!(Haler::parse_czk(bad).is_err(), "{bad:?} must be refused"); + } +} diff --git a/crates/fiscus-ledger/tests/no_float.rs b/crates/fiscus-ledger/tests/no_float.rs new file mode 100644 index 0000000..28c69a5 --- /dev/null +++ b/crates/fiscus-ledger/tests/no_float.rs @@ -0,0 +1,40 @@ +//! Mandatory test 1 (b): no floating-point type appears anywhere in the core. Money, dates, matching, +//! subscriptions and the forecast are all integers, so the whole workspace is scanned. + +use std::path::{Path, PathBuf}; + +fn rust_files(dir: &Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + if path.file_name().is_some_and(|n| n == "target") { + continue; + } + rust_files(&path, out); + } else if path.extension().is_some_and(|e| e == "rs") { + out.push(path); + } + } +} + +#[test] +fn no_float_type_in_any_source_file() { + let crates = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap(); + let mut files = Vec::new(); + rust_files(crates, &mut files); + assert!(files.len() > 10, "the scan found too few files: {}", files.len()); + + // Spelled apart so this file does not match itself. + let banned = [concat!("f", "32"), concat!("f", "64")]; + let mut hits = Vec::new(); + for file in &files { + let text = std::fs::read_to_string(file).unwrap(); + for (n, line) in text.lines().enumerate() { + let words = line.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')); + if words.into_iter().any(|w| banned.contains(&w)) { + hits.push(format!("{}:{}: {}", file.display(), n + 1, line.trim())); + } + } + } + assert!(hits.is_empty(), "floating point in the core:\n{}", hits.join("\n")); +} diff --git a/crates/fiscus-ledger/tests/replay.rs b/crates/fiscus-ledger/tests/replay.rs new file mode 100644 index 0000000..93d6401 --- /dev/null +++ b/crates/fiscus-ledger/tests/replay.rs @@ -0,0 +1,129 @@ +//! Mandatory test 4: derived state is a pure function of the log. Delete it, rebuild it from the log, and +//! the bytes are identical, however it was built. + +use fiscus_ledger::import::{plan_import, StatementLine}; +use fiscus_ledger::{Date, Decision, Event, EventBody, Haler, State, Timestamp}; + +fn d(s: &str) -> Date { + s.parse().unwrap() +} + +/// A month of everything: captures, a statement, hand-added cash, fixes, rules, budgets, a trial, decisions, +/// and a few events that must be rejected. +fn sample_log() -> Vec { + let mut n = 0u64; + let mut id = || { + n += 1; + format!("e{n:04}") + }; + let mut log = Vec::new(); + let push = |log: &mut Vec, id: String, body: EventBody| { + let at = Timestamp(1_790_000_000_000 + log.len() as i64 * 1000); + log.push(Event::new(id, at, body)); + }; + push(&mut log, id(), EventBody::BudgetCreated { budget: "b-home".into(), name: "Home".into(), limit: Haler(2_000_000) }); + push(&mut log, id(), EventBody::BudgetCreated { budget: "b-fun".into(), name: "Fun".into(), limit: Haler(300_000) }); + push(&mut log, id(), EventBody::BudgetLimitSet { budget: "b-fun".into(), limit: Haler(350_000) }); + push( + &mut log, + id(), + EventBody::PaymentCaptured { payment: "p-cap1".into(), amount: Haler(-12_900), date: d("2026-10-02"), merchant: "ALBERT 1234".into(), card: Some("Visa".into()) }, + ); + push( + &mut log, + id(), + EventBody::PaymentAdded { payment: "p-cash".into(), amount: Haler(-8_000), date: d("2026-10-04"), merchant: "Trh".into(), category: Some("groceries".into()), note: Some("market".into()) }, + ); + let lines: Vec = [ + (-12_900, "2026-10-03", "Albert"), + (-49_900, "2026-10-05", "PAYPAL *SPOTIFY"), + (-100, "2026-10-06", "NETFLIX.COM"), + (3_500_000, "2026-10-10", "Mzda"), + ] + .iter() + .map(|(a, date, m)| StatementLine { + bank: "test".into(), + account: "1/0000".into(), + booked: d(date), + amount: Haler(*a), + merchant: (*m).into(), + counterparty: None, + variable_symbol: None, + message: None, + bank_ref: None, + }) + .collect(); + let mut state = State::replay(&log); + let mut k = 0u64; + let plan = plan_import(&state, &lines, &mut || { + k += 1; + format!("imp{k:03}") + }, Timestamp(1_790_000_100_000)); + for e in plan.events.iter().chain(&plan.confirmations) { + state.apply(e); + log.push(e.clone()); + } + push(&mut log, id(), EventBody::RuleCreated { rule: "r1".into(), merchant_key: "spotify".into(), category: "subscriptions".into() }); + push(&mut log, id(), EventBody::PaymentCategorised { payment: "p-cap1".into(), category: "groceries".into() }); + push(&mut log, id(), EventBody::PaymentAssigned { payment: "p-cash".into(), budget: "b-fun".into() }); + push(&mut log, id(), EventBody::PaymentTrialMarked { payment: "imp003".into(), ends: d("2026-11-06") }); + push(&mut log, id(), EventBody::SubscriptionDecided { subscription: "spotify".into(), decision: Decision::Keep, amount: Haler(49_900), on: d("2026-10-20") }); + // To be rejected, deterministically. + push(&mut log, id(), EventBody::PaymentAssigned { payment: "p-nope".into(), budget: "b-fun".into() }); + push(&mut log, id(), EventBody::BudgetCreated { budget: "b-fun".into(), name: "Again".into(), limit: Haler(1) }); + push(&mut log, id(), EventBody::PaymentAdded { payment: "p-zero".into(), amount: Haler(0), date: d("2026-10-04"), merchant: "x".into(), category: None, note: None }); + let dup = log[3].clone(); + log.push(dup); // the same event twice (a sync replay) + log +} + +#[test] +fn rebuild_from_the_log_is_byte_identical() { + let log = sample_log(); + + // 1. Built incrementally, saved, "deleted". + let mut live = State::default(); + for e in &log { + live.apply(e); + } + let saved = serde_json::to_vec(&live).unwrap(); + drop(live); + + // 2. Rebuilt in one go from the log. + let rebuilt = State::replay(&log); + assert_eq!(serde_json::to_vec(&rebuilt).unwrap(), saved); + + // 3. Rebuilt from the log after it went through its serialised form (what the app stores). + let stored = serde_json::to_vec(&log).unwrap(); + let reloaded: Vec = serde_json::from_slice(&stored).unwrap(); + assert_eq!(serde_json::to_vec(&State::replay(&reloaded)).unwrap(), saved); + + // 4. The derived views are byte-identical too. + assert_eq!( + serde_json::to_vec(&State::replay(&log).effective_payments()).unwrap(), + serde_json::to_vec(&rebuilt.effective_payments()).unwrap() + ); + + // The bad events were rejected, and the right ones. + assert_eq!(rebuilt.rejected.len(), 4, "{:#?}", rebuilt.rejected); +} + +#[test] +fn the_state_says_what_the_log_says() { + let s = State::replay(&sample_log()); + let pays = s.effective_payments(); + // cap1 + its line are one; cash; spotify; netflix check; salary. + assert_eq!(pays.len(), 5); + let albert = pays.iter().find(|p| p.merchant_key == "albert").unwrap(); + assert_eq!(albert.category.as_deref(), Some("groceries")); + assert!(albert.line.is_some() && albert.captured.is_some()); + let spotify = pays.iter().find(|p| p.merchant_key == "spotify").unwrap(); + assert_eq!(spotify.category.as_deref(), Some("subscriptions"), "the rule applies to earlier payments"); + let cash = pays.iter().find(|p| p.id == "p-cash").unwrap(); + assert_eq!(cash.budget.as_deref(), Some("b-fun")); + assert_eq!(spotify.budget.as_deref(), Some("b-home"), "the first budget is the default"); + assert_eq!(s.budgets["b-fun"].limit, Haler(350_000)); + // Money in = money on the statement + hand-added cash. + let total = Haler::sum(pays.iter().map(|p| p.amount)).unwrap(); + assert_eq!(total, Haler(-12_900 - 49_900 - 100 + 3_500_000 - 8_000)); +}