//! The statement header and its lines, in the owner's file. //! //! Two rules live here and nowhere else: //! //! A LINE IS ADDRESSED BY ITS FINGERPRINT, not by where it sat in a reading. //! [`fingerprints_for`] is the `txt2:` discipline applied to paper — content //! only, no identity of a person — so reading the same statement twice //! converges on the same rows rather than doubling them. //! //! A BOOKED LINE SURVIVES A RE-READ THAT LOST IT. Its transaction cites it //! as evidence; deleting the row would leave a transaction pointing at //! nothing, which is the one thing "never lose information" cannot allow. use crate::mcp::writer::Retract; use std::collections::BTreeMap; use cotton_core::constants::LineDirection; use cotton_store::protocol::fingerprint::statement::{ statement_line_account_key, statement_line_fingerprint, Direction, StatementLineFingerprintInput, StatementLineOccurrenceCounter, }; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::{ insert_row, int, maybe_row, now_iso, rows, text, update_row, Valid, }; use crate::mcp::handlers::money::engine_shim::StatementReadLine; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::{Filter, Order, Query}; pub const STATEMENT_COLUMNS: &[&str] = &[ "id", "document_id", "account_id", "kind", "period_start", "period_end", "opening_balance_minor", "closing_balance_minor", "currency", "read_status", "read_error", "read_by", "read_at", "line_count", "sum_in_minor", "sum_out_minor", "balance_check", "created_at", "updated_at", ]; pub const STATEMENT_LINE_COLUMNS: &[&str] = &[ "id", "statement_id", "page", "line_no", "posted_on", "text", "amount_minor", "direction", "balance_after_minor", "reference", "fingerprint", "ignored_reason", ]; /// One statement header. /// /// The three nullable header fields are null until the reader has read the /// paper — a pending row knows only which document it is about. #[derive(Debug, Clone)] pub struct StatementRow { pub id: String, pub document_id: String, pub account_id: Option, pub kind: String, pub period_start: Option, pub period_end: Option, pub opening_balance_minor: Option, pub closing_balance_minor: Option, pub currency: String, pub read_status: String, pub read_error: Option, pub read_by: Option, pub read_at: Option, pub line_count: i64, pub sum_in_minor: i64, pub sum_out_minor: i64, pub balance_check: String, pub created_at: Option, } #[derive(Debug, Clone)] pub struct StatementLineRow { pub id: String, pub statement_id: String, pub page: i64, pub line_no: i64, pub posted_on: String, pub text: String, pub amount_minor: i64, pub direction: LineDirection, pub balance_after_minor: Option, pub reference: Option, pub fingerprint: String, pub ignored_reason: Option, } fn optional_int(row: &Map, column: &str) -> Option { match row.get(column) { None | Some(Value::Null) => None, Some(_) => Some(int(row, column)), } } fn to_statement(row: &Map) -> StatementRow { StatementRow { id: text(row, "id").unwrap_or_default(), document_id: text(row, "document_id").unwrap_or_default(), account_id: text(row, "account_id"), // The file's CHECK has two values; anything else reads as `bank`, // exactly as the TypeScript's ternary does. kind: if text(row, "kind").as_deref() == Some("credit_card") { "credit_card".to_string() } else { "bank".to_string() }, period_start: text(row, "period_start"), period_end: text(row, "period_end"), opening_balance_minor: optional_int(row, "opening_balance_minor"), closing_balance_minor: optional_int(row, "closing_balance_minor"), currency: text(row, "currency").unwrap_or_default(), read_status: text(row, "read_status").unwrap_or_default(), read_error: text(row, "read_error"), read_by: text(row, "read_by"), read_at: text(row, "read_at"), line_count: int(row, "line_count"), sum_in_minor: int(row, "sum_in_minor"), sum_out_minor: int(row, "sum_out_minor"), balance_check: text(row, "balance_check").unwrap_or_default(), created_at: text(row, "created_at"), } } fn to_line(row: &Map) -> StatementLineRow { StatementLineRow { id: text(row, "id").unwrap_or_default(), statement_id: text(row, "statement_id").unwrap_or_default(), page: int(row, "page"), line_no: int(row, "line_no"), posted_on: text(row, "posted_on").unwrap_or_default(), text: text(row, "text").unwrap_or_default(), amount_minor: int(row, "amount_minor"), direction: if text(row, "direction").as_deref() == Some("in") { LineDirection::In } else { LineDirection::Out }, balance_after_minor: optional_int(row, "balance_after_minor"), reference: text(row, "reference"), fingerprint: text(row, "fingerprint").unwrap_or_default(), ignored_reason: text(row, "ignored_reason"), } } /// The identity a fingerprint is computed against — a thin wrapper over the /// store's own rule, because the file format owns what makes two lines the /// same line. pub fn account_key_for( institution: Option<&str>, number_mask: Option<&str>, statement_id: &str, ) -> String { statement_line_account_key(institution, number_mask, statement_id) } /// The engines' direction in the file format's own words. fn store_direction(direction: LineDirection) -> Direction { match direction { LineDirection::In => Direction::In, LineDirection::Out => Direction::Out, } } /// The content a fingerprint is computed from. #[derive(Debug, Clone)] pub struct FingerprintLine { pub posted_on: String, pub amount_minor: i64, pub direction: LineDirection, pub text: String, } /// The fingerprint of every line of ONE statement, in the order given — which /// must be printed order, because the occurrence counter numbers identical /// lines by it. /// /// The ONE place the counter runs: the reader's write and a correction /// (`update_statement_line`) both call this, so a corrected line re-keys /// exactly as a re-read of the same content would. pub fn fingerprints_for(account_key: &str, lines: &[FingerprintLine]) -> Valid> { // Same (day, amount, direction, words) twice in one statement is ordinary // — two identical UPI payments on one afternoon. The occurrence counter is // what keeps them two rows rather than one. let mut counter = StatementLineOccurrenceCounter::new(); let mut out = Vec::with_capacity(lines.len()); for line in lines { let mut material = StatementLineFingerprintInput { account_key, posted_on: &line.posted_on, amount_minor: line.amount_minor, // The FILE FORMAT's own direction type, which is what the // fingerprint is defined over; the engines speak // `LineDirection`, and the two never meet except here. direction: store_direction(line.direction), text: &line.text, occurrence: 0, }; material.occurrence = counter.next(&material); out.push( statement_line_fingerprint(&material) .map_err(|error| ToolFailure::new(error.to_string()))?, ); } Ok(out) } pub struct EnsuredStatement { pub id: String, pub created: bool, } pub fn ensure_pending_statement(ctx: &mut Ctx<'_>, document_id: &str) -> Valid { let existing = maybe_row( ctx, &Query::on("cotton_money_statements") .columns(&["id"]) .eq("document_id", document_id.to_string()) .limit(1), )?; if let Some(row) = existing { return Ok(EnsuredStatement { id: text(&row, "id").unwrap_or_default(), created: false, }); } let id = ctx.new_uuid(); let mut patch = Map::new(); patch.insert( "document_id".to_string(), Value::from(document_id.to_string()), ); patch.insert("account_id".to_string(), Value::Null); // The reader decides all three. `kind` is born "bank" because its CHECK // has no third value and a card statement is re-stamped the moment the // reader says so; the two dates are born NULL, which is exactly what // "nobody has read the paper yet" means. Inventing "the day it was filed" // here would put a fictional month into coverage and into every gap the // audit reports. patch.insert("kind".to_string(), Value::from("bank")); patch.insert("period_start".to_string(), Value::Null); patch.insert("period_end".to_string(), Value::Null); patch.insert("opening_balance_minor".to_string(), Value::Null); patch.insert("closing_balance_minor".to_string(), Value::Null); // Unknown until the reader says it (it re-stamps the row): the book's home // currency is the likeliest, and a book with no account yet says ISO 4217's // "no currency" (XXX) — never a country's by default. let currency = crate::mcp::handlers::money::accounts::home_currency( &crate::mcp::handlers::money::model::load_money_accounts(ctx)?, ) .unwrap_or_else(|| "XXX".to_string()); patch.insert("currency".to_string(), Value::from(currency)); patch.insert("read_status".to_string(), Value::from("pending")); patch.insert("read_error".to_string(), Value::Null); patch.insert("read_by".to_string(), Value::Null); patch.insert("read_at".to_string(), Value::Null); patch.insert("line_count".to_string(), Value::from(0)); patch.insert("sum_in_minor".to_string(), Value::from(0)); patch.insert("sum_out_minor".to_string(), Value::from(0)); patch.insert("balance_check".to_string(), Value::from("unknown")); insert_row(ctx, "cotton_money_statements", &id, patch)?; Ok(EnsuredStatement { id, created: true }) } pub fn load_statement(ctx: &Ctx<'_>, id: &str) -> Valid> { Ok(maybe_row( ctx, &Query::on("cotton_money_statements") .columns(STATEMENT_COLUMNS) .eq("id", id.to_string()) .limit(1), )? .as_ref() .map(to_statement)) } pub fn load_statement_by_document(ctx: &Ctx<'_>, document_id: &str) -> Valid> { Ok(maybe_row( ctx, &Query::on("cotton_money_statements") .columns(STATEMENT_COLUMNS) .eq("document_id", document_id.to_string()) .limit(1), )? .as_ref() .map(to_statement)) } /// One statement's lines in PRINTED order — which is what the occurrence /// counter numbers by, so every caller that re-fingerprints reads them here. pub fn load_statement_lines(ctx: &Ctx<'_>, statement_id: &str) -> Valid> { Ok(rows( ctx, &Query::on("cotton_money_statement_lines") .columns(STATEMENT_LINE_COLUMNS) .eq("statement_id", statement_id.to_string()) .order_by("page", Order::Asc) .order_by("line_no", Order::Asc), )? .iter() .map(to_line) .collect()) } pub fn patch_statement(ctx: &mut Ctx<'_>, id: &str, patch: Map) -> Valid<()> { update_row(ctx, "cotton_money_statements", id, patch) } /// Put one statement back on the queue the statements worker drains. /// /// `read_status` IS the queue, so a re-read is this patch and nothing else — /// and `read_error` goes with it, because the reason an earlier attempt fell /// over is not a description of a statement nobody has read yet. pub fn requeue_statement(ctx: &mut Ctx<'_>, id: &str) -> Valid<()> { let stamp = now_iso(ctx); let mut patch = Map::new(); patch.insert("read_status".to_string(), Value::from("pending")); patch.insert("read_error".to_string(), Value::Null); patch.insert("updated_at".to_string(), Value::from(stamp)); patch_statement(ctx, id, patch) } /// How far above any real `line_no` the parking pass pushes a retained row. /// /// Comfortably beyond any statement's line count — the DDL's /// `CHECK (line_no >= 1)` is the reason this is an offset rather than the /// negative sentinel a Postgres-shaped design would use. const PARK_OFFSET: i64 = 1_000_000; pub struct WriteLinesInput<'a> { pub statement_id: &'a str, pub account_key: &'a str, pub lines: &'a [StatementReadLine], /// What is already stored for this statement — [`load_statement_lines`]. pub existing: &'a [StatementLineRow], /// Line ids an evidence row already cites. Never deleted. pub booked_line_ids: &'a [String], } pub struct WriteLinesResult { pub inserted: usize, pub updated: usize, pub removed: usize, /// The statement's lines as they now stand, in final printed order. /// /// Answered rather than re-read: this call's writes are queued on the /// caller's writer, and a `SELECT` before its `commit` would answer with /// the rows as they were. pub stored: Vec, } struct PlannedLine { id: String, page: i64, line_no: i64, posted_on: String, text: String, amount_minor: i64, direction: LineDirection, balance_after_minor: Option, reference: Option, fingerprint: String, ignored_reason: Option, is_new: bool, } fn row_for(statement_id: &str, line: &PlannedLine) -> Map { let mut patch = Map::new(); patch.insert( "statement_id".to_string(), Value::from(statement_id.to_string()), ); patch.insert("page".to_string(), Value::from(line.page)); patch.insert("line_no".to_string(), Value::from(line.line_no)); patch.insert("posted_on".to_string(), Value::from(line.posted_on.clone())); patch.insert("text".to_string(), Value::from(line.text.clone())); patch.insert("amount_minor".to_string(), Value::from(line.amount_minor)); patch.insert( "direction".to_string(), Value::from(line.direction.as_str()), ); patch.insert( "balance_after_minor".to_string(), line.balance_after_minor.map_or(Value::Null, Value::from), ); patch.insert( "reference".to_string(), line.reference.clone().map_or(Value::Null, Value::from), ); patch.insert( "fingerprint".to_string(), Value::from(line.fingerprint.clone()), ); patch.insert( "ignored_reason".to_string(), line.ignored_reason.clone().map_or(Value::Null, Value::from), ); patch } /// Write one statement's lines so a re-read never collides with itself. /// /// A re-read that shifts content — one line's text changed, a line inserted, a /// booked line the reading no longer produces — moves rows to different /// `line_no` positions than they currently hold. `UNIQUE (statement_id, /// line_no)` makes a naive "renumber and upsert" collide with whatever row /// currently sits at a row's new position. Three passes avoid that by /// construction: /// /// 1. DELETE the truly stale rows first — not matched by the new reading and /// not cited by any transaction's evidence. This frees their `line_no` /// slots before anything else moves. /// 2. PARK every row that survives (matched by fingerprint, or booked and /// lost) on a scratch sentinel (`old_line_no + PARK_OFFSET`). The DDL's /// `CHECK (line_no >= 1)` rules out the negative sentinel a Postgres /// design would reach for, so the sentinel is pushed well ABOVE any real /// position instead. /// 3. UPSERT the final numbering: new-reading lines take their read /// position; a booked line the reading lost keeps its own page and is /// numbered after the last read line. /// /// Matched rows keep their id throughout — never delete-then-reinsert — /// because an evidence row's foreign key depends on it. And a BOOKED row keeps /// its CONTENT: a transaction cites it as evidence, and its amount, date and /// words are what that transaction was posted from. A second reading that says /// otherwise about a line already in the owner's money moves the row's page and /// position only. /// /// THE THREE PASSES STILL MATTER IN RUST, even though a whole tool call folds /// in one transaction: the fold applies each op in order and the UNIQUE is /// checked per statement, so an out-of-order numbering collides inside the /// transaction exactly as it did across three batches. pub fn write_statement_lines( ctx: &mut Ctx<'_>, input: WriteLinesInput<'_>, ) -> Valid { let mut by_fingerprint: BTreeMap<&str, &StatementLineRow> = BTreeMap::new(); for line in input.existing { by_fingerprint.insert(line.fingerprint.as_str(), line); } let fingerprints = fingerprints_for( input.account_key, &input .lines .iter() .map(|line| FingerprintLine { posted_on: line.posted_on.clone(), amount_minor: line.amount_minor, direction: line.direction, text: line.text.clone(), }) .collect::>(), )?; let mut planned: Vec = Vec::with_capacity(input.lines.len()); let mut kept_fingerprints: Vec<&str> = Vec::with_capacity(fingerprints.len()); for (index, line) in input.lines.iter().enumerate() { let fingerprint = fingerprints[index].clone(); kept_fingerprints.push(fingerprints[index].as_str()); let previous = by_fingerprint.get(fingerprint.as_str()).copied(); planned.push(PlannedLine { id: previous.map_or_else(|| ctx.new_uuid(), |row| row.id.clone()), page: line.page, line_no: (index as i64) + 1, posted_on: line.posted_on.clone(), text: line.text.clone(), amount_minor: line.amount_minor, direction: line.direction, balance_after_minor: line.balance_after_minor, reference: line.reference.clone(), fingerprint, ignored_reason: line.ignored_reason.clone(), is_new: previous.is_none(), }); } let inserted = planned.iter().filter(|line| line.is_new).count(); let updated = planned.len() - inserted; let is_booked = |id: &str| -> bool { input.booked_line_ids.iter().any(|booked| booked == id) }; let is_kept = |fingerprint: &str| -> bool { kept_fingerprints.contains(&fingerprint) }; // Pass 1: delete what is genuinely gone — not reproduced by this reading, // and not cited by any transaction. let stale: Vec<&StatementLineRow> = input .existing .iter() .filter(|line| !is_kept(&line.fingerprint) && !is_booked(&line.id)) .collect(); for line in &stale { ctx.writer()? .retract("cotton_money_statement_lines", &line.id, Retract::Relation); } // A booked line the new reading no longer produces — kept, appended after // the last read line. let booked_lost: Vec<&StatementLineRow> = input .existing .iter() .filter(|line| !is_kept(&line.fingerprint) && is_booked(&line.id)) .collect(); // Pass 2: park every row that survives on a scratch sentinel, so its old // position can never collide with the final numbering below. let retained: Vec<&StatementLineRow> = planned .iter() .filter(|line| !line.is_new) .filter_map(|line| by_fingerprint.get(line.fingerprint.as_str()).copied()) .chain(booked_lost.iter().copied()) .collect(); for line in &retained { let mut patch = Map::new(); patch.insert( "line_no".to_string(), Value::from(line.line_no + PARK_OFFSET), ); update_row(ctx, "cotton_money_statement_lines", &line.id, patch)?; } // Pass 3: the final numbering. A row a transaction already cites moves // POSITION only — its content is what the money was posted from — so those // rows are placed by a narrow update rather than the whole-row upsert. let mut stored: Vec = Vec::with_capacity(planned.len() + booked_lost.len()); for line in &planned { if !line.is_new && is_booked(&line.id) { let mut patch = Map::new(); patch.insert("page".to_string(), Value::from(line.page)); patch.insert("line_no".to_string(), Value::from(line.line_no)); update_row(ctx, "cotton_money_statement_lines", &line.id, patch)?; // The stored row keeps the CONTENT it was posted from; only its // position moved. let previous = by_fingerprint .get(line.fingerprint.as_str()) .copied() .expect("a matched line has a previous row"); stored.push(StatementLineRow { page: line.page, line_no: line.line_no, ..previous.clone() }); continue; } let patch = row_for(input.statement_id, line); if line.is_new { insert_row(ctx, "cotton_money_statement_lines", &line.id, patch)?; } else { update_row(ctx, "cotton_money_statement_lines", &line.id, patch)?; } stored.push(StatementLineRow { id: line.id.clone(), statement_id: input.statement_id.to_string(), page: line.page, line_no: line.line_no, posted_on: line.posted_on.clone(), text: line.text.clone(), amount_minor: line.amount_minor, direction: line.direction, balance_after_minor: line.balance_after_minor, reference: line.reference.clone(), fingerprint: line.fingerprint.clone(), ignored_reason: line.ignored_reason.clone(), }); } for (index, line) in booked_lost.iter().enumerate() { let line_no = (planned.len() + index + 1) as i64; let mut patch = Map::new(); patch.insert("page".to_string(), Value::from(line.page)); patch.insert("line_no".to_string(), Value::from(line_no)); update_row(ctx, "cotton_money_statement_lines", &line.id, patch)?; stored.push(StatementLineRow { line_no, ..(*line).clone() }); } Ok(WriteLinesResult { inserted, updated, removed: stale.len(), stored, }) } /// statement id → how many of its entries are already in the owner's money. /// /// ONE read for the whole page. Evidence carries the LINE's id, not the /// statement's, so the join is what keys it by statement; the count is /// DISTINCT because two transactions may perfectly well cite one line and the /// number being answered is "how many of these entries are in their money", /// not "how many citations exist". pub fn recorded_counts_for( ctx: &Ctx<'_>, statement_ids: &[String], ) -> Valid> { let mut counts: BTreeMap = BTreeMap::new(); if statement_ids.is_empty() { return Ok(counts); } let placeholders = vec!["?"; statement_ids.len()].join(", "); let sql = format!( "SELECT line.statement_id AS statement_id, COUNT(DISTINCT line.id) AS recorded FROM cotton_money_evidence ev JOIN cotton_money_statement_lines line ON line.id = ev.ref_id AND line.workspace_id = ev.workspace_id WHERE ev.workspace_id = ? AND ev.kind = 'statement_line' AND line.statement_id IN ({placeholders}) GROUP BY line.statement_id" ); let mut params: Vec = vec![SqlValue::Text(ctx.workspace_id.to_string())]; params.extend( statement_ids .iter() .map(|id| SqlValue::Text(id.clone())) .collect::>(), ); let found = ctx .db() .all(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))?; for row in found { let Some(statement_id) = row.text("statement_id") else { continue; }; counts.insert(statement_id.to_string(), row.int("recorded").unwrap_or(0)); } Ok(counts) } /// The `IN (…)` filter one batch of ids makes. pub fn id_filter(column: &str, ids: &[String]) -> Filter { Filter::In( column.to_string(), ids.iter().map(|id| SqlValue::Text(id.clone())).collect(), ) }