Cotton code
177 lines · 8.8 KB · RustRaw
//! This Device's Add sample records / Remove sample records//! (`cotton_tools::mcp::handlers::tables::samples`).//!//! RULE: an add fills every pace band a todo deck draws (late, today, soon,//! upcoming, someday, done) and puts calendar events today — one already//! begun — and over the next two weeks, dated from the clock at the add; a//! remove bins exactly the records the add marked, including one edited//! since, and leaves the owner's own record alone. Without this, the deck//! the owner flips through could miss a band, and a remove could bin his own//! todo or leave a sample behind once it was marked done.//!//! Every title is the kit's invented sample words; the database is synthetic.mod support;use std::collections::BTreeSet;use std::sync::Arc;use chrono::{DateTime, Utc};use cotton_core::records::page::Moment;use cotton_core::transforms::pace::Pace;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::tables::samples;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::{call_tool, mint_token, owner_at};const ZONE: &str = "Asia/Kolkata";fn now(h: &Harness) -> DateTime<Utc> {    cotton_tools::clock::Clock::now(&h.clock)}/// One act, committed as the owner's phone commits it: Add samples is the/// device fan's (`cotton-ffi` `phone::samples`), the owner's own app, and a/// kit sample can go through an owner-only tool (Pages' pages, bd21fe220).fn act(h: &Harness, body: impl FnOnce(&mut Ctx<'_>) -> Value) -> Value {    let at = now(h);    let owner = owner_at(&h.db, &h.workspace_id, PHONE);    h.with(|db| {        let mut ctx = Ctx::phone(            db,            &h.file,            &h.owner_id,            PHONE,            owner,            cotton_store::mint::Held::Replica,            at,            Arc::clone(&h.random),            &h.services.services,        );        let answer = body(&mut ctx);        ctx.commit().expect("commits");        answer    })}/// The owner's synthetic phone.const PHONE: &str = "synthetic-phone";fn live_ids(h: &Harness, store: &str) -> BTreeSet<String> {    h.all(&format!("SELECT id FROM {store} WHERE trashed_at IS NULL"), &[])        .into_iter()        .map(|row| row["id"].as_str().unwrap().to_string())        .collect()}#[test]fn an_add_fills_every_band_and_a_remove_bins_exactly_the_samples() {    let mut h = Harness::new();    // Mid-afternoon in Kolkata, so "earlier today" and "later today" are both today.    h.clock.set(DateTime::parse_from_rfc3339("2026-10-22T09:30:00Z").unwrap().with_timezone(&Utc));    // A device that finished setting up has its default calendar.    h.run(        "INSERT OR IGNORE INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at) \         VALUES (?, ?, 'calendar', 'Personal', 1, '2026-10-01T09:00:00.000Z')",        &[SqlValue::Text(synthetic_uuid("calendar")), SqlValue::Text(h.workspace_id.clone())],    );    let secret = mint_token(&mut h, &["read", "write"], "test");    let own = call_tool(&h, &secret, "create_record", json!({ "table": "todo", "data": { "title": "Owner's own errand" } }));    let own = own["record"]["id"].as_str().expect("the owner's todo").to_string();    let added = act(&h, |ctx| samples::add(ctx, ZONE).expect("samples are added"));    let todos: BTreeSet<String> = added["todos"].as_array().unwrap().iter().map(|id| id.as_str().unwrap().to_string()).collect();    let events: BTreeSet<String> = added["events"].as_array().unwrap().iter().map(|id| id.as_str().unwrap().to_string()).collect();    assert_eq!((todos.len(), events.len()), (15, 10), "{added}");    assert_eq!(added["kit_records"], 45, "the installed kit packages carry forty-five examples: Books five, Journal four, Keys three (b1a4db5d1), Notebook six, People seven, Story twenty (two stories, six scenes, six characters, four places, two notes); Trips is retired with its nine and Pages with its three (22 Nov 2026); Music ships none: a song is never made without its file; Cinemas none: its first open is the doors; Screenplays is retired with its sample (17 Nov 2026)");    assert_eq!(added["added"], 70);    assert_eq!(added["receipt"], "Added 70 sample records");    let live = act(&h, |ctx| json!(samples::live(ctx).unwrap()));    assert_eq!(live.as_array().unwrap().len(), 70, "the receipt counts exactly the rows written");    for (table, count) in [("person", 7), ("note", 6), ("book", 5), ("film", 0)] {        let held = live.as_array().unwrap().iter().filter(|row| row[0] == table).count();        assert_eq!(held, count, "{table} samples are marked for removal");    }    // Every band, read the way a card reads it.    let today = Moment::now(now(&h), ZONE).unwrap();    let mut bands = BTreeSet::new();    let mut today_plain = false;    for row in h.all("SELECT id, due_at, status FROM cotton_todos", &[]) {        if !todos.contains(row["id"].as_str().unwrap()) {            continue;        }        let due = row["due_at"].as_str().and_then(|text| Moment::parse(text, ZONE));        let pace = Pace::of(due, today, row["status"] == "done", false);        today_plain |= pace == Pace::Soon && due.is_some_and(|due| due.day == today.day);        bands.insert(pace);    }    assert_eq!(bands, [Pace::Late, Pace::Soon, Pace::Upcoming, Pace::Someday, Pace::Done].into(), "every band is filled");    assert!(today_plain, "a todo is owed today");    // Events: three today, one already begun, none past two weeks.    let mut starts = Vec::new();    for row in h.all("SELECT id, starts_at FROM cotton_events", &[]) {        if events.contains(row["id"].as_str().unwrap()) {            starts.push(Moment::parse(row["starts_at"].as_str().unwrap(), ZONE).unwrap());        }    }    let on_today: Vec<_> = starts.iter().filter(|at| at.day == today.day).collect();    assert!(on_today.len() >= 2, "a couple of events today: {starts:?}");    assert!(on_today.iter().any(|at| at.minute < today.minute), "one began earlier today");    assert!(starts.iter().all(|at| (today.day..=today.day + 14).contains(&at.day)), "all within two weeks");    // A second add while they are here adds nothing.    let again = act(&h, |ctx| samples::add(ctx, ZONE).expect("a second add answers"));    assert_eq!(again["added"], 0);    assert_eq!(again["receipt"], "70 sample records are already here");    // A sample marked done is still a sample: an open one, by id, since the    // samples hold a done one already (marking it done again changes nothing    // and is refused) and a set's order is not the same in every process.    let edited = h        .all("SELECT id FROM cotton_todos WHERE status != 'done' ORDER BY id", &[])        .into_iter()        .map(|row| row["id"].as_str().unwrap().to_string())        .find(|id| todos.contains(id.as_str()))        .expect("an open sample todo");    call_tool(&h, &secret, "update_record", json!({ "table": "todo", "id": edited, "patch": { "status": "done" } }));    let removed = act(&h, |ctx| samples::remove(ctx).expect("samples are removed"));    assert_eq!(removed["removed"], 70, "{removed}");    assert_eq!(removed["receipt"], "Moved 70 sample records to the bin");    assert_eq!(live_ids(&h, "cotton_todos"), [own.clone()].into(), "only the owner's todo stays");    assert!(live_ids(&h, "cotton_events").is_disjoint(&events), "every sample event is binned");    let binned = h.count(        "SELECT COUNT(*) FROM cotton_todos WHERE trashed_at IS NOT NULL",        &[],    );    assert_eq!(binned, 15, "the todos went to the bin, not away");    let live = act(&h, |ctx| json!(samples::live(ctx).unwrap()));    assert_eq!(live, json!([]), "every table's samples are removed");    assert_eq!(h.count("SELECT COUNT(*) FROM cotton_people WHERE archived_at IS NULL AND trashed_at IS NULL", &[]), 0);    assert_eq!(h.count("SELECT COUNT(*) FROM cotton_notes WHERE trashed_at IS NULL", &[]), 0);    let none = act(&h, |ctx| samples::remove(ctx).expect("an empty remove answers"));    assert_eq!((none["removed"].clone(), none["receipt"].clone()), (json!(0), json!("There are no sample records to remove")));}#[test]fn binned_package_samples_can_be_added_again() {    let h = Harness::new();    h.run(        "INSERT OR IGNORE INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at) VALUES (?, ?, 'calendar', 'Synthetic calendar', 1, '2026-10-01T09:00:00.000Z')",        &[SqlValue::Text(synthetic_uuid("calendar")), SqlValue::Text(h.workspace_id.clone())],    );    for _ in 0..2 {        let added = act(&h, |ctx| samples::add(ctx, ZONE).expect("add succeeds"));        assert_eq!(added["added"], 70);        let removed = act(&h, |ctx| samples::remove(ctx).expect("remove succeeds"));        assert_eq!(removed["removed"], 70);        assert_eq!(act(&h, |ctx| json!(samples::live(ctx).unwrap())), json!([]));    }}