Cotton code
459 lines · 15.7 KB · RustRaw
//! Statement reader contract, evidence kinds and stable external row identities.use cotton_core::constants::{LineDirection, StatementKind};use serde_json::Value;use sha2::{Digest, Sha256};/// `DOCUMENT_STATEMENT_TYPES` — permanent home `cotton_core::constants`.pub const DOCUMENT_STATEMENT_TYPES: [&str; 3] =    ["bank_statement", "card_statement", "statement_other"];/// Which filed documents are READ as statements.////// DERIVED from [`DOCUMENT_STATEMENT_TYPES`] minus `statement_other`, which the/// reader's contract has no kind for (`bank` | `credit_card`): minting a/// pending row for an investment or utility statement would pay a model to read/// a document it cannot represent, and then report a mismatch about it. Every/// writer of a pending row reads THIS, so "which documents are statements" is/// answered once.pub const READABLE_STATEMENT_DOC_TYPES: [&str; 2] = ["bank_statement", "card_statement"];pub fn is_readable_statement_doc_type(doc_type: Option<&str>) -> bool {    doc_type.is_some_and(|value| READABLE_STATEMENT_DOC_TYPES.contains(&value))}/// `cotton_money_evidence.kind` — what proves a transaction happened.pub const EVIDENCE_KINDS: [&str; 5] =    ["statement_line", "document", "message", "email", "external"];/// Every kind but `external`, which is the one that points at nothing.////// `EVIDENCE_KINDS.filter(kind => kind !== "external")` — derived there,/// spelled out here, and the total match in [`evidence_ref_table`] is what/// keeps the two from drifting.pub const EVIDENCE_KINDS_NEEDING_REF: [&str; 4] =    ["statement_line", "document", "message", "email"];/// Where each kind of evidence's `ref_id` has to actually exist.////// `ref_id` carries NO foreign key — one column standing in for five tables is/// not something SQLite can point at — so the check is the handler's. TOTAL/// over [`EVIDENCE_KINDS`], with `external` the written `None`: a row from/// somebody's spreadsheet has no row HERE to point at, which is why that kind/// carries a source label instead.pub fn evidence_ref_table(kind: &str) -> Option<Option<&'static str>> {    match kind {        "statement_line" => Some(Some("cotton_money_statement_lines")),        "document" => Some(Some("cotton_documents")),        "message" => Some(Some("cotton_msg_messages")),        "email" => Some(Some("cotton_emails")),        "external" => Some(None),        _ => None,    }}// ── the external evidence ref ───────────────────────────────────────────────/// A separator no field can contain, so the canonical form is unambiguous.const SEPARATOR: &str = "\u{0}";/// The stable id an external evidence row is filed under.////// The file's uniqueness rule for evidence is PARTIAL and skips nulls, so a/// null-ref external row could be attached again on every retry — of a tool/// annotated idempotent. A spreadsheet row has no id of its own, so the ref is/// DERIVED from what identifies it: the source label plus the row's content,/// sha256'd. One hash, shared by `attach_evidence` and `match_external`; a/// second would drift, and two spellings of "the same external row" is exactly/// the duplicate this guards against.pub fn external_ref(source_label: &str, parts: &[&str]) -> String {    let mut canonical = source_label.trim().to_string();    for part in parts {        canonical.push_str(SEPARATOR);        canonical.push_str(part);    }    let digest = Sha256::digest(canonical.as_bytes());    let hex = hex::encode(digest);    format!("ext:{}", &hex[..32])}// ── the statement reading contract ──────────────────────────────────────────/// The header, as a reading states it.#[derive(Debug, Clone, PartialEq)]pub struct StatementReadHeader {    pub institution: String,    pub number_mask: Option<String>,    pub kind: StatementKind,    pub period_start: String,    pub period_end: String,    pub opening_balance_minor: Option<i64>,    pub closing_balance_minor: Option<i64>,    pub currency: String,    pub account_name: String,}/// One entry, as a reading states it.#[derive(Debug, Clone, PartialEq)]pub struct StatementReadLine {    pub page: i64,    pub posted_on: String,    pub text: String,    /// Positive whole paise, always — `direction` carries the sign.    pub amount_minor: i64,    pub direction: LineDirection,    pub balance_after_minor: Option<i64>,    pub reference: Option<String>,    pub ignored_reason: Option<String>,}#[derive(Debug, Clone, PartialEq)]pub struct StatementReadOutput {    pub header: StatementReadHeader,    pub lines: Vec<StatementReadLine>,}/// The one sentence a contract failure is allowed to say by itself.pub const STATEMENT_CONTRACT_ERROR_TEXT: &str = "the statement reading did not match the contract";/// How many refused fields a message names before it says "+N more".////// Not cosmetic: one wrong assumption ("amounts are rupees") breaks every line/// on the page, and a message naming four hundred of them is unreadable, would/// not fit `read_error`'s 500 characters, and says nothing the first five do/// not.pub const MAX_REPORTED_ISSUES: usize = 5;/// One refused field: WHERE it is, and WHY — never what it held.#[derive(Debug, Clone, PartialEq)]pub struct ContractIssue {    pub path: String,    pub why: String,}/// A reading that will not parse, reduced to paths and our own sentences.#[derive(Debug, Clone, PartialEq)]pub struct StatementContractError {    pub issues: Vec<ContractIssue>,}impl StatementContractError {    fn one(path: impl Into<String>, why: impl Into<String>) -> StatementContractError {        StatementContractError {            issues: vec![ContractIssue {                path: path.into(),                why: why.into(),            }],        }    }    /// Every refused field, as `path: why`, capped.    pub fn detail(&self) -> String {        if self.issues.is_empty() {            return "(no issue reported)".to_string();        }        let shown = self            .issues            .iter()            .take(MAX_REPORTED_ISSUES)            .map(|issue| format!("{}: {}", issue.path, issue.why))            .collect::<Vec<_>>()            .join("; ");        let rest = self.issues.len().saturating_sub(MAX_REPORTED_ISSUES);        if rest > 0 {            format!("{shown} (+{rest} more)")        } else {            shown        }    }    /// What may be written into `read_error` and handed to an assistant.    pub fn text(&self) -> String {        format!("{STATEMENT_CONTRACT_ERROR_TEXT}: {}", self.detail())    }}fn is_iso_date(value: &str) -> bool {    let bytes = value.as_bytes();    bytes.len() == 10        && bytes[..4].iter().all(u8::is_ascii_digit)        && bytes[4] == b'-'        && bytes[5..7].iter().all(u8::is_ascii_digit)        && bytes[7] == b'-'        && bytes[8..10].iter().all(u8::is_ascii_digit)}/// `z.string().trim()` — the trim is JavaScript's, applied before every length/// check, exactly as zod's `.trim()` is.fn trimmed(value: &Value) -> Option<String> {    value.as_str().map(|text| text.trim().to_string())}/// zod's own words for a wrong type. `expected X, received Y` with TYPE NAMES/// on both sides and never the value.fn type_name(value: &Value) -> &'static str {    match value {        Value::Null => "null",        Value::Bool(_) => "boolean",        Value::Number(number) => {            if number.as_i64().is_some() || number.as_u64().is_some() {                "number"            } else {                "float"            }        }        Value::String(_) => "string",        Value::Array(_) => "array",        Value::Object(_) => "object",    }}fn require_string(    object: &serde_json::Map<String, Value>,    path: &str,    key: &str,    min: usize,    max: usize,) -> Result<String, StatementContractError> {    let Some(raw) = object.get(key) else {        return Err(StatementContractError::one(            format!("{path}{key}"),            "expected string, received undefined",        ));    };    let Some(value) = trimmed(raw) else {        return Err(StatementContractError::one(            format!("{path}{key}"),            format!("expected string, received {}", type_name(raw)),        ));    };    let length = value.chars().count();    if length < min {        return Err(StatementContractError::one(            format!("{path}{key}"),            format!("String must contain at least {min} character(s)"),        ));    }    if length > max {        return Err(StatementContractError::one(            format!("{path}{key}"),            format!("String must contain at most {max} character(s)"),        ));    }    Ok(value)}fn require_integer(    object: &serde_json::Map<String, Value>,    path: &str,    key: &str,) -> Result<i64, StatementContractError> {    let Some(raw) = object.get(key) else {        return Err(StatementContractError::one(            format!("{path}{key}"),            "expected number, received undefined",        ));    };    match raw.as_i64() {        Some(value) => Ok(value),        None => Err(StatementContractError::one(            format!("{path}{key}"),            format!("expected integer, received {}", type_name(raw)),        )),    }}fn nullable_integer(    object: &serde_json::Map<String, Value>,    path: &str,    key: &str,) -> Result<Option<i64>, StatementContractError> {    match object.get(key) {        None => Err(StatementContractError::one(            format!("{path}{key}"),            "expected number, received undefined",        )),        Some(Value::Null) => Ok(None),        Some(raw) => match raw.as_i64() {            Some(value) => Ok(Some(value)),            None => Err(StatementContractError::one(                format!("{path}{key}"),                format!("expected integer, received {}", type_name(raw)),            )),        },    }}fn nullable_string(    object: &serde_json::Map<String, Value>,    path: &str,    key: &str,    min: usize,    max: usize,) -> Result<Option<String>, StatementContractError> {    match object.get(key) {        None => Err(StatementContractError::one(            format!("{path}{key}"),            "expected string, received undefined",        )),        Some(Value::Null) => Ok(None),        Some(_) => Ok(Some(require_string(object, path, key, min, max)?)),    }}fn require_iso_date(    object: &serde_json::Map<String, Value>,    path: &str,    key: &str,) -> Result<String, StatementContractError> {    let Some(raw) = object.get(key) else {        return Err(StatementContractError::one(            format!("{path}{key}"),            "expected string, received undefined",        ));    };    let Some(value) = raw.as_str() else {        return Err(StatementContractError::one(            format!("{path}{key}"),            format!("expected string, received {}", type_name(raw)),        ));    };    if !is_iso_date(value) {        return Err(StatementContractError::one(            format!("{path}{key}"),            "must be YYYY-MM-DD",        ));    }    Ok(value.to_string())}fn require_enum<T: Copy>(    object: &serde_json::Map<String, Value>,    path: &str,    key: &str,    allowed: &[(&str, T)],) -> Result<T, StatementContractError> {    let names = allowed        .iter()        .map(|(name, _)| *name)        .collect::<Vec<_>>()        .join(" | ");    let raw = object.get(key);    let found = raw        .and_then(Value::as_str)        .and_then(|text| allowed.iter().find(|(name, _)| *name == text));    match found {        Some((_, value)) => Ok(*value),        // The value is DELIBERATELY not quoted: zod's own `invalid_enum_value`        // spells out what it received, and on this path that is a line off        // somebody's bank statement.        None => Err(StatementContractError::one(            format!("{path}{key}"),            format!("expected one of {names}"),        )),    }}/// Parse a reading, or say which FIELD broke.pub fn parse_read_output(    header: &Value,    lines: &Value,) -> Result<StatementReadOutput, StatementContractError> {    let Some(header_object) = header.as_object() else {        return Err(StatementContractError::one(            "header",            format!("expected object, received {}", type_name(header)),        ));    };    let path = "header.";    let institution = require_string(header_object, path, "institution", 1, 120)?;    let number_mask = nullable_string(header_object, path, "number_mask", 1, 24)?;    let kind = require_enum(        header_object,        path,        "kind",        &[            ("bank", StatementKind::Bank),            ("credit_card", StatementKind::CreditCard),        ],    )?;    let period_start = require_iso_date(header_object, path, "period_start")?;    let period_end = require_iso_date(header_object, path, "period_end")?;    if period_end < period_start {        return Err(StatementContractError::one(            "header.period_end",            "period_end must not be before period_start",        ));    }    let opening_balance_minor = nullable_integer(header_object, path, "opening_balance_minor")?;    let closing_balance_minor = nullable_integer(header_object, path, "closing_balance_minor")?;    let currency = require_string(header_object, path, "currency", 3, 3)?;    let account_name = require_string(header_object, path, "account_name", 1, 80)?;    let Some(line_array) = lines.as_array() else {        return Err(StatementContractError::one(            "lines",            format!("expected array, received {}", type_name(lines)),        ));    };    let mut parsed: Vec<StatementReadLine> = Vec::with_capacity(line_array.len());    for (index, raw) in line_array.iter().enumerate() {        let path = format!("lines[{index}].");        let Some(object) = raw.as_object() else {            return Err(StatementContractError::one(                format!("lines[{index}]"),                format!("expected object, received {}", type_name(raw)),            ));        };        let page = require_integer(object, &path, "page")?;        if page < 1 {            return Err(StatementContractError::one(                format!("{path}page"),                "Number must be greater than or equal to 1",            ));        }        let posted_on = require_iso_date(object, &path, "posted_on")?;        let text = require_string(object, &path, "text", 1, 500)?;        let amount_minor = require_integer(object, &path, "amount_minor")?;        if amount_minor <= 0 {            return Err(StatementContractError::one(                format!("{path}amount_minor"),                "Number must be greater than 0",            ));        }        let direction = require_enum(            object,            &path,            "direction",            &[("in", LineDirection::In), ("out", LineDirection::Out)],        )?;        let balance_after_minor = nullable_integer(object, &path, "balance_after_minor")?;        let reference = nullable_string(object, &path, "reference", 0, 120)?;        let ignored_reason = nullable_string(object, &path, "ignored_reason", 0, 120)?;        parsed.push(StatementReadLine {            page,            posted_on,            text,            amount_minor,            direction,            balance_after_minor,            reference,            ignored_reason,        });    }    Ok(StatementReadOutput {        header: StatementReadHeader {            institution,            number_mask,            kind,            period_start,            period_end,            opening_balance_minor,            closing_balance_minor,            currency,            account_name,        },        lines: parsed,    })}