[ledger] Core: haléře, dates, the event log and apply(), merchant keys and rules, one-to-one matching, import planning

This commit is contained in:
2026-11-03 18:52:36 +01:00
parent da672b132e
commit 6572f31b1d
14 changed files with 1731 additions and 0 deletions
+222
View File
@@ -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);
}
}
+97
View File
@@ -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");
}
}
+40
View File
@@ -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<PathBuf>) {
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"));
}
+129
View File
@@ -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<Event> {
let mut n = 0u64;
let mut id = || {
n += 1;
format!("e{n:04}")
};
let mut log = Vec::new();
let push = |log: &mut Vec<Event>, 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<StatementLine> = [
(-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<Event> = 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));
}