237 lines · 13.1 KB · RustRaw
//! The phone's money run over a file: it fills what the object has not//! stamped and leaves what it has. Synthetic rows only.use super::*;use cotton_store::meta::Meta;use cotton_store::schema::package_shape::{add_served, served_column};use cotton_store::test_template::create_workspace_in_memory_for_test;const WS: &str = "22222222-2222-4222-8222-222222222222";const AT: &str = "2026-10-05T00:00:00.000Z";fn text(value: &str) -> SqlValue { SqlValue::Text(value.to_owned())}fn file() -> Driver { let db = create_workspace_in_memory_for_test(&Meta { workspace_id: WS.to_string(), owner_id: "owner-1".to_string(), device_id: "device:test".to_string(), last_server_seq: 0, last_hlc: None, }) .expect("a file"); db.run("INSERT OR IGNORE INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?, 'Home', 'owner-1', ?)", &[text(WS), text(AT)]) .expect("a workspace"); db}/// The columns a copy keeps for the kit's money definitions.fn keep_columns(db: &Driver) { let row = ["balance_before_minor", "balance_after_minor"].map(|key| served_column(key, "amount", false).unwrap()); let state = served_column("balance_state", "choice", false).unwrap(); add_served(db, TRANSACTIONS, &[row[0].clone(), row[1].clone(), state]).expect("the row's columns"); let account = [ served_column("balance_minor", "amount", false).unwrap(), served_column("balance_as_of", "date", false).unwrap(), served_column("known_balance_minor", "amount", false).unwrap(), served_column("known_balance_on", "date", false).unwrap(), ]; add_served(db, ACCOUNTS, &account).expect("the account's columns");}fn account(db: &Driver, id: &str, known: i64) { db.run( "INSERT INTO cotton_money_accounts (id, workspace_id, kind, subtype, name, currency, known_balance_minor, known_balance_on, created_at, updated_at) \ VALUES (?, ?, 'bank', 'bank', 'Synthetic bank', 'INR', ?, '2026-01-01', ?, ?)", &[text(id), text(WS), SqlValue::Integer(known), text(AT), text(AT)], ) .expect("an account");}fn movement(db: &Driver, id: &str, account: &str, day: &str, amount: i64, direction: &str) { db.run( "INSERT INTO cotton_money_transactions (id, workspace_id, occurred_on, description, account_id, amount_minor, direction, currency, status, created_at, updated_at) \ VALUES (?, ?, ?, 'Synthetic movement', ?, ?, ?, 'INR', 'actual', ?, ?)", &[text(id), text(WS), text(day), text(account), SqlValue::Integer(amount), text(direction), text(AT), text(AT)], ) .expect("a money row");}fn numbers(db: &Driver, id: &str) -> (Option<i64>, Option<i64>, Option<String>) { let row = db .get("SELECT balance_before_minor, balance_after_minor, balance_state FROM cotton_money_transactions WHERE id = ?", &[text(id)]) .unwrap() .expect("the row"); (row.int("balance_before_minor"), row.int("balance_after_minor"), row.text("balance_state").map(str::to_owned))}fn balance(db: &Driver, id: &str) -> (Option<i64>, Option<String>) { let row = db.get("SELECT balance_minor, balance_as_of FROM cotton_money_accounts WHERE id = ?", &[text(id)]).unwrap().expect("the account"); (row.int("balance_minor"), row.text("balance_as_of").map(str::to_owned))}/// The object wrote `id` of `table`: its receipt, as a pull leaves it.fn stamped_by_the_object(db: &Driver, table: &str, id: &str) { db.run( "INSERT INTO _writes (tbl, row_id, hlc, author, held) VALUES (?, ?, '0000000000001:0000:object', 'object', 0)", &[text(table), text(id)], ) .expect("the object's receipt");}/// RULE (coordinator, 2 Nov 2026): the phone fills the balances of the rows the object has not stamped, by the object's own rule, and writes nothing the object owns: a row or an account the object wrote keeps the object's figures.#[test]fn the_run_fills_the_rows_the_object_has_not_stamped() { let db = file(); keep_columns(&db); account(&db, "acct-local", 500000); movement(&db, "tx-local-1", "acct-local", "2026-01-05", 120000, "out"); movement(&db, "tx-local-2", "acct-local", "2026-01-09", 20000, "in"); account(&db, "acct-object", 1000); movement(&db, "tx-object", "acct-object", "2026-01-05", 100, "out"); db.run("UPDATE cotton_money_transactions SET balance_before_minor = 7, balance_after_minor = 8, balance_state = 'ok' WHERE id = 'tx-object'", &[]).unwrap(); db.run("UPDATE cotton_money_accounts SET balance_minor = 9, balance_as_of = '2026-10-01' WHERE id = 'acct-object'", &[]).unwrap(); stamped_by_the_object(&db, TRANSACTIONS, "tx-object"); stamped_by_the_object(&db, ACCOUNTS, "acct-object"); refill(&db, "2026-11-03").expect("the run"); assert_eq!(numbers(&db, "tx-local-1"), (Some(500000), Some(380000), Some("ok".into()))); assert_eq!(numbers(&db, "tx-local-2"), (Some(380000), Some(400000), Some("ok".into()))); assert_eq!(balance(&db, "acct-local"), (Some(400000), Some("2026-11-03".into()))); assert_eq!(numbers(&db, "tx-object"), (Some(7), Some(8), Some("ok".into())), "the object's figures win"); assert_eq!(balance(&db, "acct-object"), (Some(9), Some("2026-10-01".into())), "the object's figures win"); // A row binned leaves the run, its numbers emptied, and the run fills again. db.run("UPDATE cotton_money_transactions SET trashed_at = ? WHERE id = 'tx-local-1'", &[text(AT)]).unwrap(); refill(&db, "2026-11-03").expect("the run"); assert_eq!(numbers(&db, "tx-local-1"), (None, None, None)); assert_eq!(numbers(&db, "tx-local-2"), (Some(500000), Some(520000), Some("ok".into()))); assert_eq!(balance(&db, "acct-local"), (Some(520000), Some("2026-11-03".into())));}/// RULE (e2e rulings R3, 16 Nov 2026): when the copy's money row is sealed the object works no run, so the phone fills every row and account, those the object wrote too.#[test]fn a_sealed_money_row_is_figured_on_the_phone_alone() { let db = file(); keep_columns(&db); account(&db, "acct-object", 1000); movement(&db, "tx-object", "acct-object", "2026-01-05", 100, "out"); db.run("UPDATE cotton_money_transactions SET balance_before_minor = 7, balance_after_minor = 8, balance_state = 'ok' WHERE id = 'tx-object'", &[]).unwrap(); stamped_by_the_object(&db, TRANSACTIONS, "tx-object"); stamped_by_the_object(&db, ACCOUNTS, "acct-object"); db.run( &format!("INSERT INTO {} (id, workspace_id, definition, builtin, created_at, updated_at) VALUES ('transaction', ?, ?, 0, ?, ?)", crate::definitions::TABLE_DEFINITIONS), &[text(WS), text(r#"{"id":"transaction","seal":{"clear":["occurred_on","account_id"]}}"#), text(AT), text(AT)], ) .expect("the sealed definition"); refill(&db, "2026-11-03").expect("the run"); assert_eq!(numbers(&db, "tx-object"), (Some(1000), Some(900), Some("ok".into())), "the phone's figures: the object works none"); assert_eq!(balance(&db, "acct-object"), (Some(900), Some("2026-11-03".into())));}/// RULE: a copy that keeps no balance column is filled with nothing, and the pass does not fail its fold.#[test]fn a_copy_with_no_balance_column_is_left_as_it_is() { let db = file(); db.run( "INSERT INTO cotton_money_accounts (id, workspace_id, kind, subtype, name, currency, created_at, updated_at) VALUES ('a', ?, 'bank', 'bank', 'Synthetic', 'INR', ?, ?)", &[text(WS), text(AT), text(AT)], ) .unwrap(); movement(&db, "t", "a", "2026-01-05", 100, "out"); refill(&db, "2026-11-03").expect("nothing to fill, and no failure"); after_fold(&db, &[(TRANSACTIONS.to_owned(), "t".to_owned())]).expect("nothing to fill, and no failure");}/// RULE: today is the workspace's day: the zone it names, UTC when it names none.#[test]fn today_is_the_workspaces_day() { let db = file(); let late = crate::clock::FixedClock::new(chrono::DateTime::parse_from_rfc3339("2026-11-02T20:00:00Z").unwrap().with_timezone(&chrono::Utc)); assert_eq!(today(&db, &late).unwrap(), "2026-11-02"); db.run("INSERT INTO cotton_news_settings (workspace_id, timezone, created_at, updated_at) VALUES (?, 'Asia/Kolkata', ?, ?)", &[text(WS), text(AT), text(AT)]) .unwrap(); assert_eq!(today(&db, &late).unwrap(), "2026-11-03");}/// Every filled number, rows and accounts, to compare two ways of arriving at them.fn filled(db: &Driver) -> Vec<String> { let mut out: Vec<String> = db .all("SELECT id, balance_before_minor, balance_after_minor, balance_state FROM cotton_money_transactions ORDER BY id", &[]) .unwrap() .iter() .map(|row| format!("{:?}", (row.text("id"), row.int("balance_before_minor"), row.int("balance_after_minor"), row.text("balance_state")))) .collect(); out.extend(db.all("SELECT id, balance_minor, balance_as_of FROM cotton_money_accounts ORDER BY id", &[]).unwrap().iter().map(|row| format!("{:?}", (row.text("id"), row.int("balance_minor"), row.text("balance_as_of"))))); out}/// RULE (coordinator, 7 Nov 2026: every money write re-worked every account/// over the whole book): a write works out only the runs it moved — the/// accounts its rows ran on and settled into, before and now — and a random/// sequence of single writes (amounts, days, accounts moved and emptied onto/// the usual one, expectations, bins, settlements, rows that move no money,/// rows booked from a statement line that printed a balance) ends with the/// very numbers a whole refill gives.#[test]fn single_money_writes_fill_what_a_whole_refill_fills() { let db = file(); keep_columns(&db); db.exec("PRAGMA foreign_keys = OFF").unwrap(); for (id, known) in [("a-1", 100_000), ("a-2", 50_000), ("a-3", -2_000)] { account(&db, id, known); } db.run("UPDATE cotton_money_accounts SET is_default = 1 WHERE id = 'a-2'", &[]).unwrap(); db.run( "INSERT INTO cotton_money_statements (id, workspace_id, document_id, kind, currency, read_status, account_id, period_start, period_end, opening_balance_minor, closing_balance_minor, created_at, updated_at) \ VALUES ('s-1', ?, 'd-1', 'bank', 'INR', 'read', 'a-1', '2026-09-01', '2026-09-30', 90000, 95000, ?, ?)", &[text(WS), text(AT), text(AT)], ).unwrap(); let mut seed: u64 = 42; let mut roll = |n: u64| { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) % n }; let mut made = 0; for step in 0..300 { let id = if made < 20 || roll(4) == 0 { made += 1; let id = format!("t-{made:03}"); movement(&db, &id, &format!("a-{}", 1 + roll(3)), &format!("2026-{:02}-{:02}", 9 + roll(3), 1 + roll(28)), 100 + roll(9000) as i64, if roll(2) == 0 { "in" } else { "out" }); if made % 7 == 0 { db.run( "INSERT INTO cotton_money_statement_lines (id, workspace_id, statement_id, page, line_no, posted_on, text, amount_minor, direction, fingerprint, balance_after_minor, created_at) \ VALUES (?, ?, 's-1', 1, ?, '2026-09-15', 'Synthetic line', 100, 'in', ?, ?, ?)", &[text(&format!("l-{made}")), text(WS), SqlValue::Integer(made), text(&format!("f-{made}")), SqlValue::Integer(80_000 + made), text(AT)], ).unwrap(); db.run( "INSERT INTO cotton_money_evidence (id, workspace_id, transaction_id, kind, ref_id, excerpt, attached_by, created_at) VALUES (?, ?, ?, 'statement_line', ?, 'Synthetic', 'import', ?)", &[text(&format!("e-{made}")), text(WS), text(&id), text(&format!("l-{made}")), text(AT)], ).unwrap(); } id } else { let id = format!("t-{:03}", 1 + roll(made as u64)); let (column, value) = match roll(9) { 0 => ("amount_minor", SqlValue::Integer(100 + roll(9000) as i64)), 1 => ("occurred_on", text(&format!("2026-{:02}-{:02}", 9 + roll(3), 1 + roll(28)))), 2 => ("account_id", text(&format!("a-{}", 1 + roll(3)))), 3 => ("account_id", SqlValue::Null), 4 => ("status", text(["actual", "expected", "actual"][roll(3) as usize])), 5 => ("trashed_at", if roll(3) == 0 { text(AT) } else { SqlValue::Null }), 6 => ("settles_transaction_id", if roll(2) == 0 { text(&format!("t-{:03}", 1 + roll(made as u64))) } else { SqlValue::Null }), 7 => ("moves_money", SqlValue::Integer(i64::from(roll(4) != 0))), _ => ("direction", text(if roll(2) == 0 { "in" } else { "out" })), }; db.run(&format!("UPDATE cotton_money_transactions SET {column} = ?, updated_at = ? WHERE id = ?"), &[value, text(&format!("step {step}")), text(&id)]).unwrap(); id }; after_fold(&db, &[(TRANSACTIONS.to_owned(), id.clone())]).unwrap(); // After every write, not only at the end: a later write to a stale // account would work it out again and hide the miss. let stepped = filled(&db); refill(&db, &today(&db, &SystemClock).unwrap()).unwrap(); assert_eq!(filled(&db), stepped, "step {step}, {id}"); } assert!(filled(&db).iter().filter(|row| row.contains("Some(")).count() > 20, "the runs are anchored");}