Cotton code
822 lines · 38.9 KB · RustRaw
//! Cotton Contacts on this phone (PEOPLE-DESIGN.md section f): the home with its//! tiers, the person page, add and edit, and reading the phone's address book.//! Groups, pin and archive are `contacts_groups`; pin//! writes `person_state.pinned`, which the tiers read here. The answers are the ones `assets/design/shared/CONTACTS-ANSWERS.md`//! fixes for both shells; every word comes from the `contacts` line set.//!//! **What it reads.** The contact tables only: `person`, `person_handle`,//! `shared_handle`, `person_source`, `person_state` (kind, Close pin, merges),//! `person_fact` (one sealed line per person per app, which Comms, Post, Days and//! Albums write: Contacts never reads another app's tables), and the groups of//! people (`cotton_groups` with `table_id = 'person'`, and `group_origin`).//! The kit tables are laid where the kit is: a copy that does not hold one yet//! reads as holding none of its rows.//!//! **The tiers** are written rules over both directions (f.1), [`tier`]://! Close (he and they wrote or called each other in at least 3 of the last 8//! weeks, or he keeps them there), Often (10 or more exchanges in 90 days),//! Now and then (any exchange he took part in this year), Everyone else.//! Someone who writes and is never answered never rises: `took_part` is required.use std::collections::{BTreeMap, HashMap};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_core::keys::app::list::{fold, say};use cotton_core::rules::people::handles::HandleSource;use cotton_core::rules::shell_lines::LineSet;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};use super::cotton_chat::{read, rows, write, ws};use crate::methods::MethodError;use crate::shell::client::ClientController;/// Every method this module answers.pub const METHODS: &[&str] = &[    "contacts.home",    "contacts.person",    "contacts.add.form",    "contacts.edit.form",    "contacts.add",    "contacts.edit",    "contacts.read",    "contacts.circle",    "contacts.facts",];/// The kit tables Contacts keeps (local names).pub(crate) const STATE: &str = "cotton_person_state";pub(crate) const FACTS: &str = "cotton_person_fact";pub(crate) const SOURCES: &str = "cotton_person_source";const SHARED: &str = cotton_store::protocol::who::SHARED_TABLE;pub fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "contacts.home" => home(client, request),        "contacts.person" => person(client, request),        "contacts.add.form" => Ok(form(None)),        "contacts.edit.form" => edit_form(client, request),        "contacts.add" => add(client, request),        "contacts.edit" => edit(client, request),        "contacts.read" => read_book(client, request),        "contacts.facts" => super::contacts_facts::count(client),        "contacts.circle" => Ok(json!({ "title": s("circle.title"), "empty": { "title": s("circle.soon"), "message": s("circle.soon_message") } })),        other => Err(MethodError::new("unknown_method", format!("{other} is not a Contacts method"))),    }}// ── words and small helpers ────────────────────────────────────────────fn lines() -> &'static LineSet {    static LINES: std::sync::OnceLock<LineSet> = std::sync::OnceLock::new();    LINES.get_or_init(|| LineSet::shipped("contacts").expect("the kit ships the contacts line set"))}pub(crate) fn s(line: &str) -> String {    say(lines(), line, &[])}pub(crate) fn sf(line: &str, fills: &[(&str, &str)]) -> String {    say(lines(), line, fills)}fn bad(why: &str) -> MethodError {    MethodError::new("bad_request", why)}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn str_of<'a>(row: &'a Map<String, Value>, key: &str) -> Option<&'a str> {    row.get(key).and_then(Value::as_str).filter(|v| !v.is_empty())}fn int_of(row: &Map<String, Value>, key: &str) -> i64 {    row.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f as i64)).or_else(|| v.as_bool().map(i64::from))).unwrap_or(0)}fn initials(name: &str) -> String {    cotton_core::messages::app::lay::initials(name)}fn call_of(method: &str, request: Value) -> Value {    json!({ "method": method, "request": request })}/// Whether this copy holds a table (a kit table is laid where its kit is).pub(crate) fn held(ctx: &mut Ctx<'_>, table: &str) -> bool {    ctx.db().get("SELECT 1 AS one FROM sqlite_master WHERE type = 'table' AND name = ?", &[text(table)]).ok().flatten().is_some()}fn now_ms(ctx: &Ctx<'_>) -> i64 {    cotton_tools::mcp::handlers::common::now_ms(ctx)}fn iso_now(ctx: &Ctx<'_>) -> String {    chrono::DateTime::from_timestamp_millis(now_ms(ctx)).unwrap_or_default().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}fn ms_of(at: &str) -> Option<i64> {    chrono::DateTime::parse_from_rfc3339(at).ok().map(|t| t.timestamp_millis()).or_else(|| {        chrono::NaiveDate::parse_from_str(at.get(..10)?, "%Y-%m-%d").ok().map(|d| d.and_hms_opt(12, 0, 0).unwrap_or_default().and_utc().timestamp_millis())    })}fn tool(error: cotton_tools::mcp::protocol::ToolFailure) -> String {    error.to_string()}// ── the tiers (f.1) ────────────────────────────────────────────────────/// What the apps' lines say about one person, summed over apps.#[derive(Debug, Clone, Default, PartialEq)]pub struct Facts {    pub count_90d: i64,    pub count_year: i64,    pub weeks_8: i64,    pub took_part: bool,    pub last_ms: Option<i64>,}#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]pub enum Tier {    Close,    Often,    Now,    Rest,}impl Tier {    pub fn id(self) -> &'static str {        match self {            Tier::Close => "close",            Tier::Often => "often",            Tier::Now => "now",            Tier::Rest => "rest",        }    }}/// The written rule (f.1): a pin keeps someone in Close; otherwise only an exchange he took part in raises anyone.pub fn tier(facts: &Facts, pinned: bool) -> Tier {    if pinned {        return Tier::Close;    }    if !facts.took_part {        return Tier::Rest;    }    if facts.weeks_8 >= 3 {        Tier::Close    } else if facts.count_90d >= 10 {        Tier::Often    } else if facts.count_year > 0 {        Tier::Now    } else {        Tier::Rest    }}/// When they last talked, in the line set's words.pub fn when_words(last_ms: i64, now_ms: i64) -> String {    let day = 86_400_000;    let days = (now_ms.div_euclid(day)) - (last_ms.div_euclid(day));    let key = match days {        i64::MIN..=0 => "today",        1 => "yesterday",        2..=6 => "week",        7..=13 => "last_week",        14..=30 => "month",        31..=365 => "earlier",        _ => "long",    };    s(&format!("when.{key}"))}// ── reads ──────────────────────────────────────────────────────────────/// One contact as the lists read it.#[derive(Debug, Clone)]struct Row {    id: String,    name: String,    picture: Option<String>,    kind: String,    pinned: bool,    facts: Facts,    group: Option<String>,}fn facts_by_person(ctx: &mut Ctx<'_>) -> Result<HashMap<String, Facts>, String> {    if !held(ctx, FACTS) {        return Ok(HashMap::new());    }    let found = rows(        ctx,        &format!(            "SELECT person, SUM(coalesce(count_90d, 0)) AS n90, SUM(coalesce(count_year, 0)) AS ny, MAX(coalesce(weeks_8, 0)) AS w8, \             MAX(coalesce(took_part, 0)) AS took, MAX(last) AS last FROM {FACTS} WHERE workspace_id = ? AND deleted_at IS NULL GROUP BY person"        ),        &[ws(ctx)],    )?;    Ok(found        .into_iter()        .filter_map(|row| {            let person = str_of(&row, "person")?.to_string();            Some((                person,                Facts {                    count_90d: int_of(&row, "n90"),                    count_year: int_of(&row, "ny"),                    weeks_8: int_of(&row, "w8"),                    took_part: int_of(&row, "took") > 0,                    last_ms: str_of(&row, "last").and_then(ms_of),                },            ))        })        .collect())}/// Every living contact (not binned, not archived, not merged away), with its kind and pin.fn contacts(ctx: &mut Ctx<'_>) -> Result<Vec<Row>, String> {    let state = held(ctx, STATE);    let (state_cols, state_join) = if state {        (            "coalesce(st.kind, 'person') AS kind, coalesce(st.pinned, 0) AS pinned",            format!("LEFT JOIN {STATE} st ON st.person = p.id AND st.deleted_at IS NULL"),        )    } else {        ("'person' AS kind, 0 AS pinned", String::new())    };    let away = super::contacts_same::merged_away(ctx)?;    let people: Vec<Map<String, Value>> = rows(        ctx,        &format!(            "SELECT p.id AS id, p.full_name AS name, p.avatar_key AS picture, {state_cols} FROM cotton_people p {state_join} \             WHERE p.workspace_id = ? AND p.trashed_at IS NULL AND p.archived_at IS NULL"        ),        &[ws(ctx)],    )?    .into_iter()    .filter(|r| str_of(r, "id").is_some_and(|id| !away.contains_key(id)))    .collect();    let groups = first_groups(ctx)?;    let mut facts = facts_by_person(ctx)?;    Ok(people        .into_iter()        .filter_map(|row| {            let id = str_of(&row, "id")?.to_string();            Some(Row {                name: str_of(&row, "name").unwrap_or_default().trim().to_string(),                picture: str_of(&row, "picture").map(str::to_string),                kind: str_of(&row, "kind").unwrap_or("person").to_string(),                pinned: int_of(&row, "pinned") > 0,                facts: facts.remove(&id).unwrap_or_default(),                group: groups.get(&id).cloned(),                id,            })        })        .collect())}/// Each person's first group by name.fn first_groups(ctx: &mut Ctx<'_>) -> Result<HashMap<String, String>, String> {    let found = rows(        ctx,        "SELECT m.record_id AS person, MIN(g.name) AS name FROM cotton_group_members m JOIN cotton_groups g ON g.id = m.group_id \         WHERE g.workspace_id = ? AND g.table_id = 'person' AND g.deleted_at IS NULL GROUP BY m.record_id",        &[ws(ctx)],    )?;    Ok(found.into_iter().filter_map(|r| Some((str_of(&r, "person")?.to_string(), str_of(&r, "name")?.to_string()))).collect())}fn row_json(row: &Row, now: i64) -> Value {    let mut detail: Vec<String> = Vec::new();    if let Some(last) = row.facts.last_ms {        detail.push(when_words(last, now));    }    if let Some(group) = &row.group {        detail.push(group.clone());    }    json!({        "id": row.id,        "words": row.name,        "detail": (!detail.is_empty()).then(|| detail.join(" · ")),        "initials": initials(&row.name),        "picture": row.picture,        "kind": row.kind,        "call": call_of("contacts.person", json!({ "id": row.id })),    })}/// The ids of the contacts whose numbers or addresses hold `query` (digits for a number, else text).fn by_handle(ctx: &mut Ctx<'_>, query: &str) -> Result<Vec<String>, String> {    let digits: String = query.chars().filter(char::is_ascii_digit).collect();    let needle = if digits.len() >= 3 && !query.contains('@') { digits } else { query.trim().to_lowercase() };    if needle.len() < 3 {        return Ok(Vec::new());    }    let like = format!("%{needle}%");    let mut sql = "SELECT person_id AS id FROM cotton_person_handles WHERE workspace_id = ?1 AND trashed_at IS NULL AND normalised LIKE ?2".to_string();    if cotton_store::protocol::who::shared_held(ctx.db()) {        sql.push_str(&format!(" UNION SELECT person AS id FROM {SHARED} WHERE workspace_id = ?1 AND deleted_at IS NULL AND normalised LIKE ?2"));    }    Ok(rows(ctx, &sql, &[ws(ctx), text(&like)])?.into_iter().filter_map(|r| str_of(&r, "id").map(str::to_string)).collect())}fn home(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let kind = request.get("kind").and_then(Value::as_str).unwrap_or("all").to_string();    if !["all", "person", "organisation", "assistant"].contains(&kind.as_str()) {        return Err(bad("kind is all, person, organisation or assistant"));    }    let query = request.get("query").and_then(Value::as_str).unwrap_or("").trim().to_string();    read(client, "contacts.home", |ctx| {        let now = now_ms(ctx);        let all = contacts(ctx)?;        let any = !all.is_empty();        let mut list: Vec<Row> = all.into_iter().filter(|r| kind == "all" || r.kind == kind).collect();        let kinds: Vec<Value> = ["all", "person", "organisation", "assistant"]            .iter()            .map(|id| json!({ "id": id, "words": s(&format!("kind.{id}")), "on": *id == kind, "call": call_of("contacts.home", json!({ "kind": id })) }))            .collect();        let sections: Vec<Value> = if !query.is_empty() {            let folded = fold(&query.to_lowercase());            let handles: std::collections::HashSet<String> = by_handle(ctx, &query)?.into_iter().collect();            list.retain(|r| fold(&r.name.to_lowercase()).contains(&folded) || handles.contains(&r.id));            list.sort_by(|a, b| fold(&a.name.to_lowercase()).cmp(&fold(&b.name.to_lowercase())));            let rows: Vec<Value> = list.iter().map(|r| row_json(r, now)).collect();            vec![json!({ "id": "found", "title": s("home.found"), "count": rows.len(), "rows": rows })]        } else {            let mut tiers: BTreeMap<Tier, Vec<Row>> = BTreeMap::new();            for row in list {                tiers.entry(tier(&row.facts, row.pinned)).or_default().push(row);            }            tiers                .into_iter()                .map(|(t, mut rows)| {                    if t == Tier::Rest {                        rows.sort_by(|a, b| fold(&a.name.to_lowercase()).cmp(&fold(&b.name.to_lowercase())));                    } else {                        rows.sort_by(|a, b| b.facts.last_ms.cmp(&a.facts.last_ms).then_with(|| a.name.cmp(&b.name)));                    }                    let drawn: Vec<Value> = rows.iter().map(|r| row_json(r, now)).collect();                    json!({ "id": t.id(), "title": s(&format!("tier.{}", t.id())), "count": drawn.len(), "rows": drawn })                })                .collect()        };        let read_before = held(ctx, SOURCES)            && !rows(ctx, &format!("SELECT 1 AS one FROM {SOURCES} WHERE workspace_id = ? AND kind = 'address_book' AND deleted_at IS NULL LIMIT 1"), &[ws(ctx)])?.is_empty();        let empty = (!any).then(|| json!({ "title": s("home.empty_title"), "message": s("home.empty_message") }));        let nothing = (!query.is_empty() && sections.first().and_then(|f| f["count"].as_u64()) == Some(0)).then(|| json!({ "title": s("home.nothing_found") }));        let same = super::contacts_same::count(ctx)?;        // Before every app's lines are counted once (a first rebuild, on the sync pass), the tiers are not yet right.        let sorting = super::contacts_facts::sorting(ctx)?.then(|| s("home.sorting"));        Ok(json!({            "title": s("home.title"),            "search": { "placeholder": s("home.search"), "query": query },            "kinds": kinds,            "sorting": sorting,            "same": (same > 0).then(|| json!({                "words": if same == 1 { s("home.same_one") } else { sf("home.same", &[("count", &same.to_string())]) },                "act": s("home.review"),                "call": call_of("contacts.same.list", json!({})),            })),            "sections": if any { Value::from(sections) } else { json!([]) },            "add": { "words": s("home.add"), "call": call_of("contacts.add.form", json!({})) },            "import": (!read_before).then(|| json!({ "words": s("home.import"), "hint": s("home.import_hint") })),            "empty": empty.or(nothing),        }))    })}/// One person's handles, each with whoever else holds it.fn reach(ctx: &mut Ctx<'_>, id: &str) -> Result<Vec<Value>, String> {    let mut sql = "SELECT h.id AS id, h.kind AS kind, h.value AS value, h.normalised AS normalised, 'own' AS whose FROM cotton_person_handles h \                   WHERE h.workspace_id = ?1 AND h.person_id = ?2 AND h.trashed_at IS NULL"        .to_string();    if cotton_store::protocol::who::shared_held(ctx.db()) {        sql.push_str(&format!(" UNION ALL SELECT s.id AS id, s.kind AS kind, s.value AS value, s.normalised AS normalised, 'shared' AS whose FROM {SHARED} s WHERE s.workspace_id = ?1 AND s.person = ?2 AND s.deleted_at IS NULL"));    }    sql.push_str(" ORDER BY kind DESC, value");    let mut found = rows(ctx, &sql, &[ws(ctx), text(id)])?;    // A contact merged into this one whose move the object has not synced yet: its ways to reach show here already.    let merged = super::contacts_same::merged_into_keep(ctx, id)?;    for drop in &merged {        found.extend(rows(ctx, &sql, &[ws(ctx), text(drop)])?);    }    // One line per number or address: a share of one this contact also holds (or took in by a merge) is said once.    let mut seen = std::collections::HashSet::new();    found.sort_by_key(|row| str_of(row, "whose") != Some("own"));    found.retain(|row| seen.insert((str_of(row, "kind").unwrap_or_default().to_string(), str_of(row, "normalised").unwrap_or_default().to_string())));    found.sort_by(|x, y| str_of(y, "kind").cmp(&str_of(x, "kind")).then_with(|| str_of(x, "value").cmp(&str_of(y, "value"))));    let workspace = ctx.workspace_id.to_string();    let labels = super::contacts_labels::labels_of(ctx, id)?;    let mut out = Vec::new();    for row in found {        let (Some(handle), Some(kind), Some(value)) = (str_of(&row, "id"), str_of(&row, "kind"), str_of(&row, "value")) else { continue };        let normalised = str_of(&row, "normalised").unwrap_or_default();        let others: Vec<String> = match cotton_store::protocol::who::who(ctx.db(), &workspace, kind, normalised).map_err(|e| e.to_string())? {            cotton_store::protocol::who::Who::Shared(holders) => holders.into_iter().filter(|h| h.id != id && !merged.contains(&h.id)).map(|h| h.full_name).collect(),            _ => Vec::new(),        };        // His label for it (CONTACT KINDS), else the kind's word.        let label = labels.get(handle).cloned();        let kind_words = label.clone().unwrap_or_else(|| if kind == "email" { s("person.email") } else { s("person.mobile") });        let detail = if others.is_empty() { kind_words } else { sf("person.also", &[("names", &others.join(" & "))]) };        let remove = json!({ "id": "remove", "words": s("person.remove_handle"), "red": true,            "call": call_of("contacts.edit", json!({ "id": id, "removeHandle": handle })) });        out.push(json!({ "id": handle, "kind": kind, "words": value, "detail": detail, "label": label, "shared": (!others.is_empty()).then_some(others), "acts": [remove] }));    }    Ok(out)}fn person(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request.get("id").and_then(Value::as_str).ok_or_else(|| bad("id names the contact"))?.to_string();    read(client, "contacts.person", |ctx| {        let Some(p) = rows(ctx, "SELECT id, full_name, avatar_key, archived_at FROM cotton_people WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL", &[ws(ctx), text(&id)])?.into_iter().next() else {            return Err(format!("no contact {id}"));        };        let name = str_of(&p, "full_name").unwrap_or_default().trim().to_string();        let state = state_of(ctx, &id)?;        let kind = state.as_ref().and_then(|s| str_of(s, "kind")).unwrap_or("person").to_string();        let pinned = state.as_ref().map(|s| int_of(s, "pinned") > 0).unwrap_or(false);        let merged_into = super::contacts_same::merged_away(ctx)?.remove(&id);        let archived = str_of(&p, "archived_at").is_some();        let now = now_ms(ctx);        let facts = facts_by_person(ctx)?.remove(&id).unwrap_or_default();        let tier_words = s(&format!("tier.{}", tier(&facts, pinned).id()));        let groups = rows(            ctx,            "SELECT g.id AS id, g.name AS name FROM cotton_group_members m JOIN cotton_groups g ON g.id = m.group_id \             WHERE g.workspace_id = ? AND g.table_id = 'person' AND g.deleted_at IS NULL AND m.record_id = ? ORDER BY g.name",            &[ws(ctx), text(&id)],        )?;        let group_rows: Vec<Value> = groups            .iter()            .filter_map(|g| Some(json!({ "id": str_of(g, "id")?, "words": str_of(g, "name")?, "call": call_of("contacts.group", json!({ "id": str_of(g, "id")? })) })))            .collect();        let mut subtitle = vec![tier_words];        if let Some(first) = groups.first().and_then(|g| str_of(g, "name")) {            subtitle.push(first.to_string());        }        if archived {            subtitle.push(s("person.archived"));        }        let mut acts = vec![json!({ "id": "edit", "words": s("person.edit"), "call": call_of("contacts.edit.form", json!({ "id": id })) })];        acts.push(if pinned {            json!({ "id": "unpin", "words": s("person.unpin"), "call": call_of("contacts.pin", json!({ "id": id, "on": false })) })        } else {            json!({ "id": "pin", "words": s("person.pin"), "call": call_of("contacts.pin", json!({ "id": id, "on": true })) })        });        if super::contacts_same::can_unmerge(ctx, &id, now)? {            acts.push(json!({ "id": "unmerge", "words": s("person.unmerge"), "call": call_of("contacts.unmerge", json!({ "id": id })) }));        }        acts.push(if archived {            json!({ "id": "unarchive", "words": s("person.unarchive"), "call": call_of("contacts.unarchive", json!({ "id": id })) })        } else {            json!({ "id": "archive", "words": s("person.archive"), "red": true, "confirm": sf("person.archive_confirm", &[("name", &name)]),                    "call": call_of("contacts.archive", json!({ "id": id })) })        });        Ok(json!({            "id": id,            "kind": kind,            "title": name,            "initials": initials(&name),            "picture": str_of(&p, "avatar_key"),            "subtitle": subtitle.join(" · "),            "archived": archived,            "mergedInto": merged_into,            "between": between(ctx, &id, now)?,            "reach": reach(ctx, &id)?,            "groups": group_rows,            "organisation": organisation_row(ctx, &id)?,            "sources": sources(ctx, &id)?,            "same": super::contacts_same::pairs_of(ctx, &id)?,            "pinned": pinned,            "acts": acts,        }))    })}/// Between you, per app: the person's fact lines, said.fn between(ctx: &mut Ctx<'_>, id: &str, now: i64) -> Result<Vec<Value>, String> {    if !held(ctx, FACTS) {        return Ok(Vec::new());    }    let found = rows(        ctx,        &format!("SELECT app, SUM(coalesce(count, 0)) AS n, MAX(last) AS last FROM {FACTS} WHERE workspace_id = ? AND person = ? AND deleted_at IS NULL GROUP BY app"),        &[ws(ctx), text(id)],    )?;    let order = ["comms", "post", "days", "albums", "health"];    let mut by_app: BTreeMap<usize, Value> = BTreeMap::new();    for row in found {        let Some(app) = str_of(&row, "app") else { continue };        let Some(place) = order.iter().position(|a| *a == app) else { continue };        let n = int_of(&row, "n").to_string();        let when = str_of(&row, "last").and_then(ms_of).map(|last| when_words(last, now)).unwrap_or_default();        let detail = match app {            "comms" => sf("person.messages", &[("count", &n), ("when", &when)]),            "post" => sf("person.mails", &[("count", &n), ("when", &when)]),            "days" => sf("person.events", &[("count", &n)]),            "albums" => sf("person.photos", &[("count", &n)]),            _ => s("person.health"),        };        let words = match app {            "comms" => "Comms",            "post" => "Post",            "days" => "Days",            "albums" => "Albums",            _ => "Health",        };        by_app.insert(place, json!({ "app": app, "words": words, "detail": detail, "open": { "app": app, "person": id } }));    }    Ok(by_app.into_values().collect())}/// The organisation a person's address is at (one Contacts made from that domain, living, and not this contact):/// `{id, words, call}`, or null.fn organisation_row(ctx: &mut Ctx<'_>, id: &str) -> Result<Value, String> {    let addresses = rows(ctx, "SELECT normalised FROM cotton_person_handles WHERE workspace_id = ? AND person_id = ? AND kind = 'email' AND trashed_at IS NULL ORDER BY position, id", &[ws(ctx), text(id)])?;    for row in addresses {        let Some(domain) = str_of(&row, "normalised").and_then(|a| a.rsplit_once('@')).map(|(_, d)| d.to_lowercase()) else { continue };        let Some(org) = super::contacts_facts::organisation_of(ctx, &domain)? else { continue };        if org == id {            continue;        }        if let Some(found) = rows(ctx, "SELECT full_name FROM cotton_people WHERE id = ? AND trashed_at IS NULL AND archived_at IS NULL", &[text(&org)])?.into_iter().next() {            let words = str_of(&found, "full_name").unwrap_or_default().to_string();            return Ok(json!({ "id": org, "words": words, "call": call_of("contacts.person", json!({ "id": org })) }));        }    }    Ok(Value::Null)}fn sources(ctx: &mut Ctx<'_>, id: &str) -> Result<Vec<Value>, String> {    if !held(ctx, SOURCES) {        return Ok(Vec::new());    }    let mut found = rows(ctx, &format!("SELECT kind, name FROM {SOURCES} WHERE workspace_id = ? AND person = ? AND deleted_at IS NULL ORDER BY first_seen, id"), &[ws(ctx), text(id)])?;    // A contact merged into this one: where it came from too, until the object moves its sources (Android, 28 Nov).    for drop in super::contacts_same::merged_into_keep(ctx, id)? {        found.extend(rows(ctx, &format!("SELECT kind, name FROM {SOURCES} WHERE workspace_id = ? AND person = ? AND deleted_at IS NULL ORDER BY first_seen, id"), &[ws(ctx), text(&drop)])?);    }    let mut seen = std::collections::HashSet::new();    found.retain(|row| seen.insert((str_of(row, "kind").unwrap_or_default().to_string(), str_of(row, "name").unwrap_or_default().to_string())));    Ok(found        .iter()        .map(|row| {            let words = match str_of(row, "kind").unwrap_or_default() {                "address_book" => s("person.from_contacts"),                "whatsapp" => s("person.from_whatsapp"),                "cotton" => s("person.from_cotton"),                "mail" | "mail_domain" => s("person.from_mail"),                "photos" => s("person.from_photos"),                "health" => s("person.from_health"),                _ => s("person.from_you"),            };            json!({ "words": words, "detail": str_of(row, "name") })        })        .collect())}pub(crate) fn state_of(ctx: &mut Ctx<'_>, id: &str) -> Result<Option<Map<String, Value>>, String> {    if !held(ctx, STATE) {        return Ok(None);    }    Ok(rows(ctx, &format!("SELECT * FROM {STATE} WHERE workspace_id = ? AND person = ? AND deleted_at IS NULL"), &[ws(ctx), text(id)])?.into_iter().next())}/// The id a contact's state row has: one per contact.pub(crate) fn state_id(ctx: &Ctx<'_>, person: &str) -> String {    cotton_core::cotton_rules::ids::derived_id("person_state", &[&ctx.file.namespace().to_string(), person])}/// Write `patch` onto a contact's state row, making it the first time.pub(crate) fn put_state(ctx: &mut Ctx<'_>, person: &str, patch: Map<String, Value>) -> Result<(), String> {    if !held(ctx, STATE) {        return Err("this copy does not hold Contacts' tables yet; sync once and try again".into());    }    let id = state_id(ctx, person);    let there = rows(ctx, &format!("SELECT id FROM {STATE} WHERE id = ?"), &[text(&id)])?.into_iter().next().is_some();    let now = iso_now(ctx);    let mut patch = patch;    patch.insert("updated_at".into(), Value::from(now.clone()));    if there {        update_row(ctx, STATE, &id, patch).map_err(tool)?;    } else {        patch.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()));        patch.insert("person".into(), Value::from(person));        patch.insert("created_at".into(), Value::from(now));        insert_row(ctx, STATE, &id, patch).map_err(tool)?;    }    Ok(())}// ── add, edit, pin, archive ────────────────────────────────────────────fn form(person: Option<(&str, &str, &str, Vec<String>, Vec<String>)>) -> Value {    let (id, name, kind, phones, emails) = person.unwrap_or(("", "", "person", Vec::new(), Vec::new()));    let editing = !id.is_empty();    json!({        "title": if editing { s("form.edit") } else { s("form.new") },        "kinds": [ { "id": "person", "words": s("form.person"), "on": kind != "organisation" },                   { "id": "organisation", "words": s("form.organisation"), "on": kind == "organisation" } ],        "fields": [            { "id": "name", "words": s("form.name"), "value": name },            { "id": "phones", "words": s("form.phone"), "values": phones, "add": s("form.add_phone") },            { "id": "emails", "words": s("form.email"), "values": emails, "add": s("form.add_email") },        ],        "save": if editing {            json!({ "words": s("form.save"), "call": call_of("contacts.edit", json!({ "id": id })) })        } else {            json!({ "words": s("form.save"), "call": call_of("contacts.add", json!({})) })        },    })}fn edit_form(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request.get("id").and_then(Value::as_str).ok_or_else(|| bad("id names the contact"))?.to_string();    read(client, "contacts.edit.form", |ctx| {        let Some(p) = rows(ctx, "SELECT full_name FROM cotton_people WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL", &[ws(ctx), text(&id)])?.into_iter().next() else {            return Err(format!("no contact {id}"));        };        let kind = state_of(ctx, &id)?.and_then(|s| str_of(&s, "kind").map(str::to_string)).unwrap_or_else(|| "person".into());        let mut phones = Vec::new();        let mut emails = Vec::new();        let (mut phone_labels, mut email_labels) = (Vec::new(), Vec::new());        for h in reach(ctx, &id)? {            let value = h["words"].as_str().unwrap_or_default().to_string();            if h["kind"] == "email" {                emails.push(value);                email_labels.push(h["label"].clone());            } else if h["kind"] == "phone" {                phones.push(value);                phone_labels.push(h["label"].clone());            }        }        let mut answer = form(Some((&id, str_of(&p, "full_name").unwrap_or_default(), &kind, phones, emails)));        // Each value's label beside it, in the same order (null: none).        answer["fields"][1]["labels"] = Value::from(phone_labels);        answer["fields"][2]["labels"] = Value::from(email_labels);        Ok(answer)    })}fn strings(request: &Value, key: &str) -> Option<Vec<String>> {    entries(request, key).map(|list| list.into_iter().map(|(value, _)| value).collect())}/// A request's numbers or addresses, each a string or `{value, label?}` (CONTACT KINDS: labels).fn entries(request: &Value, key: &str) -> Option<Vec<(String, Option<String>)>> {    request.get(key).and_then(Value::as_array).map(|list| list.iter().filter_map(super::contacts_labels::entry).collect())}fn kind_arg(request: &Value) -> Result<Option<String>, MethodError> {    match request.get("kind").and_then(Value::as_str) {        None => Ok(None),        Some(kind @ ("person" | "organisation")) => Ok(Some(kind.to_string())),        Some("assistant") => Err(bad("an assistant is not made here")),        Some(_) => Err(bad("kind is person or organisation")),    }}fn add(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let name = request.get("name").and_then(Value::as_str).map(str::trim).unwrap_or("").to_string();    if name.is_empty() {        return Ok(json!({ "error": s("form.no_name") }));    }    let kind = kind_arg(request)?;    let phones = strings(request, "phones").unwrap_or_default();    let emails = strings(request, "emails").unwrap_or_default();    write(client, "contacts.add", |ctx| {        let id = ctx.new_uuid();        let mut patch = Map::new();        patch.insert("full_name".into(), Value::from(name.clone()));        patch.insert("contact_source".into(), Value::from("manual"));        insert_row(ctx, "cotton_people", &id, patch).map_err(tool)?;        let mut claimed = BTreeMap::new();        cotton_tools::mcp::handlers::records_1::people::hold_handles(ctx, &id, &phones, &emails, None, HandleSource::Manual, &mut claimed).map_err(tool)?;        if let Some(kind) = kind.as_deref().filter(|k| *k != "person") {            let mut state = Map::new();            state.insert("kind".into(), Value::from(kind));            put_state(ctx, &id, state)?;        }        ctx.commit().map_err(tool)?;        // Labels after the handles have landed (a read sees them only once committed).        super::contacts_labels::label_held(ctx, &id, &entries(request, "phones").unwrap_or_default(), &entries(request, "emails").unwrap_or_default())?;        ctx.commit().map_err(tool)?;        Ok(json!({ "id": id, "said": s("form.saved") }))    })}fn edit(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request.get("id").and_then(Value::as_str).ok_or_else(|| bad("id names the contact"))?.to_string();    let name = request.get("name").and_then(Value::as_str).map(str::trim).map(str::to_string);    if name.as_deref() == Some("") {        return Ok(json!({ "error": s("form.no_name") }));    }    let kind = kind_arg(request)?;    let phones = strings(request, "phones");    let emails = strings(request, "emails");    let remove = request.get("removeHandle").and_then(Value::as_str).map(str::to_string);    write(client, "contacts.edit", |ctx| {        if rows(ctx, "SELECT id FROM cotton_people WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL", &[ws(ctx), text(&id)])?.is_empty() {            return Err(format!("no contact {id}"));        }        if let Some(name) = &name {            let mut patch = Map::new();            patch.insert("full_name".into(), Value::from(name.clone()));            update_row(ctx, "cotton_people", &id, patch).map_err(tool)?;        }        if let Some(kind) = &kind {            let mut state = Map::new();            state.insert("kind".into(), Value::from(kind.clone()));            put_state(ctx, &id, state)?;        }        let now = iso_now(ctx);        // A handle taken off: the contact's own goes to the bin (who stops naming them by it); a share is let go.        let drop_handle = |ctx: &mut Ctx<'_>, handle: &str| -> Result<(), String> {            if !rows(ctx, "SELECT id FROM cotton_person_handles WHERE id = ? AND person_id = ?", &[text(handle), text(&id)])?.is_empty() {                let mut patch = Map::new();                patch.insert("trashed_at".into(), Value::from(now.clone()));                update_row(ctx, "cotton_person_handles", handle, patch).map_err(tool)?;            } else if cotton_store::protocol::who::shared_held(ctx.db()) && !rows(ctx, &format!("SELECT id FROM {SHARED} WHERE id = ? AND person = ?"), &[text(handle), text(&id)])?.is_empty() {                let mut patch = Map::new();                patch.insert("deleted_at".into(), Value::from(now.clone()));                update_row(ctx, SHARED, handle, patch).map_err(tool)?;            }            Ok(())        };        if let Some(handle) = &remove {            drop_handle(ctx, handle)?;        }        if phones.is_some() || emails.is_some() {            // The form's lists are the whole of each kind: what is no longer there goes, what is new is held.            let current = reach(ctx, &id)?;            let keep = |kind: &str, value: &str| -> bool {                let list = if kind == "email" { &emails } else { &phones };                list.as_ref().is_none_or(|list| list.iter().any(|v| v.trim() == value.trim()))            };            for h in &current {                let (Some(handle), Some(kind), Some(value)) = (h["id"].as_str(), h["kind"].as_str(), h["words"].as_str()) else { continue };                if (kind == "phone" || kind == "email") && !keep(kind, value) {                    drop_handle(ctx, handle)?;                }            }            let mut claimed = BTreeMap::new();            cotton_tools::mcp::handlers::records_1::people::hold_handles(                ctx,                &id,                phones.as_deref().unwrap_or_default(),                emails.as_deref().unwrap_or_default(),                None,                HandleSource::Manual,                &mut claimed,            )            .map_err(tool)?;        }        ctx.commit().map_err(tool)?;        // Labels after the handles have landed (a read sees them only once committed).        super::contacts_labels::label_held(ctx, &id, &entries(request, "phones").unwrap_or_default(), &entries(request, "emails").unwrap_or_default())?;        ctx.commit().map_err(tool)?;        Ok(json!({ "id": id, "said": s("form.saved") }))    })}// ── the phone's address book ───────────────────────────────────────────fn read_book(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let cards = request.get("cards").and_then(Value::as_array).cloned().ok_or_else(|| bad("cards is the phone's address book, every card"))?;    let count = cards.len();    let before = read(client, "contacts.read.before", |ctx| Ok(Value::from(super::contacts_same::count(ctx)?)))?.as_u64().unwrap_or(0);    let done = write(client, "contacts.read", |ctx| {        let mut args = Map::new();        args.insert("contacts".into(), Value::Array(cards.clone()));        let answer = cotton_tools::mcp::handlers::records_1::people::sync_device_contacts(ctx, &args).map_err(tool)?;        ctx.commit().map_err(tool)?;        Ok(answer)    })?;    let after = read(client, "contacts.read.after", |ctx| Ok(Value::from(super::contacts_same::count(ctx)?)))?.as_u64().unwrap_or(0);    let same = after.saturating_sub(before);    let n = |key: &str| done.get(key).and_then(Value::as_u64).unwrap_or(0);    let read_words = count.to_string();    Ok(json!({        "read": count,        "made": n("inserted"),        "attached": n("attached"),        "same": same,        "said": if same > 0 { sf("read.said_same", &[("read", &read_words), ("same", &same.to_string())]) } else { sf("read.said", &[("read", &read_words)]) },    }))}#[cfg(test)]#[path = "contacts_app_tests.rs"]mod tests;#[cfg(test)]#[path = "contacts_at_size_tests.rs"]mod at_size_tests;