//! The statement tools, over `dispatch::call_tool`. //! //! The fixture writes its rows STRAIGHT to the file, exactly as the //! TypeScript's does: nothing here is testing how a statement gets filed, and a //! sync push would only put a second contract between the test and the row it //! is asserting on. The page text is invented; the Rust `read_statement` never //! reads a page, so the TypeScript's `MERIDIAN_PAGES` fixture is not needed — //! only that pages exist at all. //! //! Every case drives the tool through `dispatch::call_tool` over a fake //! `ToolServices` rather than the `/v1/mcp` endpoint. mod support; use cotton_core::constants::LineDirection; use cotton_tools::mcp::handlers::money::rows::{ account_key_for, fingerprints_for, FingerprintLine, }; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use support::harness::{synthetic_uuid, Harness}; use support::mcp::{call_tool, call_tool_raw, mint_token}; /// When every seeded row says it was written. The TypeScript's `NOW`. const AT: &str = "2026-04-01T09:00:00.000Z"; /// A uuid this workspace has never issued. const NOBODY: &str = "00000000-0000-4000-8000-000000000000"; // ── the fixture ───────────────────────────────────────────────────────────── fn run(h: &Harness, sql: &str, params: Vec) { h.with(|db| db.run(sql, ¶ms)).expect("the write runs"); } fn one(h: &Harness, sql: &str, params: Vec) -> cotton_store::driver::Row { h.with(|db| db.get(sql, ¶ms)) .expect("the read runs") .expect("the row is there") } fn all(h: &Harness, sql: &str, params: Vec) -> Vec { h.with(|db| db.all(sql, ¶ms)).expect("the read runs") } fn text(value: &str) -> SqlValue { SqlValue::Text(value.to_string()) } /// One filed bank statement — the paper, and two pages of text on it. fn seed_statement_document(h: &Harness, label: &str) -> String { let document_id = synthetic_uuid(label); run( h, "INSERT INTO cotton_documents \ (id, workspace_id, original_name, mime, byte_size, sha256, storage_path, source, \ status, status_changed_at, doc_type, text_extracted, created_at, updated_at) \ VALUES (?, ?, 'march.pdf', 'application/pdf', 1024, ?, ?, 'app', 'ready', ?, \ 'bank_statement', 1, ?, ?)", vec![ text(&document_id), text(&h.workspace_id), text(&document_id.replace('-', "").repeat(2)), text(&format!("{}/{document_id}/original.pdf", h.workspace_id)), text(AT), text(AT), text(AT), ], ); for page in 1..=2 { run( h, "INSERT INTO cotton_document_pages (id, workspace_id, document_id, page, text, created_at) \ VALUES (?, ?, ?, ?, ?, ?)", vec![ text(&synthetic_uuid(&format!("{label}-page-{page}"))), text(&h.workspace_id), text(&document_id), SqlValue::Integer(page), text(&format!("MERIDIAN BANK — page {page}")), text(AT), ], ); } document_id } struct Seeded { statement_id: String, line_ids: Vec, } fn recorded_two_lines(h: &Harness, statement_id: &str, closing: i64) { use cotton_tools::mcp::handlers::money::statement_visual_check::{StatementFigures, VisualStatementHeader, VisualStatementLine}; h.services.statement_visual.recording_for(statement_id, StatementFigures { header: VisualStatementHeader { page: 1, period_start: "2026-03-01".into(), period_end: "2026-03-31".into(), opening_balance_minor: Some(12045000), closing_balance_minor: Some(closing) }, lines: (0..2).map(|_| VisualStatementLine { page: 1, posted_on: "2026-03-03".into(), amount_minor: 245000, direction: cotton_core::constants::LineDirection::Out, balance_after_minor: None, ignored: false }).collect(), }); } /// A statement whose lines are already stored, without running a model. fn seed_read_statement(h: &Harness) -> Seeded { let document_id = seed_statement_document(h, "statements-doc"); let statement_id = synthetic_uuid("statements-statement"); run( h, "INSERT INTO cotton_money_statements \ (id, workspace_id, document_id, kind, currency, read_status, balance_check, \ period_start, period_end, opening_balance_minor, closing_balance_minor, line_count, \ created_at, updated_at) \ VALUES (?, ?, ?, 'bank', 'INR', 'mismatch', 'mismatch', '2026-03-01', '2026-03-31', \ 12045000, 10520000, 2, ?, ?)", vec![ text(&statement_id), text(&h.workspace_id), text(&document_id), text(AT), text(AT), ], ); let line_ids: Vec = (1..=2) .map(|n| synthetic_uuid(&format!("statements-line-{n}"))) .collect(); for (index, id) in line_ids.iter().enumerate() { run( h, "INSERT INTO cotton_money_statement_lines \ (id, workspace_id, statement_id, page, line_no, posted_on, text, amount_minor, \ direction, balance_after_minor, reference, fingerprint, ignored_reason, created_at) \ VALUES (?, ?, ?, 1, ?, '2026-03-03', ?, 245000, 'out', NULL, NULL, ?, NULL, ?)", vec![ text(id), text(&h.workspace_id), text(&statement_id), SqlValue::Integer(index as i64 + 1), text(&format!("LINE {}", index + 1)), text(&format!("stl:{id}")), text(AT), ], ); } recorded_two_lines(h, &statement_id, 10520000); Seeded { statement_id, line_ids, } } /// The one real account a statement has to be attached to before it can book. fn attach_account(h: &Harness, statement_id: &str) -> String { let account_id = synthetic_uuid("statements-account"); run( h, "INSERT INTO cotton_money_accounts \ (id, workspace_id, name, kind, subtype, institution, number_mask, currency, \ is_default, created_at, updated_at) \ VALUES (?, ?, 'Meridian savings', 'bank', 'bank', 'Meridian Bank', '9021', 'INR', 0, ?, ?)", vec![ text(&account_id), text(&h.workspace_id), text(AT), text(AT), ], ); run( h, "UPDATE cotton_money_statements SET account_id = ?, closing_balance_minor=11555000, balance_check='ok' WHERE id = ?", vec![text(&account_id), text(statement_id)], ); recorded_two_lines(h, statement_id, 11555000); account_id } fn harness_with(scopes: &[&str]) -> (Harness, String) { let mut h = Harness::new(); let secret = mint_token(&mut h, scopes, "Claude"); (h, secret) } // ── statement tools ───────────────────────────────────────────────────────── #[test] fn list_statements_answers_headers_with_their_check() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); let answer = call_tool(&h, &secret, "list_statements", json!({})); let statements = answer["statements"].as_array().expect("a list"); assert_eq!(statements.len(), 1); assert_eq!(statements[0]["id"], json!(seeded.statement_id)); assert_eq!(statements[0]["readStatus"], json!("mismatch")); } #[test] fn list_statements_refuses_a_read_status_it_does_not_know() { let (h, secret) = harness_with(&["read"]); let answer = call_tool_raw( &h, &secret, "list_statements", json!({ "readStatus": "half-read" }), ); assert!(answer.is_error, "{}", answer.text); assert!(answer.text.contains("readStatus"), "{}", answer.text); } #[test] fn get_statement_returns_the_lines_with_their_derived_state() { let (h, secret) = harness_with(&["read"]); let seeded = seed_read_statement(&h); let answer = call_tool( &h, &secret, "get_statement", json!({ "id": seeded.statement_id, "includeLines": true }), ); let lines = answer["lines"].as_array().expect("a list"); assert_eq!(lines.len(), 2); assert_eq!(lines[0]["state"], json!("unbooked")); assert_eq!(lines[0]["transactionId"], Value::Null); } #[test] fn get_statement_refuses_an_id_that_is_not_in_this_workspace() { let (h, secret) = harness_with(&["read"]); let answer = call_tool_raw(&h, &secret, "get_statement", json!({ "id": NOBODY })); assert!(answer.is_error, "{}", answer.text); assert!( answer.text.to_lowercase().contains("no statement"), "{}", answer.text ); } #[test] fn update_statement_line_corrects_an_amount_and_re_runs_the_check() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); let answer = call_tool( &h, &secret, "update_statement_line", json!({ "id": seeded.line_ids[0], "amountMinor": 1_525_000 }), ); assert!(answer.get("balanceCheck").is_some(), "{answer}"); let row = one( &h, "SELECT amount_minor FROM cotton_money_statement_lines WHERE id = ?", vec![text(&seeded.line_ids[0])], ); assert_eq!(row.int("amount_minor"), Some(1_525_000)); assert_eq!(answer["statementId"], json!(seeded.statement_id)); } #[test] fn update_statement_line_refuses_fractional_minor_units() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); let answer = call_tool_raw( &h, &secret, "update_statement_line", json!({ "id": seeded.line_ids[0], "amountMinor": 2450.5 }), ); assert!(answer.is_error, "{}", answer.text); assert!( answer.text.to_lowercase().contains("whole minor units"), "{}", answer.text ); } #[test] fn update_statement_line_refuses_a_call_that_changes_nothing() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); let answer = call_tool_raw( &h, &secret, "update_statement_line", json!({ "id": seeded.line_ids[0] }), ); assert!(answer.is_error, "{}", answer.text); assert!( answer.text.to_lowercase().contains("nothing to change"), "{}", answer.text ); } #[test] fn book_statement_refuses_a_statement_with_no_account_yet() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); let answer = call_tool_raw( &h, &secret, "book_statement", json!({ "id": seeded.statement_id }), ); assert!(answer.is_error, "{}", answer.text); assert!( answer.text.contains("read_statement") || answer.text.contains("read it first"), "{}", answer.text ); } /// RULE: Manual booking cannot bypass the statement balance check, even if its stored verdict mistakenly says the figures agree. #[test] fn book_statement_rechecks_the_figures_before_writing_money() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); attach_account(&h, &seeded.statement_id); run( &h, "UPDATE cotton_money_statements SET closing_balance_minor=1,balance_check='ok' WHERE id=?", vec![text(&seeded.statement_id)], ); recorded_two_lines(&h, &seeded.statement_id, 1); let answer = call_tool_raw( &h, &secret, "book_statement", json!({"id":seeded.statement_id}), ); assert!(answer.is_error, "{}", answer.text); assert!(all( &h, "SELECT id FROM cotton_money_transactions WHERE workspace_id=?", vec![text(&h.workspace_id)] ) .is_empty()); } #[test] fn read_statement_marks_the_statement_pending_before_anything_else_runs() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); let document_id = one( &h, "SELECT document_id FROM cotton_money_statements WHERE id = ?", vec![text(&seeded.statement_id)], ) .text("document_id") .expect("the statement names its paper") .to_string(); let answer = call_tool( &h, &secret, "read_statement", json!({ "documentId": document_id }), ); assert_eq!(answer["statementId"], json!(seeded.statement_id)); assert_eq!(answer["readStatus"], json!("pending")); let row = one( &h, "SELECT read_status FROM cotton_money_statements WHERE id = ?", vec![text(&seeded.statement_id)], ); assert_eq!(row.text("read_status"), Some("pending")); } #[test] fn book_statement_records_a_statements_entries_and_a_second_call_records_none() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); attach_account(&h, &seeded.statement_id); let first = call_tool( &h, &secret, "book_statement", json!({ "id": seeded.statement_id }), ); assert_eq!(first["recorded"], json!(2)); assert_eq!(first["alreadyThere"], json!(0)); let second = call_tool( &h, &secret, "book_statement", json!({ "id": seeded.statement_id }), ); assert_eq!(second["recorded"], json!(0)); assert_eq!(second["alreadyThere"], json!(2)); // Each entry now cites its own line as evidence, which is what makes the // second call answer "already there" rather than book a twin. let opened = call_tool( &h, &secret, "get_statement", json!({ "id": seeded.statement_id }), ); let lines = opened["lines"].as_array().expect("a list"); let states: Vec<&Value> = lines.iter().map(|line| &line["state"]).collect(); assert_eq!(states, vec![&json!("booked"), &json!("booked")]); assert_ne!(lines[0]["transactionId"], Value::Null); let listed = call_tool(&h, &secret, "list_statements", json!({})); assert_eq!(listed["statements"][0]["recordedCount"], json!(2)); assert_eq!(seeded.line_ids.len(), 2); } #[test] fn book_statement_books_every_line_once_so_two_callers_cannot_double_book_one() { // Booking is keyed on the statement line's own evidence row, so a second // caller that got in anyway finds it already there. let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); attach_account(&h, &seeded.statement_id); let result = call_tool( &h, &secret, "book_statement", json!({ "id": seeded.statement_id }), ); assert_eq!(result["recorded"], json!(2)); let transactions = all( &h, "SELECT id FROM cotton_money_transactions WHERE workspace_id = ?", vec![text(&h.workspace_id)], ); assert_eq!(transactions.len(), 2); } #[test] fn update_statement_line_refuses_an_entry_that_is_already_in_the_users_money() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); attach_account(&h, &seeded.statement_id); call_tool( &h, &secret, "book_statement", json!({ "id": seeded.statement_id }), ); let answer = call_tool_raw( &h, &secret, "update_statement_line", json!({ "id": seeded.line_ids[0], "amountMinor": 99_900 }), ); assert!(answer.is_error, "{}", answer.text); assert!( answer.text.contains("already in the user's money"), "{}", answer.text ); assert!( answer.text.contains("update_transaction") || answer.text.contains("delete_transaction"), "{}", answer.text ); } #[test] fn update_statement_line_leaves_a_pending_statement_pending() { // A correction never cancels a re-read. let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); run( &h, "UPDATE cotton_money_statements SET read_status = 'pending' WHERE id = ?", vec![text(&seeded.statement_id)], ); // The correction makes the arithmetic agree, which is exactly the case that // used to stamp `read` over the queue and lose the re-read. let answer = call_tool( &h, &secret, "update_statement_line", json!({ "id": seeded.line_ids[0], "amountMinor": 1_280_000 }), ); assert_eq!(answer["balanceCheck"], json!("ok")); let row = one( &h, "SELECT read_status, sum_out_minor FROM cotton_money_statements WHERE id = ?", vec![text(&seeded.statement_id)], ); assert_eq!(row.text("read_status"), Some("pending")); // The totals are still re-stated — only the queue place is left alone. assert_eq!(row.int("sum_out_minor"), Some(1_525_000)); } #[test] fn update_statement_line_clears_the_reason_an_earlier_reading_failed_when_it_does_stamp() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); run( &h, "UPDATE cotton_money_statements SET read_error = ? WHERE id = ?", vec![ text("the model answered with no tool call"), text(&seeded.statement_id), ], ); call_tool( &h, &secret, "update_statement_line", json!({ "id": seeded.line_ids[0], "amountMinor": 1_280_000 }), ); let row = one( &h, "SELECT read_status, read_error FROM cotton_money_statements WHERE id = ?", vec![text(&seeded.statement_id)], ); assert_eq!(row.text("read_status"), Some("read")); assert_eq!(row.text("read_error"), None); } #[test] fn update_statement_line_leaves_a_failed_statement_failed() { // Only read_statement reads it again. let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); run( &h, "UPDATE cotton_money_statements SET read_status = 'failed', read_error = ? WHERE id = ?", vec![ text("the model answered with no tool call"), text(&seeded.statement_id), ], ); let answer = call_tool( &h, &secret, "update_statement_line", json!({ "id": seeded.line_ids[0], "amountMinor": 1_280_000 }), ); assert_eq!(answer["balanceCheck"], json!("ok")); let row = one( &h, "SELECT read_status, read_error, sum_out_minor FROM cotton_money_statements WHERE id = ?", vec![text(&seeded.statement_id)], ); // A correction of one figure does not say the reading succeeded. assert_eq!(row.text("read_status"), Some("failed")); assert_eq!( row.text("read_error"), Some("the model answered with no tool call") ); // The totals are still re-stated. assert_eq!(row.int("sum_out_minor"), Some(1_525_000)); } #[test] fn update_statement_line_re_keys_the_corrected_line_and_the_twin_it_moved() { let (h, secret) = harness_with(&["read", "write"]); let seeded = seed_read_statement(&h); // Two identical printed lines: the second is occurrence 1 of the same // material. run( &h, "UPDATE cotton_money_statement_lines SET text = 'LINE 1' WHERE statement_id = ?", vec![text(&seeded.statement_id)], ); // No account on this statement, so the key is the statement id itself (the // store's own fallback) — the same helper the reading uses. let account_key = account_key_for(None, None, &seeded.statement_id); let keyed = |amounts: [i64; 2]| -> Vec { fingerprints_for( &account_key, &amounts .iter() .map(|amount| FingerprintLine { posted_on: "2026-03-03".to_string(), amount_minor: *amount, direction: LineDirection::Out, text: "LINE 1".to_string(), }) .collect::>(), ) .expect("the fingerprints compute") }; let twin_before = keyed([245_000, 245_000])[1].clone(); call_tool( &h, &secret, "update_statement_line", json!({ "id": seeded.line_ids[0], "amountMinor": 1_525_000 }), ); let rows = all( &h, "SELECT id, fingerprint FROM cotton_money_statement_lines WHERE statement_id = ? \ ORDER BY line_no", vec![text(&seeded.statement_id)], ); let wanted = keyed([1_525_000, 245_000]); let found: Vec = rows .iter() .filter_map(|row| row.text("fingerprint").map(str::to_string)) .collect(); assert_eq!(found, wanted); // The untouched line moved from occurrence 1 to 0 — a re-read now finds it. assert_ne!(wanted[1], twin_before); let ids: Vec = rows .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect(); assert_eq!(ids, seeded.line_ids); } #[test] fn read_statement_sets_a_filed_statement_back_to_pending_and_says_so() { let (h, secret) = harness_with(&["read", "write"]); let document_id = seed_statement_document(&h, "statements-filed-doc"); let answer = call_tool( &h, &secret, "read_statement", json!({ "documentId": document_id }), ); assert_eq!(answer["readStatus"], json!("pending")); assert!(answer["statementId"].is_string(), "{answer}"); // Calling it again on the same document reaches the same statement. let again = call_tool( &h, &secret, "read_statement", json!({ "documentId": document_id }), ); assert_eq!(again["statementId"], answer["statementId"]); } #[test] fn read_statement_refuses_a_document_that_is_not_a_statement() { let (h, secret) = harness_with(&["read", "write"]); let document_id = synthetic_uuid("statements-lease"); run( &h, "INSERT INTO cotton_documents \ (id, workspace_id, original_name, mime, byte_size, sha256, storage_path, source, \ status, status_changed_at, doc_type, created_at, updated_at) \ VALUES (?, ?, 'lease.pdf', 'application/pdf', 1, ?, ?, 'app', 'ready', ?, 'legal', ?, ?)", vec![ text(&document_id), text(&h.workspace_id), text(&"b".repeat(64)), text(&format!("{}/{document_id}/original.pdf", h.workspace_id)), text(AT), text(AT), text(AT), ], ); let answer = call_tool_raw( &h, &secret, "read_statement", json!({ "documentId": document_id }), ); assert!(answer.is_error, "{}", answer.text); assert!( answer.text.contains("bank_statement") || answer.text.contains("card_statement"), "{}", answer.text ); } #[test] fn a_read_only_token_cannot_read_statement() { let (h, secret) = harness_with(&["read"]); let document_id = seed_statement_document(&h, "statements-readonly-doc"); let answer = call_tool_raw( &h, &secret, "read_statement", json!({ "documentId": document_id }), ); assert!(answer.is_error, "{}", answer.text); assert!(answer.text.contains("write"), "{}", answer.text); } /// RULE: A loan statement uses the bank balance direction: a payment out of /// 2,000 from 10,000 owed leaves 8,000 owed, never an inverted card balance. #[test] fn a_loan_statement_books_with_bank_balance_arithmetic() { let (h, secret) = harness_with(&["read", "write"]); let document_id = seed_statement_document(&h, "loan-statement-doc"); let statement_id = synthetic_uuid("loan-statement"); let account_id = synthetic_uuid("loan-account"); let line_id = synthetic_uuid("loan-statement-line"); run(&h, "INSERT INTO cotton_money_accounts (id, workspace_id, name, kind, subtype, currency, is_default, created_at, updated_at) VALUES (?, ?, 'Loan', 'loan', 'loan', 'INR', 0, ?, ?)", vec![text(&account_id), text(&h.workspace_id), text(AT), text(AT)]); run(&h, "INSERT INTO cotton_money_statements (id, workspace_id, document_id, account_id, kind, currency, read_status, balance_check, period_start, period_end, opening_balance_minor, closing_balance_minor, line_count, created_at, updated_at) VALUES (?, ?, ?, ?, 'bank', 'INR', 'read', 'ok', '2026-03-01', '2026-03-31', 10000, 8000, 1, ?, ?)", vec![text(&statement_id), text(&h.workspace_id), text(&document_id), text(&account_id), text(AT), text(AT)]); run(&h, "INSERT INTO cotton_money_statement_lines (id, workspace_id, statement_id, page, line_no, posted_on, text, amount_minor, direction, fingerprint, created_at) VALUES (?, ?, ?, 1, 1, '2026-03-02', 'Loan payment', 2000, 'out', 'loan-line', ?)", vec![text(&line_id), text(&h.workspace_id), text(&statement_id), text(AT)]); use cotton_tools::mcp::handlers::money::statement_visual_check::{StatementFigures, VisualStatementHeader, VisualStatementLine}; h.services.statement_visual.recording_for(&statement_id, StatementFigures { header: VisualStatementHeader { page: 1, period_start: "2026-03-01".into(), period_end: "2026-03-31".into(), opening_balance_minor: Some(10000), closing_balance_minor: Some(8000) }, lines: vec![VisualStatementLine { page: 1, posted_on: "2026-03-02".into(), amount_minor: 2000, direction: cotton_core::constants::LineDirection::Out, balance_after_minor: None, ignored: false }], }); let answer = call_tool(&h, &secret, "book_statement", json!({"id":statement_id})); assert_eq!(answer["recorded"], json!(1)); let row = one(&h, "SELECT amount_minor, direction, account_id FROM cotton_money_transactions WHERE account_id=?", vec![text(&account_id)]); assert_eq!(row.int("amount_minor"), Some(2000)); assert_eq!(row.text("direction"), Some("out")); assert_eq!(row.text("account_id"), Some(account_id.as_str())); // Running balances belong to the Worker since 687ddecc7. The matching // booked-loan regression lives in apps/business/test/balances.test.ts. let again = call_tool(&h, &secret, "book_statement", json!({"id":statement_id})); assert_eq!(again["recorded"], json!(0), "booking the same line twice creates no second payment"); }