//! `health:import` on synthetic reports (invented people, invented values): //! whose each is, partial then final, a second run that adds nothing, and a //! summary that never says a value. use base64::Engine as _; use serde_json::{json, Value}; use cotton_core::health::lab::sample_pdf::Sample; use cotton_mac::health_import::{files_in, run, Options, Plain}; use cotton_mac::music::import::Memory; fn options() -> Options { Options { zone: "Asia/Kolkata".parse().unwrap(), dry: false, owner: Some("Asha Verma".into()), same: Vec::new(), new_people: Vec::new(), add_people: false, reread: false } } fn object() -> Memory { let memory = Memory::new("db-test"); memory.seed("person", json!({ "id": "p-asha", "full_name": "Asha Verma" })); memory.seed("person", json!({ "id": "p-arun", "full_name": "Arun Verma" })); memory } fn write(dir: &std::path::Path, name: &str, sample: &Sample) { std::fs::write(dir.join(name), sample.pdf()).unwrap(); } fn mail_with(pdf: &[u8]) -> Vec { let body = base64::engine::general_purpose::STANDARD.encode(pdf); format!( "Message-ID: \r\nFrom: reports@lab.example\r\nTo: owner@example.com\r\nSubject: Your test reports are now available\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"b\"\r\n\r\n--b\r\nContent-Type: text/plain\r\n\r\nYour reports.\r\n--b\r\nContent-Type: application/pdf; name=\"report.pdf\"\r\nContent-Disposition: attachment; filename=\"report.pdf\"\r\nContent-Transfer-Encoding: base64\r\n\r\n{body}\r\n--b--\r\n" ) .into_bytes() } fn outcome<'a>(summary: &'a Value, file: &str) -> &'a str { summary["files"].as_array().unwrap().iter().find(|f| f["file"].as_str().unwrap().starts_with(file)).unwrap_or_else(|| panic!("{file} in {summary}"))["outcome"].as_str().unwrap() } #[test] fn reports_land_on_their_people_once_and_the_summary_says_no_value() { let dir = tempfile::tempdir().unwrap(); write(dir.path(), "a1-partial.pdf", &Sample::invented("Asha Verma", "ORD-1", "Partial Report")); write(dir.path(), "a2-final.pdf", &Sample::invented("Mrs. VERMA ASHA", "ORD-1", "Final")); write(dir.path(), "b-arun.pdf", &Sample::invented("Mr. Arun Verma", "ORD-2", "Final")); write(dir.path(), "c-initials.pdf", &Sample::invented("A Verma", "ORD-3", "Final")); write(dir.path(), "d-new.pdf", &Sample::invented("Meena Iyer", "ORD-4", "Final")); std::fs::write(dir.path().join("e-mail.eml"), mail_with(&Sample::invented("Asha Verma", "ORD-5", "Final").pdf())).unwrap(); std::fs::write(dir.path().join("notes.txt"), "not a report").unwrap(); std::fs::write(dir.path().join("f-broken.pdf"), b"%PDF-1.4 nothing here").unwrap(); let object = object(); let files = files_in(dir.path()).unwrap(); assert_eq!(files.len(), 7, "six PDFs and the one a mail carries"); let summary = serde_json::to_value(run(&object, &Plain, files, &options()).unwrap()).unwrap(); assert_eq!(outcome(&summary, "a1-partial"), "added"); assert_eq!(outcome(&summary, "a2-final"), "updated", "the final lands on its partial"); assert_eq!(outcome(&summary, "b-arun"), "added"); assert_eq!(outcome(&summary, "c-initials"), "waiting"); assert_eq!(outcome(&summary, "d-new"), "waiting"); assert_eq!(outcome(&summary, "e-mail.eml"), "added"); assert_eq!(outcome(&summary, "f-broken"), "unreadable"); let people = summary["people"].as_array().unwrap(); let state = |name: &str| people.iter().find(|p| p["name"] == name).map(|p| (p["state"].as_str().unwrap().to_string(), p["reports"].as_u64().unwrap())); assert_eq!(state("Asha Verma"), Some(("owner".into(), 3))); assert_eq!(state("Arun Verma"), Some(("existing".into(), 1))); assert_eq!(state("A Verma").map(|s| s.0), Some("asked".into())); assert_eq!(state("Meena Iyer").map(|s| s.0), Some("proposed".into())); let reports = object.table("lab_report"); assert_eq!(reports.len(), 3, "one row per order"); let order_one = reports.iter().find(|r| r["order_id"] == "ORD-1").unwrap(); assert_eq!(order_one["status"], "final"); assert_eq!(order_one["person"], "p-asha"); assert_eq!(serde_json::from_str::(order_one["versions"].as_str().unwrap()).unwrap().as_array().unwrap().len(), 2); let mail_report = reports.iter().find(|r| r["order_id"] == "ORD-5").unwrap(); assert_eq!(mail_report["mail_message_id"], ""); assert_eq!(object.table("lab_result").len(), 15, "five results per order, the final's on its partial's rows"); assert!(object.table("lab_result").iter().all(|r| r["person"] == "p-asha" || r["person"] == "p-arun")); let owner = object.table("health_person").into_iter().find(|p| p["person"] == "p-asha").unwrap(); assert_eq!((owner["owner"].clone(), owner["sex"].clone(), owner["position"].clone()), (json!(true), json!("female"), json!(0))); assert!(object.media.borrow().keys().all(|key| key.starts_with("db-test/") && key.ends_with("/original.pdf"))); assert_eq!(object.media.borrow().len(), 4, "each PDF kept, sealed, once"); let said = summary.to_string(); for value in ["212", "5.8", "< 200", "ORD-", "2024", "Serum"] { assert!(!said.contains(value), "the summary never says `{value}`: {said}"); } // Again: nothing is written. let writes = object.writes.borrow().len(); let again = serde_json::to_value(run(&object, &Plain, files_in(dir.path()).unwrap(), &options()).unwrap()).unwrap(); assert_eq!(outcome(&again, "a2-final"), "seen"); assert_eq!(outcome(&again, "b-arun"), "seen"); assert_eq!(object.writes.borrow().len(), writes, "a second run adds nothing"); // The owner answers: the initials are Arun, the new name is a new person. let mut answered = options(); answered.same.push(("A Verma".into(), "Arun Verma".into())); answered.new_people.push("Meena Iyer".into()); let third = serde_json::to_value(run(&object, &Plain, files_in(dir.path()).unwrap(), &answered).unwrap()).unwrap(); assert_eq!(outcome(&third, "c-initials"), "added"); assert_eq!(outcome(&third, "d-new"), "added"); assert_eq!(object.table("person").len(), 3, "Meena is made once"); let arun = object.table("health_person").into_iter().find(|p| p["person"] == "p-arun").unwrap(); assert!(arun["names"].as_str().unwrap().contains("A Verma"), "the confirmed variant is remembered: next time it is surely Arun"); // A partial after its final only notes its version. let later = tempfile::tempdir().unwrap(); let mut late = Sample::invented("Asha Verma", "ORD-1", "Partial Report"); late.reported = "12/Mar/2024 01:00 PM".into(); write(later.path(), "late-partial.pdf", &late); let fourth = serde_json::to_value(run(&object, &Plain, files_in(later.path()).unwrap(), &options()).unwrap()).unwrap(); assert_eq!(outcome(&fourth, "late-partial"), "older"); let order_one = object.table("lab_report").into_iter().find(|r| r["order_id"] == "ORD-1").unwrap(); assert_eq!(order_one["status"], "final"); } #[test] fn a_dry_run_writes_nothing_and_says_whose_each_would_be() { let dir = tempfile::tempdir().unwrap(); write(dir.path(), "one.pdf", &Sample::invented("Asha Verma", "ORD-9", "Final")); write(dir.path(), "two.pdf", &Sample::invented("Ravi Menon", "ORD-10", "Final")); let object = object(); let mut dry = options(); dry.dry = true; let summary = serde_json::to_value(run(&object, &Plain, files_in(dir.path()).unwrap(), &dry).unwrap()).unwrap(); assert_eq!(summary["dry"], true); assert_eq!(outcome(&summary, "one"), "added"); assert_eq!(outcome(&summary, "two"), "waiting"); assert!(object.writes.borrow().is_empty(), "a dry run writes nothing"); assert_eq!(summary["files"][0]["results"], 5); assert_eq!(summary["files"][0]["matched"], 5); } #[test] fn the_owner_named_with_no_person_yet_is_made_once() { let dir = tempfile::tempdir().unwrap(); write(dir.path(), "one.pdf", &Sample::invented("Ms. Asha Verma", "ORD-1", "Final")); write(dir.path(), "two.pdf", &Sample::invented("Asha Verma", "ORD-2", "Final")); let object = Memory::new("db-test"); let summary = serde_json::to_value(run(&object, &Plain, files_in(dir.path()).unwrap(), &options()).unwrap()).unwrap(); assert_eq!((outcome(&summary, "one"), outcome(&summary, "two")), ("added", "added")); assert_eq!(object.table("person").len(), 1); assert_eq!(object.table("person")[0]["full_name"], "Asha Verma", "the title is no part of a name"); assert_eq!(summary["people"][0]["state"], "owner"); } /// Write synthetic reports to rehearse the command with (invented people and values): /// HEALTH_SAMPLES= cargo test -p cotton-mac --test health_import write_samples -- --ignored #[test] #[ignore = "writes rehearsal PDFs where HEALTH_SAMPLES says"] fn write_samples() { let dir = std::path::PathBuf::from(std::env::var("HEALTH_SAMPLES").expect("HEALTH_SAMPLES names a folder")); std::fs::create_dir_all(&dir).unwrap(); write(&dir, "2024-03-partial.pdf", &Sample::invented("Asha Verma", "ORD-1", "Partial Report")); write(&dir, "2024-03-final.pdf", &Sample::invented("Asha Verma", "ORD-1", "Final")); write(&dir, "2024-05-family.pdf", &Sample::invented("Mr. Arun Verma", "ORD-2", "Final")); } /// The object as `Memory` keeps it, where the owner corrects a person's Health row on the phone while the run is /// still reading its files: after it read the people, before it writes the first report. struct OwnerEditsMidRun<'a> { inner: &'a Memory, edited: std::cell::Cell, } impl cotton_mac::music::import::Object for OwnerEditsMidRun<'_> { fn database_id(&self) -> Result { self.inner.database_id() } fn rows(&self, table: &str) -> Result, cotton_mac::object::ObjectError> { self.inner.rows(table) } fn media_held(&self, key: &str) -> Result { self.inner.media_held(key) } fn put_file(&self, key: &str, path: &std::path::Path, size: u64, content_type: &str) -> Result<(), cotton_mac::object::ObjectError> { self.inner.put_file(key, path, size, content_type) } fn put_bytes(&self, key: &str, bytes: Vec, content_type: &str) -> Result<(), cotton_mac::object::ObjectError> { if !self.edited.replace(true) { for row in self.inner.rows.borrow_mut().get_mut("health_person").into_iter().flatten() { row.insert("sex".into(), json!("male")); row.insert("position".into(), json!(3)); } } self.inner.put_bytes(key, bytes, content_type) } fn create(&self, table: &str, id: &str, data: &cotton_mac::music::import::Row) -> Result<(), cotton_mac::object::ObjectError> { self.inner.create(table, id, data) } fn update(&self, table: &str, id: &str, patch: &cotton_mac::music::import::Row) -> Result<(), cotton_mac::object::ObjectError> { self.inner.update(table, id, patch) } } /// RULE (STALE WRITES, 25 Nov 2026): a report teaches the person's Health row over the row as the object holds it /// when it is written, and sends only what it changed: a sex or a switcher place the owner set while the run was /// reading its files stays. #[test] fn what_the_owner_set_on_a_health_person_during_a_run_stays() { let dir = tempfile::tempdir().unwrap(); write(dir.path(), "a.pdf", &Sample::invented("Asha Verma", "ORD-1", "Final")); let memory = object(); memory.seed("health_person", json!({ "id": "h-asha", "person": "p-asha", "owner": true, "sex": "female", "names": "[]", "position": 0 })); let object = OwnerEditsMidRun { inner: &memory, edited: std::cell::Cell::new(false) }; let mut not_owner = options(); not_owner.owner = None; let summary = serde_json::to_value(run(&object, &Plain, files_in(dir.path()).unwrap(), ¬_owner).unwrap()).unwrap(); assert_eq!(outcome(&summary, "a"), "added"); let asha = memory.table("health_person").into_iter().find(|p| p["person"] == "p-asha").unwrap(); assert_eq!((asha["sex"].clone(), asha["position"].clone()), (json!("male"), json!(3)), "{asha:?}"); assert!(asha["names"].as_str().unwrap().contains("Asha Verma"), "what the report taught is there: {asha:?}"); } /// RULE (PEOPLE BUILD 2): a report's printed name is kept as a source of the person it settled to, so the next run /// finds that person by it first, even after the contact was renamed by hand. #[test] fn a_printed_name_is_kept_as_a_source_and_found_again_after_a_rename() { let dir = tempfile::tempdir().unwrap(); write(dir.path(), "one.pdf", &Sample::invented("Mr. Arun Verma", "ORD-1", "Final")); let object = object(); object.seed("person_source", json!({ "id": "seed", "person": "p-asha", "kind": "address_book", "device": "d", "source_id": "x" })); run(&object, &Plain, files_in(dir.path()).unwrap(), &options()).unwrap(); let sources: Vec = object.table("person_source").into_iter().map(Value::Object).filter(|s| s["kind"] == "health").collect(); assert_eq!(sources.len(), 1, "{sources:?}"); assert_eq!(sources[0]["person"], "p-arun"); assert_eq!(sources[0]["name"], "Mr. Arun Verma"); // He renames Arun by hand; the next report with the same printed name still lands on him. let renamed = Memory::new("db-test"); renamed.seed("person", json!({ "id": "p-asha", "full_name": "Asha Verma" })); renamed.seed("person", json!({ "id": "p-arun", "full_name": "Dad" })); renamed.seed("person_source", sources[0].clone()); let dir2 = tempfile::tempdir().unwrap(); write(dir2.path(), "two.pdf", &Sample::invented("Mr. Arun Verma", "ORD-2", "Final")); let summary = serde_json::to_value(run(&renamed, &Plain, files_in(dir2.path()).unwrap(), &options()).unwrap()).unwrap(); assert_eq!(outcome(&summary, "two"), "added", "{summary}"); assert_eq!(renamed.table("person").len(), 2, "nobody new is made"); assert_eq!(renamed.table("person_source").iter().filter(|s| s["kind"] == "health").count(), 1, "the source is not written twice"); }