//! A number's or an address's own label (CONTACT KINDS, 28 Nov 2026): Mobile, Work, Home, Other, or his own word.//!//! Kept in the kit-own table `handle_label` (`kits/personal/tables/handle_label.json`): one row per handle, its id//! derived from the handle's id, the label sealed, the contact and the handle clear (links, as every link is). A//! handle is a contact's own (`cotton_person_handles`) or one it shares (`shared_handle`); the label follows the id.//! The person page shows it in place of "Mobile" or "Email" (`contacts.person`); add, edit, import and export carry it.use std::collections::HashMap;use rusqlite::types::ValueasSqlValue;use serde_json::{Map, Value};use cotton_core::cotton_rules::handles::{normalise_handle_in, HandleKind};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};usesuper::contacts_app::held;usesuper::cotton_chat::{rows, ws};/// The table's local name.pub(crate) const LABELS: &str = "cotton_handle_label";const SHARED: &str = cotton_store::protocol::who::SHARED_TABLE;/// A label is a word or two: longer is cut.const LABEL_MAX: usize = 40;fn text(value: &str) -> SqlValue {SqlValue::Text(value.to_string())}/// A label as kept: the usual words in their usual spelling (`cell` and `mobile` are Mobile), his own word trimmed and/// cut at 40 characters, nothing for an empty one.pubfn label_word(raw: &str) -> Option<String> {let word = raw.trim();if word.is_empty() {returnNone; }let known = match word.to_ascii_lowercase().as_str() {"cell" | "mobile" | "mobil" => Some("Mobile"),"iphone" => Some("iPhone"),"work" | "office" => Some("Work"),"home" => Some("Home"),"main" => Some("Main"),"fax" => Some("Fax"),"pager" => Some("Pager"),"other" => Some("Other"), _ => None, };Some(known.map(str::to_string).unwrap_or_else(|| word.chars().take(LABEL_MAX).collect()))}/// A number's or an address's entry in a request: a bare string, or `{value, label?}`.pubfn entry(value: &Value) -> Option<(String, Option<String>)> {match value {Value::String(v) => Some(v.trim().to_string()).filter(|v| !v.is_empty()).map(|v| (v, None)),Value::Object(o) => {let v = o.get("value").and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty())?;Some((v.to_string(), o.get("label").and_then(Value::as_str).and_then(label_word))) } _ => None, }}fn label_id(ctx: &Ctx<'_>, handle: &str) -> String { cotton_core::cotton_rules::ids::derived_id("handle_label", &[&ctx.file.namespace().to_string(), handle])}/// Every label of one contact's handles: handle id → label.pub(crate) fn labels_of(ctx: &mutCtx<'_>, person: &str) -> Result<HashMap<String, String>, String> {if !held(ctx, LABELS) {returnOk(HashMap::new()); }let found = rows(ctx, &format!("SELECT handle, label FROM {LABELS} WHERE workspace_id = ?1 AND person = ?2"), &[ws(ctx), text(person)])?;Ok(found.into_iter().filter_map(|r| Some((r.get("handle")?.as_str()?.to_string(), r.get("label")?.as_str()?.to_string()))).collect())}/// Every label in this copy: handle id → label (export reads them all at once).pub(crate) fn all_labels(ctx: &mutCtx<'_>) -> Result<HashMap<String, String>, String> {if !held(ctx, LABELS) {returnOk(HashMap::new()); }let found = rows(ctx, &format!("SELECT handle, label FROM {LABELS} WHERE workspace_id = ?1"), &[ws(ctx)])?;Ok(found.into_iter().filter_map(|r| Some((r.get("handle")?.as_str()?.to_string(), r.get("label")?.as_str()?.to_string()))).collect())}/// The id of the contact's handle (its own, else one it shares) that `value` names, by its normalised form.pub(crate) fn handle_of(ctx: &mutCtx<'_>, person: &str, kind: HandleKind, value: &str) -> Result<Option<String>, String> {let region = match kind {HandleKind::Phone => cotton_store::phone_fold::region_hint(ctx.db(), ctx.workspace_id).ok().flatten(), _ => None, };letSome(normalised) = normalise_handle_in(kind, value, region) else { returnOk(None) };// The stored form may carry the `+` or not: either matches, as does the value as typed.let bare = normalised.trim_start_matches('+').to_string();let kind_word = if kind == HandleKind::Email { "email" } else { "phone" };let own = rows(ctx, "SELECT id FROM cotton_person_handles WHERE workspace_id = ?1 AND person_id = ?2 AND kind = ?3 AND (normalised = ?4 OR normalised = ?5 OR value = ?6) AND trashed_at IS NULL", &[ws(ctx), text(person), text(kind_word), text(&normalised), text(&bare), text(value)])?;ifletSome(id) = own.into_iter().next().and_then(|r| r.get("id").and_then(Value::as_str).map(str::to_string)) {returnOk(Some(id)); }if cotton_store::protocol::who::shared_held(ctx.db()) {let shared = rows(ctx, &format!("SELECT id FROM {SHARED} WHERE workspace_id = ?1 AND person = ?2 AND kind = ?3 AND (normalised = ?4 OR normalised = ?5 OR value = ?6) AND deleted_at IS NULL"), &[ws(ctx), text(person), text(kind_word), text(&normalised), text(&bare), text(value)])?;returnOk(shared.into_iter().next().and_then(|r| r.get("id").and_then(Value::as_str).map(str::to_string))); }Ok(None)}/// Keep `label` on a handle (made the first time; `None` clears it). A copy without the table yet writes nothing.pub(crate) fn set_label(ctx: &mutCtx<'_>, person: &str, handle: &str, label: Option<&str>) -> Result<(), String> {if !held(ctx, LABELS) {returnOk(()); }let id = label_id(ctx, handle);let there = !rows(ctx, &format!("SELECT id FROM {LABELS} WHERE id = ?"), &[text(&id)])?.is_empty();letmut patch = Map::new(); patch.insert("label".into(), label.map_or(Value::Null, Value::from));if there { update_row(ctx, LABELS, &id, patch).map_err(|e| e.to_string())?; } elseif label.is_some() { patch.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string())); patch.insert("person".into(), Value::from(person)); patch.insert("handle".into(), Value::from(handle)); insert_row(ctx, LABELS, &id, patch).map_err(|e| e.to_string())?; }Ok(())}/// Labels for the numbers and addresses just held on a contact: each `(value, label)` with a label finds its handle.pub(crate) fn label_held(ctx: &mutCtx<'_>, person: &str, phones: &[(String, Option<String>)], emails: &[(String, Option<String>)]) -> Result<(), String> {for (kind, list) in [(HandleKind::Phone, phones), (HandleKind::Email, emails)] {for (value, label) in list {letSome(label) = label else { continue };ifletSome(handle) = handle_of(ctx, person, kind, value)? { set_label(ctx, person, &handle, Some(label))?; } } }Ok(())}#[cfg(test)]mod tests {usesuper::*;use serde_json::json; #[test]fn labels_read_in_their_usual_spelling_and_his_own_words_kept() { assert_eq!(label_word("cell").as_deref(), Some("Mobile")); assert_eq!(label_word(" WORK ").as_deref(), Some("Work")); assert_eq!(label_word("Studio").as_deref(), Some("Studio")); assert_eq!(label_word(" "), None); assert_eq!(label_word(&"x".repeat(60)).map(|l| l.len()), Some(40)); assert_eq!(entry(&json!("+91 98765 00001")), Some(("+91 98765 00001".into(), None))); assert_eq!(entry(&json!({ "value": "a@example.com", "label": "home" })), Some(("a@example.com".into(), Some("Home".into())))); assert_eq!(entry(&json!({ "label": "home" })), None); }}