//! The chart, and the account a statement is about.//!//! The three chart tools live here too: `create_money_account`,//! `update_money_account`.//!//! Creating an account from a statement is RIGHT: the paper is proof the//! account exists. What must never happen is creating a SECOND row for an//! account that is already there — a split identity is a balance that is wrong//! on both halves and obviously wrong on neither. So the match is a ladder,//! most specific first: the printed identity (institution + mask, DIGITS ONLY),//! then institution + the reader's proposed name when the paper printed no//! number, then create.//!//! ONE DIVERGENCE FROM THE TYPESCRIPT, and it is the writer's shape rather than//! a decision. `PgrestClient` applied each write on its own, so a function that//! inserted an account and then re-read the chart saw it. This writer COLLECTS//! changes and folds them in one transaction at `ctx.commit()`, so a fresh row//! is not readable until then — which is why every helper here takes the//! caller's account list `&mut` and pushes what it created into it. The list,//! not a re-read, is what the rest of the call works from.use cotton_core::constants::{MoneyAccountKind, MoneyAccountSubtype, RealAccountSubtype, StatementKind};use serde_json::{Map, Value};usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{ fail, insert_row, optional_string, require_string, require_uuid, update_row, Valid,};usecrate::mcp::handlers::money::model::{ can_be_usual, clear_usual, load_money_accounts, take_usual_off_others, usual_refusal,MoneyAccount,};usecrate::mcp::protocol::ToolFailure;// ── the two foldings a name and a number get ────────────────────────────────pubfn fold(value: &str) -> String { value.trim().to_lowercase()}/// An institution as an account's identity reads it: folded, and without the/// legal form a statement may or may not print — "Invented Bank Limited" is/// "Invented Bank", "Example Bank Ltd" is "EXAMPLE Bank". Two statements of one account/// named the bank both ways on the owner's file and minted it twice (3 Sep/// 2026).pubfn institution_identity(value: &str) -> String {const LEGAL_FORMS: &[&str] = &["limited", "ltd", "pvt", "private", "plc", "inc", "corp", "corporation", "co", "n.a", "na"];let folded = fold(value);letmut words: Vec<&str> = folded .split(|c: char| c.is_whitespace() || c == ',') .map(|word| word.trim_end_matches('.')) .filter(|word| !word.is_empty()) .collect();while words.len() > 1 && words.last().is_some_and(|last| LEGAL_FORMS.contains(last)) { words.pop(); } words.join(" ")}/// Whether two masks name one account number: the digits of one end with the/// digits of the other, at least four of them — a statement that prints the/// whole masked number ("00045670009904") and one that prints its ending/// ("9904") are one account, and two numbers that only share an ending are/// not.pubfn same_number(held: &str, printed: &str) -> bool {let (short, long) = if held.len() <= printed.len() { (held, printed) } else { (printed, held) }; short.len() >= 4 && long.ends_with(short)}/// Whether `account` is the one a paper printing `institution` and `mask`/// (digits, [`normalise_mask`]) names.fn printed_as(account: &MoneyAccount, institution: &str, mask: &str) -> bool { account .institution .as_deref() .is_some_and(|held| institution_identity(held) == institution_identity(institution)) && normalise_mask(account.number_mask.as_deref()).is_some_and(|held| same_number(&held, mask))}/// A number mask is its DIGITS ONLY — "XX9007" and "**** 9007" are the same/// identity, and the letters and punctuation a bank glues on carry no meaning./// An empty result is "no mask", never an empty string, so it compares and/// stores as `NULL`.pubfn normalise_mask(mask: Option<&str>) -> Option<String> {let digits: String = mask .unwrap_or("") .chars() .filter(char::is_ascii_digit) .collect(); (!digits.is_empty()).then_some(digits)}/// The account kind is the personal kit's vocabulary. Its matching subtype/// still supplies the arithmetic rules elsewhere in the engine. Total over/// the subtypes a person opens: no other reaches a written row.fn account_kind_for_subtype(subtype: RealAccountSubtype) -> MoneyAccountKind {match subtype {RealAccountSubtype::Bank => MoneyAccountKind::Bank,RealAccountSubtype::CreditCard => MoneyAccountKind::CreditCard,RealAccountSubtype::Cash => MoneyAccountKind::Cash,RealAccountSubtype::Wallet => MoneyAccountKind::Wallet,RealAccountSubtype::Loan => MoneyAccountKind::Loan, }}// ── the writer ──────────────────────────────────────────────────────────────/// Queue one account row and hand back what it will be.////// The four columns a caller may never set — `id`, `workspace_id` and the two/// stamps — are this function's, exactly as the TypeScript spreads `row` BEFORE/// them so no key of the caller's can win.fn insert_account( ctx: &mutCtx<'_>, accounts: &mutVec<MoneyAccount>, kind: MoneyAccountKind, subtype: MoneyAccountSubtype, name: &str, institution: Option<String>, number_mask: Option<String>, currency: &str,) -> Valid<MoneyAccount> {// The first open place that can be the usual account becomes it, so a// fresh book has a usual account; at most one is ever usual, and once the// person has turned it off a later account does not take it back — a mark// left on an account since put away is taken off it first.let usual = can_be_usual(subtype.as_str()) && !accounts .iter() .any(|account| account.archived_at.is_none() && can_be_usual(account.subtype.as_str()));if usual { clear_usual(ctx, accounts)?;for account in accounts.iter_mut() { account.is_default = false; } }let id = ctx.new_uuid();letmut patch = Map::new(); patch.insert("kind".to_string(), Value::from(kind.as_str())); patch.insert("subtype".to_string(), Value::from(subtype.as_str())); patch.insert("name".to_string(), Value::from(name.to_string())); patch.insert("currency".to_string(), Value::from(currency)); patch.insert("is_default".to_string(), Value::Bool(usual)); patch.insert("counterparty_person_id".to_string(), Value::Null); patch.insert("archived_at".to_string(), Value::Null); patch.insert("institution".to_string(), institution.clone().map_or(Value::Null, Value::from), ); patch.insert("number_mask".to_string(), number_mask.clone().map_or(Value::Null, Value::from), ); insert_row(ctx, "cotton_money_accounts", &id, patch)?;let account = MoneyAccount { id, kind, subtype, name: name.to_string(), person_id: None, currency: currency.to_string(), institution, number_mask, is_default: usual, is_pooled: None, archived_at: None, }; accounts.push(account.clone());Ok(account)}/// Create one real-world account, refusing an identity another already holds.////// The printed identity is the file's own partial UNIQUE, and hitting it raw/// hands a caller a SQLite constraint string that says nothing about which/// account is already there. Read it first and say that account's name — the/// same ladder [`resolve_statement_account`] climbs, so a statement never/// reaches this refusal either.pubfn create_money_account_row( ctx: &mutCtx<'_>, accounts: &mutVec<MoneyAccount>, name: &str, kind: RealAccountSubtype, institution: Option<&str>, number_mask: Option<&str>, currency: &str,) -> Valid<MoneyAccount> {let name = name.trim().to_string();if name.is_empty() {return fail("an account needs a name"); }let institution = institution .map(str::trim) .filter(|value| !value.is_empty()) .map(str::to_string);let number_mask = normalise_mask(number_mask);iflet (Some(institution), Some(mask)) = (&institution, &number_mask) {ifletSome(clash) = accounts.iter().find(|account| printed_as(account, institution, mask)) {return fail(format!("\"{}\" ({}) is already {institution} ending {ending} — one account per printed \ identity, so rename that one with update_money_account rather than adding a \ second", clash.name, clash.id, ending = cotton_core::records::account_number_ending(mask) )); } } insert_account( ctx, accounts, account_kind_for_subtype(kind), kind.widen(), &name, institution, number_mask, currency, )}/// The account a statement's lines are keyed on — matched, or minted.pubfn resolve_statement_account( ctx: &mutCtx<'_>, accounts: &mutVec<MoneyAccount>, institution: &str, number_mask: Option<&str>, statement_kind: StatementKind, proposed_name: &str, currency: &str,) -> Valid<(MoneyAccount, bool)> {let folded = institution_identity(institution);let mask = normalise_mask(number_mask);let wanted = match statement_kind {StatementKind::Bank => RealAccountSubtype::Bank,StatementKind::CreditCard => RealAccountSubtype::CreditCard, };let wanted_subtype = wanted.widen();ifletSome(mask) = &mask {ifletSome(printed) = accounts.iter().find(|account| printed_as(account, institution, mask)) {returnOk((printed.clone(), false)); } } else {// No number on the paper. Matching on institution ALONE would merge a// savings account into a current one at the same bank, so the reader's// proposed name has to agree too.ifletSome(named) = accounts.iter().find(|account| { account .institution .as_ref() .is_some_and(|held| institution_identity(held) == folded) && fold(&account.name) == fold(proposed_name) && (account.subtype == wanted_subtype || (statement_kind == StatementKind::Bank && account.subtype == MoneyAccountSubtype::Loan)) }) {returnOk((named.clone(), false)); } }let account = create_money_account_row( ctx, accounts, proposed_name, wanted,Some(institution), number_mask, currency, )?;Ok((account, true))}// ── the answer shape ────────────────────────────────────────────────────────/// An account answers the same kind the create/update tools accept, and only/// the identifying ending of its number.pubfn account_answer(account: &MoneyAccount) -> Value {letmut out = Map::new(); out.insert("id".to_string(), Value::from(account.id.clone())); out.insert("name".to_string(), Value::from(account.name.clone())); out.insert("kind".to_string(),Value::from(account.kind.as_str()), ); out.insert("subtype".to_string(), Value::from(account.subtype.as_str())); out.insert("institution".to_string(), account.institution.clone().map_or(Value::Null, Value::from), ); out.insert("numberMask".to_string(), account.number_mask.as_deref().map(cotton_core::records::account_number_ending).map_or(Value::Null, Value::from), ); out.insert("archived".to_string(),Value::Bool(account.archived_at.is_some()), ); out.insert("usual".to_string(), Value::Bool(account.is_default)); out.insert("isPooled".to_string(),Value::Bool(account.is_pooled.unwrap_or( account.kind == MoneyAccountKind::Bank, )), ); out.insert("currency".to_string(),Value::from(account.currency.clone()), );Value::Object(out)}/// The book's home currency: the usual account's — the first real account/// that can be usual becomes it when made — else its first real account's/// (the oldest still open, else the oldest). The usual account comes first/// because accounts made in the same second (a seed, a template) tie on their/// creation time and fall back to id order, which is no order at all. A book/// with no account has none — and no totals.pubfn home_currency(accounts: &[MoneyAccount]) -> Option<String> {let real = |account: &&MoneyAccount| { !matches!( account.subtype,MoneyAccountSubtype::Category | MoneyAccountSubtype::Suspense ) && account.person_id.is_none() }; accounts .iter() .filter(|account| account.archived_at.is_none()) .filter(real) .find(|account| account.is_default) .or_else(|| { accounts .iter() .filter(|account| account.archived_at.is_none()) .find(real) }) .or_else(|| accounts.iter().find(real)) .map(|account| account.currency.clone())}// ── the tools ───────────────────────────────────────────────────────────────pubfn create_money_account(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_create_money_account(args)?;letmut accounts = load_money_accounts(ctx)?;let account = create_money_account_row( ctx, &mut accounts, &args.name, args.kind, args.institution.as_deref(), args.number_mask.as_deref(), &args.currency, )?; ctx.commit()?;Ok(account_answer(&account))}pubfn update_money_account(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_update_money_account(args)?;let accounts = load_money_accounts(ctx)?;letSome(found) = accounts.iter().find(|account| account.id == args.id) else {returnErr(ToolFailure::new(format!("no account with id {}", args.id))); };letmut account = found.clone();let stamp = crate::mcp::handlers::common::now_iso(ctx);letmut patch = Map::new(); patch.insert("updated_at".to_string(), Value::from(stamp.clone()));ifletSome(name) = &args.name { patch.insert("name".to_string(), Value::from(name.clone())); account.name = name.clone(); }ifletSome(archived) = args.archived {// At most one open place is usual: putting the usual one away takes// its mark off, and none is made usual in its place — with none the// bar asks which account each time.if archived && account.is_default { patch.insert("is_default".to_string(), Value::Bool(false)); account.is_default = false; }let next = archived.then(|| stamp.clone()); patch.insert("archived_at".to_string(), next.clone().map_or(Value::Null, Value::from), ); account.archived_at = next; }if args.usual == Some(false) {// Turned off: no account is usual until one is made usual again. patch.insert("is_default".to_string(), Value::Bool(false)); account.is_default = false; }if args.usual == Some(true) {// Read as it now stands: an account put away by this same call is// refused. The other's mark goes first; this account's is part of// its one write below.ifletSome(refusal) = usual_refusal(&account) {return fail(refusal); } take_usual_off_others(ctx, &accounts, &account.id)?; patch.insert("is_default".to_string(), Value::Bool(true)); account.is_default = true; }ifletSome(is_pooled) = args.is_pooled { patch.insert("is_pooled".to_string(), is_pooled.map_or(Value::Null, Value::Bool), ); account.is_pooled = is_pooled; } update_row(ctx, "cotton_money_accounts", &args.id, patch)?; ctx.commit()?;Ok(account_answer(&account))}// ── the validators ──────────────────────────────────────────────────────────structCreateMoneyAccountArgs { name: String, kind: RealAccountSubtype, institution: Option<String>, number_mask: Option<String>, currency: String,}fn validate_create_money_account(args: &Map<String, Value>) -> Valid<CreateMoneyAccountArgs> {letSome(name) = require_string(args, "name") else {return fail("a name is required"); };// The subtypes a person may OPEN an account as.let kind = match require_string(args, "kind").and_then(|raw| RealAccountSubtype::parse(&raw)) {Some(kind) => kind,None => {return fail(format!("kind must be one of: {}",RealAccountSubtype::ALL .iter() .map(|kind| kind.as_str()) .collect::<Vec<_>>() .join(", ") )) } };Ok(CreateMoneyAccountArgs { name, kind, institution: optional_string(args, "institution"), number_mask: optional_string(args, "numberMask"), currency: currency_arg(args)?, })}/// `currency`: an ISO 4217 code, three capital letters. Every account is held/// in one; none is assumed for it (no country is the default).fn currency_arg(args: &Map<String, Value>) -> Valid<String> {match args.get("currency") {None | Some(Value::Null) => fail("Which currency is this account in? Give currency, an ISO 4217 code such as EUR, USD or JPY."),Some(Value::String(code)) if code.len() == 3 && code.bytes().all(|b| b.is_ascii_uppercase()) => Ok(code.clone()),Some(_) => fail("currency is an ISO 4217 code, three capital letters (EUR, USD, JPY)"), }}structUpdateMoneyAccountArgs { id: String, name: Option<String>, archived: Option<bool>, usual: Option<bool>, is_pooled: Option<Option<bool>>,}fn validate_update_money_account(args: &Map<String, Value>) -> Valid<UpdateMoneyAccountArgs> {let id = require_uuid(args, "id")?;let name = optional_string(args, "name");if args.get("name").is_some() && name.is_none() {return fail("a name is required"); }let archived = match args.get("archived") {None => None,Some(Value::Bool(value)) => Some(*value),Some(_) => return fail("archived must be true or false"), };let usual = match args.get("usual") {None => None,Some(Value::Bool(value)) => Some(*value),Some(_) => return fail("usual must be true or false"), };let is_pooled = match args.get("isPooled") {None => None,Some(Value::Null) => Some(None),Some(Value::Bool(value)) => Some(Some(*value)),Some(_) => return fail("isPooled must be true, false or null"), };if name.is_none() && archived.is_none() && usual.is_none() && is_pooled.is_none() {return fail("nothing to change — pass a field to change"); }Ok(UpdateMoneyAccountArgs { id, name, archived, usual, is_pooled, })}#[cfg(test)]mod tests {usesuper::*;/// RULE: one account is one bank and one number however a statement/// prints them — the legal form left off, the number whole or its ending. #[test]fn a_statement_names_one_account_however_it_prints_the_bank_and_the_number() { assert_eq!(institution_identity("Invented Bank Limited"), institution_identity("Invented Bank")); assert_eq!(institution_identity("Example Bank Ltd."), institution_identity("EXAMPLE Bank")); assert_eq!(institution_identity("Invented Bank, N.A."), "invented bank"); assert_eq!(institution_identity("Limited"), "limited", "a name that is only a legal form stays a name"); assert_ne!(institution_identity("Invented Bank"), institution_identity("Invented Securities")); assert!(same_number("9904", "00045670009904")); assert!(same_number("00045670009904", "9904")); assert!(!same_number("12349904", "56789904"), "two numbers that share only an ending are two accounts"); assert!(!same_number("904", "00045670009904"), "fewer than four digits names no account"); }}