Cotton code
553 lines · 16.4 KB · RustRaw
//! The transfer-match rules, case by case, plus the vectors at the bottom.use super::*;use crate::constants::TRANSFER_MATCH_WINDOW_DAYS;fn accounts() -> Vec<TransferAccount> {    vec![        TransferAccount {            id: "acct-bank".into(),            institution: Some("Example Bank".into()),            name: "Savings".into(),            number_mask: Some("4821".into()),        },        TransferAccount {            id: "acct-card".into(),            institution: Some("Sample Card Co".into()),            name: "Sapphire card".into(),            number_mask: Some("9007".into()),        },        TransferAccount {            id: "acct-other".into(),            institution: None,            name: "Cash tin".into(),            number_mask: None,        },    ]}/// The TypeScript's `candidate({ … })` helper: everything not named takes the/// same default (12 March 2026, ₹5000.00, no payee text).fn candidate(    transaction_id: &str,    account_id: &str,    direction: LineDirection,) -> TransferCandidate {    TransferCandidate {        transaction_id: transaction_id.into(),        account_id: account_id.into(),        occurred_on: "2026-03-12".into(),        amount_minor: 500_000,        direction,        payee_text: String::new(),    }}fn with_payee(mut candidate: TransferCandidate, payee_text: &str) -> TransferCandidate {    candidate.payee_text = payee_text.into();    candidate}fn on(mut candidate: TransferCandidate, occurred_on: &str) -> TransferCandidate {    candidate.occurred_on = occurred_on.into();    candidate}fn pairs(candidates: &[TransferCandidate]) -> Vec<TransferPair> {    find_transfer_pairs(candidates, &accounts(), TRANSFER_MATCH_WINDOW_DAYS).unwrap()}fn pair(out_id: &str, in_id: &str, amount_minor: i64) -> TransferPair {    TransferPair {        out_transaction_id: out_id.into(),        in_transaction_id: in_id.into(),        amount_minor,    }}#[test]fn pairs_a_card_payment_named_on_the_bank_side() {    assert_eq!(        pairs(&[            with_payee(                candidate("txn-out", "acct-bank", LineDirection::Out),                "SAMPLE CARD CO PAYMENT 9007"            ),            candidate("txn-in", "acct-card", LineDirection::In),        ]),        vec![pair("txn-out", "txn-in", 500_000)]    );}/// One side naming the other is enough — banks are inconsistent about which.#[test]fn pairs_when_only_the_receiving_side_names_the_other_account() {    assert_eq!(        pairs(&[            candidate("txn-out", "acct-card", LineDirection::Out),            with_payee(                candidate("txn-in", "acct-bank", LineDirection::In),                "REFUND FROM SAMPLE CARD CO"            ),        ])        .len(),        1    );}#[test]fn matches_on_the_number_mask_alone() {    assert_eq!(        pairs(&[            with_payee(                candidate("txn-out", "acct-bank", LineDirection::Out),                "NEFT TO 9007"            ),            candidate("txn-in", "acct-card", LineDirection::In),        ])        .len(),        1    );}#[test]fn does_not_match_a_mask_that_is_a_substring_of_a_longer_number() {    assert!(pairs(&[        with_payee(            candidate("txn-out", "acct-bank", LineDirection::Out),            "UPI 590071234"        ),        candidate("txn-in", "acct-card", LineDirection::In),    ])    .is_empty());}#[test]fn pairs_across_the_window_and_refuses_one_day_past_it() {    let within = pairs(&[        with_payee(            on(                candidate("txn-out", "acct-bank", LineDirection::Out),                "2026-03-12",            ),            "SAMPLE CARD CO",        ),        on(            candidate("txn-in", "acct-card", LineDirection::In),            "2026-03-15",        ),    ]);    assert_eq!(within.len(), 1);    let beyond = pairs(&[        with_payee(            on(                candidate("txn-out", "acct-bank", LineDirection::Out),                "2026-03-12",            ),            "SAMPLE CARD CO",        ),        on(            candidate("txn-in", "acct-card", LineDirection::In),            "2026-03-16",        ),    ]);    assert!(beyond.is_empty());}#[test]fn pairs_when_the_receiving_side_is_dated_earlier_the_window_is_absolute() {    assert_eq!(        pairs(&[            with_payee(                on(                    candidate("txn-out", "acct-bank", LineDirection::Out),                    "2026-03-15"                ),                "SAMPLE CARD CO"            ),            on(                candidate("txn-in", "acct-card", LineDirection::In),                "2026-03-13"            ),        ])        .len(),        1    );}#[test]fn refuses_two_rows_on_one_account_however_well_they_read() {    assert!(pairs(&[        with_payee(            candidate("a", "acct-bank", LineDirection::Out),            "Example Bank 4821"        ),        with_payee(            candidate("b", "acct-bank", LineDirection::In),            "Example Bank 4821"        ),    ])    .is_empty());}/// The naming rule is what stops a salary and a rent payment of the same round/// number from being called one transfer.#[test]fn refuses_two_rows_of_equal_amount_that_name_nothing() {    assert!(pairs(&[        candidate("a", "acct-bank", LineDirection::Out),        candidate("b", "acct-card", LineDirection::In),    ])    .is_empty());}#[test]fn refuses_unequal_amounts_a_transfer_is_exact_never_approximate() {    let mut into = candidate("b", "acct-card", LineDirection::In);    into.amount_minor = 500_001;    assert!(pairs(&[        with_payee(            candidate("a", "acct-bank", LineDirection::Out),            "SAMPLE CARD CO"        ),        into,    ])    .is_empty());}#[test]fn refuses_two_rows_in_the_same_direction() {    assert!(pairs(&[        with_payee(            candidate("a", "acct-bank", LineDirection::Out),            "SAMPLE CARD CO"        ),        candidate("b", "acct-card", LineDirection::Out),    ])    .is_empty());}#[test]fn puts_each_transaction_in_at_most_one_pair_nearest_date_first() {    assert_eq!(        pairs(&[            with_payee(                on(                    candidate("out-1", "acct-bank", LineDirection::Out),                    "2026-03-12"                ),                "SAMPLE CARD CO"            ),            on(                candidate("in-far", "acct-card", LineDirection::In),                "2026-03-14"            ),            on(                candidate("in-near", "acct-card", LineDirection::In),                "2026-03-12"            ),        ]),        vec![pair("out-1", "in-near", 500_000)]    );}#[test]fn is_deterministic_when_two_candidates_tie_on_date() {    let input = [        with_payee(            candidate("out-1", "acct-bank", LineDirection::Out),            "SAMPLE CARD CO",        ),        candidate("in-b", "acct-card", LineDirection::In),        candidate("in-a", "acct-card", LineDirection::In),    ];    let first = pairs(&input);    let mut reversed = input.to_vec();    reversed.reverse();    let second = pairs(&reversed);    assert_eq!(first, second);    assert_eq!(first[0].in_transaction_id, "in-a");}#[test]fn ignores_a_candidate_on_an_account_it_has_never_heard_of() {    assert!(pairs(&[        with_payee(            candidate("a", "acct-ghost", LineDirection::Out),            "SAMPLE CARD CO"        ),        candidate("b", "acct-card", LineDirection::In),    ])    .is_empty());}/// A bank never prints what the owner privately calls an account. A false pair/// here would fold a real, unrelated spend into a transfer; missing one costs/// nothing — it stays as two unaccounted rows the audit shows. "acct-other" has/// no institution and no mask, so nothing can name it.#[test]fn does_not_match_an_account_by_its_name_alone() {    assert!(pairs(&[        with_payee(            candidate("a", "acct-bank", LineDirection::Out),            "moved to cash tin"        ),        candidate("b", "acct-other", LineDirection::In),    ])    .is_empty());}/// The reviewer's case: an account named "Savings" and a line reading "SAVINGS/// ACCOUNT AUTO DEBIT" — names nothing about the OTHER account (no institution,/// no mask), so this must not pair.#[test]fn does_not_pair_on_a_coincidental_name_match() {    assert!(pairs(&[        with_payee(            candidate("a", "acct-card", LineDirection::Out),            "SAVINGS ACCOUNT AUTO DEBIT"        ),        candidate("b", "acct-bank", LineDirection::In),    ])    .is_empty());}#[test]fn matches_the_mask_however_the_statement_prints_it() {    for rendering in [        "XX9007",              // letters then digits, glued        "XXXXXXXX9007",        // a long run of masking letters then digits        "xx9007",              // lowercase        "xxxxxxxxxxxx9007",    // a full 16-digit card masked to twelve X's        "XXXX XXXX XXXX 9007", // grouped in fours with spaces    ] {        assert_eq!(            pairs(&[                with_payee(                    candidate("txn-out", "acct-bank", LineDirection::Out),                    &format!("CARD PAYMENT {rendering}")                ),                candidate("txn-in", "acct-card", LineDirection::In),            ])            .len(),            1,            "rendering {rendering}"        );    }}/// The mask normally carries the letters (as printed by the reader); the payee/// text on the other side may print only the bare digits.#[test]fn matches_a_stored_mask_with_letters_against_a_bare_digit_token() {    let mut masked = accounts();    masked[1].number_mask = Some("XX9007".into());    let found = find_transfer_pairs(        &[            with_payee(                candidate("txn-out", "acct-bank", LineDirection::Out),                "NEFT TO 9007",            ),            candidate("txn-in", "acct-card", LineDirection::In),        ],        &masked,        TRANSFER_MATCH_WINDOW_DAYS,    )    .unwrap();    assert_eq!(found.len(), 1);}#[test]fn honours_a_callers_own_window() {    let far = [        with_payee(            on(                candidate("a", "acct-bank", LineDirection::Out),                "2026-03-01",            ),            "SAMPLE CARD CO",        ),        on(candidate("b", "acct-card", LineDirection::In), "2026-03-09"),    ];    assert!(        find_transfer_pairs(&far, &accounts(), TRANSFER_MATCH_WINDOW_DAYS)            .unwrap()            .is_empty()    );    assert_eq!(find_transfer_pairs(&far, &accounts(), 10).unwrap().len(), 1);}// ---------------------------------------------------------------------------// Node vectors — the naming rule probed through the public function, one payee// text at a time. Every answer below was printed by running the TypeScript.// ---------------------------------------------------------------------------/// `named(text)` is the vector harness: an out on the bank carrying `text` and/// a matching in on the card. One pair means the text named the card.fn named(payee_text: &str, accs: &[TransferAccount]) -> bool {    find_transfer_pairs(        &[            with_payee(candidate("o", "acct-bank", LineDirection::Out), payee_text),            candidate("i", "acct-card", LineDirection::In),        ],        accs,        TRANSFER_MATCH_WINDOW_DAYS,    )    .unwrap()    .len()        == 1}#[test]fn vector_the_institution_match_is_a_substring_of_the_normalised_text() {    let accs = accounts();    for (text, expected) in [        ("SAMPLE CARD CO PAYMENT 9007", true),        ("sample card co ltd", true),        ("sample card co", true),        // Every non-alphanumeric run — an em dash, a tab, a newline, an        // accented letter — collapses to ONE space, so all of these still read        // as "sample card co".        ("SaMpLe  Card—Co", true),        ("sample-card-co", true),        ("SAMPLE\tCARD\nCO", true),        ("café sample card co", true),        // Glued to a number, the letter→digit split leaves the institution        // intact and adds the mask as its own token besides.        ("SAMPLE CARD CO9007", true),        // Not the institution: a prefix of it, and the same words with the        // spaces removed (which normalisation does NOT re-insert).        ("sample card c", false),        ("SAMPLECARDCO", false),        // Nothing at all.        ("", false),        ("   ", false),        ("!!!", false),        ("SAVINGS ACCOUNT AUTO DEBIT", false),        // The account's own NAME is never enough — spec §4.6.        ("sapphire card", false),        ("Sapphire Card 1234", false),    ] {        assert_eq!(named(text, &accs), expected, "payee text {text:?}");    }}#[test]fn vector_the_mask_matches_only_as_its_own_token() {    let accs = accounts();    for (text, expected) in [        ("NEFT TO 9007", true),        ("9007", true),        (" 9007 ", true),        // The letter↔digit split is symmetric, so the mask isolates on either        // side of a run of masking characters.        ("x9007", true),        ("9007x", true),        ("9007SAMPLE", true),        // A longer number that merely CONTAINS the mask does not: no letters        // means no new boundary.        ("UPI 590071234", false),        ("90070", false),        ("09007", false),        // Punctuation between the digits makes four one-digit tokens.        ("CARD 9 0 0 7", false),    ] {        assert_eq!(named(text, &accs), expected, "payee text {text:?}");    }}/// Under three characters is refused outright, on both halves of the rule — a/// two-letter institution or a two-digit mask would match half the statement.#[test]fn vector_a_short_institution_or_mask_names_nothing() {    let mut short = accounts();    short[1].institution = Some("SC".into());    short[1].number_mask = Some("07".into());    for text in ["SC PAYMENT", "07", "sc 07", "SAMPLE CARD CO"] {        assert!(!named(text, &short), "payee text {text:?}");    }}#[test]fn vector_a_stored_mask_keeps_only_its_digits() {    let mut masked = accounts();    masked[1].number_mask = Some("XX9007".into());    assert!(named("NEFT TO 9007", &masked));    assert!(named("NEFT TO XX9007", &masked));    assert!(!named("NEFT TO 590071234", &masked));}/// The greedy sweep is stable across input order because the sort key is/// (distance, out id, in id). Two equally good pairs are matched by id, not by/// the order the rows arrived in.#[test]fn vector_two_whole_pairs_are_matched_by_id_not_by_arrival() {    assert_eq!(        pairs(&[            with_payee(                candidate("out-2", "acct-bank", LineDirection::Out),                "SAMPLE CARD CO"            ),            with_payee(                candidate("out-1", "acct-bank", LineDirection::Out),                "SAMPLE CARD CO"            ),            candidate("in-2", "acct-card", LineDirection::In),            candidate("in-1", "acct-card", LineDirection::In),        ]),        vec![            pair("out-1", "in-1", 500_000),            pair("out-2", "in-2", 500_000),        ]    );}#[test]fn vector_the_window_is_a_closed_interval_on_the_absolute_distance() {    let far = [        with_payee(            on(                candidate("a", "acct-bank", LineDirection::Out),                "2026-03-01",            ),            "SAMPLE CARD CO",        ),        on(candidate("b", "acct-card", LineDirection::In), "2026-03-09"),    ];    for window in [0, 1, 2, 3, 4] {        assert!(            find_transfer_pairs(&far, &accounts(), window)                .unwrap()                .is_empty(),            "window {window}"        );    }    assert_eq!(find_transfer_pairs(&far, &accounts(), 10).unwrap().len(), 1);}/// A row whose date cannot be read stops the sweep rather than being skipped:/// that is a booking bug, and pairing around it would hide it.#[test]fn vector_an_unreadable_date_refuses_the_whole_sweep() {    let error = find_transfer_pairs(        &[            with_payee(                on(candidate("a", "acct-bank", LineDirection::Out), "2026-3-01"),                "SAMPLE CARD CO",            ),            candidate("b", "acct-card", LineDirection::In),        ],        &accounts(),        TRANSFER_MATCH_WINDOW_DAYS,    )    .unwrap_err();    assert_eq!(error.kind(), "TypeError");    assert!(matches!(error, crate::rules::money::dates::DatesError::NotAnIsoDate(value) if value == "2026-3-01"));}#[test]fn the_default_window_is_three_days() {    assert_eq!(TRANSFER_MATCH_WINDOW_DAYS, 3);}