Cotton code
202 lines · 11.2 KB · RustRaw
//! Health's screens on invented people and values.use serde_json::{json, Map, Value};use super::body::{body, metric, value_said};use super::labs::{labs, parameter, people, report, reports, PersonEntry, ReportEntry, ResultEntry};use super::settings::settings;use super::shapes::Tone;use super::{day_said, look, number_said};use crate::health::lab::catalogue::Catalogue;use crate::health::lab::parse::parse;use crate::health::lab::report::read_report;use crate::health::lab::rows::{report_data, report_key, result_data, result_keys, Origin};use crate::health::lab::sample_pdf::Sample;use crate::health::rows::{DayRow, Source};fn asha() -> PersonEntry {    PersonEntry { id: "p-asha".into(), name: "Asha Verma".into(), owner: true, sex: Some("female".into()), born_on: Some("1983-04-02".into()), position: Some(0), reports: 2 }}fn arun() -> PersonEntry {    PersonEntry { id: "p-arun".into(), name: "Arun Verma".into(), owner: false, sex: Some("male".into()), born_on: None, position: Some(1), reports: 1 }}/// A sample report's rows as the import lands them (plain keys for ids).fn landed(person: &str, sample: &Sample) -> (ReportEntry, Vec<ResultEntry>) {    let pages: Vec<_> = sample.pages().into_iter().map(|texts| {        let glyphs = texts.iter().flat_map(|t| {            let mut x = t.x;            t.text.chars().map(move |c| {                let g = crate::health::lab::text::Glyph { x, y: t.y, width: 4.5, size: t.size, text: c.to_string() };                x += 4.5;                g            }).collect::<Vec<_>>()        }).collect();        crate::health::lab::text::assemble(glyphs)    }).collect();    let read = read_report(&parse(&pages), Catalogue::shipped(), "Asia/Kolkata".parse().unwrap());    let key = format!("{person}:{}", report_key(&read, "sha"));    let origin = Origin { person: person.into(), pdf: Some("db/x/original.pdf".into()), sha256: "sha".into(), added_by: "import", ..Origin::default() };    let mut data = report_data(&key, &read, &origin, &[]);    data.insert("id".into(), json!(key));    let report = ReportEntry::of_row(&data).expect("a report row reads");    let results = result_keys(&key, &read.readings)        .iter()        .zip(&read.readings)        .enumerate()        .map(|(at, (id, reading))| {            let mut row: Map<String, Value> = result_data(id, &key, person, &read, reading, at);            row.insert("id".into(), json!(id));            ResultEntry::of_row(&row).expect("a result row reads")        })        .collect();    (report, results)}fn world() -> (Vec<ReportEntry>, Vec<ResultEntry>) {    let mut early = Sample::invented("Asha Verma", "ORD-1", "Final");    early.collected = "04/Jan/2024 08:00 AM".into();    early.panels[0].1[0].1 = "190".into();    let late = Sample::invented("Asha Verma", "ORD-2", "Final");    let mut his = Sample::invented("Arun Verma", "ORD-3", "Final");    his.panels[0].1[0].1 = "260".into();    let mut reports = Vec::new();    let mut results = Vec::new();    for (person, sample) in [("p-asha", early), ("p-asha", late), ("p-arun", his)] {        let (report, mine) = landed(person, &sample);        reports.push(report);        results.extend(mine);    }    (reports, results)}#[test]fn the_look_and_the_lines_ship_whole() {    let look = look();    assert_eq!(look.id, "health");    assert_eq!(look.roles.get("out_of_range").map(String::as_str), Some("danger"));    assert_eq!(number_said(212.0), "212");    assert_eq!(number_said(5.80), "5.8");    assert_eq!(day_said("2024-03-12"), "12 Mar 2024");    let lines = super::lines();    for line in ["tabs.labs", "tabs.body", "tabs.reports", "tabs.settings", "labs.title", "state.in_range", "state.borderline", "state.out_of_range", "reports.partial_notice", "body.more", "body.events", "add.no_text"] {        assert!(lines.say(line, &[]).is_some(), "{line} is said");    }}#[test]fn labs_stand_in_medical_order_with_the_strip_and_one_person_only() {    let (_, results) = world();    let answer = labs(&asha(), &results, Catalogue::shipped(), "");    assert_eq!(answer.title, "Labs");    let panels: Vec<&str> = answer.panels.iter().map(|p| p.id.as_str()).collect();    assert_eq!(panels, ["sugar", "lipids"], "the catalogue's order, not the report's");    let lipids = &answer.panels[1];    assert_eq!(lipids.rows[0].id, "cholesterol_total");    assert_eq!(lipids.rows[0].latest.text, "212");    assert_eq!(lipids.rows[0].mark.id, "borderline");    assert_eq!(lipids.rows[0].mark.tone, Tone::Attention);    assert_eq!(lipids.rows[0].trend.iter().map(|p| p.value).collect::<Vec<_>>(), [190.0, 212.0], "only Asha's readings");    assert_eq!(answer.strip.out.iter().map(|row| row.id.as_str()).collect::<Vec<_>>(), ["triglycerides"], "150 against < 150 is out; HbA1c 5.8 in its Prediabetes band is borderline, not out");    let hba1c = answer.panels[0].rows.iter().find(|row| row.id == "hba1c").unwrap();    assert_eq!(hba1c.mark.id, "borderline");    let changed = &answer.strip.changed[0];    assert_eq!(changed.row.id, "cholesterol_total");    assert_eq!(changed.change, "Up 22 mg/dL since 4 Jan 2024");    let his = labs(&arun(), &results, Catalogue::shipped(), "");    assert_eq!(his.panels[1].rows[0].latest.text, "260");    assert_eq!(his.panels[1].rows[0].mark.id, "high");    assert_eq!(his.panels[1].rows[0].trend.len(), 1, "nothing of Asha's in Arun's trend");    let searched = labs(&asha(), &results, Catalogue::shipped(), "hba");    assert_eq!(searched.panels.len(), 1);    assert_eq!(searched.panels[0].rows[0].id, "hba1c");    let none = labs(&asha(), &results, Catalogue::shipped(), "zzz");    assert_eq!(none.empty.map(|e| e.title), Some("Nothing matches".into()));    let nobody = labs(&PersonEntry { id: "p-new".into(), name: "New".into(), ..PersonEntry::default() }, &results, Catalogue::shipped(), "");    assert_eq!(nobody.empty.map(|e| e.title), Some("No lab results yet".into()));}#[test]fn a_parameter_is_its_whole_history_with_the_labs_band() {    let (reports, results) = world();    let answer = parameter(&asha(), "cholesterol_total", &results, &reports, Catalogue::shipped());    assert_eq!(answer.title, "Total cholesterol");    assert!(answer.line.ends_with('.'));    assert_eq!(answer.unit, "mg/dL");    assert_eq!(answer.loinc.as_deref(), Some("LOINC 2093-3"));    assert!(answer.attribution.as_deref().is_some_and(|a| a.contains("Regenstrief")));    assert_eq!(answer.band.as_ref().map(|b| b.said.as_str()), Some("The lab's range: below 200 mg/dL"));    assert_eq!(answer.points.len(), 2);    assert_eq!(answer.readings[0].said.text, "212", "newest first");    assert_eq!(answer.readings[0].act.method, "health.report");}#[test]fn reports_list_by_date_and_a_report_reads_as_printed() {    let (all, results) = world();    let mine = reports(&asha(), &all, &results);    assert_eq!(mine.rows.len(), 2);    assert_eq!(mine.rows[0].day, "12 Mar 2024", "newest first");    assert_eq!(mine.rows[0].detail, "5 results · 1 out of range");    let one = report(&asha(), &all[1], &results);    assert_eq!(one.sections.iter().map(|s| s.title.as_str()).collect::<Vec<_>>(), ["LIPID PROFILE", "DIABETES"], "as printed, in its order");    assert_eq!(one.sections[0].rows[0].range, "Desirable : < 200; Borderline High : 200 - 239; High : >= 240");    assert!(one.facts.iter().any(|f| f.label == "Collected"));    assert!(one.pdf.is_some());    assert!(one.notice.is_none(), "a final has no notice");}#[test]fn the_switcher_puts_the_owner_first_and_body_keeps_apple_health_theirs() {    let switcher = people(&[arun(), asha()], None);    assert_eq!(switcher.people[0].id, "p-asha");    assert_eq!(switcher.current.as_deref(), Some("p-asha"));    assert_eq!(switcher.people[1].detail, "1 report");    assert_eq!(switcher.add.method, "health.addPerson");    assert_eq!(switcher.add.input.as_ref().map(|prompt| prompt.key.as_str()), Some("name"), "a name is all someone new needs");    let days = vec![        DayRow { metric: "steps", day: "2026-11-20".into(), value: Some(8123.0), min: None, max: None, samples: None, state: None, source: Source::HealthKit },        DayRow { metric: "weight", day: "2026-11-18".into(), value: Some(64.2), min: None, max: None, samples: None, state: None, source: Source::HealthKit },        DayRow { metric: "sleep_asleep", day: "2026-11-20".into(), value: Some(440.0), min: None, max: None, samples: None, state: None, source: Source::HealthKit },    ];    let mine = body(&asha(), &days, &[], "2026-11-20", true);    assert_eq!(mine.sections[0].id, "today");    assert_eq!(mine.sections[0].rows[0].latest.text, "8,123");    let sleep = mine.sections[0].rows.iter().find(|r| r.metric == "sleep_asleep").unwrap();    assert_eq!(sleep.latest.text, "7 h 20 min");    let his = body(&arun(), &days, &[], "2026-11-20", true);    assert!(his.sections.is_empty(), "Apple Health is the owner's alone");    assert!(his.empty.as_ref().is_some_and(|e| e.body.contains("Arun Verma")));    // A report's weight and Apple Health's are one history.    let weighed = ResultEntry { id: "r1".into(), person: "p-asha".into(), report: "x".into(), day: "2025-06-01".into(), parameter: Some("body_weight".into()), name: "Weight".into(), result: "66".into(), value: Some(66.0), unit: "kg".into(), canonical_value: Some(66.0), canonical_unit: Some("kg".into()), ..ResultEntry::default() };    let history = metric(&asha(), "weight", &days, std::slice::from_ref(&weighed));    assert_eq!(history.points.iter().map(|p| p.source.clone().unwrap()).collect::<Vec<_>>(), ["lab", "apple_health"]);    assert_eq!(value_said("distance", 5210.0, None).text, "5.21");}#[test]fn settings_say_the_people_and_what_the_records_are() {    let answer = settings(&[asha(), arun()], 3, Catalogue::shipped(), true);    assert_eq!(answer.sections[0].rows[0].label, "Asha Verma · You");    assert!(answer.sections[0].rows[1].acts.iter().any(|a| a.id == "set_owner"));    assert_eq!(answer.sections[2].rows[0].detail.as_deref(), Some("3 test names"));    assert!(answer.sections[3].rows[1].detail.as_deref().is_some_and(|d| d.contains("LOINC")));}/// RULE (Cotton Health on Android, 20 Nov 2026): a phone that reads no Apple Health (`platform: android`) is/// never asked to connect it: Body's owner empty says their reports' measures, Settings has no Apple Health/// section or line, and a sex is set by choosing one of the two the core offers.#[test]fn a_phone_without_apple_health_is_never_asked_to_connect_it() {    let empty = body(&asha(), &[], &[], "2026-11-20", false);    assert!(empty.connect.is_none());    let said = empty.empty.expect("an empty Body");    assert!(said.act.is_none() && !said.body.contains("Apple"), "{}", said.body);    let answer = settings(&[asha(), arun()], 3, Catalogue::shipped(), false);    assert!(answer.sections.iter().all(|s| s.id != "apple_health"));    assert!(answer.sections[0].rows.iter().all(|r| !r.detail.as_deref().unwrap_or_default().contains("Apple")));    let sex = answer.sections[0].rows[0].acts.iter().find(|a| a.id == "set_sex").and_then(|a| a.input.clone()).expect("set_sex asks");    assert_eq!(sex.choices.iter().map(|c| c.label.as_str()).collect::<Vec<_>>(), ["Female", "Male", "Not said"]);    assert_eq!(settings(&[asha()], 0, Catalogue::shipped(), true).sections[1].id, "apple_health", "an iPhone keeps it");}