//! A person's handles as the People tools read and write them (schema v90)://! `cotton_person_handles` is the only place a phone, an email or a social//! handle of a person lives. What a handle IS — its kind, its normalised form,//! its row id — is `cotton_core::rules::people::handles`; this is the tools'//! half: setting one kind's list on a person, and answering `phones`/`emails`//! in the shape the people rows always had.use std::collections::HashMap;use cotton_core::rules::people::handles::{HandleKind, HandleSource};use cotton_store::protocol::person_handles::normalise_handle_in;use cotton_store::protocol::derived_id::person_handle_id;use rusqlite::types::ValueasSqlValue;use serde_json::{Map, Value};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::{insert_row, maybe_row, text, update_row, Valid};usecrate::mcp::read_db::Query;usecrate::mcp::protocol::ToolFailure;usecrate::mcp::writer::Retract;pubconst PERSON_HANDLES: &str = "cotton_person_handles";/// Who carries one handle, archived included — what a write asks before/// claiming it — and their name for the refusal.#[derive(Debug, Clone, PartialEq, Eq)]pubstructHandleHolder {pub person_id: String,pub full_name: Option<String>,}/// The holder of `(kind, normalised)` in this workspace, if anyone holds it.pubfn handle_holder(ctx: &Ctx<'_>, kind: HandleKind, normalised: &str) -> Valid<Option<HandleHolder>> {let held = maybe_row( ctx, &Query::on(PERSON_HANDLES) .columns(&["person_id"]) .eq("kind", kind.as_str().to_string()) .eq("normalised", normalised.to_string()), )?;letSome(person_id) = held.as_ref().and_then(|row| text(row, "person_id")) else {returnOk(None); };let full_name = maybe_row( ctx, &Query::on("cotton_people").columns(&["full_name"]).eq("id", person_id.clone()), )? .and_then(|row| text(&row, "full_name"));Ok(Some(HandleHolder { person_id, full_name }))}/// What a write does with a handle another person already carries.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumClaimed {/// The owner or an assistant asked for it: refuse, naming the holder — a/// handle names one person, and two people with one number are one/// person to merge, or a mistake.Refuse,/// An import (the phone's contacts): leave the handle where it is and/// carry on — an address book with a shared landline is not an error.Skip,}fn sql_err(error: impl std::fmt::Display) -> ToolFailure {ToolFailure::new(error.to_string())}/// Every handle of the given people, `(person, kind) → values as written`, in/// the page's order — one read for a whole page of people.pubfn handle_lists(ctx: &Ctx<'_>, people: &[String]) -> Valid<HashMap<(String, String), Vec<String>>> {letmut lists: HashMap<(String, String), Vec<String>> = HashMap::new();for chunk in people.chunks(400) {let holes = vec!["?"; chunk.len()].join(", ");let params: Vec<SqlValue> = chunk.iter().cloned().map(SqlValue::Text).collect();let rows = ctx .db() .all( &format!("SELECT person_id, kind, value FROM cotton_person_handles WHERE person_id IN ({holes}) \ ORDER BY person_id, kind, position, created_at, id" ), ¶ms, ) .map_err(sql_err)?;for row in rows {let (Some(person), Some(kind), Some(value)) = (row.text("person_id"), row.text("kind"), row.text("value")) else {continue; }; lists.entry((person.to_string(), kind.to_string())).or_default().push(value.to_string()); } }Ok(lists)}/// One person's handles of one kind, as written.pubfn handles_of(ctx: &Ctx<'_>, person: &str, kind: HandleKind) -> Valid<Vec<String>> {Ok(handle_lists(ctx, &[person.to_string()])?.remove(&(person.to_string(), kind.as_str().to_string())).unwrap_or_default())}/// Put `phones` and `emails` on each people row (keyed by its `id`) as the/// JSON lists the columns used to hold — `[]` when there are none.pubfn fill_phones_and_emails(ctx: &Ctx<'_>, rows: &mut [Map<String, Value>]) -> Valid<()> {let ids: Vec<String> = rows.iter().filter_map(|row| text(row, "id")).collect();letmut lists = handle_lists(ctx, &ids)?;for row in rows.iter_mut() {let id = text(row, "id").unwrap_or_default();for (kind, key) in [("phone", "phones"), ("email", "emails")] {let list = lists.remove(&(id.clone(), kind.to_string())).unwrap_or_default(); row.insert(key.to_string(), Value::Array(list.into_iter().map(Value::from).collect())); } }Ok(())}/// The form a handle is matched by in this database: a phone written without/// its code is read in the owner's own number's country/// (`cotton_store::phone_fold::region_hint`); with no owner number, as typed.pub(crate) fn handle_form(ctx: &Ctx<'_>, kind: HandleKind, raw: &str) -> Option<String> {let region = match kind {HandleKind::Phone => cotton_store::phone_fold::region_hint(ctx.db(), ctx.workspace_id).ok().flatten(), _ => None, }; normalise_handle_in(kind, raw, region)}/// Make `values` the person's whole list of `kind`, in that order: new/// handles are added, ones no longer named are removed, and a handle that/// normalises like an earlier one is the same handle. A value that is no/// handle of this kind (an Instagram name with a space) is refused under/// [`Claimed::Refuse`] and skipped under [`Claimed::Skip`], as is a handle/// another person carries. Answers the values it skipped.pubfn set_person_handles( ctx: &mutCtx<'_>, person: &str, kind: HandleKind, values: &[String], source: HandleSource, claimed: Claimed,) -> Valid<Vec<String>> {let existing = ctx .db() .all("SELECT id, normalised, value, position FROM cotton_person_handles WHERE person_id = ?1 AND kind = ?2", &[SqlValue::Text(person.to_string()), SqlValue::Text(kind.as_str().to_string())], ) .map_err(sql_err)?;letmut skipped = Vec::new();letmut kept: Vec<String> = Vec::new();letmut position = 0i64;for raw in values {letSome(normalised) = handle_form(ctx, kind, raw) else {if claimed == Claimed::Refuse && !raw.trim().is_empty() {returnErr(ToolFailure::new(format!("{raw:?} is not a {kind} handle"))); } skipped.push(raw.clone());continue; };if kept.contains(&normalised) {continue; }let holder = handle_holder(ctx, kind, &normalised)?;ifletSome(holder) = holder.as_ref().filter(|holder| holder.person_id != person) {if claimed == Claimed::Refuse {returnErr(ToolFailure::new(format!("{} is already {}'s (person {}) — a {kind} names one person; if they are one person, merge_people", raw.trim(), holder.full_name.as_deref().unwrap_or("someone else"), holder.person_id ))); } skipped.push(raw.clone());continue; } kept.push(normalised.clone());let mine = existing.iter().find(|row| row.text("normalised") == Some(normalised.as_str()));match mine {Some(row) => {let id = row.text("id").unwrap_or_default().to_string();letmut patch = Map::new();if row.text("value") != Some(raw.trim()) { patch.insert("value".into(), Value::from(raw.trim())); }if row.int("position") != Some(position) { patch.insert("position".into(), Value::from(position)); }if !patch.is_empty() { update_row(ctx, PERSON_HANDLES, &id, patch)?; } }None => {let id = person_handle_id(ctx.file.namespace(), kind.as_str(), &normalised);letmut patch = Map::new(); patch.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string())); patch.insert("person_id".into(), Value::from(person)); patch.insert("kind".into(), Value::from(kind.as_str())); patch.insert("value".into(), Value::from(raw.trim())); patch.insert("normalised".into(), Value::from(normalised.as_str())); patch.insert("source".into(), Value::from(source.as_str())); patch.insert("verified_at".into(), Value::Null); patch.insert("position".into(), Value::from(position)); insert_row(ctx, PERSON_HANDLES, &id, patch)?; } } position += 1; }for row in &existing {if row.text("normalised").is_some_and(|normalised| !kept.iter().any(|kept| kept == normalised)) {let id = row.text("id").unwrap_or_default().to_string(); ctx.writer()?.retract(PERSON_HANDLES, &id, Retract::Relation); } }Ok(skipped)}/// Add ONE handle to a person, after whatever they already carry of that/// kind — the owner confirmed "this sender is them". Nothing happens when/// they already carry it; another person carrying it is refused.pubfn add_person_handle( ctx: &mutCtx<'_>, person: &str, kind: HandleKind, value: &str, source: HandleSource, verified_at: Option<&str>,) -> Valid<()> {letSome(normalised) = handle_form(ctx, kind, value) else {returnErr(ToolFailure::new(format!("{value:?} is not a {kind} handle"))); };let holder = handle_holder(ctx, kind, &normalised)?;match holder {Some(holder) if holder.person_id == person => returnOk(()),Some(holder) => {returnErr(ToolFailure::new(format!("{} is already {}'s (person {}) — a {kind} names one person; if they are one person, merge_people", value.trim(), holder.full_name.as_deref().unwrap_or("someone else"), holder.person_id ))) }None => {} }let position = handles_of(ctx, person, kind)?.len() as i64;let id = person_handle_id(ctx.file.namespace(), kind.as_str(), &normalised);letmut patch = Map::new(); patch.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string())); patch.insert("person_id".into(), Value::from(person)); patch.insert("kind".into(), Value::from(kind.as_str())); patch.insert("value".into(), Value::from(value.trim())); patch.insert("normalised".into(), Value::from(normalised.as_str())); patch.insert("source".into(), Value::from(source.as_str())); patch.insert("verified_at".into(), verified_at.map_or(Value::Null, Value::from)); patch.insert("position".into(), Value::from(position)); insert_row(ctx, PERSON_HANDLES, &id, patch)}