Cotton code
380 lines · 17.4 KB · RustRaw
//! Cotton Contacts on this phone: groups, archive and unarchive//! (assets/design/shared/CONTACTS-ANSWERS.md sections 2 and 6; PEOPLE-DESIGN f.2).//!//! ```text//! contacts.groups contacts.group contacts.group.make contacts.group.rename//! contacts.group.add contacts.group.remove contacts.group.delete//! contacts.archive contacts.unarchive contacts.pin//! ```//!//! A group is the person table's group as every app keeps it (`record_group`, through the group tools://! `list_groups`, `create_group`, `update_group`, `delete_group`; a group's members read with `list_records`//! narrowed to the group), so a group made here is the same group an assistant or another app sees. Archive is//! `archive_person` / `unarchive_person`: the person leaves the list and nothing they are linked to is lost. Every//! write goes through `write`, as the app's own edits do, so it is sealed and synced like any other. Every word is//! the kit's `contacts` line set, or the tool's own `said`.//!//! Why a group was made is `group_origin` (`cotton_group_origin`: `made_by` app or you, `reason`): a group Contacts//! made stands under Made by Contacts with its reason; any other under Made by you. Deleting a group Contacts made//! marks its origin dismissed, so it is not made again. Pin is `person_state.pinned`, written through//! `contacts_app::put_state`; the home reads it as Close.use std::collections::HashMap;use serde_json::{json, Map, Value};use cotton_core::rules::shell_lines::LineSet;use cotton_tools::mcp::handlers::common::update_row;use rusqlite::types::Value as SqlValue;use super::contacts_app::{held, put_state};use super::cotton_chat::{read, rows, write};use crate::methods::MethodError;use crate::shell::client::ClientController;/// Every method this module answers.pub const METHODS: [&str; 10] = [    "contacts.archive",    "contacts.group",    "contacts.group.add",    "contacts.group.delete",    "contacts.group.make",    "contacts.group.remove",    "contacts.group.rename",    "contacts.groups",    "contacts.pin",    "contacts.unarchive",];/// The local table that says why a group was made.const ORIGIN: &str = "cotton_group_origin";/// The table a contact group gathers.const PERSON: &str = "person";pub fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "contacts.groups" => groups(client),        "contacts.group" => group(client, &text(request, "id")?),        "contacts.group.make" => {            let made = tool(client, "create_group", json!({ "table": PERSON, "name": text(request, "name")?, "records": ids(request, "people")? }))?;            let id = made.pointer("/group/id").and_then(Value::as_str).ok_or_else(|| refused("create_group answered no group"))?;            with_said(group(client, id)?, &made)        }        "contacts.group.rename" => {            let id = text(request, "id")?;            let renamed = tool(client, "update_group", json!({ "id": id, "name": text(request, "name")? }))?;            with_said(group(client, &id)?, &renamed)        }        "contacts.group.add" => {            let id = text(request, "id")?;            let added = tool(client, "update_group", json!({ "id": id, "add": ids(request, "people")? }))?;            with_said(group(client, &id)?, &added)        }        "contacts.group.remove" => {            let id = text(request, "id")?;            let removed = tool(client, "update_group", json!({ "id": id, "remove": [text(request, "person")?] }))?;            with_said(group(client, &id)?, &removed)        }        "contacts.group.delete" => {            let id = text(request, "id")?;            dismiss(client, &id)?;            tool(client, "delete_group", json!({ "id": id }))?;            Ok(json!({ "id": id, "said": say("groups.deleted", &[]) }))        }        "contacts.archive" => {            let id = text(request, "id")?;            tool(client, "archive_person", json!({ "id": id }))?;            Ok(json!({ "id": id, "said": say("edit.removed", &[]) }))        }        "contacts.unarchive" => {            let id = text(request, "id")?;            tool(client, "unarchive_person", json!({ "id": id }))?;            Ok(json!({ "id": id, "said": say("person.unarchived", &[]) }))        }        "contacts.pin" => {            let id = text(request, "id")?;            let on = request.get("on").and_then(Value::as_bool).ok_or_else(|| MethodError::new("bad_request", "`on` is true or false"))?;            let person = id.clone();            write(client, "contacts.pin", |ctx| {                let mut patch = Map::new();                patch.insert("pinned".into(), Value::from(on));                put_state(ctx, &person, patch)?;                Ok(json!({}))            })?;            Ok(json!({ "id": id, "said": say(if on { "person.pinned" } else { "person.unpinned" }, &[]) }))        }        other => Err(MethodError::new("unknown_method", format!("this core answers no `{other}`"))),    }}/// `contacts.groups {}`: the person groups, Contacts' own (with why) above the person's, each with how many it/// holds; New group.fn groups(client: &ClientController) -> Result<Value, MethodError> {    let groups = person_groups(client)?;    let origins = origins(client)?;    let (mut by_app, mut by_you) = (Vec::new(), Vec::new());    for g in &groups {        let id = g.get("id").and_then(Value::as_str).unwrap_or_default();        let count = g.get("count").and_then(Value::as_u64).unwrap_or(0).to_string();        let origin = origins.get(id);        let detail = match origin.and_then(|o| o.reason.as_deref()) {            Some(reason) => format!("{} · {reason}", say("groups.count", &[("count", &count)])),            None => say("groups.count", &[("count", &count)]),        };        let row = json!({            "id": id,            "words": g.get("name").and_then(Value::as_str).unwrap_or_default(),            "detail": detail,            "call": call_of("contacts.group", json!({ "id": id })),        });        if origin.is_some_and(|o| o.by_app) { by_app.push(row) } else { by_you.push(row) }    }    let mut sections = Vec::new();    if !by_app.is_empty() {        sections.push(json!({ "id": "app", "title": say("groups.by_app", &[]), "rows": by_app }));    }    if !by_you.is_empty() {        sections.push(json!({ "id": "you", "title": say("groups.by_you", &[]), "rows": by_you }));    }    Ok(json!({        "title": say("groups.title", &[]),        "sections": sections,        "foot": say(if groups.is_empty() { "groups.empty" } else { "groups.foot" }, &[]),        "add": { "words": say("groups.new", &[]), "call": call_of("contacts.group.make", json!({})) },    }))}/// Why a group was made, as `group_origin` says it.struct Origin {    by_app: bool,    reason: Option<String>,}/// Every live origin by group id; none when this copy does not hold the table yet.fn origins(client: &ClientController) -> Result<HashMap<String, Origin>, MethodError> {    let found = read(client, "contacts.groups", |ctx| {        if !held(ctx, ORIGIN) {            return Ok(json!([]));        }        let rows = rows(ctx, &format!("SELECT group_id, made_by, reason FROM {ORIGIN} WHERE dismissed_at IS NULL"), &[])?;        Ok(Value::Array(rows.into_iter().map(Value::Object).collect()))    })?;    Ok(found        .as_array()        .into_iter()        .flatten()        .filter_map(|o| {            let id = o.get("group_id").and_then(Value::as_str)?.to_string();            let by_app = o.get("made_by").and_then(Value::as_str) == Some("app");            let reason = o.get("reason").and_then(Value::as_str).filter(|r| !r.is_empty()).map(str::to_string);            Some((id, Origin { by_app, reason }))        })        .collect())}/// A group Contacts made, deleted by the person: its origin is marked dismissed, so Contacts never makes it again.fn dismiss(client: &ClientController, group: &str) -> Result<(), MethodError> {    let group = group.to_string();    write(client, "contacts.group.delete", |ctx| {        if !held(ctx, ORIGIN) {            return Ok(json!({}));        }        let found = rows(ctx, &format!("SELECT id FROM {ORIGIN} WHERE group_id = ? AND dismissed_at IS NULL"), &[SqlValue::Text(group.clone())])?;        for row in found {            if let Some(id) = row.get("id").and_then(Value::as_str) {                let mut patch = Map::new();                patch.insert("dismissed_at".into(), Value::from(cotton_tools::mcp::handlers::common::now_iso(ctx)));                update_row(ctx, ORIGIN, id, patch).map_err(|e| e.to_string())?;            }        }        Ok(json!({}))    })?;    Ok(())}/// `contacts.group {id}`: its name, how many, its people as the home's rows (each with Take out), and its acts.fn group(client: &ClientController, id: &str) -> Result<Value, MethodError> {    let groups = person_groups(client)?;    let Some(g) = groups.iter().find(|g| g.get("id").and_then(Value::as_str) == Some(id)) else {        return Err(MethodError::new("not_found", say("groups.gone", &[])));    };    let name = g.get("name").and_then(Value::as_str).unwrap_or_default().to_string();    // Only its members, read where they are kept, in the group's order (CONTACTS AT SIZE: the whole book read through    // `list_people`, each person's figures worked out, took 200M steps on 1,500 contacts).    let people = members_of(client, id)?;    let member_ids: Vec<String> = people.keys().cloned().collect::<Vec<_>>();    let order = read(client, "contacts.group", |ctx| {        let found = rows(ctx, "SELECT record_id FROM cotton_group_members WHERE group_id = ? ORDER BY place, id", &[rusqlite::types::Value::Text(id.to_string())])?;        Ok(Value::from(found.iter().filter_map(|r| r.get("record_id").and_then(Value::as_str)).map(str::to_string).collect::<Vec<_>>()))    })?;    let member_ids: Vec<String> = order.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).filter(|m| member_ids.contains(m)).collect();    let rows: Vec<Value> = member_ids        .iter()        .filter_map(|member| people.get(member))        .map(|person| {            let mut row = person_row(person);            let pid = row["id"].clone();            row["acts"] = json!([act("remove", say("groups.remove_person", &[]), call_of("contacts.group.remove", json!({ "id": id, "person": pid })), true, None)]);            row        })        .collect();    let count = rows.len().to_string();    let origin = origins(client)?.remove(id);    let detail = match origin.as_ref().and_then(|o| o.reason.as_deref()) {        Some(reason) => format!("{} · {reason}", say("groups.count", &[("count", &count)])),        None => say("groups.count", &[("count", &count)]),    };    Ok(json!({        "id": id,        "title": name,        "detail": detail,        "madeBy": if origin.is_some_and(|o| o.by_app) { "app" } else { "you" },        "rows": rows,        "acts": [            act("add", say("groups.add_people", &[]), call_of("contacts.group.add", json!({ "id": id })), false, None),            act("rename", say("groups.rename", &[]), call_of("contacts.group.rename", json!({ "id": id })), false, None),            act("delete", say("groups.delete", &[]), call_of("contacts.group.delete", json!({ "id": id })), true,                Some(say("groups.delete_confirm", &[("name", &name)]))),        ],    }))}/// A person as the home draws them (section 1's row): name, a second line, initials, and the call to their page.pub fn person_row(person: &Value) -> Value {    let id = person.get("id").and_then(Value::as_str).unwrap_or_default();    let name = person.get("name").and_then(Value::as_str).unwrap_or_default();    let strings = |key: &str| -> Vec<String> {        person.get(key).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()    };    let org = person.get("org").and_then(Value::as_str).filter(|s| !s.is_empty());    let role = person.get("roleTitle").and_then(Value::as_str).filter(|s| !s.is_empty());    let detail = match (role, org) {        (Some(role), Some(org)) => Some(format!("{role} · {org}")),        (None, Some(org)) => Some(org.to_string()),        _ => strings("phones").into_iter().chain(strings("emails")).next(),    };    json!({        "id": id,        "words": name,        "detail": detail,        "initials": initials(name),        "picture": person.get("avatarKey").cloned().unwrap_or(Value::Null),        "kind": "person",        "call": call_of("contacts.person", json!({ "id": id })),    })}/// Up to two letters for the round mark: the first letter of the first and of the last word; `#` for a name with no/// letter (a number standing in for a name).pub fn initials(name: &str) -> String {    let words: Vec<&str> = name.split([' ', '-']).filter(|w| !w.is_empty()).collect();    let first = words.first().and_then(|w| w.chars().find(|c| c.is_alphabetic()));    let last = if words.len() > 1 { words.last().and_then(|w| w.chars().find(|c| c.is_alphabetic())) } else { None };    let letters: String = first.into_iter().chain(last).flat_map(char::to_uppercase).collect();    if letters.is_empty() { "#".to_string() } else { letters }}fn person_groups(client: &ClientController) -> Result<Vec<Value>, MethodError> {    // Names and counts only: the list draws no member (CONTACTS AT SIZE).    let listed = read(client, "contacts.groups", |ctx| {        cotton_tools::mcp::handlers::tables::groups::group_summaries(ctx, PERSON).map(Value::from).map_err(|failure| failure.0)    })?;    Ok(listed.as_array().cloned().unwrap_or_default())}/// A group's living members, by id, in the shape `list_people` answers (name, phones, emails, org, roleTitle,/// avatarKey): read from the people and their handles directly.fn members_of(client: &ClientController, group: &str) -> Result<HashMap<String, Value>, MethodError> {    let found = read(client, "contacts.group", |ctx| {        let handles = |kind: &str| {            format!("(SELECT json_group_array(h.value) FROM cotton_person_handles h WHERE h.person_id = p.id AND h.kind = '{kind}' AND h.trashed_at IS NULL)")        };        let found = rows(            ctx,            &format!(                "SELECT DISTINCT p.id AS id, p.full_name AS name, p.org AS org, p.role_title AS roleTitle, p.avatar_key AS avatarKey, {} AS phones, {} AS emails \                 FROM cotton_group_members m JOIN cotton_people p ON p.id = m.record_id WHERE m.group_id = ? AND p.trashed_at IS NULL AND p.archived_at IS NULL",                handles("phone"),                handles("email")            ),            &[rusqlite::types::Value::Text(group.to_string())],        )?;        Ok(Value::from(found.into_iter().map(Value::Object).collect::<Vec<_>>()))    })?;    Ok(found        .as_array()        .into_iter()        .flatten()        .filter_map(|p| {            let mut p = p.clone();            for key in ["phones", "emails"] {                let list: Value = p.get(key).and_then(Value::as_str).and_then(|t| serde_json::from_str(t).ok()).unwrap_or_else(|| json!([]));                p[key] = list;            }            Some((p.get("id")?.as_str()?.to_string(), p))        })        .collect())}/// A tool's own answer (`write` nests it under `answer`); its refusal is the sentence it gave.fn tool(client: &ClientController, name: &str, args: Value) -> Result<Value, MethodError> {    let args: Map<String, Value> = args.as_object().cloned().unwrap_or_default();    let answer = client.write(name, &args).map_err(refused)?;    Ok(answer.get("answer").cloned().unwrap_or(answer))}fn refused(reason: impl Into<String>) -> MethodError {    MethodError::new("write_refused", reason.into())}/// The group's answer with the tool's own sentence ("Made Family with 2 people") as its `said`.fn with_said(mut answer: Value, tool_answer: &Value) -> Result<Value, MethodError> {    // A change's receipt carries the tool's sentence (`change.receipt.said`).    if let Some(said) = tool_answer.pointer("/change/receipt/said").or_else(|| tool_answer.get("said")).and_then(Value::as_str) {        answer["said"] = json!(said);    }    Ok(answer)}fn text(request: &Value, key: &str) -> Result<String, MethodError> {    request        .get(key)        .and_then(Value::as_str)        .map(str::trim)        .filter(|s| !s.is_empty())        .map(str::to_string)        .ok_or_else(|| MethodError::new("bad_request", format!("`{key}` is needed")))}fn ids(request: &Value, key: &str) -> Result<Vec<String>, MethodError> {    let ids: Vec<String> = request.get(key).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();    if ids.is_empty() {        return Err(MethodError::new("bad_request", format!("`{key}` names no one")));    }    Ok(ids)}fn call_of(method: &str, request: Value) -> Value {    json!({ "method": method, "request": request })}fn act(id: &str, words: String, call: Value, red: bool, confirm: Option<String>) -> Value {    let mut act = json!({ "id": id, "words": words, "call": call });    if red {        act["red"] = json!(true);    }    if let Some(confirm) = confirm {        act["confirm"] = json!(confirm);    }    act}/// One of the kit's `contacts` lines, filled.fn say(line: &str, fills: &[(&str, &str)]) -> String {    LineSet::shipped("contacts").and_then(|set| set.say(line, fills)).unwrap_or_else(|| format!("contacts.{line}"))}#[cfg(test)]#[path = "contacts_groups_tests.rs"]mod tests;