diff --git a/crates/fiscus-statement/Cargo.toml b/crates/fiscus-statement/Cargo.toml new file mode 100644 index 0000000..29f2dcd --- /dev/null +++ b/crates/fiscus-statement/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "fiscus-statement" +description = "Fiscus Domi: strict statement parsing (only banks with real samples)" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +fiscus-ledger = { path = "../fiscus-ledger" } +encoding_rs = "0.8" +serde.workspace = true +thiserror.workspace = true + +[dev-dependencies] +proptest.workspace = true +serde_json.workspace = true diff --git a/crates/fiscus-statement/src/csv.rs b/crates/fiscus-statement/src/csv.rs new file mode 100644 index 0000000..0671c70 --- /dev/null +++ b/crates/fiscus-statement/src/csv.rs @@ -0,0 +1,155 @@ +//! A strict CSV reader (RFC 4180 with a chosen delimiter). Every irregularity is an error with its line +//! number; a row is either returned whole or the file is refused. + +use serde::Serialize; + +/// Longest row accepted, in bytes. +pub const MAX_ROW: usize = 64 * 1024; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Dialect { + pub delimiter: char, + /// The last row must end with a line break: a file cut mid-row is then always an error. + pub final_newline: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error, Serialize)] +pub enum CsvError { + #[error("a quote inside a field that is not quoted")] + BareQuote, + #[error("a quoted field is never closed")] + UnterminatedQuote, + #[error("text after a closing quote")] + TextAfterQuote, + #[error("{found} fields where the header has {expected}")] + Ragged { expected: usize, found: usize }, + #[error("the row is longer than {MAX_ROW} bytes")] + RowTooLong, + #[error("the file does not end with a line break; it may be cut short")] + MissingFinalNewline, + #[error("a carriage return without a line feed")] + LoneCarriageReturn, +} + +/// One row and the line it starts on (1-based). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Row { + pub line: usize, + pub fields: Vec, +} + +/// Reads every row. All rows must have as many fields as the first. Blank lines are refused too (a bank +/// parser that expects them, e.g. between a preamble and the table, splits the text first). +pub fn read(text: &str, dialect: Dialect) -> Result, (usize, CsvError)> { + let mut rows: Vec = Vec::new(); + let mut chars = text.chars().peekable(); + let mut line = 1usize; + let mut row_start_line = 1usize; + let mut row_bytes = 0usize; + let mut fields: Vec = Vec::new(); + let mut field = String::new(); + let mut in_quotes = false; + let mut was_quoted = false; // the current field was quoted and has been closed + let mut field_started = false; + let mut ended_with_newline = false; + + let finish_row = |rows: &mut Vec, fields: &mut Vec, start: usize| -> Result<(), (usize, CsvError)> { + let row = std::mem::take(fields); + if let Some(first) = rows.first() { + if row.len() != first.fields.len() { + return Err((start, CsvError::Ragged { expected: first.fields.len(), found: row.len() })); + } + } + rows.push(Row { line: start, fields: row }); + Ok(()) + }; + + while let Some(c) = chars.next() { + row_bytes += c.len_utf8(); + if row_bytes > MAX_ROW { + return Err((row_start_line, CsvError::RowTooLong)); + } + ended_with_newline = false; + if in_quotes { + match c { + '"' if chars.peek() == Some(&'"') => { + chars.next(); + field.push('"'); + } + '"' => { + in_quotes = false; + was_quoted = true; + } + '\n' => { + line += 1; + field.push('\n'); + } + '\r' => { + if chars.peek() == Some(&'\n') { + chars.next(); + line += 1; + field.push('\n'); + } else { + return Err((line, CsvError::LoneCarriageReturn)); + } + } + other => field.push(other), + } + continue; + } + let newline = match c { + '\n' => true, + '\r' if chars.peek() == Some(&'\n') => { + chars.next(); + true + } + '\r' => return Err((line, CsvError::LoneCarriageReturn)), + _ => false, + }; + if newline { + fields.push(std::mem::take(&mut field)); + finish_row(&mut rows, &mut fields, row_start_line)?; + line += 1; + row_start_line = line; + row_bytes = 0; + was_quoted = false; + field_started = false; + ended_with_newline = true; + continue; + } + if c == dialect.delimiter { + fields.push(std::mem::take(&mut field)); + was_quoted = false; + field_started = false; + continue; + } + if was_quoted { + return Err((line, CsvError::TextAfterQuote)); + } + if c == '"' { + if field_started { + return Err((line, CsvError::BareQuote)); + } + in_quotes = true; + field_started = true; + continue; + } + field_started = true; + field.push(c); + } + + if in_quotes { + return Err((row_start_line, CsvError::UnterminatedQuote)); + } + let pending = field_started || was_quoted || !fields.is_empty(); + if pending { + if dialect.final_newline { + return Err((row_start_line, CsvError::MissingFinalNewline)); + } + fields.push(field); + finish_row(&mut rows, &mut fields, row_start_line)?; + } else if dialect.final_newline && !ended_with_newline && !text.is_empty() { + return Err((row_start_line, CsvError::MissingFinalNewline)); + } + Ok(rows) +} diff --git a/crates/fiscus-statement/src/field.rs b/crates/fiscus-statement/src/field.rs new file mode 100644 index 0000000..997df75 --- /dev/null +++ b/crates/fiscus-statement/src/field.rs @@ -0,0 +1,83 @@ +//! Field parsers for Czech statements: amounts to whole haléře, dates. Strict: anything unusual is an error. + +use fiscus_ledger::{Date, Haler}; +use serde::Serialize; + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error, Serialize)] +pub enum FieldError { + #[error("empty")] + Empty, + #[error("not an amount: {0:?}")] + Amount(String), + #[error("more than two decimals: {0:?}")] + TooPrecise(String), + #[error("the amount is too large")] + Overflow, + #[error("not a date: {0:?}")] + Date(String), +} + +fn shown(s: &str) -> String { + s.chars().take(40).collect() +} + +/// `-1 234,50` → `Haler(-123450)` with `decimal = ','`; `-1,234.50` with `decimal = '.'`. +/// +/// One sign at the front (`-`, `+` or the Unicode minus `−`), ASCII digits, the decimal mark followed by one +/// or two digits. Thousands separators (space, no-break spaces, or the other of `,`/`.`) only between +/// groups of exactly three digits. +pub fn amount(text: &str, decimal: char) -> Result { + let t = text.trim_matches(|c: char| c == ' ' || c == '\u{a0}'); + if t.is_empty() { + return Err(FieldError::Empty); + } + let bad = || FieldError::Amount(shown(text)); + let (neg, rest) = if let Some(r) = t.strip_prefix('-').or_else(|| t.strip_prefix('\u{2212}')) { + (true, r) + } else if let Some(r) = t.strip_prefix('+') { + (false, r) + } else { + (false, t) + }; + let (int, frac) = match rest.split_once(decimal) { + Some((i, f)) => (i, Some(f)), + None => (rest, None), + }; + let other = if decimal == ',' { '.' } else { ',' }; + let is_sep = |c: char| c == ' ' || c == '\u{a0}' || c == '\u{202f}' || c == other; + let groups: Vec<&str> = int.split(is_sep).collect(); + if groups.iter().any(|g| g.is_empty() || !g.bytes().all(|b| b.is_ascii_digit())) { + return Err(bad()); + } + if groups.len() > 1 && (groups[0].len() > 3 || groups[1..].iter().any(|g| g.len() != 3)) { + return Err(bad()); + } + let cents = match frac { + None => 0, + Some(f) if f.is_empty() || !f.bytes().all(|b| b.is_ascii_digit()) => return Err(bad()), + Some(f) if f.len() > 2 => return Err(FieldError::TooPrecise(shown(text))), + Some(f) => f.parse::().map_err(|_| bad())? * if f.len() == 1 { 10 } else { 1 }, + }; + let digits: String = groups.concat(); + let whole: i64 = digits.parse().map_err(|_| FieldError::Overflow)?; + let abs = whole.checked_mul(100).and_then(|w| w.checked_add(cents)).ok_or(FieldError::Overflow)?; + Ok(Haler(if neg { -abs } else { abs })) +} + +/// `03.11.2026` or `3.11.2026` (a two-digit year is refused). +pub fn date_dmy(text: &str) -> Result { + let t = text.trim(); + let bad = || FieldError::Date(shown(text)); + let parts: Vec<&str> = t.split('.').collect(); + let [d, m, y] = parts.as_slice() else { return Err(bad()) }; + let ok = |s: &str, lens: &[usize]| lens.contains(&s.len()) && s.bytes().all(|b| b.is_ascii_digit()); + if !ok(d, &[1, 2]) || !ok(m, &[1, 2]) || !ok(y, &[4]) { + return Err(bad()); + } + Date::from_ymd(y.parse().map_err(|_| bad())?, m.parse().map_err(|_| bad())?, d.parse().map_err(|_| bad())?).ok_or_else(bad) +} + +/// `2026-11-03`. +pub fn date_iso(text: &str) -> Result { + text.trim().parse().map_err(|_| FieldError::Date(shown(text))) +} diff --git a/crates/fiscus-statement/src/lib.rs b/crates/fiscus-statement/src/lib.rs new file mode 100644 index 0000000..6a21498 --- /dev/null +++ b/crates/fiscus-statement/src/lib.rs @@ -0,0 +1,112 @@ +//! Statement parsing for Fiscus Domi. Hostile input: strict, typed errors, never a partial row. +//! +//! **Only banks with real samples in `fixtures/` are supported.** No bank format is ever written from memory +//! or documentation alone. Until a bank's redacted samples arrive, [`parse`] returns +//! [`ParseError::UnsupportedFormat`] for it, and the app says so. What this crate already holds is the +//! strict ground every bank parser stands on: [`csv`], [`field`] and [`decode`]. + +pub mod csv; +pub mod field; + +use fiscus_ledger::import::StatementLine; +use serde::{Deserialize, Serialize}; + +/// A statement file larger than this is refused before it is read. +pub const MAX_FILE: usize = 16 * 1024 * 1024; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Statement { + pub bank: String, + pub account: String, + pub lines: Vec, +} + +/// A supported bank: which formats it parses, built from which samples. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct Bank { + pub id: &'static str, + pub name: &'static str, + pub formats: &'static [&'static str], +} + +/// Every bank with a parser. Empty until real samples arrive (see the crate docs). +pub const BANKS: &[Bank] = &[]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Encoding { + /// Strict UTF-8; a leading BOM is dropped. + Utf8, + /// Windows-1250 (Central European), which many Czech banks still export. + Windows1250, +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error, Serialize)] +pub enum ParseError { + #[error("the file is empty")] + Empty, + #[error("the file is {size} bytes; the limit is {MAX_FILE}")] + TooLarge { size: usize }, + #[error("the file is not valid text in the expected encoding (byte {offset})")] + Encoding { offset: usize }, + #[error("this is not a statement format Fiscus knows; no bank is supported until its real samples are added")] + UnsupportedFormat, + #[error("line {line}: {kind}")] + Csv { line: usize, kind: csv::CsvError }, + #[error("line {line}, {column}: {error}")] + Field { line: usize, column: String, error: field::FieldError }, + #[error("the header is not the one this bank writes")] + Header, +} + +/// Decodes a whole file. Strict: invalid UTF-8 is an error, never replaced; NUL bytes are refused. +pub fn decode(bytes: &[u8], encoding: Encoding) -> Result { + if bytes.is_empty() { + return Err(ParseError::Empty); + } + if bytes.len() > MAX_FILE { + return Err(ParseError::TooLarge { size: bytes.len() }); + } + if let Some(offset) = bytes.iter().position(|b| *b == 0) { + return Err(ParseError::Encoding { offset }); + } + let (text, bom) = match encoding { + Encoding::Utf8 => { + let body = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes); + let bom = bytes.len() - body.len(); + let text = std::str::from_utf8(body).map_err(|e| ParseError::Encoding { offset: e.valid_up_to() + bom })?; + (text.to_owned(), bom) + } + Encoding::Windows1250 => { + // The WHATWG table maps Windows-1250's five unassigned bytes to C1 controls, refused below. + let (text, _, had_errors) = encoding_rs::WINDOWS_1250.decode(bytes); + if had_errors { + return Err(ParseError::Encoding { offset: 0 }); + } + (text.into_owned(), 0) + } + }; + // A statement is text: no control characters but tab and line breaks. Report the byte where it starts. + if let Some((i, _)) = text.char_indices().find(|(_, c)| c.is_control() && !matches!(c, '\t' | '\r' | '\n')) { + let offset = match encoding { + Encoding::Utf8 => i + bom, + Encoding::Windows1250 => text[..i].chars().count(), // one byte per character + }; + return Err(ParseError::Encoding { offset }); + } + Ok(text) +} + +/// Parses a statement file with the bank parser that recognises it. +/// +/// No bank parser exists yet, so after the size checks every file is `UnsupportedFormat`. +pub fn parse(bytes: &[u8]) -> Result { + if bytes.is_empty() { + return Err(ParseError::Empty); + } + if bytes.len() > MAX_FILE { + return Err(ParseError::TooLarge { size: bytes.len() }); + } + // Each bank in BANKS gets a `detect(bytes) -> bool` and a `parse(bytes)` here, in its own module, + // with its fixtures under fixtures//. + Err(ParseError::UnsupportedFormat) +} diff --git a/crates/fiscus-statement/tests/fixtures.rs b/crates/fiscus-statement/tests/fixtures.rs new file mode 100644 index 0000000..cadfb40 --- /dev/null +++ b/crates/fiscus-statement/tests/fixtures.rs @@ -0,0 +1,62 @@ +//! Mandatory test 2: every real sample in `fixtures//` parses to exactly its `.expected.json`, and +//! every truncation of it is an error or a prefix of whole lines. +//! +//! A sample is any file in `fixtures//` other than `*.expected.json` and `README*`. Day 1 has no +//! samples, so this test walks an empty tree; it starts to bite the moment a sample is added (and fails until +//! that bank has a parser and the expected rows). + +use fiscus_statement::{parse, Statement}; +use std::path::{Path, PathBuf}; + +fn samples() -> Vec { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); + 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() { + let name = f.file_name().to_string_lossy().to_string(); + if f.path().is_file() && !name.ends_with(".expected.json") && !name.starts_with("README") { + out.push(f.path()); + } + } + } + out.sort(); + out +} + +fn expected_for(sample: &Path) -> PathBuf { + let name = sample.file_name().unwrap().to_string_lossy(); + sample.with_file_name(format!("{name}.expected.json")) +} + +#[test] +fn every_fixture_parses_to_its_expected_rows() { + let all = samples(); + eprintln!("statement fixtures: {}", all.len()); + for sample in all { + let bytes = std::fs::read(&sample).unwrap(); + let want: Statement = serde_json::from_slice( + &std::fs::read(expected_for(&sample)).unwrap_or_else(|_| panic!("{} has no .expected.json", sample.display())), + ) + .unwrap(); + let got = parse(&bytes).unwrap_or_else(|e| panic!("{}: {e}", sample.display())); + assert_eq!(got, want, "{}", sample.display()); + } +} + +#[test] +fn every_truncated_fixture_is_an_error_or_whole_lines() { + for sample in samples() { + let bytes = std::fs::read(&sample).unwrap(); + let full = parse(&bytes).unwrap(); + let step = (bytes.len() / 2000).max(1); + for cut in (0..bytes.len()).step_by(step) { + if let Ok(st) = parse(&bytes[..cut]) { + assert!(st.lines.len() <= full.lines.len(), "{} cut at {cut}", sample.display()); + for (got, want) in st.lines.iter().zip(&full.lines) { + assert_eq!(got, want, "{} cut at {cut}: a partial line", sample.display()); + } + } + } + } +} diff --git a/crates/fiscus-statement/tests/hostile.rs b/crates/fiscus-statement/tests/hostile.rs new file mode 100644 index 0000000..324f113 --- /dev/null +++ b/crates/fiscus-statement/tests/hostile.rs @@ -0,0 +1,155 @@ +//! Mandatory test 2: hostile statement input. Random bytes and every truncation give a typed error or only +//! whole rows, never a panic and never a partial row. + +use fiscus_ledger::Haler; +use fiscus_statement::csv::{read, CsvError, Dialect}; +use fiscus_statement::field::{amount, date_dmy, FieldError}; +use fiscus_statement::{decode, parse, Encoding, ParseError, MAX_FILE}; +use proptest::prelude::*; + +const STRICT: Dialect = Dialect { delimiter: ';', final_newline: true }; + +/// A generic RFC 4180 file (not any bank's format): quotes, an escaped quote, a line break inside a field, +/// CRLF, diacritics. +const SAMPLE: &str = "date;amount;merchant;note\r\n\ +03.10.2026;-129,00;Albert;\r\n\ +04.10.2026;\"-1 234,50\";\"Kavárna \"\"U Nováků\"\"\";\"two\nlines\"\r\n\ +05.10.2026;35 000,00;Mzda;říjen\r\n"; + +#[test] +fn reads_the_generic_sample() { + let rows = read(SAMPLE, STRICT).unwrap(); + assert_eq!(rows.len(), 4); + assert_eq!(rows[2].fields, vec!["04.10.2026", "-1 234,50", "Kavárna \"U Nováků\"", "two\nlines"]); + assert_eq!(rows[3].line, 5, "the row after a two-line field starts on line 5"); + assert_eq!(amount(&rows[2].fields[1], ','), Ok(Haler(-123_450))); + assert_eq!(amount(&rows[3].fields[1], ','), Ok(Haler(3_500_000))); +} + +#[test] +fn every_truncation_is_an_error_or_whole_rows() { + let full = read(SAMPLE, STRICT).unwrap(); + for cut in 0..SAMPLE.len() { + if !SAMPLE.is_char_boundary(cut) { + continue; + } + match read(&SAMPLE[..cut], STRICT) { + Err(_) => {} + Ok(rows) => { + assert!(rows.len() <= full.len()); + for (got, want) in rows.iter().zip(&full) { + assert_eq!(got, want, "a partial row at cut {cut}"); + } + } + } + } +} + +#[test] +fn irregular_csv_is_refused_with_its_line() { + let cases: &[(&str, usize, CsvError)] = &[ + ("a;b\nc;d;e\n", 2, CsvError::Ragged { expected: 2, found: 3 }), + ("a;b\nc\n", 2, CsvError::Ragged { expected: 2, found: 1 }), + ("a;b\n\nc;d\n", 2, CsvError::Ragged { expected: 2, found: 1 }), + ("a;b\nc\"x;d\n", 2, CsvError::BareQuote), + ("a;b\n\"c;d\n", 2, CsvError::UnterminatedQuote), + ("a;b\n\"c\"x;d\n", 2, CsvError::TextAfterQuote), + ("a;b\nc;d", 2, CsvError::MissingFinalNewline), + ("a;b\rc;d\n", 1, CsvError::LoneCarriageReturn), + ]; + for (text, line, kind) in cases { + assert_eq!(read(text, STRICT), Err((*line, kind.clone())), "{text:?}"); + } + let long = format!("a\n{}\n", "x".repeat(70_000)); + assert_eq!(read(&long, STRICT), Err((2, CsvError::RowTooLong))); +} + +#[test] +fn amounts() { + let ok: &[(&str, char, i64)] = &[ + ("-1 234,50", ',', -123_450), + ("1234,50", ',', 123_450), + ("\u{2212}12,00", ',', -1_200), + ("1.234,50", ',', 123_450), + ("+5,5", ',', 550), + ("1\u{a0}000\u{a0}000,00", ',', 100_000_000), + ("-1,234.50", '.', -123_450), + ("0,01", ',', 1), + ("12", ',', 1_200), + ]; + for (text, dec, want) in ok { + assert_eq!(amount(text, *dec), Ok(Haler(*want)), "{text:?}"); + } + let bad = ["", "-", "1,2,3", "12,345", "1 23,00", "12 3456,00", "--5", "5-", "1e3", "12,", ",50", "NaN", "0x10", "١٢٣", "12.50"]; + for text in bad { + assert!(amount(text, ',').is_err(), "{text:?} must be refused"); + } + assert!(matches!(amount("12,345", ','), Err(FieldError::TooPrecise(_)))); + assert_eq!(amount("99999999999999999999,00", ','), Err(FieldError::Overflow)); +} + +#[test] +fn dates() { + assert_eq!(date_dmy("03.11.2026").unwrap().to_string(), "2026-11-03"); + assert_eq!(date_dmy("3.1.2026").unwrap().to_string(), "2026-01-03"); + for bad in ["31.02.2026", "03.11.26", "2026.11.03", "03/11/2026", "03.11.2026x", "", "0.0.0000"] { + assert!(date_dmy(bad).is_err(), "{bad:?}"); + } +} + +#[test] +fn decoding_is_strict() { + assert_eq!(decode(b"\xEF\xBB\xBFa;b\n", Encoding::Utf8).unwrap(), "a;b\n"); + assert!(matches!(decode(b"a;\xC3\x28\n", Encoding::Utf8), Err(ParseError::Encoding { offset: 2 }))); + assert!(matches!(decode(b"a\x00b", Encoding::Utf8), Err(ParseError::Encoding { offset: 1 }))); + // "Příliš" in Windows-1250. + assert_eq!(decode(b"P\xF8\xEDli\x9A", Encoding::Windows1250).unwrap(), "Příliš"); + assert!(matches!(decode(b"x\x81", Encoding::Windows1250), Err(ParseError::Encoding { .. }))); + assert_eq!(decode(b"", Encoding::Utf8), Err(ParseError::Empty)); +} + +#[test] +fn no_bank_is_supported_without_samples() { + assert!(fiscus_statement::BANKS.is_empty()); + assert_eq!(parse(SAMPLE.as_bytes()), Err(ParseError::UnsupportedFormat)); + assert_eq!(parse(b""), Err(ParseError::Empty)); + let huge = vec![b'a'; MAX_FILE + 1]; + assert_eq!(parse(&huge), Err(ParseError::TooLarge { size: MAX_FILE + 1 })); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + #[test] + fn random_bytes_never_panic(bytes in prop::collection::vec(any::(), 0..400)) { + let _ = parse(&bytes); + for enc in [Encoding::Utf8, Encoding::Windows1250] { + if let Ok(text) = decode(&bytes, enc) { + for dialect in [STRICT, Dialect { delimiter: ',', final_newline: false }] { + if let Ok(rows) = read(&text, dialect) { + if let Some(first) = rows.first() { + prop_assert!(rows.iter().all(|r| r.fields.len() == first.fields.len())); + } + for r in &rows { + for f in &r.fields { + let _ = amount(f, ','); + let _ = date_dmy(f); + } + } + } + } + } + } + } + + #[test] + fn csv_like_noise_never_panics(text in "[a;\"\r\n,0-9 ]{0,200}") { + let _ = read(&text, STRICT); + let _ = read(&text, Dialect { delimiter: ',', final_newline: false }); + } + + #[test] + fn amounts_round_trip(h in -100_000_000_000i64..100_000_000_000) { + prop_assert_eq!(amount(&Haler(h).to_czk(), ','), Ok(Haler(h))); + } +}