use openehr_base::containers::NonEmptyVec;
use openehr_base::v1_3::base_types::identification::party_ref::PartyRef;
use openehr_its::json::JsonParseError;
use openehr_its::json::from_canonical_value;
use openehr_its::json::to_canonical_value;
use openehr_rm::v1_2::common::generic::party_identified::PartyIdentifiedData;
use openehr_rm::v1_2::data_types::basic::dv_boolean::DvBoolean;
use openehr_rm::v1_2::data_types::basic::dv_identifier::DvIdentifier;
use openehr_rm::v1_2::data_types::encapsulated::dv_multimedia::DvMultimedia;
use openehr_rm::v1_2::data_types::encapsulated::dv_parsable::DvParsable;
use openehr_rm::v1_2::data_types::quantity::date_time::dv_date::DvDate;
use openehr_rm::v1_2::data_types::quantity::date_time::dv_date_time::DvDateTime;
use openehr_rm::v1_2::data_types::quantity::date_time::dv_duration::DvDuration;
use openehr_rm::v1_2::data_types::quantity::date_time::dv_time::DvTime;
use openehr_rm::v1_2::data_types::quantity::dv_count::DvCount;
use openehr_rm::v1_2::data_types::quantity::dv_interval::DvInterval;
use openehr_rm::v1_2::data_types::quantity::dv_ordinal::DvOrdinal;
use openehr_rm::v1_2::data_types::quantity::dv_proportion::DvProportion;
use openehr_rm::v1_2::data_types::quantity::dv_quantity::DvQuantity;
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_rm::v1_2::data_types::uri::dv_uri::DvUri;
use openehr_rm::v1_2::typing::base_name;
use openehr_sdt::flat::attribute_keys::attribute_key;
use openehr_sdt::flat::path::Segment;
use serde_json::Value;
pub mod carried;
pub mod interval;
pub mod null_flavour;
pub(crate) mod tail_walk;
use crate::engine::rm::null_flavour::NULL_FLAVOUR;
use crate::resolve::derive::type_argument;
pub const RAW: &str = "raw";
#[derive(Debug, Clone, PartialEq)]
pub enum RmValue {
Text(DvTextData),
CodedText(Box<DvCodedText>),
CodePhrase(CodePhrase),
Date(Box<DvDate>),
DateTime(Box<DvDateTime>),
DateTimeInterval(Box<DvInterval<DvDateTime>>),
QuantityInterval(Box<DvInterval<DvQuantity>>),
Party(PartyIdentifiedData),
Identifier(DvIdentifier),
Proportion(Box<DvProportion>),
Quantity(Box<DvQuantity>),
Count(Box<DvCount>),
Ordinal(Box<DvOrdinal>),
Time(Box<DvTime>),
Duration(Box<DvDuration>),
Uri(DvUri),
Multimedia(Box<DvMultimedia>),
Parsable(Box<DvParsable>),
Boolean(DvBoolean),
PartyRef(PartyRef),
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RmError {
#[error("no data-type cell carries the openEHR class {rm_type}")]
UnknownClass {
rm_type: String,
},
#[error("the value at {node} does not read as {rm_type}")]
Decode {
node: String,
rm_type: String,
#[source]
source: JsonParseError,
},
#[error("the {rm_type} attribute at {node} takes {expected}, and `{text}` is none")]
Scalar {
node: String,
rm_type: String,
text: String,
expected: &'static str,
},
#[error("the {rm_type} value has no canonical JSON form: {reason}")]
Encode {
rm_type: &'static str,
reason: String,
},
}
impl RmValue {
#[must_use]
pub const fn rm_type(&self) -> &'static str {
match *self {
Self::Text(_) => "DV_TEXT",
Self::CodedText(_) => "DV_CODED_TEXT",
Self::CodePhrase(_) => "CODE_PHRASE",
Self::Date(_) => "DV_DATE",
Self::DateTime(_) => "DV_DATE_TIME",
Self::DateTimeInterval(_) | Self::QuantityInterval(_) => "DV_INTERVAL",
Self::Party(_) => "PARTY_IDENTIFIED",
Self::Identifier(_) => "DV_IDENTIFIER",
Self::Proportion(_) => "DV_PROPORTION",
Self::Quantity(_) => "DV_QUANTITY",
Self::Count(_) => "DV_COUNT",
Self::Ordinal(_) => "DV_ORDINAL",
Self::Time(_) => "DV_TIME",
Self::Duration(_) => "DV_DURATION",
Self::Uri(_) => "DV_URI",
Self::Multimedia(_) => "DV_MULTIMEDIA",
Self::Parsable(_) => "DV_PARSABLE",
Self::Boolean(_) => "DV_BOOLEAN",
Self::PartyRef(_) => "PARTY_REF",
}
}
pub fn from_canonical(rm_type: &str, node: &str, value: &Value) -> Result<Self, RmError> {
let refuse = |source: JsonParseError| RmError::Decode {
node: String::from(node),
rm_type: String::from(rm_type),
source,
};
match base_name(rm_type) {
"DV_TEXT" | "DV_CODED_TEXT" => from_canonical_value::<DvText>(value)
.map(|text| match text {
DvText::DvCodedText(coded) => Self::CodedText(Box::new(coded)),
DvText::DvText(plain) => Self::Text(plain),
})
.map_err(refuse),
"CODE_PHRASE" => from_canonical_value(value)
.map(Self::CodePhrase)
.map_err(refuse),
"DV_DATE" => from_canonical_value(value)
.map(|date| Self::Date(Box::new(date)))
.map_err(refuse),
"DV_BOOLEAN" => from_canonical_value(value)
.map(Self::Boolean)
.map_err(refuse),
"DV_DATE_TIME" => from_canonical_value(value)
.map(|date| Self::DateTime(Box::new(date)))
.map_err(refuse),
"DV_INTERVAL"
if type_argument(rm_type).is_some_and(|bound| bound.name() == DV_QUANTITY)
|| bound_class(value) == Some(DV_QUANTITY) =>
{
from_canonical_value(value)
.map(|interval| Self::QuantityInterval(Box::new(interval)))
.map_err(refuse)
}
"DV_INTERVAL" => from_canonical_value(value)
.map(|interval| Self::DateTimeInterval(Box::new(interval)))
.map_err(refuse),
"PARTY_IDENTIFIED" | "PARTY_PROXY" => {
from_canonical_value(value).map(Self::Party).map_err(refuse)
}
"DV_IDENTIFIER" => from_canonical_value(value)
.map(Self::Identifier)
.map_err(refuse),
"DV_PROPORTION" => from_canonical_value(value)
.map(|proportion| Self::Proportion(Box::new(proportion)))
.map_err(refuse),
"DV_QUANTITY" => from_canonical_value(value)
.map(|quantity| Self::Quantity(Box::new(quantity)))
.map_err(refuse),
"DV_COUNT" => from_canonical_value(value)
.map(|count| Self::Count(Box::new(count)))
.map_err(refuse),
"DV_ORDINAL" => from_canonical_value(value)
.map(|ordinal| Self::Ordinal(Box::new(ordinal)))
.map_err(refuse),
"DV_TIME" => from_canonical_value(value)
.map(|time| Self::Time(Box::new(time)))
.map_err(refuse),
"DV_DURATION" => from_canonical_value(value)
.map(|duration| Self::Duration(Box::new(duration)))
.map_err(refuse),
"DV_URI" => from_canonical_value(value).map(Self::Uri).map_err(refuse),
"DV_MULTIMEDIA" => from_canonical_value(value)
.map(|multimedia| Self::Multimedia(Box::new(multimedia)))
.map_err(refuse),
"DV_PARSABLE" => from_canonical_value(value)
.map(|parsable| Self::Parsable(Box::new(parsable)))
.map_err(refuse),
"PARTY_REF" => from_canonical_value(value)
.map(Self::PartyRef)
.map_err(refuse),
other => Err(RmError::UnknownClass {
rm_type: String::from(other),
}),
}
}
pub fn to_canonical(&self) -> Result<Value, RmError> {
let encoded = match *self {
Self::Text(ref text) => to_canonical_value(text),
Self::CodedText(ref coded) => to_canonical_value(coded.as_ref()),
Self::CodePhrase(ref code) => to_canonical_value(code),
Self::Date(ref date) => to_canonical_value(date.as_ref()),
Self::Boolean(ref boolean) => to_canonical_value(boolean),
Self::DateTime(ref date) => to_canonical_value(date.as_ref()),
Self::DateTimeInterval(ref interval) => to_canonical_value(interval.as_ref()),
Self::QuantityInterval(ref interval) => to_canonical_value(interval.as_ref()),
Self::Party(ref party) => to_canonical_value(party),
Self::Identifier(ref identifier) => to_canonical_value(identifier),
Self::PartyRef(ref party) => to_canonical_value(party),
Self::Proportion(ref proportion) => {
for number in [proportion.numerator, proportion.denominator] {
if !number.is_finite() {
return Err(RmError::Encode {
rm_type: "DV_PROPORTION",
reason: format!("{number} is not a finite JSON number"),
});
}
}
to_canonical_value(proportion.as_ref())
}
Self::Quantity(ref quantity) => {
if !quantity.magnitude.is_finite() {
return Err(RmError::Encode {
rm_type: "DV_QUANTITY",
reason: format!("{} is not a finite JSON number", quantity.magnitude),
});
}
to_canonical_value(quantity.as_ref())
}
Self::Count(ref count) => to_canonical_value(count.as_ref()),
Self::Ordinal(ref ordinal) => to_canonical_value(ordinal.as_ref()),
Self::Time(ref time) => to_canonical_value(time.as_ref()),
Self::Duration(ref duration) => to_canonical_value(duration.as_ref()),
Self::Uri(ref uri) => to_canonical_value(uri),
Self::Multimedia(ref multimedia) => to_canonical_value(multimedia.as_ref()),
Self::Parsable(ref parsable) => to_canonical_value(parsable.as_ref()),
};
Ok(encoded)
}
}
const DV_QUANTITY: &str = "DV_QUANTITY";
fn bound_class(value: &Value) -> Option<&str> {
["lower", "upper"]
.into_iter()
.find_map(|bound| value.get(bound)?.get("_type")?.as_str())
}
pub const FAMILIES: &[(&str, &str)] = &[
("ENTRY", "provider"),
("EVENT_CONTEXT", "health_care_facility"),
("EVENT_CONTEXT", "end_time"),
("ELEMENT", NULL_FLAVOUR),
];
pub const ENTRY_TIMES: &[(&str, &str)] = &[("OBSERVATION", "data/origin"), ("ACTION", "time")];
#[must_use]
pub fn entry_time_key(owner: &str, tail: &str) -> Option<&'static str> {
ENTRY_TIMES
.iter()
.any(|&(entry, path)| entry == owner && path == tail)
.then(|| attribute_key(owner, tail))
.flatten()
.map(|row| row.key)
}
pub const PARTY_ROOTS: &[(&str, &str)] = &[("ROLE", "performer")];
#[must_use]
pub fn family_of(owner: &str, tail: &[&str]) -> Option<Vec<Segment>> {
let row = attribute_key(owner, &tail.join("/"))?;
Some(vec![Segment {
name: row.key.to_owned(),
index: None,
}])
}
#[must_use]
pub fn identifiers(values: Vec<DvIdentifier>) -> Option<NonEmptyVec<DvIdentifier>> {
NonEmptyVec::new(values).ok()
}
#[cfg(test)]
mod tests {
use super::RmValue;
use super::carried::Carried;
use super::carried::carried;
use super::entry_time_key;
use openehr_base::v1_3::base_types::identification::terminology_id::TerminologyId;
use openehr_rm::v1_2::data_types::text::code_phrase::CodePhrase;
#[test]
fn a_code_phrase_writes_all_three_attributes_in_its_canonical_form() {
let value = RmValue::CodePhrase(CodePhrase {
terminology_id: TerminologyId {
value: String::from("local"),
},
code_string: String::from("at0017"),
preferred_term: Some(String::from("Working")),
});
let canonical = value.to_canonical().expect("a code phrase encodes");
assert_eq!(
canonical,
serde_json::json!({
"_type": "CODE_PHRASE",
"terminology_id": {"_type": "TERMINOLOGY_ID", "value": "local"},
"code_string": "at0017",
"preferred_term": "Working"
})
);
assert_eq!(
RmValue::from_canonical("CODE_PHRASE", "/x", &canonical).expect("it reads back"),
value
);
}
#[test]
fn a_date_time_keeps_its_text_byte_for_byte() {
let value = RmValue::from_canonical(
"DV_DATE_TIME",
"/context/start_time",
&serde_json::json!({"_type": "DV_DATE_TIME", "value": "2026-09-12T10:00:00+02:00"}),
)
.expect("the canonical form reads back");
let canonical = value.to_canonical().expect("a date and time encodes");
assert_eq!(
canonical.get("value").and_then(serde_json::Value::as_str),
Some("2026-09-12T10:00:00+02:00"),
"the offset survives byte for byte"
);
}
#[test]
fn a_class_no_cell_carries_names_itself() {
let error = RmValue::from_canonical("DV_MULTIMEDIA", "/x", &serde_json::Value::Null)
.expect_err("no cell carries DV_MULTIMEDIA");
assert!(
error.to_string().contains("DV_MULTIMEDIA"),
"the refusal names the class: {error}"
);
}
#[test]
fn a_coded_text_keeps_its_term_mappings_and_language() {
let written = serde_json::json!({
"_type": "DV_CODED_TEXT",
"value": "Synthetic problem one",
"mappings": [{
"_type": "TERM_MAPPING",
"match": "=",
"target": {
"_type": "CODE_PHRASE",
"terminology_id": {"_type": "TERMINOLOGY_ID", "value": "SNOMED-CT"},
"code_string": "73211009"
}
}],
"language": {
"_type": "CODE_PHRASE",
"terminology_id": {"_type": "TERMINOLOGY_ID", "value": "ISO_639-1"},
"code_string": "en"
},
"defining_code": {
"_type": "CODE_PHRASE",
"terminology_id": {"_type": "TERMINOLOGY_ID", "value": "local"},
"code_string": "at0001"
}
});
let value = RmValue::from_canonical("DV_CODED_TEXT", "/x", &written)
.expect("the canonical form reads back");
let canonical = value.to_canonical().expect("a coded text encodes");
assert_eq!(canonical.get("mappings"), written.get("mappings"));
assert_eq!(canonical.get("language"), written.get("language"));
}
#[test]
fn a_defective_value_names_the_json_path_it_failed_at() {
let error = RmValue::from_canonical(
"DV_TEXT",
"/x",
&serde_json::json!({"_type": "DV_TEXT", "value": "text", "undeclared": 1}),
)
.expect_err("the strict reader refuses an undeclared key");
assert!(
core::error::Error::source(&error).is_some(),
"the reader's refusal is the source: {error}"
);
}
#[test]
fn the_entry_provider_is_a_family() {
assert_eq!(
carried("EVALUATION", &["provider"]),
Some(("ENTRY", Carried::Family))
);
}
#[test]
fn the_context_health_care_facility_is_a_family() {
assert_eq!(
carried("EVENT_CONTEXT", &["health_care_facility"]),
Some(("EVENT_CONTEXT", Carried::Family))
);
assert_eq!(carried("EVENT_CONTEXT", &["location"]), None);
}
#[test]
fn the_context_end_time_is_a_family() {
assert_eq!(
carried("EVENT_CONTEXT", &["end_time"]),
Some(("EVENT_CONTEXT", Carried::Family))
);
}
#[test]
fn the_history_origin_is_carried_on_an_observation_alone() {
assert_eq!(
carried("OBSERVATION", &["data", "origin"]),
Some(("OBSERVATION", Carried::EntryTime))
);
assert_eq!(carried("EVALUATION", &["data", "origin"]), None);
assert_eq!(carried("OBSERVATION", &["data", "period"]), None);
}
#[test]
fn the_time_of_an_action_is_carried_on_an_action_alone() {
assert_eq!(
carried("ACTION", &["time"]),
Some(("ACTION", Carried::EntryTime))
);
assert_eq!(entry_time_key("ACTION", "time"), Some("time"));
assert_eq!(carried("INSTRUCTION", &["time"]), None);
}
}