//! A read's stamps as the core's day parts, put beside the stamps //! (`@day_parts`), so a screen draws a date and never spells one. use cotton_core::rules::shell_lines::{LineRow, LineSet}; use cotton_core::records::page::{attach_stamp_parts, DateWords, DAY_PARTS_KEY}; use serde_json::Value; use crate::shell::client::ClientController; use crate::CottonHandle; /// Where each read's stamps sit: the method, the path to the objects that /// hold them (`list[]` walks a list, `*` every member of an object) and the /// stamp keys. A screen reads each one's parts with `JSONValue.day(key)`. const STAMPED: &[(&str, &str, &[&str])] = &[ ("read.devices", "devices[]", &["lastSeenAt", "sampledAt", "approvedAt"]), ("devices.pending", "pending[]", &["createdAt"]), ("google.status", "accounts[].*", &["syncedAt"]), ("read.syncStatus", "", &["lastPullAt"]), ("sync.now", "", &["lastPullAt"]), ("read.home", "doneForYou[]", &["at"]), ("read.home", "workingOn", &["oldestQueuedAt"]), ("sync.rejected", "rejected[]", &["at"]), ("read.find", "hits[]", &["when"]), ("read.find", "defined.*.hits[]", &["when"]), ("server.householdRefusal", "householdRefusal", &["refusedAt"]), ("read.secret", "placements[]", &["appliedAt"]), ("read.project", "linked.*[]", &["takenAt", "startedAt"]), ("records.page", "reach[].channels[]", &["lastActivity"]), ("read.session", "session", &["startedAt", "endedAt"]), ("read.session", "prompts[]", &["ts"]), ("read.session", "messages[]", &["createdAt"]), ("read.repoRuns", "runs[]", &["startedAt", "createdAt"]), ("read.repoRun", "run", &["startedAt", "createdAt"]), ("read.repoReleases", "releases[]", &["publishedAt"]), ("read.repoRelease", "release", &["publishedAt"]), ("read.repoIssues", "issues[]", &["remoteUpdatedAt"]), ("read.repoIssue", "issue", &["remoteUpdatedAt"]), ("read.repoPulls", "pulls[]", &["remoteUpdatedAt"]), ("read.repoPull", "pull", &["remoteUpdatedAt"]), ]; /// A read's answer with its stamps' day parts beside them. pub(crate) fn on_answer(handle: &CottonHandle, method: &str, answer: &mut Value) { let mut places = STAMPED.iter().filter(|(stamped, ..)| *stamped == method).peekable(); if places.peek().is_none() { return; } let stamps = Stamps::of(&handle.client()); for (_, path, keys) in places { stamps.at(answer, path, keys); } if method == "read.session" { stamps.say_session(answer); } } /// The reader's zone, the read's now and the database's date words. pub(crate) struct Stamps { zone: String, now: chrono::DateTime, dates: DateWords, /// The database's line rows, for the sentences a stamp sits in. rows: Vec, } impl Stamps { pub(crate) fn of(client: &ClientController) -> Self { let mut rows = Vec::new(); let _ = client.read_rows("stamps", &mut |ctx| { rows = cotton_tools::presentation::line_rows(ctx.read.driver(), ctx.workspace_id); Ok(Value::Null) }); let mut stamps = Self::new(client.time_zone().unwrap_or("Etc/UTC"), client.clock().now(), DateWords::of_rows(&rows)); stamps.rows = rows; stamps } pub(crate) fn new(zone: &str, now: chrono::DateTime, dates: DateWords) -> Self { Self { zone: zone.to_string(), now, dates, rows: Vec::new() } } /// A session's start and end as the transcript's pencil lines say them /// (`dispatch.transcript.*`), put on the session as `startedLine` and /// `endedLine` — after its stamps, whose clock they read. pub(crate) fn say_session(&self, answer: &mut Value) { let Some(session) = answer.get_mut("session").and_then(Value::as_object_mut) else { return; }; let Some(lines) = LineSet::of_rows("dispatch", &self.rows) else { return; }; let clock = |key: &str| { session.get(DAY_PARTS_KEY)?.get(key)?.get("clock")?.as_str().map(str::to_string) }; let text = |key: &str| { session.get(key).and_then(Value::as_str).map(str::trim).filter(|words| !words.is_empty()) }; let between = lines.say("between", &[]).unwrap_or_default(); let who = [text("machine"), text("account")].into_iter().flatten().collect::>().join(&between); let started = clock("startedAt").and_then(|clock| lines.say("transcript.started", &[("who", &who), ("clock", &clock)])); let ended = clock("endedAt").and_then(|clock| lines.say("transcript.ended", &[("clock", &clock)])); for (key, line) in [("startedLine", started), ("endedLine", ended)] { if let Some(line) = line { session.insert(key.to_string(), Value::String(line)); } } } /// The named stamps of one object. pub(crate) fn on(&self, object: &mut Value, keys: &[&str]) { if let Some(object) = object.as_object_mut() { attach_stamp_parts(object, keys, &self.zone, self.now, &self.dates); } } /// The named stamps of every object `path` reaches in `answer`. pub(crate) fn at(&self, answer: &mut Value, path: &str, keys: &[&str]) { let path: Vec<&str> = path.split('.').filter(|segment| !segment.is_empty()).collect(); walk(answer, &path, &mut |object| self.on(object, keys)); } /// The named stamps of every object in the list at `list`. pub(crate) fn on_each(&self, list: Option<&mut Value>, keys: &[&str]) { for row in list.and_then(Value::as_array_mut).into_iter().flatten() { self.on(row, keys); } } } fn walk(value: &mut Value, path: &[&str], apply: &mut dyn FnMut(&mut Value)) { let Some((segment, rest)) = path.split_first() else { return apply(value); }; let (name, each) = segment.strip_suffix("[]").map_or((*segment, false), |name| (name, true)); let children: Vec<&mut Value> = match name { "*" => value.as_object_mut().map(|object| object.values_mut().collect()).unwrap_or_default(), name => value.get_mut(name).into_iter().collect(), }; for child in children { match each { true => child.as_array_mut().into_iter().flatten().for_each(|item| walk(item, rest, apply)), false => walk(child, rest, apply), } } } #[cfg(test)] mod tests { use super::*; use serde_json::json; #[test] fn every_stamp_a_path_reaches_carries_its_parts() { let now = chrono::DateTime::parse_from_rfc3339("2026-10-14T10:03:00Z").unwrap().with_timezone(&chrono::Utc); let stamps = Stamps::new("UTC", now, DateWords::shipped().clone()); let mut answer = json!({ "accounts": [{ "calendar": { "syncedAt": "2026-10-14T10:00:00Z" }, "gmail": { "syncedAt": "2026-10-13T09:00:00Z" } }], "linked": { "photos": [{ "takenAt": "2026-08-17T12:00:00Z" }], "calls": [{ "startedAt": "2026-10-14T08:00:00Z" }] }, "lastPullAt": "2026-10-14T10:02:00Z", "defined": { "synthetic_find": { "hits": [{ "when": "2026-10-13T09:00:00Z" }] } }, }); stamps.at(&mut answer, "defined.*.hits[]", &["when"]); assert_eq!(answer["defined"]["synthetic_find"]["hits"][0]["@day_parts"]["when"]["recent"], "Yesterday"); stamps.at(&mut answer, "accounts[].*", &["syncedAt"]); stamps.at(&mut answer, "linked.*[]", &["takenAt", "startedAt"]); stamps.at(&mut answer, "", &["lastPullAt"]); assert_eq!(answer["accounts"][0]["calendar"]["@day_parts"]["syncedAt"]["ago"], "3 min ago"); assert_eq!(answer["accounts"][0]["gmail"]["@day_parts"]["syncedAt"]["recent"], "Yesterday"); assert_eq!(answer["linked"]["photos"][0]["@day_parts"]["takenAt"]["day_long"], "17 August"); assert_eq!(answer["linked"]["calls"][0]["@day_parts"]["startedAt"]["clock"], "8:00 am"); assert_eq!(answer["@day_parts"]["lastPullAt"]["ago"], "1 min ago"); } #[test] fn a_sessions_start_and_end_are_said_in_the_dispatch_lines() { let now = chrono::DateTime::parse_from_rfc3339("2026-10-14T10:03:00Z").unwrap().with_timezone(&chrono::Utc); let mut stamps = Stamps::new("UTC", now, DateWords::shipped().clone()); stamps.rows = vec![LineRow { set: "dispatch".into(), line: "transcript.ended".into(), words: "done at {clock}".into() }]; let mut answer = json!({ "session": { "machine": "Studio Mac", "account": "owner@example.com", "startedAt": "2026-10-14T09:04:00Z", "endedAt": "2026-10-14T18:12:00Z" }, "prompts": [{ "ts": "2026-10-14T09:05:00Z" }], }); stamps.at(&mut answer, "session", &["startedAt", "endedAt"]); stamps.at(&mut answer, "prompts[]", &["ts"]); stamps.say_session(&mut answer); assert_eq!(answer["session"]["startedLine"], "started on Studio Mac · owner@example.com · 9:04 am"); assert_eq!(answer["session"]["endedLine"], "done at 6:12 pm"); assert_eq!(answer["prompts"][0]["@day_parts"]["ts"]["clock"], "9:05 am"); } }