SGHI FHIR Profile Implementation Guide
0.1.0 - ci-build

SGHI FHIR Profile Implementation Guide, published by Kathurima Kimathi. This guide is not an authorized publication; it is the continuous build for version 0.1.0 built by the FHIR (HL7® FHIR® Standard) CI Build. This version is based on the current content of https://github.com/savannahghi/sil_fhir_profile_ig/ and changes regularly. See the Directory of published versions

StructureMap: Newborn Admission Record Extraction

Official URL: https://fhir.slade360.co.ke/fhir/StructureMap/ExtractNewbornAdmissionRecord Version: 0.1.0
Active as of 2026-09-14 Computable Name: ExtractNewbornAdmissionRecord

The newborn unit's admission record out as: the birth and current measurements each as their own Observation, so a weight chart can graph them from the first day; the intranatal and newborn history as one panel; the newborn examination as a second panel with its graded findings coded and its rates as quantities; the Apgar carried over from the delivery record as two Observations under the LOINC score codes; a Condition per admission diagnosis; a CarePlan for the supportive care planned; and a Consent from the parent's signature.

/// url = 'https://fhir.slade360.co.ke/fhir/StructureMap/ExtractNewbornAdmissionRecord'
/// name = 'ExtractNewbornAdmissionRecord'
/// title = 'Newborn Admission Record Extraction'
/// status = 'active'
/// description = 'The newborn unit\'s admission record out as: the birth and current measurements each as their own Observation, so a weight chart can graph them from the first day; the intranatal and newborn history as one panel; the newborn examination as a second panel with its graded findings coded and its rates as quantities; the Apgar carried over from the delivery record as two Observations under the LOINC score codes; a Condition per admission diagnosis; a CarePlan for the supportive care planned; and a Consent from the parent\'s signature.'

uses "http://hl7.org/fhir/StructureDefinition/QuestionnaireResponse" alias QR as source
uses "http://hl7.org/fhir/StructureDefinition/Bundle" alias Bundle as target
uses "http://hl7.org/fhir/StructureDefinition/Observation" alias Observation as target
uses "http://hl7.org/fhir/StructureDefinition/Condition" alias Condition as target
uses "http://hl7.org/fhir/StructureDefinition/CarePlan" alias CarePlan as target
uses "http://hl7.org/fhir/StructureDefinition/Consent" alias Consent as target

