Cotton code
265 lines · 17.1 KB · RustRaw
//! A view that names its own card (`view.card`, sent with the view since//! e4a5c851b) is dealt by `shell.deck` as a deck of THAT card: each card wears//! the view's face, says its title, and fills the other places its fields//! name wherever the row holds a value. One test per such view in the//! personal kit, each over synthetic rows the view reads, asked for the way//! the phone asks (`shell.deck {table, view: "<tool>/<id>"}`).//!//! Every value is invented ([nothing-real-ever-goes-in-cotton-s-public-tree]).use crate::handle::CottonHandle;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};const TODAY: &str = "2026-11-06";const AT: &str = "2026-11-02T09:00:00.000Z";/// A fresh phone opened as Cotton, started local.fn phone() -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let manifest: Value = serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("a manifest");    let handle = CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(manifest),    })    .expect("an open core");    crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started");    (dir, handle)}fn make(handle: &CottonHandle, table: &str, data: Value) -> String {    let made = crate::methods::dispatch(handle, "records.create", &json!({"table": table, "data": data, "timezone": "Asia/Kolkata"}))        .unwrap_or_else(|error| panic!("a {table} is made: {error:?}"));    made["id"].as_str().or_else(|| made["record"]["id"].as_str()).unwrap_or_else(|| panic!("a made id: {made}")).to_string()}/// A row written straight into the phone's file — a table no record is/// written into by hand (an imported document, a message, a statement).fn exec(handle: &CottonHandle, sql: &str, params: Vec<SqlValue>) {    handle        .client()        .with_writer(|file| {            file.driver.run(sql, &params).map_err(|error| error.to_string())?;            crate::fixture::receipted(file.driver, sql);            Ok(())        })        .expect("the statement");}fn workspace(handle: &CottonHandle) -> String {    handle.client().with_writer(|file| Ok(file.workspace_id.to_string())).expect("the workspace id")}/// A media key under this file's own prefix, as every database's bytes are.fn media_key(handle: &CottonHandle, name: &str) -> String {    handle        .client()        .with_writer(|file| {            let identity = cotton_store::file_identity::read_file_identity(file.driver).map_err(|error| error.to_string())?;            Ok(identity.map_or_else(|| name.to_string(), |identity| format!("{}/{name}", identity.id())))        })        .expect("the file's id")}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// The view's deck, as the phone asks for it.fn deck(handle: &CottonHandle, table: &str, view: &str) -> Value {    crate::methods::dispatch(handle, "shell.deck", &json!({"table": table, "view": view, "timezone": "Asia/Kolkata", "today": TODAY}))        .unwrap_or_else(|error| panic!("{view}'s deck reads: {error:?}"))}/// The view's own card, as its tool's manifest names it.fn view_card(tool: &str, view: &str) -> Value {    let path = cotton_store::manifest_dir().join(format!("../cotton-core/kits/personal/tools/{tool}/manifest.json"));    let manifest: Value = serde_json::from_str(&std::fs::read_to_string(path).expect("the tool's manifest")).expect("it reads");    manifest["views"].as_array().and_then(|views| views.iter().find(|found| found["id"] == view)).map(|found| found["card"].clone())        .filter(Value::is_object).unwrap_or_else(|| panic!("{tool}/{view} names its own card"))}fn card<'a>(answer: &'a Value, id: &str) -> &'a Value {    answer["cards"].as_array().and_then(|cards| cards.iter().find(|card| card["id"] == id)).unwrap_or_else(|| panic!("{id} is dealt: {answer}"))}fn said(value: &Value) -> bool {    match value {        Value::Null => false,        Value::String(text) => !text.trim().is_empty(),        Value::Array(items) => !items.is_empty(),        Value::Object(map) => !map.is_empty(),        _ => true,    }}/// Every dealt card wears the view's face and says its title; each place the/// view's card names over a column says something on `filled`, whose row/// holds a value there.fn wears_the_views_card(answer: &Value, tool: &str, view: &str, filled: &[(&str, &[&str])]) {    let own = view_card(tool, view);    let face = own["face"].as_str().expect("the view's face");    let cards = answer["cards"].as_array().unwrap_or_else(|| panic!("{tool}/{view} deals cards: {answer}"));    assert!(!cards.is_empty(), "{tool}/{view} deals its rows: {answer}");    assert_eq!(answer["count"].as_u64(), Some(cards.len() as u64), "{tool}/{view} counts what it deals: {answer}");    for dealt in cards {        assert_eq!(dealt["face"], face, "{tool}/{view} deals its own card: {dealt}");        assert!(dealt["slots"]["title"].as_str().is_some_and(|title| !title.trim().is_empty()), "{tool}/{view}'s card says its title: {dealt}");    }    for (id, places) in filled {        let dealt = card(answer, id);        for place in *places {            assert!(said(&dealt["slots"][*place]), "{tool}/{view}'s card says its {place}: {dealt}");        }    }}// RULE (owner, 6 Nov 2026): Birthdays' Everyone deals every person with a birthday — the phone's own month and day, or the date the object keeps whole on a signed-in copy — on the birthday card: their name, city, the day and the age they turn.#[test]fn birthdays_everyone_deals_the_birthday_card() {    use cotton_store::schema::package_shape::{add_served, served_column};    let (_dir, handle) = phone();    let asha = make(&handle, "person", json!({"full_name": "Invented Asha", "city": "Invented Town", "birthday": "1991-11-09", "language": "en"}));    let ravi = make(&handle, "person", json!({"full_name": "Invented Ravi", "birthday": "--03-02", "language": "en"}));    make(&handle, "person", json!({"full_name": "Invented Nobirthday", "language": "en"}));    // A signed-in copy: the object keeps the birthday whole, the pull fills    // the copy's served `birthday`, the month, day and year stay empty.    let bela = make(&handle, "person", json!({"full_name": "Invented Bela", "city": "Invented City", "language": "en"}));    handle        .client()        .with_writer(|file| {            add_served(file.driver, "cotton_people", &[served_column("birthday", "date", false).map_err(|error| error.to_string())?])                .map_err(|error| error.to_string())?;            file.driver.run("UPDATE cotton_people SET birthday = '1988-11-20' WHERE id = ?", &[text(&bela)]).map_err(|error| error.to_string())?;            Ok(())        })        .expect("the copy keeps the object's birthday");    let answer = deck(&handle, "person", "birthdays/everyone");    wears_the_views_card(&answer, "birthdays", "everyone", &[(&asha, &["subtitle", "date", "turns"]), (&ravi, &["date"]), (&bela, &["subtitle", "date", "turns"])]);    let ids: Vec<&str> = answer["cards"].as_array().unwrap().iter().filter_map(|card| card["id"].as_str()).collect();    assert_eq!(ids, [asha.as_str(), bela.as_str(), ravi.as_str()], "soonest birthday first, none without one: {answer}");}// RULE (owner, 6 Nov 2026): Birthday wishes deals the people the owner sends wishes to (the switch on a person, never worked out) on the birthday card, its switch on.#[test]fn birthdays_wishes_deals_the_birthday_card() {    let (_dir, handle) = phone();    let asha = make(&handle, "person", json!({"full_name": "Invented Asha", "city": "Invented Town", "birthday": "1991-11-09", "language": "en"}));    make(&handle, "person", json!({"full_name": "Invented Ravi", "birthday": "1990-11-08", "language": "en"}));    crate::methods::dispatch(&handle, "records.update", &json!({"table": "person", "id": asha, "patch": {"own_birthdays__wish": true}}))        .expect("the switch is on");    let answer = deck(&handle, "person", "birthdays/wishes");    wears_the_views_card(&answer, "birthdays", "wishes", &[(&asha, &["subtitle", "date", "turns"])]);    assert_eq!(answer["count"], 1, "only the switched-on person, a birthday near or not: {answer}");    assert_eq!(card(&answer, &asha)["slots"]["wishes"], json!(true), "{answer}");}// RULE: Artifacts' All deals the saved pages on the artifact card: the title, the site it is from and when.#[test]#[ignore = "TABLE DROP 1: the artifacts tool is retired (GONE_TOOLS) and the Cotton manifest no longer names it (RUST GREEN 2)"]fn artifacts_all_deals_the_artifact_card() {    let (_dir, handle) = phone();    let page = make(&handle, "page", json!({"url": "https://invented.example/a-slow-morning", "title": "An Invented Slow Morning"}));    let answer = deck(&handle, "page", "artifacts/all");    wears_the_views_card(&answer, "artifacts", "all", &[(&page, &["source", "date"])]);}// RULE: Artifacts' Made deals the html documents made, on the artifact card: the title, its reading and when.#[test]#[ignore = "TABLE DROP 1: the artifacts tool is retired (GONE_TOOLS) and the Cotton manifest no longer names it (RUST GREEN 2)"]fn artifacts_made_deals_the_artifact_card() {    let (_dir, handle) = phone();    let workspace = workspace(&handle);    let insert = "INSERT INTO cotton_documents (id, workspace_id, title, original_name, mime, byte_size, sha256, storage_path, status, summary, created_at, updated_at) \                  VALUES (?, ?, ?, ?, ?, 120, ?, ?, 'ready', ?, ?, ?)";    exec(&handle, insert, vec![text("invented-doc-html"), text(&workspace), text("An Invented Chart"), text("chart.html"), text("text/html"),        text(&"a".repeat(64)), text(&media_key(&handle, "documents/invented-chart.html")), text("A chart of invented numbers."), text(AT), text(AT)]);    exec(&handle, insert, vec![text("invented-doc-pdf"), text(&workspace), text("An Invented Bill"), text("bill.pdf"), text("application/pdf"),        text(&"b".repeat(64)), text(&media_key(&handle, "documents/invented-bill.pdf")), text("A bill."), text(AT), text(AT)]);    let answer = deck(&handle, "document", "artifacts/made");    wears_the_views_card(&answer, "artifacts", "made", &[("invented-doc-html", &["body", "date"])]);    assert_eq!(answer["count"], 1, "only the html: {answer}");}// RULE: Messages' Starred deals the starred messages on the message card: who sent it, what it says, when and over what.#[test]fn messages_starred_deals_the_message_card() {    let (_dir, handle) = phone();    let workspace = workspace(&handle);    exec(&handle, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) VALUES (?, ?, 'dm', ?, ?, ?)",        vec![text("invented-thread"), text(&workspace), text("Invented Asha"), text(AT), text(AT)]);    let message = "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, starred_at) \                   VALUES (?, 'invented-thread', ?, ?, 'cotton', 'live', ?, ?, ?, ?)";    exec(&handle, message, vec![text("invented-starred-in"), text(&workspace), text("in"), text("See you at the invented cafe"), text(AT), text(AT), text(AT)]);    exec(&handle, message, vec![text("invented-starred-out"), text(&workspace), text("out"), text("I'll bring the invented book"), text(AT), text(AT), text(AT)]);    exec(&handle, message, vec![text("invented-plain"), text(&workspace), text("in"), text("An unstarred invented line"), text(AT), text(AT), SqlValue::Null]);    let answer = deck(&handle, "message", "messages/starred");    wears_the_views_card(&answer, "messages", "starred", &[("invented-starred-in", &["body", "date", "source"]), ("invented-starred-out", &["body", "date", "source"])]);    assert_eq!(answer["count"], 2, "only the starred: {answer}");}// RULE: Money's Statements deals each statement on its own plain card: the account and its period as the title, the account, the day it ends and its figures.#[test]#[ignore = "TABLE DROP 1: the money tool is retired (GONE_TOOLS) and the Cotton manifest no longer names it (RUST GREEN 2)"]fn money_statements_deals_the_statement_card() {    let (_dir, handle) = phone();    let workspace = workspace(&handle);    // An account is opened by its own act and a statement read from its file: both written as those leave them.    let account = "invented-bank";    exec(&handle, "INSERT INTO cotton_money_accounts (id, workspace_id, kind, subtype, name, currency, created_at, updated_at) VALUES (?, ?, 'asset', 'bank', 'Invented Bank', 'INR', ?, ?)",        vec![text(account), text(&workspace), text(AT), text(AT)]);    exec(&handle, "INSERT INTO cotton_documents (id, workspace_id, title, original_name, mime, byte_size, sha256, storage_path, status, created_at, updated_at) \                   VALUES ('invented-statement-file', ?, 'Invented statement', 'statement.pdf', 'application/pdf', 120, ?, ?, 'ready', ?, ?)",        vec![text(&workspace), text(&"c".repeat(64)), text(&media_key(&handle, "documents/invented-statement.pdf")), text(AT), text(AT)]);    exec(&handle, "INSERT INTO cotton_money_statements (id, workspace_id, document_id, account_id, kind, period_start, period_end, opening_balance_minor, closing_balance_minor, currency, read_status, line_count, created_at, updated_at) \                   VALUES ('invented-statement', ?, 'invented-statement-file', ?, 'bank', '2026-10-01', '2026-10-31', 1000000, 950000, 'INR', 'read', 12, ?, ?)",        vec![text(&workspace), text(account), text(AT), text(AT)]);    let answer = deck(&handle, "statement", "money/statements");    wears_the_views_card(&answer, "money", "statements", &[("invented-statement", &["account", "date", "facts"])]);}// RULE: Money's Owed deals each money row between you and a person on the receipt: the person, what it was, the amount, which way and when.#[test]#[ignore = "TABLE DROP 1: the money tool is retired (GONE_TOOLS) and the Cotton manifest no longer names it (RUST GREEN 2)"]fn money_owed_deals_the_receipt() {    let (_dir, handle) = phone();    let orrel = make(&handle, "person", json!({"full_name": "Invented Orrel", "language": "en"}));    let dinner = make(&handle, "transaction", json!({"description": "Invented dinner", "occurred_on": "2026-11-01", "amount_minor": 150000, "currency": "INR", "direction": "in", "status": "actual", "moves_money": false, "counterparty_person_id": orrel}));    let answer = deck(&handle, "money_owed", "money/owed");    wears_the_views_card(&answer, "money", "owed", &[(&dinner, &["people", "amount", "state", "date"])]);}// RULE: Money's With a person — a person's part of Owed, never a deck of its own (`partition`), read for one person as their page reads it — deals each row between you on the receipt, each with the balance after it.#[test]#[ignore = "TABLE DROP 1: the money tool is retired (GONE_TOOLS) and the Cotton manifest no longer names it (RUST GREEN 2)"]fn money_with_person_deals_the_receipt() {    let (_dir, handle) = phone();    let orrel = make(&handle, "person", json!({"full_name": "Invented Orrel", "language": "en"}));    let dinner = make(&handle, "transaction", json!({"description": "Invented dinner", "occurred_on": "2026-11-01", "amount_minor": 150000, "currency": "INR", "direction": "in", "status": "actual", "moves_money": false, "counterparty_person_id": orrel}));    let read = crate::methods::dispatch(&handle, "records.list", &json!({"table": "money_owed", "view": "money/with_person", "where": {"counterparty_person_id": orrel}, "timezone": "Asia/Kolkata", "today": TODAY}))        .expect("a person's money reads");    let own = view_card("money", "with_person");    let row = read["records"].as_array().and_then(|rows| rows.iter().find(|row| row["id"] == json!(dinner))).unwrap_or_else(|| panic!("the dinner: {read}"));    let dealt = &row["data"]["@card"];    assert_eq!(dealt["face"], own["face"], "{read}");    for place in ["title", "amount", "state", "date", "facts"] {        assert!(said(&dealt["fields"][place]), "With a person's card says its {place}: {dealt}");    }}// RULE: Money's By person deals one group card a person, their name its title and what is between you in its amount.#[test]#[ignore = "TABLE DROP 1: the money tool is retired (GONE_TOOLS) and the Cotton manifest no longer names it (RUST GREEN 2)"]fn money_by_person_deals_the_group_card() {    let (_dir, handle) = phone();    let orrel = make(&handle, "person", json!({"full_name": "Invented Orrel", "language": "en"}));    make(&handle, "transaction", json!({"description": "Invented dinner", "occurred_on": "2026-11-01", "amount_minor": 150000, "currency": "INR", "direction": "in", "status": "actual", "moves_money": false, "counterparty_person_id": orrel}));    let answer = deck(&handle, "money_owed", "money/by_person");    wears_the_views_card(&answer, "money", "by_person", &[]);    assert_eq!(answer["cards"][0]["slots"]["title"], "Invented Orrel", "{answer}");}