//! A folder of lab reports into the owner's object: `pnpm -s health:import //! --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 "="`. A name nobody //! has is proposed as a new person and waits for `--new ""` (or //! `--add-people` for every one proposed). `--owner ""` 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, }; use crate::ids::sha256_hex; use crate::music::import::{Object, Row}; use crate::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. pub trait Keyer { fn id(&self, table: &str, planned: &str) -> String; } /// The plain key itself: a dry run against nothing, and the tests. pub struct Plain; impl Keyer for Plain { fn id(&self, _table: &str, planned: &str) -> String { planned.to_string() } } /// The data key's keyed id, as the phone makes it. pub struct Keyed { pub dk: cotton_core::seal::DataKey, pub database_id: String, } impl Keyer for Keyed { 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)] pub struct Options { pub zone: chrono_tz::Tz, pub dry: bool, /// The owner, by a name `whose` finds (or one of `new_people`). pub owner: Option, /// 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, /// 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)] pub struct FileIn { /// Shown in the summary: the file's name (and the attachment's, from a mail). pub shown: String, pub bytes: Vec, pub mail_message_id: Option, } /// Every PDF under `folder` (and in its `.eml` mails), sorted by name. A /// PDF's `.json` beside it may say `{ "mail_message_id": "…" }`. pub fn files_in(folder: &Path) -> Result, String> { let mut paths: Vec = Vec::new(); let mut stack = vec![folder.to_path_buf()]; while let Some(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(); let mut 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::(&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. pub fn pdfs_of_mail(raw: &[u8], shown: &str) -> Vec { use mail_parser::{MessageParser, MimeHeaders}; let Some(message) = MessageParser::default().parse(raw) else { return Vec::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)] pub struct FileSummary { 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, #[serde(skip_serializing_if = "Option::is_none")] pub layout: Option, #[serde(skip_serializing_if = "Option::is_none")] pub status: Option, pub results: usize, pub matched: usize, /// Test names no canonical parameter matched (for the review list). pub unmatched: Vec, /// Lines under a table head that read as nothing: `p l`. pub unparsed: Vec, pub prose_lines: usize, /// The name printed on it. #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, /// `owner`, `existing`, `new`, `proposed`, `asked`, `no_name`. #[serde(skip_serializing_if = "Option::is_none")] pub person: Option, /// For `asked`: the people it could be. #[serde(skip_serializing_if = "Vec::is_empty")] pub could_be: Vec, } /// One person the run found, by the reports theirs. #[derive(Debug, Clone, Serialize, PartialEq)] pub struct PersonSummary { 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, } #[derive(Debug, Clone, Serialize, PartialEq, Default)] pub struct Summary { pub dry: bool, pub files: Vec, pub people: Vec, 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, } struct Read { file: FileIn, sha: String, report: Report, key: String, } fn text(row: &Row, key: &str) -> Option { 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. pub fn person_name(printed: &str) -> String { let words = name_words(printed); let cased: Vec = words .iter() .map(|word| { let mut chars = word.chars(); chars.next().map(|first| first.to_uppercase().collect::() + 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"; struct People { /// person id → (full name, the names they are known by). known: Vec<(String, String, Vec)>, /// 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, /// person id → (health_person row id when one exists, what it holds). health: HashMap, HealthPerson)>, } impl People { fn read(object: &dyn Object) -> Result { let mut 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)); } } let mut 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; } let mut names = vec![name.clone()]; if let Some((_, 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. let mut sources = HashMap::new(); for row in object.rows(SOURCE_TABLE).unwrap_or_default() { if text(&row, "kind").as_deref() != Some(SOURCE_KIND) { continue; } if let (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)> { 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 { if self.known.iter().any(|(id, _, _)| id == name_or_id) { return Some(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. enum Settled { Person { id: String, state: &'static str }, /// Make this person, then it is theirs. Make { name: String }, Waiting { state: &'static str, could_be: Vec }, } fn settle(report: &Report, people: &People, options: &Options) -> Settled { let Some(printed) = report.name.as_deref().filter(|name| !name_words(name).is_empty()) else { return Settled::Waiting { state: "no_name", could_be: Vec::new() }; }; let printed_key = folded_name(printed); if let Some(id) = people.sources.get(&printed_key) { return Settled::Person { id: id.clone(), state: "existing" }; } if let Some((_, target)) = options.same.iter().find(|(said, _)| folded_name(said) == printed_key) { if let Some(id) = people.find(target) { return Settled::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)) { return Settled::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) { return Settled::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 { let sha = sha256_hex(&file.bytes); let pages = match pages_of(&file.bytes) { Ok(pages) => pages, Err(error) => return Err((file, error.to_string(), "unreadable")), }; if pages.iter().all(|page| page.lines.is_empty()) { return Err((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() { return Err((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`. pub fn run(object: &dyn Object, keyer: &dyn Keyer, files: Vec, options: &Options) -> Result { let catalogue = Catalogue::shipped(); let database_id = object.database_id()?; let mut summary = Summary { dry: options.dry, ..Summary::default() }; let mut people = People::read(object)?; // What the object holds, by row id. let mut reports: HashMap = object.rows(REPORT_TABLE)?.into_iter().filter_map(|row| text(&row, "id").map(|id| (id, row))).collect(); let mut results: HashSet = object.rows(RESULT_TABLE)?.into_iter().filter_map(|row| text(&row, "id")).collect(); let mut 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()))); let mut tally: BTreeMap = BTreeMap::new(); let mut made: HashMap = HashMap::new(); for one in read { let mut 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 { let mut 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. if let Some(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() { let mut 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" } else if 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) }; let mut 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(); let mut 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)?; } if let Some(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); let mut 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 = 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)); } let mut 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(); let mut 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. pub fn is_partial(status: Option) -> bool { status == Some(Status::Partial) }