Cotton code
203 lines · 9.8 KB · RustRaw
//! `people.fillCities` — Cotton fills in the city of every person who has a//! time zone and has never had a city.//!//! A person's clock is chosen as a CITY now: the owner picks a place and the//! zone comes with it. People given a zone before that have a clock and no//! place, and Cotton fills the place in by itself — Europe/London → London —//! from [`cotton_core::rules::people::zone_city::main_city`], which derives the//! city from the zone identifier alone and never asks the network. The owner's//! standing rule is that Cotton acts without asking, shows what it did and lets//! him correct it: the city lands as an ordinary, editable city on the person's//! page, and the change is in the person's history like any other edit.//!//! **Four promises, each held by a case in `people_city_tests.rs`:**//!//! * **It never overwrites a city.** Only a person whose city is empty is//!   touched, and only the `city` field is written — the zone stays as it was.//! * **It fills a person ONCE.** Every person a pass fills carries that pass's//!   instant in `cotton_people.city_filled_at`, a synced column, and a stamped//!   person is never filled again — on any device, whatever became of the city//!   since. A person whose history holds ANY earlier city is left alone too: the//!   owner who cleared a city by hand has answered (`cotton_changes`, which//!   travels with each act, so every device reads the same clears).//! * **It is listed and undoable.** Home's Done for you shows each recent pass//!   (`reads::done_for_you`), and `people.unfillCities {at}` takes one back://!   it clears the city of every person of that pass whose city is still the//!   one Cotton gave them, and leaves the stamp, so the pass never runs again//!   for them. A city the owner has changed since is his, and is left alone.//! * **It is idempotent.** Asked twice, the second pass finds nobody: the first//!   pass's people now have a city.//! * **It writes through the normal path.** Each fill is one `update_row` on//!   this device's `Ctx::phone` — the op layer every tool writes through — so it//!   reaches the outbox and syncs, and a Mac and a phone that both run it race//!   only towards the same value.//!//! Nothing is guessed: a zone that names no place (`Etc/UTC`) or that this//! build cannot read answers no city, and that person is simply left as they//! were. A person with a city and no zone is never looked at — this does not//! geocode anybody.use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_core::rules::people::zone_city::main_city;use cotton_store::driver::Driver;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{now_iso, update_row};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;pub const METHODS: [&str; 2] = ["people.fillCities", "people.unfillCities"];/// What the receipt calls this write.const LABEL: &str = "people.fillCities";/// What the receipt calls the undo.const UNFILL_LABEL: &str = "people.unfillCities";/// `people.fillCities {}` — answers `{filled: [{id, city, timezone}]}`.pub fn call(handle: &CottonHandle, _request: &Value) -> Result<Value, MethodError> {    fill(&handle.client()).map_err(|reason| MethodError::new("write_refused", reason))}/// One pass. Reads first and writes only when somebody is owed a city, so the/// pass the app runs on every foreground costs one query and wakes nothing on/// the days there is nothing to do.pub fn fill(client: &ClientController) -> Result<Value, String> {    let owed = client.read_rows(LABEL, &mut |ctx| {        Ok(json!({ "owed": owed(ctx.db(), ctx.workspace_id)?.len() }))    })?;    if owed.get("owed").and_then(Value::as_u64).unwrap_or(0) == 0 {        return Ok(json!({ "filled": [] }));    }    let answer = client.write_rows(LABEL, &mut |ctx| fill_in(ctx))?;    // The body's own answer, lifted out of the write envelope.    let own = crate::authoring::own_answer(answer);    Ok(json!({ "filled": own.get("filled").cloned().unwrap_or_else(|| json!([])) }))}/// The write itself: the people still owed a city, asked again INSIDE the/// transaction — a sync that landed between the read and the write may have/// given one of them a city already, and that city wins. Every person of one/// pass carries the same instant, which is how Home lists the pass as one act.fn fill_in(ctx: &mut Ctx<'_>) -> Result<Value, String> {    let at = now_iso(ctx);    let mut filled = Vec::new();    for (id, zone, city) in owed(ctx.db(), ctx.workspace_id)? {        let mut patch = Map::new();        patch.insert("city".to_string(), json!(city));        patch.insert("city_filled_at".to_string(), json!(at));        // The zone the city came from rides along: a city written as words        // without its companions clears them (`place::invalidate_unpicked`),        // and this one's zone is the fact it was filled from.        patch.insert("timezone".to_string(), json!(zone));        update_row(ctx, "cotton_people", &id, patch).map_err(|failure| failure.to_string())?;        filled.push(json!({ "id": id, "city": city, "timezone": zone }));    }    ctx.commit().map_err(|failure| failure.to_string())?;    Ok(json!({ "filled": filled, "at": at }))}/// `people.unfillCities {at}` — answers `{cleared: [id]}`.pub fn call_unfill(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let at = request        .get("at")        .and_then(Value::as_str)        .map(str::trim)        .filter(|at| !at.is_empty())        .ok_or_else(|| MethodError::new("bad_request", "say which fill to take back (at)"))?        .to_string();    unfill(&handle.client(), &at).map_err(|reason| MethodError::new("write_refused", reason))}/// Takes one pass back: every live person of the pass at `at` whose city is/// still the one their zone named loses it. The stamp stays, so the fill never/// comes back for them; a person whose city changed since is not touched.pub fn unfill(client: &ClientController, at: &str) -> Result<Value, String> {    let answer = client.write_rows(UNFILL_LABEL, &mut |ctx| {        let mut cleared = Vec::new();        for (id, _name, _city) in still_filled(ctx.db(), ctx.workspace_id, at)? {            let mut patch = Map::new();            patch.insert("city".to_string(), Value::Null);            // The zone and the pass's stamp stay as they are: a cleared city            // would otherwise clear its zone companion and the stamp, and the            // next pass would fill it again.            let kept = ctx.db().get("SELECT timezone FROM cotton_people WHERE id = ?", &[SqlValue::Text(id.clone())])                .map_err(|error| error.to_string())?                .and_then(|row| row.text("timezone").map(str::to_string));            patch.insert("timezone".to_string(), json!(kept));            patch.insert("city_filled_at".to_string(), json!(at));            update_row(ctx, "cotton_people", &id, patch).map_err(|failure| failure.to_string())?;            cleared.push(json!(id));        }        ctx.commit().map_err(|failure| failure.to_string())?;        Ok(json!({ "cleared": cleared }))    })?;    let own = crate::authoring::own_answer(answer);    Ok(json!({ "cleared": own.get("cleared").cloned().unwrap_or_else(|| json!([])) }))}/// The live people of the pass at `at` whose city is still the one Cotton/// gave them — `(id, name, city)`, by name. Done for you lists these and the/// undo clears these: one question, asked in one place.pub fn still_filled(    db: &Driver,    workspace_id: &str,    at: &str,) -> Result<Vec<(String, String, String)>, String> {    let rows = db        .all(            "SELECT id, full_name, city, timezone FROM cotton_people \             WHERE workspace_id = ? AND city_filled_at = ? AND archived_at IS NULL \             ORDER BY full_name, id",            &[SqlValue::Text(workspace_id.to_string()), SqlValue::Text(at.to_string())],        )        .map_err(|error| error.to_string())?;    Ok(rows        .iter()        .filter_map(|row| {            let id = row.text("id")?.to_string();            let name = row.text("full_name").unwrap_or_default().to_string();            let zone = row.text("timezone")?.trim();            let city = row.text("city")?.trim().to_string();            (main_city(zone).as_deref() == Some(city.as_str())).then_some((id, name, city))        })        .collect())}/// Every live person with a zone, no city, and no city anywhere in their/// history — each with the city their zone names. A person whose zone names no/// place is not owed anything and is not listed.fn owed(db: &Driver, workspace_id: &str) -> Result<Vec<(String, String, String)>, String> {    let rows = db        .all(            "SELECT p.id, p.timezone FROM cotton_people p \             WHERE p.workspace_id = ? AND p.archived_at IS NULL \               AND (p.city IS NULL OR trim(p.city) = '') AND p.city_filled_at IS NULL \               AND p.timezone IS NOT NULL AND trim(p.timezone) <> '' \               AND NOT EXISTS ( \                 SELECT 1 FROM cotton_changes v \                 WHERE v.record_id = p.id AND v.table_id IN ('cotton_people', 'person') \                   AND (trim(coalesce(json_extract(v.before, '$.city'), '')) <> '' \                     OR trim(coalesce(json_extract(v.after, '$.city'), '')) <> '') \               ) \             ORDER BY p.id",            &[SqlValue::Text(workspace_id.to_string())],        )        .map_err(|error| error.to_string())?;    Ok(rows        .iter()        .filter_map(|row| {            let id = row.text("id")?.to_string();            let zone = row.text("timezone")?.trim().to_string();            let city = main_city(&zone)?;            Some((id, zone, city))        })        .collect())}#[cfg(test)]#[path = "people_city_tests.rs"]mod tests;