//! Paper to recorded transactions — the six statement tools, and the run they//! share.//!//! The order is the spec's and every step of it is a state written on the row//! before the next one starts, so a crash anywhere leaves something a person//! can read rather than a half-import nobody can name://!//! read → check → account → book//!//! NOTHING IS BOOKED ON A MISMATCH. The lines are saved — they are what the//! paper says, and losing them would be losing information — but the money is//! not, because the arithmetic says a line is missing or wrong and booking a//! known-wrong set is worse than booking none. The correction path is//! `update_statement_line` then `book_statement`.//!//! NOTHING HERE READS PAPER. The reader is the WORKER's, not a second one: a//! tool that built its own model leg would meter and refuse differently from//! the background pass, and "why did it work over MCP but not on its own" is//! the bug that costs a day. So `read_statement` puts the row back on the queue//! the worker drains, `submit_statement_reading` hands the run a reading the//! assistant already made, and `book_statement` needs no model at all. There is//! no `read` port on this path to reach for.//!//! THE RUN COMMITS IN STAGES, and that is a deliberate divergence. The//! TypeScript's `PgrestClient` applied each write on its own, so every stage//! read what the stage before it had written — the account resolve, the line//! write, the booking and the transfer sweep all depend on that. Here the//! writer collects and folds at `ctx.commit()`, so the run commits at each//! stage boundary rather than once at the end. Every fold is still atomic; what//! a stage cannot do is read its own uncommitted writes.use std::collections::BTreeMap;use cotton_core::constants::{LineDirection, StatementKind};use cotton_core::rules::money::statement_check::{ check_statement, CheckInput, CheckLine, CheckResult,};use serde_json::{json, Map, Value};usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{ bounded_limit, clearable_string, fail, is_calendar_date, maybe_row, now_iso, optional_string, require_uuid, rows, text, Clearable, Valid,};usecrate::mcp::handlers::money::accounts::resolve_statement_account;usecrate::mcp::handlers::money::book::{book_statement_lines, booked_line_ids, BookResult};usecrate::mcp::handlers::money::engine_shim::{ is_readable_statement_doc_type, parse_read_output, StatementReadOutput, READABLE_STATEMENT_DOC_TYPES,};usecrate::mcp::handlers::money::model::{load_money_accounts, MoneyAccount};usecrate::mcp::handlers::money::rows::{ account_key_for, ensure_pending_statement, fingerprints_for, load_statement, load_statement_lines, patch_statement, recorded_counts_for, requeue_statement, write_statement_lines, FingerprintLine, StatementLineRow, StatementRow, WriteLinesInput, STATEMENT_COLUMNS,};usecrate::mcp::handlers::money::statement_visual_check::{ verify_statement_reading, verify_visual_facts, StatementFigures, VisualCheckError, VisualStatementHeader,VisualStatementLine,};usecrate::mcp::protocol::ToolFailure;usecrate::mcp::read_db::{Filter, Query};/// What `read_by` records when a caller did not name itself.const DEFAULT_READ_BY: &str = "assistant";use cotton_core::rules::shell_lines::LineRow;use cotton_core::records::amount::{amount, MoneyForm, MoneyWords};/// The document a statement may be minted for — a filed `bank_statement` or/// `card_statement`, in this workspace — or a refusal that names the way out.fn assert_readable_statement_document(ctx: &Ctx<'_>, document_id: &str) -> Valid<()> {let found = maybe_row( ctx, &Query::on("cotton_documents") .columns(&["id", "doc_type", "status", "original_name"]) .eq("id", document_id.to_string()) .limit(1), )?;letSome(document) = found else {return fail(format!("no document with id {document_id}")); };let doc_type = text(&document, "doc_type");if !is_readable_statement_doc_type(doc_type.as_deref()) {return fail(format!("\"{}\" is filed as {} — only a document typed {} can be read as a statement. \ update_document can change its type.", text(&document, "original_name").unwrap_or_default(), doc_type.unwrap_or_else(|| "no type".to_string()), READABLE_STATEMENT_DOC_TYPES.join(" or ") )); }Ok(())}// ── read_statement ──────────────────────────────────────────────────────────pubfn read_statement(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let document_id = require_uuid(args, "documentId")?; assert_readable_statement_document(ctx, &document_id)?;let ensured = ensure_pending_statement(ctx, &document_id)?;// The SHARED re-read writer, which the host's `repend` also calls. What a// re-read clears is decided in one place. requeue_statement(ctx, &ensured.id)?; ctx.commit()?;Ok(json!({"statementId": ensured.id,"documentId": document_id,"readStatus": "pending","note": "Marked pending. The server reads it on its own only with the user's own API \ key; otherwise read the paper (get_document_bytes) and call \ submit_statement_reading.", }))}// ── the run ─────────────────────────────────────────────────────────────────/// The account the lines were keyed on, as the caller is told about it.pubstructAccountOutcome { id: String, name: String, institution: Option<String>, number_mask: Option<String>, created: bool,}implAccountOutcome {fn to_value(&self) -> Value { json!({"id": self.id,"name": self.name,"institution": self.institution,"numberMask": self.number_mask.as_deref().map(cotton_core::records::account_number_ending),"created": self.created, }) }}/// `pub`, and the fields with it (design P3): the statements WORKER runs this/// same pipeline from `cotton_server::money`, and the crate boundary now runs/// between them. `pub(crate)` here would mean "the tools only", which is the/// opposite of why this type exists — one implementation of the money run,/// whether an assistant handed in a reading or the worker read the paper.pubstructDiscrepancy {pub stated_closing_minor: Option<i64>,pub expected_closing_minor: Option<i64>,pub sum_in_minor: i64,pub sum_out_minor: i64,pub first_break_line_no: Option<i64>,/// The statement's currency: the sentence says each figure in it.pub currency: String,}implDiscrepancy {fn to_value(&self) -> Value { json!({"statedClosingMinor": self.stated_closing_minor,"expectedClosingMinor": self.expected_closing_minor,"sumInMinor": self.sum_in_minor,"sumOutMinor": self.sum_out_minor,"firstBreakLineNo": self.first_break_line_no, }) }}fn check_lines_of(lines: &[StatementLineRow]) -> Vec<CheckLine> { lines .iter() .map(|line| CheckLine { line_no: line.line_no as f64, amount_minor: line.amount_minor as f64, direction: line.direction, balance_after_minor: line.balance_after_minor.map(|value| value as f64), ignored: line.ignored_reason.is_some(), }) .collect()}fn run_check( kind: StatementKind, opening: Option<i64>, closing: Option<i64>, lines: &[StatementLineRow],) -> Valid<CheckResult> { check_statement(&CheckInput { kind, opening_minor: opening.map(|value| value as f64), closing_minor: closing.map(|value| value as f64), lines: check_lines_of(lines), }) .map_err(|error| ToolFailure::new(error.to_string()))}/// The account the lines are keyed on.////// The statement's own, when it has one: by id, never the header, and a pinned/// id that names no row is said out loud rather than resolved around —/// `account_id` is `ON DELETE SET NULL`, so the only way here is a write that/// raced this run, and a fresh resolve would quietly re-key the whole/// statement. With no account yet — the first reading of a fresh paper — the/// header is what there is, and the ladder matches or creates against it.////// And resolved ONCE per statement, ever. A statement that already has an/// account is PINNED to it: the paper's account does not change between/// readings, and resolving the header again is how a re-spelling ("Meridian/// Bank" → "Meridian Bank Ltd") minted a SECOND account, re-keyed every/// fingerprint onto it, and left the first reading's booked rows where no twin/// lookup could see them — so the booking pass posted every line again.fn account_for( ctx: &mutCtx<'_>, accounts: &mutVec<MoneyAccount>, pinned_id: Option<&str>, output: &StatementReadOutput,) -> Valid<(MoneyAccount, bool)> {ifletSome(pinned_id) = pinned_id {letSome(pinned) = accounts.iter().find(|account| account.id == pinned_id) else {return fail(format!("this statement is attached to account {pinned_id}, which no longer exists — \ read_statement again once the account's removal has settled" )); };returnOk((pinned.clone(), false)); } resolve_statement_account( ctx, accounts, &output.header.institution, output.header.number_mask.as_deref(), output.header.kind, &output.header.account_name, &output.header.currency, )}pubenumRunOutcome {Read { statement_id: String, booked: usize, already_booked: usize, balance_check: String, account: AccountOutcome, },Mismatch { statement_id: String, account: AccountOutcome, discrepancy: Discrepancy, },}/// The whole pipeline, entered after its read step — the reading is handed in.////// `pub(crate)` for the statements WORKER, which reads the paper itself and/// then runs exactly this: one implementation of "which account is this", of/// what a line write does to a booked row, and of when a statement is `read`.pubfn run_statement( ctx: &mutCtx<'_>, statement_id: &str, output: &StatementReadOutput, read_by: &str,) -> Valid<RunOutcome> {letSome(statement) = load_statement(ctx, statement_id)? else {return fail(format!("no statement with id {statement_id}")); };// The text layer is only a candidate reading. A trusted renderer has to// agree with it before this path can create an account, store lines or book// a transaction. `None` is deliberately a refusal, never a compatibility// path for hosts that have not installed the platform renderer yet.ifletErr(reason) = verify_statement_reading( ctx.services.statement_visual.as_deref(), ctx.workspace_id, statement_id, output, ) { rest_visual_refusal(ctx, statement_id, &reason)?;return fail(reason.to_string()); }// ── account, then header, lines, check ──────────────────────────────────//// The account is resolved BEFORE any line is fingerprinted, because the// fingerprint keys on the STORED account's identity — the institution and// mask as the account row carries them — never on the header text the model// read off one page, whose spelling drifts between readings and would key// two statements of one account differently.letmut accounts = load_money_accounts(ctx)?;let (account, created) = account_for(ctx, &mut accounts, statement.account_id.as_deref(), output)?;let account_outcome = AccountOutcome { id: account.id.clone(), name: account.name.clone(), institution: account.institution.clone(), number_mask: account.number_mask.clone(), created, };// A minted account has to be IN THE FILE before the booking pass reads the// chart, so the stage boundary is here. ctx.commit()?;// Which lines a transaction already cites, read BEFORE anything is written:// those rows are never deleted by a re-read, whatever the second reading// says, because deleting one would orphan its evidence.let existing = load_statement_lines(ctx, statement_id)?;let existing_ids: Vec<String> = existing.iter().map(|line| line.id.clone()).collect();let booked_before = booked_line_ids(ctx, &existing_ids)?;let booked_ids: Vec<String> = booked_before.keys().cloned().collect();let written = write_statement_lines( ctx,WriteLinesInput { statement_id, account_key: &account_key_for( account.institution.as_deref(), account.number_mask.as_deref(), statement_id, ), lines: &output.lines, existing: &existing, booked_line_ids: &booked_ids, }, )?;let stored = written.stored;let check = run_check( output.header.kind, output.header.opening_balance_minor, output.header.closing_balance_minor, &stored, )?;// ── header ──────────────────────────────────────────────────────────────let stamp = now_iso(ctx);letmut header = Map::new(); header.insert("account_id".to_string(), Value::from(account.id.clone())); header.insert("kind".to_string(), Value::from(output.header.kind.as_str())); header.insert("period_start".to_string(),Value::from(output.header.period_start.clone()), ); header.insert("period_end".to_string(),Value::from(output.header.period_end.clone()), ); header.insert("opening_balance_minor".to_string(), output .header .opening_balance_minor .map_or(Value::Null, Value::from), ); header.insert("closing_balance_minor".to_string(), output .header .closing_balance_minor .map_or(Value::Null, Value::from), ); header.insert("currency".to_string(),Value::from(output.header.currency.clone()), ); header.insert("line_count".to_string(), Value::from(stored.len() as i64)); header.insert("sum_in_minor".to_string(),Value::from(check.sum_in_minor as i64), ); header.insert("sum_out_minor".to_string(),Value::from(check.sum_out_minor as i64), ); header.insert("balance_check".to_string(),Value::from(check.balance_check.as_str()), ); header.insert("read_by".to_string(), Value::from(read_by.to_string())); header.insert("read_at".to_string(), Value::from(stamp.clone()));// A statement that reads cleanly now is not still carrying the reason an// earlier attempt failed. header.insert("read_error".to_string(), Value::Null); header.insert("updated_at".to_string(), Value::from(stamp));if check.balance_check.as_str() == "mismatch" { header.insert("read_status".to_string(), Value::from("mismatch")); patch_statement(ctx, statement_id, header)?; ctx.commit()?;returnOk(RunOutcome::Mismatch { statement_id: statement_id.to_string(), account: account_outcome, discrepancy: Discrepancy { stated_closing_minor: output.header.closing_balance_minor, expected_closing_minor: check.expected_closing_minor.map(|value| value as i64), sum_in_minor: check.sum_in_minor as i64, sum_out_minor: check.sum_out_minor as i64, first_break_line_no: check.first_break_line_no.map(|value| value as i64), currency: output.header.currency.clone(), }, }); } header.insert("read_status".to_string(), Value::from("read")); patch_statement(ctx, statement_id, header)?; ctx.commit()?;let booked = book_and_finish(ctx, &account.id, &stored)?; ctx.commit()?;Ok(RunOutcome::Read { statement_id: statement_id.to_string(), booked: booked.booked, already_booked: booked.skipped, balance_check: check.balance_check.as_str().to_string(), account: account_outcome, })}structFinishResult { booked: usize, skipped: usize,}/// Book one row for each statement line. Meaning and transfer pairing are/// explicit acts, never a side effect of importing a statement.fn book_and_finish( ctx: &mutCtx<'_>, account_id: &str, lines: &[StatementLineRow],) -> Valid<FinishResult> {let accounts = load_money_accounts(ctx)?;let currency = accounts .iter() .find(|account| account.id == account_id) .map(|account| account.currency.clone()) .ok_or_else(|| ToolFailure::new(format!("no account with id {account_id}")))?;let result: BookResult = book_statement_lines(ctx, account_id, ¤cy, lines)?;Ok(FinishResult { booked: result.booked,// What the caller reports as "already there". An IGNORED line is not// counted here: it was never money, so it is not work that was skipped// — and the count a caller prints comes from the lines themselves. skipped: result.already_booked, })}// ── submit_statement_reading ────────────────────────────────────────────────/// The discrepancy, in sentences of the `money` line set (`rows`: this/// database's lines; empty says the kit's) — the numbers ride beside it as/// numbers.pubfn describe_discrepancy(d: &Discrepancy, rows: &[LineRow]) -> String {let words = MoneyWords::of_rows(rows);let money = |minor: i64| amount(minor, Some(&d.currency), &words).said(MoneyForm::Money, &words);let line = |line: &str, fills: &[(&str, &str)]| words.say(line, fills).unwrap_or_default();let closing = match (d.stated_closing_minor, d.expected_closing_minor) { (None, _) => line("statement.closing_unprinted", &[]), (Some(stated), None) => line("statement.closing", &[("stated", &money(stated))]), (Some(stated), Some(expected)) => line("statement.closing_and_sum", &[("stated", &money(stated)), ("expected", &money(expected))]), };let flows = line("statement.flows", &[("in", &money(d.sum_in_minor)), ("out", &money(d.sum_out_minor))]);let found = match d.first_break_line_no {None => line("statement.break_unknown", &[]),Some(line_no) => line("statement.break_at", &[("line", &line_no.to_string())]), }; [closing, flows, found].join(" ")}/// `readBy`'s ceiling — the column is text, the label is a name, not prose.const STATEMENT_READ_BY_MAX: usize = 80;pubfn submit_statement_reading(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let statement_id = optional_string(args, "statementId");let document_id = optional_string(args, "documentId");if statement_id.is_none() == document_id.is_none() {returnErr(ToolFailure::new("pass exactly one of statementId or documentId", )); }for (key, value) in [ ("statementId", statement_id.as_ref()), ("documentId", document_id.as_ref()), ] {ifletSome(value) = value {if !crate::mcp::handlers::common::is_uuid(value) {returnErr(ToolFailure::new(format!("{key} must be a uuid"))); } } }let read_by = optional_string(args, "readBy").unwrap_or_else(|| DEFAULT_READ_BY.to_string());if read_by.chars().count() > STATEMENT_READ_BY_MAX {returnErr(ToolFailure::new(format!("readBy must be at most {STATEMENT_READ_BY_MAX} characters" ))); }letSome(Value::Object(_header)) = args.get("header") else {returnErr(ToolFailure::new("header must be an object — the statement's header, in the reader's contract", )); };letSome(Value::Array(_lines)) = args.get("lines") else {returnErr(ToolFailure::new("lines must be an array — every entry printed on the statement, in order", )); };// The contract is run FIRST, before any row is touched, and its refusal is// the reader's own path-only sentence — the field that broke, never the// value, which on this path is a line off somebody's bank statement. A// refused reading marks nothing on the row: the assistant fixes the payload// and calls again.let output = parse_read_output( args.get("header").expect("header was matched above"), args.get("lines").expect("lines were matched above"), ) .map_err(|error| ToolFailure::new(error.text()))?;let statement_id = match statement_id {Some(id) => id,None => {let document_id = document_id.unwrap_or_default();// The same minting `read_statement` does: a readable statement with// no row gets one, an existing row is found. assert_readable_statement_document(ctx, &document_id)?;let ensured = ensure_pending_statement(ctx, &document_id)?; ctx.commit()?; ensured.id } };let outcome = run_statement(ctx, &statement_id, &output, &read_by)?;// The row's own truth, read after the run: how many entries a transaction// now cites, and how many were never money.let statement_id = match &outcome {RunOutcome::Read { statement_id, .. } | RunOutcome::Mismatch { statement_id, .. } => { statement_id.clone() } };let lines = load_statement_lines(ctx, &statement_id)?;let line_ids: Vec<String> = lines.iter().map(|line| line.id.clone()).collect();let booked = booked_line_ids(ctx, &line_ids)?;let counts = json!({"read": lines.len(),"booked": booked.len(),"ignored": lines.iter().filter(|line| line.ignored_reason.is_some()).count(), });match outcome {RunOutcome::Mismatch { statement_id, account, discrepancy, .. } => Ok(json!({"statementId": statement_id,"readStatus": "mismatch","balanceCheck": "mismatch","lines": counts,"transactions": { "actual": 0, "alreadyBooked": booked.len() },"account": account.to_value(),"discrepancy": discrepancy.to_value(),"note": format!("The totals do not agree, so nothing was recorded. The entries are saved. {} \ Read those lines again and call submit_statement_reading again with the whole \ reading.", describe_discrepancy(&discrepancy, &crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id)) ), })),RunOutcome::Read { statement_id, booked, already_booked, balance_check, account, .. } => {let out = json!({"statementId": statement_id,"readStatus": "read","balanceCheck": balance_check,"lines": counts,"transactions": { "actual": booked, "alreadyBooked": already_booked },"account": account.to_value(), });Ok(out) } }}fn rest_visual_refusal(ctx: &mutCtx<'_>, id: &str, reason: &VisualCheckError) -> Valid<()> {letmut resting = Map::new(); resting.insert("read_status".into(), Value::from("failed")); resting.insert("read_error".into(), Value::from(reason.stored_reason())); resting.insert("updated_at".into(), Value::from(now_iso(ctx))); patch_statement(ctx, id, resting)?; ctx.commit()}// ── book_statement ──────────────────────────────────────────────────────────pubfn book_statement_tool(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let id = require_uuid(args, "id")?;letSome(statement) = load_statement(ctx, &id)? else {returnErr(ToolFailure::new(format!("no statement with id {id}"))); };letSome(account_id) = statement.account_id.clone() else {returnErr(ToolFailure::new("this statement is not attached to an account yet — read it first with read_statement", )); };let lines = load_statement_lines(ctx, &id)?;let facts = StatementFigures { header: VisualStatementHeader { page: 1, period_start: statement.period_start.clone().unwrap_or_default(), period_end: statement.period_end.clone().unwrap_or_default(), opening_balance_minor: statement.opening_balance_minor, closing_balance_minor: statement.closing_balance_minor, }, lines: lines.iter().map(|line| VisualStatementLine { page: line.page, posted_on: line.posted_on.clone(), amount_minor: line.amount_minor, direction: line.direction, balance_after_minor: line.balance_after_minor, ignored: line.ignored_reason.is_some(), }).collect(), };ifletErr(reason) = verify_visual_facts(ctx.services.statement_visual.as_deref(), ctx.workspace_id, &id, &facts) { rest_visual_refusal(ctx, &id, &reason)?;returnErr(ToolFailure::new(reason.to_string())); }let kind = if statement.kind == "credit_card" {StatementKind::CreditCard } else {StatementKind::Bank };let check = run_check( kind, statement.opening_balance_minor, statement.closing_balance_minor, &lines, )?;if check.balance_check.as_str() == "mismatch" {returnErr(ToolFailure::new("the statement totals do not agree, so its entries cannot be recorded", )); }let result = book_and_finish(ctx, &account_id, &lines)?; ctx.commit()?;Ok(json!({"statementId": id,"recorded": result.booked,"alreadyThere": result.skipped, }))}// ── list_statements ─────────────────────────────────────────────────────────pubfn list_statements(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let account_id = optional_string(args, "accountId");ifletSome(value) = account_id.as_ref() {if !crate::mcp::handlers::common::is_uuid(value) {returnErr(ToolFailure::new("accountId must be a uuid")); } }const READ_STATUSES: [&str; 4] = ["pending", "read", "mismatch", "failed"];let read_status = optional_string(args, "readStatus");ifletSome(value) = read_status.as_ref() {if !READ_STATUSES.contains(&value.as_str()) {returnErr(ToolFailure::new(format!("readStatus must be one of: {}", READ_STATUSES.join(", ") ))); } }let from = optional_string(args, "from");let to = optional_string(args, "to");for (key, value) in [("from", from.as_ref()), ("to", to.as_ref())] {ifletSome(value) = value {if !is_calendar_date(value) {returnErr(ToolFailure::new(format!("{key} must be YYYY-MM-DD"))); } } }iflet (Some(from), Some(to)) = (from.as_ref(), to.as_ref()) {if from > to {returnErr(ToolFailure::new("from must not be after to")); } }let limit = bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST);letmut query = Query::on("cotton_money_statements").columns(STATEMENT_COLUMNS);ifletSome(account_id) = account_id { query = query.eq("account_id", account_id); }ifletSome(read_status) = read_status { query = query.eq("read_status", read_status); }ifletSome(from) = from { query = query.filter(Filter::Gte("period_end".to_string(), from.into())); }ifletSome(to) = to { query = query.filter(Filter::Lte("period_start".to_string(), to.into())); }// A statement waiting to be read has NO period yet — the reader is what// fills those two dates in. Ordering on `period_start` alone therefore// heaps every pending statement at one end of the list on the strength of a// date nobody has read, so a row with no period falls back to when it was// filed, which is the only date it actually has.//// `COALESCE(period_start, created_at) DESC` is one expression the query// builder cannot spell, so the ordering is done here, over a page the// filters have already narrowed. `id` breaks the tie, so two rows filed in// the same millisecond keep one order between runs.letmut found = rows(ctx, &query)?; found.sort_by(|left, right| {let key = |row: &Map<String, Value>| { ( text(row, "period_start") .or_else(|| text(row, "created_at")) .unwrap_or_default(), text(row, "id").unwrap_or_default(), ) }; key(right).cmp(&key(left)) }); found.truncate(limit as usize);let statement_ids: Vec<String> = found.iter().filter_map(|row| text(row, "id")).collect();let recorded: BTreeMap<String, i64> = recorded_counts_for(ctx, &statement_ids)?;let statements: Vec<Value> = found .iter() .map(|row| {let id = text(row, "id").unwrap_or_default();let number = |column: &str| -> Value {match row.get(column) {None | Some(Value::Null) => Value::Null, _ => Value::from(crate::mcp::handlers::common::int(row, column)), } }; json!({"id": id,"documentId": text(row, "document_id"),"accountId": text(row, "account_id"),"kind": text(row, "kind"),// Null until the paper has been read — a pending row knows only// which document it is about, and saying "1970-01-01" would be// a lie."period": { "from": text(row, "period_start"), "to": text(row, "period_end") },"openingBalanceMinor": number("opening_balance_minor"),"closingBalanceMinor": number("closing_balance_minor"),"currency": text(row, "currency"),"readStatus": text(row, "read_status"),"readError": text(row, "read_error"),"balanceCheck": text(row, "balance_check"),"lineCount": crate::mcp::handlers::common::int(row, "line_count"),"recordedCount": recorded.get(&id).copied().unwrap_or(0),"sumInMinor": crate::mcp::handlers::common::int(row, "sum_in_minor"),"sumOutMinor": crate::mcp::handlers::common::int(row, "sum_out_minor"), }) }) .collect();Ok(json!({ "statements": statements }))}// ── get_statement ───────────────────────────────────────────────────────────fn header_out(statement: &StatementRow) -> Map<String, Value> {letmut out = Map::new(); out.insert("id".to_string(), Value::from(statement.id.clone())); out.insert("documentId".to_string(),Value::from(statement.document_id.clone()), ); out.insert("accountId".to_string(), statement .account_id .clone() .map_or(Value::Null, Value::from), ); out.insert("kind".to_string(), Value::from(statement.kind.clone())); out.insert("period".to_string(), json!({"from": statement.period_start,"to": statement.period_end, }), ); out.insert("openingBalanceMinor".to_string(), statement .opening_balance_minor .map_or(Value::Null, Value::from), ); out.insert("closingBalanceMinor".to_string(), statement .closing_balance_minor .map_or(Value::Null, Value::from), ); out.insert("currency".to_string(),Value::from(statement.currency.clone()), ); out.insert("readStatus".to_string(),Value::from(statement.read_status.clone()), ); out.insert("readError".to_string(), statement .read_error .clone() .map_or(Value::Null, Value::from), ); out.insert("readBy".to_string(), statement.read_by.clone().map_or(Value::Null, Value::from), ); out.insert("readAt".to_string(), statement.read_at.clone().map_or(Value::Null, Value::from), ); out.insert("balanceCheck".to_string(),Value::from(statement.balance_check.clone()), ); out.insert("lineCount".to_string(), Value::from(statement.line_count)); out.insert("sumInMinor".to_string(),Value::from(statement.sum_in_minor), ); out.insert("sumOutMinor".to_string(),Value::from(statement.sum_out_minor), ); out}pubfn get_statement(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let id = require_uuid(args, "id")?;let include_lines = args.get("includeLines") != Some(&Value::Bool(false));letSome(statement) = load_statement(ctx, &id)? else {returnErr(ToolFailure::new(format!("no statement with id {id}"))); };letmut out = header_out(&statement);if !include_lines {returnOk(Value::Object(out)); }let lines = load_statement_lines(ctx, &id)?;let line_ids: Vec<String> = lines.iter().map(|line| line.id.clone()).collect();let booked = booked_line_ids(ctx, &line_ids)?; out.insert("lines".to_string(),Value::Array( lines .iter() .map(|line| { json!({"id": line.id,"page": line.page,"lineNo": line.line_no,"postedOn": line.posted_on,"text": line.text,"amountMinor": line.amount_minor,"direction": line.direction.as_str(),"balanceAfterMinor": line.balance_after_minor,"reference": line.reference,"ignoredReason": line.ignored_reason,// DERIVED, never stored — one writer per fact."state": matchcrate::mcp::handlers::money_views::line_state(booked.get(&line.id).map(String::as_str), line.ignored_reason.as_deref()) {"recorded" => "booked", "skipped" => "ignored", _ => "unbooked", },"transactionId": booked.get(&line.id),"viewState": crate::mcp::handlers::money_views::line_state(booked.get(&line.id).map(String::as_str), line.ignored_reason.as_deref()), }) }) .collect(), ), );Ok(Value::Object(out))}// ── update_statement_line ───────────────────────────────────────────────────pubfn update_statement_line(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let id = require_uuid(args, "id")?;let posted_on = optional_string(args, "postedOn");ifletSome(value) = posted_on.as_ref() {if !is_calendar_date(value) {returnErr(ToolFailure::new("postedOn must be YYYY-MM-DD")); } }let amount_minor =match args.get("amountMinor") {None => None,Some(Value::Number(number)) => match number.as_i64() {Some(value) if value > 0 => Some(value),Some(_) => returnErr(ToolFailure::new("amountMinor must be greater than zero — direction says which way the money \ went", )),None => {returnErr(ToolFailure::new("amountMinor must be positive whole minor units — 2450.00 is 245000 for a currency with two decimal places, and a value \ with a decimal is refused rather than rounded", )) } },Some(_) => returnErr(ToolFailure::new("amountMinor must be positive whole minor units — 2450.00 is 245000 for a currency with two decimal places, and a value with a \ decimal is refused rather than rounded", )), };let direction = match args.get("direction") {None => None,Some(Value::String(value)) if value == "in" => Some(LineDirection::In),Some(Value::String(value)) if value == "out" => Some(LineDirection::Out),Some(_) => returnErr(ToolFailure::new("direction must be \"in\" or \"out\"")), };let ignored_reason = clearable_string(args, "ignoredReason");if posted_on.is_none() && amount_minor.is_none() && direction.is_none() && ignored_reason.is_unchanged() {returnErr(ToolFailure::new("nothing to change — pass a field to change", )); }let found = maybe_row( ctx, &Query::on("cotton_money_statement_lines") .columns(&["id", "statement_id"]) .eq("id", id.clone()) .limit(1), )?;letSome(row) = found else {returnErr(ToolFailure::new(format!("no statement entry with id {id}"))); };let statement_id = text(&row, "statement_id").unwrap_or_default();// A booked line's transaction CITES it. Editing the amount here would leave// the evidence saying one thing and the money saying another, with nothing// in the file to say which is right — so the refusal names the way out// instead of half-doing it.let already_booked = booked_line_ids(ctx, std::slice::from_ref(&id))?;ifletSome(transaction_id) = already_booked.get(&id) {returnErr(ToolFailure::new(format!("that entry is already in the user's money as transaction {transaction_id}; its statement evidence stays. Use update_transaction for its tag, person, month or notes" ))); }letmut patch = Map::new();ifletSome(posted_on) = posted_on { patch.insert("posted_on".to_string(), Value::from(posted_on)); }ifletSome(amount_minor) = amount_minor { patch.insert("amount_minor".to_string(), Value::from(amount_minor)); }ifletSome(direction) = direction { patch.insert("direction".to_string(), Value::from(direction.as_str())); }match &ignored_reason {Clearable::Unchanged => {}Clearable::Cleared => { patch.insert("ignored_reason".to_string(), Value::Null); }Clearable::Set(value) => { patch.insert("ignored_reason".to_string(), Value::from(value.clone())); } } ctx.writer()? .upsert("cotton_money_statement_lines", &id, patch);// The correction has to be IN the file before the fingerprints and the// check are computed off it — both read the whole statement back. ctx.commit()?;letSome(statement) = load_statement(ctx, &statement_id)? else {returnErr(ToolFailure::new(format!("no statement with id {statement_id}" ))); };let lines = load_statement_lines(ctx, &statement_id)?;// The fingerprint follows the content. It is the line's identity for the// next reading of this paper: left as it was, a later re-read would not// recognise the corrected line, keep it as booked-and-lost or delete it,// and mint a second row for the same money. restate_fingerprints(ctx, statement.account_id.as_deref(), &statement_id, &lines)?;// The check runs again straight away, so the answer says whether the// correction fixed it — which is the whole reason the tool exists.let kind = if statement.kind == "credit_card" {StatementKind::CreditCard } else {StatementKind::Bank };let check = run_check( kind, statement.opening_balance_minor, statement.closing_balance_minor, &lines, )?;letmut header = Map::new(); header.insert("sum_in_minor".to_string(),Value::from(check.sum_in_minor as i64), ); header.insert("sum_out_minor".to_string(),Value::from(check.sum_out_minor as i64), ); header.insert("balance_check".to_string(),Value::from(check.balance_check.as_str()), );// `read_status` IS the worker's queue, and `pending` is somebody asking for// this statement to be read again. Stamping `read` over it because the// arithmetic happens to agree NOW would cancel a re-read the person asked// for a second ago, silently — so a pending statement keeps its place in// the queue and only its totals are re-stated. A `failed` statement keeps// its status too: `failed` is a state only the owner leaves, and a// correction to one line is not a reading of the paper. Only a statement// that HAS been read — `read` or `mismatch` — moves between those two on// its arithmetic, and when the stamp lands it also clears `read_error`.let stamps_status = statement.read_status == "read" || statement.read_status == "mismatch";if stamps_status { header.insert("read_status".to_string(),Value::from(if check.balance_check.as_str() == "mismatch" {"mismatch" } else {"read" }), ); header.insert("read_error".to_string(), Value::Null); } header.insert("updated_at".to_string(), Value::from(now_iso(ctx))); patch_statement(ctx, &statement_id, header)?; ctx.commit()?;Ok(json!({"statementId": statement_id,"lineId": id,"balanceCheck": check.balance_check.as_str(),"sumInMinor": check.sum_in_minor as i64,"sumOutMinor": check.sum_out_minor as i64,"expectedClosingMinor": check.expected_closing_minor.map(|value| value as i64),"firstBreakLineNo": check.first_break_line_no.map(|value| value as i64),"note": if check.balance_check.as_str() == "mismatch" {"The totals still do not agree. Fix another entry, then call book_statement." } else {"The totals agree now. Call book_statement to record its entries." }, }))}/// Re-key one statement's lines after a correction.////// Keyed on the STORED account's identity, exactly as the run keys them (the/// statement's id when it has no account yet). Only the fingerprints that moved/// are written, and each one is parked on a scratch value first: two identical/// lines swap occurrences when the first of them is corrected, and writing the/// second one's new key while the first still holds it would trip/// `(statement_id, fingerprint)`.fn restate_fingerprints( ctx: &mutCtx<'_>, account_id: Option<&str>, statement_id: &str, lines: &[StatementLineRow],) -> Valid<()> {let accounts = load_money_accounts(ctx)?;let account = account_id.and_then(|id| accounts.iter().find(|account| account.id == id));let account_key = account_key_for( account.and_then(|account| account.institution.as_deref()), account.and_then(|account| account.number_mask.as_deref()), statement_id, );// `load_statement_lines` answers in (page, line_no) order — printed order,// which is what the occurrence counter numbers by.let fresh = fingerprints_for( &account_key, &lines .iter() .map(|line| FingerprintLine { posted_on: line.posted_on.clone(), amount_minor: line.amount_minor, direction: line.direction, text: line.text.clone(), }) .collect::<Vec<_>>(), )?;let moved: Vec<(String, String)> = lines .iter() .zip(fresh.iter()) .filter(|(line, fingerprint)| &&line.fingerprint != fingerprint) .map(|(line, fingerprint)| (line.id.clone(), fingerprint.clone())) .collect();if moved.is_empty() {returnOk(()); }for (line_id, _) in &moved {letmut patch = Map::new(); patch.insert("fingerprint".to_string(),Value::from(format!("parked:{line_id}")), ); ctx.writer()? .upsert("cotton_money_statement_lines", line_id, patch); }for (line_id, fingerprint) in &moved {letmut patch = Map::new(); patch.insert("fingerprint".to_string(), Value::from(fingerprint.clone())); ctx.writer()? .upsert("cotton_money_statement_lines", line_id, patch); }Ok(())}#[cfg(test)]mod tests {usesuper::*;/// RULE: A statement that does not add up is described in the statement's own currency — a euro statement's figures carry the euro sign, never a bare rupee-shaped number. #[test]fn a_euro_statements_discrepancy_is_said_in_euros() {let said = describe_discrepancy(&Discrepancy { stated_closing_minor: Some(125_050), expected_closing_minor: Some(120_000), sum_in_minor: 5_000, sum_out_minor: 0, first_break_line_no: Some(3), currency: "EUR".to_string(), }, &[]); assert!(said.contains("€1,250.50"), "{said}"); assert!(said.contains("€1,200"), "{said}"); assert!(said.contains("€50") && said.contains("€0"), "{said}"); }}