Cotton code
672 lines · 28.4 KB · RustRaw
//! PEOPLE ON AN EVENT (CONTRACT.md section 15, 22 Nov 2026): who is on an//! event, how each hears of it, and what saving a new list will do.//!//! **The route rule** ([`route`]), decided here and nowhere else://! - `cotton`: the person's number is among this person's connected people//!   on Cotton (Your people). Never an arbitrary email or number: nothing here//!   ever asks whether an address is on Cotton.//! - `google`: anyone else with an email, while a Google calendar that can//!   be written is connected; Google emails the invitation.//! - `none`: anyone else while no such calendar is connected; the sheet says//!   so with Connect.//! - `mail` is the seam for Cotton's own mail: once Cotton sends mail itself,//!   [`route`] answers it for an email with no writable Google calendar, and//!   the send pass hands the invitation to that sender. Nothing answers it yet.//!//! **Where it is kept.** Each person is an `event_attendee` row: `email`,//! `phone`, `display_name`, `via` (cotton or google, fixed when added),//! `response` (their answer as Cotton heard it), `sent` (the event's version//! that last reached them by Cotton, or `off`), `removed_at` (taken off, kept//! until told) and `role` (`organizer` on an invitation received). Google's//! answers for people it emailed arrive with the pull in the event's own//! `guest_responses` (a JSON list), and are read from there by email.//!//! **What the phone knows without asking.** [`Heard`], in memory on the//! controller: the object's last Google status (from `days.google`) and the//! connected numbers (from the last `days.people_find`). A sheet draws from//! it; nothing in a sheet waits on the network.use std::collections::{BTreeMap, BTreeSet};use cotton_store::driver::Row;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use sha2::{Digest, Sha256};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, now_iso, update_row};use crate::methods::MethodError;use crate::shell::client::ClientController;pub const ATTENDEES: &str = "cotton_event_attendees";/// At most this many people found for one search.const FOUND: usize = 20;/// What Days last heard from the object, kept in memory (never written).#[derive(Debug, Clone, Default)]pub struct Heard {    /// The object's `google.status` answer.    pub google: Option<Value>,    /// The numbers (E.164) of this person's connected people on Cotton, with the name the object gave.    pub connected: Option<Vec<(String, Option<String>)>>,}impl Heard {    pub fn of(client: &ClientController) -> Heard {        client.days_heard.lock().unwrap_or_else(|p| p.into_inner()).clone()    }    pub fn google(client: &ClientController, status: &Value) {        client.days_heard.lock().unwrap_or_else(|p| p.into_inner()).google = Some(status.clone());    }    pub fn connected(client: &ClientController, people: Vec<(String, Option<String>)>) {        client.days_heard.lock().unwrap_or_else(|p| p.into_inner()).connected = Some(people);    }    /// A Google account that can be written and is not stopped; `None`: not heard yet.    /// The status a phone with no server copy stands in: nothing connected, and nothing can be.    pub fn unconnected() -> Value {        json!({ "available": false, "accounts": [] })    }    /// No server copy answered: what was last heard stands (a phone signed in a moment ago may only be offline);    /// with nothing heard yet, nothing is connected.    pub fn not_connected(client: &ClientController) {        let mut heard = client.days_heard.lock().unwrap_or_else(|p| p.into_inner());        if heard.google.is_none() {            heard.google = Some(Self::unconnected());        }    }    pub fn writable(&self) -> Option<Option<String>> {        let status = self.google.as_ref()?;        Some(            status["accounts"]                .as_array()                .into_iter()                .flatten()                .find(|a| a["canWrite"] == json!(true) && a["calendar"]["phase"] != json!("reconnect"))                .and_then(|a| a["googleEmail"].as_str().map(str::to_string)),        )    }    /// Some Google account is connected (read-only or not), as last heard.    pub fn connected_google(&self) -> bool {        self.google.as_ref().is_some_and(|s| s["accounts"].as_array().is_some_and(|a| !a.is_empty()))    }    pub fn is_connected(&self, number: &str) -> Option<bool> {        self.connected.as_ref().map(|people| people.iter().any(|(n, _)| n == number))    }}/// How a person on an event hears of it (the route rule, module doc).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Via {    Cotton,    Google,    None,}impl Via {    pub fn word(self) -> &'static str {        match self {            Via::Cotton => "cotton",            Via::Google => "google",            Via::None => "none",        }    }}/// The route for someone being added: a connected number goes by Cotton; an email by Google while one can be/// written (`writable`), else nowhere yet. `None`: neither a connected number nor an email.pub fn route(number: Option<&str>, email: Option<&str>, connected: bool, writable: bool) -> Option<Via> {    match (number, email) {        (Some(_), _) if connected => Some(Via::Cotton),        (_, Some(_)) if writable => Some(Via::Google),        (_, Some(_)) => Some(Via::None),        _ => None,    }}pub fn line(name: &str) -> Result<String, MethodError> {    say(name, &[])}pub fn say(name: &str, fills: &[(&str, &str)]) -> Result<String, MethodError> {    cotton_core::rules::shell_lines::LineSet::shipped("days")        .and_then(|lines| lines.say(name, fills))        .ok_or_else(|| MethodError::new("unreadable", format!("the days set says no line {name}")))}fn sql(error: impl std::fmt::Display) -> MethodError {    MethodError::new("unreadable", error.to_string())}fn tool(failure: cotton_tools::mcp::protocol::ToolFailure) -> MethodError {    MethodError::new("write_refused", failure.to_string())}fn rows(ctx: &Ctx<'_>, statement: &str, params: &[SqlValue]) -> Result<Vec<Row>, MethodError> {    ctx.read.driver().all(statement, params).map_err(sql)}/// An email as compared: trimmed and lowercased; `None` when it is not one.pub fn email_key(raw: &str) -> Option<String> {    let email = raw.trim().to_lowercase();    let (local, domain) = email.split_once('@')?;    (!local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.') && !email.contains(char::is_whitespace)).then_some(email)}/// "Priya", "Priya and Akash", "Priya, Akash and Rose".pub fn names(list: &[String]) -> String {    match list {        [] => String::new(),        [one] => one.clone(),        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),    }}/// One person on an event as this copy holds them.#[derive(Debug, Clone)]pub struct Guest {    pub id: String,    pub email: Option<String>,    pub phone: Option<String>,    pub name: Option<String>,    pub via: Via,    pub response: Option<String>,    pub sent: Option<String>,    pub removed: bool,    pub organizer: bool,}impl Guest {    pub fn shown(&self) -> String {        self.name.clone().filter(|n| !n.trim().is_empty()).or_else(|| self.email.clone()).or_else(|| self.phone.clone()).unwrap_or_default()    }    pub fn key(&self) -> String {        match (&self.phone, &self.email) {            (Some(phone), _) if self.via == Via::Cotton => format!("number:{phone}"),            (_, Some(email)) => format!("email:{email}"),            (Some(phone), None) => format!("number:{phone}"),            (None, None) => format!("row:{}", self.id),        }    }}fn holds(ctx: &Ctx<'_>, table: &str, column: &str) -> Result<bool, MethodError> {    Ok(rows(ctx, &format!("SELECT name FROM pragma_table_info('{table}')"), &[])?.iter().any(|row| row.text("name") == Some(column)))}fn optional(ctx: &Ctx<'_>, column: &str) -> Result<String, MethodError> {    Ok(if holds(ctx, ATTENDEES, column)? { column.to_string() } else { format!("NULL AS {column}") })}/// Everyone on `event`, the removed ones too, oldest first.pub fn guests(ctx: &Ctx<'_>, event: &str) -> Result<Vec<Guest>, MethodError> {    let extra = ["via", "sent", "removed_at", "role"].iter().map(|c| optional(ctx, c)).collect::<Result<Vec<_>, _>>()?.join(", ");    let found = rows(ctx, &format!("SELECT id, email, phone, display_name, response, {extra} FROM {ATTENDEES} WHERE event_id = ? ORDER BY created_at, rowid"), &[SqlValue::Text(event.to_string())])?;    Ok(found        .iter()        .map(|row| {            let phone = row.text("phone").map(str::to_string).filter(|p| !p.is_empty());            let email = row.text("email").and_then(email_key);            let via = match row.text("via") {                Some("cotton") => Via::Cotton,                Some("google") => Via::Google,                // A row this copy did not make (the Mac's, an import): by what it names.                _ if email.is_some() => Via::Google,                _ => Via::Cotton,            };            Guest {                id: row.text("id").unwrap_or_default().to_string(),                email,                phone,                name: row.text("display_name").map(str::to_string),                via,                response: row.text("response").map(str::to_string),                sent: row.text("sent").map(str::to_string).filter(|s| !s.is_empty()),                removed: row.text("removed_at").is_some(),                organizer: row.text("role") == Some("organizer"),            }        })        .collect())}/// Google's guests on an event, from the pull's `guest_responses`.#[derive(Debug, Clone)]pub struct GoogleGuest {    pub email: String,    pub name: Option<String>,    pub answer: Option<String>,    pub me: bool,    pub organizer: bool,}pub fn google_guests(raw: Option<&str>) -> Vec<GoogleGuest> {    let Some(list) = raw.and_then(|raw| serde_json::from_str::<Value>(raw).ok()) else { return Vec::new() };    list.as_array()        .into_iter()        .flatten()        .filter_map(|g| {            Some(GoogleGuest {                email: g["email"].as_str().and_then(email_key)?,                name: g["name"].as_str().or_else(|| g["displayName"].as_str()).map(str::to_string),                answer: g["answer"].as_str().or_else(|| g["responseStatus"].as_str()).map(str::to_string),                me: g["self"] == json!(true),                organizer: g["organizer"] == json!(true),            })        })        .collect()}/// An answer as the sheet names it: Google's words and Cotton's are the same four.pub fn answer_key(raw: Option<&str>) -> Option<&'static str> {    match raw? {        "accepted" => Some("coming"),        "tentative" => Some("maybe"),        "declined" => Some("not_coming"),        "needsAction" | "needs_action" => Some("no_answer"),        _ => None,    }}/// The version of an event a person on it was last told: a digest of what they see of it.pub fn rev(row: &Row) -> String {    let mut hasher = Sha256::new();    for column in ["title", "starts_at", "ends_at", "all_day", "rrule", "exdates", "location", "notes"] {        hasher.update(row.get(column).map(|v| format!("{v:?}")).unwrap_or_default().as_bytes());        hasher.update([0u8]);    }    hex::encode(&hasher.finalize()[..8])}/// The connect act and its notice (CONTRACT.md section 13), for the blocked line.pub fn connect_act(heard: &Heard) -> Result<Value, MethodError> {    // Signed out: no Connect can work yet, so none is offered.    if heard.google.as_ref().is_some_and(|s| s["available"] == json!(false)) {        return Ok(Value::Null);    }    let at = super::days_google::At { zone: "UTC".into(), now_ms: 0 };    let shaped = super::days_google::shape(Some(heard.google.as_ref().unwrap_or(&json!({ "available": true, "accounts": [] }))), &at)?;    if !shaped["connect"].is_null() {        return Ok(shaped["connect"].clone());    }    // An account stands but cannot write: connecting again is what gives Days the right to.    let fresh = super::days_google::shape(Some(&json!({ "available": true, "accounts": [] })), &at)?;    let mut connect = fresh["connect"].clone();    connect["label"] = json!(line("settings.connect_again")?);    Ok(connect)}/// Whether a Google-bound change can reach Google, as last heard (unknown counts as yes: it waits and goes).fn can_write(heard: &Heard) -> bool {    match heard.writable() {        Some(account) => account.is_some(),        None => true,    }}/// The sheet's PEOPLE part for an event (CONTRACT.md section 15).pub fn part(ctx: &Ctx<'_>, heard: &Heard, event: &Row, master: Option<&Row>) -> Result<Value, MethodError> {    let id = event.text("id").unwrap_or_default();    let series = event.text("series_id");    // An occurrence carries its series' people.    let owner = series.filter(|_| guests(ctx, id).map(|g| g.is_empty()).unwrap_or(true)).unwrap_or(id);    let held = guests(ctx, owner)?;    let source = master.unwrap_or(event);    let google = google_guests(event.text("guest_responses").or_else(|| source.text("guest_responses")));    let received = event.text("invited") == Some("invited") || source.text("invited") == Some("invited");    let writable = can_write(heard);    let mut out = Vec::new();    let mut seen = BTreeSet::new();    for guest in held.iter().filter(|g| !g.removed) {        let via = match guest.via {            Via::Google if !writable => Via::None,            other => other,        };        let answer = match guest.via {            _ if guest.organizer => None,            Via::Cotton if guest.sent.is_some() => answer_key(guest.response.as_deref()).or(Some("no_answer")),            Via::Cotton => None,            _ => guest.email.as_ref().and_then(|e| google.iter().find(|g| &g.email == e)).map(|g| answer_key(g.answer.as_deref()).unwrap_or("no_answer")),        };        if let Some(email) = &guest.email {            seen.insert(email.clone());        }        out.push(row_of(&guest.key(), &guest.shown(), detail(guest.email.as_deref(), via)?, via, answer, guest.organizer)?);    }    for guest in google.iter().filter(|g| !g.me && !seen.contains(&g.email)) {        let answer = answer_key(guest.answer.as_deref()).unwrap_or("no_answer");        let shown = guest.name.clone().unwrap_or_else(|| guest.email.clone());        out.push(row_of(&format!("email:{}", guest.email), &shown, detail(Some(&guest.email), Via::Google)?, Via::Google, (!guest.organizer).then_some(answer), guest.organizer)?);    }    let blocked = if out.iter().any(|r| r["via"] == "none") {        json!({ "line": line("people.blocked")?, "connect": connect_act(heard)? })    } else {        Value::Null    };    let from_google = source.text("gcal_id").is_some();    let organizer_self = source.int("organizer_is_self").unwrap_or(1) != 0;    Ok(json!({        "title": line("people.title")?, "add": line("people.add")?,        "canChange": !received && (!from_google || organizer_self),        "rows": out, "blocked": blocked,    }))}fn detail(email: Option<&str>, via: Via) -> Result<Value, MethodError> {    Ok(match (via, email) {        (Via::Cotton, _) => json!(line("people.on_cotton")?),        (_, Some(email)) => json!(email),        _ => Value::Null,    })}fn row_of(key: &str, name: &str, detail: Value, via: Via, answer: Option<&str>, organizer: bool) -> Result<Value, MethodError> {    let words = match answer {        Some(answer) => json!(line(&format!("people.{answer}"))?),        None if organizer => json!(line("people.organizer")?),        None => Value::Null,    };    Ok(json!({ "key": key, "name": name, "detail": detail, "via": via.word(), "answer": answer, "answerWords": words, "organizer": organizer }))}/// One person a search found.#[derive(Debug, Clone)]struct Found {    name: String,    email: Option<String>,    number: Option<String>,    connected: bool,}/// Folded for matching: lowercased, Latin, Greek and Cyrillic accents let go.fn folded(text: &str) -> String {    cotton_core::cotton_rules::days::rhythm::fold(text)}/// Who is connected: asked of the object when it can be reached, else what was last heard stands.pub fn hear_connected(client: &ClientController) {    if let Ok(mut listed) = super::cotton_chat::ask(client, "GET", "/v1/chat/people", None) {        super::circle::open_sealed(client, &mut listed);        let people = listed["people"]            .as_array()            .into_iter()            .flatten()            .filter(|p| p["waiting"] != json!(true))            .filter_map(|p| Some((p["number"].as_str()?.to_string(), p["name"].as_str().map(str::to_string))))            .collect();        Heard::connected(client, people);    }}/// `days.people_find { words }` (CONTRACT.md section 15): contacts with an email or connected on Cotton.pub fn find(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let typed = request.get("words").and_then(Value::as_str).unwrap_or_default().trim().to_string();    hear_connected(client);    let heard = Heard::of(client);    let connected = heard.connected.clone().unwrap_or_default();    let handles = super::cotton_chat::read(client, "days.people_find", |ctx| {        let rows = ctx            .read            .driver()            .all(                "SELECT h.person_id AS person, h.kind AS kind, h.value AS value, p.full_name AS name FROM cotton_person_handles h JOIN cotton_people p ON p.id = h.person_id WHERE h.workspace_id = ? AND h.kind IN ('email', 'phone') AND h.trashed_at IS NULL AND p.trashed_at IS NULL",                &[SqlValue::Text(ctx.workspace_id.to_string())],            )            .map_err(|e| e.to_string())?;        Ok(Value::from(            rows.iter()                .map(|r| json!({ "person": r.text("person"), "kind": r.text("kind"), "value": r.text("value"), "name": r.text("name") }))                .collect::<Vec<_>>(),        ))    })    ?;    let mut people: BTreeMap<String, Found> = BTreeMap::new();    for handle in handles.as_array().into_iter().flatten() {        let Some(person) = handle["person"].as_str() else { continue };        let entry = people.entry(person.to_string()).or_insert_with(|| Found {            name: handle["name"].as_str().unwrap_or_default().to_string(),            email: None,            number: None,            connected: false,        });        match handle["kind"].as_str() {            Some("email") => {                if entry.email.is_none() {                    entry.email = handle["value"].as_str().and_then(email_key);                }            }            Some("phone") => {                let Some(number) = handle["value"].as_str().and_then(super::cotton_chat::e164) else { continue };                if connected.iter().any(|(n, _)| *n == number) {                    entry.number = Some(number);                    entry.connected = true;                }            }            _ => {}        }    }    let mut found: Vec<Found> = people.into_values().filter(|f| f.email.is_some() || f.connected).collect();    // Connected people the address book does not hold, under the name the object gave.    for (number, name) in &connected {        if !found.iter().any(|f| f.number.as_deref() == Some(number)) {            found.push(Found { name: name.clone().unwrap_or_else(|| number.clone()), email: None, number: Some(number.clone()), connected: true });        }    }    let wanted = folded(&typed);    let words: Vec<&str> = wanted.split_whitespace().collect();    found.retain(|f| {        let hay = folded(&format!("{} {}", f.name, f.email.clone().unwrap_or_default()));        words.iter().all(|w| hay.contains(w))    });    found.sort_by(|a, b| b.connected.cmp(&a.connected).then_with(|| folded(&a.name).cmp(&folded(&b.name))));    let writable = can_write(&heard);    let mut out = Vec::new();    if let Some(email) = email_key(&typed) {        if !found.iter().any(|f| f.email.as_deref() == Some(email.as_str())) {            let via = route(None, Some(&email), false, writable).unwrap_or(Via::None);            out.push(json!({ "key": format!("email:{email}"), "name": email, "detail": email, "via": via.word(), "email": email }));        }    }    for f in found.into_iter() {        if out.len() >= FOUND {            break;        }        let via = route(f.number.as_deref(), f.email.as_deref(), f.connected, writable).unwrap_or(Via::None);        let key = match (&f.number, &f.email) {            (Some(n), _) if via == Via::Cotton => format!("number:{n}"),            (_, Some(e)) => format!("email:{e}"),            (Some(n), None) => format!("number:{n}"),            _ => continue,        };        let mut row = json!({ "key": key, "name": f.name, "detail": detail(f.email.as_deref(), via)?, "via": via.word() });        if let Some(email) = &f.email {            row["email"] = json!(email);        }        if let Some(number) = &f.number {            row["number"] = json!(number);        }        out.push(row);    }    Ok(json!({ "rows": out }))}/// One person as the sheet sends them back in `people`.#[derive(Debug, Clone)]pub struct Wanted {    pub email: Option<String>,    pub number: Option<String>,    pub name: Option<String>,}pub fn wanted_list(request: &Value) -> Result<Option<Vec<Wanted>>, MethodError> {    let Some(list) = request.get("people") else { return Ok(None) };    let list = list.as_array().ok_or_else(|| MethodError::new("bad_request", "`people` is the whole list of people on the event"))?;    let mut out: Vec<Wanted> = Vec::new();    for person in list {        let key = person["key"].as_str().unwrap_or_default();        let email = person["email"].as_str().and_then(email_key).or_else(|| key.strip_prefix("email:").and_then(email_key));        let number = person["number"].as_str().map(str::to_string).or_else(|| key.strip_prefix("number:").map(str::to_string)).filter(|n| !n.is_empty());        if email.is_none() && number.is_none() {            return Err(MethodError::new("bad_request", "Each person needs an email address, or to be one of your people on Cotton."));        }        let name = person["name"].as_str().map(str::to_string).filter(|n| !n.trim().is_empty());        if out.iter().any(|w| (w.email.is_some() && w.email == email) || (w.number.is_some() && w.number == number)) {            continue;        }        out.push(Wanted { email, number, name });    }    Ok(Some(out))}fn same(guest: &Guest, wanted: &Wanted) -> bool {    (guest.phone.is_some() && guest.phone == wanted.number) || (guest.email.is_some() && guest.email == wanted.email)}/// What a new list changes against the event: who is added, who is taken off.pub struct Diff {    pub added: Vec<(Wanted, Via)>,    pub removed: Vec<Guest>,}pub fn diff(held: &[Guest], wanted: &[Wanted], heard: &Heard) -> Diff {    let standing: Vec<&Guest> = held.iter().filter(|g| !g.removed && !g.organizer).collect();    let writable = can_write(heard);    let added = wanted        .iter()        .filter(|w| !standing.iter().any(|g| same(g, w)))        .map(|w| {            let connected = w.number.as_deref().is_some_and(|n| heard.is_connected(n).unwrap_or(true));            (w.clone(), route(w.number.as_deref(), w.email.as_deref(), connected, writable).unwrap_or(Via::None))        })        .collect();    let removed = standing.into_iter().filter(|g| !wanted.iter().any(|w| same(g, w))).cloned().collect();    Diff { added, removed }}fn shown_wanted(w: &Wanted) -> String {    w.name.clone().or_else(|| w.email.clone()).or_else(|| w.number.clone()).unwrap_or_default()}/// The lines saving `wanted` would say (CONTRACT.md section 15 `days.tell`).pub fn tells(held: &[Guest], wanted: &[Wanted], heard: &Heard, moved: bool) -> Result<Vec<String>, MethodError> {    let change = diff(held, wanted, heard);    let mut out = Vec::new();    for (w, via) in &change.added {        let name = shown_wanted(w);        out.push(match via {            Via::Cotton => say("people.tell_cotton", &[("name", &name)])?,            Via::Google => say("people.tell_google", &[("name", &name)])?,            Via::None => say("people.tell_waits", &[("name", &name)])?,        });    }    for g in &change.removed {        let told = match g.via {            Via::Cotton => g.sent.is_some(),            _ => true,        };        if !told {            continue;        }        let name = g.shown();        out.push(match g.via {            Via::Cotton => say("people.tell_off_cotton", &[("name", &name)])?,            _ => say("people.tell_off_google", &[("name", &name)])?,        });    }    let staying = held.iter().any(|g| !g.removed && !g.organizer && !change.removed.iter().any(|r| r.id == g.id));    if moved && staying {        out.push(line("people.tell_change")?);    }    Ok(out)}/// The Delete ask's line for an event with people: "Priya and Akash are told it is off."/// Only people who were told of the event are told it is off: by Cotton once their invitation went, by Google once/// the event is at Google (the emulator walk, 22 Nov 2026: someone never invited, signed out, was "told it is off").pub fn delete_tells(held: &[Guest], at_google: bool) -> Result<Value, MethodError> {    let told: Vec<String> = held        .iter()        .filter(|g| !g.removed && !g.organizer)        .filter(|g| match g.via {            Via::Cotton => g.sent.is_some(),            _ => at_google && g.email.is_some(),        })        .map(Guest::shown)        .collect();    Ok(match told.len() {        0 => Value::Null,        1 => json!(say("people.delete_tells_one", &[("name", &told[0])])?),        _ => json!(say("people.delete_tells", &[("names", &names(&told))])?),    })}/// Lays the new list on the event: new rows for the added, the removed taken off (kept, marked, until told, when/// they were told anything). Answers whether Google must hear of it.pub fn set(ctx: &mut Ctx<'_>, event: &str, wanted: &[Wanted], heard: &Heard) -> Result<bool, MethodError> {    let held = guests(ctx, event)?;    let change = diff(&held, wanted, heard);    let now = now_iso(ctx);    let has = |ctx: &Ctx<'_>, c: &str| holds(ctx, ATTENDEES, c);    if !has(ctx, "via")? {        return Err(MethodError::new("write_refused", "this copy keeps no people on events yet"));    }    let mut google = false;    for (w, via) in &change.added {        let mut row = Map::new();        row.insert("event_id".into(), json!(event));        row.insert("email".into(), w.email.clone().map_or(Value::Null, Value::from));        row.insert("phone".into(), if *via == Via::Cotton { w.number.clone().map_or(Value::Null, Value::from) } else { Value::Null });        row.insert("display_name".into(), w.name.clone().map_or(Value::Null, Value::from));        row.insert("response".into(), json!("needs_action"));        row.insert("via".into(), json!(if *via == Via::Cotton { "cotton" } else { "google" }));        let id = ctx.new_uuid();        insert_row(ctx, ATTENDEES, &id, row).map_err(tool)?;        google |= *via != Via::Cotton;    }    for g in &change.removed {        let told = match g.via {            Via::Cotton => g.sent.is_some() && g.sent.as_deref() != Some("off"),            _ => false,        };        if told {            let mut patch = Map::new();            patch.insert("removed_at".into(), json!(now));            update_row(ctx, ATTENDEES, &g.id, patch).map_err(tool)?;        } else {            ctx.writer().map_err(tool)?.retract(ATTENDEES, &g.id, cotton_tools::mcp::writer::Retract::Relation);        }        google |= g.via != Via::Cotton;    }    ctx.commit().map_err(tool)?;    Ok(google)}/// Google's guests laid down as rows, once, before a Google event's list is first changed here: from then on the/// rows are the list Days sends.pub fn adopt_google(ctx: &mut Ctx<'_>, event: &str, raw: Option<&str>) -> Result<(), MethodError> {    if !guests(ctx, event)?.is_empty() {        return Ok(());    }    for g in google_guests(raw).into_iter().filter(|g| !g.me && !g.organizer) {        let mut row = Map::new();        row.insert("event_id".into(), json!(event));        row.insert("email".into(), json!(g.email));        row.insert("display_name".into(), g.name.map_or(Value::Null, Value::from));        row.insert("response".into(), json!(match g.answer.as_deref() { Some("accepted") => "accepted", Some("tentative") => "tentative", Some("declined") => "declined", _ => "needs_action" }));        row.insert("via".into(), json!("google"));        let id = ctx.new_uuid();        insert_row(ctx, ATTENDEES, &id, row).map_err(tool)?;    }    Ok(())}#[cfg(test)]#[path = "days_people_tests.rs"]mod tests;