Cotton code
391 lines · 17.9 KB · RustRaw
//! Small typed helpers shared by statement reads and the generic table reader.use std::collections::BTreeMap;use serde_json::{Map, Value};use crate::mcp::dispatch::Ctx;pub fn today_of(args: &Map<String, Value>) -> Result<String, String> {    let Some(day) = args        .get("today")        .and_then(Value::as_str)        .filter(|day| cotton_core::records::is_date(day))    else {        return Err("Please provide today as a valid calendar day in YYYY-MM-DD.".into());    };    Ok(day.into())}/// Statement imports need one typed state for each line. A booked line is not/// inferred from a ledger; it is linked to its one Money row.pub fn line_state(transaction: Option<&str>, ignored: Option<&str>) -> &'static str {    if transaction.is_some() {        "recorded"    } else if ignored.is_some() {        "skipped"    } else {        "unread"    }}/// The reader-day is only meaningful to derived definition views. Money rows/// carry their own occurrence day, so ordinary reads accept it unchanged.pub fn validate_view_day(    _ctx: &Ctx<'_>,    _table: &str,    args: &Map<String, Value>,) -> Result<(), String> {    if args.contains_key("today") {        today_of(args).map(|_| ())    } else {        Ok(())    }}/// Resolve typed Money columns for the MCP reader without composing display prose.pub fn engine_rows(    ctx: &Ctx<'_>,    table: &str,    rows: Vec<(String, Map<String, Value>)>,    _args: &Map<String, Value>,) -> Result<Vec<Map<String, Value>>, String> {    project_rows(ctx.read.driver(), ctx.workspace_id, table, rows)}/// Physical source tables whose changes invalidate this typed projection./// Derived readers use the same inputs as the MCP path, including balances/// anchored by a checked statement and movements after that statement.pub fn projection_tables(table: &str) -> &'static [&'static str] {    match table {        "money_account" => &[            "cotton_money_accounts",            "cotton_money_statements",            "cotton_money_transactions",        ],        "transaction" => &["cotton_money_transactions", "cotton_money_evidence"],        "statement" => &[            "cotton_money_statements",            "cotton_money_statement_lines",            "cotton_money_evidence",        ],        "statement_line" => &[            "cotton_money_statement_lines",            "cotton_money_statements",            "cotton_money_evidence",        ],        "evidence" => &["cotton_money_evidence"],        _ => &[],    }}/// Canonical Money columns over stored rows, also used by derived readers./// It reads no clock, service or writer and cannot change the file.pub fn project_rows(    db: &cotton_store::Driver,    workspace_id: &str,    table: &str,    rows: Vec<(String, Map<String, Value>)>,) -> Result<Vec<Map<String, Value>>, String> {    if rows.is_empty() {        return Ok(Vec::new());    }    if matches!(table, "statement" | "statement_line" | "evidence" | "transaction") {        let mut facts = BTreeMap::new();        for chunk in rows.chunks(400) {            // Lead with the caller's bounded ids. Without statistics SQLite can            // prefer a workspace index over an IN list and scan its archive.            let selected = (0..chunk.len()).map(|i| format!("(?{})", i + 2)).collect::<Vec<_>>().join(",");            let mut params = vec![rusqlite::types::Value::Text(workspace_id.into())];            params.extend(                chunk                    .iter()                    .map(|(id, _)| rusqlite::types::Value::Text(id.clone())),            );            let sql=match table {                "statement" => format!("WITH selected(id) AS (VALUES {selected}) SELECT s.id,(SELECT COUNT(DISTINCT l.id) FROM cotton_money_statement_lines l JOIN cotton_money_evidence e ON e.workspace_id=l.workspace_id AND e.kind='statement_line' AND e.ref_id=l.id WHERE l.workspace_id=s.workspace_id AND l.statement_id=s.id) AS recorded_count FROM selected CROSS JOIN cotton_money_statements s WHERE s.workspace_id=?1 AND s.id=selected.id"),                "statement_line" => format!("WITH selected(id) AS (VALUES {selected}) SELECT l.id,l.text,l.ignored_reason,s.currency,(SELECT e.transaction_id FROM cotton_money_evidence e WHERE e.workspace_id=l.workspace_id AND e.kind='statement_line' AND e.ref_id=l.id LIMIT 1) AS transaction_id FROM selected CROSS JOIN cotton_money_statement_lines l JOIN cotton_money_statements s ON s.id=l.statement_id AND s.workspace_id=l.workspace_id WHERE l.workspace_id=?1 AND l.id=selected.id"),                "evidence" => format!("WITH selected(id) AS (VALUES {selected}) SELECT e.id,e.kind,e.attached_by FROM selected CROSS JOIN cotton_money_evidence e WHERE e.workspace_id=?1 AND e.id=selected.id"),                _ => format!("WITH selected(id) AS (VALUES {selected}) SELECT t.id,t.description,t.payee_text,EXISTS(SELECT 1 FROM cotton_money_evidence e INDEXED BY idx_cotton_money_evidence_transaction WHERE e.workspace_id=t.workspace_id AND e.transaction_id=t.id AND e.kind='statement_line') AS booked,EXISTS(SELECT 1 FROM cotton_money_transactions paid INDEXED BY idx_cotton_money_transactions_settles WHERE paid.workspace_id=t.workspace_id AND paid.status='actual' AND paid.trashed_at IS NULL AND paid.settles_transaction_id=t.id) AS settled FROM selected CROSS JOIN cotton_money_transactions t WHERE t.workspace_id=?1 AND t.id=selected.id"),            };            for fact in db                .all(&sql, &params)                .map_err(|e| e.to_string())?            {                if let Some(id) = fact.text("id") {                    facts.insert(id.to_string(), fact);                }            }        }        return Ok(rows            .into_iter()            .map(|(id, mut row)| {                if let Some(fact) = facts.get(&id) {                    match table {                        "statement" => { row.insert("recorded_count".into(), Value::from(fact.int("recorded_count").unwrap_or(0))); visual_problem(&mut row); },                        "statement_line" => {                            row.insert(                                "title".into(),                                Value::from(fact.text("text").unwrap_or_default()),                            );                            row.insert(                                "currency".into(),                                fact.text("currency").map_or(Value::Null, Value::from),                            );                            row.insert(                                "transaction_id".into(),                                fact.text("transaction_id").map_or(Value::Null, Value::from),                            );                            row.insert(                                "state".into(),                                Value::from(line_state(                                    fact.text("transaction_id"),                                    fact.text("ignored_reason"),                                )),                            );                        }                        "evidence" => {                            deletable(                                &mut row,                                crate::mcp::handlers::money::evidence::a_person_may_remove(                                    fact.text("kind").unwrap_or_default(),                                    fact.text("attached_by").unwrap_or_default(),                                ),                            );                        }                        _ => {                            deletable(&mut row, fact.int("booked") == Some(0));                            row.insert(                                "settled".into(),                                Value::Bool(fact.int("settled") == Some(1)),                            );                            // Its slip, its page and a link to it name it the                            // same: who it was with, else what it was for.                            let words: Map<String, Value> = ["payee_text", "description"]                                .into_iter()                                .filter_map(|key| fact.text(key).map(|text| (key.to_string(), Value::from(text))))                                .collect();                            row.insert(                                "title".into(),                                movement_title(&words).map_or(Value::Null, Value::from),                            );                        }                    }                }                row            })            .collect());    }    if table != "money_account" {        return Ok(rows.into_iter().map(|(_, row)| row).collect());    }    let mut facts = BTreeMap::new();    for chunk in rows.chunks(400) {        let holes = vec!["?"; chunk.len()].join(",");        let mut params = vec![rusqlite::types::Value::Text(workspace_id.into())];        params.extend(            chunk                .iter()                .map(|(id, _)| rusqlite::types::Value::Text(id.clone())),        );        // Balances are supplied by the object's engine. This projection only        // normalizes the account's descriptive fields; it never totals money.        let sql = format!("SELECT a.id,a.kind,a.subtype,a.number_mask,a.is_pooled \            FROM cotton_money_accounts a WHERE a.workspace_id=? AND a.id IN ({holes})");        for fact in db            .all(&sql, &params)            .map_err(|e| e.to_string())?        {            if let Some(id) = fact.text("id") {                facts.insert(id.to_string(), fact);            }        }    }    Ok(rows        .into_iter()        .map(|(id, mut row)| {            if let Some(fact) = facts.get(&id) {                let subtype = fact.text("subtype").unwrap_or_default();                row.insert(                    "kind".into(),                    Value::from(if fact.text("kind") == Some("loan") {                        "loan"                    } else {                        subtype                    }),                );                row.insert(                    "number_mask".into(),                    fact.text("number_mask")                        .map(|number| Value::from(cotton_core::records::account_number_ending(number)))                        .unwrap_or(Value::Null),                );                row.insert(                    "is_pooled".into(),                    Value::Bool(                        fact.int("is_pooled")                            .map(|v| v != 0)                            .unwrap_or(fact.text("kind") == Some("bank") && subtype == "bank"),                    ),                );            }            row        })        .collect())}/// `can_delete` is said only of a row that may be deleted: the definitions'/// `delete_when` reads its presence, so a `false` written beside it offered/// Delete on a booked movement that `delete_transaction` then refused.fn deletable(row: &mut Map<String, Value>, may: bool) {    if may {        row.insert("can_delete".into(), Value::Bool(true));    } else {        row.remove("can_delete");    }}/// Bank text as a person would write it: "BEACON CINEMA 539351" is "Beacon/// Cinema". Words somebody typed (anything with a small letter) are left as/// they are; text all in capitals loses the reference digits a bank puts at/// its end and is set in ordinary capitals. The raw text stays on the/// statement line it was read from.pub fn tidy_bank_text(text: &str) -> String {    let text = text.trim();    if text.chars().any(char::is_lowercase) || !text.chars().any(char::is_alphabetic) {        return text.to_string();    }    let mut words: Vec<&str> = text.split_whitespace().collect();    let reference = |word: &str| {        word.chars().any(|c| c.is_ascii_digit()) && !word.chars().any(char::is_alphabetic)    };    while words.len() > 1 && words.last().is_some_and(|word| reference(word)) {        words.pop();    }    let mut out = String::new();    for (place, word) in words.iter().enumerate() {        if place > 0 {            out.push(' ');        }        // The small joining words stay small inside a name: "Transfer from        // Umber & Co".        let small = place > 0            && ["FROM", "TO", "OF", "AND", "THE", "AT", "FOR", "BY", "IN", "ON"].contains(word);        let mut inside = small;        for c in word.chars() {            if c.is_alphabetic() {                if inside {                    out.extend(c.to_lowercase());                } else {                    out.extend(c.to_uppercase());                }                inside = true;            } else {                // An apostrophe stays inside its word: "Baker's", never "Baker'S".                inside = inside && c == '\'';                out.push(c);            }        }    }    out}/// What a movement is called: who it was with, else what it was for, bank/// text tidied (`tidy_bank_text`). A payee that only repeats the words/// ("harbour bakery" at "Harbour bakery") gives way to them, because the/// words were written to be read.pub fn movement_title(data: &Map<String, Value>) -> Option<String> {    let word = |key: &str| {        data.get(key)            .and_then(Value::as_str)            .map(str::trim)            .filter(|text| !text.is_empty())    };    let named = match (word("payee_text"), word("description")) {        (Some(payee), Some(what)) if payee.eq_ignore_ascii_case(what) => Some(what),        (Some(payee), _) => Some(payee),        (None, what) => what,    };    named.map(tidy_bank_text)}#[cfg(test)]mod movement_title_tests {    use serde_json::json;    use super::{deletable, movement_title, tidy_bank_text};    /// RULE: A Money row says can_delete only where it may be deleted, because delete_when reads the key's presence; a booked movement offers no Delete its verb would refuse.    #[test]    fn a_row_that_may_not_be_deleted_says_nothing_of_it() {        let mut row = json!({"can_delete": true}).as_object().unwrap().clone();        deletable(&mut row, false);        assert!(!row.contains_key("can_delete"));        deletable(&mut row, true);        assert_eq!(row.get("can_delete"), Some(&json!(true)));    }    /// RULE: A movement is called by who it was with, else by what it was for; a payee that only repeats the words gives way to them as they were written.    // The one-row rewrite (d36e64379) dropped this title with the ledger, and    // every imported movement read its raw bank narration on its slip, its    // page and in a link: the payee the import kept was on no surface.    #[test]    fn a_movement_is_titled_by_its_payee_else_its_words() {        let said = |payee: Option<&str>, what: Option<&str>| {            movement_title(json!({"payee_text": payee, "description": what}).as_object().unwrap())        };        assert_eq!(said(Some("Quay Street Grocer"), Some("UPI 8841 QSG")), Some("Quay Street Grocer".into()));        assert_eq!(said(Some("harbour bakery"), Some("Harbour bakery")), Some("Harbour bakery".into()));        assert_eq!(said(Some("  "), Some("Rent")), Some("Rent".into()));        assert_eq!(said(None, None), None);        assert_eq!(said(Some("BEACON CINEMA 539351"), Some("BEACON CINEMA 539351")), Some("Beacon Cinema".into()));        assert_eq!(tidy_bank_text("UPI/ALDER GROCERS 00417 88213"), "Upi/Alder Grocers");        assert_eq!(tidy_bank_text("BAKER'S DOZEN #4471"), "Baker's Dozen");        assert_eq!(tidy_bank_text("Quay street grocer 12"), "Quay street grocer 12");        assert_eq!(tidy_bank_text("539351"), "539351");        assert_eq!(tidy_bank_text("TRANSFER FROM UMBER & CO"), "Transfer from Umber & Co");        assert_eq!(tidy_bank_text("THE FERRY LINE 973730"), "The Ferry Line");    }}/// Only typed visual-refusal metadata reaches the definition. The synced error/// stays machine-readable; figures and renderer diagnostics never become prose.fn visual_problem(row: &mut Map<String, Value>) {    let Some(reason) = row.get("read_error").and_then(Value::as_str)        .and_then(|error| serde_json::from_str::<Value>(error).ok()) else { return; };    let Some(code) = reason.get("code").and_then(Value::as_str) else { return; };    let kind = match code {        "visual_mismatch" if reason.get("page").and_then(Value::as_i64).is_some_and(|page| page > 0) => "page_mismatch",        "visual_mismatch" => "heading_mismatch",        "visual_unavailable" => "unavailable",        "visual_renderer_failed" => "renderer_failed",        "visual_glyph_maps_unread" => "glyph_maps_unread",        _ => return,    };    row.insert("read_error".into(), Value::Null);    row.insert("visual_problem".into(), Value::from(kind));    if let Some(page) = reason.get("page").and_then(Value::as_i64).filter(|page| *page > 0) {        row.insert("visual_problem_page".into(), Value::from(page));    }    if let Some(field) = reason.get("field").and_then(Value::as_str).filter(|field| matches!(*field,        "entry_type" | "entry_count" | "date" | "amount" | "direction" | "balance" | "balance_after" | "balance_after_minor" | "period_start" | "period_end" | "opening_balance" | "closing_balance" | "opening_balance_minor" | "closing_balance_minor")) {        row.insert("visual_problem_field".into(), Value::from(field));    }}#[cfg(test)]mod visual_problem_tests {    use super::*;    use serde_json::json;    /// RULE: The statement engine supplies typed refusal facts to definition lines, never raw JSON or renderer diagnostics on a page.    #[test]    fn visual_refusal_projects_only_safe_typed_facts() {        let mut row = json!({"read_error":r#"{"code":"visual_mismatch","page":2,"field":"amount","details":"private fixture"}"#}).as_object().unwrap().clone();        visual_problem(&mut row);        assert_eq!(row, json!({"read_error":null,"visual_problem":"page_mismatch","visual_problem_page":2,"visual_problem_field":"amount"}).as_object().unwrap().clone());        let mut old = json!({"read_error":"reader unavailable"}).as_object().unwrap().clone();        visual_problem(&mut old);        assert_eq!(old["read_error"], "reader unavailable");    }}