[statement] Parsing: strict CSV, amount and date fields, decoding; no bank until real samples arrive
This commit is contained in:
@@ -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<String>,
|
||||
}
|
||||
|
||||
/// 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<Vec<Row>, (usize, CsvError)> {
|
||||
let mut rows: Vec<Row> = 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<String> = 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<Row>, fields: &mut Vec<String>, 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)
|
||||
}
|
||||
@@ -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)))
|
||||
}
|
||||
@@ -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<StatementLine>,
|
||||
}
|
||||
|
||||
/// 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<String, ParseError> {
|
||||
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<Statement, ParseError> {
|
||||
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/<bank>/.
|
||||
Err(ParseError::UnsupportedFormat)
|
||||
}
|
||||
Reference in New Issue
Block a user