//! How a lab report is laid out, as kit data (`kits/health/layouts.json`). use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use super::catalogue::fold_name; pub const SHIPPED: &str = include_str!("../../../kits/health/layouts.json"); /// The columns a result table can carry. pub const COLUMNS: &[&str] = &["name", "result", "unit", "range", "method", "flag", "specimen"]; /// The header fields a report can carry. pub const FIELDS: &[&str] = &["name", "age_sex", "age", "sex", "dob", "order_id", "collected_via", "sample_type", "status", "collected_at", "received_at", "reported_at", "referred_by", "lab"]; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Layout { pub id: String, pub name: String, /// Column → the heads it is printed under. pub columns: BTreeMap>, /// Columns the head must carry. pub needs: Vec, /// At least one of these too. #[serde(default)] pub needs_one_of: Vec, /// Words the head line carries that are no column (`Final` beside `Test Report Status`). #[serde(default)] pub head_words: Vec, /// Columns printed under two heads, one of them filled on a row (`In Range` | `Out of Range`). #[serde(default)] pub split: Vec, /// Header fields this lab prints that do not say what their label does /// (a `Sample Type` naming the order's last sample on every page). #[serde(default)] pub ignore_fields: Vec, /// The lab prints values well left of their heads: a cell that starts past /// the end of one head, nearer the next, is the next column's. #[serde(default)] pub left_of_heads: bool, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Layouts { pub format_version: u32, pub id: String, pub purpose: String, pub layouts: Vec, pub fields: BTreeMap>, pub statuses: BTreeMap>, pub prose: Vec, pub furniture: Vec, pub date_formats: Vec, pub day_formats: Vec, #[serde(skip)] pub furniture_res: Vec, } #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum LayoutError { #[error("the layouts do not read: {0}")] DoesNotRead(String), #[error("layout `{layout}` names a column `{column}` the reader does not know")] UnknownColumn { layout: String, column: String }, #[error("field `{0}` is not one the reader knows")] UnknownField(String), #[error("furniture `{0}` is not a pattern")] BadPattern(String), #[error("the last layout must be the generic one")] NoGeneric, } impl Layouts { pub fn shipped() -> &'static Layouts { static LAYOUTS: std::sync::OnceLock = std::sync::OnceLock::new(); LAYOUTS.get_or_init(|| Layouts::parse(SHIPPED).expect("kits/health/layouts.json reads")) } pub fn parse(json: &str) -> Result { let mut layouts: Layouts = serde_json::from_str(json).map_err(|error| LayoutError::DoesNotRead(error.to_string()))?; for layout in &layouts.layouts { for column in layout.columns.keys().chain(&layout.needs).chain(&layout.needs_one_of).chain(&layout.split) { if !COLUMNS.contains(&column.as_str()) { return Err(LayoutError::UnknownColumn { layout: layout.id.clone(), column: column.clone() }); } } } for layout in &layouts.layouts { if let Some(field) = layout.ignore_fields.iter().find(|field| !FIELDS.contains(&field.as_str())) { return Err(LayoutError::UnknownField(field.clone())); } } if layouts.layouts.last().map(|layout| layout.id.as_str()) != Some("generic") { return Err(LayoutError::NoGeneric); } for field in layouts.fields.keys() { if !FIELDS.contains(&field.as_str()) { return Err(LayoutError::UnknownField(field.clone())); } } layouts.furniture_res = layouts .furniture .iter() .map(|pattern| regex::RegexBuilder::new(pattern).case_insensitive(true).build().map_err(|_| LayoutError::BadPattern(pattern.clone()))) .collect::>()?; Ok(layouts) } /// The field a printed label names. pub fn field_of(&self, label: &str) -> Option<&str> { let label = fold_name(label); if label.is_empty() { return None; } self.fields.iter().find(|(_, labels)| labels.iter().any(|known| fold_name(known) == label)).map(|(field, _)| field.as_str()) } /// `partial` or `final`, from a printed status. pub fn status_of(&self, printed: &str) -> Option<&str> { let printed = fold_name(printed); self.statuses.iter().find(|(_, words)| words.iter().any(|word| fold_name(word) == printed)).map(|(status, _)| status.as_str()) } pub fn is_furniture(&self, line: &str) -> bool { let line = line.trim(); self.furniture_res.iter().any(|re| re.is_match(line)) } /// Is `text` itself one of the words that open a paragraph (`Interpretation`, `Comment`)? pub fn prose_word(&self, text: &str) -> bool { let folded = fold_name(text); self.prose.iter().any(|word| fold_name(word) == folded) } /// Does `text` open an interpretive paragraph (`Interpretation:`, `Note :`)? pub fn opens_prose(&self, text: &str) -> bool { let folded = fold_name(text); self.prose.iter().any(|word| { let word = fold_name(word); folded == word || folded.starts_with(&format!("{word} ")) && (text.contains(':') || text.split_whitespace().count() > 4) }) } } impl Layout { /// The column a head names, in this layout. pub fn column_of(&self, head: &str) -> Option<&str> { let head = fold_name(head); self.columns.iter().find(|(_, heads)| heads.iter().any(|known| fold_name(known) == head)).map(|(column, _)| column.as_str()) } /// Is `text` a word the head line carries that is no column? pub fn is_head_word(&self, text: &str) -> bool { let text = fold_name(text); !text.is_empty() && self.head_words.iter().any(|word| fold_name(word) == text) } }