//! A Records thread's two acts (architect brief, Records slips typed by kind,//! landing 3): "Record as a transaction" and "Add to calendar" — each the//! owner's tap, never automatic; the record and its link to the thread are//! written together, and the thread then shows the link in place of the act.//!//! Every value is invented ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use std::sync::Arc;use cotton_tools::mcp::dispatch::{Ctx, ToolServices};use cotton_tools::mcp::handlers::emails::record_acts;use cotton_tools::mcp::protocol::ToolFailure;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::{call_tool, mint_token};const OWNER: &str = "owner@example.invalid";const NOW: &str = "2026-10-05T09:00:00.000Z";fn file() -> (Harness, String) {letmut h = Harness::new();let secret = mint_token(&mut h, &["read", "write"], "Claude"); h.run("INSERT INTO cotton_google_accounts (id, workspace_id, google_email, created_at, updated_at) VALUES ('google-1', ?1, ?2, ?3, ?3)", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(OWNER.into()), SqlValue::Text(NOW.into())], );// The calendar a new database starts with. Money receipts use the real// account each case creates; the removed ledger has no suspense account. h.run("INSERT INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at) VALUES ('calendar-1', ?1, 'calendar', 'Personal', 1, ?2)", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into())], ); h.run("INSERT INTO cotton_news_settings (workspace_id, timezone, created_at, updated_at) VALUES (?1, 'Asia/Kolkata', ?2, ?2)", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into())], ); (h, secret)}/// A service thread, typed as it lands; answers its id.fn thread(h: &Harness, secret: &str, key: &str, from: &str, name: &str, subject: &str, body: &str) -> String {let mail = json!({"threadKey": key, "subject": subject, "sentAt": "2026-10-03T09:00:00.000Z", "body": body,"messageId": format!("<{key}@example.invalid>"),"from": { "email": from, "name": name }, "to": [{ "email": OWNER }], });let out = call_tool(h, secret, "ingest_emails", json!({ "emails": [mail] })); assert!(out.get("added").is_some(), "{out}");let row = h .one("SELECT id FROM cotton_email_threads WHERE external_key = ?1", &[SqlValue::Text(key.into())]) .expect("the thread"); row["id"].as_str().expect("an id").to_string()}/// One tap: the act in its own write, committed only when it answers.fn tap( h: &Harness, act: fn(&mutCtx<'_>, &str) -> Result<Value, ToolFailure>, thread: &str,) -> Result<Value, String> {let services = ToolServices::none();let audit = |_tool: &str, _summary: &str| {}; h.with(|db| {letmut ctx = Ctx::for_worker( db, &h.file, &h.owner_id, cotton_tools::mcp::writer::job("records"),"job:records", cotton_tools::clock::Clock::now(&h.clock),Arc::clone(&h.random), &services, &audit, );let out = act(&mut ctx, thread).map_err(|failure| failure.to_string())?; ctx.commit().expect("commits");Ok(out) })}/// A record's page data, read the way the app reads it.fn data(h: &Harness, secret: &str, table: &str, id: &str) -> Value {let answer = call_tool(h, secret, "list_records", json!({ "table": table, "limit": 50 })); answer["records"] .as_array() .unwrap_or_else(|| panic!("records: {answer}")) .iter() .find(|record| record["id"] == id) .unwrap_or_else(|| panic!("{table} {id} in {answer}"))["data"] .clone()}/// Whether the thread's page offers a command, by the definition's own `when`.fn offers(data: &Value, command: &str) -> bool {let definition = cotton_core::definitions::builtin_table_definition("email_thread").expect("email_thread"); definition .commands .iter() .flatten() .find(|offered| offered.id == command) .unwrap_or_else(|| panic!("{command} is declared")) .offered_on(data)}fn count(h: &Harness, sql: &str) -> i64 { h.one(sql, &[]).expect("a count")["n"].as_i64().expect("a number")}/// RULE: A receipt in another currency than the account Money would book it in is refused by name before anything is written — no transaction, no link.#[test]fn a_receipt_in_another_currency_is_refused_and_writes_nothing() {let (h, secret) = file(); call_tool(&h, &secret, "create_money_account", json!({ "name": "Everyday", "kind": "bank", "currency": "INR" }));let receipt = thread( &h, &secret,"dollars","billing@app.example.invalid","Example App","Your receipt from Example App","Receipt number: EA-2001\nPaid on 2 Oct 2026\nTotal: $12.00", );let refused = tap(&h, record_acts::record_as_transaction, &receipt).expect_err("refused"); assert!(refused.contains("USD") && refused.contains("INR"), "{refused}"); assert_eq!(count(&h, "SELECT count(*) AS n FROM cotton_money_transactions"), 0); assert_eq!(count(&h, "SELECT count(*) AS n FROM cotton_links"), 0);}/// RULE: Adding a ticket to the calendar makes one all-day event on the day the ticket is about, named by its merchant and reference and linked to the thread; the thread then shows the event in place of the act and the event shows the thread.#[test]fn a_ticket_added_to_the_calendar_links_both_ways_once() {let (h, secret) = file();let ticket = thread( &h, &secret,"rail","tickets@rail.example.invalid","Example Rail","E-ticket: Bengaluru to Pune","Booked on 01/10/2026.\nPNR: 4711XQ\nDate of journey: 18 Oct 2026", );let before = data(&h, &secret, "email_thread", &ticket); assert!(offers(&before, "add_to_calendar")); assert!(!offers(&before, "record_as_transaction"), "a ticket names no receipt to book");let out = tap(&h, record_acts::add_to_calendar, &ticket).expect("adds");let id = out["eventId"].as_str().expect("an event").to_string();let event = data(&h, &secret, "event", &id); assert_eq!(event["title"], "Example Rail · 4711XQ"); assert_eq!(event["email_thread_id"], ticket.as_str());let after = data(&h, &secret, "email_thread", &ticket); assert_eq!(after["event_id"], id.as_str()); assert!(!offers(&after, "add_to_calendar"), "the link replaces the act"); assert_eq!(tap(&h, record_acts::add_to_calendar, &ticket).expect("answers")["already"], true); assert_eq!(count(&h, "SELECT count(*) AS n FROM cotton_events"), 1);}/// RULE: An act on a thread of the wrong kind, or one whose amount or day was not read for sure, is refused and writes nothing — the owner records it by hand.#[test]fn an_act_on_the_wrong_kind_or_an_unsure_record_is_refused() {let (h, secret) = file(); call_tool(&h, &secret, "create_money_account", json!({ "name": "Everyday", "kind": "bank", "currency": "INR" }));let notice = thread(&h, &secret, "terms", "news@example.invalid", "Example", "Updates to our terms", "Nothing to keep.");let unsure = thread(&h, &secret, "items", "shop@example.invalid", "Example Shop", "Your receipt", "Item one ₹100\nItem two ₹250\n");let undated = thread(&h, &secret, "stay", "stays@example.invalid", "Example Stays", "Booking confirmed", "Check-in: 03/04/2026"); assert!(tap(&h, record_acts::record_as_transaction, ¬ice).is_err()); assert!(tap(&h, record_acts::add_to_calendar, ¬ice).is_err()); assert!(tap(&h, record_acts::record_as_transaction, &unsure).expect_err("no amount").contains("by hand")); assert!(tap(&h, record_acts::add_to_calendar, &undated).expect_err("no day").contains("by hand")); assert_eq!(count(&h, "SELECT count(*) AS n FROM cotton_money_transactions"), 0); assert_eq!(count(&h, "SELECT count(*) AS n FROM cotton_events"), 0); assert_eq!(count(&h, "SELECT count(*) AS n FROM cotton_links"), 0);}