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
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! `DV_CODED_TEXT` against FHIR `CodeableConcept` and `Coding`.
//!
//! The cell is
//! `docs/specs/fhirconnect/modules/ROOT/pages/types-of-mappings/data-type/DV_CODED_TEXT.adoc`.
//! Its `CodeableConcept` table puts one `coding` into `defining_code` and
//! every further one into `mappings`, pairs `coding.display` with
//! `defining_code/preferred_term` and `text` with `value`, and gives `value`
//! two fallbacks marked "not for openEHR->FHIR".
//!
//! Which coding becomes the defining one is the page's own rule: the engine
//! takes the coding whose system matches the terminology the openEHR element
//! is bound to, "if yes, this one should be transformed into the `defining_code`
//! instead of the first one", and otherwise the first.

use fhir_types::r4::codeable_concept::CodeableConcept;
use fhir_types::r4::coding::Coding;
use fhir_types::r4::primitives;
use openehr_base::containers::NonEmptyVec;
use openehr_rm::v1_2::data_types::text::code_phrase::CodePhrase;
use openehr_rm::v1_2::data_types::text::dv_coded_text::DvCodedText;

use crate::engine::lens::Fallback;
use crate::engine::lens::Lens;
use crate::engine::lens::LensError;
use crate::engine::lens::code_phrase::CodePhraseLens;
use crate::engine::lens::code_phrase::text_of;
use crate::engine::lens::term_mapping::Withheld;
use crate::engine::lens::term_mapping::coding_of;
use crate::engine::lens::term_mapping::equivalents;
use crate::engine::lens::term_mapping::mappings_of;
use crate::engine::lens::term_mapping::uncarried;
use crate::engine::lens::term_mapping::withheld;
use crate::model::ast::keyword::Direction;

/// The name the `CodeableConcept` cell carries in a diagnostic.
pub const CODEABLE_CONCEPT_CELL: &str = "DV_CODED_TEXT against CodeableConcept";

/// The name the `Coding` cell carries in a diagnostic.
pub const CODING_CELL: &str = "DV_CODED_TEXT against Coding";

/// `DV_CODED_TEXT` against `CodeableConcept` and against `Coding`.
///
/// The lens carries the terminology the openEHR element is bound to, when the
/// Web Template node declares one, because that is what decides which coding
/// of a `CodeableConcept` becomes the `defining_code`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CodedTextLens {
    binding: Option<String>,
}

impl CodedTextLens {
    /// Creates a lens for an element the template binds to no terminology.
    #[must_use]
    pub const fn unbound() -> Self {
        Self { binding: None }
    }

    /// Creates a lens for an element bound to the terminology `system`.
    #[must_use]
    pub fn bound(system: impl Into<String>) -> Self {
        Self {
            binding: Some(system.into()),
        }
    }

    /// Returns the terminology the element is bound to.
    #[must_use]
    pub fn binding(&self) -> Option<&str> {
        self.binding.as_deref()
    }

    /// Returns the position of the coding that becomes the `defining_code`.
    ///
    /// The bound system wins when the list carries it, and the first coding
    /// otherwise.
    fn defining(&self, codings: &[Coding]) -> Option<usize> {
        let bound = self.binding.as_deref().and_then(|system| {
            codings.iter().position(|coding| {
                text_of(coding.system.as_ref().map(|uri| &uri.value)) == Some(system)
            })
        });
        bound.or_else(|| codings.first().map(|_first| 0))
    }
}

