fhirconnect 0.2.4

The FHIRconnect mapping language for Rust: the mapping file model and its validation, context resolution into an immutable program, and the bidirectional interpreter between openEHR compositions and FHIR resources
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! The reference-model attribute families a composition carries beside its
//! archetyped content.
//!
//! `FEEDER_AUDIT`, `LINK` and `PARTICIPATION` are attributes of the reference
//! model that no Web Template node stands for, so the composition seam reaches
//! them as the `_`-prefixed families Simplified Formats spells under the node
//! they belong to: `_feeder_audit` on any `LOCATABLE`, `_link:i` on any
//! `LOCATABLE`, `_other_participation:i` on an `ENTRY` and `_participation:i`
//! under the `context` of a composition (openEHR ITS-REST 1.1.0, Simplified
//! Formats, `docs/specs/its-rest/docs/simplified_formats/master05-rm_mapping.adoc`,
//! the sections `EVENT_CONTEXT`, the `ENTRY` classes, `LINK`, `FEEDER_AUDIT`
//! and `PARTICIPATION`). This module writes each family whole, as the typed
//! `openehr-rm` value in canonical JSON under `|raw` (master04 §Raw canonical
//! JSON), and reads the same attributes back out of the canonical JSON of the
//! node as typed `openehr-rm` values.

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;

/// The `feeder_system_item_ids` type every defaulted field is recorded under.
///
/// No specification governs the spelling: our own design.
pub const DEFAULTED: &str = "defaulted";

/// Why a family a node carries could not be read.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("the `{attribute}` of the node does not read as its reference-model class")]
pub struct FamilyError {
    /// The reference-model attribute that holds the family.
    pub attribute: &'static str,
    /// What the strict ITS-JSON reader refused, with its JSON path.
    #[source]
    pub source: JsonParseError,
}

/// Returns a segment with no instance index.
fn plain(name: &str) -> Segment {
    Segment {
        name: String::from(name),
        index: None,
    }
}

/// Returns a segment with the instance index `index`.
///
/// NOTE: no specification governs this: our own design, an index past `u32`
/// saturates, and the composition seam refuses it past the FLAT bound.
fn indexed(name: &str, index: usize) -> Segment {
    Segment {
        name: String::from(name),
        index: Some(u32::try_from(index).unwrap_or(u32::MAX)),
    }
}

/// Returns the `_feeder_audit` family of the composition root.
///
/// `originating_system_audit.system_id` names the originating system when the
/// origin names one apart and the bridge otherwise, `feeder_system_audit`
/// names the bridge and is present when the two differ or a field was
/// defaulted, the item ids the origin names, or else the source resource,
/// travel as `originating_system_item_ids`, with the source its `meta.versionId` as
/// `originating_system_audit.version_id`, and the origin's feeder item ids and
/// then each defaulted field travel as `feeder_system_item_ids`, a field's
/// `id` being its openEHR path, in `defaulted` order
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/common.html#_feeder_audit_class>).
/// The allocation of facts to attributes is our own design.
#[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),
    ]
}

/// Returns the `PARTY_IDENTIFIED` of `party`: its name and its identifiers.
#[must_use]
pub fn party_identified(party: &Party) -> PartyIdentified {
    PartyIdentified::PartyIdentified(PartyIdentifiedData {
        external_ref: None,
        name: party.name.clone(),
        identifiers: dv_identifiers(&party.identifiers),
    })
}

/// Returns `items` as the `DV_IDENTIFIER`s of a `PARTY_IDENTIFIED`.
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();
    // NOTE: RM Common IM, `PARTY_IDENTIFIED.identifiers` is optional; a party with none
    // legitimately has no list, which is the only failure of the constructor.
    openehr_base::containers::NonEmptyVec::new(identifiers).ok()
}

/// Returns the default composer at the `composer` node, whole: its name, the
/// `external_ref` `id` names and its `identifiers` (RM EHR IM,
/// `COMPOSITION.composer`; RM Common IM, `PARTY_IDENTIFIED`).
///
/// The reference is the one the Simplified Formats builder writes from
/// `ctx/composer_id`, `ctx/id_namespace` and `ctx/id_scheme`, typed `PERSON`
/// (master06 §Composer).
#[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)
}

/// Returns the `_health_care_facility` family of the `context` node naming
/// `facility` (RM EHR IM, `EVENT_CONTEXT.health_care_facility`).
#[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),
    ]
}

/// The FLAT family `EVENT_CONTEXT.health_care_facility` travels as.
pub const HEALTH_CARE_FACILITY: &str = "_health_care_facility";

/// Returns the `_link:i` family of one `LINK` on `node`.
///
/// `LINK.meaning` and `LINK.type` are `DV_TEXT` and `LINK.target` a
/// `DV_EHR_URI`, all three mandatory
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/common.html#_link_class>).
#[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),
    ]
}

/// A plain `DV_TEXT` carrying `value`.
fn plain_text(value: &str) -> DvText {
    DvText::DvText(DvTextData {
        value: String::from(value),
        hyperlink: None,
        formatting: None,
        mappings: None,
        language: None,
        encoding: None,
    })
}

/// The three attributes of one `LINK`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LinkParts<'text> {
    /// `LINK.meaning`.
    pub meaning: &'text str,
    /// `LINK.type`.
    pub link_type: &'text str,
    /// `LINK.target`, an `ehr:` URI.
    pub target: &'text str,
}

