Cotton code
386 lines · 15.7 KB · RustRaw
mod support;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::{call_tool, call_tool_raw, mint_token};fn row(h: &Harness, token: &str, status: &str, known: bool) -> Value {    let mut data = json!({"occurredOn":"2026-10-17","description":"Synthetic payment","direction":"out","currency":"EUR","movesMoney":false,"status":status,"amountKnown":known});    if known {        data["amountMinor"] = json!(1250);    }    if status == "expected" {        data["certainty"] = json!("estimate");    }    call_tool(h, token, "record_transaction", data)}/// RULE: An unknown expected amount remains absent through reads and updates, and invalid dates or fractions are refused before a money row is written.#[test]fn unknown_amounts_never_turn_into_zero_and_invalid_inputs_never_write() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic money writer");    let expected = row(&h, &token, "expected", false);    assert_eq!(expected["amountKnown"], false);    assert!(expected["amountMinor"].is_null());    let changed = call_tool(        &h,        &token,        "update_transaction",        json!({"id":expected["id"],"tag":"Synthetic tag"}),    );    assert_eq!(changed["amountKnown"], false);    assert!(changed["amountMinor"].is_null());    for mut bad in [        json!({"occurredOn":"x","description":"Synthetic invalid date","direction":"out","currency":"EUR","amountMinor":100}),        json!({"occurredOn":"2026-02-30","description":"Synthetic impossible date","direction":"out","currency":"EUR","amountMinor":100}),        json!({"occurredOn":"2026-10-17","description":"Synthetic fractional amount","direction":"out","currency":"EUR","amountMinor":12.5}),        json!({"occurredOn":"2026-10-17","description":"Synthetic invalid repeat","direction":"out","currency":"EUR","amountMinor":100,"repeat":"monthly","repeatDay":257}),    ] {        bad["movesMoney"] = json!(false);        assert!(call_tool_raw(&h, &token, "record_transaction", bad).is_error);    }    let stored = h        .with(|db| db.get("SELECT count(*) AS n FROM cotton_money_transactions", &[]))        .unwrap()        .unwrap();    assert_eq!(stored.int("n"), Some(1));}/// RULE: A bank account served by the personal kit can become the usual/// account through the generic record writer.#[test]fn usual_account_write_accepts_a_served_bank_account() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic money writer");    let account_id = synthetic_uuid("served-bank-account");    h.run(        "INSERT INTO cotton_money_accounts \         (id, workspace_id, kind, subtype, name, currency, is_default, created_at, updated_at) \         VALUES (?, ?, 'bank', 'bank', 'Synthetic served bank', 'EUR', 0, '2026-10-17', '2026-10-17')",        &[SqlValue::Text(account_id.clone()), SqlValue::Text(h.workspace_id.clone())],    );    call_tool(        &h,        &token,        "update_record",        json!({"table":"money_account","id":account_id,"patch":{"is_default":true}}),    );    let stored = h        .with(|db| db.get("SELECT is_default FROM cotton_money_accounts WHERE id = ?", &[SqlValue::Text(account_id)]))        .expect("a query")        .expect("the served account");    assert_eq!(stored.int("is_default"), Some(1));}/// RULE: Settling a forecast links the actual payment to its expected row without deleting either record or allowing a second payment to silently claim it.#[test]fn settlement_preserves_both_rows_and_rejects_a_second_payment() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic money writer");    let expected = row(&h, &token, "expected", true);    let actual = row(&h, &token, "actual", true);    let args = json!({"expectedId":expected["id"],"actualId":actual["id"]});    call_tool(&h, &token, "settle_expected", args.clone());    call_tool(&h, &token, "settle_expected", args);    let read = call_tool(&h, &token, "list_money_transactions", json!({}));    let records = read["transactions"].as_array().unwrap();    assert_eq!(records.len(), 2);    assert_eq!(        records            .iter()            .find(|record| record["id"] == actual["id"])            .unwrap()["settlesTransactionId"],        expected["id"]    );    for (id, patch) in [        (actual["id"].clone(), json!({"status":"expected","certainty":"estimate"})),        (actual["id"].clone(), json!({"direction":"in"})),        (expected["id"].clone(), json!({"status":"actual","certainty":null})),    ] {        let mut specialized = patch.clone();        specialized["id"] = id.clone();        assert!(call_tool_raw(&h, &token, "update_transaction", specialized).is_error);        assert!(call_tool_raw(&h, &token, "update_record", json!({"table":"transaction","id":id,"patch":patch})).is_error);    }    let another = row(&h, &token, "actual", true);    assert!(        call_tool_raw(            &h,            &token,            "settle_expected",            json!({"expectedId":expected["id"],"actualId":another["id"]})        )        .is_error    );}/// RULE: Settling a forecast never crosses currencies or reverses the direction of money, because either would hide the wrong future amount.#[test]fn settlement_refuses_a_different_currency() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic settlement writer");    let expected = row(&h, &token, "expected", true);    let actual = call_tool(        &h,        &token,        "record_transaction",        json!({"occurredOn":"2026-10-17","description":"Synthetic other currency","direction":"out","currency":"INR","movesMoney":false,"amountMinor":1250}),    );    assert!(        call_tool_raw(            &h,            &token,            "settle_expected",            json!({"actualId":actual["id"],"expectedId":expected["id"]})        )        .is_error    );}/// RULE: Deleting a handmade money row puts it in the Bin and preserves its amount; live money reads leave it out.#[test]fn handmade_rows_wait_in_the_bin() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic bin writer");    let made = row(&h, &token, "actual", true);    call_tool(&h, &token, "delete_transaction", json!({"id":made["id"]}));    let stored = h        .with(|db| {            db.get(                "SELECT amount_minor,trashed_at FROM cotton_money_transactions WHERE id=?",                &[rusqlite::types::Value::Text(                    made["id"].as_str().unwrap().into(),                )],            )        })        .unwrap()        .unwrap();    assert_eq!(stored.int("amount_minor"), Some(1250));    assert!(stored.text("trashed_at").is_some());    let live = call_tool(&h, &token, "list_money_transactions", json!({}));    assert!(live["transactions"].as_array().unwrap().is_empty());}/// RULE: Marking a transfer links two existing equal and opposite rows; it/// never replaces either row, because both account histories remain true.#[test]fn transfer_mark_keeps_both_rows_and_links_them_reciprocally() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic transfer writer");    let first_account = call_tool(        &h,        &token,        "create_money_account",        json!({"name":"Synthetic bank","kind":"bank","currency":"EUR"}),    );    let second_account = call_tool(        &h,        &token,        "create_money_account",        json!({"name":"Synthetic wallet","kind":"wallet","currency":"EUR"}),    );    let out = call_tool(        &h,        &token,        "record_transaction",        json!({"occurredOn":"2026-10-17","description":"Synthetic transfer out","accountId":first_account["id"],"direction":"out","currency":"EUR","amountMinor":1250}),    );    let input = call_tool(        &h,        &token,        "record_transaction",        json!({"occurredOn":"2026-10-17","description":"Synthetic transfer in","accountId":second_account["id"],"direction":"in","currency":"EUR","amountMinor":1250}),    );    call_tool(&h, &token, "update_transaction", json!({"id":out["id"],"movesMoney":false}));    assert!(call_tool_raw(&h, &token, "mark_transfer", json!({"firstId":out["id"],"secondId":input["id"]})).is_error);    call_tool(&h, &token, "update_transaction", json!({"id":out["id"],"movesMoney":true}));    call_tool(        &h,        &token,        "mark_transfer",        json!({"firstId":out["id"],"secondId":input["id"]}),    );    for patch in [json!({"amountMinor":1500}), json!({"status":"expected","certainty":"estimate"}), json!({"movesMoney":false})] {        let mut patch = patch;        patch["id"] = out["id"].clone();        assert!(call_tool_raw(&h, &token, "update_transaction", patch).is_error);    }    let rows = call_tool(&h, &token, "list_money_transactions", json!({}))["transactions"]        .as_array()        .unwrap()        .clone();    assert_eq!(rows.len(), 2);    assert_eq!(        rows.iter().find(|row| row["id"] == out["id"]).unwrap()["transferOf"],        input["id"]    );    assert_eq!(        rows.iter().find(|row| row["id"] == input["id"]).unwrap()["transferOf"],        out["id"]    );}/// RULE: Binning a mistaken actual payment reopens its expectation, so a replacement actual row can settle it without reviving the mistaken payment.#[test]fn a_binned_payment_does_not_block_a_replacement_settlement() {    let mut h = Harness::new();    let token = mint_token(        &mut h,        &["read", "write"],        "Synthetic settlement correction",    );    let expected = row(&h, &token, "expected", true);    let mistaken = row(&h, &token, "actual", true);    call_tool(        &h,        &token,        "settle_expected",        json!({"expectedId":expected["id"],"actualId":mistaken["id"]}),    );    call_tool(        &h,        &token,        "delete_transaction",        json!({"id":mistaken["id"]}),    );    let replacement = row(&h, &token, "actual", true);    call_tool(        &h,        &token,        "settle_expected",        json!({"expectedId":expected["id"],"actualId":replacement["id"]}),    );    let rows = call_tool(&h, &token, "list_money_transactions", json!({}));    assert_eq!(rows["transactions"].as_array().unwrap().len(), 2);}/// RULE: A person filter applies before the Money page limit, so a newer unrelated payment cannot hide the person's payment.#[test]fn person_filter_is_applied_before_paging() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic person filter");    let person = call_tool(        &h,        &token,        "create_person",        json!({"fullName":"Synthetic row person"}),    );    let made = call_tool(        &h,        &token,        "record_transaction",        json!({"occurredOn":"2026-10-17","description":"Synthetic linked payment","direction":"out","currency":"EUR","movesMoney":false,"amountMinor":1250,"personId":person["id"]}),    );    call_tool(        &h,        &token,        "record_transaction",        json!({"occurredOn":"2026-10-18","description":"Synthetic unrelated payment","direction":"out","currency":"EUR","movesMoney":false,"amountMinor":1250}),    );    let listed = call_tool(        &h,        &token,        "list_money_transactions",        json!({"personId":person["id"],"limit":1}),    );    assert_eq!(listed["transactions"][0]["id"], made["id"]);}/// RULE: Money preserves every accepted minor unit, and refuses amounts outside the canonical receipt integer range before writing so a numeric reader never rounds them.#[test]fn a_money_rows_amount_never_rounds_through_a_float() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic exact amount");    let amount = 9_007_199_254_740_991i64;    let made = call_tool(        &h,        &token,        "record_transaction",        json!({"occurredOn":"2026-10-17","description":"Synthetic exact payment","direction":"out","currency":"EUR","movesMoney":false,"amountMinor":amount}),    );    assert_eq!(made["amountMinor"], amount);    let listed = call_tool(&h, &token, "list_money_transactions", json!({}));    assert_eq!(listed["transactions"][0]["amountMinor"], amount);    let refused = call_tool_raw(        &h,        &token,        "record_transaction",        json!({"occurredOn":"2026-10-17","description":"Synthetic oversized payment","direction":"out","currency":"EUR","movesMoney":false,"amountMinor":9_007_199_254_740_993i64}),    );    assert!(refused.is_error, "an unsafe receipt amount must be refused");    let listed = call_tool(&h, &token, "list_money_transactions", json!({}));    let rows = listed["transactions"].as_array().unwrap();    assert_eq!(rows.len(), 1, "refusal must leave no partial money row");    assert_eq!(rows[0]["amountMinor"], amount);}/// RULE: A loan repayment reduces both bank cash and the amount still owed; its two out rows can be marked as one transfer because a loan uses bank arithmetic on an owed balance.#[test]fn loan_repayments_pair_without_counting_the_payment_twice() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic loan transfer");    let bank = call_tool(        &h,        &token,        "create_money_account",        json!({"name":"Synthetic paying bank","kind":"bank","currency":"EUR"}),    );    let loan = call_tool(        &h,        &token,        "create_money_account",        json!({"name":"Synthetic owed loan","kind":"loan","currency":"EUR"}),    );    let payment = call_tool(        &h,        &token,        "record_transaction",        json!({"occurredOn":"2026-10-17","description":"Synthetic repayment from bank","accountId":bank["id"],"amountMinor":100,"direction":"out","currency":"EUR"}),    );    let owed = call_tool(        &h,        &token,        "record_transaction",        json!({"occurredOn":"2026-10-17","description":"Synthetic owed amount reduced","accountId":loan["id"],"amountMinor":100,"direction":"out","currency":"EUR"}),    );    call_tool(        &h,        &token,        "mark_transfer",        json!({"firstId":payment["id"],"secondId":owed["id"]}),    );    let listed = call_tool(&h, &token, "list_money_transactions", json!({}));    let rows = listed["transactions"].as_array().unwrap();    assert_eq!(        rows.iter().find(|row| row["id"] == payment["id"]).unwrap()["transferOf"],        owed["id"]    );    assert_eq!(        rows.iter().find(|row| row["id"] == owed["id"]).unwrap()["transferOf"],        payment["id"]    );}/// RULE (6 Nov 2026): a row held with no period (`for_period` is the/// column's empty none, as an import or a booked line leaves it) takes an/// update of its date: the empty period is merged back, never refused as a/// month, and stays empty. (When on a phone wrote nothing for this.)#[test]fn a_row_with_no_period_takes_a_new_date() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic money writer");    let expected = row(&h, &token, "expected", true);    let id = expected["id"].as_str().expect("an id").to_string();    let params = vec![SqlValue::Text(id.clone())];    h.with(|db| db.run("UPDATE cotton_money_transactions SET for_period = '' WHERE id = ?1", &params)).expect("the period empties");    let moved = call_tool(&h, &token, "update_transaction", json!({"id": id, "occurredOn": "2026-10-20"}));    assert_eq!(moved["occurredOn"], "2026-10-20");    let stored = h        .with(|db| db.get("SELECT for_period FROM cotton_money_transactions WHERE id = ?1", &params))        .unwrap()        .unwrap();    assert_eq!(stored.text("for_period").as_deref(), Some(""), "no period is made up for it");}