use fhir_types::r4::coding::Coding;
use openehr_rm::v1_2::data_types::text::term_mapping::TermMapping;
use crate::engine::lens::Lens;
use crate::engine::lens::LensError;
use crate::engine::lens::code_phrase::CodePhraseLens;
use crate::model::ast::keyword::Direction;
pub const EQUIVALENT: char = '=';
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Cause {
Match,
Uncarried,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Withheld {
match_code: char,
terminology: String,
code: String,
cause: Cause,
}
impl Withheld {
#[must_use]
pub fn of(mapping: &TermMapping) -> Option<Self> {
(mapping.r#match != EQUIVALENT).then(|| Self::with_cause(mapping, Cause::Match))
}
#[must_use]
pub fn uncarried(mapping: &TermMapping) -> Self {
Self::with_cause(mapping, Cause::Uncarried)
}
fn with_cause(mapping: &TermMapping, cause: Cause) -> Self {
Self {
match_code: mapping.r#match,
terminology: mapping.target.terminology_id.value.clone(),
code: mapping.target.code_string.clone(),
cause,
}
}
#[must_use]
pub const fn match_code(&self) -> char {
self.match_code
}
#[must_use]
pub const fn cause(&self) -> Cause {
self.cause
}
#[must_use]
pub fn terminology(&self) -> &str {
&self.terminology
}
#[must_use]
pub fn code(&self) -> &str {
&self.code
}
}
pub fn equivalents<'held>(
mappings: impl IntoIterator<Item = &'held TermMapping>,
) -> impl Iterator<Item = &'held TermMapping> {
mappings
.into_iter()
.filter(|mapping| mapping.r#match == EQUIVALENT)
}
#[must_use]
pub fn withheld<'held>(mappings: impl IntoIterator<Item = &'held TermMapping>) -> Vec<Withheld> {
mappings.into_iter().filter_map(Withheld::of).collect()
}
#[must_use]
pub fn uncarried<'held>(mappings: impl IntoIterator<Item = &'held TermMapping>) -> Vec<Withheld> {
mappings.into_iter().map(Withheld::uncarried).collect()
}
pub fn coding_of(mapping: &TermMapping, cell: &'static str) -> Result<Coding, LensError> {
if mapping.r#match != EQUIVALENT {
return Err(LensError::Shape {
cell,
attribute: "TERM_MAPPING.match",
found: mapping.r#match.to_string(),
reason: "FHIR carries no relation beside a coding, so only `=` maps",
direction: Direction::OpenehrToFhir,
});
}
CodePhraseLens.get(&mapping.target)
}
pub fn mapping_of(
coding: &Coding,
existing: Option<&TermMapping>,
) -> Result<TermMapping, LensError> {
Ok(TermMapping {
r#match: EQUIVALENT,
purpose: existing.and_then(|mapping| mapping.purpose.clone()),
target: CodePhraseLens.put(coding, existing.map(|mapping| &mapping.target))?,
})
}
pub fn mappings_of<'view>(
codings: impl IntoIterator<Item = &'view Coding>,
held: Option<&[TermMapping]>,
) -> Result<Vec<TermMapping>, LensError> {
let mut codings = codings.into_iter();
let mut written = Vec::new();
for mapping in held.unwrap_or_default() {
if mapping.r#match != EQUIVALENT {
written.push(mapping.clone());
} else if let Some(coding) = codings.next() {
written.push(mapping_of(coding, Some(mapping))?);
}
}
for coding in codings {
written.push(mapping_of(coding, None)?);
}
Ok(written)
}
#[cfg(test)]
mod tests {
use super::Withheld;
use super::coding_of;
use super::equivalents;
use super::mapping_of;
use super::mappings_of;
use super::withheld;
use crate::engine::lens::LensError;
use fhir_types::r4::coding::Coding;
use fhir_types::r4::primitives::Code;
use fhir_types::r4::primitives::Uri;
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::term_mapping::TermMapping;
fn mapping(relation: char) -> TermMapping {
mapping_to(relation, "http://snomed.info/sct", "386661006")
}
fn mapping_to(relation: char, system: &str, code: &str) -> TermMapping {
TermMapping {
r#match: relation,
purpose: None,
target: CodePhrase {
terminology_id: TerminologyId::new(system, ""),
code_string: String::from(code),
preferred_term: None,
},
}
}
fn code_of(system: &str, code: &str) -> Coding {
Coding {
system: Some(Uri::from(system)),
code: Some(Code::from(code)),
..Coding::default()
}
}
#[test]
fn an_equivalent_mapping_is_one_coding() {
let view = coding_of(&mapping('='), "test").expect("an equivalent mapping");
assert_eq!(
view.code.as_ref().and_then(|code| code.value.as_deref()),
Some("386661006"),
"the target code travels into the coding"
);
}
#[test]
fn a_narrower_mapping_is_refused() {
let error = coding_of(&mapping('<'), "test").expect_err("a narrower relation");
assert!(
matches!(error, LensError::Shape { attribute, .. } if attribute == "TERM_MAPPING.match"),
"the refusal names the operator: {error}"
);
}
#[test]
fn an_equivalent_mapping_is_withheld_from_nothing() {
assert_eq!(Withheld::of(&mapping('=')), None, "FHIR carries `=`");
}
#[test]
fn each_relation_fhir_cannot_carry_is_withheld_with_its_term() {
for relation in ['>', '<', '?'] {
let held = mapping_to(relation, "http://loinc.org", "LP74849-8");
let taken = Withheld::of(&held).expect("only `=` maps");
assert_eq!(taken.match_code(), relation, "the operator is kept");
assert_eq!(taken.terminology(), "http://loinc.org");
assert_eq!(taken.code(), "LP74849-8");
}
}
#[test]
fn the_two_filters_split_the_mappings_in_order() {
let held = [
mapping_to('=', "http://loinc.org", "A"),
mapping_to('<', "http://loinc.org", "B"),
mapping_to('=', "http://loinc.org", "C"),
mapping_to('?', "http://loinc.org", "D"),
];
let carried: Vec<&str> = equivalents(&held)
.map(|mapping| mapping.target.code_string.as_str())
.collect();
assert_eq!(carried, ["A", "C"], "the `=` mappings travel in order");
let taken = withheld(&held);
let left: Vec<(char, &str)> = taken
.iter()
.map(|taken| (taken.match_code(), taken.code()))
.collect();
assert_eq!(
left,
[('<', "B"), ('?', "D")],
"the others are withheld in order"
);
}
#[test]
fn a_written_mapping_is_always_equivalent_and_keeps_its_purpose() {
let existing = TermMapping {
purpose: Some(
openehr_rm::v1_2::data_types::text::dv_coded_text::DvCodedText {
value: String::from("billing"),
hyperlink: None,
formatting: None,
mappings: None,
language: None,
encoding: None,
defining_code: CodePhrase {
terminology_id: TerminologyId::new("http://example.org/purpose", ""),
code_string: String::from("bill"),
preferred_term: None,
},
},
),
..mapping('=')
};
let view = code_of("http://loinc.org", "LP74849-8");
let written = mapping_of(&view, Some(&existing)).expect("the coding is complete");
assert_eq!(written.r#match, '=', "the match is hard coded to `=`");
assert_eq!(
written.purpose, existing.purpose,
"purpose has no FHIR counterpart and is carried"
);
}
#[test]
fn a_held_mapping_fhir_cannot_carry_keeps_its_place_going_back() {
let held = [
mapping_to('=', "http://loinc.org", "A"),
mapping_to('>', "http://loinc.org", "B"),
mapping_to('=', "http://loinc.org", "C"),
];
let codings = [
code_of("http://loinc.org", "A2"),
code_of("http://loinc.org", "C2"),
code_of("http://loinc.org", "E2"),
];
let written = mappings_of(&codings, Some(&held)).expect("complete codings");
let rows: Vec<(char, &str)> = written
.iter()
.map(|mapping| (mapping.r#match, mapping.target.code_string.as_str()))
.collect();
assert_eq!(
rows,
[('=', "A2"), ('>', "B"), ('=', "C2"), ('=', "E2")],
"each coding replaces the next `=` mapping and the `>` one stays"
);
}
#[test]
fn a_held_equivalent_no_coding_replaces_is_dropped() {
let held = [
mapping_to('=', "http://loinc.org", "A"),
mapping_to('?', "http://loinc.org", "B"),
mapping_to('=', "http://loinc.org", "C"),
];
let written = mappings_of(&[], Some(&held)).expect("no coding to write");
let rows: Vec<(char, &str)> = written
.iter()
.map(|mapping| (mapping.r#match, mapping.target.code_string.as_str()))
.collect();
assert_eq!(rows, [('?', "B")], "only the withheld mapping is carried");
}
}