//! 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.usecrate::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::ValueasSqlValue;use serde_json::{Map, Value};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::{ insert_row, int, maybe_row, now_iso, rows, text, update_row, Valid,};usecrate::mcp::handlers::money::engine_shim::StatementReadLine;usecrate::mcp::protocol::ToolFailure;usecrate::mcp::read_db::{Filter, Order, Query};pubconst 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",];pubconst 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)]pubstructStatementRow {pub id: String,pub document_id: String,pub account_id: Option<String>,pub kind: String,pub period_start: Option<String>,pub period_end: Option<String>,pub opening_balance_minor: Option<i64>,pub closing_balance_minor: Option<i64>,pub currency: String,pub read_status: String,pub read_error: Option<String>,pub read_by: Option<String>,pub read_at: Option<String>,pub line_count: i64,pub sum_in_minor: i64,pub sum_out_minor: i64,pub balance_check: String,pub created_at: Option<String>,}#[derive(Debug, Clone)]pubstructStatementLineRow {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<i64>,pub reference: Option<String>,pub fingerprint: String,pub ignored_reason: Option<String>,}fn optional_int(row: &Map<String, Value>, column: &str) -> Option<i64> {match row.get(column) {None | Some(Value::Null) => None,Some(_) => Some(int(row, column)), }}fn to_statement(row: &Map<String, Value>) -> 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<String, Value>) -> 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.pubfn 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)]pubstructFingerprintLine {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.pubfn fingerprints_for(account_key: &str, lines: &[FingerprintLine]) -> Valid<Vec<String>> {// 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.letmut counter = StatementLineOccurrenceCounter::new();letmut out = Vec::with_capacity(lines.len());for line in lines {letmut 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)}pubstructEnsuredStatement {pub id: String,pub created: bool,}pubfn ensure_pending_statement(ctx: &mutCtx<'_>, document_id: &str) -> Valid<EnsuredStatement> {let existing = maybe_row( ctx, &Query::on("cotton_money_statements") .columns(&["id"]) .eq("document_id", document_id.to_string()) .limit(1), )?;ifletSome(row) = existing {returnOk(EnsuredStatement { id: text(&row, "id").unwrap_or_default(), created: false, }); }let id = ctx.new_uuid();letmut 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 })}pubfn load_statement(ctx: &Ctx<'_>, id: &str) -> Valid<Option<StatementRow>> {Ok(maybe_row( ctx, &Query::on("cotton_money_statements") .columns(STATEMENT_COLUMNS) .eq("id", id.to_string()) .limit(1), )? .as_ref() .map(to_statement))}pubfn load_statement_by_document(ctx: &Ctx<'_>, document_id: &str) -> Valid<Option<StatementRow>> {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.pubfn load_statement_lines(ctx: &Ctx<'_>, statement_id: &str) -> Valid<Vec<StatementLineRow>> {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())}pubfn patch_statement(ctx: &mutCtx<'_>, id: &str, patch: Map<String, Value>) -> 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.pubfn requeue_statement(ctx: &mutCtx<'_>, id: &str) -> Valid<()> {let stamp = now_iso(ctx);letmut 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;pubstructWriteLinesInput<'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],}pubstructWriteLinesResult {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<StatementLineRow>,}structPlannedLine { id: String, page: i64, line_no: i64, posted_on: String, text: String, amount_minor: i64, direction: LineDirection, balance_after_minor: Option<i64>, reference: Option<String>, fingerprint: String, ignored_reason: Option<String>, is_new: bool,}fn row_for(statement_id: &str, line: &PlannedLine) -> Map<String, Value> {letmut 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.pubfn write_statement_lines( ctx: &mutCtx<'_>, input: WriteLinesInput<'_>,) -> Valid<WriteLinesResult> {letmut 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::<Vec<_>>(), )?;letmut planned: Vec<PlannedLine> = Vec::with_capacity(input.lines.len());letmut 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 {letmut 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.letmut stored: Vec<StatementLineRow> = Vec::with_capacity(planned.len() + booked_lost.len());for line in &planned {if !line.is_new && is_booked(&line.id) {letmut 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;letmut 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".pubfn recorded_counts_for( ctx: &Ctx<'_>, statement_ids: &[String],) -> Valid<BTreeMap<String, i64>> {letmut counts: BTreeMap<String, i64> = BTreeMap::new();if statement_ids.is_empty() {returnOk(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" );letmut params: Vec<SqlValue> = vec![SqlValue::Text(ctx.workspace_id.to_string())]; params.extend( statement_ids .iter() .map(|id| SqlValue::Text(id.clone())) .collect::<Vec<_>>(), );let found = ctx .db() .all(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))?;for row in found {letSome(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.pubfn id_filter(column: &str, ids: &[String]) -> Filter {Filter::In( column.to_string(), ids.iter().map(|id| SqlValue::Text(id.clone())).collect(), )}