Cotton code
160 lines · 5.5 KB · RustRaw
//! The content fingerprint of a statement line — the idempotency key for//! paper, which carries no ids of its own.//!//! `fingerprint` is UNIQUE per STATEMENT, so a RE-READ of the same statement//! must reproduce the same ids or every run duplicates the owner's money. The//! material is CONTENT ONLY: which account the paper is about, the date it//! printed, the amount, the direction, the whitespace-collapsed text, and the//! line's occurrence among identical lines in printed order.//!//! NO PERSON IS IN IT — no payee id, no counterparty, no category. Identity is//! decided AFTER a line is booked, can be corrected for years, and must never//! move an id: exactly the `txt2:` and `eml2:` rule that came before it.use std::collections::HashMap;use super::{EncodeError, Result};use crate::fingerprint::message::{digest32, material};use crate::js;pub const STATEMENT_LINE_FINGERPRINT_PREFIX: &str = "stl:";/// Which way the money went.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Direction {    In,    Out,}impl Direction {    pub fn as_str(self) -> &'static str {        match self {            Direction::In => "in",            Direction::Out => "out",        }    }}/// Layout is discarded, content is kept — a bank that rewraps a description/// across a page break must not mint a second row for the same money./// Punctuation stays: `NEFT-CR-XYZ0001234` is a reference, not decoration.pub fn normalise_line_text(text: &str) -> String {    js::collapse_whitespace_and_trim(text).to_lowercase()}/// Which account the paper is about.////// `institution|number_mask` of the STORED account — never the header text the/// model read off one page. The institution is lowercased and the mask reduced/// to its DIGITS: "XX4821" and "**** 4821" are one identity.////// When either is missing (a mask with no digits counts as missing) the key/// falls back to the STATEMENT's own id: the narrowest scope there is, so two/// accounts' lines cannot collide on one day, one amount and one text.pub fn statement_line_account_key(    institution: Option<&str>,    number_mask: Option<&str>,    statement_id: &str,) -> String {    let bank = institution        .map(|value| value.trim_matches(js::is_js_whitespace).to_lowercase())        .unwrap_or_default();    let digits: String = number_mask        .unwrap_or("")        .chars()        .filter(char::is_ascii_digit)        .collect();    if bank.is_empty() || digits.is_empty() {        return statement_id.to_string();    }    format!("{bank}|{digits}")}pub struct StatementLineFingerprintInput<'a> {    pub account_key: &'a str,    /// The date as printed, ISO yyyy-mm-dd.    pub posted_on: &'a str,    /// Positive integer paise.    pub amount_minor: i64,    pub direction: Direction,    pub text: &'a str,    /// 0 for the first line with this material, 1 for the next, …    pub occurrence: u64,}fn assert_shape(input: &StatementLineFingerprintInput<'_>) -> Result<()> {    if !is_iso_day(input.posted_on) {        return Err(EncodeError(format!(            "statementLineFingerprint: expected an ISO date (YYYY-MM-DD), got \"{}\"",            input.posted_on        )));    }    // `amountMinor` arrives as an i64 here, so the "must be an integer" arm of    // the TypeScript is structural — a non-integer cannot be constructed.    if input.amount_minor <= 0 {        return Err(EncodeError(format!(            "statementLineFingerprint: amountMinor must be positive, got {}",            input.amount_minor        )));    }    Ok(())}/// TypeScript's `/^\d{4}-\d{2}-\d{2}$/` — the SHAPE only, exactly as written:/// `2026-13-45` passes it there and must pass it here too, or one side would/// fingerprint a line the other refuses.fn is_iso_day(value: &str) -> bool {    let bytes = value.as_bytes();    bytes.len() == 10        && bytes[..4].iter().all(u8::is_ascii_digit)        && bytes[4] == b'-'        && bytes[5..7].iter().all(u8::is_ascii_digit)        && bytes[7] == b'-'        && bytes[8..10].iter().all(u8::is_ascii_digit)}/// The material both the hash and the occurrence counter key on.fn fingerprint_material(input: &StatementLineFingerprintInput<'_>) -> String {    material(&[        input.account_key.into(),        input.posted_on.into(),        input.amount_minor.into(),        input.direction.as_str().into(),        normalise_line_text(input.text).into(),    ])}/// `stl:<32 hex>`.////// The hash is over `[<the inner material string>, occurrence]` — a JSON array/// whose first element is itself a JSON string, exactly as the TypeScript/// nests it. Flattening that would change every fingerprint ever written.pub fn statement_line_fingerprint(input: &StatementLineFingerprintInput<'_>) -> Result<String> {    assert_shape(input)?;    let outer = material(&[fingerprint_material(input).into(), input.occurrence.into()]);    Ok(format!(        "{STATEMENT_LINE_FINGERPRINT_PREFIX}{}",        digest32(&outer)    ))}/// Keyed on exactly the material the hash uses, so two runs over one statement/// walk the same sequence. One counter per statement read.#[derive(Default)]pub struct StatementLineOccurrenceCounter {    seen: HashMap<String, u64>,}impl StatementLineOccurrenceCounter {    pub fn new() -> Self {        Self::default()    }    pub fn next(&mut self, input: &StatementLineFingerprintInput<'_>) -> u64 {        let key = fingerprint_material(input);        let count = self.seen.entry(key).or_insert(0);        let value = *count;        *count += 1;        value    }}