use openehr_base::v1_3::base_types::identification::generic_id::GenericId;
use openehr_base::v1_3::base_types::identification::object_id::ObjectId;
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_mapping_core::composition::NodeValue;
use openehr_mapping_core::composition::RmPosition;
use openehr_mapping_core::index::ResolvedNode;
use openehr_rm::v1_2::common::archetyped::feeder_audit::FeederAudit;
use openehr_rm::v1_2::common::archetyped::feeder_audit_details::FeederAuditDetails;
use openehr_rm::v1_2::common::archetyped::link::Link;
use openehr_rm::v1_2::common::generic::party_identified::PartyIdentified;
use openehr_rm::v1_2::common::generic::party_identified::PartyIdentifiedData;
use openehr_rm::v1_2::common::generic::party_proxy::PartyProxy;
use openehr_rm::v1_2::data_types::basic::dv_identifier::DvIdentifier;
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_ehr_uri::DvEhrUri;
use openehr_sdt::flat::path::Segment;
use crate::engine::demographics::PartyIdentity;
use crate::engine::lens::null_flavour::NullFlavour;
use crate::engine::origin::ItemId;
use crate::engine::origin::Origin;
use crate::engine::origin::Party;
use crate::engine::origin::UNKNOWN_SOURCE;
use crate::engine::rm::RAW;
use crate::engine::traverse::defaults::ComposerId;
pub const DEFAULTED: &str = "defaulted";
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("the `{attribute}` of the node does not read as its reference-model class")]
pub struct FamilyError {
pub attribute: &'static str,
#[source]
pub source: JsonParseError,
}
fn plain(name: &str) -> Segment {
Segment {
name: String::from(name),
index: None,
}
}
fn indexed(name: &str, index: usize) -> Segment {
Segment {
name: String::from(name),
index: Some(u32::try_from(index).unwrap_or(u32::MAX)),
}
}
#[must_use]
pub fn feeder_audit(
root: &ResolvedNode,
origin: &Origin,
defaulted: &[String],
unplaced: Option<&Party>,
) -> Vec<NodeValue> {
let details = |system_id: &str, version_id: Option<&str>| FeederAuditDetails {
system_id: String::from(system_id),
location: None,
subject: None,
provider: None,
time: None,
version_id: version_id.map(String::from),
other_details: None,
};
let identifier = |id: &str, kind: &str, issuer: Option<&str>| DvIdentifier {
issuer: issuer.map(String::from),
assigner: None,
id: String::from(id),
r#type: Some(String::from(kind)),
};
let source = origin.source();
let audit = FeederAudit {
originating_system_item_ids: match origin.originating_items() {
Some(items) => (!items.is_empty()).then(|| {
items
.iter()
.map(|item| identifier(&item.id, &item.kind, item.issuer.as_deref()))
.collect()
}),
None => source.map(|source| {
vec![identifier(
source.id().unwrap_or(UNKNOWN_SOURCE),
source.resource_type(),
None,
)]
}),
},
feeder_system_item_ids: (!defaulted.is_empty() || !origin.feeder_items().is_empty()).then(
|| {
origin
.feeder_items()
.iter()
.map(|item| identifier(&item.id, &item.kind, item.issuer.as_deref()))
.chain(
defaulted
.iter()
.map(|field| identifier(field, DEFAULTED, Some(origin.system_id()))),
)
.collect()
},
),
original_content: None,
originating_system_audit: Box::new(FeederAuditDetails {
location: origin.location().or(unplaced).map(party_identified),
provider: origin.provider().map(party_identified),
..details(
origin.originating_system().unwrap_or(origin.system_id()),
source.and_then(|source| source.version_id()),
)
}),
feeder_system_audit: (!defaulted.is_empty()
|| !origin.feeder_items().is_empty()
|| origin.originating_system().is_some())
.then(|| Box::new(details(origin.system_id(), None))),
};
vec![
NodeValue::new(root, to_canonical_value(&audit))
.under(vec![plain("_feeder_audit")])
.with_datum(RAW),
]
}
#[must_use]
pub fn party_identified(party: &Party) -> PartyIdentified {
PartyIdentified::PartyIdentified(PartyIdentifiedData {
external_ref: None,
name: party.name.clone(),
identifiers: dv_identifiers(&party.identifiers),
})
}
fn dv_identifiers(items: &[ItemId]) -> Option<openehr_base::containers::NonEmptyVec<DvIdentifier>> {
let identifiers: Vec<DvIdentifier> = items
.iter()
.map(|item| DvIdentifier {
issuer: item.issuer.clone(),
assigner: None,
id: item.id.clone(),
r#type: Some(item.kind.clone()),
})
.collect();
openehr_base::containers::NonEmptyVec::new(identifiers).ok()
}
#[must_use]
pub fn composer(
node: &ResolvedNode,
name: &str,
id: Option<&ComposerId>,
identifiers: &[ItemId],
) -> NodeValue {
let party = PartyIdentified::PartyIdentified(PartyIdentifiedData {
external_ref: id.map(|id| PartyRef {
namespace: id.namespace.clone(),
r#type: String::from("PERSON"),
id: ObjectId::GenericId(GenericId {
value: id.id.clone(),
scheme: id.scheme.clone(),
}),
}),
name: Some(String::from(name)),
identifiers: dv_identifiers(identifiers),
});
NodeValue::new(node, to_canonical_value(&party)).with_datum(RAW)
}
#[must_use]
pub fn health_care_facility(context: &ResolvedNode, facility: &Party) -> Vec<NodeValue> {
vec![
NodeValue::new(context, to_canonical_value(&party_identified(facility)))
.under(vec![plain(HEALTH_CARE_FACILITY)])
.with_datum(RAW),
]
}
pub const HEALTH_CARE_FACILITY: &str = "_health_care_facility";
#[must_use]
pub fn link(
node: &ResolvedNode,
positions: &[RmPosition],
index: usize,
parts: &LinkParts<'_>,
) -> Vec<NodeValue> {
let link = Link {
meaning: plain_text(parts.meaning),
r#type: plain_text(parts.link_type),
target: DvEhrUri {
value: String::from(parts.target),
},
};
vec![
NodeValue::new(node, to_canonical_value(&link))
.with_occurrences(positions.to_vec())
.under(vec![indexed("_link", index)])
.with_datum(RAW),
]
}
fn plain_text(value: &str) -> DvText {
DvText::DvText(DvTextData {
value: String::from(value),
hyperlink: None,
formatting: None,
mappings: None,
language: None,
encoding: None,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LinkParts<'text> {
pub meaning: &'text str,
pub link_type: &'text str,
pub target: &'text str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParticipationParts<'text> {
pub function: &'text str,
pub name: Option<&'text str>,
pub id: &'text str,
pub id_scheme: &'text str,
pub id_namespace: &'text str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParticipationList {
pub owner: &'static str,
pub attribute: &'static str,
pub family: &'static str,
}
pub const ENTRY_PARTICIPATIONS: ParticipationList = ParticipationList {
owner: "ENTRY",
attribute: "other_participations",
family: "_other_participation",
};
pub const CONTEXT_PARTICIPATIONS: ParticipationList = ParticipationList {
owner: "EVENT_CONTEXT",
attribute: "participations",
family: "_participation",
};
#[must_use]
pub fn participation_list(class: &str, tail: &[&str]) -> Option<ParticipationList> {
[ENTRY_PARTICIPATIONS, CONTEXT_PARTICIPATIONS]
.into_iter()
.find(|list| tail == [list.attribute] && openehr_rm::v1_2::model::is_a(class, list.owner))
}
#[must_use]
pub fn participation(
node: &ResolvedNode,
list: ParticipationList,
positions: &[RmPosition],
index: usize,
parts: &ParticipationParts<'_>,
) -> Vec<NodeValue> {
let participation = openehr_rm::v1_2::common::generic::participation::Participation {
function: plain_text(parts.function),
mode: None,
performer: PartyProxy::PartyIdentified(PartyIdentified::PartyIdentified(
PartyIdentifiedData {
external_ref: Some(PartyRef {
namespace: String::from(parts.id_namespace),
r#type: String::from("PERSON"),
id: ObjectId::GenericId(GenericId {
value: String::from(parts.id),
scheme: String::from(parts.id_scheme),
}),
}),
name: parts.name.map(String::from),
identifiers: None,
},
)),
time: None,
};
vec![
NodeValue::new(node, to_canonical_value(&participation))
.with_occurrences(positions.to_vec())
.under(vec![indexed(list.family, index)])
.with_datum(RAW),
]
}
#[must_use]
pub fn provider(
node: &ResolvedNode,
positions: &[RmPosition],
family: &[Segment],
party: &PartyIdentifiedData,
) -> Vec<NodeValue> {
let party = PartyIdentified::PartyIdentified(party.clone());
vec![
NodeValue::new(node, to_canonical_value(&party))
.with_occurrences(positions.to_vec())
.under(family.to_vec())
.with_datum(RAW),
]
}
#[must_use]
pub fn end_time(
node: &ResolvedNode,
positions: &[RmPosition],
family: &[Segment],
value: &str,
) -> NodeValue {
NodeValue::new(node, serde_json::Value::String(String::from(value)))
.with_occurrences(positions.to_vec())
.under(family.to_vec())
}
#[must_use]
pub fn null_flavour(
node: &ResolvedNode,
positions: &[RmPosition],
flavour: &NullFlavour,
) -> Vec<NodeValue> {
let code = &flavour.flavour.defining_code;
let mut values: Vec<NodeValue> = [
("code", code.code_string.as_str()),
("value", flavour.flavour.value.as_str()),
("terminology", code.terminology_id.value.as_str()),
]
.into_iter()
.map(|(datum, value)| {
NodeValue::new(node, serde_json::Value::String(String::from(value)))
.with_occurrences(positions.to_vec())
.under(vec![plain("_null_flavour")])
.with_datum(datum)
})
.collect();
if let Some(ref reason) = flavour.reason {
values.push(
NodeValue::new(
node,
serde_json::Value::String(String::from(text_of(reason))),
)
.with_occurrences(positions.to_vec())
.under(vec![plain("_null_reason")]),
);
}
values
}
const fn undecodable(attribute: &'static str) -> impl Fn(JsonParseError) -> FamilyError {
move |source| FamilyError { attribute, source }
}
fn text_of(text: &DvText) -> &str {
match *text {
DvText::DvCodedText(ref coded) => &coded.value,
DvText::DvText(ref plain) => &plain.value,
}
}
pub fn link_targets(
value: &serde_json::Value,
meaning: &str,
link_type: &str,
) -> Result<Vec<String>, FamilyError> {
let Some(found) = value.get("links") else {
return Ok(Vec::new());
};
Ok(from_canonical_value::<Vec<Link>>(found)
.map_err(undecodable("links"))?
.into_iter()
.filter(|link| text_of(&link.meaning) == meaning && text_of(&link.r#type) == link_type)
.map(|link| link.target.value)
.collect())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Participation {
pub id: Option<String>,
pub name: Option<String>,
pub identity: Option<PartyIdentity>,
}
fn id_value(id: &ObjectId) -> String {
match *id {
ObjectId::ArchetypeId(ref id) => id.value.clone(),
ObjectId::GenericId(ref id) => id.value.clone(),
ObjectId::HierObjectId(ref id) => String::from(id.value()),
ObjectId::ObjectVersionId(ref id) => String::from(id.value()),
ObjectId::TemplateId(ref id) => id.value.clone(),
ObjectId::TerminologyId(ref id) => id.value.clone(),
}
}
pub fn participations(
value: &serde_json::Value,
list: ParticipationList,
function: &str,
) -> Result<Vec<Participation>, FamilyError> {
let Some(found) = value.get(list.attribute) else {
return Ok(Vec::new());
};
Ok(from_canonical_value::<
Vec<openehr_rm::v1_2::common::generic::participation::Participation>,
>(found)
.map_err(undecodable(list.attribute))?
.into_iter()
.filter(|entry| text_of(&entry.function) == function)
.map(|entry| {
let (reference, name) = match entry.performer {
PartyProxy::PartySelf(party) => (party.external_ref, None),
PartyProxy::PartyIdentified(PartyIdentified::PartyIdentified(party)) => {
(party.external_ref, party.name)
}
PartyProxy::PartyIdentified(PartyIdentified::PartyRelated(party)) => {
(party.external_ref, party.name)
}
};
Participation {
identity: reference.as_ref().and_then(PartyIdentity::from_party_ref),
id: reference.map(|reference| id_value(&reference.id)),
name,
}
})
.collect())
}