impl Lens<DvCodedText, CodeableConcept> for CodedTextLens {
    fn cell(&self) -> &'static str {
        CODEABLE_CONCEPT_CELL
    }

    fn get(&self, source: &DvCodedText) -> Result<CodeableConcept, LensError> {
        let mut defining = CodePhraseLens.get(&source.defining_code)?;
        defining.display = source
            .defining_code
            .preferred_term
            .clone()
            .map(primitives::String::from);
        let mut codings = vec![defining];
        for mapping in equivalents(source.mappings.iter().flatten()) {
            codings.push(coding_of(mapping, CODEABLE_CONCEPT_CELL)?);
        }
        Ok(CodeableConcept {
            coding: codings,
            text: Some(primitives::String::from(source.value.clone())),
            ..CodeableConcept::default()
        })
    }

    fn put(
        &self,
        view: &CodeableConcept,
        existing: Option<&DvCodedText>,
    ) -> Result<DvCodedText, LensError> {
        let absent = || LensError::Missing {
            cell: CODEABLE_CONCEPT_CELL,
            attribute: "DV_CODED_TEXT.defining_code",
            direction: Direction::FhirToOpenehr,
        };
        let position = self.defining(&view.coding).ok_or_else(absent)?;
        let defining = view.coding.get(position).ok_or_else(absent)?;
        let held = existing.and_then(|value| value.mappings.as_deref());
        let mappings = mappings_of(
            view.coding
                .iter()
                .enumerate()
                .filter(|&(index, _coding)| index != position)
                .map(|(_index, coding)| coding),
            held,
        )?;
        let value = value_of(
            text_of(view.text.as_ref().map(|text| &text.value)),
            defining,
            CODEABLE_CONCEPT_CELL,
        )?;
        Ok(DvCodedText {
            value: String::from(value),
            hyperlink: existing.and_then(|held| held.hyperlink.clone()),
            formatting: existing.and_then(|held| held.formatting.clone()),
            mappings: NonEmptyVec::new(mappings).ok(),
            language: existing.and_then(|held| held.language.clone()),
            encoding: existing.and_then(|held| held.encoding.clone()),
            defining_code: CodePhraseLens.put(defining, None)?,
        })
    }

    fn fallbacks(&self, view: &CodeableConcept) -> Vec<Fallback> {
        if text_of(view.text.as_ref().map(|text| &text.value)).is_some() {
            return Vec::new();
        }
        vec![Fallback::new(CODEABLE_CONCEPT_CELL, "DV_TEXT.value")]
    }

    fn withheld(&self, source: &DvCodedText) -> Vec<Withheld> {
        withheld(source.mappings.iter().flatten())
    }
}

impl Lens<DvCodedText, Coding> for CodedTextLens {
    fn cell(&self) -> &'static str {
        CODING_CELL
    }

    fn get(&self, source: &DvCodedText) -> Result<Coding, LensError> {
        let mut coding = CodePhraseLens.get(&source.defining_code)?;
        // NOTE: DV_CODED_TEXT.adoc §Coding pairs `display` with `value`, so in
        // this cell the rubric travels and `preferred_term` has no counterpart.
        coding.display = Some(primitives::String::from(source.value.clone()));
        Ok(coding)
    }

    fn put(&self, view: &Coding, existing: Option<&DvCodedText>) -> Result<DvCodedText, LensError> {
        let defining = CodePhraseLens.put(view, None)?;
        let value = match text_of(view.display.as_ref().map(|display| &display.value)) {
            Some(display) => String::from(display),
            None => defining.code_string.clone(),
        };
        Ok(DvCodedText {
            value,
            hyperlink: existing.and_then(|held| held.hyperlink.clone()),
            formatting: existing.and_then(|held| held.formatting.clone()),
            mappings: existing.and_then(|held| held.mappings.clone()),
            language: existing.and_then(|held| held.language.clone()),
            encoding: existing.and_then(|held| held.encoding.clone()),
            defining_code: CodePhrase {
                preferred_term: existing.and_then(|held| held.defining_code.preferred_term.clone()),
                ..defining
            },
        })
    }

    fn fallbacks(&self, view: &Coding) -> Vec<Fallback> {
        if text_of(view.display.as_ref().map(|display| &display.value)).is_some() {
            return Vec::new();
        }
        vec![Fallback::new(CODING_CELL, "DV_TEXT.value")]
    }

    // NOTE: DV_CODED_TEXT.adoc §Coding gives `mappings` no FHIRpath row, so a
    // single Coding carries none of them and each is a declared loss.
    fn withheld(&self, source: &DvCodedText) -> Vec<Withheld> {
        uncarried(source.mappings.iter().flatten())
    }
}