/// The attributes of one `PARTICIPATION` the engine writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParticipationParts<'text> {
    /// `PARTICIPATION.function`, a `DV_TEXT`.
    pub function: &'text str,
    /// The performer's `PARTY_IDENTIFIED.name`, when the reference has one.
    pub name: Option<&'text str>,
    /// The performer's `external_ref.id.value`.
    pub id: &'text str,
    /// The performer's `external_ref.id.scheme`.
    pub id_scheme: &'text str,
    /// The performer's `external_ref.namespace`.
    pub id_namespace: &'text str,
}

/// One list of `PARTICIPATION`s the reference model gives a class, with the
/// FLAT family it travels as.
///
/// `ENTRY.other_participations` and `EVENT_CONTEXT.participations` are the
/// same `List<PARTICIPATION>`
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/ehr.html#_entry_class>,
/// <https://specifications.openehr.org/releases/RM/Release-1.1.0/ehr.html#_event_context_class>),
/// spelled `_other_participation:i` and `_participation:i` (`master05-rm_mapping.adoc`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParticipationList {
    /// The owner class the list belongs to, or an ancestor of it.
    pub owner: &'static str,
    /// The reference-model attribute that holds the list.
    pub attribute: &'static str,
    /// The FLAT family one participation of it is written under.
    pub family: &'static str,
}

/// The participations of an `ENTRY`.
pub const ENTRY_PARTICIPATIONS: ParticipationList = ParticipationList {
    owner: "ENTRY",
    attribute: "other_participations",
    family: "_other_participation",
};

/// The participations of an `EVENT_CONTEXT`.
pub const CONTEXT_PARTICIPATIONS: ParticipationList = ParticipationList {
    owner: "EVENT_CONTEXT",
    attribute: "participations",
    family: "_participation",
};

/// Returns the participation list `tail` names below a node of `class`.
#[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))
}

/// Returns the family of one `PARTICIPATION` of `list` on `node`.
///
/// The performer is a `PARTY_IDENTIFIED` whose `external_ref` names a
/// `GENERIC_ID` of `PERSON`, the party type the master05 `PARTICIPATION`
/// spelling defaults to (Simplified Formats, the `PARTICIPATION` mapping
/// table).
#[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),
    ]
}

/// Returns the family of one `PARTY_IDENTIFIED` written under `family` on
/// `node`: the `_provider` of an `ENTRY`, the `_health_care_facility` of an
/// `EVENT_CONTEXT`.
///
/// The party travels whole, its name, identifiers and external reference.
#[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),
    ]
}

/// Returns the family of one `DV_DATE_TIME` written under `family` on
/// `node`, the `_end_time` of an `EVENT_CONTEXT`.
///
/// Simplified Formats writes the family as the date-time text itself, with
/// no attribute suffix (the `EVENT_CONTEXT` table, `/_end_time`).
#[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())
}

/// Returns the `_null_flavour` family of an `ELEMENT`, on the node the
/// element shares with its value, with `_null_reason` beside it.
///
/// Simplified Formats spells the flavour `|code`, `|value` and
/// `|terminology` under `_null_flavour` and the reason as the text of
/// `_null_reason` (`master05-rm_mapping.adoc`, §ELEMENT).
#[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
}

/// Returns the refusal of a present list `attribute` that does not decode.
///
/// Both lists are optional in the reference model (`LOCATABLE.links`,
/// `ENTRY.other_participations` and `EVENT_CONTEXT.participations` are
/// `0..1`), so an absent attribute reads as no entries; a present one that
/// does not decode is a defect of the document and a refusal.
const fn undecodable(attribute: &'static str) -> impl Fn(JsonParseError) -> FamilyError {
    move |source| FamilyError { attribute, source }
}

/// Returns the text a `DV_TEXT` or `DV_CODED_TEXT` carries.
fn text_of(text: &DvText) -> &str {
    match *text {
        DvText::DvCodedText(ref coded) => &coded.value,
        DvText::DvText(ref plain) => &plain.value,
    }
}

/// Returns the `LINK.target` values of the links a node carries with one
/// meaning and one type, in order.
///
/// `value` is the canonical JSON of the node, whose `links` is the
/// `LOCATABLE` attribute; the meaning and the type are what tell one `link`
/// mapping's links from another's.
///
/// # Errors
///
/// Returns [`FamilyError`] when the node's `links` do not decode as `LINK`s.
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())
}

/// One `PARTICIPATION` read back out of an `ENTRY`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Participation {
    /// The performer's `external_ref.id.value`, when it carries one.
    pub id: Option<String>,
    /// The performer's name, when it carries one.
    pub name: Option<String>,
    /// The demographic identity the performer's `external_ref` carries, when
    /// it carries one ([`crate::engine::demographics`]).
    pub identity: Option<PartyIdentity>,
}

/// Returns the value of an object id, whichever subtype it is.
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(),
    }
}

/// Returns the participations of `list` whose function is `function`.
///
/// `value` is the canonical JSON of the node that holds the list
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/common.html#_participation_class>).
///
/// # Errors
///
/// Returns [`FamilyError`] when the list does not decode as `PARTICIPATION`s.
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())
}