//! The rows a report lands as, their keys, and how a second copy of an//! order merges with the first.//!//! - `lab_report`: one row per ORDER (`report|<order id>`; a report with no//! order id is its own PDF's: `report|sha|<sha256>`). A partial and a final//! of one order are one row; `versions` lists every PDF received for it.//! - `lab_result`: one row per parameter per order//! (`result|<report key>|<parameter or printed name>|<n>`, `n` counting//! the same parameter twice in one report), so a final lands on the//! partial's rows and nothing doubles. A parameter the partial had and the//! final does not keeps its row.//! - `health_person`: what Health keeps of a person beyond `person`: owner//! or not, sex, date of birth, the printed names confirmed as theirs.//!//! Every key is a PLANNED id: sealed tables key it with the data key//! (`cotton_client::seal::keyed_row_id`), so the Worker sees neither the//! order id nor the parameter in a row's id.use serde::{Deserialize, Serialize};use serde_json::{json, Map, Value};usesuper::catalogue::fold_name;usesuper::report::{Reading, Report, Status};pubconst REPORT_TABLE: &str = "lab_report";pubconst RESULT_TABLE: &str = "lab_result";pubconst PERSON_TABLE: &str = "health_person";/// The people table every app shares.pubconst PEOPLE_TABLE: &str = "person";fn slug(text: &str) -> String { fold_name(text).replace(' ', "")}/// One order for one person: a lab may book a family under one order, so/// the printed name (title, order and case aside) keys it too.pubfn report_key(report: &Report, sha256: &str) -> String {let person = report.name.as_deref().map(super::names::folded_name).unwrap_or_default();match report.order_id.as_deref().map(slug).filter(|order| !order.is_empty()) {Some(order) if person.is_empty() => format!("report|{order}"),Some(order) => format!("report|{order}|{person}"),None => format!("report|sha|{sha256}"), }}/// Each reading's planned key, in the report's order.pubfn result_keys(report: &str, readings: &[Reading]) -> Vec<String> {letmut seen: std::collections::HashMap<String, usize> = std::collections::HashMap::new(); readings .iter() .map(|reading| {let what = match &reading.parameter {Some(id) => id.clone(),None => format!("name:{}", slug(&reading.row.name)), };let n = seen.entry(what.clone()).or_default();let key = format!("result|{report}|{what}|{n}"); *n += 1; key }) .collect()}pubfn person_key(person_id: &str) -> String { format!("health_person|{person_id}")}/// One PDF received for an order.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructVersion {pub sha256: String,/// `partial` or `final`.pub status: String, #[serde(default, skip_serializing_if = "Option::is_none")]pub reported_at: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub mail_message_id: Option<String>,}/// What an order already holds, read from its row.#[derive(Debug, Clone, PartialEq, Eq, Default)]pubstructHeld {pub status: Option<Status>,pub versions: Vec<Version>,}implHeld {pubfn of_row(row: &Map<String, Value>) -> Held {let status = row.get("status").and_then(Value::as_str).and_then(Status::of);let versions = row.get("versions").and_then(Value::as_str).and_then(|text| serde_json::from_str(text).ok()).unwrap_or_default();Held { status, versions } }}/// What to do with a PDF of an order.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumDecision {/// This very PDF came in before: nothing is written.Seen,/// An older copy (a partial after the final): only its version is noted.Older,/// The report and its results are written over what the order held.Write,}/// A report with no status printed is taken as final.pubfn status_of(report: &Report) -> Status { report.status.unwrap_or(Status::Final)}pubfn decide(held: Option<&Held>, sha256: &str, incoming: Status) -> Decision {letSome(held) = held else { returnDecision::Write };if held.versions.iter().any(|version| version.sha256 == sha256) {returnDecision::Seen; }match (held.status, incoming) { (Some(Status::Final), Status::Partial) => Decision::Older, _ => Decision::Write, }}/// Where the report came from and what it keeps of its file.#[derive(Debug, Clone, PartialEq, Default)]pubstructOrigin {/// The person's row id (`person`).pub person: String,/// The sealed PDF's media key.pub pdf: Option<String>,pub sha256: String,pub mail_message_id: Option<String>,pub file_name: Option<String>,/// `import` (the Mac's tool) or `phone` (picked on a phone).pub added_by: &'static str,}fn opt(value: &Option<String>) -> Value { value.clone().map(Value::from).unwrap_or(Value::Null)}fn kept(value: f64) -> Value {crate::health::rows::kept(value)}/// The report row's data. `versions` is every PDF the order has had, this one among them.pubfn report_data(id: &str, report: &Report, origin: &Origin, versions: &[Version]) -> Map<String, Value> {let unmatched = report.readings.iter().filter(|reading| reading.parameter.is_none()).count();let data = json!({"key": id,"person": origin.person,"day": opt(&report.day),"lab": opt(&report.lab),"order_id": opt(&report.order_id),"printed_name": opt(&report.name),"age": opt(&report.age_printed),"age_years": report.age_years.map(kept),"sex": report.sex,"born_on": opt(&report.born_on),"collected_via": opt(&report.collected_via),"sample_type": opt(&report.sample_type),"referred_by": opt(&report.referred_by),"status": status_of(report).as_str(),"collected_at": opt(&report.collected_at),"received_at": opt(&report.received_at),"reported_at": opt(&report.reported_at),"pdf": opt(&origin.pdf),"pdf_sha256": origin.sha256,"versions": serde_json::to_string(versions).expect("versions serialise"),"mail_message_id": opt(&origin.mail_message_id),"file_name": opt(&origin.file_name),"results": report.readings.len(),"unmatched": unmatched,"layout": opt(&report.layout),"added_by": origin.added_by, }); data.as_object().cloned().expect("an object")}/// A result row's data.pubfn result_data(id: &str, report_id: &str, person: &str, report: &Report, reading: &Reading, position: usize) -> Map<String, Value> {let interval = (!reading.interval.is_empty()).then(|| serde_json::to_string(&reading.interval).expect("an interval serialises"));let data = json!({"key": id,"person": person,"report": report_id,"day": opt(&report.day),"parameter": reading.parameter,"name": reading.row.name,"panel": Some(reading.row.panel.clone()).filter(|panel| !panel.is_empty()),"result": reading.value.text,"value": reading.value.number.map(kept),"comparator": reading.value.comparator.map(|c| c.as_str()),"unit": Some(reading.row.unit.clone()).filter(|unit| !unit.is_empty()),"range": Some(reading.row.range.clone()).filter(|range| !range.is_empty()),"range_low": reading.interval.low.map(kept),"range_high": reading.interval.high.map(kept),"interval": interval,"method": Some(reading.row.method.clone()).filter(|method| !method.is_empty()),"specimen": Some(reading.row.specimen.clone()).filter(|specimen| !specimen.is_empty()).or_else(|| report.sample_type.clone()),"flag": reading.flag,"canonical_value": reading.canonical.as_ref().map(|(value, _)| kept(*value)),"canonical_unit": reading.canonical.as_ref().map(|(_, unit)| unit.clone()),"position": position,"page": reading.row.page,"line": reading.row.line, }); data.as_object().cloned().expect("an object")}/// What Health keeps of a person, as a row.#[derive(Debug, Clone, PartialEq, Default)]pubstructHealthPerson {pub person: String,pub owner: bool,pub sex: Option<String>,pub born_on: Option<String>,/// The latest age a report printed, and the day it was collected.pub age_years: Option<f64>,pub age_on: Option<String>,/// Printed names confirmed as theirs.pub names: Vec<String>,/// Where they stand in the switcher (the owner first).pub position: Option<i64>,}implHealthPerson {pubfn of_row(row: &Map<String, Value>) -> HealthPerson {let text = |key: &str| row.get(key).and_then(Value::as_str).map(str::to_string).filter(|text| !text.is_empty());HealthPerson { person: text("person").unwrap_or_default(), owner: row.get("owner").and_then(Value::as_bool).unwrap_or(false), sex: text("sex"), born_on: text("born_on"), age_years: row.get("age_years").and_then(Value::as_f64), age_on: text("age_on"), names: text("names").and_then(|names| serde_json::from_str(&names).ok()).unwrap_or_default(), position: row.get("position").and_then(Value::as_i64), } }pubfn data(&self, id: &str) -> Map<String, Value> {let data = json!({"key": id,"person": self.person,"owner": self.owner,"sex": self.sex,"born_on": self.born_on,"age_years": self.age_years.map(kept),"age_on": self.age_on,"names": serde_json::to_string(&self.names).expect("names serialise"),"position": self.position, }); data.as_object().cloned().expect("an object") }/// Take what a report prints of its person: a name variant now confirmed,/// a sex and a date of birth where none was kept, the latest age.pubfn learn(&mutself, report: &Report) {ifletSome(name) = &report.name {if !self.names.iter().any(|known| super::names::folded_name(known) == super::names::folded_name(name)) {self.names.push(name.clone()); } }ifself.sex.is_none() {self.sex = report.sex.map(str::to_string); }ifself.born_on.is_none() {self.born_on = report.born_on.clone(); }iflet (Some(age), Some(day)) = (report.age_years, &report.day) {ifself.age_on.as_deref().is_none_or(|known| known <= day.as_str()) {self.age_years = Some(age);self.age_on = Some(day.clone()); } } }}