diff --git a/crates/fiscus-capture/tests/notification.rs b/crates/fiscus-capture/tests/notification.rs new file mode 100644 index 0000000..6b995d0 --- /dev/null +++ b/crates/fiscus-capture/tests/notification.rs @@ -0,0 +1,133 @@ +//! Day-2 mandatory test: Android bank notifications. Every real fixture parses; a notification from an app +//! the person did not select is never read; an unknown format is ignored, never guessed. +//! +//! The registry has no templates until real samples exist, so the engine is tested here with SYNTHETIC +//! templates that live only in this file. They are not any bank's format. + +use fiscus_capture::notification::{recognise, recognise_with, Recognised, Template, TEMPLATES}; +use fiscus_ledger::{Date, Haler, Timestamp}; +use serde::Deserialize; +use std::path::{Path, PathBuf}; + +const APP: &str = "test.synthetic.bank"; + +const SYNTHETIC: &[Template] = &[ + Template { app: APP, bank: "synthetic", title: Some("Card payment"), text: "Paid {amount} at {merchant} with card {card}." }, + Template { app: APP, bank: "synthetic", title: None, text: "{_}: {amount} - {merchant}" }, +]; + +fn day() -> Date { + "2026-11-03".parse().unwrap() +} + +fn at() -> Timestamp { + Timestamp(1_793_711_100_000) +} + +fn run(app: &str, title: &str, text: &str, selected: &[&str]) -> Recognised { + recognise_with(SYNTHETIC, app, title, text, day(), at(), selected) +} + +#[test] +fn a_notification_matching_a_template_is_a_payment() { + match run(APP, "Card payment", "Paid 129,50 Kč at Albert Praha with card *1234.", &[APP]) { + Recognised::Payment(c) => { + assert_eq!(c.amount, Haler(-12_950)); + assert_eq!(c.merchant, "Albert Praha"); + assert_eq!(c.card.as_deref(), Some("*1234")); + assert_eq!((c.date, c.at), (day(), at())); + } + other => panic!("{other:?}"), + } + assert!(matches!(run(APP, "anything", "Debit: 1 234,00 CZK - Shell", &[APP]), Recognised::Payment(c) if c.amount == Haler(-123_400) && c.merchant == "Shell")); +} + +#[test] +fn an_app_that_was_not_selected_is_never_read() { + // Even text that a template would match: the app decides first. + assert_eq!(run(APP, "Card payment", "Paid 129,50 Kč at Albert with card *1234.", &[]), Recognised::NotSelected); + assert_eq!(run(APP, "Card payment", "Paid 129,50 Kč at Albert with card *1234.", &["other.bank"]), Recognised::NotSelected); + assert_eq!(run("com.chat.app", "Card payment", "Paid 129,50 Kč at Albert with card *1234.", &[APP]), Recognised::NotSelected); +} + +#[test] +fn an_unknown_format_is_ignored_never_guessed() { + for (title, text) in [ + ("Card payment", "Paid 129,50 Kč at Albert with card *1234"), // the final full stop is missing + ("Card payment", "Paid around 129,50 Kč at Albert with card *1234."), + ("Card payment", "Paid 129,50 EUR at Albert with card *1234."), + ("Card payment", "Paid 0 Kč at Albert with card *1234."), + ("Balance", "Your balance is 12 000 Kč"), + ("Card payment", ""), + ] { + assert_eq!(run(APP, title, text, &[APP]), Recognised::Unknown, "{text}"); + } + let long = format!("Debit: {} - Shell", "1".repeat(5000)); + assert_eq!(run(APP, "x", &long, &[APP]), Recognised::Unknown); +} + +#[test] +fn an_ambiguous_match_is_unknown() { + // `{_}: {amount} - {merchant}` matches "A: 1 - B: 2 - C" two ways with different amounts. + assert_eq!(run(APP, "x", "A: 1 - B: 2 - C", &[APP]), Recognised::Unknown); +} + +#[test] +fn the_real_registry_is_used_by_recognise() { + // With no templates for an app, a selected app's notification is unknown, never a payment. + for t in TEMPLATES { + assert!(!t.app.is_empty() && !t.bank.is_empty() && !t.text.is_empty()); + } + assert_eq!(recognise(APP, "Card payment", "Paid 129,50 Kč at Albert with card *1234.", day(), at(), &[APP]), Recognised::Unknown); +} + +/// A real, redacted notification and what it must become (`fixtures/notifications//*.json`). +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Sample { + app: String, + title: String, + text: String, + /// `null` for a notification that is not a payment (a balance, a login) and must stay unknown. + expected: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Expected { + amount: i64, + merchant: String, + card: Option, +} + +fn samples() -> Vec { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/notifications"); + let mut out = Vec::new(); + let Ok(banks) = std::fs::read_dir(&root) else { return out }; + for bank in banks.flatten().filter(|e| e.path().is_dir()) { + for f in std::fs::read_dir(bank.path()).unwrap().flatten() { + if f.path().extension().is_some_and(|e| e == "json") { + out.push(f.path()); + } + } + } + out.sort(); + out +} + +#[test] +fn every_real_fixture_parses_to_what_it_must() { + let all = samples(); + eprintln!("notification fixtures: {}", all.len()); + for path in all { + let s: Sample = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + let got = recognise(&s.app, &s.title, &s.text, day(), at(), &[s.app.as_str()]); + match (&s.expected, got) { + (None, Recognised::Unknown) => {} + (Some(e), Recognised::Payment(c)) => { + assert_eq!((c.amount, c.merchant.as_str(), c.card.as_deref()), (Haler(e.amount), e.merchant.as_str(), e.card.as_deref()), "{}", path.display()); + } + (_, got) => panic!("{}: {got:?}", path.display()), + } + } +} diff --git a/crates/fiscus-capture/tests/shortcut.rs b/crates/fiscus-capture/tests/shortcut.rs new file mode 100644 index 0000000..caf3424 --- /dev/null +++ b/crates/fiscus-capture/tests/shortcut.rs @@ -0,0 +1,92 @@ +//! Day-2 mandatory test (the inbox's half in the core): the iPhone Shortcut post is hostile input. A malformed, +//! oversized or ambiguous body is an error with a reason, never a partial payment. + +use fiscus_capture::shortcut::{parse, CaptureError, MAX_BODY}; +use fiscus_ledger::{Date, Haler, Timestamp}; +use proptest::prelude::*; + +/// 2026-11-03T13:05:00Z in milliseconds. +const AT: i64 = 1_793_711_100_000; + +fn post(amount: &str) -> String { + format!(r#"{{"amount":{amount},"merchant":"ALBERT HYPERMARKET","card":"Apple Card","time":"2026-11-03T14:05:00+01:00"}}"#) +} + +#[test] +fn a_good_post_becomes_one_outflow() { + let c = parse(post("129.5").as_bytes()).unwrap(); + assert_eq!(c.amount, Haler(-12_950)); + assert_eq!(c.merchant, "ALBERT HYPERMARKET"); + assert_eq!(c.card.as_deref(), Some("Apple Card")); + assert_eq!(c.date, "2026-11-03".parse::().unwrap()); + // 14:05 at +01:00 is 13:05 UTC. + assert_eq!(c.at, Timestamp(AT)); +} + +#[test] +fn the_amount_forms_shortcuts_writes_are_read_from_text_never_as_a_float() { + for (text, want) in [ + ("129", 12_900), + ("129.00", 12_900), + ("0.1", 10), + (r#""129,50""#, 12_950), + (r#""129,50 Kč""#, 12_950), + (r#""Kč 129,50""#, 12_950), + (r#""CZK 1 234,50""#, 123_450), + ("\"1\u{a0}234,50\u{a0}Kč\"", 123_450), + ("\"1\u{202f}234,50 CZK\"", 123_450), + ] { + assert_eq!(parse(post(text).as_bytes()).map(|c| c.amount), Ok(Haler(-want)), "{text}"); + } + for text in ["0", "-129", "1e3", "129.555", "\"\"", "\"abc\"", "\"$129\"", "\"129 EUR\"", "null", "true", "[129]", "99999999999"] { + assert_eq!(parse(post(text).as_bytes()).map(|c| c.amount), Err(CaptureError::Amount), "{text}"); + } +} + +#[test] +fn every_field_is_checked() { + let ok = r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z"}"#; + assert!(parse(ok.as_bytes()).is_ok()); + let cases: &[(&str, CaptureError)] = &[ + (r#"{"merchant":"M","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Malformed), + (r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z","extra":1}"#, CaptureError::Malformed), + (r#"{"amount":1,"amount":2,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Malformed), + (r#"{"amount":1,"merchant":"","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Merchant), + (r#"{"amount":1,"merchant":"a\u0000b","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Merchant), + (r#"{"amount":1,"merchant":"M","card":"a\nb","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Card), + (r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03 14:05"}"#, CaptureError::Time), + (r#"{"amount":1,"merchant":"M","card":"","time":"2026-02-30T14:05:00Z"}"#, CaptureError::Time), + (r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T24:05:00Z"}"#, CaptureError::Time), + (r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00"}"#, CaptureError::Time), + (r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z","currency":"EUR"}"#, CaptureError::Currency), + (r#"[1,2]"#, CaptureError::Malformed), + ("", CaptureError::Malformed), + ]; + for (body, want) in cases { + assert_eq!(parse(body.as_bytes()).err().as_ref(), Some(want), "{body}"); + } + let long = format!(r#"{{"amount":1,"merchant":"{}","card":"","time":"2026-11-03T14:05:00Z"}}"#, "m".repeat(201)); + assert_eq!(parse(long.as_bytes()).err(), Some(CaptureError::Merchant)); + assert!(parse(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z","currency":"CZK"}"#.as_bytes()).is_ok()); +} + +#[test] +fn an_oversized_body_is_refused_before_parsing() { + let mut big = post("1").into_bytes(); + big.resize(MAX_BODY + 1, b' '); + assert_eq!(parse(&big).err(), Some(CaptureError::TooLarge)); +} + +proptest! { + #[test] + fn random_bytes_never_panic_and_never_half_parse(bytes in proptest::collection::vec(any::(), 0..600)) { + let _ = parse(&bytes); + } + + #[test] + fn every_truncation_of_a_good_post_is_an_error(cut in 0usize..90) { + let full = post("\"129,50 Kč\""); + let cut = cut.min(full.len() - 1); + prop_assert!(parse(&full.as_bytes()[..cut]).is_err()); + } +} diff --git a/crates/fiscus-insight/tests/household.rs b/crates/fiscus-insight/tests/household.rs new file mode 100644 index 0000000..a1cb4bc --- /dev/null +++ b/crates/fiscus-insight/tests/household.rs @@ -0,0 +1,31 @@ +//! Day 2: household duplicates ("you both pay Spotify"), only from names members chose to share. + +use fiscus_insight::household::{household_duplicates, Duplicate}; + +fn names(v: &[&str]) -> Vec { + v.iter().map(|s| s.to_string()).collect() +} + +#[test] +fn two_members_paying_the_same_service_is_a_duplicate() { + let shared = vec![ + ("mark".to_string(), names(&["PAYPAL *SPOTIFY", "Netflix.com", "O2 Czech"])), + ("jana".to_string(), names(&["Spotify AB", "Netflix"])), + ("kid".to_string(), names(&["Spotify"])), + ]; + let d = household_duplicates(&shared); + assert_eq!( + d, + vec![ + Duplicate { key: "netflix".into(), members: vec!["jana".into(), "mark".into()] }, + Duplicate { key: "spotify".into(), members: vec!["jana".into(), "kid".into(), "mark".into()] }, + ] + ); +} + +#[test] +fn one_member_alone_or_nobody_sharing_is_nothing() { + assert!(household_duplicates(&[]).is_empty()); + let one = vec![("mark".to_string(), names(&["Spotify", "spotify", "PAYPAL *SPOTIFY"]))]; + assert!(household_duplicates(&one).is_empty(), "the same member twice is not a duplicate"); +} diff --git a/crates/fiscus-ledger/tests/pay.rs b/crates/fiscus-ledger/tests/pay.rs new file mode 100644 index 0000000..14c9c76 --- /dev/null +++ b/crates/fiscus-ledger/tests/pay.rs @@ -0,0 +1,99 @@ +//! Day-2 mandatory test: QR Platba. Generated SPAYD strings match the format, and only valid Czech accounts +//! get one. + +use fiscus_ledger::pay::{spayd, Iban, PayError}; +use fiscus_ledger::Haler; + +const IBAN: &str = "CZ6508000000192000145399"; + +#[test] +fn an_iban_is_checked_by_mod_97() { + assert_eq!(Iban::parse(IBAN).unwrap().as_str(), IBAN); + assert_eq!(Iban::parse("cz65 0800 0000 1920 0014 5399").unwrap().as_str(), IBAN); + for bad in [ + "CZ6608000000192000145399", // check digits + "CZ650800000019200014539", // too short + "CZ65080000001920001453991", // too long + "SK3112000000198742637541", // valid, but not Czech + "CZ65 0800 0000 1920 0014 539X", + "", + ] { + assert!(Iban::parse(bad).is_err(), "{bad}"); + } +} + +#[test] +fn a_czech_account_number_becomes_its_iban() { + assert_eq!(Iban::parse("19-2000145399/0800").unwrap().as_str(), IBAN); + assert_eq!(Iban::parse("2000145399/0800").unwrap().as_str(), "CZ7908000000002000145399"); + for bad in [ + "19-2000145398/0800", // the number's mod 11 + "18-2000145399/0800", // the prefix's mod 11 + "2000145399/080", + "2000145399", + "1234567-2000145399/0800", + ] { + assert!(Iban::parse(bad).is_err(), "{bad}"); + } +} + +/// The SPAYD 1.0 grammar for what Fiscus writes: `SPD*1.0` then `KEY:value` pairs separated by `*`, values +/// without a raw `*`. +fn well_formed(s: &str) -> bool { + let mut parts = s.split('*'); + if parts.next() != Some("SPD") || parts.next() != Some("1.0") { + return false; + } + let mut keys = Vec::new(); + for p in parts { + let Some((k, v)) = p.split_once(':') else { return false }; + if v.is_empty() || !k.bytes().all(|b| b.is_ascii_uppercase() || b == b'-') { + return false; + } + keys.push(k); + } + keys.first() == Some(&"ACC") && keys.contains(&"AM") && keys.contains(&"CC") +} + +#[test] +fn spayd_strings_match_the_format() { + let iban = Iban::parse(IBAN).unwrap(); + let s = spayd(&iban, Haler(45_000), Some("Marek"), "Pizza, 2.11.", Some("123")).unwrap(); + assert_eq!(s, "SPD*1.0*ACC:CZ6508000000192000145399*AM:450.00*CC:CZK*RN:Marek*MSG:Pizza, 2.11.*X-VS:123"); + assert!(well_formed(&s)); + for amount in [1, 99, 100, 123_456, 999_999_999] { + let s = spayd(&iban, Haler(amount), None, "x", None).unwrap(); + assert!(well_formed(&s), "{s}"); + let am = s.split('*').find_map(|p| p.strip_prefix("AM:")).unwrap(); + assert_eq!(am, format!("{}.{:02}", amount / 100, amount % 100)); + } +} + +#[test] +fn a_star_in_a_text_never_breaks_the_string_and_texts_are_cut_to_size() { + let iban = Iban::parse(IBAN).unwrap(); + let s = spayd(&iban, Haler(100), Some("A*B"), "1*2", None).unwrap(); + assert!(s.contains("RN:A%2AB") && s.contains("MSG:1%2A2"), "{s}"); + assert!(well_formed(&s)); + let long = "ž".repeat(100); + let s = spayd(&iban, Haler(100), Some(&long), &long, None).unwrap(); + let msg = s.split('*').find_map(|p| p.strip_prefix("MSG:")).unwrap(); + let rn = s.split('*').find_map(|p| p.strip_prefix("RN:")).unwrap(); + assert_eq!((msg.chars().count(), rn.chars().count()), (60, 35)); + // `%2A` is never cut in half. + let s = spayd(&iban, Haler(100), None, &"*".repeat(30), None).unwrap(); + let msg = s.split('*').find_map(|p| p.strip_prefix("MSG:")).unwrap(); + assert!(msg.len() <= 60 && msg.len() % 3 == 0, "{msg}"); +} + +#[test] +fn what_cannot_be_paid_is_an_error() { + let iban = Iban::parse(IBAN).unwrap(); + assert_eq!(spayd(&iban, Haler(0), None, "x", None), Err(PayError::Amount)); + assert_eq!(spayd(&iban, Haler(-100), None, "x", None), Err(PayError::Amount)); + assert_eq!(spayd(&iban, Haler(1_000_000_000), None, "x", None), Err(PayError::Amount)); + for vs in ["", "12345678901", "12a"] { + assert_eq!(spayd(&iban, Haler(100), None, "x", Some(vs)), Err(PayError::VariableSymbol), "{vs}"); + } + assert_eq!(spayd(&iban, Haler(100), None, "a\nb", None), Err(PayError::Text)); +} diff --git a/crates/fiscus-ledger/tests/sharing.rs b/crates/fiscus-ledger/tests/sharing.rs new file mode 100644 index 0000000..7c9d5f3 --- /dev/null +++ b/crates/fiscus-ledger/tests/sharing.rs @@ -0,0 +1,110 @@ +//! Day 2: what a shared budget's log holds. `payment.shared` carries the effective payment and nothing of +//! its origin's details; the budget's members see it and can split it; unsharing takes it out again. + +use fiscus_ledger::share::shared_payment; +use fiscus_ledger::split::Share; +use fiscus_ledger::{Date, Event, EventBody, Glyph, 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 personal() -> Vec { + vec![ + ev("e1", EventBody::BudgetCreated { budget: "b-home".into(), name: "Home".into(), limit: Haler(1_000_000) }), + ev("e2", EventBody::BudgetCreated { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(500_000) }), + ev( + "e3", + EventBody::PaymentCaptured { + payment: "p1".into(), + amount: Haler(-45_000), + date: d("2026-11-02"), + merchant: "Pension Lipno".into(), + card: Some("Visa 1234".into()), + }, + ), + ev("e4", EventBody::PaymentCategorised { payment: "p1".into(), category: "travel".into() }), + ev("e5", EventBody::PaymentAssigned { payment: "p1".into(), budget: "b-trip".into() }), + ev( + "e6", + EventBody::PaymentAdded { + payment: "p2".into(), + amount: Haler(-12_000), + date: d("2026-11-02"), + merchant: "Lekarna".into(), + category: None, + note: Some("private".into()), + }, + ), + ] +} + +#[test] +fn shared_payment_is_made_only_for_a_payment_in_that_budget() { + let s = State::replay(&personal()); + let body = shared_payment(&s, "p1", "b-trip").expect("p1 is in the trip budget"); + assert_eq!( + body, + EventBody::PaymentShared { + payment: "p1".into(), + budget: "b-trip".into(), + amount: Haler(-45_000), + date: d("2026-11-02"), + merchant: "Pension Lipno".into(), + category: Some("travel".into()), + glyph: Glyph::Captured, + } + ); + let json = serde_json::to_string(&body).unwrap(); + assert!(!json.contains("Visa") && !json.contains("1234"), "the card stays home: {json}"); + assert!(shared_payment(&s, "p2", "b-trip").is_none(), "p2 is in the default budget, not the trip"); + assert!(shared_payment(&s, "p1", "b-home").is_none()); + assert!(shared_payment(&s, "nope", "b-trip").is_none()); +} + +fn shared_log() -> Vec { + let s = State::replay(&personal()); + vec![ + ev("g1", EventBody::BudgetCreated { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(500_000) }), + ev("g2", shared_payment(&s, "p1", "b-trip").unwrap()), + ] +} + +#[test] +fn members_see_the_shared_payment_in_the_budget() { + let s = State::replay(&shared_log()); + assert!(s.rejected.is_empty(), "{:?}", s.rejected); + let p = s.effective_payment("p1").unwrap(); + assert_eq!((p.amount, p.glyph, p.budget.as_deref(), p.category.as_deref()), (Haler(-45_000), Glyph::Captured, Some("b-trip"), Some("travel"))); + assert_eq!(p.card, None); +} + +#[test] +fn a_shared_payment_can_be_split_and_unshared_until_it_is() { + let mut log = shared_log(); + log.push(ev("g3", EventBody::PaymentUnshared { payment: "p1".into(), budget: "b-trip".into() })); + let s = State::replay(&log); + assert!(s.rejected.is_empty() && s.effective_payment("p1").is_none(), "unshared: gone from the budget"); + + let mut log = shared_log(); + let shares = vec![ + Share { person: "me".into(), name: "Me".into(), amount: Haler(-22_500) }, + Share { person: "anna".into(), name: "Anna".into(), amount: Haler(-22_500) }, + ]; + log.push(ev("g3", EventBody::SplitCreated { split: "s1".into(), payment: "p1".into(), payer: "me".into(), shares })); + log.push(ev("g4", EventBody::PaymentUnshared { payment: "p1".into(), budget: "b-trip".into() })); + let s = State::replay(&log); + assert_eq!(s.rejected.len(), 1, "a split payment stays shared"); + assert!(s.effective_payment("p1").is_some()); +} + +#[test] +fn sharing_into_a_budget_the_log_does_not_have_is_rejected() { + let s = State::replay(&personal()); + let s2 = State::replay(&[ev("g2", shared_payment(&s, "p1", "b-trip").unwrap())]); + assert_eq!(s2.rejected.len(), 1); +} diff --git a/crates/fiscus-ledger/tests/splits.rs b/crates/fiscus-ledger/tests/splits.rs new file mode 100644 index 0000000..5286c0b --- /dev/null +++ b/crates/fiscus-ledger/tests/splits.rs @@ -0,0 +1,211 @@ +//! Day-2 mandatory tests: splits always sum exactly to the total and the remainder rule is deterministic; +//! `split.created` / `split.settled` refuse anything that does not add up; a share link shows exactly one +//! person's share, and nothing once it is settled, expired or unknown. + +use fiscus_ledger::pay::Iban; +use fiscus_ledger::split::{split_equal, Person, Share}; +use fiscus_ledger::{Date, Event, EventBody, Haler, Settlement, State, Timestamp}; +use proptest::prelude::*; + +fn d(s: &str) -> Date { + s.parse().unwrap() +} + +fn people(ids: &[&str]) -> Vec { + ids.iter().map(|i| Person { id: (*i).into(), name: format!("Name {i}") }).collect() +} + +fn ev(id: &str, body: EventBody) -> Event { + Event::new(id, Timestamp(0), body) +} + +fn paid(amount: i64) -> Vec { + vec![ev( + "e-pay", + EventBody::PaymentAdded { + payment: "p1".into(), + amount: Haler(amount), + date: d("2026-11-02"), + merchant: "Pizzeria Uno".into(), + category: None, + note: None, + }, + )] +} + +fn created(shares: Vec) -> Event { + ev("e-split", EventBody::SplitCreated { split: "s1".into(), payment: "p1".into(), payer: "me".into(), shares }) +} + +fn share(person: &str, amount: i64) -> Share { + Share { person: person.into(), name: format!("Name {person}"), amount: Haler(amount) } +} + +fn rejected_reason(log: &[Event]) -> Option { + State::replay(log).rejected.last().map(|r| r.reason.clone()) +} + +proptest! { + #[test] + fn shares_always_sum_exactly_to_the_total(total in -10_000_000_000i64..10_000_000_000, n in 1usize..12) { + let ids: Vec = (0..n).map(|i| format!("p{i}")).collect(); + let ps: Vec = ids.iter().map(|i| Person { id: i.clone(), name: i.clone() }).collect(); + let shares = split_equal(Haler(total), &ps).unwrap(); + prop_assert_eq!(shares.len(), n); + prop_assert_eq!(shares.iter().map(|s| s.amount.0).sum::(), total); + let max = shares.iter().map(|s| s.amount.0.abs()).max().unwrap(); + let min = shares.iter().map(|s| s.amount.0.abs()).min().unwrap(); + prop_assert!(max - min <= 1, "equal shares differ by at most one haléř"); + } + + #[test] + fn the_remainder_does_not_depend_on_the_order_people_were_picked(total in -1_000_000i64..1_000_000, seed in any::()) { + let ids = ["anna", "bara", "cyril", "dana", "eva"]; + let mut shuffled = ids.to_vec(); + // A deterministic shuffle from the seed. + let mut s = seed; + for i in (1..shuffled.len()).rev() { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + shuffled.swap(i, (s >> 33) as usize % (i + 1)); + } + prop_assert_eq!(split_equal(Haler(total), &people(&ids)).unwrap(), split_equal(Haler(total), &people(&shuffled)).unwrap()); + } +} + +#[test] +fn the_leftover_hal_go_to_the_first_people_by_id() { + let shares = split_equal(Haler(-100), &people(&["cyril", "anna", "bara"])).unwrap(); + let got: Vec<(&str, i64)> = shares.iter().map(|s| (s.person.as_str(), s.amount.0)).collect(); + assert_eq!(got, vec![("anna", -34), ("bara", -33), ("cyril", -33)]); +} + +#[test] +fn a_person_picked_twice_counts_once_and_nobody_is_an_error() { + let shares = split_equal(Haler(-90), &people(&["anna", "bara", "anna"])).unwrap(); + assert_eq!(shares.len(), 2); + assert!(split_equal(Haler(-90), &[]).is_err()); +} + +#[test] +fn a_split_that_adds_up_is_accepted() { + let mut log = paid(-1000); + log.push(created(vec![share("me", -334), share("anna", -333), share("bara", -333)])); + let s = State::replay(&log); + assert!(s.rejected.is_empty(), "{:?}", s.rejected); + assert_eq!(s.splits["s1"].shares.len(), 3); +} + +#[test] +fn a_split_that_does_not_add_up_is_rejected() { + for (shares, why) in [ + (vec![share("me", -500), share("anna", -499)], "sum"), + (vec![share("me", -1001), share("anna", 1)], "sign"), + (vec![share("me", -500), share("me", -500)], "twice"), + (vec![share("anna", -500), share("bara", -500)], "payer"), + (vec![], "nobody"), + ] { + let mut log = paid(-1000); + log.push(created(shares)); + let s = State::replay(&log); + assert_eq!(s.rejected.len(), 1, "{why}: {:?}", s.rejected); + assert!(s.splits.is_empty(), "{why}: half-applied"); + } + // A payment in (money received) is not split, and a split needs its payment. + let mut log = paid(1000); + log.push(created(vec![share("me", 500), share("anna", 500)])); + assert!(rejected_reason(&log).is_some()); + assert!(rejected_reason(&[created(vec![share("me", -1)])]).is_some()); +} + +#[test] +fn settling_is_once_per_person_and_never_the_payer() { + let mut log = paid(-1000); + log.push(created(vec![share("me", -500), share("anna", -500)])); + let settle = |id: &str, person: &str| ev(id, EventBody::SplitSettled { split: "s1".into(), person: person.into(), how: Settlement::Qr }); + log.push(settle("e-s1", "anna")); + assert!(State::replay(&log).rejected.is_empty()); + for (id, person) in [("e-s2", "anna"), ("e-s3", "me"), ("e-s4", "cyril")] { + let mut l = log.clone(); + l.push(settle(id, person)); + assert!(rejected_reason(&l).is_some(), "{person} settled"); + } + assert!(State::replay(&log).splits["s1"].settled.contains_key("anna")); +} + +const LINK: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90"; +const OTHER: &str = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + +fn with_link() -> Vec { + let mut log = paid(-1000); + log.push(created(vec![share("me", -334), share("anna", -333), share("bara", -333)])); + log.push(ev("e-acc", EventBody::AccountSet { iban: "CZ6508000000192000145399".into(), name: "Marek Novak".into() })); + log.push(ev( + "e-link", + EventBody::ShareLinkCreated { link: LINK.into(), split: "s1".into(), person: "anna".into(), expires: d("2026-12-02") }, + )); + log +} + +#[test] +fn a_share_link_shows_exactly_one_persons_share() { + let s = State::replay(&with_link()); + assert!(s.rejected.is_empty(), "{:?}", s.rejected); + let v = s.share_view(LINK, d("2026-11-03")).expect("open"); + assert_eq!(v.name, "Name anna"); + assert_eq!(v.amount, Haler(333)); + assert_eq!(v.merchant, "Pizzeria Uno"); + assert_eq!(v.date, d("2026-11-02")); + assert_eq!(v.spayd.as_deref(), Some("SPD*1.0*ACC:CZ6508000000192000145399*AM:3.33*CC:CZK*RN:Marek Novak*MSG:Pizzeria Uno 2.11.2026")); + // Everything the page can show is in this one struct; serialise it and look for the others. + let all = serde_json::to_string(&v).unwrap(); + for leak in ["bara", "Name me", "334", "-1000", "10,00", "s1", "p1"] { + assert!(!all.contains(leak), "{leak} leaked into {all}"); + } +} + +#[test] +fn a_settled_expired_or_unknown_link_shows_nothing() { + let s = State::replay(&with_link()); + assert!(s.share_view(OTHER, d("2026-11-03")).is_none(), "unknown"); + assert!(s.share_view(LINK, d("2026-12-03")).is_none(), "expired"); + assert!(s.share_view(LINK, d("2026-12-02")).is_some(), "the last day is still open"); + let mut log = with_link(); + log.push(ev("e-set", EventBody::SplitSettled { split: "s1".into(), person: "anna".into(), how: Settlement::Marked })); + assert!(State::replay(&log).share_view(LINK, d("2026-11-03")).is_none(), "settled"); +} + +#[test] +fn a_link_for_the_payer_or_a_stranger_is_rejected() { + for person in ["me", "cyril"] { + let mut log = with_link(); + log.pop(); + log.push(ev( + "e-link", + EventBody::ShareLinkCreated { link: LINK.into(), split: "s1".into(), person: person.into(), expires: d("2026-12-02") }, + )); + assert!(rejected_reason(&log).is_some(), "{person}"); + } + let mut log = with_link(); + log.push(ev("e-link2", EventBody::ShareLinkCreated { link: "short".into(), split: "s1".into(), person: "bara".into(), expires: d("2026-12-02") })); + assert!(rejected_reason(&log).is_some(), "a link is a SHA-256 in hex"); +} + +#[test] +fn the_account_must_be_a_valid_czech_iban() { + assert!(Iban::parse("CZ6508000000192000145399").is_ok()); + let bad = ev("e-acc", EventBody::AccountSet { iban: "CZ6608000000192000145399".into(), name: "X".into() }); + assert!(rejected_reason(&[bad]).is_some()); +} + +#[test] +fn capture_tokens_are_hashes_and_revoke_once() { + let add = ev("e-t1", EventBody::CaptureTokenAdded { token: OTHER.into(), name: "Mark's iPhone".into(), kind: fiscus_ledger::CaptureKind::Iphone }); + let revoke = |id: &str| ev(id, EventBody::CaptureTokenRevoked { token: OTHER.into() }); + let s = State::replay(std::slice::from_ref(&add)); + assert!(s.capture_token_active(OTHER)); + let s = State::replay(&[add.clone(), revoke("e-t2")]); + assert!(!s.capture_token_active(OTHER) && s.rejected.is_empty()); + assert!(rejected_reason(&[add.clone(), revoke("e-t2"), revoke("e-t3")]).is_some()); + let raw = ev("e-t1", EventBody::CaptureTokenAdded { token: "my-secret-token".into(), name: "x".into(), kind: fiscus_ledger::CaptureKind::Android }); + assert!(rejected_reason(&[raw]).is_some(), "only a hash is ever stored"); +}