//! A folder of lab reports into the owner's object: `pnpm -s health:import//! <folder> --zone <IANA zone> [--dry] …` (src/bin/health_import.rs).//!//! Each PDF (or each PDF attached to a `.eml` mail, its Message-ID kept) is//! read for its text layer and its result table by `cotton_core::health::lab`//! (pure Rust: no poppler, no PDFKit), matched to the canonical parameters,//! and landed sealed as the owner: the person it is for, the report (one row//! per order, the PDF sealed beside it) and its results.//!//! **Whose.** The name printed on a report is matched against the people the//! owner keeps (`person`, and the printed names `health_person` remembers).//! Title, order, case and spacing never split a person; initials, or a name//! that fits two of the family, are ASKED: the report waits, listed in the//! summary, until the run says `--same "<printed>=<person>"`. A name nobody//! has is proposed as a new person and waits for `--new "<printed>"` (or//! `--add-people` for every one proposed). `--owner "<name>"` says which//! person is the owner.//!//! **Idempotent.** A PDF already received (its sha256 among the order's//! versions) is `seen` and nothing is written; a final lands on its partial's//! rows by key; a partial after the final only notes its version.//!//! **Never a value.** The summary says, per file, counts, the test names not//! yet known, the line numbers that read as nothing, whose it is and what//! was done. The names of people are said (the summary is the owner's, on the//! owner's Mac); a result, a range, an order id or a date never is.use std::collections::{BTreeMap, HashMap, HashSet};use std::path::{Path, PathBuf};use serde::Serialize;use serde_json::{json, Map, Value};use cotton_core::health::lab::catalogue::Catalogue;use cotton_core::health::lab::names::{folded_name, name_words, whose, Whose};use cotton_core::health::lab::parse::parse;use cotton_core::health::lab::pdf::pages_of;use cotton_core::health::lab::report::{read_report, Report, Status};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,};usecrate::ids::sha256_hex;usecrate::music::import::{Object, Row};usecrate::object::ObjectError;/// Makes a row's id from its planned key: the data key's keyed id on a real/// object, the plain key in memory.pubtraitKeyer {fn id(&self, table: &str, planned: &str) -> String;}/// The plain key itself: a dry run against nothing, and the tests.pubstructPlain;implKeyerforPlain {fn id(&self, _table: &str, planned: &str) -> String { planned.to_string() }}/// The data key's keyed id, as the phone makes it.pubstructKeyed {pub dk: cotton_core::seal::DataKey,pub database_id: String,}implKeyerforKeyed {fn id(&self, table: &str, planned: &str) -> String { cotton_client::seal::keyed_row_id(&self.dk, &self.database_id, table, planned).expect("a data key keys any id") }}/// What the run is told.#[derive(Debug, Clone)]pubstructOptions {pub zone: chrono_tz::Tz,pub dry: bool,/// The owner, by a name `whose` finds (or one of `new_people`).pub owner: Option<String>,/// Printed name → the person it is (a person's name or row id).pub same: Vec<(String, String)>,/// Printed names confirmed as new people.pub new_people: Vec<String>,/// Every proposed new person is made.pub add_people: bool,/// Read a PDF again though its version is in (a better reader).pub reread: bool,}/// One PDF to read.#[derive(Debug, Clone)]pubstructFileIn {/// Shown in the summary: the file's name (and the attachment's, from a mail).pub shown: String,pub bytes: Vec<u8>,pub mail_message_id: Option<String>,}/// Every PDF under `folder` (and in its `.eml` mails), sorted by name. A/// PDF's `<name>.json` beside it may say `{ "mail_message_id": "…" }`.pubfn files_in(folder: &Path) -> Result<Vec<FileIn>, String> {letmut paths: Vec<PathBuf> = Vec::new();letmut stack = vec![folder.to_path_buf()];whileletSome(dir) = stack.pop() {if dir.is_file() { paths.push(dir);continue; }let entries = std::fs::read_dir(&dir).map_err(|e| format!("{} cannot be read: {e}", dir.display()))?;for entry in entries.flatten() {let path = entry.path();if path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with('.')) {continue; }if path.is_dir() { stack.push(path); } else { paths.push(path); } } } paths.sort();letmut out = Vec::new();for path in paths {let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default();let shown = path.strip_prefix(folder).unwrap_or(&path).display().to_string();match ext.as_str() {"pdf" => {let bytes = std::fs::read(&path).map_err(|e| format!("{shown} cannot be read: {e}"))?;let sidecar = path.with_extension("json");let mail_message_id = std::fs::read(&sidecar) .ok() .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok()) .and_then(|value| value.get("mail_message_id").and_then(Value::as_str).map(str::to_string)); out.push(FileIn { shown: if shown.is_empty() { path.display().to_string() } else { shown }, bytes, mail_message_id }); }"eml" => {let raw = std::fs::read(&path).map_err(|e| format!("{shown} cannot be read: {e}"))?; out.extend(pdfs_of_mail(&raw, &shown)); } _ => {} } }Ok(out)}/// The PDFs a mail carries, each with the mail's Message-ID.pubfn pdfs_of_mail(raw: &[u8], shown: &str) -> Vec<FileIn> {use mail_parser::{MessageParser, MimeHeaders};letSome(message) = MessageParser::default().parse(raw) else { returnVec::new() };let id = message.message_id().map(|id| format!("<{id}>")); message .attachments() .filter(|part| {let name = part.attachment_name().unwrap_or_default().to_ascii_lowercase(); name.ends_with(".pdf") || part.content_type().is_some_and(|ct| ct.subtype().is_some_and(|sub| sub.eq_ignore_ascii_case("pdf"))) }) .map(|part| FileIn { shown: format!("{shown} › {}", part.attachment_name().unwrap_or("attachment.pdf")), bytes: part.contents().to_vec(), mail_message_id: id.clone() }) .collect()}/// One file's line in the summary: counts and names, never a value.#[derive(Debug, Clone, Serialize, PartialEq)]pubstructFileSummary {pub file: String,/// What was done: `added`, `updated` (a final over its partial), `seen`/// (in already), `older` (a partial after its final: noted only),/// `waiting` (whose it is is asked), `unreadable`, `no_table`.pub outcome: String, #[serde(skip_serializing_if = "Option::is_none")]pub why: Option<String>, #[serde(skip_serializing_if = "Option::is_none")]pub layout: Option<String>, #[serde(skip_serializing_if = "Option::is_none")]pub status: Option<String>,pub results: usize,pub matched: usize,/// Test names no canonical parameter matched (for the review list).pub unmatched: Vec<String>,/// Lines under a table head that read as nothing: `p<page> l<line>`.pub unparsed: Vec<String>,pub prose_lines: usize,/// The name printed on it. #[serde(skip_serializing_if = "Option::is_none")]pub name: Option<String>,/// `owner`, `existing`, `new`, `proposed`, `asked`, `no_name`. #[serde(skip_serializing_if = "Option::is_none")]pub person: Option<String>,/// For `asked`: the people it could be. #[serde(skip_serializing_if = "Vec::is_empty")]pub could_be: Vec<String>,}/// One person the run found, by the reports theirs.#[derive(Debug, Clone, Serialize, PartialEq)]pubstructPersonSummary {pub name: String,/// `owner`, `existing`, `new` (made by this run), `proposed` (waits for/// `--new`), `asked` (waits for `--same`).pub state: String,pub reports: usize, #[serde(skip_serializing_if = "Vec::is_empty")]pub could_be: Vec<String>,}#[derive(Debug, Clone, Serialize, PartialEq, Default)]pubstructSummary {pub dry: bool,pub files: Vec<FileSummary>,pub people: Vec<PersonSummary>,pub reports_written: usize,pub results_written: usize,pub people_made: usize,/// Every test name not yet known, once each, with how many results carry it.pub unmatched: BTreeMap<String, usize>,}structRead { file: FileIn, sha: String, report: Report, key: String,}fn text(row: &Row, key: &str) -> Option<String> { row.get(key).and_then(Value::as_str).map(str::to_string).filter(|text| !text.is_empty())}/// A printed name as a person's name: titles dropped, each word capitalised.pubfn person_name(printed: &str) -> String {let words = name_words(printed);let cased: Vec<String> = words .iter() .map(|word| {letmut chars = word.chars(); chars.next().map(|first| first.to_uppercase().collect::<String>() + chars.as_str()).unwrap_or_default() }) .collect(); cased.join(" ")}/// Where each contact came from (PEOPLE-DESIGN b.6): a Health import's printed names.const SOURCE_TABLE: &str = "person_source";const SOURCE_KIND: &str = "health";structPeople {/// person id → (full name, the names they are known by). known: Vec<(String, String, Vec<String>)>,/// A printed name a report was settled to before (folded) → the person (`person_source`, kind `health`): found/// first, so a person renamed or merged since is found again (PEOPLE BUILD 2). sources: HashMap<String, String>,/// person id → (health_person row id when one exists, what it holds). health: HashMap<String, (Option<String>, HealthPerson)>,}implPeople {fn read(object: &dynObject) -> Result<People, ObjectError> {letmut health = HashMap::new();for row in object.rows(PERSON_TABLE)? {let held = HealthPerson::of_row(&row);if !held.person.is_empty() { health.insert(held.person.clone(), (text(&row, "id"), held)); } }letmut known = Vec::new();for row in object.rows(PEOPLE_TABLE)? {let (Some(id), Some(name)) = (text(&row, "id"), text(&row, "full_name")) else { continue };if row.get("archived_at").is_some_and(|at| !at.is_null()) || row.get("trashed_at").is_some_and(|at| !at.is_null()) {continue; }letmut names = vec![name.clone()];ifletSome((_, held)) = health.get(&id) { names.extend(held.names.iter().cloned()); } known.push((id, name, names)); }// A table the object does not define yet holds no source.letmut sources = HashMap::new();for row in object.rows(SOURCE_TABLE).unwrap_or_default() {if text(&row, "kind").as_deref() != Some(SOURCE_KIND) {continue; }iflet (Some(key), Some(person)) = (text(&row, "source_id"), text(&row, "person")) {if known.iter().any(|(id, _, _)| id == &person) { sources.insert(key, person); } } }Ok(People { known, health, sources }) }fn candidates(&self) -> Vec<(String, Vec<String>)> {self.known.iter().map(|(id, _, names)| (id.clone(), names.clone())).collect() }fn name_of(&self, id: &str) -> String {self.known.iter().find(|(known, _, _)| known == id).map(|(_, name, _)| name.clone()).unwrap_or_else(|| id.to_string()) }/// A person by a name or a row id, surely, or `None`.fn find(&self, name_or_id: &str) -> Option<String> {ifself.known.iter().any(|(id, _, _)| id == name_or_id) {returnSome(name_or_id.to_string()); }match whose(name_or_id, &self.candidates()) {Whose::Person(id) => Some(id), _ => None, } }}/// How a report's person was settled.enumSettled {Person { id: String, state: &'static str },/// Make this person, then it is theirs.Make { name: String },Waiting { state: &'static str, could_be: Vec<String> },}fn settle(report: &Report, people: &People, options: &Options) -> Settled {letSome(printed) = report.name.as_deref().filter(|name| !name_words(name).is_empty()) else {returnSettled::Waiting { state: "no_name", could_be: Vec::new() }; };let printed_key = folded_name(printed);ifletSome(id) = people.sources.get(&printed_key) {returnSettled::Person { id: id.clone(), state: "existing" }; }ifletSome((_, target)) = options.same.iter().find(|(said, _)| folded_name(said) == printed_key) {ifletSome(id) = people.find(target) {returnSettled::Person { id, state: "existing" }; }// `--same` naming someone not yet made, in this run's --new.if options.new_people.iter().any(|name| folded_name(name) == folded_name(target)) {returnSettled::Make { name: person_name(target) }; } }match whose(printed, &people.candidates()) {Whose::Person(id) => Settled::Person { id, state: "existing" },Whose::Ask(ids) => {if options.new_people.iter().any(|name| folded_name(name) == printed_key) {returnSettled::Make { name: person_name(printed) }; }Settled::Waiting { state: "asked", could_be: ids.iter().map(|id| people.name_of(id)).collect() } }Whose::New => {let named_owner = options.owner.as_deref().is_some_and(|owner| folded_name(owner) == printed_key);if options.add_people || named_owner || options.new_people.iter().any(|name| folded_name(name) == printed_key) {Settled::Make { name: person_name(printed) } } else {Settled::Waiting { state: "proposed", could_be: Vec::new() } } } }}fn read_file(file: FileIn, catalogue: &Catalogue, zone: chrono_tz::Tz) -> Result<Read, (FileIn, String, &'static str)> {let sha = sha256_hex(&file.bytes);let pages = match pages_of(&file.bytes) {Ok(pages) => pages,Err(error) => returnErr((file, error.to_string(), "unreadable")), };if pages.iter().all(|page| page.lines.is_empty()) {returnErr((file, "the PDF has no text layer (a scan)".into(), "unreadable")); }let report = read_report(&parse(&pages), catalogue, zone);if report.layout.is_none() || report.readings.is_empty() {returnErr((file, "no result table was found".into(), "no_table")); }let key = report_key(&report, &sha);Ok(Read { file, sha, report, key })}fn file_summary(read: &Read) -> FileSummary {FileSummary { file: read.file.shown.clone(), outcome: String::new(), why: None, layout: read.report.layout.clone(), status: Some(status_of(&read.report).as_str().to_string()), results: read.report.readings.len(), matched: read.report.matched(), unmatched: read.report.unmatched(), unparsed: read.report.unparsed.iter().map(|(page, line)| format!("p{page} l{line}")).collect(), prose_lines: read.report.prose, name: read.report.name.clone(), person: None, could_be: Vec::new(), }}/// Bring `files` in. Nothing is written when `options.dry`.pubfn run(object: &dynObject, keyer: &dynKeyer, files: Vec<FileIn>, options: &Options) -> Result<Summary, ObjectError> {let catalogue = Catalogue::shipped();let database_id = object.database_id()?;letmut summary = Summary { dry: options.dry, ..Summary::default() };letmut people = People::read(object)?;// What the object holds, by row id.letmut reports: HashMap<String, Row> = object.rows(REPORT_TABLE)?.into_iter().filter_map(|row| text(&row, "id").map(|id| (id, row))).collect();letmut results: HashSet<String> = object.rows(RESULT_TABLE)?.into_iter().filter_map(|row| text(&row, "id")).collect();letmut read = Vec::new();for file in files {match read_file(file, catalogue, options.zone) {Ok(done) => read.push(done),Err((file, why, outcome)) => summary.files.push(FileSummary { file: file.shown, outcome: outcome.into(), why: Some(why), layout: None, status: None, results: 0, matched: 0, unmatched: Vec::new(), unparsed: Vec::new(), prose_lines: 0, name: None, person: None, could_be: Vec::new(), }), } }// One order's copies partial first, then final, then by when reported. read.sort_by(|a, b| (a.key.as_str(), status_of(&a.report), a.report.reported_at.as_deref()).cmp(&(b.key.as_str(), status_of(&b.report), b.report.reported_at.as_deref())));letmut tally: BTreeMap<String, PersonSummary> = BTreeMap::new();letmut made: HashMap<String, String> = HashMap::new();for one in read {letmut line = file_summary(&one);for name in &line.unmatched { *summary.unmatched.entry(name.clone()).or_default() += one.report.readings.iter().filter(|r| r.parameter.is_none() && &r.row.name == name).count(); }// Whose.let (person, state) = match settle(&one.report, &people, options) {Settled::Person { id, state } => (Some(id), state),Settled::Make { name } => {let id = match made.get(&folded_name(&name)) {Some(id) => id.clone(),None => {let id = new_person_id();if !options.dry {letmut data = Map::new(); data.insert("full_name".into(), json!(name)); object.create(PEOPLE_TABLE, &id, &data)?; } summary.people_made += 1; made.insert(folded_name(&name), id.clone()); people.known.push((id.clone(), name.clone(), vec![name.clone()])); id } }; (Some(id), "new") }Settled::Waiting { state, could_be } => { line.outcome = "waiting".into(); line.person = Some(state.into()); line.could_be = could_be.clone();let shown = one.report.name.clone().unwrap_or_else(|| "(no name printed)".into());let entry = tally.entry(folded_name(&shown)).or_insert(PersonSummary { name: shown, state: state.into(), reports: 0, could_be }); entry.reports += 1; summary.files.push(line);continue; } };let person = person.expect("settled");// The printed name is kept as one of this person's sources, once.ifletSome(printed) = one.report.name.as_deref().filter(|name| !name_words(name).is_empty()) {let key = folded_name(printed);if !people.sources.contains_key(&key) {if !options.dry && object.rows(SOURCE_TABLE).is_ok() {letmut data = Map::new(); data.insert("person".into(), json!(person)); data.insert("kind".into(), json!(SOURCE_KIND)); data.insert("device".into(), json!("")); data.insert("source_id".into(), json!(key)); data.insert("name".into(), json!(printed.trim())); object.create(SOURCE_TABLE, &keyer.id(SOURCE_TABLE, &format!("{SOURCE_KIND}:{key}")), &data)?; } people.sources.insert(key, person.clone()); } }let is_owner = options.owner.as_deref().is_some_and(|owner| people.find(owner).as_deref() == Some(person.as_str()));let state = if is_owner { "owner" } elseif made.values().any(|id| id == &person) { "new" } else { state }; line.person = Some(state.into());let shown = people.name_of(&person); tally.entry(format!("id:{person}")).or_insert(PersonSummary { name: shown, state: state.into(), reports: 0, could_be: Vec::new() }).reports += 1;// The order.let report_id = keyer.id(REPORT_TABLE, &one.key);let held_row = reports.get(&report_id);let held = held_row.map(Held::of_row);let incoming = status_of(&one.report);let decision = if options.reread && held.is_some() { Decision::Write } else { decide(held.as_ref(), &one.sha, incoming) };letmut versions = held.as_ref().map(|held| held.versions.clone()).unwrap_or_default();if !versions.iter().any(|version| version.sha256 == one.sha) { versions.push(Version { sha256: one.sha.clone(), status: incoming.as_str().into(), reported_at: one.report.reported_at.clone(), mail_message_id: one.file.mail_message_id.clone() }); }match decision {Decision::Seen => { line.outcome = "seen".into(); }Decision::Older => { line.outcome = "older".into();letmut patch = Map::new(); patch.insert("versions".into(), json!(serde_json::to_string(&versions).expect("versions serialise")));if !options.dry { object.update(REPORT_TABLE, &report_id, &patch)?; }ifletSome(row) = reports.get_mut(&report_id) { row.extend(patch); } }Decision::Write => { line.outcome = if held.is_some() { "updated".into() } else { "added".into() };// The person's Health row learns what the report prints.let (health_id, read) = people.health.get(&person).cloned().unwrap_or_else(|| (None, HealthPerson { person: person.clone(), ..HealthPerson::default() }));// Learned over the row as the object holds it NOW, never as the run read it before every file was// parsed: a sex or date of birth the owner corrected, a name taken out or a switcher order set// meanwhile stays (STALE WRITES, 25 Nov 2026).let fresh = match (&health_id, options.dry) { (Some(id), false) => object.rows(PERSON_TABLE)?.into_iter().find(|row| text(row, "id").as_deref() == Some(id.as_str())), _ => None, };let was = fresh.as_ref().map(HealthPerson::of_row);letmut health = was.clone().unwrap_or(read); health.learn(&one.report);if is_owner { health.owner = true; health.position = Some(0); }if health.position.is_none() { health.position = Some(1 + people.health.len() as i64); }let health_row_id = health_id.clone().unwrap_or_else(|| keyer.id(PERSON_TABLE, &person_key(&person)));// The PDF, sealed, under a folder its own bytes key.let pdf_key = format!("{database_id}/{}/original.pdf", keyer.id(REPORT_TABLE, &format!("pdf|{}", one.sha)));let origin = Origin { person: person.clone(), pdf: Some(pdf_key.clone()), sha256: one.sha.clone(), mail_message_id: one.file.mail_message_id.clone(), file_name: Some(one.file.shown.clone()), added_by: "import", };let data = report_data(&report_id, &one.report, &origin, &versions);let keys = result_keys(&one.key, &one.report.readings);if !options.dry {if !object.media_held(&pdf_key)? { object.put_bytes(&pdf_key, one.file.bytes.clone(), "application/pdf")?; }let health_data = health.data(&health_row_id);if health_id.is_some() {// Only what this report changed: the rest of the row is the owner's, as he left it.let before = was.as_ref().map(|was| was.data(&health_row_id)).unwrap_or_default();let patch: Map<String, Value> = health_data.into_iter().filter(|(key, value)| before.get(key) != Some(value)).collect();if !patch.is_empty() { object.update(PERSON_TABLE, &health_row_id, &patch)?; } } else { object.create(PERSON_TABLE, &health_row_id, &health_data)?; }if held_row.is_some() { object.update(REPORT_TABLE, &report_id, &data)?; } else { object.create(REPORT_TABLE, &report_id, &data)?; }for (position, (reading, key)) in one.report.readings.iter().zip(&keys).enumerate() {let id = keyer.id(RESULT_TABLE, key);let row = result_data(&id, &report_id, &person, &one.report, reading, position);if results.contains(&id) { object.update(RESULT_TABLE, &id, &row)?; } else { object.create(RESULT_TABLE, &id, &row)?; } } } people.health.insert(person.clone(), (Some(health_row_id), health));for key in &keys { results.insert(keyer.id(RESULT_TABLE, key)); }letmut kept = data; kept.insert("id".into(), json!(report_id)); reports.insert(report_id.clone(), kept); summary.reports_written += 1; summary.results_written += keys.len(); } } summary.files.push(line); } summary.people = tally.into_values().collect();Ok(summary)}/// A person's new row id (a person's id says nothing: a random uuid).fn new_person_id() -> String {let bytes: [u8; 16] = rand::random();letmut b = bytes; b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80;let h = hex::encode(b); format!("{}-{}-{}-{}-{}", &h[0..8], &h[8..12], &h[12..16], &h[16..20], &h[20..32])}/// Whether the status said partial, for a summary's reader.pubfn is_partial(status: Option<Status>) -> bool { status == Some(Status::Partial)}