/// Returns the rubric a `DV_CODED_TEXT` carries, taking the page's fallbacks.
///
/// `value` is `1..1` in the reference model, so when FHIR carries no `text`
/// the table takes `coding.display` and then `coding.code`. Both rows are
/// marked "not for openEHR->FHIR", so each is recorded as a fallback.
fn value_of<'view>(
    text: Option<&'view str>,
    defining: &'view Coding,
    cell: &'static str,
) -> Result<&'view str, LensError> {
    text.or_else(|| text_of(defining.display.as_ref().map(|display| &display.value)))
        .or_else(|| text_of(defining.code.as_ref().map(|code| &code.value)))
        .ok_or(LensError::Missing {
            cell,
            attribute: "DV_TEXT.value",
            direction: Direction::FhirToOpenehr,
        })
}

#[cfg(test)]
pub(crate) mod tests {
    use super::CODEABLE_CONCEPT_CELL;
    use super::CodedTextLens;
    use crate::engine::lens::Fallback;
    use crate::engine::lens::Lens;
    use crate::engine::lens::code_phrase::tests::code_phrase;
    use crate::engine::lens::code_phrase::tests::coding;
    use fhir_types::r4::codeable_concept::CodeableConcept;
    use fhir_types::r4::coding::Coding;
    use fhir_types::r4::primitives;
    use fhir_types::r4::primitives::Code;
    use fhir_types::r4::primitives::Uri;
    use openehr_base::containers::NonEmptyVec;
    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::term_mapping::TermMapping;
    use proptest::collection::vec;
    use proptest::prop_compose;
    use proptest::proptest;