group ExtractNewbornAdmissionRecord(source qr : QR, target bundle : Bundle) {
  qr -> bundle.type = 'transaction' "setBundleType";
  // ── The measurements ────────────────────────────────────────────────────
  // Birth weight and weight now are both LOINC-coded and both extracted: they
  // are different facts, and the difference between them on day three is what
  // tells physiological weight loss from failure to feed.
  qr.item as g where (linkId = 'bio') then {
    g.item as it where ((linkId = 'bio/birth-weight') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetVitalSignsCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '8339-4' "cd";
          it -> cg.display = 'Birth weight Measured' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_8339_4";
    g.item as it where ((linkId = 'bio/weight-now') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetVitalSignsCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '29463-7' "cd";
          it -> cg.display = 'Body weight' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_29463_7";
    g.item as it where ((linkId = 'bio/gestation') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetVitalSignsCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '11884-4' "cd";
          it -> cg.display = 'Gestational age Estimated' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_11884_4";
    g.item as it where ((linkId = 'bio/temperature') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetVitalSignsCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '8310-5' "cd";
          it -> cg.display = 'Body temperature' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_8310_5";
    g.item as it where ((linkId = 'bio/mode-of-delivery') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetSurveyCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'cord-mode-of-delivery' "cd";
          it -> cg.display = 'Mode of delivery' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as cv -> obs.value = create('CodeableConcept') as cc then {
          cv -> cc.coding = cv "valueCoding";
          cv.display as d -> cc.text = d "valueText";
        } "codedValue";
      };
    } "coded_cord_condition";
    g.item as it where ((linkId = 'bio/place-of-birth') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetSurveyCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'cord-place-of-birth' "cd";
          it -> cg.display = 'Place of birth' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as cv -> obs.value = create('CodeableConcept') as cc then {
          cv -> cc.coding = cv "valueCoding";
          cv.display as d -> cc.text = d "valueText";
        } "codedValue";
      };
    } "coded_cord_condition2";
  } "bioGroup";
  // ── Apgar carried over from the delivery record ─────────────────────────
  // Two Observations under the LOINC score codes, not components of anything.
  // A five-minute Apgar is the single most-quoted number about a newborn and it
  // has to be findable by its own code.
  // No component breakdown here: this sheet copies the totals off the delivery
  // record and does not ask for the five signs. The breakdown lives on the
  // newborn observation chart, where it is actually assessed.
  qr.item as g where (linkId = 'apgar-at-birth') then {
    g.item as it where ((linkId = 'apgar-at-birth/one-minute') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetSurveyCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '9272-6' "cd";
          it -> cg.display = '1 minute Apgar Score' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_9272_6";
    g.item as it where ((linkId = 'apgar-at-birth/five-minutes') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetSurveyCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '9274-2' "cd";
          it -> cg.display = '5 minute Apgar Score' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_9274_2";
  } "apgarGroup";
  // ── The history, as one panel ───────────────────────────────────────────
  qr.item as g where ((linkId = 'history') and item.answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
    qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
    qr -> obs then SetSurveyCategory(qr, obs) "category";
    g -> obs.code as cc then {
      g -> cc.coding as cg then {
        g -> cg.system = 'http://loinc.org' "sys";
        g -> cg.code = '10164-2' "cd";
        g -> cg.display = 'History of Present illness Narrative' "dsp";
      } "coding";
      g -> cc.text = 'Newborn history on admission' "codeText";
    } "code";
    g.item as it where ((linkId = 'history/prolonged-rom') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-prolonged-rupture-of-membranes-over-24-hours' "cd";
          it -> cg.display = 'Prolonged rupture of membranes over 24 hours' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_sign_prolonged_rupture_of_membranes_over_24_hours";
    g.item as it where ((linkId = 'history/fever') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-fever' "cd";
          it -> cg.display = 'Fever' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_sign_fever";
    g.item as it where ((linkId = 'history/difficulty-breathing') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-difficulty-breathing' "cd";
          it -> cg.display = 'Difficulty breathing' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_sign_difficulty_breathing";
    g.item as it where ((linkId = 'history/apnoeas') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-apnoeas' "cd";
          it -> cg.display = 'Apnoeas' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_sign_apnoeas";
    g.item as it where ((linkId = 'history/diarrhoea') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-diarrhoea' "cd";
          it -> cg.display = 'Diarrhoea' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_sign_diarrhoea";
    g.item as it where ((linkId = 'history/convulsions') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-convulsions' "cd";
          it -> cg.display = 'Convulsions' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_sign_convulsions";
    g.item as it where ((linkId = 'history/partial-focal-fits') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-partial-or-focal-fits' "cd";
          it -> cg.display = 'Partial or focal fits' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_sign_partial_or_focal_fits";
    g.item as it where ((linkId = 'history/high-pitched-cry') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-high-pitched-cry' "cd";
          it -> cg.display = 'High pitched cry' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_sign_high_pitched_cry";
    g.item as it where ((linkId = 'history/difficulty-feeding') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-difficulty-feeding' "cd";
          it -> cg.display = 'Difficulty feeding' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_sign_difficulty_feeding";
    g.item as it where ((linkId = 'history/severe-vomiting') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-severe-vomiting' "cd";
          it -> cg.display = 'Severe vomiting' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_sign_severe_vomiting";
    g.item as it where ((linkId = 'history/length-of-illness') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-length-of-illness-in-days' "cd";
          it -> cg.display = 'Length of illness in days' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_sign_length_of_illness_in_days";
    g.item as it where ((linkId = 'history/maternal-hiv-status') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'maternal-hiv-status' "cd";
          it -> cg.display = 'Maternal HIV status' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_maternal_hiv_status";
    g.item as it where (linkId = 'history/maternal-and-infant-drugs') then {
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "note";
  } "panel_10164_2";
  // ── The newborn examination, as one panel ───────────────────────────────
  qr.item as g where ((linkId = 'examination') and item.item.answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
    qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
    qr -> obs then SetExamCategory(qr, obs) "category";
    g -> obs.code as cc then {
      g -> cc.coding as cg then {
        g -> cg.system = 'http://loinc.org' "sys";
        g -> cg.code = '8716-3' "cd";
        g -> cg.display = 'Vital signs note' "dsp";
      } "coding";
      g -> cc.text = 'Newborn examination on admission' "codeText";
    } "code";
    g.item as g2 where (linkId = 'examination/breathing') then {
      g2.item as it where ((linkId = 'examination/breathing/central-cyanosis') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'sign-central-cyanosis' "cd";
            it -> cg.display = 'Central cyanosis' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_sign_central_cyanosis";
      g2.item as it where ((linkId = 'examination/breathing/severe-indrawing') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'sign-severe-indrawing' "cd";
            it -> cg.display = 'Severe indrawing' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_sign_severe_indrawing";
      g2.item as it where ((linkId = 'examination/breathing/grunting') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'sign-grunting' "cd";
            it -> cg.display = 'Grunting' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_sign_grunting";
      g2.item as it where ((linkId = 'examination/breathing/crackles') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'sign-crackles' "cd";
            it -> cg.display = 'Crackles' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_sign_crackles";
      g2.item as it where ((linkId = 'examination/breathing/respiratory-rate') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'http://loinc.org' "sys";
            it -> cg.code = '9279-1' "cd";
            it -> cg.display = 'Respiratory rate' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_9279_1";
    } "examSub";
    g.item as g2 where (linkId = 'examination/circulation') then {
      g2.item as it where ((linkId = 'examination/circulation/heart-rate') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'http://loinc.org' "sys";
            it -> cg.code = '8867-4' "cd";
            it -> cg.display = 'Heart rate' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_8867_4";
      g2.item as it where ((linkId = 'examination/circulation/capillary-refill') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'sign-capillary-refill-band' "cd";
            it -> cg.display = 'Capillary refill band' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_sign_capillary_refill_band";
      g2.item as it where ((linkId = 'examination/circulation/pallor') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'grade-pallor-or-anaemia-grade' "cd";
            it -> cg.display = 'Pallor or anaemia grade' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_grade_pallor_or_anaemia_grade";
    } "examSub2";
    g.item as g2 where (linkId = 'examination/dehydration') then {
      g2.item as it where ((linkId = 'examination/dehydration/skin-pinch') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'skin-pinch-time' "cd";
            it -> cg.display = 'Skin pinch return time' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_skin_pinch_time";
    } "examSub3";
    g.item as g2 where (linkId = 'examination/disability') then {
      g2.item as it where ((linkId = 'examination/disability/floppy-or-unable-to-suck') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'sign-floppy-or-unable-to-suck' "cd";
            it -> cg.display = 'Floppy, or unable to suck' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_sign_floppy_or_unable_to_suck";
      g2.item as it where ((linkId = 'examination/disability/bulging-fontanelle') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'sign-bulging-fontanelle' "cd";
            it -> cg.display = 'Bulging fontanelle' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_sign_bulging_fontanelle";
    } "examSub4";
    g.item as g2 where (linkId = 'examination/general') then {
      g2.item as it where ((linkId = 'examination/general/jaundice') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'grade-jaundice-grade' "cd";
            it -> cg.display = 'Jaundice grade' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_grade_jaundice_grade";
      g2.item as it where ((linkId = 'examination/general/abdominal-distension') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'sign-abdominal-distension' "cd";
            it -> cg.display = 'Abdominal distension' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_sign_abdominal_distension";
      g2.item as it where ((linkId = 'examination/general/umbilicus') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'umbilicus-appearance' "cd";
            it -> cg.display = 'Umbilical stump appearance' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_umbilicus_appearance";
      g2.item as it where ((linkId = 'examination/general/severe-skin-pustules') and answer.value.exists()) -> obs.component as comp then {
        it -> comp.code as cc then {
          it -> cc.coding as cg then {
            it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
            it -> cg.code = 'sign-severe-skin-pustules' "cd";
            it -> cg.display = 'Severe skin pustules' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_sign_severe_skin_pustules";
    } "examSub5";
    g.item as it where (linkId = 'examination/other') then {
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "note2";
  } "examinationPanel";
  // ── Admission diagnoses ─────────────────────────────────────────────────
  // The sheet prints eight named diagnoses as tick boxes plus two free-text
  // lines. A ticked box becomes a Condition; the tick's own display is the
  // diagnosis name, which is why the label travels in the rule rather than
  // being read off the answer.
  qr.item as g where (linkId = 'admission-diagnoses') then {
    g.item as it where ((linkId = 'admission-diagnoses/birth-asphyxia') and (answer.value.ofType(Coding).code = 'Y')) ->  bundle.entry as entry,  entry.resource = create('Condition') as cond then {
      qr ->  cond,  entry then BuildConditionBase(qr, cond, entry) "base";
      it -> cond.clinicalStatus as cs then {
        it -> cs.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "sys";
          it -> cg.code = 'active' "cd";
          it -> cg.display = 'Active' "dsp";
        } "coding";
      } "clinicalStatus";
      it -> cond.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-category' "sys";
          it -> cg.code = 'encounter-diagnosis' "cd";
          it -> cg.display = 'Encounter Diagnosis' "dsp";
        } "coding";
      } "category";
      it ->  cond.code as cc,  cc.text = 'Birth asphyxia' "codeText";
      qr.authored as t -> cond.recordedDate = t "recordedDate";
      qr.encounter as e -> cond.encounter = e;
    } "dx_birth_asphyxia";
    g.item as it where ((linkId = 'admission-diagnoses/meconium-aspiration') and (answer.value.ofType(Coding).code = 'Y')) ->  bundle.entry as entry,  entry.resource = create('Condition') as cond then {
      qr ->  cond,  entry then BuildConditionBase(qr, cond, entry) "base";
      it -> cond.clinicalStatus as cs then {
        it -> cs.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "sys";
          it -> cg.code = 'active' "cd";
          it -> cg.display = 'Active' "dsp";
        } "coding";
      } "clinicalStatus";
      it -> cond.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-category' "sys";
          it -> cg.code = 'encounter-diagnosis' "cd";
          it -> cg.display = 'Encounter Diagnosis' "dsp";
        } "coding";
      } "category";
      it ->  cond.code as cc,  cc.text = 'Meconium aspiration' "codeText";
      qr.authored as t -> cond.recordedDate = t "recordedDate";
      qr.encounter as e -> cond.encounter = e;
    } "dx_meconium_aspiration";
    g.item as it where ((linkId = 'admission-diagnoses/premature-or-lbw') and (answer.value.ofType(Coding).code = 'Y')) ->  bundle.entry as entry,  entry.resource = create('Condition') as cond then {
      qr ->  cond,  entry then BuildConditionBase(qr, cond, entry) "base";
      it -> cond.clinicalStatus as cs then {
        it -> cs.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "sys";
          it -> cg.code = 'active' "cd";
          it -> cg.display = 'Active' "dsp";
        } "coding";
      } "clinicalStatus";
      it -> cond.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-category' "sys";
          it -> cg.code = 'encounter-diagnosis' "cd";
          it -> cg.display = 'Encounter Diagnosis' "dsp";
        } "coding";
      } "category";
      it ->  cond.code as cc,  cc.text = 'Premature or low birth weight' "codeText";
      qr.authored as t -> cond.recordedDate = t "recordedDate";
      qr.encounter as e -> cond.encounter = e;
    } "dx_premature_or_lbw";
    g.item as it where ((linkId = 'admission-diagnoses/twin-delivery') and (answer.value.ofType(Coding).code = 'Y')) ->  bundle.entry as entry,  entry.resource = create('Condition') as cond then {
      qr ->  cond,  entry then BuildConditionBase(qr, cond, entry) "base";
      it -> cond.clinicalStatus as cs then {
        it -> cs.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "sys";
          it -> cg.code = 'active' "cd";
          it -> cg.display = 'Active' "dsp";
        } "coding";
      } "clinicalStatus";
      it -> cond.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-category' "sys";
          it -> cg.code = 'encounter-diagnosis' "cd";
          it -> cg.display = 'Encounter Diagnosis' "dsp";
        } "coding";
      } "category";
      it ->  cond.code as cc,  cc.text = 'Twin delivery' "codeText";
      qr.authored as t -> cond.recordedDate = t "recordedDate";
      qr.encounter as e -> cond.encounter = e;
    } "dx_twin_delivery";
    g.item as it where ((linkId = 'admission-diagnoses/newborn-rds') and (answer.value.ofType(Coding).code = 'Y')) ->  bundle.entry as entry,  entry.resource = create('Condition') as cond then {
      qr ->  cond,  entry then BuildConditionBase(qr, cond, entry) "base";
      it -> cond.clinicalStatus as cs then {
        it -> cs.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "sys";
          it -> cg.code = 'active' "cd";
          it -> cg.display = 'Active' "dsp";
        } "coding";
      } "clinicalStatus";
      it -> cond.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-category' "sys";
          it -> cg.code = 'encounter-diagnosis' "cd";
          it -> cg.display = 'Encounter Diagnosis' "dsp";
        } "coding";
      } "category";
      it ->  cond.code as cc,  cc.text = 'Newborn respiratory distress syndrome' "codeText";
      qr.authored as t -> cond.recordedDate = t "recordedDate";
      qr.encounter as e -> cond.encounter = e;
    } "dx_newborn_rds";
    g.item as it where ((linkId = 'admission-diagnoses/jaundice') and (answer.value.ofType(Coding).code = 'Y')) ->  bundle.entry as entry,  entry.resource = create('Condition') as cond then {
      qr ->  cond,  entry then BuildConditionBase(qr, cond, entry) "base";
      it -> cond.clinicalStatus as cs then {
        it -> cs.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "sys";
          it -> cg.code = 'active' "cd";
          it -> cg.display = 'Active' "dsp";
        } "coding";
      } "clinicalStatus";
      it -> cond.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-category' "sys";
          it -> cg.code = 'encounter-diagnosis' "cd";
          it -> cg.display = 'Encounter Diagnosis' "dsp";
        } "coding";
      } "category";
      it ->  cond.code as cc,  cc.text = 'Jaundice' "codeText";
      qr.authored as t -> cond.recordedDate = t "recordedDate";
      qr.encounter as e -> cond.encounter = e;
    } "dx_jaundice";
    g.item as it where ((linkId = 'admission-diagnoses/neonatal-sepsis') and (answer.value.ofType(Coding).code = 'Y')) ->  bundle.entry as entry,  entry.resource = create('Condition') as cond then {
      qr ->  cond,  entry then BuildConditionBase(qr, cond, entry) "base";
      it -> cond.clinicalStatus as cs then {
        it -> cs.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "sys";
          it -> cg.code = 'active' "cd";
          it -> cg.display = 'Active' "dsp";
        } "coding";
      } "clinicalStatus";
      it -> cond.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-category' "sys";
          it -> cg.code = 'encounter-diagnosis' "cd";
          it -> cg.display = 'Encounter Diagnosis' "dsp";
        } "coding";
      } "category";
      it ->  cond.code as cc,  cc.text = 'Neonatal sepsis' "codeText";
      qr.authored as t -> cond.recordedDate = t "recordedDate";
      qr.encounter as e -> cond.encounter = e;
    } "dx_neonatal_sepsis";
    g.item as it where ((linkId = 'admission-diagnoses/meningitis') and (answer.value.ofType(Coding).code = 'Y')) ->  bundle.entry as entry,  entry.resource = create('Condition') as cond then {
      qr ->  cond,  entry then BuildConditionBase(qr, cond, entry) "base";
      it -> cond.clinicalStatus as cs then {
        it -> cs.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "sys";
          it -> cg.code = 'active' "cd";
          it -> cg.display = 'Active' "dsp";
        } "coding";
      } "clinicalStatus";
      it -> cond.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-category' "sys";
          it -> cg.code = 'encounter-diagnosis' "cd";
          it -> cg.display = 'Encounter Diagnosis' "dsp";
        } "coding";
      } "category";
      it ->  cond.code as cc,  cc.text = 'Meningitis' "codeText";
      qr.authored as t -> cond.recordedDate = t "recordedDate";
      qr.encounter as e -> cond.encounter = e;
    } "dx_meningitis";
    g.item as it where (linkId = 'admission-diagnoses/other') then {
      it.answer as a ->  bundle.entry as entry,  entry.resource = create('Condition') as cond then {
        qr ->  cond,  entry then BuildConditionBase(qr, cond, entry) "base";
        a -> cond.clinicalStatus as cs then {
          a -> cs.coding as cg then {
            a -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "sys";
            a -> cg.code = 'active' "cd";
            a -> cg.display = 'Active' "dsp";
          } "coding";
        } "clinicalStatus";
        a -> cond.category as cat then {
          a -> cat.coding as cg then {
            a -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-category' "sys";
            a -> cg.code = 'encounter-diagnosis' "cd";
            a -> cg.display = 'Encounter Diagnosis' "dsp";
          } "coding";
        } "category";
        a.value as txt ->  cond.code as cc,  cc.text = txt "codeText";
        qr.authored as t -> cond.recordedDate = t "recordedDate";
        qr.encounter as e -> cond.encounter = e;
      } "createOtherCondition";
    } "otherDiagnoses";
  } "admissionDiagnoses";
  // ── Investigations known and their results ──────────────────────────────
  // The sheet mixes orders and results on one block: it asks for the maternal
  // VDRL *result*, not for a VDRL to be done. So these become laboratory
  // Observations carrying what is known, not ServiceRequests -- ordering a test
  // whose answer is already written on the sheet would be wrong twice over.
  qr.item as g where ((linkId = 'investigations') and item.answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
    qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
    qr -> obs then SetLaboratoryCategory(qr, obs) "category";
    g -> obs.code as cc then {
      g -> cc.coding as cg then {
        g -> cg.system = 'http://loinc.org' "sys";
        g -> cg.code = '11502-2' "cd";
        g -> cg.display = 'Laboratory report' "dsp";
      } "coding";
      g -> cc.text = 'Investigations known or ordered on admission' "codeText";
    } "code";
    g.item as it where ((linkId = 'investigations/maternal-vdrl') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'maternal-vdrl-result' "cd";
          it -> cg.display = 'Maternal VDRL result' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_maternal_vdrl_result";
    g.item as it where ((linkId = 'investigations/maternal-hiv') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'maternal-hiv-status' "cd";
          it -> cg.display = 'Maternal HIV status' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_maternal_hiv_status2";
    g.item as it where ((linkId = 'investigations/hb-hct') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-haemoglobin-or-haematocrit' "cd";
          it -> cg.display = 'Haemoglobin or haematocrit' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_sign_haemoglobin_or_haematocrit";
    g.item as it where ((linkId = 'investigations/glucose') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '15074-8' "cd";
          it -> cg.display = 'Glucose [Moles/volume] in Blood' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_15074_8";
    g.item as it where ((linkId = 'investigations/bilirubin') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-bilirubin' "cd";
          it -> cg.display = 'Bilirubin' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_sign_bilirubin";
    g.item as it where ((linkId = 'investigations/lumbar-puncture') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'sign-lumbar-puncture' "cd";
          it -> cg.display = 'Lumbar puncture' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_sign_lumbar_puncture";
    g.item as it where (linkId = 'investigations/other') then {
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "note3";
  } "investigationsPanel";
  // ── Supportive care planned ─────────────────────────────────────────────
  qr.item as g where ((linkId = 'supportive-care') and item.answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('CarePlan') as plan then {
    qr ->  plan,  entry then BuildCarePlanBase(qr, plan, entry) "base";
    g -> plan.status = 'active' "status";
    g -> plan.intent = 'plan' "intent";
    g -> plan.title = 'Supportive care on newborn admission' "title";
    qr.authored as t -> plan.created = t "created";
    qr.encounter as e -> plan.encounter = e;
    qr.source as src -> plan.custodian = src "custodian";
    g -> plan.category as cat then {
      g -> cat.coding as cg then {
        g -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/document-type-codesystem' "sys";
        g -> cg.code = 'newborn-admission-record' "cd";
        g -> cg.display = 'Newborn admission record' "dsp";
      } "coding";
    } "category";
    g.item as it where ((linkId = 'supportive-care/vitamin-k-and-teo') and (answer.value.ofType(Coding).code = 'Y')) ->  plan.activity as act,  act.plannedActivityReference = create('Reference') as ref then {
      it -> ref.display = 'Vitamin K and tetracycline eye ointment' "activityDisplay";
    } "care_vitamin_k_and_teo";
    g.item as it where ((linkId = 'supportive-care/arvs-for-pmtct') and (answer.value.ofType(Coding).code = 'Y')) ->  plan.activity as act,  act.plannedActivityReference = create('Reference') as ref then {
      it -> ref.display = 'ARVs for PMTCT' "activityDisplay";
    } "care_arvs_for_pmtct";
    g.item as it where ((linkId = 'supportive-care/nutrition-or-feeds') and (answer.value.ofType(Coding).code = 'Y')) ->  plan.activity as act,  act.plannedActivityReference = create('Reference') as ref then {
      it -> ref.display = 'Nutrition or feeds' "activityDisplay";
    } "care_nutrition_or_feeds";
    g.item as it where ((linkId = 'supportive-care/oxygen') and (answer.value.ofType(Coding).code = 'Y')) ->  plan.activity as act,  act.plannedActivityReference = create('Reference') as ref then {
      it -> ref.display = 'Oxygen' "activityDisplay";
    } "care_oxygen";
    g.item as it where ((linkId = 'supportive-care/iv-fluids') and (answer.value.ofType(Coding).code = 'Y')) ->  plan.activity as act,  act.plannedActivityReference = create('Reference') as ref then {
      it -> ref.display = 'IV fluids' "activityDisplay";
    } "care_iv_fluids";
    g.item as it where ((linkId = 'supportive-care/blood-transfusion') and (answer.value.ofType(Coding).code = 'Y')) ->  plan.activity as act,  act.plannedActivityReference = create('Reference') as ref then {
      it -> ref.display = 'Blood transfusion' "activityDisplay";
    } "care_blood_transfusion";
    g.item as it where ((linkId = 'supportive-care/incubator-or-keep-warm') and (answer.value.ofType(Coding).code = 'Y')) ->  plan.activity as act,  act.plannedActivityReference = create('Reference') as ref then {
      it -> ref.display = 'Incubator or keep warm' "activityDisplay";
    } "care_incubator_or_keep_warm";
    g.item as it where ((linkId = 'supportive-care/phototherapy') and (answer.value.ofType(Coding).code = 'Y')) ->  plan.activity as act,  act.plannedActivityReference = create('Reference') as ref then {
      it -> ref.display = 'Phototherapy' "activityDisplay";
    } "care_phototherapy";
  } "supportiveCarePlan";
  // ── Presenting problems ─────────────────────────────────────────────────
  qr.item as it where ((linkId = 'presenting-problems') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
    qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
    qr -> obs then SetSurveyCategory(qr, obs) "category";
    it -> obs.code as cc then {
      it -> cc.coding as cg then {
        it -> cg.system = 'http://loinc.org' "sys";
        it -> cg.code = '10154-3' "cd";
        it -> cg.display = 'Chief complaint Narrative - Reported' "dsp";
      } "coding";
    } "code";
    it.answer first as a then {
      a.value as txt ->  obs.note as n,  n.text = txt "text";
    };
  } "presentingProblemsObservation";
  // ── Consent for admission ───────────────────────────────────────────────
  qr.item as g where (linkId = 'sign-off') then {
    g.item as it where ((linkId = 'sign-off/consent-for-admission') and (answer.value = true)) ->  bundle.entry as entry,  entry.resource = create('Consent') as consent then {
      qr ->  consent,  entry then BuildConsentBase(qr, consent, entry) "base";
      it -> consent.status = 'active' "status";
      it -> consent.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/consentcategorycodes' "sys";
          it -> cg.code = 'acd' "cd";
          it -> cg.display = 'Advance Directive' "dsp";
        } "coding";
        it -> cat.text = 'Consent for admission and procedures by the parent or guardian' "categoryText";
      } "category";
      it -> consent.decision = 'permit' "decision";
      qr.authored as t ->  consent.period as per,  per.start = t "consentPeriodStart";
      qr.source as src -> consent.grantee = src "grantee";
      it ->  consent.provision as prov,  prov.code as pc,  pc.text = 'Taken on the newborn admission record. The parent or guardian signed the sheet; this records that the signature was obtained, not the signature itself.' "provenanceNote";
    } "createConsent";
  } "consentGroup";
}

// ─────────────────────────────────────────────────────────────────────────────
// Shared scaffolding. Repeated in each map rather than imported: the transform
// engine resolves `imports` against whatever StructureMaps happen to be on the
// server, and a form that stops extracting because a shared map was not
// uploaded is a worse failure than a duplicated group.
// Two notes on what the publisher's StructureMap validator says about this file.
// Source parameters below are left untyped on purpose. Writing `: Element` makes
// the validator compare QuestionnaireResponse.item against the literal 'Element'
// and report them as incompatible with each other, which is noise, not a finding.
// `evaluate(context, expression)` is flagged as "takes 1 parameter but 2 were
// found". Leave it. The FML parser in the same jar refuses the one-argument form
// outright -- it wants a parameter, a comma, then the FHIRPath -- so the
// publisher is objecting to what its own compiler emits. Two arguments is the
// only form that compiles, and it is what the R5 transform engine executes.
// ─────────────────────────────────────────────────────────────────────────────
group BuildObsBase(source qr : QR, target obs : Observation, target entry) {
  qr -> obs then SetResponseProvenance(qr, obs) "responseProvenance";
  qr -> obs.id = uuid() then SetObservationFullUrl(obs, entry) "idAndFullUrl";
  qr -> entry.request as request then {
    qr -> request.method = 'POST' "requestMethod";
    qr -> request.url = 'Observation' "requestUrl";
  } "entryRequest";
  qr -> obs.status = 'final' "status";
  qr.subject as s -> obs.subject = s;
  qr.encounter as e -> obs.encounter = e;
  qr.authored as t -> obs.effective = t "effective";
  qr.source as src -> obs.performer = src "performerFromSource";
  qr where (source.exists().not()) then {
    qr.author as a -> obs.performer = a "performerFromAuthor";
  } "performerFallback";
  // A stored response's id already reads "QuestionnaireResponse/<id>", so it is
  // a relative reference as it stands. The hasValue() guard is what stops an
  // unsaved response -- one posted straight to $extract rather than saved first
  // -- from writing "QuestionnaireResponse/null" into the record.
  qr.id as qid where ($this.hasValue()) ->  obs.derivedFrom = create('Reference') as ref,  ref.reference = qid "linkQuestionnaireResponse";
}

group SetObservationFullUrl(source obs : Observation, target entry) {
  obs.id as id -> entry.fullUrl = append('https://fhir.slade360.co.ke/fhir/Observation/', id) "assignFullUrl";
}

// The two answer shapes a component can carry. Both read the answer through the
// untyped `.value` accessor: reading `valueCoding` or `valueQuantity` by its
// typed property name fails at transform time on HAPI R5 with "Attempt to read
// invalid property ... on QuestionnaireResponse.item.answer".
group SetComponentCodedValue(source it, target comp) {
  it.answer first as a then {
    a.value as cv -> comp.value = create('CodeableConcept') as cc then {
      cv -> cc.coding = cv "valueCoding";
      cv.display as d -> cc.text = d "valueText";
    } "codedValue";
  } "componentAnswer";
}

group SetComponentValue(source it, target comp) {
  it.answer first as a then {
    a.value as v -> comp.value = v "plainValue";
  } "componentAnswer";
}

group SetSurveyCategory(source qr : QR, target obs : Observation) {
  qr -> obs.category as cat then {
    qr -> cat.coding as coding then {
      qr -> coding.system = 'http://terminology.hl7.org/CodeSystem/observation-category' "categorySystem";
      qr -> coding.code = 'survey' "categoryCode";
      qr -> coding.display = 'Survey' "categoryDisplay";
    } "categoryCoding";
  } "category";
}

group SetVitalSignsCategory(source qr : QR, target obs : Observation) {
  qr -> obs.category as cat then {
    qr -> cat.coding as coding then {
      qr -> coding.system = 'http://terminology.hl7.org/CodeSystem/observation-category' "categorySystem";
      qr -> coding.code = 'vital-signs' "categoryCode";
      qr -> coding.display = 'Vital Signs' "categoryDisplay";
    } "categoryCoding";
  } "category";
}

group SetExamCategory(source qr : QR, target obs : Observation) {
  qr -> obs.category as cat then {
    qr -> cat.coding as coding then {
      qr -> coding.system = 'http://terminology.hl7.org/CodeSystem/observation-category' "categorySystem";
      qr -> coding.code = 'exam' "categoryCode";
      qr -> coding.display = 'Exam' "categoryDisplay";
    } "categoryCoding";
  } "category";
}

group SetLaboratoryCategory(source qr : QR, target obs : Observation) {
  qr -> obs.category as cat then {
    qr -> cat.coding as coding then {
      qr -> coding.system = 'http://terminology.hl7.org/CodeSystem/observation-category' "categorySystem";
      qr -> coding.code = 'laboratory' "categoryCode";
      qr -> coding.display = 'Laboratory' "categoryDisplay";
    } "categoryCoding";
  } "category";
}

group BuildConditionBase(source qr : QR, target r : Condition, target entry) {
  qr -> r then SetResponseProvenance(qr, r) "responseProvenance";
  qr -> r.id = uuid() then SetConditionFullUrl(r, entry) "idAndFullUrl";
  qr -> entry.request as request then {
    qr -> request.method = 'POST' "requestMethod";
    qr -> request.url = 'Condition' "requestUrl";
  } "entryRequest";
  qr.subject as s -> r.subject = s;
}

group SetConditionFullUrl(source r : Condition, target entry) {
  r.id as id -> entry.fullUrl = append('https://fhir.slade360.co.ke/fhir/Condition/', id) "assignFullUrl";
}

group BuildCarePlanBase(source qr : QR, target r : CarePlan, target entry) {
  qr -> r then SetResponseProvenance(qr, r) "responseProvenance";
  qr -> r.id = uuid() then SetCarePlanFullUrl(r, entry) "idAndFullUrl";
  qr -> entry.request as request then {
    qr -> request.method = 'POST' "requestMethod";
    qr -> request.url = 'CarePlan' "requestUrl";
  } "entryRequest";
  qr.subject as s -> r.subject = s;
}

group SetCarePlanFullUrl(source r : CarePlan, target entry) {
  r.id as id -> entry.fullUrl = append('https://fhir.slade360.co.ke/fhir/CarePlan/', id) "assignFullUrl";
}

group BuildConsentBase(source qr : QR, target r : Consent, target entry) {
  qr -> r then SetResponseProvenance(qr, r) "responseProvenance";
  qr -> r.id = uuid() then SetConsentFullUrl(r, entry) "idAndFullUrl";
  qr -> entry.request as request then {
    qr -> request.method = 'POST' "requestMethod";
    qr -> request.url = 'Consent' "requestUrl";
  } "entryRequest";
  qr.subject as s -> r.subject = s;
}

group SetConsentFullUrl(source r : Consent, target entry) {
  r.id as id -> entry.fullUrl = append('https://fhir.slade360.co.ke/fhir/Consent/', id) "assignFullUrl";
}

// ── Provenance and tenancy ───────────────────────────────────────────────────
// Two tags on everything this map creates. The first says which questionnaire
// produced it, so a form that reopens mid-admission recalls its own earlier
// entries and not another form's. The second copies the tenant tags off the
// response, because nothing else on the path puts them there.
// The code is the form's document type, not the questionnaire's id: every
// environment mints its own ids, and there is only one set of maps, so an id
// here would tie the tag to whichever environment stamped it.
// ── Provenance and tenancy ───────────────────────────────────────────────────
group SetResponseProvenance(source qr : QR, target r) {
  qr -> r.meta as m then {
    qr -> m.tag as t then {
      qr -> t.system = 'http://slade360edi.com/questionnaire-provenance' "provenanceSystem";
      qr -> t.code = 'newborn-admission-record' "provenanceCode";
      qr -> t.display = 'Newborn admission record' "provenanceDisplay";
    } "provenanceTag";
  } "provenanceMeta";
  // Every tag the response carries, onto the resource. `meta` is 0..1, so this
  // lands on the same meta the rule above created rather than a second one.
  qr.meta as qm then {
    qm.tag as qt ->  r.meta as m,  m.tag = qt "copyTag";
  } "tenantTags";
}