Cotton code
376 lines · 16.8 KB · RustRaw
//! Records typed by kind (architect, 11 Oct 2026: "mail from companies is//! records, not mail"). A thread whose sender is a SERVICE is a record, and the//! reader types it — `record_kind` (receipt, statement, ticket, booking, code,//! delivery, notice) — and lifts what its slip shows: the amount and its//! currency, the merchant, the date the record is ABOUT (`record_on`: the//! travel date, the statement period's end, the delivery date — never when the//! mail was sent) and its reference (an order, PNR or invoice number).//!//! RULE-BASED AND CONSERVATIVE. A kind is read off the SUBJECT, where a company//! says what the mail is; the body only lends the fields once the kind is//! known. A rule that is unsure leaves its field empty, and a subject that//! names no kind leaves the thread a `notice` with every field empty. No model//! is asked.//!//! A ONE-TIME CODE IS NEVER STORED: a code mail is typed `code` and keeps its//! merchant, and nothing else is lifted from it — not the digits, not a//! reference, not an amount.use std::sync::LazyLock;use regex::Regex;use serde_json::{Map, Value};pub const RECEIPT: &str = "receipt";pub const STATEMENT: &str = "statement";pub const TICKET: &str = "ticket";pub const BOOKING: &str = "booking";pub const CODE: &str = "code";pub const DELIVERY: &str = "delivery";pub const NOTICE: &str = "notice";/// Every kind, as the column's CHECK lists them.pub const KINDS: &[&str] = &[RECEIPT, STATEMENT, TICKET, BOOKING, CODE, DELIVERY, NOTICE];/// The columns a typed thread carries — cleared together when a thread stops/// being a service's.pub const COLUMNS: &[&str] = &["record_kind", "amount_minor", "currency", "merchant", "record_on", "reference"];/// How much of a body the rules read: a receipt's figures are near its top.const BODY_WINDOW: usize = 6_000;/// What the reader lifted from one service thread.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct RecordFields {    pub kind: &'static str,    pub amount_minor: Option<i64>,    pub currency: Option<String>,    pub merchant: Option<String>,    pub on: Option<String>,    pub reference: Option<String>,}impl RecordFields {    /// A notice: nothing lifted.    pub fn notice() -> Self {        Self { kind: NOTICE, ..Self::default() }    }    /// The row's columns, every one named (a field not lifted is NULL).    pub fn columns(&self) -> Map<String, Value> {        let mut row = Map::new();        row.insert("record_kind".into(), Value::from(self.kind));        row.insert("amount_minor".into(), self.amount_minor.map_or(Value::Null, Value::from));        row.insert("currency".into(), self.currency.clone().map_or(Value::Null, Value::from));        row.insert("merchant".into(), self.merchant.clone().map_or(Value::Null, Value::from));        row.insert("record_on".into(), self.on.clone().map_or(Value::Null, Value::from));        row.insert("reference".into(), self.reference.clone().map_or(Value::Null, Value::from));        row    }}/// Every column NULL — a thread that is no service's carries no record.pub fn cleared() -> Map<String, Value> {    COLUMNS.iter().map(|column| (column.to_string(), Value::Null)).collect()}fn rule(pattern: &str) -> Regex {    Regex::new(pattern).expect("a record rule compiles")}/// The kind a subject names, or `None`. Order matters: a code first (a code/// mail is never also a receipt), then what travels, then what is carried,/// then statements, then receipts.fn kind_of(subject: &str, body_head: &str) -> Option<&'static str> {    static CODE_RULE: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)\b(otp|one[- ]time (password|code|passcode|pin)|verification code|security code|login code|sign[- ]in code|passcode|2fa code|authentication code)\b")    });    static RULES: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {        vec![            (rule(r"(?i)\b(e-?tickets?|boarding pass(es)?|pnr|your tickets?|tickets? (for|confirmed|booked)|flight (ticket|itinerary))\b"), TICKET),            (rule(r"(?i)\b(booking (confirmed|confirmation|id|reference|details)|reservation (confirmed|confirmation|details)|your (booking|reservation|stay|trip)|itinerary|check-?in (details|reminder))\b"), BOOKING),            (rule(r"(?i)\b(out for delivery|(has been|was|is) delivered|delivered:|(has |order )?shipped|dispatched|on (its|the) way|arriving (today|tomorrow|on)|tracking (number|id|details)|shipment)\b"), DELIVERY),            (rule(r"(?i)\b(e-?statement|(account|card|credit card|bank|monthly|quarterly) statement|statement (is ready|is available|for|of account)|your statement)\b"), STATEMENT),            (rule(r"(?i)\b(receipt|tax invoice|invoice|payment (received|confirmation|confirmed|successful|of)|order (confirmed|confirmation|placed)|thank you for your (order|purchase|payment)|you paid|paid successfully|bill payment)\b"), RECEIPT),        ]    });    if CODE_RULE.is_match(subject) || CODE_RULE.is_match(body_head) {        return Some(CODE);    }    RULES.iter().find(|(rule, _)| rule.is_match(subject)).map(|(_, kind)| *kind)}/// `(currency, amount text)` for each amount the words name, in order.fn amounts(words: &str) -> Vec<(String, i64)> {    static BEFORE: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)(₹|€|£|¥|US\$|S\$|A\$|\$|\b(?:rs|inr|usd|eur|gbp|aed|sgd|aud|jpy|cad)\b\.?)\s?([0-9][0-9,]*(?:\.[0-9]{1,3})?)")    });    static AFTER: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)\b([0-9][0-9,]*(?:\.[0-9]{1,3})?)\s?(inr|usd|eur|gbp|aed|sgd|aud|jpy|cad)\b")    });    let mut found: Vec<(usize, String, i64)> = Vec::new();    for caps in BEFORE.captures_iter(words) {        let (Some(mark), Some(number)) = (caps.get(1), caps.get(2)) else { continue };        if let Some(currency) = currency_of(mark.as_str()) {            if let Some(minor) = minor_units(number.as_str(), &currency) {                found.push((mark.start(), currency, minor));            }        }    }    for caps in AFTER.captures_iter(words) {        let (Some(number), Some(mark)) = (caps.get(1), caps.get(2)) else { continue };        if let Some(currency) = currency_of(mark.as_str()) {            if let Some(minor) = minor_units(number.as_str(), &currency) {                found.push((number.start(), currency, minor));            }        }    }    found.sort_by_key(|(at, _, _)| *at);    found.into_iter().map(|(_, currency, minor)| (currency, minor)).collect()}fn currency_of(mark: &str) -> Option<String> {    let mark = mark.trim().trim_end_matches('.').to_ascii_lowercase();    Some(        match mark.as_str() {            "₹" | "rs" | "inr" => "INR",            "$" | "us$" | "usd" => "USD",            "s$" | "sgd" => "SGD",            "a$" | "aud" => "AUD",            "€" | "eur" => "EUR",            "£" | "gbp" => "GBP",            "¥" | "jpy" => "JPY",            "aed" => "AED",            "cad" => "CAD",            _ => return None,        }        .to_string(),    )}pub(crate) fn minor_units(number: &str, currency: &str) -> Option<i64> {    let plain: String = number.chars().filter(|c| *c != ',').collect();    let (whole, fraction) = plain.split_once('.').unwrap_or((plain.as_str(), ""));    let digits = usize::from(cotton_core::records::amount::digits(currency));    if fraction.len() > digits {        return None;    }    let whole: i64 = whole.parse().ok()?;    let fraction: i64 = if digits == 0 { 0 } else { format!("{fraction:0<digits$}").parse().ok()? };    let minor = whole.checked_mul(10_i64.pow(digits as u32))?.checked_add(fraction)?;    (minor > 0).then_some(minor)}/// The amount a receipt or statement is FOR: the only one it names, or the one/// a total's words lead to when there are several. Several amounts and no/// single total is unsure, and leaves it empty.fn the_amount(subject: &str, body: &str) -> Option<(String, i64)> {    static TOTAL: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)\b(grand total|total amount|amount paid|total paid|total due|amount due|total|amount)\b[^0-9₹$€£¥\n]{0,24}")    });    let words = format!("{subject}\n{body}");    let all = amounts(&words);    let distinct: std::collections::BTreeSet<&(String, i64)> = all.iter().collect();    if distinct.len() == 1 {        return all.into_iter().next();    }    // The amount a total's words lead to, close by: the next forty characters.    let totals: std::collections::BTreeSet<(String, i64)> = TOTAL        .find_iter(&words)        .filter_map(|cue| {            let near: String = words[cue.end()..].chars().take(40).collect();            amounts(&near).into_iter().next()        })        .collect();    (totals.len() == 1).then(|| totals.into_iter().next()).flatten()}/// A calendar date in the words that follow one of `cues`, as YYYY-MM-DD —/// the first cue that leads to exactly one readable date. A numeric date is/// read only when its order cannot be mistaken (a year first, or a day above/// twelve).fn date_after(words: &str, cues: &Regex) -> Option<String> {    for cue in cues.find_iter(words) {        let window: String = words[cue.end()..].chars().take(48).collect();        if let Some(date) = first_date(&window) {            return Some(date);        }    }    None}fn first_date(words: &str) -> Option<String> {    static ISO: LazyLock<Regex> = LazyLock::new(|| rule(r"\b(20[0-9]{2})-([01][0-9])-([0-3][0-9])\b"));    static DAY_MONTH: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)\b([0-3]?[0-9])(?:st|nd|rd|th)?[ -]([a-z]{3,9})[ ,-]+(20[0-9]{2})\b")    });    static MONTH_DAY: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)\b([a-z]{3,9})\.? ([0-3]?[0-9])(?:st|nd|rd|th)?,? (20[0-9]{2})\b")    });    static NUMERIC: LazyLock<Regex> = LazyLock::new(|| rule(r"\b([0-3]?[0-9])[/.]([01]?[0-9])[/.](20[0-9]{2})\b"));    let mut best: Option<(usize, String)> = None;    let mut consider = |at: usize, year: &str, month: u32, day: u32| {        if !(1..=12).contains(&month) || !(1..=31).contains(&day) {            return;        }        let year: i32 = year.parse().unwrap_or(0);        if chrono::NaiveDate::from_ymd_opt(year, month, day).is_none() {            return;        }        if best.as_ref().is_none_or(|(seen, _)| at < *seen) {            best = Some((at, format!("{year:04}-{month:02}-{day:02}")));        }    };    for caps in ISO.captures_iter(words) {        consider(caps.get(0).unwrap().start(), &caps[1], caps[2].parse().unwrap_or(0), caps[3].parse().unwrap_or(0));    }    for caps in DAY_MONTH.captures_iter(words) {        if let Some(month) = month_of(&caps[2]) {            consider(caps.get(0).unwrap().start(), &caps[3], month, caps[1].parse().unwrap_or(0));        }    }    for caps in MONTH_DAY.captures_iter(words) {        if let Some(month) = month_of(&caps[1]) {            consider(caps.get(0).unwrap().start(), &caps[3], month, caps[2].parse().unwrap_or(0));        }    }    for caps in NUMERIC.captures_iter(words) {        let day: u32 = caps[1].parse().unwrap_or(0);        // 03/04 is March or April depending on who wrote it: unsure, unread.        if day > 12 {            consider(caps.get(0).unwrap().start(), &caps[3], caps[2].parse().unwrap_or(0), day);        }    }    best.map(|(_, date)| date)}fn month_of(word: &str) -> Option<u32> {    let word = word.to_ascii_lowercase();    let months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];    if word.len() < 3 {        return None;    }    let full = [        "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december",    ];    months        .iter()        .zip(full.iter())        .position(|(short, long)| word == *short || word == *long || (word == "sept" && *short == "sep"))        .map(|index| index as u32 + 1)}/// The date the record is about, by its kind's own words.fn the_date(kind: &str, words: &str) -> Option<String> {    static TRAVEL: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)\b(date of (journey|travel)|journey date|travel date|departure( date)?|departs|departing|flight date|check-?in( date)?|arrival date|show (date|time)|event date|date)\b[:\s-]*")    });    static PERIOD: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)\b(statement period|billing period|period)\b[^\n]{0,40}?\b(to|-|–|till|until)\s+")    });    static DELIVERED: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)\b(delivered on|delivery date|expected (delivery|by|on)|arriving( on| by)?|estimated delivery|will be delivered (on|by))\b[:\s-]*")    });    static PAID: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)\b(paid on|payment date|transaction date|order date|date of (purchase|payment|transaction)|invoice date)\b[:\s-]*")    });    match kind {        TICKET | BOOKING => date_after(words, &TRAVEL),        STATEMENT => date_after(words, &PERIOD),        DELIVERY => date_after(words, &DELIVERED),        RECEIPT => date_after(words, &PAID),        _ => None,    }}/// The reference its own words name: an order, PNR, booking, invoice,/// confirmation or tracking number — a token with a digit in it.fn the_reference(words: &str) -> Option<String> {    static REFERENCE: LazyLock<Regex> = LazyLock::new(|| {        rule(r"(?i)\b(?:order|pnr|booking|invoice|confirmation|reservation|tracking|awb|ticket|receipt)\s*(?:no\.?|number|num|id|ref(?:erence)?|code|#)?\s*[:#-]?\s*([A-Z0-9][A-Z0-9-]{4,24})\b")    });    REFERENCE        .captures_iter(words)        .filter_map(|caps| caps.get(1).map(|token| token.as_str().to_string()))        .find(|token| token.chars().any(|c| c.is_ascii_digit()) && token.chars().any(|c| c.is_ascii_alphanumeric()))        .map(|token| token.to_ascii_uppercase())}/// The merchant: the sender's display name, trimmed of quotes and of the/// address some mailers repeat in it.fn the_merchant(from_name: Option<&str>) -> Option<String> {    let name = from_name?.trim().trim_matches(|c| c == '"' || c == '\'').trim();    let name = name.split(" <").next().unwrap_or(name).trim();    (!name.is_empty() && !name.contains('@') && name.chars().count() <= 80).then(|| name.to_string())}/// Type one service thread by its newest mail from the sender: the subject,/// the body (plain text) and the sender's display name.pub fn read_record(subject: &str, body: &str, from_name: Option<&str>) -> RecordFields {    let body: String = body.chars().take(BODY_WINDOW).collect();    let head: String = body.chars().take(500).collect();    let Some(kind) = kind_of(subject, &head) else {        return RecordFields::notice();    };    let merchant = the_merchant(from_name);    if kind == CODE {        // The code itself, and anything beside it, stays in the mail.        return RecordFields { kind, merchant, ..RecordFields::default() };    }    let words = format!("{subject}\n{body}");    let (currency, amount_minor) = match kind {        RECEIPT | STATEMENT | TICKET | BOOKING => the_amount(subject, &body).map_or((None, None), |(c, a)| (Some(c), Some(a))),        _ => (None, None),    };    RecordFields {        kind,        amount_minor,        currency,        merchant,        on: the_date(kind, &words),        reference: match kind {            STATEMENT => None,            _ => the_reference(&words),        },    }}/// The `from_kind` record (a transaction, an event) a Records thread was/// recorded as — the link its act wrote, from the record to the thread.pub fn recorded_as(ctx: &crate::mcp::dispatch::Ctx<'_>, thread_id: &str, from_kind: &str) -> Option<String> {    ctx.db()        .get(            "SELECT from_id FROM cotton_links WHERE workspace_id = ?1 AND from_kind = ?2 \               AND to_kind = 'email_thread' AND to_id = ?3 AND to_database IS NULL \             ORDER BY created_at, id LIMIT 1",            &[                rusqlite::types::Value::Text(ctx.workspace_id.to_string()),                rusqlite::types::Value::Text(from_kind.to_string()),                rusqlite::types::Value::Text(thread_id.to_string()),            ],        )        .ok()        .flatten()        .and_then(|row| row.text("from_id").map(str::to_string))}/// The Records thread a transaction or an event was recorded from.pub fn recorded_from(ctx: &crate::mcp::dispatch::Ctx<'_>, from_kind: &str, from_id: &str) -> Option<String> {    ctx.db()        .get(            "SELECT to_id FROM cotton_links WHERE workspace_id = ?1 AND from_kind = ?2 AND from_id = ?3 \               AND to_kind = 'email_thread' AND to_database IS NULL ORDER BY created_at, id LIMIT 1",            &[                rusqlite::types::Value::Text(ctx.workspace_id.to_string()),                rusqlite::types::Value::Text(from_kind.to_string()),                rusqlite::types::Value::Text(from_id.to_string()),            ],        )        .ok()        .flatten()        .and_then(|row| row.text("to_id").map(str::to_string))}#[cfg(test)]#[path = "record_fields_tests.rs"]mod tests;