592 lines · 29.7 KB · RustRaw
//! Cotton Health on this phone: the screens' methods, answered from the//! phone's own copy in the shapes `cotton_core::health::app::shapes`//! publishes (the health core's `shapes.md` says them in prose).//!//! ```text//! health.people health.labs health.parameter health.reports health.report//! health.body health.metric health.settings health.addReport health.act health.look//! ```//!//! Every screen reads ONE person's rows (`lab_result`/`lab_report` where//! `person` is theirs), so nothing of one person can reach another's answer;//! the core decides what each screen says. The rows are sealed: they open on//! this phone with its data key, and a state (out of range, changed) is//! worked out here each time and never written. `health.addReport` reads a//! picked PDF with the core's own reader and lands it as the Mac's import does.use std::collections::HashMap;use serde_json::{json, Map, Value};use cotton_core::health::app::{self, body, labs, settings, shapes};use cotton_core::health::app::labs::{PersonEntry, ReportEntry, ResultEntry};use cotton_core::health::catalog;use cotton_core::health::lab::catalogue::{fold_name, Catalogue};use cotton_core::health::lab::names::folded_name;use cotton_core::health::lab::parse::parse;use cotton_core::health::lab::pdf::{pages_of, PdfError};use cotton_core::health::lab::report::read_report;use cotton_core::health::lab::rows::{ decide, person_key, report_data, report_key, result_data, result_keys, status_of, Decision, HealthPerson, Held, Origin, Version, PEOPLE_TABLE, PERSON_TABLE, REPORT_TABLE, RESULT_TABLE,};use cotton_core::health::rows::{DayRow, Source, DAY_TABLE};use crate::handle::CottonHandle;use crate::methods::{dispatch, MethodError};use crate::phone::health::{data_key, data_of, database, records, Keys, UNCHANGED_CHUNK};/// Every method this module answers.pub const METHODS: [&str; 12] = [ "health.act", "health.addPerson", "health.addReport", "health.body", "health.labs", "health.look", "health.metric", "health.parameter", "health.people", "health.report", "health.reports", "health.settings",];/// The days Body reads back: a year and a month of each metric.const BODY_DAYS: i64 = 400;fn bad(field: &str, shape: &str) -> MethodError { MethodError::new("bad_request", format!("`{field}` is {shape}"))}fn text<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> { optional(request, field).ok_or_else(|| bad(field, "required text"))}fn optional<'a>(request: &'a Value, field: &str) -> Option<&'a str> { request.get(field).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty())}fn answer<T: serde::Serialize>(value: T) -> Result<Value, MethodError> { serde_json::to_value(value).map_err(|error| MethodError::new("unanswerable", error.to_string()))}pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> { match method { "health.look" => answer(app::look()), "health.people" => answer(labs::people(&people(handle)?, optional(request, "person"))), "health.labs" => { let person = screen_person(handle, request)?; answer(labs::labs(&person, &results_of(handle, &person.id)?, Catalogue::shipped(), optional(request, "q").unwrap_or_default())) } "health.parameter" => { let person = person(handle, request)?; let group = match (optional(request, "parameter"), optional(request, "name")) { (Some(id), _) => id.to_string(), (None, Some(name)) => format!("name:{}", fold_name(name).replace(' ', "")), _ => return Err(bad("parameter", "a parameter id, or `name` a printed name")), }; answer(labs::parameter(&person, &group, &results_of(handle, &person.id)?, &reports_of(handle, &person.id)?, Catalogue::shipped())) } "health.reports" => { let person = screen_person(handle, request)?; answer(labs::reports(&person, &reports_of(handle, &person.id)?, &results_of(handle, &person.id)?)) } "health.report" => { let id = text(request, "id")?; let report = report_entry(handle, id)?; let person = person_by_id(handle, &report.person)?; let results = rows(handle, RESULT_TABLE, json!({ "report": id }))?.iter().filter_map(ResultEntry::of_row).collect::<Vec<_>>(); answer(labs::report(&person, &report, &results)) } "health.body" => { let person = screen_person(handle, request)?; let days = if person.owner { days(handle, json!({ "day": { "within_days": BODY_DAYS } }))? } else { Vec::new() }; let today = optional(request, "today").map(str::to_string).unwrap_or_else(|| handle.client().now().format("%Y-%m-%d").to_string()); answer(body::body(&person, &days, &results_of(handle, &person.id)?, &today, reads_apple_health(request))) } "health.metric" => { let person = person(handle, request)?; let metric = text(request, "metric")?; if catalog::metric_of(metric).is_none() { return Err(bad("metric", "a metric health.types lists")); } let days = if person.owner { days(handle, json!({ "metric": metric }))? } else { Vec::new() }; answer(body::metric(&person, metric, &days, &results_of(handle, &person.id)?)) } "health.settings" => { let all = rows(handle, RESULT_TABLE, json!({}))?.iter().filter_map(ResultEntry::of_row).collect::<Vec<_>>(); let mut said = settings::settings(&people(handle)?, labs::unknown_names(&all).len(), Catalogue::shipped(), reads_apple_health(request)); said.sections.push(account(&handle.client())); answer(said) } "health.addReport" => add_report(handle, request), "health.addPerson" => { let id = add_person(handle, &NewPerson::of(request.get("newPerson").unwrap_or(request))?)?; let person = person_by_id(handle, &id)?; answer(json!({ "person": id, "toast": toast("people.added", &[("name", &person.name)]), "open": labs::act("switch", app::sayf("acts.switch", &[("name", &person.name)]), "health.labs", json!({ "person": id })) })) } "health.act" => act(handle, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a Health screen"))), }}// ── reading the copy ───────────────────────────────────────────────────fn rows(handle: &CottonHandle, table: &str, filter: Value) -> Result<Vec<Map<String, Value>>, MethodError> { Ok(records(handle, table, filter)?.iter().map(data_of).collect())}fn results_of(handle: &CottonHandle, person: &str) -> Result<Vec<ResultEntry>, MethodError> { // No one kept yet (screen_person): nothing is theirs. if person.is_empty() { return Ok(Vec::new()); } Ok(rows(handle, RESULT_TABLE, json!({ "person": person }))?.iter().filter_map(ResultEntry::of_row).collect())}fn reports_of(handle: &CottonHandle, person: &str) -> Result<Vec<ReportEntry>, MethodError> { if person.is_empty() { return Ok(Vec::new()); } Ok(rows(handle, REPORT_TABLE, json!({ "person": person }))?.iter().filter_map(ReportEntry::of_row).collect())}fn report_entry(handle: &CottonHandle, id: &str) -> Result<ReportEntry, MethodError> { let record = dispatch(handle, "records.get", &json!({ "table": REPORT_TABLE, "id": id }))?; ReportEntry::of_row(&data_of(record.get("record").unwrap_or(&record))).ok_or_else(|| MethodError::new("record_not_found", "no such report"))}fn days(handle: &CottonHandle, filter: Value) -> Result<Vec<DayRow>, MethodError> { Ok(rows(handle, DAY_TABLE, filter)? .iter() .filter_map(|row| { let metric = catalog::metric_of(row.get("metric")?.as_str()?)?.key; Some(DayRow { metric, day: row.get("day")?.as_str()?.to_string(), value: row.get("value").and_then(Value::as_f64), min: row.get("min").and_then(Value::as_f64), max: row.get("max").and_then(Value::as_f64), samples: row.get("samples").and_then(Value::as_i64), state: row.get("state").and_then(Value::as_str).map(str::to_string), source: row.get("source").and_then(Value::as_str).and_then(Source::of).unwrap_or(Source::HealthKit), }) }) .collect())}/// Health's own row of each person, by person id.fn health_people(handle: &CottonHandle) -> Result<HashMap<String, (String, HealthPerson)>, MethodError> { Ok(rows(handle, PERSON_TABLE, json!({}))? .iter() .filter_map(|row| { let held = HealthPerson::of_row(row); let id = row.get("id").and_then(Value::as_str)?.to_string(); (!held.person.is_empty()).then(|| (held.person.clone(), (id, held))) }) .collect())}fn person_name(handle: &CottonHandle, id: &str) -> Option<String> { let record = dispatch(handle, "records.get", &json!({ "table": PEOPLE_TABLE, "id": id })).ok()?; data_of(record.get("record").unwrap_or(&record)).get("full_name").and_then(Value::as_str).map(str::to_string)}/// Everyone whose records are kept, with how many reports each.fn people(handle: &CottonHandle) -> Result<Vec<PersonEntry>, MethodError> { let mut counts: HashMap<String, u32> = HashMap::new(); for row in rows(handle, REPORT_TABLE, json!({}))? { if let Some(person) = row.get("person").and_then(Value::as_str) { *counts.entry(person.to_string()).or_default() += 1; } } let mut out = Vec::new(); for (person, (_, held)) in health_people(handle)? { out.push(PersonEntry { name: person_name(handle, &person).or_else(|| held.names.first().cloned()).unwrap_or_default(), owner: held.owner, sex: held.sex.clone(), born_on: held.born_on.clone(), position: held.position, reports: counts.get(&person).copied().unwrap_or(0), id: person, }); } Ok(out)}fn person_by_id(handle: &CottonHandle, id: &str) -> Result<PersonEntry, MethodError> { people(handle)?.into_iter().find(|person| person.id == id).ok_or_else(|| bad("person", "a person whose records are kept"))}/// The person a request names, else the owner (else the first kept).fn person(handle: &CottonHandle, request: &Value) -> Result<PersonEntry, MethodError> { let everyone = labs::ordered(&people(handle)?); match optional(request, "person") { Some(id) => everyone.into_iter().find(|person| person.id == id).ok_or_else(|| bad("person", "a person whose records are kept")), None => everyone.into_iter().next().ok_or_else(|| MethodError::new("no_person", "no records are kept for anyone yet")), }}/// Settings' last section: whether this phone is signed in, and Sign in, Back up now or Sign out as its/// state offers them (tool_acts::offered_account), as Cotton Vault's Settings says it. Health keeps sealed/// tables, so a phone signs in here before its records can open.fn account(client: &crate::shell::client::ClientController) -> shapes::SettingsSection { let status = crate::phone::tool_acts::account_status(client); let signed_in = status["signed_in"] == json!(true) || status["backing_up"] == json!(true); let mut acts = Vec::new(); for act in ["sign_in", "back_up", "sign_out"] { let id = match act { "sign_in" => crate::phone::tool_acts::ACCOUNT_SIGN_IN, "back_up" => crate::phone::tool_acts::ACCOUNT_BACK_UP, _ => crate::phone::tool_acts::ACCOUNT_SIGN_OUT, }; if !crate::phone::tool_acts::offered_account(id, &status) { continue; } let mut one = labs::act(act, app::say(&format!("settings.{act}")), "health.act", json!({ "act": act })); match act { "sign_in" => one.tone = shapes::Tone::Accent, "sign_out" => { one.tone = shapes::Tone::Danger; one.confirm = Some(shapes::Confirm { title: app::say("settings.sign_out_title"), body: app::say("settings.sign_out_body"), yes: app::say("settings.sign_out"), no: app::say("settings.sign_out_no") }); } _ => {} } acts.push(one); } shapes::SettingsSection { id: "account".into(), title: app::say("settings.account"), rows: vec![shapes::SettingsRow { id: "account".into(), label: app::say(if signed_in { "settings.signed_in" } else { "settings.not_signed_in" }), detail: None, acts }], }}/// Whether the asking phone reads Apple Health: every phone but one that says `platform: android`.fn reads_apple_health(request: &Value) -> bool { optional(request, "platform") != Some("android")}/// The person a place (Labs, Reports, Body) stands for: as [person], but before anyone's records are kept, the/// owner-to-be with nothing, so the place answers its empty state and Add a report rather than a refusal.fn screen_person(handle: &CottonHandle, request: &Value) -> Result<PersonEntry, MethodError> { match person(handle, request) { Err(error) if error.code == "no_person" => Ok(PersonEntry { owner: true, ..PersonEntry::default() }), other => other, }}// ── writing ────────────────────────────────────────────────────────────/// The picked PDF into this phone's media store and the upload ledger under the report's key, as/// `capture.media` keeps a document: the bytes first, then the ledger row the media drain claims, seals/// and uploads with backoff. `open_pdf`'s `media.ensure` then answers this copy, signed in or not.fn keep_pdf(handle: &CottonHandle, path: &str, key: &str) -> Result<(), MethodError> { use cotton_client::media::store::put_media_file; use cotton_store::media_ledger::{enqueue_media, MediaEnqueueInput}; let client = handle.client(); let layout = client.layout().clone(); let key = key.to_string(); client .write_rows("health.addReport", &mut |ctx| { let workspace_id = ctx.workspace_id.to_string(); let stored = put_media_file(&layout, &workspace_id, std::path::Path::new(path), "pdf") .map_err(|error| format!("the report's PDF could not be copied into this device's store: {}", error.kind()))?; let now = cotton_tools::mcp::handlers::common::now_iso(ctx); enqueue_media( ctx.db(), &MediaEnqueueInput { key: key.clone(), workspace_id, sha256: stored.sha256.clone(), content_type: "application/pdf".to_string(), size_bytes: i64::try_from(stored.size_bytes).unwrap_or(i64::MAX), local_path: Some(stored.path.to_string_lossy().to_string()), state: None, after: None, after_row_id: None, tier: Some(cotton_store::media_holdings::Tier::Original), // Picked on this phone: kept here for good, as a document filed here is. captured_here: true, now, }, ) .map_err(|error| error.to_string())?; Ok(Value::Null) }) .map(|_| ()) .map_err(|reason| MethodError::new("write_refused", reason))}enum Write { /// A row of a keyed table, put whole (its key in its data). Put(&'static str, Map<String, Value>), /// A new row of a table with no key (a person): its answer names its id. Create(&'static str, Map<String, Value>),}/// Write in one transaction; answers the id of each `Create`, in order.fn apply(handle: &CottonHandle, label: &str, writes: Vec<Write>) -> Result<Vec<String>, MethodError> { let unchanged = cotton_core::records::RecordError::NothingToChange.to_string(); let mut made = Vec::new(); let written = handle.client().write_rows(label, &mut |ctx| { made.clear(); let mut changed = 0usize; for write in &writes { match write { Write::Put(table, data) => { let args = json!({ "table": table, "data": Value::Object(data.clone()) }); match cotton_tools::mcp::handlers::tables::create_produced_record(ctx, args.as_object().expect("an object")) { Ok(_) => changed += 1, Err(failure) if failure.to_string() == unchanged => {} Err(failure) => return Err(failure.to_string()), } } Write::Create(table, data) => { let args = json!({ "table": table, "data": Value::Object(data.clone()) }); let written = cotton_tools::mcp::handlers::tables::create_record(ctx, args.as_object().expect("an object")).map_err(|failure| failure.to_string())?; let id = written.pointer("/record/id").and_then(Value::as_str).unwrap_or_default().to_string(); made.push(id); changed += 1; } } } if changed == 0 { return Err(UNCHANGED_CHUNK.to_string()); } Ok(Value::Null) }); match written { Ok(_) => Ok(made), Err(reason) if reason == UNCHANGED_CHUNK => Ok(made), Err(reason) => Err(MethodError::new("write_refused", reason)), }}fn row_ids(handle: &CottonHandle) -> Result<Keys, MethodError> { let client = handle.client(); let database = database(&client)?; Ok(Keys { dk: data_key(&client, &database)?, database })}fn toast(line: &str, fills: &[(&str, &str)]) -> shapes::Toast { shapes::Toast { text: app::sayf(line, fills), undo: None }}fn refused(outcome: &str) -> Result<Value, MethodError> { answer(shapes::AddAnswer { outcome: outcome.into(), report: None, results: 0, matched: 0, unmatched: Vec::new(), toast: toast(&format!("add.{outcome}"), &[]), open: None })}/// A PDF the person picked, for the person they chose (or someone new).fn add_report(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> { let path = text(request, "path")?; let bytes = std::fs::read(path).map_err(|error| MethodError::new("unreadable", format!("the picked file could not be read: {}", error.kind())))?; let pages = match pages_of(&bytes) { Ok(pages) => pages, Err(PdfError::Locked) => return refused("locked"), Err(_) => return refused("unreadable"), }; if pages.iter().all(|page| page.lines.is_empty()) { return refused("no_text"); } let zone = optional(request, "zone").and_then(|zone| zone.parse::<chrono_tz::Tz>().ok()).unwrap_or(chrono_tz::Asia::Kolkata); let report = read_report(&parse(&pages), Catalogue::shipped(), zone); if report.layout.is_none() || report.readings.is_empty() { return refused("no_table"); } let ids = row_ids(handle)?; // Whose: a person kept, or someone new by the name given. let person = match (optional(request, "person"), optional(request, "newPerson")) { (Some(id), _) => id.to_string(), (None, _) if request.get("newPerson").is_some() => add_person(handle, &NewPerson::of(&request["newPerson"])?)?, _ => return Err(bad("person", "a person's id, or `newPerson` a name")), }; let sha = { use sha2::Digest; hex::encode(sha2::Sha256::digest(&bytes)) }; let planned = report_key(&report, &sha); let report_id = ids.id(REPORT_TABLE, &planned)?; let held_row = dispatch(handle, "records.get", &json!({ "table": REPORT_TABLE, "id": report_id })).ok().map(|record| data_of(record.get("record").unwrap_or(&record))); let held = held_row.as_ref().map(Held::of_row); let incoming = status_of(&report); let mut versions = held.as_ref().map(|held| held.versions.clone()).unwrap_or_default(); if !versions.iter().any(|version| version.sha256 == sha) { versions.push(Version { sha256: sha.clone(), status: incoming.as_str().into(), reported_at: report.reported_at.clone(), mail_message_id: None }); } let unmatched = report.unmatched(); let base = |outcome: &str, results: u32, line: &str, fills: &[(&str, &str)]| shapes::AddAnswer { outcome: outcome.into(), report: Some(report_id.clone()), results, matched: report.matched() as u32, unmatched: unmatched.clone(), toast: toast(line, fills), open: Some(labs::act("open", app::say("labs.open"), "health.report", json!({ "id": report_id }))), }; match decide(held.as_ref(), &sha, incoming) { Decision::Seen => answer(base("seen", report.readings.len() as u32, "add.seen", &[])), Decision::Older => { let mut row = held_row.clone().unwrap_or_default(); row.remove("id"); row.insert("versions".into(), json!(serde_json::to_string(&versions).expect("versions serialise"))); apply(handle, "health.addReport", vec![Write::Put(REPORT_TABLE, row)])?; answer(base("older", report.readings.len() as u32, "add.older", &[])) } Decision::Write => { let database = database(&handle.client())?; let pdf_row = ids.id(REPORT_TABLE, &format!("pdf|{sha}"))?; let pdf_key = format!("{database}/{pdf_row}/original.pdf"); // The PDF is sealed and sent by the shell's own upload (the phone's media path), under this key. let origin = Origin { person: person.clone(), pdf: Some(pdf_key.clone()), sha256: sha.clone(), mail_message_id: None, file_name: std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()), added_by: "phone" }; let mut writes = vec![Write::Put(REPORT_TABLE, report_data(&report_id, &report, &origin, &versions))]; for (position, (reading, key)) in report.readings.iter().zip(result_keys(&planned, &report.readings)).enumerate() { let id = ids.id(RESULT_TABLE, &key)?; writes.push(Write::Put(RESULT_TABLE, result_data(&id, &report_id, &person, &report, reading, position))); } let kept = health_people(handle)?; let (_, mut health) = kept.get(&person).cloned().unwrap_or_else(|| (String::new(), HealthPerson { person: person.clone(), ..HealthPerson::default() })); health.learn(&report); if health.position.is_none() { health.position = Some(1 + kept.len() as i64); } writes.push(Write::Put(PERSON_TABLE, health.data(&ids.id(PERSON_TABLE, &person_key(&person))?))); apply(handle, "health.addReport", writes)?; keep_pdf(handle, path, &pdf_key)?; let n = report.readings.len().to_string(); let mut said = base(if held.is_some() { "updated" } else { "added" }, report.readings.len() as u32, "add.added", &[("n", &n)]); if held.is_some() { said.toast = toast("add.updated", &[]); } let mut value = serde_json::to_value(said).map_err(|error| MethodError::new("unanswerable", error.to_string()))?; // The PDF is already in this phone's store and queued (`kept`): the media drain seals and uploads // it under this key, so a shell sends nothing itself. value["upload"] = json!({ "path": path, "key": pdf_key, "contentType": "application/pdf", "kept": true }); Ok(value) } }}/// Someone new whose records Health keeps: a name, and their sex and date of/// birth when known. `newPerson` is a name, or `{name, sex?, bornOn?}`.struct NewPerson { name: String, sex: Option<String>, born_on: Option<String>,}impl NewPerson { fn of(value: &Value) -> Result<NewPerson, MethodError> { let name = value.as_str().or_else(|| value.get("name").and_then(Value::as_str)).map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| bad("newPerson", "a name, or {name, sex?, bornOn?}"))?; let sex = match optional(value, "sex") { Some(sex @ ("male" | "female")) => Some(sex.to_string()), None => None, Some(_) => return Err(bad("sex", "`male`, `female`, or absent")), }; let born_on = match optional(value, "bornOn") { Some(day) if cotton_core::health::rows::is_day(day) => Some(day.to_string()), None => None, Some(_) => return Err(bad("bornOn", "a day, YYYY-MM-DD")), }; Ok(NewPerson { name: name.to_string(), sex, born_on }) }}/// The shared `person` row (its name alone: the rest of a person is People's)/// and Health's row beside it, in one write. Health names `person` in its tool/// only to keep its people; it draws no People view and pulls no People table.fn add_person(handle: &CottonHandle, new: &NewPerson) -> Result<String, MethodError> { let made = apply(handle, "health.addPerson", vec![Write::Create(PEOPLE_TABLE, json!({ "full_name": new.name }).as_object().cloned().expect("an object"))])?; let id = made.into_iter().next().filter(|id| !id.is_empty()).ok_or_else(|| MethodError::new("write_refused", "the person was not made"))?; let ids = row_ids(handle)?; let kept = health_people(handle)?; let health = HealthPerson { person: id.clone(), sex: new.sex.clone(), born_on: new.born_on.clone(), names: vec![new.name.clone()], position: Some(1 + kept.len() as i64), ..HealthPerson::default() }; apply(handle, "health.addPerson", vec![Write::Put(PERSON_TABLE, health.data(&ids.id(PERSON_TABLE, &person_key(&id))?))])?; Ok(id)}/// `set_sex {person, value}`, `set_born {person, value}`, `set_owner {person}`,/// `open_pdf {id}`, `connect_apple_health {}`.fn act(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> { let done = |value: Value| answer(shapes::ActAnswer { ok: true, toast: None, value }); match text(request, "act")? { "open_pdf" => { let report = report_entry(handle, text(request, "id")?)?; let key = report.pdf.ok_or_else(|| MethodError::new("no_file", "this report keeps no PDF"))?; done(json!({ "key": key, "contentType": "application/pdf" })) } "connect_apple_health" => done(json!({ "reads": "apple_health" })), // Account: this device's own flow (`platform_action: open_flow`) or the core's words, as Vault runs them. what @ ("sign_in" | "back_up" | "sign_out") => { let id = match what { "sign_in" => crate::phone::tool_acts::ACCOUNT_SIGN_IN, "back_up" => crate::phone::tool_acts::ACCOUNT_BACK_UP, _ => crate::phone::tool_acts::ACCOUNT_SIGN_OUT, }; let answered = crate::phone::tool_acts::account(&handle.client(), id)?; let toast = answered["said"].as_str().map(|said| shapes::Toast { text: said.to_string(), undo: None }); let platform = answered.get("platform_action").map(|_| answered.clone()).unwrap_or(Value::Null); answer(shapes::ActAnswer { ok: true, toast, value: platform }) } act @ ("set_sex" | "set_born" | "set_owner") => { let ids = row_ids(handle)?; let person = text(request, "person")?.to_string(); let mut kept = health_people(handle)?; let (_, mut health) = kept.remove(&person).unwrap_or_else(|| (String::new(), HealthPerson { person: person.clone(), ..HealthPerson::default() })); let mut writes = Vec::new(); match act { "set_sex" => { health.sex = match optional(request, "value") { Some(sex @ ("male" | "female")) => Some(sex.to_string()), // Not said: absent, or the empty choice. None | Some("") => None, Some(_) => return Err(bad("value", "`male`, `female`, or absent")), } } "set_born" => { health.born_on = match optional(request, "value") { Some(day) if cotton_core::health::rows::is_day(day) => Some(day.to_string()), None => None, Some(_) => return Err(bad("value", "a day, YYYY-MM-DD")), } } _ => { health.owner = true; health.position = Some(0); for (other, (_, mut held)) in kept { if held.owner { held.owner = false; held.position = Some(1); writes.push(Write::Put(PERSON_TABLE, held.data(&ids.id(PERSON_TABLE, &person_key(&other))?))); } } } } writes.push(Write::Put(PERSON_TABLE, health.data(&ids.id(PERSON_TABLE, &person_key(&person))?))); apply(handle, "health.act", writes)?; done(Value::Null) } other => Err(MethodError::new("unknown_act", format!("`{other}` is not a Health act"))), }}/// The name a person goes by in Health, for matching a picked report's printed name.pub fn known_by(handle: &CottonHandle) -> Result<Vec<(String, Vec<String>)>, MethodError> { let health = health_people(handle)?; Ok(people(handle)? .into_iter() .map(|person| { let mut names = vec![person.name.clone()]; if let Some((_, held)) = health.get(&person.id) { names.extend(held.names.iter().cloned()); } names.sort_by_key(|name| folded_name(name)); (person.id, names) }) .collect())}#[cfg(test)]#[path = "health_app_tests.rs"]mod tests;