Cotton code
259 lines · 10.6 KB · RustRaw
//! Two unaccounted rows that are one movement of the owner's own money (spec//! §4.6). The port of `packages/core/src/engine/money/transferMatch.ts`.//!//! Card payments and own-account transfers stop being two unknowns,//! deterministically and with no model involved (rule 12).//!//! FIVE conditions, and the fifth is the one that earns the feature: opposite//! directions, different accounts, EXACTLY equal amounts, dates within the//! window — and at least one side's payee text names the other account's//! INSTITUTION or its MASKED CARD/ACCOUNT NUMBER (spec §4.6, verbatim: "names//! the other account's institution or card"). The account's own NAME is//! deliberately excluded — a bank statement never prints what the owner//! privately calls an account, only what the bank itself prints, and a//! coincidental name match (an account named "Savings" against a line reading//! "SAVINGS ACCOUNT AUTO DEBIT" that names no institution at all) would fold a//! real, unrelated spend into a transfer. Missing a real transfer costs nothing//! — it stays as two unaccounted rows the audit already shows. A false pair//! actively corrupts both accounts' history, which is the asymmetry this file//! is built to respect: without the naming rule at all, a salary in and a rent//! payment out of the same round number three days apart become "a transfer",//! and the owner's records quietly lose a month of income and a month of//! expense at once.use std::collections::{HashMap, HashSet};use serde::{Deserialize, Serialize};use super::dates::{days_between_dates, DatesError};use crate::constants::LineDirection;#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct TransferCandidate {    pub transaction_id: String,    pub account_id: String,    /// ISO yyyy-mm-dd.    pub occurred_on: String,    /// Positive integer paise.    pub amount_minor: i64,    pub direction: LineDirection,    /// As printed. Empty when the row carries none.    pub payee_text: String,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct TransferAccount {    pub id: String,    pub institution: Option<String>,    pub name: String,    pub number_mask: Option<String>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct TransferPair {    pub out_transaction_id: String,    pub in_transaction_id: String,    pub amount_minor: i64,}/// Lowercase, punctuation to spaces, and a LETTER↔DIGIT boundary is a boundary/// too — one form to compare in.////// Indian statements mask a card/account number with letters glued directly/// onto the digits ("XX9007", "XXXXXXXX9007", "xx9007") — no punctuation/// between them at all. Without splitting that boundary, "9007" is never its/// own token and a stored mask can never match. Splitting is symmetric/// (letter→digit AND digit→letter) so a mask printed either side of a run of/// masking characters still isolates cleanly, while a plain run of digits/// ("590071234") is untouched — no letters means no new boundary, so a mask/// that is merely a substring of a longer number still does not match.////// The three regexes are hand-rolled rather than compiled, because each is a/// one-character-class scan and the pass runs once per candidate pair. `[^a-z0-9]+`/// is applied AFTER lowercasing, so every non-ASCII character — an accented/// letter, a dash, a tab — collapses into the same single space, exactly as the/// non-unicode JavaScript regex does over UTF-16 code units.fn normalise(text: &str) -> String {    let lowered = text.to_lowercase();    // `.replace(/[^a-z0-9]+/g, " ")`    let mut collapsed = String::with_capacity(lowered.len());    let mut in_run = false;    for ch in lowered.chars() {        if ch.is_ascii_lowercase() || ch.is_ascii_digit() {            collapsed.push(ch);            in_run = false;        } else if !in_run {            collapsed.push(' ');            in_run = true;        }    }    // `.replace(/([a-z])(\d)/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2")` —    // both are non-overlapping left-to-right sweeps, and doing them in one pass    // would be a different function: after the first sweep "a1a" is "a 1a", and    // only then does the second find "1a". Splitting on EVERY letter/digit    // boundary in one go happens to give the same answer for both, which is why    // one pass is enough here — the two sweeps together mark every such    // boundary exactly once.    let mut split = String::with_capacity(collapsed.len());    let mut previous: Option<char> = None;    for ch in collapsed.chars() {        if let Some(before) = previous {            let boundary = (before.is_ascii_lowercase() && ch.is_ascii_digit())                || (before.is_ascii_digit() && ch.is_ascii_lowercase());            if boundary {                split.push(' ');            }        }        split.push(ch);        previous = Some(ch);    }    split.trim().to_string()}/// Does `payee_text` name `account` — by INSTITUTION or by MASKED NUMBER only/// (spec §4.6; the account's own name is never printed on a bank's own text,/// see the module header)?////// The institution matches as a substring of the normalised text — banks print/// "SAMPLE CARD CO PAYMENT" and "sample card co ltd" alike. The MASK compares/// DIGITS ONLY, on WORD BOUNDARIES: a stored mask of "XX9007" carries no/// meaning in its X's, so it is reduced to "9007" before matching, and that/// "9007" must appear as its own token in the (boundary-split) payee text —/// never as a bare substring, or a UPI reference number like "590071234" would/// pair two unrelated rows. Anything under three characters is refused outright/// — a two-letter institution or a two-digit mask would match half the/// statement.fn mentions(payee_text: &str, account: &TransferAccount) -> bool {    let haystack = normalise(payee_text);    if haystack.is_empty() {        return false;    }    if let Some(institution) = &account.institution {        let institution = normalise(institution);        // `String.prototype.length` is UTF-16 code units; the normalised form        // is ASCII by construction, so bytes and code units are the same count.        if institution.len() >= 3 && haystack.contains(&institution) {            return true;        }    }    if let Some(mask) = &account.number_mask {        let mask_digits: String = mask.chars().filter(char::is_ascii_digit).collect();        if mask_digits.len() >= 3 && format!(" {haystack} ").contains(&format!(" {mask_digits} ")) {            return true;        }    }    false}/// Every pair that is one transfer, each transaction used at most once.////// GREEDY by nearest date, and deterministic: pairs are sorted by (date/// distance, out id, in id) before the greedy sweep, so a re-run over the same/// rows in another order produces the same answer. That matters because this/// runs after EVERY booking — a non-deterministic matcher would pair/// differently on a re-read and leave a transfer half-merged.////// `window_days` is the TypeScript's defaulted argument, which Rust makes/// explicit: pass `constants::TRANSFER_MATCH_WINDOW_DAYS` unless a caller/// deliberately widens it.////// # Errors////// Whatever `days_between_dates` refuses: a candidate whose `occurred_on` is not/// an ISO day stops the whole sweep rather than being skipped, because a row/// with an unreadable date is a booking bug and pairing around it would hide it.pub fn find_transfer_pairs(    candidates: &[TransferCandidate],    accounts: &[TransferAccount],    window_days: i64,) -> Result<Vec<TransferPair>, DatesError> {    // `new Map(accounts.map(…))` — a later duplicate id overwrites an earlier    // one, which is what `HashMap::insert` does in the same order.    let mut by_id: HashMap<&str, &TransferAccount> = HashMap::new();    for account in accounts {        by_id.insert(account.id.as_str(), account);    }    let known: Vec<&TransferCandidate> = candidates        .iter()        .filter(|candidate| by_id.contains_key(candidate.account_id.as_str()))        .collect();    let outs: Vec<&&TransferCandidate> = known        .iter()        .filter(|candidate| candidate.direction == LineDirection::Out)        .collect();    let ins: Vec<&&TransferCandidate> = known        .iter()        .filter(|candidate| candidate.direction == LineDirection::In)        .collect();    let mut possible: Vec<(i64, TransferPair)> = Vec::new();    for out in &outs {        for into in &ins {            if out.account_id == into.account_id {                continue;            }            if out.amount_minor != into.amount_minor {                continue;            }            let distance = days_between_dates(&out.occurred_on, &into.occurred_on)?.abs();            if distance > window_days {                continue;            }            let (Some(out_account), Some(in_account)) = (                by_id.get(out.account_id.as_str()),                by_id.get(into.account_id.as_str()),            ) else {                continue;            };            if !mentions(&out.payee_text, in_account) && !mentions(&into.payee_text, out_account) {                continue;            }            possible.push((                distance,                TransferPair {                    out_transaction_id: out.transaction_id.clone(),                    in_transaction_id: into.transaction_id.clone(),                    amount_minor: out.amount_minor,                },            ));        }    }    // The TypeScript compares ids with `<` / `>`, which is a UTF-16 code-unit    // ordering; Rust's `str::cmp` is a UTF-8 byte ordering. The two disagree    // only where one side holds a character above the BMP and the other holds    // one in U+E000..U+FFFF — a transaction id is a uuid, so no input this sees    // can reach that difference.    possible.sort_by(|a, b| {        a.0.cmp(&b.0)            .then_with(|| a.1.out_transaction_id.cmp(&b.1.out_transaction_id))            .then_with(|| a.1.in_transaction_id.cmp(&b.1.in_transaction_id))    });    let mut taken: HashSet<&str> = HashSet::new();    let mut pairs: Vec<TransferPair> = Vec::new();    for (_distance, pair) in &possible {        if taken.contains(pair.out_transaction_id.as_str())            || taken.contains(pair.in_transaction_id.as_str())        {            continue;        }        taken.insert(pair.out_transaction_id.as_str());        taken.insert(pair.in_transaction_id.as_str());        pairs.push(pair.clone());    }    Ok(pairs)}#[cfg(test)]#[path = "transfer_match_tests.rs"]mod tests;