Cotton code
263 lines · 14.5 KB · RustRaw
//! The everyday shapes: the patterns a real file holds in its todos, calendar,//! notes, goals, alarms and moods that the scaled kinds do not//! make. One of each, so every screen has its case to draw — written through//! the same handlers, with the few columns no handler takes set by a stamped//! patch (`update_row`), each named where it is used.use super::{call, day, id_of, iso, object, refused, Household, OWNER_EMAIL};use crate::mcp::handlers::common::{insert_row, update_row};use crate::mcp::handlers::projects::write::link_to_project;use crate::mcp::handlers::records_1::events::{create_event, update_attendees};use crate::mcp::handlers::records_1::notes::{archive_note, create_note, upsert_managed_note};use crate::mcp::handlers::records_1::todos::{create_todo, update_todo};use crate::synthetic::names;use chrono::Duration;use cotton_store::protocol::derived_id;use cotton_store::Result;use serde_json::{json, Map, Value};/// Every table a shape here writes into, for the household's recount.pub(super) const TABLES: &[&str] = &[    "cotton_todos",    "cotton_todo_recurrences",    "cotton_events",    "cotton_event_attendees",    "cotton_notes",    "cotton_note_attachments",];fn patch(value: Value) -> Map<String, Value> {    object(value)}impl Household<'_> {    /// Todos around today (due this morning, tonight, tomorrow, a date with no    /// time), three that repeat (`rrule` — the handler writes the template and    /// every occurrence up to now), and `update_todo {snoozedUntil | priority:    /// "high" | status: "dropped"}`.    pub(super) fn write_todo_shapes(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let title = || format!("{} {}", rng.pick(names::TODO_VERBS), rng.pick(names::TODO_OBJECTS));        env.once(env.now - Duration::days(2), |ctx| {            // Due around today: late by a day or two, today, and the week ahead.            for (days, hour) in [(-2, 10), (-1, 17), (0, 8), (0, 13), (0, 19), (1, 9), (1, 18), (2, 11), (4, 15), (6, 10)] {                let args = patch(json!({ "title": title(), "dueAt": iso(env.day_at(days, hour, 0)) }));                call("todo due around today", create_todo(ctx, &args))?;            }            // A day and no time, as most todos typed on a phone are.            for days in [0, 1, 3] {                let args = patch(json!({ "title": title(), "dueDate": day(env.day_at(days, 0, 0)) }));                call("todo due on a day", create_todo(ctx, &args))?;            }            // Open with no date at all, one of them with a long note.            let args = patch(json!({ "title": title(), "notes": env.sentences(3, 5) }));            call("todo with a note", create_todo(ctx, &args))?;            Ok(())        })?;        env.once(env.now, |ctx| {            for (name, back, hour, rrule) in [                ("Water the plants", 3, 7, "FREQ=DAILY"),                ("Put the bins out", 15, 20, "FREQ=WEEKLY"),                ("Pay the rent", 62, 9, "FREQ=MONTHLY"),            ] {                let args = patch(json!({ "title": name, "dueAt": iso(env.day_at(-back, hour, 0)), "rrule": rrule }));                call("repeating todo", create_todo(ctx, &args))?;            }            for days in [1, 3, 10] {                let out = call("todo to snooze", create_todo(ctx, &patch(json!({ "title": title() }))))?;                let args = patch(json!({ "id": id_of("todo", &out)?, "snoozedUntil": iso(env.day_at(days, 8, 0)) }));                call("snoozed todo", update_todo(ctx, &args))?;            }            for days in [0, 2, -3, 5] {                let args = patch(json!({ "title": title(), "dueAt": iso(env.day_at(days, 12, 0)) }));                let out = call("todo to raise", create_todo(ctx, &args))?;                call("high-priority todo", update_todo(ctx, &patch(json!({ "id": id_of("todo", &out)?, "priority": "high" }))))?;            }            for _ in 0..4 {                let out = call("todo to drop", create_todo(ctx, &patch(json!({ "title": title() }))))?;                call("dropped todo", update_todo(ctx, &patch(json!({ "id": id_of("todo", &out)?, "status": "dropped" }))))?;            }            Ok(())        })    }    /// `create_event {rrule}` (repeating), an end days after the start    /// (multi-day, timed and all-day), `update_attendees` (guests), an    /// invitation still to answer, and a second calendar that reads as synced.    /// No handler sets `organizer_is_self`, `my_response` on a fresh event,    /// `gcal_id`/`sync_state`, an attendee's `response` or an event's    /// `collection_id`, and no handler makes a calendar: those are patches.    pub(super) fn write_event_shapes(&mut self) -> Result<()> {        let env = &self.env;        let people = &self.people;        let guests = |from: usize, n: usize| -> Vec<Value> {            people                .iter()                .skip(from)                .take(n)                .map(|person| json!({ "personId": person.id, "displayName": person.name, "email": person.email }))                .collect()        };        env.once(env.now - Duration::days(30), |ctx| {            for (title, back, hour, minutes, rrule) in [                ("Swimming", 28, 6, 60, "FREQ=WEEKLY;BYDAY=TU,TH"),                ("Team catch-up", 21, 10, 30, "FREQ=WEEKLY;BYDAY=MO"),                ("Call home", 30, 18, 45, "FREQ=WEEKLY;INTERVAL=2"),                ("Rent due", 60, 9, 15, "FREQ=MONTHLY"),            ] {                let starts = env.day_at(-back, hour, 0);                let args = patch(json!({                    "title": title, "startsAt": iso(starts), "endsAt": iso(starts + Duration::minutes(minutes)), "rrule": rrule,                }));                call("repeating event", create_event(ctx, &args))?;            }            // Several days: one timed (a trip), one all-day (a visit).            let args = patch(json!({                "title": "Coast trip", "startsAt": iso(env.day_at(5, 7, 0)), "endsAt": iso(env.day_at(8, 20, 0)),                "notes": env.sentences(1, 2),            }));            call("multi-day event", create_event(ctx, &args))?;            let args = patch(json!({                "title": "Family visiting", "allDay": true, "startsAt": iso(env.day_at(12, 0, 0)), "endsAt": iso(env.day_at(14, 0, 0)),            }));            call("multi-day all-day event", create_event(ctx, &args))?;            Ok(())        })?;        if people.len() < 6 {            return Ok(());        }        env.once(env.now - Duration::days(1), |ctx| {            // Guests, with every answer a guest can have given.            for (title, days, hour, from) in [("Dinner at ours", 2, 19, 0usize), ("Planning the trip", 6, 17, 2)] {                let starts = env.day_at(days, hour, 0);                let args = patch(json!({ "title": title, "startsAt": iso(starts), "endsAt": iso(starts + Duration::hours(2)) }));                let event = id_of("event", &call("event with guests", create_event(ctx, &args))?)?;                let out = call(                    "guests",                    update_attendees(ctx, &patch(json!({ "eventId": event, "attendees": guests(from, 4) }))),                )?;                let rows = out.get("attendees").and_then(Value::as_array).cloned().unwrap_or_default();                for (row, response) in rows.iter().zip(["accepted", "declined", "tentative"]) {                    if let Some(id) = row.get("id").and_then(Value::as_str) {                        update_row(ctx, "cotton_event_attendees", id, patch(json!({ "response": response })))                            .map_err(refused("guest reply"))?;                    }                }                ctx.commit().map_err(refused("guest reply"))?;            }            // Invitations from somebody else: two still to answer, one said            // yes to, one declined. They arrive from the synced calendar, so            // they carry its marks.            for (n, (title, days, hour, response)) in [                ("Housewarming", 3, 18, "needs_action"),                ("Quarterly review", 7, 14, "needs_action"),                ("Birthday lunch", 9, 12, "accepted"),                ("Committee meeting", 10, 19, "declined"),            ]            .into_iter()            .enumerate()            {                let starts = env.day_at(days, hour, 0);                let args = patch(json!({ "title": title, "startsAt": iso(starts), "endsAt": iso(starts + Duration::hours(2)) }));                let event = id_of("event", &call("invitation", create_event(ctx, &args))?)?;                call("invitation guests", update_attendees(ctx, &patch(json!({ "eventId": event, "attendees": guests(n, 3) }))))?;                let marks = patch(json!({                    "organizer_is_self": false, "my_response": response,                    "gcal_id": format!("synthetic-invite-{n}"), "gcal_etag": "1", "sync_state": "synced",                    "account": OWNER_EMAIL,                }));                update_row(ctx, "cotton_events", &event, marks).map_err(refused("invitation"))?;                ctx.commit().map_err(refused("invitation"))?;            }            // A second calendar, as a synced account adds one.            let calendar = ctx.new_uuid();            let row = patch(json!({ "kind": "calendar", "name": "Work", "is_default": false, "sort_key": "1" }));            insert_row(ctx, "cotton_collections", &calendar, row).map_err(refused("calendar"))?;            ctx.commit().map_err(refused("calendar"))?;            for (n, (title, days, hour)) in                [("Stand-up", 0, 9), ("Design review", 1, 11), ("One to one", 2, 15), ("All hands", 4, 16), ("Budget round", -1, 10)]                    .into_iter()                    .enumerate()            {                let starts = env.day_at(days, hour, 0);                let args = patch(json!({ "title": title, "startsAt": iso(starts), "endsAt": iso(starts + Duration::minutes(45)) }));                let event = id_of("event", &call("synced event", create_event(ctx, &args))?)?;                let marks = patch(json!({                    "collection_id": calendar, "gcal_id": format!("synthetic-work-{n}"), "gcal_etag": "1", "sync_state": "synced",                    "account": OWNER_EMAIL,                }));                update_row(ctx, "cotton_events", &event, marks).map_err(refused("synced event"))?;                ctx.commit().map_err(refused("synced event"))?;            }            Ok(())        })    }    /// Notes with pictures (`attachments`, captioned and not), filed in a    /// project, archived (`archive_note`), published, kept by an assistant    /// (`upsert_managed_note`). `project_id` and `published_at` have no    /// handler: patches.    pub(super) fn write_note_shapes(&mut self) -> Result<()> {        let env = &self.env;        let photos = &self.photos;        let projects = &self.projects;        let note = |title: &str| patch(json!({ "title": title, "body": env.sentences(2, 6) }));        env.once(env.now - Duration::days(6), |ctx| {            if photos.len() >= 6 {                let mut args = note("The weekend, in pictures");                args.insert(                    "attachments".into(),                    json!([                        { "kind": "photo", "id": photos[0], "caption": "Before the rain" },                        { "kind": "photo", "id": photos[1] },                        { "kind": "photo", "id": photos[2], "caption": "The path back" },                    ]),                );                call("note with pictures", create_note(ctx, &args))?;                let mut args = note("Paint colours for the hall");                args.insert("attachments".into(), json!([{ "kind": "photo", "id": photos[3] }]));                call("note with a picture", create_note(ctx, &args))?;            }            for (n, slug) in projects.iter().enumerate().take(3) {                for title in ["Where things stand", "Open questions"].iter().take(2 - n.min(1)) {                    let id = id_of("note", &call("note in a project", create_note(ctx, &note(title)))?)?;                    let args = patch(json!({ "project": slug, "records": [{ "kind": "note", "id": id }] }));                    call("note in a project", link_to_project(ctx, &args))?;                    let project_id = derived_id::memory_project_id(env.file.namespace(), slug);                    update_row(ctx, "cotton_notes", &id, patch(json!({ "project_id": project_id })))                        .map_err(refused("note in a project"))?;                    ctx.commit().map_err(refused("note in a project"))?;                }            }            // ONE RECORD IN TWO PROJECTS: a link is a row per project, so the            // same note filed under two is two links and one note — the shape            // a project page, search and the release walk must each read            // without doubling or dropping it.            if projects.len() >= 2 {                let id = id_of("note", &call("note in two projects", create_note(ctx, &note("Shared supplier list")))?)?;                for slug in projects.iter().take(2) {                    let args = patch(json!({ "project": slug, "records": [{ "kind": "note", "id": id }] }));                    call("note in two projects", link_to_project(ctx, &args))?;                }            }            for title in ["Old packing list", "Draft of the speech", "Last year's budget"] {                let id = id_of("note", &call("note to archive", create_note(ctx, &note(title)))?)?;                call("archived note", archive_note(ctx, &patch(json!({ "id": id }))))?;            }            for (title, slug) in [("How we run the allotment rota", "synthetic-allotment-rota"), ("Recipe: the lentil thing", "synthetic-lentils")] {                let id = id_of("note", &call("note to publish", create_note(ctx, &note(title)))?)?;                let marks = patch(json!({ "published_at": iso(ctx.now), "public_slug": slug }));                update_row(ctx, "cotton_notes", &id, marks).map_err(refused("published note"))?;                ctx.commit().map_err(refused("published note"))?;            }            for (external, title) in [("synthetic:reading-list", "Reading list"), ("synthetic:weekly-summary", "This week, summed up")] {                let args = patch(json!({                    "externalId": external, "managedBy": "Assistant", "title": title, "body": env.sentences(3, 6),                }));                call("managed note", upsert_managed_note(ctx, &args))?;            }            Ok(())        })    }}