[statement] Parsing: strict CSV, amount and date fields, decoding; no bank until real samples arrive

This commit is contained in:
2026-11-03 18:52:36 +01:00
parent 6572f31b1d
commit 397f9ff00e
6 changed files with 584 additions and 0 deletions
+83
View File
@@ -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<Haler, FieldError> {
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::<i64>().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<Date, FieldError> {
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<Date, FieldError> {
text.trim().parse().map_err(|_| FieldError::Date(shown(text)))
}