From 8e085bafc39a73658dd18e43a6696e776ea753c3 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 3 Nov 2026 23:27:26 +0100 Subject: [PATCH 1/5] [docs] Capture and sharing: design note for day 2 (events, capture parsing, splits, QR Platba) --- docs/02_capture_sharing.md | 71 ++++++++++++++++++++++++++++++++ fixtures/notifications/README.md | 22 ++++++++++ 2 files changed, 93 insertions(+) create mode 100644 docs/02_capture_sharing.md create mode 100644 fixtures/notifications/README.md diff --git a/docs/02_capture_sharing.md b/docs/02_capture_sharing.md new file mode 100644 index 0000000..e12e8d0 --- /dev/null +++ b/docs/02_capture_sharing.md @@ -0,0 +1,71 @@ +# 02 — Capture, splits, QR Platba, sharing (day 2) + +Written before the code. Everything here is pure, like day 1: no I/O, no clock, no randomness. The app +(Fiscus `docs/02_phones_sharing.md`) moves these events through Fundamentum; the core only defines them, +applies them and checks them. + +## New events (`fiscus-ledger`) + +A **personal log** (your own devices, the Fundamentum *self group*) holds every event. A **shared budget** +is a log of its own (one MLS group): its members see exactly what was put into it, nothing else. + +| Event | Where | Effect | +|:--|:--|:--| +| `payment.shared` | shared budget | a member put one payment into this budget: `payment, budget, amount, date, merchant, category, origin`. Creates the payment in this log, or reassigns it after an unshare | +| `payment.unshared` | shared budget | takes it out again (it stays in the log, unassigned) | +| `split.created` | either | `split, payment, payer, shares: [{person, name, amount}]`. Rejected unless the shares sum **exactly** to the payment's amount, every amount has the payment's sign, people are unique, and the payer is one of them | +| `split.settled` | either | `split, person, how` (`qr`, `marked`). Rejected for an unknown split or person, the payer, or a second settlement | +| `capture.token_added` / `capture.token_revoked` | personal | a phone's capture token: only its SHA-256 (`token`), a `name` and the `kind` (`iphone`, `android`). The token itself lives in Custos | +| `share.link_created` | personal | a share link for one person of one split: only the SHA-256 of the link token, `split`, `person`, `expires` | +| `account.set` | personal | the account for QR Platba (`iban`, `name`); the log is encrypted everywhere it is stored | + +`apply()` stays total: anything that does not fit is recorded in `state.rejected` with the reason. + +### The split rule +`split_equal(total, people)`: the people are **sorted by id and deduplicated first**, then split with +equal weights by the day-1 largest-remainder `split()`. Every device computes the same shares in whatever +order the people were picked, and the shares always sum to the total. The leftover haléře go to the first +people in id order. + +A **share link** is open while its split is not settled for that person and `today <= expires` +(`share_link_open`). The page shows exactly `ShareView { name, amount, merchant, date, spayd }` and nothing else. + +## `fiscus-capture`: what the phones send +Both are **hostile input**. Each yields a `Capture { amount (an outflow, negative), date, merchant, card }` +or a typed error, never a partial payment. + +**The iPhone Shortcut post.** We write the Shortcut, so this is our format, not a bank's. It is a JSON object +with exactly `amount`, `merchant`, `card`, `time`, plus an optional `currency`. Anything else is an error. +- `amount`: a positive number, or a string in the form Shortcuts writes in Czech or English (`129`, + `129,5`, `1 234,50`, `129.00`, optionally `Kč`/`CZK` before or after). It is parsed from its text, never + as a float. `currency`, if present, must be `CZK`. +- `merchant`: 1–200 characters, no control characters. `card`: 0–60 characters. +- `time`: ISO 8601 with an offset (`2026-11-03T14:05:00+01:00`); the payment's date is the local date in it. +- At most 4 KiB. +*(assumption)* Apple's exact `amount` text is checked against the first real post. + +**Android bank notifications.** `recognise(app, title, text, selected)`: +1. If `app` is not one of the bank apps the person selected → `NotSelected`. The listener calls this only for + selected apps; the core checks again. +2. Otherwise each template **for that app** is tried in turn. A template is literal text with `{amount}`, + `{merchant}`, `{card}` and `{_}` holes, matched exactly (no regexes, no fuzziness). +3. No template matches → `Unknown`. The app counts it and shows the count in Settings; it is **never + guessed**. + +**The template registry is empty**: no bank notification samples exist yet. Templates are written only from +real samples in `fixtures/notifications//` (see `fixtures/README.md`). The engine is tested with +synthetic templates that live only in the tests. + +## QR Platba (`fiscus_ledger::pay`) +- `Iban::parse` takes `CZ65 0800 0000 1920 0014 5399` or a Czech account `19-2000145399/0800`. Both checks + are strict: the IBAN's mod-97, and for a Czech account the weighted mod-11 of the prefix and the number. + Only CZ accounts (24 characters). +- `spayd(iban, amount, message, vs)` gives `SPD*1.0*ACC:*AM:*CC:CZK*MSG:[*X-VS:]`. + - The amount must be positive. It is written from haléře with two decimals (`450.00`), never through a float. + - The message is at most 60 characters, and `*` is written as `%2A`. + - The variable symbol is 1–10 digits. + +## Household duplicates (`fiscus-insight`) +`household_duplicates(&[(member, names)])`: the subscription merchant keys two or more members share, each +with its members. It runs only on names members chose to share into the household group (opt-in, asked once). +Nobody's names are read without that. diff --git a/fixtures/notifications/README.md b/fixtures/notifications/README.md new file mode 100644 index 0000000..779410a --- /dev/null +++ b/fixtures/notifications/README.md @@ -0,0 +1,22 @@ +# Bank notification samples (Android) + +Real, **redacted** notifications only, one folder per bank (`fixtures/notifications//`), one JSON file +per notification: + +```json +{ + "app": "cz.example.bank", + "title": "the notification's title, exactly", + "text": "the notification's text, exactly", + "expected": { "amount": -12950, "merchant": "ALBERT", "card": "*1234" } +} +``` + +`expected` is `null` for a notification from the bank app that is not a card payment (a balance, a login, an +incoming transfer); it must stay unknown. `amount` is in haléře, negative for a payment. + +Redact names, card numbers and balances, but keep every other character: spaces, no-break spaces, the +currency sign and the punctuation are exactly what a template is written from. 3–5 payments per bank app, +plus one or two that are not payments. A template (`fiscus-capture/src/notification.rs`, `TEMPLATES`) is +written only from the samples here; a bank app with no samples is unsupported, and its notifications are +counted as unrecognised, never guessed. From b4474f288e07332c31289241778ec6e0c09b98eb Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 3 Nov 2026 23:27:26 +0100 Subject: [PATCH 2/5] [tests] Day 2: splits, share links, sharing boundary, QR Platba, Shortcut posts, bank notifications, household duplicates --- crates/fiscus-capture/tests/notification.rs | 133 ++++++++++++ crates/fiscus-capture/tests/shortcut.rs | 92 +++++++++ crates/fiscus-insight/tests/household.rs | 31 +++ crates/fiscus-ledger/tests/pay.rs | 99 +++++++++ crates/fiscus-ledger/tests/sharing.rs | 110 ++++++++++ crates/fiscus-ledger/tests/splits.rs | 211 ++++++++++++++++++++ 6 files changed, 676 insertions(+) create mode 100644 crates/fiscus-capture/tests/notification.rs create mode 100644 crates/fiscus-capture/tests/shortcut.rs create mode 100644 crates/fiscus-insight/tests/household.rs create mode 100644 crates/fiscus-ledger/tests/pay.rs create mode 100644 crates/fiscus-ledger/tests/sharing.rs create mode 100644 crates/fiscus-ledger/tests/splits.rs 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"); +} From 241c924d2663768c6fc75f41698f3931b3954217 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 3 Nov 2026 23:27:26 +0100 Subject: [PATCH 3/5] [ledger] Sharing: payment.shared/unshared, splits that always add up, share links, capture tokens, account; QR Platba with checked IBAN --- crates/fiscus-ledger/src/event.rs | 51 ++++++ crates/fiscus-ledger/src/lib.rs | 10 +- crates/fiscus-ledger/src/pay.rs | 148 ++++++++++++++++++ crates/fiscus-ledger/src/share.rs | 22 +++ crates/fiscus-ledger/src/split.rs | 34 ++++ crates/fiscus-ledger/src/state.rs | 250 +++++++++++++++++++++++++++++- 6 files changed, 511 insertions(+), 4 deletions(-) create mode 100644 crates/fiscus-ledger/src/pay.rs create mode 100644 crates/fiscus-ledger/src/share.rs create mode 100644 crates/fiscus-ledger/src/split.rs diff --git a/crates/fiscus-ledger/src/event.rs b/crates/fiscus-ledger/src/event.rs index 40184a2..b38a777 100644 --- a/crates/fiscus-ledger/src/event.rs +++ b/crates/fiscus-ledger/src/event.rs @@ -3,6 +3,8 @@ use crate::date::{Date, Timestamp}; use crate::import::StatementLine; use crate::money::Haler; +use crate::split::Share; +use crate::state::Glyph; use serde::{Deserialize, Serialize}; /// Ids are opaque strings the app generates (random, unguessable); the core never makes one up. @@ -10,6 +12,7 @@ pub type EventId = String; pub type PaymentId = String; pub type BudgetId = String; pub type RuleId = String; +pub type SplitId = String; /// A category id, e.g. `groceries` (see [`crate::categories`]). pub type Category = String; @@ -35,6 +38,24 @@ pub enum Decision { Cancel, } +/// How a share of a split was settled. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Settlement { + /// Paid by QR Platba. + Qr, + /// Marked paid by hand (cash, another way). + Marked, +} + +/// Which phone a capture token is for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CaptureKind { + Iphone, + Android, +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "type")] pub enum EventBody { @@ -73,4 +94,34 @@ pub enum EventBody { /// 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 }, + /// A shared budget's log: a member put this payment (as they see it) into the budget. + #[serde(rename = "payment.shared")] + PaymentShared { + payment: PaymentId, + budget: BudgetId, + amount: Haler, + date: Date, + merchant: String, + category: Option, + glyph: Glyph, + }, + /// A shared budget's log: the payment is taken out of the budget again. + #[serde(rename = "payment.unshared")] + PaymentUnshared { payment: PaymentId, budget: BudgetId }, + /// The payment's amount, split among people (see [`crate::split::split_equal`]). + #[serde(rename = "split.created")] + SplitCreated { split: SplitId, payment: PaymentId, payer: String, shares: Vec }, + #[serde(rename = "split.settled")] + SplitSettled { split: SplitId, person: String, how: Settlement }, + /// A phone's capture token: only its SHA-256 in lowercase hex. The token itself lives in Custos. + #[serde(rename = "capture.token_added")] + CaptureTokenAdded { token: String, name: String, kind: CaptureKind }, + #[serde(rename = "capture.token_revoked")] + CaptureTokenRevoked { token: String }, + /// A share link for one person of a split: only the SHA-256 of the link's token, in lowercase hex. + #[serde(rename = "share.link_created")] + ShareLinkCreated { link: String, split: SplitId, person: String, expires: Date }, + /// The account people pay back to by QR Platba. + #[serde(rename = "account.set")] + AccountSet { iban: String, name: String }, } diff --git a/crates/fiscus-ledger/src/lib.rs b/crates/fiscus-ledger/src/lib.rs index ace9378..5420acb 100644 --- a/crates/fiscus-ledger/src/lib.rs +++ b/crates/fiscus-ledger/src/lib.rs @@ -1,5 +1,6 @@ //! 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. +//! it, merchant keys and rules, capture ↔ statement matching, splits and QR Platba. Pure: no I/O, no clock, no +//! randomness. pub mod categories; pub mod date; @@ -8,9 +9,12 @@ pub mod import; pub mod matching; pub mod merchant; pub mod money; +pub mod pay; +pub mod share; +pub mod split; pub mod state; pub use date::{Date, Timestamp}; -pub use event::{BudgetId, Category, Decision, Event, EventBody, EventId, PaymentId}; +pub use event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, Settlement, SplitId}; pub use money::Haler; -pub use state::{EffectivePayment, Glyph, Origin, State}; +pub use state::{EffectivePayment, Glyph, Origin, ShareView, State}; diff --git a/crates/fiscus-ledger/src/pay.rs b/crates/fiscus-ledger/src/pay.rs new file mode 100644 index 0000000..1255907 --- /dev/null +++ b/crates/fiscus-ledger/src/pay.rs @@ -0,0 +1,148 @@ +//! QR Platba: a checked Czech IBAN and the SPAYD 1.0 string a banking app scans. + +use crate::money::Haler; +use std::fmt; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum PayError { + #[error("not a valid Czech account number or IBAN")] + Account, + #[error("the amount must be between 0,01 and 9 999 999,99 CZK")] + Amount, + #[error("a variable symbol is 1-10 digits")] + VariableSymbol, + #[error("a text has control characters")] + Text, +} + +/// A Czech IBAN (`CZ` + 22 digits) whose check digits are right. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Iban(String); + +/// The largest amount QR Platba carries: 9 999 999,99 CZK. +pub const MAX_AMOUNT: Haler = Haler(999_999_999); + +/// The remainder mod 97 of a string of digits and letters (A = 10 … Z = 35), as IBAN check digits use. +fn mod97(s: &str) -> Option { + let mut r: u32 = 0; + for c in s.chars() { + let v = c.to_digit(36)?; + r = if v < 10 { (r * 10 + v) % 97 } else { (r * 100 + v) % 97 }; + } + Some(r) +} + +/// The Czech weighted mod-11 check of an account prefix or number, right-aligned to the weights. +fn mod11(digits: &str, weights: &[u32]) -> bool { + if digits.len() > weights.len() { + return false; + } + let pad = weights.len() - digits.len(); + let sum: u32 = digits.bytes().enumerate().map(|(i, b)| u32::from(b - b'0') * weights[pad + i]).sum(); + sum.is_multiple_of(11) +} + +const PREFIX_WEIGHTS: [u32; 6] = [10, 5, 8, 4, 2, 1]; +const NUMBER_WEIGHTS: [u32; 10] = [6, 3, 7, 9, 10, 5, 8, 4, 2, 1]; + +fn all_digits(s: &str) -> bool { + !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) +} + +impl Iban { + /// `CZ65 0800 0000 1920 0014 5399` (spaces and case do not matter) or a Czech account + /// `[prefix-]number/bank` such as `19-2000145399/0800`. + pub fn parse(text: &str) -> Result { + let t = text.trim(); + if let Some((account, bank)) = t.split_once('/') { + return Iban::from_czech(account.trim(), bank.trim()); + } + let compact: String = t.chars().filter(|c| *c != ' ').collect::().to_ascii_uppercase(); + if compact.len() != 24 || !compact.starts_with("CZ") || !all_digits(&compact[2..]) { + return Err(PayError::Account); + } + let rearranged = format!("{}{}", &compact[4..], &compact[..4]); + if mod97(&rearranged) != Some(1) { + return Err(PayError::Account); + } + // The BBAN inside must itself be a valid Czech account. + let (prefix, number) = (&compact[8..14], &compact[14..]); + if !mod11(prefix, &PREFIX_WEIGHTS) || !mod11(number, &NUMBER_WEIGHTS) { + return Err(PayError::Account); + } + Ok(Iban(compact)) + } + + fn from_czech(account: &str, bank: &str) -> Result { + let (prefix, number) = account.split_once('-').unwrap_or(("", account)); + let ok = (prefix.is_empty() || (all_digits(prefix) && prefix.len() <= 6)) + && all_digits(number) + && (2..=10).contains(&number.len()) + && bank.len() == 4 + && all_digits(bank) + && mod11(prefix, &PREFIX_WEIGHTS) + && mod11(number, &NUMBER_WEIGHTS); + if !ok { + return Err(PayError::Account); + } + let bban = format!("{bank}{prefix:0>6}{number:0>10}"); + let check = 98 - mod97(&format!("{bban}CZ00")).ok_or(PayError::Account)?; + Iban::parse(&format!("CZ{check:02}{bban}")) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for Iban { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +/// A SPAYD text value: `*` written as `%2A`, cut to `max` characters without splitting an escape. +fn text(value: &str, max: usize) -> Result { + if value.chars().any(|c| c.is_control()) { + return Err(PayError::Text); + } + let mut out = String::new(); + let mut count = 0; + for c in value.trim().chars() { + let piece = if c == '*' { "%2A".to_string() } else { c.to_string() }; + let n = piece.chars().count(); + if count + n > max { + break; + } + out.push_str(&piece); + count += n; + } + Ok(out) +} + +/// `SPD*1.0*ACC:*AM:*CC:CZK[*RN:]*MSG:[*X-VS:]`. +/// The amount is positive and written from haléře (`450.00`); the name is cut to 35 characters and the +/// message to 60. +pub fn spayd(iban: &Iban, amount: Haler, name: Option<&str>, message: &str, vs: Option<&str>) -> Result { + if amount.0 <= 0 || amount > MAX_AMOUNT { + return Err(PayError::Amount); + } + let mut s = format!("SPD*1.0*ACC:{}*AM:{}.{:02}*CC:CZK", iban.0, amount.0 / 100, amount.0 % 100); + if let Some(name) = name { + let rn = text(name, 35)?; + if !rn.is_empty() { + s.push_str(&format!("*RN:{rn}")); + } + } + let msg = text(message, 60)?; + if !msg.is_empty() { + s.push_str(&format!("*MSG:{msg}")); + } + if let Some(vs) = vs { + if !all_digits(vs) || vs.len() > 10 { + return Err(PayError::VariableSymbol); + } + s.push_str(&format!("*X-VS:{vs}")); + } + Ok(s) +} diff --git a/crates/fiscus-ledger/src/share.rs b/crates/fiscus-ledger/src/share.rs new file mode 100644 index 0000000..cf89db3 --- /dev/null +++ b/crates/fiscus-ledger/src/share.rs @@ -0,0 +1,22 @@ +//! What a shared budget may receive from a personal log: one payment, as its owner sees it, and only once it +//! is assigned to that budget. Its card, note, statement details, rules and origin events stay home. + +use crate::event::EventBody; +use crate::state::State; + +/// `payment.shared` for `payment` into `budget`, or `None` if that payment is not in that budget. +pub fn shared_payment(state: &State, payment: &str, budget: &str) -> Option { + let p = state.effective_payment(payment)?; + if p.budget.as_deref() != Some(budget) { + return None; + } + Some(EventBody::PaymentShared { + payment: p.id, + budget: budget.into(), + amount: p.amount, + date: p.date, + merchant: p.merchant, + category: p.category, + glyph: p.glyph, + }) +} diff --git a/crates/fiscus-ledger/src/split.rs b/crates/fiscus-ledger/src/split.rs new file mode 100644 index 0000000..ecb6de9 --- /dev/null +++ b/crates/fiscus-ledger/src/split.rs @@ -0,0 +1,34 @@ +//! Splitting one payment among people: shares in haléře that always sum to the payment's amount. + +use crate::money::{split, Haler, MoneyError}; +use serde::{Deserialize, Serialize}; + +/// Someone a payment can be split with: an app user (their id is their Tessera root) or a contact. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Person { + pub id: String, + pub name: String, +} + +/// One person's part of a split. Same sign as the payment (an outflow's shares are negative). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Share { + pub person: String, + pub name: String, + pub amount: Haler, +} + +/// Equal shares. The people are sorted by id and deduplicated first, so every device gets the same shares +/// whatever order they were picked in; the leftover haléře go to the first people in that order (the day-1 +/// largest-remainder [`split`]). +pub fn split_equal(total: Haler, people: &[Person]) -> Result, MoneyError> { + let mut sorted: Vec<&Person> = people.iter().collect(); + sorted.sort_by(|a, b| a.id.cmp(&b.id)); + sorted.dedup_by(|a, b| a.id == b.id); + let amounts = split(total, &vec![1; sorted.len()])?; + Ok(sorted + .into_iter() + .zip(amounts) + .map(|(p, amount)| Share { person: p.id.clone(), name: p.name.clone(), amount }) + .collect()) +} diff --git a/crates/fiscus-ledger/src/state.rs b/crates/fiscus-ledger/src/state.rs index 259467a..bdc1d52 100644 --- a/crates/fiscus-ledger/src/state.rs +++ b/crates/fiscus-ledger/src/state.rs @@ -3,10 +3,12 @@ use crate::categories; use crate::date::Date; -use crate::event::{BudgetId, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId}; +use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId}; use crate::import::StatementLine; use crate::merchant::merchant_key; use crate::money::Haler; +use crate::pay::{spayd, Iban}; +use crate::split::Share; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; @@ -89,6 +91,57 @@ pub struct DecisionRecord { pub seq: u64, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Settled { + pub how: Settlement, + pub seq: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Split { + pub id: SplitId, + pub payment: PaymentId, + pub payer: String, + pub shares: Vec, + /// Person → how they settled. The payer never appears here. + pub settled: BTreeMap, + pub seq: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CaptureToken { + pub name: String, + pub kind: CaptureKind, + pub revoked: bool, + pub seq: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShareLink { + pub split: SplitId, + pub person: String, + pub expires: Date, + pub seq: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Account { + pub iban: String, + pub name: String, +} + +/// Everything a share-link page shows: one person's share of one payment, and how to pay it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShareView { + pub name: String, + /// What they owe, positive. + pub amount: Haler, + pub merchant: String, + pub date: Date, + /// QR Platba, when an account is set. + pub spayd: Option, +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Rejection { pub event: EventId, @@ -110,6 +163,14 @@ pub struct State { pub rules: BTreeMap, /// Subscription key → its decisions, oldest first. pub decisions: BTreeMap>, + /// Payments that came into this log by `payment.shared` (a shared budget's log). + pub shared: BTreeSet, + pub splits: BTreeMap, + /// SHA-256 (hex) of a phone's capture token → the token's record. + pub capture_tokens: BTreeMap, + /// SHA-256 (hex) of a share link's token → the link. + pub share_links: BTreeMap, + pub account: Option, pub rejected: Vec, } @@ -155,6 +216,19 @@ fn opt_text_ok(s: &Option) -> bool { s.as_deref().is_none_or(text_ok) } +fn name_ok(s: &str, max: usize) -> bool { + !s.trim().is_empty() && s.chars().count() <= max && text_ok(s) +} + +fn id_ok(s: &str) -> bool { + !s.is_empty() && s.len() <= 100 && text_ok(s) +} + +/// A SHA-256 in lowercase hex. +fn hash_ok(s: &str) -> bool { + s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + fn latest(a: &Option>, b: Option<&Option>>) -> Option { let b = b.and_then(|b| b.as_ref()); match (a.as_ref(), b) { @@ -366,10 +440,184 @@ impl State { .or_default() .push(DecisionRecord { decision: *decision, amount: *amount, on: *on, seq }); } + EventBody::PaymentShared { payment, budget, amount, date, merchant, category, glyph } => { + if !self.budgets.contains_key(budget) { + return Err("no such budget"); + } + if self.payments.contains_key(payment) && !self.shared.contains(payment) { + return Err("a payment with this id exists"); + } + if !id_ok(payment) || *amount == Haler::ZERO { + return Err("a payment needs an id and an amount"); + } + if !text_ok(merchant) { + 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"); + } + let origin = match glyph { + Glyph::Captured => Origin::Captured, + Glyph::Confirmed => Origin::Imported, + Glyph::Hand => Origin::Added, + }; + self.shared.insert(payment.clone()); + self.payments.insert( + payment.clone(), + PaymentRecord { + id: payment.clone(), + origin, + seq, + amount: *amount, + date: *date, + merchant: merchant.clone(), + merchant_key: merchant_key(merchant), + card: None, + note: None, + line: None, + category: category.clone().map(|value| Stamped { seq, value }), + budget: Some(Stamped { seq, value: budget.clone() }), + trial_ends: None, + partner: None, + }, + ); + } + EventBody::PaymentUnshared { payment, budget } => { + if !self.shared.contains(payment) { + return Err("this payment was not shared here"); + } + if self.payments.get(payment).and_then(|p| p.budget.as_ref()).map(|b| &b.value) != Some(budget) { + return Err("this payment is not in that budget"); + } + if self.splits.values().any(|sp| sp.payment == *payment) { + return Err("this payment is split; it stays shared"); + } + self.shared.remove(payment); + self.payments.remove(payment); + } + EventBody::SplitCreated { split, payment, payer, shares } => { + if !id_ok(split) || self.splits.contains_key(split) { + return Err("a split needs a new id"); + } + let total = self.effective_payment(payment).ok_or("no such payment")?.amount; + if !total.is_outflow() { + return Err("only a payment out can be split"); + } + if shares.is_empty() || shares.len() > 50 { + return Err("a split is among 1-50 people"); + } + let people: BTreeSet<&str> = shares.iter().map(|s| s.person.as_str()).collect(); + if people.len() != shares.len() { + return Err("a person appears twice in the split"); + } + if shares.iter().any(|s| !id_ok(&s.person) || !name_ok(&s.name, 60)) { + return Err("every share needs a person and a name"); + } + if !people.contains(payer.as_str()) { + return Err("the payer must be one of the people"); + } + if shares.iter().any(|s| s.amount.0 > 0) { + return Err("a share has the wrong sign"); + } + if Haler::sum(shares.iter().map(|s| s.amount)) != Ok(total) { + return Err("the shares do not add up to the payment"); + } + self.splits.insert( + split.clone(), + Split { + id: split.clone(), + payment: payment.clone(), + payer: payer.clone(), + shares: shares.clone(), + settled: BTreeMap::new(), + seq, + }, + ); + } + EventBody::SplitSettled { split, person, how } => { + let sp = self.splits.get_mut(split).ok_or("no such split")?; + if !sp.shares.iter().any(|s| s.person == *person) { + return Err("this person is not in the split"); + } + if sp.payer == *person { + return Err("the payer owes nothing"); + } + if sp.settled.contains_key(person) { + return Err("already settled"); + } + sp.settled.insert(person.clone(), Settled { how: *how, seq }); + } + EventBody::CaptureTokenAdded { token, name, kind } => { + if !hash_ok(token) { + return Err("a capture token is stored only as its SHA-256"); + } + if self.capture_tokens.contains_key(token) { + return Err("this capture token exists"); + } + if !name_ok(name, 60) { + return Err("a phone's name must be 1-60 characters"); + } + self.capture_tokens.insert(token.clone(), CaptureToken { name: name.trim().into(), kind: *kind, revoked: false, seq }); + } + EventBody::CaptureTokenRevoked { token } => { + let t = self.capture_tokens.get_mut(token).ok_or("no such capture token")?; + if t.revoked { + return Err("already revoked"); + } + t.revoked = true; + } + EventBody::ShareLinkCreated { link, split, person, expires } => { + if !hash_ok(link) { + return Err("a share link is stored only as its SHA-256"); + } + if self.share_links.contains_key(link) { + return Err("this share link exists"); + } + let sp = self.splits.get(split).ok_or("no such split")?; + if sp.payer == *person || !sp.shares.iter().any(|s| s.person == *person) { + return Err("a share link is for someone who owes a share"); + } + self.share_links.insert(link.clone(), ShareLink { split: split.clone(), person: person.clone(), expires: *expires, seq }); + } + EventBody::AccountSet { iban, name } => { + let iban = Iban::parse(iban).map_err(|_| "not a valid Czech account")?; + if !name_ok(name, 70) { + return Err("an account name must be 1-70 characters"); + } + self.account = Some(Account { iban: iban.as_str().into(), name: name.trim().into() }); + } } Ok(()) } + /// Whether a phone's capture token (its SHA-256 in hex) may post captures. + pub fn capture_token_active(&self, token: &str) -> bool { + self.capture_tokens.get(token).is_some_and(|t| !t.revoked) + } + + /// The page behind a share link (its token's SHA-256 in hex): one person's open share, or `None` for an + /// unknown, expired (after `expires`) or settled link. + pub fn share_view(&self, link: &str, today: Date) -> Option { + let l = self.share_links.get(link)?; + if today > l.expires { + return None; + } + let sp = self.splits.get(&l.split)?; + if sp.settled.contains_key(&l.person) { + return None; + } + let share = sp.shares.iter().find(|s| s.person == l.person)?; + let p = self.effective_payment(&sp.payment)?; + let amount = share.amount.checked_neg().ok()?; + let (y, m, d) = p.date.ymd(); + let message = format!("{} {d}.{m}.{y}", p.merchant.trim()); + let spayd = self.account.as_ref().and_then(|a| { + let iban = Iban::parse(&a.iban).ok()?; + spayd(&iban, amount, Some(&a.name), &message, None).ok() + }); + Some(ShareView { name: share.name.clone(), amount, merchant: p.merchant, date: p.date, spayd }) + } + /// 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 From 2e07d37e86185edacc783a0f521b1c0f37f40ab2 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 3 Nov 2026 23:27:26 +0100 Subject: [PATCH 4/5] [capture] Phones: strict Shortcut post and bank-notification templates (registry empty until real samples) --- Cargo.lock | 17 +- Cargo.toml | 4 +- crates/fiscus-capture/Cargo.toml | 16 ++ crates/fiscus-capture/src/amount.rs | 26 ++++ crates/fiscus-capture/src/lib.rs | 28 ++++ crates/fiscus-capture/src/notification.rs | 179 ++++++++++++++++++++++ crates/fiscus-capture/src/shortcut.rs | 120 +++++++++++++++ 7 files changed, 385 insertions(+), 5 deletions(-) create mode 100644 crates/fiscus-capture/Cargo.toml create mode 100644 crates/fiscus-capture/src/amount.rs create mode 100644 crates/fiscus-capture/src/lib.rs create mode 100644 crates/fiscus-capture/src/notification.rs create mode 100644 crates/fiscus-capture/src/shortcut.rs diff --git a/Cargo.lock b/Cargo.lock index 983fc21..7d4dde2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -137,9 +137,20 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fiscus-capture" +version = "0.2.0" +dependencies = [ + "fiscus-ledger", + "proptest", + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "fiscus-insight" -version = "0.1.0" +version = "0.2.0" dependencies = [ "fiscus-ledger", "serde", @@ -148,7 +159,7 @@ dependencies = [ [[package]] name = "fiscus-ledger" -version = "0.1.0" +version = "0.2.0" dependencies = [ "proptest", "serde", @@ -158,7 +169,7 @@ dependencies = [ [[package]] name = "fiscus-statement" -version = "0.1.0" +version = "0.2.0" dependencies = [ "encoding_rs", "fiscus-ledger", diff --git a/Cargo.toml b/Cargo.toml index d2b605d..5fd174f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,9 @@ [workspace] resolver = "2" -members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight"] +members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"] [workspace.package] -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MPL-2.0" repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic" diff --git a/crates/fiscus-capture/Cargo.toml b/crates/fiscus-capture/Cargo.toml new file mode 100644 index 0000000..b2cfceb --- /dev/null +++ b/crates/fiscus-capture/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fiscus-capture" +description = "Fiscus Domi: what the phones send (the iPhone Shortcut post, Android bank notifications), parsed strictly" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +fiscus-ledger = { path = "../fiscus-ledger" } +serde.workspace = true +serde_json = { workspace = true, features = ["raw_value"] } +thiserror.workspace = true + +[dev-dependencies] +proptest.workspace = true diff --git a/crates/fiscus-capture/src/amount.rs b/crates/fiscus-capture/src/amount.rs new file mode 100644 index 0000000..7718440 --- /dev/null +++ b/crates/fiscus-capture/src/amount.rs @@ -0,0 +1,26 @@ +//! An amount as a phone writes it: `129`, `129,50`, `1 234,50 Kč`, `CZK 129.00`. Read from its text with +//! `Haler::parse_czk`, never through a float. + +use fiscus_ledger::Haler; + +/// The largest single card payment Fiscus believes: 10 000 000 CZK. +pub const MAX: Haler = Haler(1_000_000_000); + +/// A positive amount in CZK, with an optional `Kč` or `CZK` before or after it. A no-break space (U+00A0) or +/// narrow no-break space (U+202F) between thousands counts as a space. +pub fn parse_positive(text: &str) -> Option { + let t: String = text.chars().map(|c| if c == '\u{a0}' || c == '\u{202f}' { ' ' } else { c }).collect(); + let mut t = t.trim(); + for unit in ["Kč", "CZK"] { + if let Some(rest) = t.strip_suffix(unit) { + t = rest.trim_end(); + break; + } + if let Some(rest) = t.strip_prefix(unit) { + t = rest.trim_start(); + break; + } + } + let h = Haler::parse_czk(t).ok()?; + (h.0 > 0 && h <= MAX).then_some(h) +} diff --git a/crates/fiscus-capture/src/lib.rs b/crates/fiscus-capture/src/lib.rs new file mode 100644 index 0000000..bfcbb25 --- /dev/null +++ b/crates/fiscus-capture/src/lib.rs @@ -0,0 +1,28 @@ +//! Fiscus Domi's capture: what the phones send, parsed strictly. Both are hostile input: a post or a +//! notification becomes one [`Capture`] or nothing, never a partial payment. Pure: times are parameters. + +pub mod amount; +pub mod notification; +pub mod shortcut; + +use fiscus_ledger::{Date, Haler, Timestamp}; + +/// One card payment a phone saw: an outflow, so `amount` is negative. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Capture { + pub amount: Haler, + pub date: Date, + pub at: Timestamp, + pub merchant: String, + pub card: Option, +} + +/// 1–200 characters, no control characters. +pub(crate) fn merchant_ok(s: &str) -> bool { + !s.trim().is_empty() && s.chars().count() <= 200 && !s.chars().any(|c| c.is_control()) +} + +/// 0–60 characters, no control characters. +pub(crate) fn card_ok(s: &str) -> bool { + s.chars().count() <= 60 && !s.chars().any(|c| c.is_control()) +} diff --git a/crates/fiscus-capture/src/notification.rs b/crates/fiscus-capture/src/notification.rs new file mode 100644 index 0000000..82329de --- /dev/null +++ b/crates/fiscus-capture/src/notification.rs @@ -0,0 +1,179 @@ +//! Android bank notifications. A notification is read only if it comes from a bank app the person selected, +//! and becomes a payment only if a template **written from real samples** matches it exactly. Anything else +//! is `Unknown`: counted by the app, never guessed. + +use crate::{amount, card_ok, merchant_ok, Capture}; +use fiscus_ledger::{Date, Timestamp}; + +/// One notification format of one bank app. `text` (and `title`, if given) are literal text with holes: +/// `{amount}`, `{merchant}`, `{card}` and `{_}` (anything, ignored). Each hole matches at least one character. +#[derive(Clone, Copy, Debug)] +pub struct Template { + /// The Android package name of the bank app. + pub app: &'static str, + /// The bank, as `fixtures/notifications//` names it. + pub bank: &'static str, + pub title: Option<&'static str>, + pub text: &'static str, +} + +/// The registry. Empty: no bank notification samples exist yet (`fixtures/notifications/README.md`). +pub const TEMPLATES: &[Template] = &[]; + +/// Notifications longer than this are not read. +pub const MAX_TEXT: usize = 1000; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Recognised { + /// From an app the person did not select: not read at all. + NotSelected, + /// From a selected app, but no template matches (or two readings disagree). + Unknown, + Payment(Capture), +} + +/// [`recognise_with`] over the registry. +pub fn recognise(app: &str, title: &str, text: &str, date: Date, at: Timestamp, selected: &[&str]) -> Recognised { + recognise_with(TEMPLATES, app, title, text, date, at, selected) +} + +/// `date` and `at` are when the notification was posted (the phone's local date and the instant). +pub fn recognise_with( + templates: &[Template], + app: &str, + title: &str, + text: &str, + date: Date, + at: Timestamp, + selected: &[&str], +) -> Recognised { + if !selected.contains(&app) { + return Recognised::NotSelected; + } + if text.chars().count() > MAX_TEXT || title.chars().count() > MAX_TEXT { + return Recognised::Unknown; + } + let mut found: Option = None; + for t in templates.iter().filter(|t| t.app == app) { + if t.title.is_some_and(|pat| matches(pat, title).is_empty()) { + continue; + } + let all = matches(t.text, text); + if all.len() > MAX_READINGS { + return Recognised::Unknown; + } + for fields in all { + let Some(c) = capture(&fields, date, at) else { continue }; + match &found { + None => found = Some(c), + Some(prev) if *prev == c => {} + Some(_) => return Recognised::Unknown, + } + } + } + found.map(Recognised::Payment).unwrap_or(Recognised::Unknown) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Hole { + Amount, + Merchant, + Card, + Any, +} + +#[derive(Debug)] +enum Piece<'a> { + Lit(&'a str), + Hole(Hole), +} + +fn pieces(pattern: &str) -> Vec> { + let mut out = Vec::new(); + let mut rest = pattern; + while let Some(i) = rest.find('{') { + let Some(j) = rest[i..].find('}') else { break }; + let hole = match &rest[i + 1..i + j] { + "amount" => Some(Hole::Amount), + "merchant" => Some(Hole::Merchant), + "card" => Some(Hole::Card), + "_" => Some(Hole::Any), + _ => None, + }; + match hole { + Some(h) => { + if i > 0 { + out.push(Piece::Lit(&rest[..i])); + } + out.push(Piece::Hole(h)); + } + None => out.push(Piece::Lit(&rest[..i + j + 1])), + } + rest = &rest[i + j + 1..]; + } + if !rest.is_empty() { + out.push(Piece::Lit(rest)); + } + out +} + +type Fields<'a> = Vec<(Hole, &'a str)>; + +/// More readings than this of one notification is not a format, it is noise. +const MAX_READINGS: usize = 16; + +/// Every way `text` matches `pattern` exactly, as the text of each hole. +fn matches<'a>(pattern: &str, text: &'a str) -> Vec> { + let ps = pieces(pattern); + let mut out = Vec::new(); + walk(&ps, text, Vec::new(), &mut out); + out +} + +fn walk<'a>(ps: &[Piece], text: &'a str, acc: Fields<'a>, out: &mut Vec>) { + if out.len() > MAX_READINGS { + return; // the caller treats this many readings as unknown + } + match ps.first() { + None => { + if text.is_empty() { + out.push(acc); + } + } + Some(Piece::Lit(l)) => { + if let Some(rest) = text.strip_prefix(l) { + walk(&ps[1..], rest, acc, out); + } + } + Some(Piece::Hole(h)) => { + // The hole takes 1.. characters; with nothing after it, all the rest. + let ends: Vec = match ps.get(1) { + None => vec![text.len()], + Some(Piece::Lit(l)) => text.match_indices(l).map(|(i, _)| i).filter(|i| *i > 0).collect(), + Some(Piece::Hole(_)) => text.char_indices().map(|(i, _)| i).skip(1).chain([text.len()]).collect(), + }; + for end in ends { + if end == 0 { + continue; + } + let mut next = acc.clone(); + next.push((*h, &text[..end])); + walk(&ps[1..], &text[end..], next, out); + } + } + } +} + +fn capture(fields: &Fields, date: Date, at: Timestamp) -> Option { + let get = |h: Hole| fields.iter().find(|(k, _)| *k == h).map(|(_, v)| v.trim()); + let amount = amount::parse_positive(get(Hole::Amount)?)?.checked_neg().ok()?; + let merchant = get(Hole::Merchant)?; + if !merchant_ok(merchant) { + return None; + } + let card = get(Hole::Card); + if card.is_some_and(|c| !card_ok(c)) { + return None; + } + Some(Capture { amount, date, at, merchant: merchant.to_string(), card: card.filter(|c| !c.is_empty()).map(str::to_string) }) +} diff --git a/crates/fiscus-capture/src/shortcut.rs b/crates/fiscus-capture/src/shortcut.rs new file mode 100644 index 0000000..1fa35e7 --- /dev/null +++ b/crates/fiscus-capture/src/shortcut.rs @@ -0,0 +1,120 @@ +//! The iPhone Shortcut post (`POST /inbox`). We write the Shortcut, so the shape is ours: +//! `{"amount", "merchant", "card", "time"}` and an optional `"currency": "CZK"`, nothing else. + +use crate::{amount, card_ok, merchant_ok, Capture}; +use fiscus_ledger::{Date, Timestamp}; +use serde::Deserialize; +use serde_json::value::RawValue; + +/// The largest body the inbox reads. +pub const MAX_BODY: usize = 4096; + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum CaptureError { + #[error("the post is larger than 4 KiB")] + TooLarge, + #[error("the post is not a JSON object with exactly amount, merchant, card and time")] + Malformed, + #[error("the amount is not a positive amount in CZK")] + Amount, + #[error("the currency is not CZK")] + Currency, + #[error("the merchant must be 1-200 characters without control characters")] + Merchant, + #[error("the card name must be at most 60 characters without control characters")] + Card, + #[error("the time is not ISO 8601 with an offset (2026-11-03T14:05:00+01:00)")] + Time, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Post<'a> { + #[serde(borrow)] + amount: &'a RawValue, + merchant: String, + card: String, + time: String, + currency: Option, +} + +/// One post → one capture, or the first thing wrong with it. +pub fn parse(body: &[u8]) -> Result { + if body.len() > MAX_BODY { + return Err(CaptureError::TooLarge); + } + let post: Post = serde_json::from_slice(body).map_err(|_| CaptureError::Malformed)?; + let raw = post.amount.get(); + let text: String = if raw.starts_with('"') { + serde_json::from_str(raw).map_err(|_| CaptureError::Amount)? + } else if raw.bytes().all(|b| b.is_ascii_digit() || b == b'.') { + raw.to_string() + } else { + return Err(CaptureError::Amount); + }; + let amount = amount::parse_positive(&text).ok_or(CaptureError::Amount)?; + if post.currency.as_deref().is_some_and(|c| c != "CZK") { + return Err(CaptureError::Currency); + } + if !merchant_ok(&post.merchant) { + return Err(CaptureError::Merchant); + } + if !card_ok(&post.card) { + return Err(CaptureError::Card); + } + let (date, at) = parse_time(&post.time).ok_or(CaptureError::Time)?; + let card = post.card.trim(); + Ok(Capture { + amount: amount.checked_neg().map_err(|_| CaptureError::Amount)?, + date, + at, + merchant: post.merchant.trim().to_string(), + card: (!card.is_empty()).then(|| card.to_string()), + }) +} + +fn num(s: &str) -> Option { + (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok()).flatten() +} + +/// `YYYY-MM-DDTHH:MM[:SS[.fff]](Z|±HH:MM)` → the local date written in it, and the instant. +pub fn parse_time(s: &str) -> Option<(Date, Timestamp)> { + let (date, rest) = s.split_once('T')?; + if date.len() != 10 || &date[4..5] != "-" || &date[7..8] != "-" { + return None; + } + let day = Date::from_ymd(num(&date[..4])? as i32, num(&date[5..7])?, num(&date[8..])?)?; + let (clock, offset_min) = if let Some(c) = rest.strip_suffix('Z') { + (c, 0i64) + } else { + let i = rest.rfind(['+', '-'])?; + let (c, off) = rest.split_at(i); + let sign = if off.starts_with('-') { -1 } else { 1 }; + let off = &off[1..]; + if off.len() != 5 || &off[2..3] != ":" { + return None; + } + let (h, m) = (num(&off[..2])?, num(&off[3..])?); + if h > 14 || m > 59 { + return None; + } + (c, sign * (h as i64 * 60 + m as i64)) + }; + let (hms, millis) = match clock.split_once('.') { + Some((hms, frac)) if (1..=3).contains(&frac.len()) => (hms, num(frac)? as i64 * 10i64.pow(3 - frac.len() as u32)), + Some(_) => return None, + None => (clock, 0), + }; + let parts: Vec<&str> = hms.split(':').collect(); + if !(2..=3).contains(&parts.len()) || parts.iter().any(|p| p.len() != 2) { + return None; + } + let (h, m) = (num(parts[0])?, num(parts[1])?); + let sec = if parts.len() == 3 { num(parts[2])? } else { 0 }; + if h > 23 || m > 59 || sec > 59 { + return None; + } + let local_s = day.days() as i64 * 86_400 + h as i64 * 3600 + m as i64 * 60 + sec as i64; + let utc_ms = (local_s - offset_min * 60) * 1000 + millis; + Some((day, Timestamp(utc_ms))) +} From 701f15840a9656fa9f9fdd32caa677a51356ddea Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 3 Nov 2026 23:27:26 +0100 Subject: [PATCH 5/5] [insight] Household duplicates from shared subscription names --- crates/fiscus-insight/src/household.rs | 36 ++++++++++++++++++++++++++ crates/fiscus-insight/src/lib.rs | 1 + 2 files changed, 37 insertions(+) create mode 100644 crates/fiscus-insight/src/household.rs diff --git a/crates/fiscus-insight/src/household.rs b/crates/fiscus-insight/src/household.rs new file mode 100644 index 0000000..5ec3aae --- /dev/null +++ b/crates/fiscus-insight/src/household.rs @@ -0,0 +1,36 @@ +//! Household duplicates: two or more members paying for the same service ("You both pay Spotify"). Runs only +//! on the subscription names members chose to share into the household budget. + +use fiscus_ledger::merchant::merchant_key; +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Duplicate { + /// The service: the first word of the merchant key (`PAYPAL *SPOTIFY`, `Spotify AB` → `spotify`). + pub key: String, + /// Who pays it, sorted. + pub members: Vec, +} + +/// The first word of the merchant key, if it is at least three letters long. +pub fn service_key(name: &str) -> Option { + let key = merchant_key(name); + let first = key.split(' ').next()?; + (first.chars().count() >= 3).then(|| first.to_string()) +} + +/// `(member, the subscription names they shared)` → every service two or more members pay, by key. +pub fn household_duplicates(shared: &[(String, Vec)]) -> Vec { + let mut by_key: BTreeMap> = BTreeMap::new(); + for (member, names) in shared { + for key in names.iter().filter_map(|n| service_key(n)) { + by_key.entry(key).or_default().insert(member.clone()); + } + } + by_key + .into_iter() + .filter(|(_, m)| m.len() >= 2) + .map(|(key, m)| Duplicate { key, members: m.into_iter().collect() }) + .collect() +} diff --git a/crates/fiscus-insight/src/lib.rs b/crates/fiscus-insight/src/lib.rs index df8622e..1ba1533 100644 --- a/crates/fiscus-insight/src/lib.rs +++ b/crates/fiscus-insight/src/lib.rs @@ -3,4 +3,5 @@ pub mod cancel; pub mod forecast; +pub mod household; pub mod subscriptions;