use openehr_base::v1_3::base_types::identification::terminology_id::TerminologyId;
use openehr_rm::v1_2::data_types::text::code_phrase::CodePhrase;
use openehr_rm::v1_2::data_types::text::dv_coded_text::DvCodedText;
use openehr_rm::v1_2::data_types::text::dv_text::DvText;
use openehr_rm::v1_2::data_types::text::dv_text::DvTextData;
use openehr_term::codes::NullFlavour as Flavour;
use crate::engine::lens::Fallback;
use crate::engine::lens::Lens;
use crate::engine::lens::LensError;
use crate::engine::lens::code_phrase::text_of;
use crate::model::ast::keyword::Direction;
pub const CELL: &str = "NULL_FLAVOUR against data-absent-reason";
pub const OPENEHR: &str = "openehr";
pub const EXTENSION: &str = "http://hl7.org/fhir/StructureDefinition/data-absent-reason";
#[must_use]
pub const fn fhir_default(flavour: Flavour) -> &'static str {
match flavour {
Flavour::Unknown | Flavour::NoInformation => "unknown",
Flavour::Masked => "masked",
Flavour::NotApplicable => "not-applicable",
}
}
pub const BRIDGE: &[(&str, Flavour)] = &[
("unknown", Flavour::Unknown),
("asked-unknown", Flavour::Unknown),
("temp-unknown", Flavour::Unknown),
("not-asked", Flavour::Unknown),
("asked-declined", Flavour::Unknown),
("masked", Flavour::Masked),
("not-applicable", Flavour::NotApplicable),
("unsupported", Flavour::Unknown),
("as-text", Flavour::Unknown),
("error", Flavour::Unknown),
("not-a-number", Flavour::Unknown),
("negative-infinity", Flavour::Unknown),
("positive-infinity", Flavour::Unknown),
("not-performed", Flavour::Unknown),
("not-permitted", Flavour::Unknown),
];
#[derive(Debug, Clone, PartialEq)]
pub struct NullFlavour {
pub flavour: DvCodedText,
pub reason: Option<DvText>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NullFlavourLens;
impl Lens<NullFlavour, fhir_types::r4::primitives::String> for NullFlavourLens {
fn cell(&self) -> &'static str {
CELL
}
fn get(&self, source: &NullFlavour) -> Result<fhir_types::r4::primitives::String, LensError> {
let code = &source.flavour.defining_code;
let default = (code.terminology_id.value == OPENEHR)
.then(|| Flavour::from_code(&code.code_string))
.flatten()
.map(fhir_default)
.ok_or_else(|| LensError::Shape {
cell: CELL,
attribute: "ELEMENT.null_flavour",
found: format!("{}::{}", code.terminology_id.value, code.code_string),
reason: "the openEHR terminology's null flavours are 253, 271, 272 and 273",
direction: Direction::OpenehrToFhir,
})?;
let named = reason_text(source.reason.as_ref()).filter(|&text| bridged(text).is_some());
Ok(text(named.unwrap_or(default)))
}
fn put(
&self,
view: &fhir_types::r4::primitives::String,
existing: Option<&NullFlavour>,
) -> Result<NullFlavour, LensError> {
let code = text_of(Some(&view.value)).ok_or(LensError::Missing {
cell: CELL,
attribute: "ELEMENT.null_flavour",
direction: Direction::FhirToOpenehr,
})?;
let flavour = bridged(code).ok_or_else(|| LensError::Shape {
cell: CELL,
attribute: "ELEMENT.null_flavour",
found: String::from(code),
reason: "the code is outside the R4 data-absent-reason value set",
direction: Direction::FhirToOpenehr,
})?;
if let Some(held) = existing
&& self.get(held).is_ok_and(|read| read == *view)
{
return Ok(held.clone());
}
Ok(NullFlavour {
flavour: coded(flavour),
reason: (code != fhir_default(flavour)).then(|| reason(code)),
})
}
fn fallbacks(&self, _view: &fhir_types::r4::primitives::String) -> Vec<Fallback> {
Vec::new()
}
}
#[must_use]
pub fn uncarried_reason(source: &NullFlavour) -> Option<&str> {
reason_text(source.reason.as_ref()).filter(|&text| bridged(text).is_none())
}
fn bridged(code: &str) -> Option<Flavour> {
BRIDGE
.iter()
.find(|&&(fhir, _)| fhir == code)
.map(|&(_, flavour)| flavour)
}
fn reason_text(reason: Option<&DvText>) -> Option<&str> {
match reason? {
DvText::DvCodedText(coded) => Some(coded.value.as_str()),
DvText::DvText(plain) => Some(plain.value.as_str()),
}
}
fn text(code: &str) -> fhir_types::r4::primitives::String {
fhir_types::r4::primitives::String {
value: Some(String::from(code)),
..fhir_types::r4::primitives::String::default()
}
}
fn coded(flavour: Flavour) -> DvCodedText {
DvCodedText {
value: String::from(flavour.rubric()),
hyperlink: None,
formatting: None,
mappings: None,
language: None,
encoding: None,
defining_code: CodePhrase {
terminology_id: TerminologyId {
value: String::from(OPENEHR),
},
code_string: String::from(flavour.code()),
preferred_term: None,
},
}
}
fn reason(code: &str) -> DvText {
DvText::DvText(DvTextData {
value: String::from(code),
hyperlink: None,
formatting: None,
mappings: None,
language: None,
encoding: None,
})
}
#[cfg(test)]
mod tests {
use super::BRIDGE;
use super::Flavour;
use super::NullFlavour;
use super::NullFlavourLens;
use super::coded;
use super::reason;
use super::text;
use super::uncarried_reason;
use crate::engine::lens::Lens;
use proptest::prop_oneof;
use proptest::proptest;
use proptest::sample::select;
use proptest::strategy::Just;
use proptest::strategy::Strategy;
fn flavour(code: &str) -> NullFlavour {
let flavour = Flavour::from_code(code).map_or_else(
|| {
let mut outside = coded(Flavour::Unknown);
outside.value = String::new();
outside.defining_code.code_string = String::from(code);
outside
},
coded,
);
NullFlavour {
flavour,
reason: None,
}
}
fn held() -> impl Strategy<Value = NullFlavour> {
let codes: Vec<&str> = Flavour::ALL.iter().map(|flavour| flavour.code()).collect();
let fhir: Vec<&str> = BRIDGE.iter().map(|&(code, _)| code).collect();
let reasons = prop_oneof![
Just(None),
select(fhir).prop_map(|code| Some(reason(code))),
"[a-z ]{1,12}".prop_map(|text| Some(reason(&text))),
];
(select(codes), reasons).prop_map(|(code, reason)| NullFlavour {
reason,
..flavour(code)
})
}
proptest! {
#[test]
fn get_put(source in held()) {
let view = NullFlavourLens.get(&source).expect("a null flavour of the group travels");
let back = NullFlavourLens.put(&view, Some(&source)).expect("the view is a code of the set");
assert_eq!(back, source, "GetPut failed for {source:?}");
}
#[test]
fn put_get(code in select(BRIDGE.iter().map(|&(code, _)| code).collect::<Vec<&str>>())) {
let view = text(code);
let source = NullFlavourLens.put(&view, None).expect("the code is in the set");
let back = NullFlavourLens.get(&source).expect("the written flavour is of the group");
assert_eq!(back, view, "PutGet failed for {code}");
}
}
#[test]
fn every_bridge_entry_writes_its_flavour() {
for &(code, flavour) in BRIDGE {
let flavour_code = flavour.code();
let written = NullFlavourLens
.put(&text(code), None)
.expect("every row writes a flavour");
assert_eq!(
written.flavour.defining_code.code_string, flavour_code,
"{code} is written as {flavour_code}"
);
assert_eq!(
written.flavour.defining_code.terminology_id.value,
"openehr"
);
let read = NullFlavourLens.get(&written).expect("the row reads back");
assert_eq!(read, text(code), "{code} reads back as itself");
}
}
#[test]
fn the_three_defaults_write_no_reason() {
for code in ["unknown", "masked", "not-applicable"] {
let written = NullFlavourLens
.put(&text(code), None)
.expect("a default code");
assert_eq!(written.reason, None, "{code} needs no reason");
}
}
#[test]
fn a_code_without_a_flavour_of_its_own_keeps_it_in_the_reason() {
let written = NullFlavourLens
.put(&text("asked-declined"), None)
.expect("the code is in the set");
assert_eq!(written.flavour.defining_code.code_string, "253");
assert_eq!(written.reason, Some(reason("asked-declined")));
}
#[test]
fn no_information_reads_back_as_unknown() {
let read = NullFlavourLens
.get(&flavour("271"))
.expect("271 is of the group");
assert_eq!(read, text("unknown"));
}
#[test]
fn a_code_outside_the_value_set_is_refused() {
let error = NullFlavourLens
.put(&text("not-a-reason"), None)
.expect_err("the bridge is closed");
assert!(error.to_string().contains("not-a-reason"), "{error}");
}
#[test]
fn a_flavour_outside_the_group_is_refused() {
let error = NullFlavourLens
.get(&flavour("999"))
.expect_err("999 is no null flavour");
assert!(error.to_string().contains("999"), "{error}");
}
#[test]
fn a_flavour_of_another_terminology_is_refused() {
let mut source = flavour("253");
source.flavour.defining_code.terminology_id.value = String::from("local");
assert!(NullFlavourLens.get(&source).is_err());
}
#[test]
fn a_code_with_no_value_is_refused() {
assert!(
NullFlavourLens
.put(&fhir_types::r4::primitives::String::default(), None)
.is_err()
);
}
#[test]
fn a_free_text_reason_is_named_as_uncarried() {
let source = NullFlavour {
reason: Some(reason("the patient was asleep")),
..flavour("253")
};
assert_eq!(uncarried_reason(&source), Some("the patient was asleep"));
let coded_reason = NullFlavour {
reason: Some(reason("asked-declined")),
..flavour("253")
};
assert_eq!(uncarried_reason(&coded_reason), None);
assert_eq!(
NullFlavourLens
.get(&coded_reason)
.expect("253 is of the group"),
text("asked-declined"),
"a reason that names a code is read back"
);
}
}