Cotton code
450 lines · 17.9 KB · RustRaw
//! Every money row knows its account's balance before and after it (owner,//! 27 Oct 2026), and an account knows its balance. This is the object's rule//! (`apps/business/src/balances.ts`) run on the phone too, so a local copy —//! before Backup, or while the object has not answered — shows the same//! figures the object will. The two are held together by one vector table,//! `crates/cotton-rules/vectors/balances.json`, that both test suites read.//!//! An account's run is its live rows (not binned, moving money, amount known,//! not a suggestion, not an expectation an actual row already settles) in two//! parts: what has happened (every row but an expected one, dated today or//! before) and what is coming (every expected row, and any row dated after//! today), each by day, then the moment it was made, then its statement line.//!//! The latest known balance anchors the run: a balance a statement printed//! after a line, a read statement's closing balance at the end of its period//! or its opening balance at the start of it, or the balance the account is//! known to have held at the end of a day. On one day the start comes before//! the end, and at the end a known balance beats a closing, a closing beats a//! line's; between two lines, the later row. The run walks forward and back//! from the anchor. No anchor, no balances: a balance is never guessed from//! zero.//!//! On a card the balance is what is owed, so money out raises it; on every//! other account (a loan too) money in raises it. Below zero is `overdrawn`,//! or `recovers` when that calendar month ends back at zero or above; a card//! or a loan is never overdrawn.use std::cmp::Ordering;use std::collections::{BTreeMap, HashMap, HashSet};use serde::{Deserialize, Serialize};use serde_json::{Map, Value};string_enum! {    /// `LINE_DIRECTIONS` — mirrors `cotton_money_statement_lines.direction`,    /// from the ACCOUNT's point of view. For a card a spend is `out` and a    /// payment or refund is `in`, which is the opposite of what the card's own    /// balance does; the sign convention lives in `checkStatement`, never in a    /// reader's head.    LineDirection {        In => "in",        Out => "out",    }}/// What a row's balance says about the account after it.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum BalanceState {    Ok,    Overdrawn,    Recovers,}impl BalanceState {    pub const fn as_str(self) -> &'static str {        match self {            Self::Ok => "ok",            Self::Overdrawn => "overdrawn",            Self::Recovers => "recovers",        }    }}/// The numbers a money row carries; all empty when its account has no anchor.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct Balance {    pub balance_before_minor: Option<i64>,    pub balance_after_minor: Option<i64>,    pub balance_state: Option<BalanceState>,}/// One row of an account's run.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct RunRow {    pub id: String,    pub day: String,    pub created_at: String,    /// Its statement line's place, when it was booked from one.    pub line_no: Option<i64>,    pub amount_minor: i64,    pub direction: LineDirection,    pub expected: bool,}/// The balances one of the account's read statements printed.#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct StatementBalances {    pub period_start: Option<String>,    pub opening_balance_minor: Option<i64>,    pub period_end: Option<String>,    pub closing_balance_minor: Option<i64>,}/// An account as its run needs it.#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct RunAccount {    pub kind: Option<String>,    pub known_balance_minor: Option<i64>,    pub known_balance_on: Option<String>,    #[serde(default)]    pub statements: Vec<StatementBalances>,}/// An account's worked-out run: each row's numbers by id, and the balance/// after the last row that happened (`None` with no anchor).#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct Run {    pub rows: BTreeMap<String, Balance>,    pub balance: Option<i64>,}/// Who said an anchor's balance, weakest first.const BY_LINE: u8 = 0;const BY_STATEMENT: u8 = 1;const BY_KNOWN: u8 = 2;/// A balance the run is anchored on: the balance after the row at `at` in/// what happened (`-1` is before its first row), said for `day`.struct Anchor<'a> {    day: &'a str,    start: bool,    by: u8,    at: isize,    balance: i64,}fn later(a: &Anchor<'_>, b: &Anchor<'_>) -> bool {    if a.day != b.day {        return a.day > b.day;    }    if a.start != b.start {        return b.start;    }    if a.by != b.by {        return a.by > b.by;    }    a.at > b.at}fn order(a: &RunRow, b: &RunRow) -> Ordering {    a.day        .cmp(&b.day)        .then_with(|| a.created_at.cmp(&b.created_at))        .then_with(|| a.line_no.unwrap_or(i64::MAX).cmp(&b.line_no.unwrap_or(i64::MAX)))        .then_with(|| a.id.cmp(&b.id))}const OWED: [&str; 2] = ["credit_card", "loan"];/// One account's run on `today`, from its rows, its known balance, its/// statements' balances and the balances its statements printed after rows/// (`printed`, by row id).pub fn work_run(account: &RunAccount, rows: &[RunRow], printed: &HashMap<String, i64>, today: &str) -> Run {    let mut past: Vec<&RunRow> = rows.iter().filter(|r| !r.expected && r.day.as_str() <= today).collect();    let mut coming: Vec<&RunRow> = rows.iter().filter(|r| r.expected || r.day.as_str() > today).collect();    past.sort_by(|a, b| order(a, b));    coming.sort_by(|a, b| order(a, b));    let run: Vec<&RunRow> = past.iter().chain(coming.iter()).copied().collect();    let raises = if account.kind.as_deref() == Some("credit_card") { LineDirection::Out } else { LineDirection::In };    let delta = |r: &RunRow| if r.direction == raises { r.amount_minor } else { -r.amount_minor };    // Where a day ends and starts in what happened: after its last row, and before its first.    let end_of = |day: &str| past.iter().rposition(|r| r.day.as_str() <= day).map_or(-1, |i| i as isize);    let start_of = |day: &str| past.iter().rposition(|r| r.day.as_str() < day).map_or(-1, |i| i as isize);    let mut anchors: Vec<Anchor<'_>> = Vec::new();    for (i, r) in past.iter().enumerate() {        if let Some(&balance) = printed.get(&r.id) {            anchors.push(Anchor { day: &r.day, start: false, by: BY_LINE, at: i as isize, balance });        }    }    for s in &account.statements {        if let (Some(day), Some(balance)) = (s.period_start.as_deref(), s.opening_balance_minor) {            anchors.push(Anchor { day, start: true, by: BY_STATEMENT, at: start_of(day), balance });        }        if let (Some(day), Some(balance)) = (s.period_end.as_deref(), s.closing_balance_minor) {            anchors.push(Anchor { day, start: false, by: BY_STATEMENT, at: end_of(day), balance });        }    }    if let (Some(balance), Some(day)) = (account.known_balance_minor, account.known_balance_on.as_deref()) {        anchors.push(Anchor { day, start: false, by: BY_KNOWN, at: end_of(day), balance });    }    let anchor = anchors.into_iter().reduce(|best, a| if later(&a, &best) { a } else { best });    let Some(Anchor { at, balance, .. }) = anchor else {        return Run { rows: run.iter().map(|r| (r.id.clone(), Balance::default())).collect(), balance: None };    };    let n = run.len();    let mut before = vec![0_i64; n];    let mut after = vec![0_i64; n];    let mut running = balance;    for i in (at + 1) as usize..n {        before[i] = running;        running += delta(run[i]);        after[i] = running;    }    running = balance;    let mut i = at;    while i >= 0 {        let k = i as usize;        after[k] = running;        running -= delta(run[k]);        before[k] = running;        i -= 1;    }    // The month a row falls in: a coming row whose day passed is still to come, so it falls in today's month.    let month = |i: usize| -> &str {        let day = if i >= past.len() && run[i].day.as_str() < today { today } else { run[i].day.as_str() };        &day[..7.min(day.len())]    };    let mut month_end: HashMap<&str, i64> = HashMap::new();    for (i, _) in run.iter().enumerate() {        month_end.insert(month(i), after[i]);    }    let owed = account.kind.as_deref().is_some_and(|k| OWED.contains(&k));    let rows = run        .iter()        .enumerate()        .map(|(i, r)| {            let a = after[i];            let state = if owed || a >= 0 {                BalanceState::Ok            } else if month_end[month(i)] >= 0 {                BalanceState::Recovers            } else {                BalanceState::Overdrawn            };            (r.id.clone(), Balance { balance_before_minor: Some(before[i]), balance_after_minor: Some(a), balance_state: Some(state) })        })        .collect();    let balance = if past.is_empty() { balance } else { after[past.len() - 1] };    Run { rows, balance: Some(balance) }}// ── the book: every account's run from the money tables ─────────────────────/// A live row of a money table as the runs read it: the object's row shape.#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]pub struct BookRow {    pub id: String,    pub created_at: String,    pub data: Map<String, Value>,}/// The live rows of every table a run reads, by table id.#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]pub struct Book {    #[serde(default)]    pub money_account: Vec<BookRow>,    #[serde(default)]    pub transaction: Vec<BookRow>,    #[serde(default)]    pub statement: Vec<BookRow>,    #[serde(default)]    pub statement_line: Vec<BookRow>,    #[serde(default)]    pub evidence: Vec<BookRow>,}/// The tables a run is written on: a copy keeps their columns the/// definitions name, so a local copy has a balance to fill.pub const RUN_TABLES: [&str; 2] = ["transaction", "money_account"];/// Every account's run: each money row's numbers (every row, empty when it/// runs on no anchored account), and each account's balance after the last/// row that happened (`None` with no anchor).#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct Worked {    pub transactions: BTreeMap<String, Balance>,    pub accounts: BTreeMap<String, Option<i64>>,}/// A text value: a non-empty string.fn text<'a>(data: &'a Map<String, Value>, key: &str) -> Option<&'a str> {    data.get(key).and_then(Value::as_str).filter(|v| !v.is_empty())}/// A whole number of minor units.fn whole(data: &Map<String, Value>, key: &str) -> Option<i64> {    const SAFE: i64 = (1 << 53) - 1;    let v = data.get(key)?;    let n = v.as_i64().or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && f.abs() <= SAFE as f64).map(|f| f as i64))?;    (n.abs() <= SAFE).then_some(n)}/// The day a stored date or moment names (`YYYY-MM-DD…`).fn day(data: &Map<String, Value>, key: &str) -> Option<String> {    let value = data.get(key)?.as_str()?;    let b = value.as_bytes();    let digits = |r: std::ops::Range<usize>| r.into_iter().all(|i| b.get(i).is_some_and(u8::is_ascii_digit));    (b.len() >= 10 && digits(0..4) && b[4] == b'-' && digits(5..7) && b[7] == b'-' && digits(8..10)).then(|| value[..10].to_owned())}/// A stored false: a bool kept as false or as 0.fn is_false(data: &Map<String, Value>, key: &str) -> bool {    matches!(data.get(key), Some(Value::Bool(false))) || data.get(key).and_then(Value::as_f64) == Some(0.0)}/// A stored true: a bool kept as true or as 1.fn is_true(data: &Map<String, Value>, key: &str) -> bool {    matches!(data.get(key), Some(Value::Bool(true))) || data.get(key).and_then(Value::as_f64) == Some(1.0)}fn binned(row: &BookRow) -> bool {    data_text_trimmed(&row.data, "trashed_at").is_some()}/// The accounts rule reads a trimmed text for the bin and the archive.fn data_text_trimmed<'a>(data: &'a Map<String, Value>, key: &str) -> Option<&'a str> {    data.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty())}/// The usual account a row with no account runs on: the one live, unarchived/// account marked `is_default`; none, or two, is no usual account.pub fn usual_account(accounts: &[BookRow]) -> Option<&str> {    let mut marked = accounts        .iter()        .filter(|a| is_true(&a.data, "is_default") && !binned(a) && data_text_trimmed(&a.data, "archived_at").is_none());    match (marked.next(), marked.next()) {        (Some(one), None) => Some(one.id.as_str()),        _ => None,    }}/// The window a money row's run is worked out in: the account it runs on —/// its own, else the usual one — and the row it settles, which it takes out/// of that row's account's run. An account's run reads only its own rows,/// its read statements, the lines and evidence those rows were booked from,/// and every row that settles another; so a write moves only the runs of/// the windows its rows were in and are in now, and those are worked out/// again whole (coordinator, 7 Nov 2026: one money write re-worked every/// account).pub fn run_window<'a>(row: &'a BookRow, usual: Option<&'a str>) -> (Option<&'a str>, Option<&'a str>) {    (text(&row.data, "account_id").or(usual), text(&row.data, "settles_transaction_id"))}struct HeldLine<'a> {    balance: Option<i64>,    line_no: Option<i64>,    transaction: Option<&'a str>,}/// Every account's run worked out on `today` from the live rows of the money tables.pub fn work_book(book: &Book, today: &str) -> Worked {    // The balances each account's read statements printed at the start and the end of their periods.    let mut statements: HashMap<&str, Vec<StatementBalances>> = HashMap::new();    for st in &book.statement {        let d = &st.data;        let Some(account) = text(d, "account_id") else { continue };        if d.get("read_status").and_then(Value::as_str) != Some("read") || text(d, "trashed_at").is_some() {            continue;        }        statements.entry(account).or_default().push(StatementBalances {            period_start: day(d, "period_start"),            opening_balance_minor: whole(d, "opening_balance_minor"),            period_end: day(d, "period_end"),            closing_balance_minor: whole(d, "closing_balance_minor"),        });    }    // The balances statements printed: by line, then by the row booked from it.    let mut lines: HashMap<&str, HeldLine<'_>> = HashMap::new();    let mut line_order: Vec<&str> = Vec::new();    for l in &book.statement_line {        if text(&l.data, "trashed_at").is_some() || text(&l.data, "ignored_reason").is_some() {            continue;        }        if lines.insert(l.id.as_str(), HeldLine { balance: whole(&l.data, "balance_after_minor"), line_no: whole(&l.data, "line_no"), transaction: text(&l.data, "transaction_id") }).is_none() {            line_order.push(l.id.as_str());        }    }    let mut line_of: HashMap<&str, &str> = HashMap::new();    for id in &line_order {        if let Some(tx) = lines[id].transaction {            line_of.insert(tx, id);        }    }    for e in &book.evidence {        if e.data.get("kind").and_then(Value::as_str) != Some("statement_line") || text(&e.data, "trashed_at").is_some() {            continue;        }        if let (Some(tx), Some(line)) = (text(&e.data, "transaction_id"), text(&e.data, "ref_id")) {            if lines.contains_key(line) && !line_of.contains_key(tx) {                line_of.insert(tx, line);            }        }    }    // An expectation an actual row settles is paid by that row: it no longer moves the balance.    let settled: HashSet<&str> = book        .transaction        .iter()        .filter(|t| t.data.get("status").and_then(Value::as_str) == Some("actual") && text(&t.data, "trashed_at").is_none())        .filter_map(|t| run_window(t, None).1)        .collect();    let usual = usual_account(&book.money_account);    let mut by_account: HashMap<&str, Vec<RunRow>> = HashMap::new();    let mut printed: HashMap<String, i64> = HashMap::new();    for t in &book.transaction {        let d = &t.data;        let status = d.get("status").and_then(Value::as_str);        let direction = d.get("direction").and_then(Value::as_str).and_then(LineDirection::parse);        let (Some(account), Some(day), Some(amount), Some(direction)) = (run_window(t, usual).0, day(d, "occurred_on"), whole(d, "amount_minor"), direction) else {            continue;        };        if text(d, "trashed_at").is_some() || is_false(d, "moves_money") || is_false(d, "amount_known") || status == Some("proposed") || settled.contains(t.id.as_str()) {            continue;        }        let held = line_of.get(t.id.as_str()).and_then(|id| lines.get(id));        if let Some(balance) = held.and_then(|l| l.balance) {            printed.insert(t.id.clone(), balance);        }        by_account.entry(account).or_default().push(RunRow {            id: t.id.clone(),            day,            created_at: t.created_at.clone(),            line_no: held.and_then(|l| l.line_no),            amount_minor: amount,            direction,            expected: status == Some("expected"),        });    }    let mut worked = Worked::default();    for a in &book.money_account {        let d = &a.data;        let account = RunAccount {            kind: text(d, "kind").map(str::to_owned),            known_balance_minor: whole(d, "known_balance_minor"),            known_balance_on: day(d, "known_balance_on"),            statements: statements.get(a.id.as_str()).cloned().unwrap_or_default(),        };        let run = work_run(&account, by_account.get(a.id.as_str()).map_or(&[][..], Vec::as_slice), &printed, today);        worked.transactions.extend(run.rows);        worked.accounts.insert(a.id.clone(), run.balance);    }    for t in &book.transaction {        worked.transactions.entry(t.id.clone()).or_default();    }    worked}#[cfg(test)]#[path = "balances_tests.rs"]mod tests;