    prop_compose! {
        /// A `DV_CODED_TEXT` inside the subset the two cells carry losslessly.
        pub(crate) fn coded_text()(
            value in "[A-Za-z ]{1,12}",
            defining in code_phrase(),
            targets in vec(code_phrase(), 0..3),
        ) -> DvCodedText {
            DvCodedText {
                value,
                hyperlink: None,
                formatting: None,
                mappings: NonEmptyVec::new(
                    targets
                        .into_iter()
                        .map(|target| TermMapping { r#match: '=', purpose: None, target })
                        .collect::<Vec<TermMapping>>(),
                )
                .ok(),
                language: None,
                encoding: None,
                defining_code: defining,
            }
        }
    }

    prop_compose! {
        /// A `Coding` that carries a display.
        ///
        /// The `Coding` cell fills the mandatory `value` from `display`, and
        /// falls back to `code` when there is none. The fallback is one-way,
        /// so the law is stated over the codings that carry a display.
        fn displayed_coding()(
            system in "[a-z]{1,8}://[a-z.]{1,12}",
            version in proptest::option::of("[0-9]{4}"),
            code in "[A-Za-z0-9-]{1,10}",
            display in "[A-Za-z ]{1,12}",
        ) -> Coding {
            Coding {
                system: Some(Uri::from(system)),
                version: version.map(primitives::String::from),
                code: Some(Code::from(code)),
                display: Some(primitives::String::from(display)),
                ..Coding::default()
            }
        }
    }

    prop_compose! {
        /// A `CodeableConcept` inside the subset the cell carries losslessly.
        pub(crate) fn codeable_concept()(
            codings in vec(coding(), 1..4),
            text in "[A-Za-z ]{1,12}",
        ) -> CodeableConcept {
            CodeableConcept {
                coding: codings,
                text: Some(primitives::String::from(text)),
                ..CodeableConcept::default()
            }
        }
    }

    proptest! {
        #[test]
        fn codeable_concept_get_put(source in coded_text()) {
            let lens = CodedTextLens::unbound();
            let view: CodeableConcept = lens.get(&source).expect("the generated subset is carried");
            let back = lens.put(&view, Some(&source)).expect("the view is complete");
            assert_eq!(back, source, "GetPut failed for {source:?}");
        }

        #[test]
        fn codeable_concept_put_get(view in codeable_concept()) {
            let lens = CodedTextLens::unbound();
            let source: DvCodedText = lens.put(&view, None).expect("the generated subset is carried");
            let back: CodeableConcept = lens.get(&source).expect("the value is complete");
            assert_eq!(back, view, "PutGet failed for {view:?}");
        }

        #[test]
        fn coding_get_put(source in coded_text()) {
            let lens = CodedTextLens::unbound();
            let view: Coding = lens.get(&source).expect("the generated subset is carried");
            let back = lens.put(&view, Some(&source)).expect("the view is complete");
            assert_eq!(back, source, "GetPut failed for {source:?}");
        }

        #[test]
        fn coding_put_get(view in displayed_coding()) {
            let lens = CodedTextLens::unbound();
            let source: DvCodedText = lens.put(&view, None).expect("the generated subset is carried");
            let back: Coding = lens.get(&source).expect("the value is complete");
            assert_eq!(back, view, "PutGet failed for {view:?}");
        }
    }

    /// A coding of `system` carrying `code`.
    fn code_of(system: &str, code: &str) -> Coding {
        Coding {
            system: Some(Uri::from(system)),
            code: Some(Code::from(code)),
            ..Coding::default()
        }
    }

    #[test]
    fn the_bound_terminology_becomes_the_defining_code() {
        let view = CodeableConcept {
            coding: vec![
                code_of("http://loinc.org", "LP74849-8"),
                code_of("http://snomed.info/sct", "386661006"),
            ],
            text: Some(primitives::String::from("Fever")),
            ..CodeableConcept::default()
        };
        let lens = CodedTextLens::bound("http://snomed.info/sct");
        let source: DvCodedText = lens.put(&view, None).expect("two complete codings");
        assert_eq!(
            source.defining_code.code_string, "386661006",
            "the coding of the bound terminology is the defining code"
        );
        assert_eq!(
            source
                .mappings
                .as_deref()
                .and_then(<[TermMapping]>::first)
                .map(|mapping| mapping.target.code_string.clone()),
            Some(String::from("LP74849-8")),
            "every further coding becomes a term mapping"
        );
    }

    #[test]
    fn the_first_coding_wins_when_no_binding_matches() {
        let view = CodeableConcept {
            coding: vec![
                code_of("http://loinc.org", "LP74849-8"),
                code_of("http://snomed.info/sct", "386661006"),
            ],
            text: Some(primitives::String::from("Fever")),
            ..CodeableConcept::default()
        };
        let lens = CodedTextLens::bound("http://example.org/other");
        let source: DvCodedText = lens.put(&view, None).expect("two complete codings");
        assert_eq!(
            source.defining_code.code_string, "LP74849-8",
            "the first coding is the defining code when the binding is absent"
        );
    }

    #[test]
    fn an_absent_text_falls_back_to_the_display_and_is_recorded() {
        let view = CodeableConcept {
            coding: vec![Coding {
                display: Some(primitives::String::from("Fever")),
                ..code_of("http://loinc.org", "LP74849-8")
            }],
            ..CodeableConcept::default()
        };
        let lens = CodedTextLens::unbound();
        let source: DvCodedText = lens.put(&view, None).expect("one complete coding");
        assert_eq!(
            source.value, "Fever",
            "the display fills the mandatory value"
        );
        assert_eq!(
            Lens::<DvCodedText, CodeableConcept>::fallbacks(&lens, &view),
            vec![Fallback::new(CODEABLE_CONCEPT_CELL, "DV_TEXT.value")],
            "the one-way row is recorded"
        );
    }

    #[test]
    fn an_absent_text_and_display_falls_back_to_the_code() {
        let view = CodeableConcept {
            coding: vec![code_of("http://loinc.org", "LP74849-8")],
            ..CodeableConcept::default()
        };
        let source: DvCodedText = CodedTextLens::unbound()
            .put(&view, None)
            .expect("one complete coding");
        assert_eq!(
            source.value, "LP74849-8",
            "the code fills the mandatory value when the display is absent"
        );
    }

    #[test]
    fn a_concept_with_no_coding_is_refused() {
        let view = CodeableConcept {
            text: Some(primitives::String::from("Fever")),
            ..CodeableConcept::default()
        };
        let error = <CodedTextLens as Lens<DvCodedText, CodeableConcept>>::put(
            &CodedTextLens::unbound(),
            &view,
            None,
        )
        .expect_err("defining_code is mandatory");
        assert!(
            error.to_string().contains("defining_code"),
            "the refusal names the mandatory attribute: {error}"
        );
    }

    /// A `DV_CODED_TEXT` whose mappings are an `=` one and one with `relation`.
    fn with_relation(relation: char) -> DvCodedText {
        let target = |system: &str, code: &str| CodePhrase {
            terminology_id: TerminologyId::new(system, ""),
            code_string: String::from(code),
            preferred_term: None,
        };
        DvCodedText {
            value: String::from("Fever"),
            hyperlink: None,
            formatting: None,
            mappings: NonEmptyVec::new(vec![
                TermMapping {
                    r#match: relation,
                    purpose: None,
                    target: target("http://snomed.info/sct", "386661006"),
                },
                TermMapping {
                    r#match: '=',
                    purpose: None,
                    target: target("http://hl7.org/fhir/sid/icd-10", "R50.9"),
                },
            ])
            .ok(),
            language: None,
            encoding: None,
            defining_code: target("http://loinc.org", "LP74849-8"),
        }
    }

    // TERM_MAPPING.adoc: `match` is "hard coded to `=`, other operators not mappable
    // to FHIR", so the mapping writes no coding and the rest of the value converts.
    #[test]
    fn a_term_mapping_fhir_cannot_carry_is_withheld_and_the_rest_converts() {
        let lens = CodedTextLens::unbound();
        for relation in ['>', '<', '?'] {
            let source = with_relation(relation);
            let view: CodeableConcept = lens.get(&source).expect("the mapping is withheld");
            let codes: Vec<Option<&str>> = view
                .coding
                .iter()
                .map(|coding| coding.code.as_ref().and_then(|code| code.value.as_deref()))
                .collect();
            assert_eq!(
                codes,
                [Some("LP74849-8"), Some("R50.9")],
                "the defining code and the `=` mapping travel past `{relation}`"
            );
            let taken = Lens::<DvCodedText, CodeableConcept>::withheld(&lens, &source);
            let rows: Vec<(char, &str, &str)> = taken
                .iter()
                .map(|term| (term.match_code(), term.terminology(), term.code()))
                .collect();
            assert_eq!(
                rows,
                [(relation, "http://snomed.info/sct", "386661006")],
                "the withheld term names its operator and target"
            );
        }
    }

    #[test]
    fn a_withheld_term_mapping_returns_from_the_held_value() {
        let lens = CodedTextLens::unbound();
        for relation in ['>', '<', '?'] {
            let source = with_relation(relation);
            let view: CodeableConcept = lens.get(&source).expect("the mapping is withheld");
            let back = lens
                .put(&view, Some(&source))
                .expect("the view is complete");
            assert_eq!(back, source, "GetPut holds past `{relation}`");
        }
    }

    #[test]
    fn an_equivalent_term_mapping_is_withheld_from_nothing() {
        let source = with_relation('=');
        let lens = CodedTextLens::unbound();
        let view: CodeableConcept = lens.get(&source).expect("both mappings travel");
        assert_eq!(view.coding.len(), 3, "the defining code and both mappings");
        assert!(
            Lens::<DvCodedText, CodeableConcept>::withheld(&lens, &source).is_empty(),
            "`=` is carried"
        );
    }
}