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))) +}