Cotton code
265 lines · 14.9 KB · RustRaw
//! Statements as a file really holds them: a document, a statement pinned to//! its account, and every printed line — READ THROUGH THE READER'S OWN DOOR//! (`submit_statement_reading`), so the lines are fingerprinted, checked and//! recorded exactly as a real reading is: a transaction per line, the line//! cited as its evidence. The cases a walk needs are made by what is handed//! in: a line marked not-money (skipped), a closing balance that does not//! follow from the lines (totals differ — the lines are kept, nothing is//! recorded, so they stand unread), a file that could not be read, and a month//! with no statement at all.use super::{call, iso, month_back, object, refused, Household, SYNTHETIC_LABEL};use crate::mcp::handlers::common::insert_row;use crate::mcp::handlers::money::evidence::attach_evidence;use crate::mcp::handlers::money::statements::submit_statement_reading;use crate::mcp::handlers::money::statement_visual_check::{StatementFigures, VisualStatementHeader, VisualStatementLine};use cotton_core::constants::LineDirection;use crate::synthetic::names;use chrono::{DateTime, Datelike, Duration, TimeZone, Utc};use cotton_store::protocol::derived_id;use cotton_store::{Result, StoreError};use serde_json::{json, Map, Value};/// Every table a statement's reading writes into, for the household's recount.pub(super) const TABLES: &[&str] = &[    "cotton_documents",    "cotton_money_statements",    "cotton_money_statement_lines",    "cotton_money_evidence",    "cotton_money_transactions",];/// How many months back a statement is read line by line. A reading weighs/// its lines against every transaction the file holds — seconds a statement/// in a full ledger — and records a transaction a line, so three years of/// them would be half an hour of seeding and most of the ledger.const READ_MONTHS: i64 = 4;/// How one statement is to turn out.#[derive(Clone, Copy, PartialEq)]enum Case {    /// Read, and the totals agree.    Agrees,    /// Read, and the closing balance is not what the lines come to.    Differs,    /// The file could not be read at all.    Unreadable,}struct Statement {    delivered: DateTime<Utc>,    account: usize,    start: chrono::NaiveDate,    end: chrono::NaiveDate,    sha: String,    case: Case,}impl Household<'_> {    /// One statement a month for every bank and card account, newest months    /// first in the plan; see the module note for the cases.    pub(super) fn write_statements(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        // The accounts were made in `names::ACCOUNTS` order.        let held: Vec<usize> = (0..self.accounts.len())            .filter(|n| matches!(self.accounts[*n].1, "bank" | "credit_card"))            .collect();        let first = env.now.date_naive().with_day(1).expect("a first of the month");        let oldest_read = month_back(first, READ_MONTHS);        let mut statements: Vec<Statement> = Vec::new();        for month in 1..=env.plan.statement_months as i64 {            let start = month_back(first, month);            let end = month_back(first, month - 1) - Duration::days(1);            for (nth, account) in held.iter().enumerate() {                // The first account never got its statement for the month                // before last: a gap in what the paper covers.                if nth == 0 && month == 2 {                    continue;                }                let case = match (nth, month) {                    (1, 1) => Case::Differs,                    (0, 3) => Case::Unreadable,                    _ => Case::Agrees,                };                let delivered = Utc                    .from_utc_datetime(&(end + Duration::days(3)).and_hms_opt(8, 0, 0).expect("eight"))                    .min(env.now);                statements.push(Statement { delivered, account: *account, start, end, sha: env.hex(64), case });            }        }        statements.sort_by_key(|item| item.delivered);        let accounts = &self.accounts;        let mut documents: Vec<String> = Vec::new();        for statement in &statements {            let (account_id, kind, _) = &accounts[statement.account];            let (name, _, institution, mask, currency) = names::ACCOUNTS[statement.account];            let (start, end) = (statement.start.to_string(), statement.end.to_string());            let document_id = derived_id::document_id(env.file.namespace(), &statement.sha);            env.once(statement.delivered, |ctx| {                let doc_type = if *kind == "bank" { "bank_statement" } else { "card_statement" };                let mut document = Map::new();                document.insert("title".into(), Value::from(format!("{name} statement, {}", statement.start.format("%B %Y"))));                document.insert("original_name".into(), Value::from(format!("{kind}-statement-{start}.pdf")));                document.insert("mime".into(), Value::from("application/pdf"));                document.insert("byte_size".into(), Value::from(rng.between(40_000, 400_000)));                document.insert("sha256".into(), Value::from(statement.sha.clone()));                document.insert(                    "storage_path".into(),                    Value::from(cotton_core::media::keys::document_original_key(env.file.id(), &document_id, "pdf")),                );                document.insert("status".into(), Value::from("ready"));                document.insert("status_changed_at".into(), Value::from(iso(statement.delivered)));                document.insert("doc_type".into(), Value::from(doc_type));                document.insert("issuer".into(), Value::from(institution.unwrap_or(name)));                document.insert("period_start".into(), Value::from(start.clone()));                document.insert("period_end".into(), Value::from(end.clone()));                document.insert("source".into(), Value::from("app"));                insert_row(ctx, "cotton_documents", &document_id, document).map_err(refused("statement document"))?;                // The statement, pinned to its account. Written already                // FAILED where the file could not be read — the one status                // besides read that no worker picks up — and otherwise                // pending for the length of this transaction only: the                // reading below settles it.                let unreadable = statement.case == Case::Unreadable;                let mut row = Map::new();                row.insert("document_id".into(), Value::from(document_id.clone()));                row.insert("account_id".into(), Value::from(account_id.clone()));                row.insert("kind".into(), Value::from(*kind));                row.insert("period_start".into(), Value::from(start.clone()));                row.insert("period_end".into(), Value::from(end.clone()));                row.insert("currency".into(), Value::from(currency));                // Only the last [`READ_MONTHS`] are read line by line; an older                // statement is the finished row with its totals, as before.                let summary_only = !unreadable && statement.end < oldest_read;                row.insert(                    "read_status".into(),                    Value::from(if unreadable { "failed" } else if summary_only { "read" } else { "pending" }),                );                if summary_only {                    let opening = rng.between(1_000, 500_000) * 100;                    let (sum_in, sum_out) = (rng.between(0, 200_000) * 100, rng.between(0, 200_000) * 100);                    let closing = if *kind == "bank" { opening + sum_in - sum_out } else { opening + sum_out - sum_in };                    row.insert("opening_balance_minor".into(), Value::from(opening));                    row.insert("closing_balance_minor".into(), Value::from(closing));                    row.insert("read_by".into(), Value::from(SYNTHETIC_LABEL));                    row.insert("read_at".into(), Value::from(iso(statement.delivered)));                    row.insert("line_count".into(), Value::from(rng.between(8, 60)));                    row.insert("sum_in_minor".into(), Value::from(sum_in));                    row.insert("sum_out_minor".into(), Value::from(sum_out));                    row.insert("balance_check".into(), Value::from("ok"));                }                if unreadable {                    row.insert("read_error".into(), Value::from("The pages are a scan too faint to read."));                }                let statement_id = ctx.new_uuid();                insert_row(ctx, "cotton_money_statements", &statement_id, row).map_err(refused("statement"))?;                ctx.commit().map_err(refused("statement"))?;                if unreadable || summary_only {                    return Ok(());                }                // The printed lines, in date order, with the running balance a                // bank prints and a card does not.                let days = (statement.end - statement.start).num_days();                let opening = rng.between(1_000, 500_000) * 100;                let mut balance = opening;                let mut dated: Vec<i64> = (0..rng.between(8, 60)).map(|_| rng.between(0, days)).collect();                dated.sort_unstable();                let mut lines: Vec<Value> = Vec::with_capacity(dated.len() + 1);                let mut recorded_lines = Vec::with_capacity(dated.len() + 1);                let bank = *kind == "bank";                for (n, offset) in dated.iter().enumerate() {                    let posted = (statement.start + Duration::days(*offset)).to_string();                    let page = 1 + n / 25;                    // A summary row the paper prints among the entries: not                    // money, so the reader marks it and it is skipped.                    if n == 4 || (n > 0 && n % 31 == 0) {                        let carried = rng.between(100, 9_000) * 100;                        recorded_lines.push(VisualStatementLine { page: page as i64, posted_on: posted.clone(), amount_minor: carried, direction: LineDirection::In, balance_after_minor: None, ignored: true });                        lines.push(json!({                            "page": page, "posted_on": posted, "text": "BALANCE BROUGHT FORWARD",                            "amount_minor": carried, "direction": "in",                            "balance_after_minor": null, "reference": null,                            "ignored_reason": "A carried-forward total, not a payment.",                        }));                    }                    let incoming = rng.chance(if bank { 22 } else { 8 });                    let amount = if incoming { rng.between(500, 90_000) } else { rng.between(40, 6_000) } * 100;                    let text = if incoming {                        format!("TRANSFER FROM {}", rng.pick(names::ORGS).to_uppercase())                    } else {                        format!("{} {:06}", rng.pick(names::MERCHANTS).to_uppercase(), rng.below(1_000_000))                    };                    // bank: closing = opening + in − out; card (what is owed): opening + out − in.                    balance += if incoming == bank { amount } else { -amount };                    recorded_lines.push(VisualStatementLine { page: page as i64, posted_on: posted.clone(), amount_minor: amount, direction: if incoming { LineDirection::In } else { LineDirection::Out }, balance_after_minor: bank.then_some(balance), ignored: false });                    lines.push(json!({                        "page": page, "posted_on": posted, "text": text, "amount_minor": amount,                        "direction": if incoming { "in" } else { "out" },                        "balance_after_minor": if bank { Value::from(balance) } else { Value::Null },                        "reference": if rng.chance(40) { Value::from(format!("REF{:08}", rng.below(100_000_000))) } else { Value::Null },                        "ignored_reason": null,                    }));                }                let closing = if statement.case == Case::Differs { balance + 123_400 } else { balance };                // Record the invented paper's figures before handing its text                // reading to the normal handler. The fixture renderer never                // constructs its answer from that handler's candidate.                env.statement_pages.record(ctx.workspace_id, &statement_id, StatementFigures {                    header: VisualStatementHeader { page: 1, period_start: start.clone(), period_end: end.clone(), opening_balance_minor: Some(opening), closing_balance_minor: Some(closing) },                    lines: recorded_lines,                });                let args = object(json!({                    "statementId": statement_id,                    "readBy": SYNTHETIC_LABEL,                    "header": {                        "institution": institution.unwrap_or(name), "number_mask": mask, "kind": kind,                        "period_start": start, "period_end": end,                        "opening_balance_minor": opening, "closing_balance_minor": closing,                        "currency": currency, "account_name": name,                    },                    "lines": lines,                }));                let out = call("statement reading", submit_statement_reading(ctx, &args))?;                let wanted = if statement.case == Case::Differs { "mismatch" } else { "read" };                if out.get("readStatus").and_then(Value::as_str) != Some(wanted) {                    return Err(StoreError::refused(format!(                        "synthetic household: the {start} statement of {name} was to be {wanted} and came out {:?}",                        out.get("readStatus")                    )));                }                Ok(())            })?;            documents.push(document_id);        }        self.statement_documents = documents;        Ok(())    }    /// Evidence a statement does not give: a document, and a note of where    /// else the proof is, on a few of the transactions written by hand.    pub(super) fn write_evidence(&mut self) -> Result<()> {        let env = &self.env;        let documents = &self.statement_documents;        let transactions = &self.transactions;        env.once(env.now, |ctx| {            for (n, transaction) in transactions.iter().enumerate() {                let args = match documents.get(n).filter(|_| n % 2 == 0) {                    Some(document) => json!({                        "transactionId": transaction, "kind": "document", "refId": document,                        "excerpt": "Shown on page 1 of the statement.",                    }),                    None => json!({                        "transactionId": transaction, "kind": "external", "sourceLabel": "Paper receipt",                        "excerpt": "Receipt kept in the blue folder.",                    }),                };                call("evidence", attach_evidence(ctx, &object(args)))?;            }            Ok(())        })    }}