Cotton code
288 lines · 11.0 KB · RustRaw
//! Does the paper add up? — the port of//! `packages/core/src/engine/money/statementCheck.ts` (spec §4.3, rule 12://! "balance checks, transfer matching, coverage and the audit are pure//! functions. A model is used only to read paper and to propose meaning.")//!//! **THE SIGN CONVENTION IS THE WHOLE FILE.** A line's `direction` is always//! from the ACCOUNT's point of view, so a card spend is `out` and a card//! payment is `in` — but a card's printed balance is what is OWED, which moves//! the other way. Reading a card with the bank's rule does not fail loudly; it//! produces a number that is wrong by exactly twice the period's turnover and//! calls it ok. So the rule is stated once, here, and nowhere else://!//! ```text//! bank:        closing      = opening      + Σin  − Σout//! credit card: closing_owed = opening_owed + Σout − Σin//! ```//!//! Pure, dependency-free and total: no I/O, no clock, no locale. Loud about//! nonsense in the `posting.ts` house style — a TypeError for a non-integer, a//! RangeError for an out-of-domain value.//!//! **Amounts and line numbers are `f64`.** A statement is read by a MODEL, so//! `amountMinor: 1234.56` and `lineNo: 1.5` are shapes that genuinely arrive;//! the guards below are the money rule ("refused, never rounded") and a refusal//! whose input the type cannot hold is a refusal that cannot be ported.use cotton_store::protocol::js::number_to_string;use crate::constants::{BalanceCheck, LineDirection, StatementKind};fn is_js_integer(value: f64) -> bool {    value.is_finite() && value.fract() == 0.0}/// One line as the reader transcribed it.#[derive(Debug, Clone, PartialEq)]pub struct CheckLine {    /// The line's position on the paper, 1-based. Positive whole numbers only.    pub line_no: f64,    /// POSITIVE whole paise; `direction` carries the sign.    pub amount_minor: f64,    pub direction: LineDirection,    /// The running balance as PRINTED, when the paper printed one.    pub balance_after_minor: Option<f64>,    /// The reader marked it not-to-be-booked (an opening row, a summary total).    pub ignored: bool,}/// One statement's reading, as the check receives it.#[derive(Debug, Clone, PartialEq)]pub struct CheckInput {    pub kind: StatementKind,    /// As printed; `None` when the paper carries none. For a card, what is    /// OWED.    pub opening_minor: Option<f64>,    pub closing_minor: Option<f64>,    pub lines: Vec<CheckLine>,}/// What the arithmetic said.#[derive(Debug, Clone, PartialEq)]pub struct CheckResult {    pub balance_check: BalanceCheck,    pub sum_in_minor: f64,    pub sum_out_minor: f64,    /// What the closing balance SHOULD be; `None` with no opening printed.    pub expected_closing_minor: Option<f64>,    /// The first line whose printed running balance disagrees, if any.    ///    /// An `f64` because [`CheckLine::line_no`] is one — see the module note.    pub first_break_line_no: Option<f64>,}/// The refusals. `Display` is the TypeScript's sentence verbatim; [`kind`]/// answers which JavaScript constructor it throws.////// [`kind`]: CheckStatementError::kind#[derive(Debug, Clone, PartialEq, thiserror::Error)]pub enum CheckStatementError {    #[error(        "checkStatement: openingMinor must be an integer (paise) or null, got {}",        number_to_string(*.0)    )]    OpeningNotAnInteger(f64),    #[error(        "checkStatement: closingMinor must be an integer (paise) or null, got {}",        number_to_string(*.0)    )]    ClosingNotAnInteger(f64),    #[error("checkStatement: lineNo must be an integer, got {}", number_to_string(*.0))]    LineNoNotAnInteger(f64),    #[error("checkStatement: lineNo must be positive, got {}", number_to_string(*.0))]    LineNoNotPositive(f64),    #[error(        "checkStatement: line {} amountMinor must be an integer (paise), got {}",        number_to_string(*.0),        number_to_string(*.1)    )]    AmountNotAnInteger(f64, f64),    #[error(        "checkStatement: line {} amountMinor must be positive — direction carries the sign, got {}",        number_to_string(*.0),        number_to_string(*.1)    )]    AmountNotPositive(f64, f64),    #[error(        "checkStatement: line {} balanceAfterMinor must be an integer (paise), got {}",        number_to_string(*.0),        number_to_string(*.1)    )]    BalanceAfterNotAnInteger(f64, f64),    #[error("checkStatement: two lines claim line_no {}", number_to_string(*.0))]    DuplicateLineNo(f64),}impl CheckStatementError {    /// Which JavaScript error constructor the TypeScript throws.    pub const fn kind(&self) -> &'static str {        match self {            CheckStatementError::OpeningNotAnInteger(_)            | CheckStatementError::ClosingNotAnInteger(_)            | CheckStatementError::LineNoNotAnInteger(_)            | CheckStatementError::AmountNotAnInteger(..)            | CheckStatementError::BalanceAfterNotAnInteger(..) => "TypeError",            CheckStatementError::LineNoNotPositive(_)            | CheckStatementError::AmountNotPositive(..)            | CheckStatementError::DuplicateLineNo(_) => "RangeError",        }    }}fn assert_lines(lines: &[CheckLine]) -> Result<(), CheckStatementError> {    let mut seen: Vec<f64> = Vec::with_capacity(lines.len());    for line in lines {        if !is_js_integer(line.line_no) {            return Err(CheckStatementError::LineNoNotAnInteger(line.line_no));        }        if line.line_no <= 0.0 {            return Err(CheckStatementError::LineNoNotPositive(line.line_no));        }        if !is_js_integer(line.amount_minor) {            return Err(CheckStatementError::AmountNotAnInteger(                line.line_no,                line.amount_minor,            ));        }        if line.amount_minor <= 0.0 {            return Err(CheckStatementError::AmountNotPositive(                line.line_no,                line.amount_minor,            ));        }        if let Some(balance) = line.balance_after_minor {            if !is_js_integer(balance) {                return Err(CheckStatementError::BalanceAfterNotAnInteger(                    line.line_no,                    balance,                ));            }        }        // The TypeScript's `Set<number>`; the values are already known to be        // whole numbers, so equality is exact and a linear scan over one        // statement's lines is cheaper than hashing a float.        if seen.contains(&line.line_no) {            return Err(CheckStatementError::DuplicateLineNo(line.line_no));        }        seen.push(line.line_no);    }    Ok(())}/// What one booked line does to the printed balance, given the paper's kind.////// The TypeScript's `default:` arm throws on an unknown kind; here/// [`StatementKind`] has two members and the `match` is total, so the/// unreachable third case is inexpressible rather than merely guarded.fn movement(kind: StatementKind, line: &CheckLine) -> f64 {    let raises = match kind {        StatementKind::Bank => LineDirection::In,        StatementKind::CreditCard => LineDirection::Out,    };    if line.direction == raises {        line.amount_minor    } else {        -line.amount_minor    }}/// The closing balance a statement's own totals give: its opening moved by/// the money in and the money out the way its kind runs — the arithmetic/// [`check_statement`] does line by line, said from the totals kept.pub fn closing_from_totals(kind: StatementKind, opening_minor: i64, sum_in_minor: i64, sum_out_minor: i64) -> i64 {    match kind {        StatementKind::Bank => opening_minor + sum_in_minor - sum_out_minor,        StatementKind::CreditCard => opening_minor - sum_in_minor + sum_out_minor,    }}/// Check one statement's reading against its own printed balances.pub fn check_statement(input: &CheckInput) -> Result<CheckResult, CheckStatementError> {    if let Some(opening) = input.opening_minor {        if !is_js_integer(opening) {            return Err(CheckStatementError::OpeningNotAnInteger(opening));        }    }    if let Some(closing) = input.closing_minor {        if !is_js_integer(closing) {            return Err(CheckStatementError::ClosingNotAnInteger(closing));        }    }    assert_lines(&input.lines)?;    let booked = || input.lines.iter().filter(|line| !line.ignored);    let sum_in_minor: f64 = booked()        .filter(|line| line.direction == LineDirection::In)        .map(|line| line.amount_minor)        .sum();    let sum_out_minor: f64 = booked()        .filter(|line| line.direction == LineDirection::Out)        .map(|line| line.amount_minor)        .sum();    let expected_closing_minor = input        .opening_minor        .map(|opening| booked().fold(opening, |total, line| total + movement(input.kind, line)));    // The RUNNING check, which is what makes a mismatch actionable: the totals    // say "somewhere in twenty-four lines", the run says "line 7". An IGNORED    // line is skipped entirely — it neither advances the running total nor has    // its printed balance compared. A "statement summary" row can print a total    // that has nothing to do with the running balance (an opening row's ignored    // balance happens to already agree, but that is not guaranteed of every    // ignored row), and comparing it anyway would fail a statement that is    // otherwise perfectly readable.    let mut first_break_line_no: Option<f64> = None;    if let Some(opening) = input.opening_minor {        let mut ordered: Vec<&CheckLine> = input.lines.iter().collect();        // `total_cmp` rather than `partial_cmp().unwrap()`: every line number        // here has already passed the integer guard, so the two agree, and a        // pure library must not hold a panic for a case it has already ruled        // out.        ordered.sort_by(|a, b| a.line_no.total_cmp(&b.line_no));        let mut running = opening;        for line in ordered {            if line.ignored {                continue;            }            running += movement(input.kind, line);            if let Some(printed) = line.balance_after_minor {                if printed != running {                    first_break_line_no = Some(line.line_no);                    break;                }            }        }    }    // `unknown` is a real answer and not a failure: plenty of paper prints no    // balances at all, and §4.3 books those lines anyway.    let balance_check = match (        input.opening_minor,        first_break_line_no,        input.closing_minor,    ) {        (None, _, _) => BalanceCheck::Unknown,        (Some(_), Some(_), _) => BalanceCheck::Mismatch,        (Some(_), None, None) => BalanceCheck::Unknown,        (Some(_), None, Some(closing)) => {            if expected_closing_minor == Some(closing) {                BalanceCheck::Ok            } else {                BalanceCheck::Mismatch            }        }    };    Ok(CheckResult {        balance_check,        sum_in_minor,        sum_out_minor,        expected_closing_minor,        first_break_line_no,    })}#[cfg(test)]#[path = "statement_check_tests.rs"]mod tests;