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 Unit Handover Extraction

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

The mother's ANC serology becomes laboratory Observations on the baby's own record rather than staying as prose on a sheet that lives at the cot – her blood group, VDRL, HIV status and third-trimester urinalysis all govern the baby's management and are the part most often lost in a verbal handover. Gestation, birth weight, Apgar and the first vitals extract under their real LOINC codes; the intranatal and birth histories become panels.

/// url = 'https://fhir.slade360.co.ke/fhir/StructureMap/ExtractNewbornUnitHandover'
/// name = 'ExtractNewbornUnitHandover'
/// title = 'Newborn Unit Handover Extraction'
/// status = 'active'
/// description = 'The mother\'s ANC serology becomes laboratory Observations on the baby\'s own record rather than staying as prose on a sheet that lives at the cot -- her blood group, VDRL, HIV status and third-trimester urinalysis all govern the baby\'s management and are the part most often lost in a verbal handover. Gestation, birth weight, Apgar and the first vitals extract under their real LOINC codes; the intranatal and birth histories become panels.'

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

group ExtractNewbornUnitHandover(source qr : QR, target bundle : Bundle) {
  qr -> bundle.type = 'transaction' "setBundleType";
  qr.item as g where (linkId = 'handover') then {
    g.item as it where ((linkId = 'handover/age-in-days') 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 = 'obs-age-in-days' "cd";
          it -> cg.display = 'Age in days' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_labour_stage_duration";
  } "handoverGroup";
  qr.item as g where (linkId = 'intranatal') then {
    g.item as it where ((linkId = 'intranatal/gestation-by-dates') 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 = '11885-1' "cd";
          it -> cg.display = 'Gestational age Estimated from last menstrual period' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_11885_1";
    g.item as it where ((linkId = 'intranatal/gestation-by-ultrasound') 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";
      };
      it ->  obs.note as n,  n.text = 'Estimated by ultrasound. LOINC has no gestational-age-by-ultrasound term that is not tied to a named biometry formula, so the generic estimate code carries it and this note says where the number came from.' "note";
    } "measure_11884_4";
    g.item as it where ((linkId = 'intranatal/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 = 'intranatal/admission-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 = '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";
      };
      it ->  obs.note as n,  n.text = 'Weight on admission to the newborn unit' "note";
    } "measure_29463_7";
    g.item as it where ((linkId = 'intranatal/apgar') 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 SetExamCategory(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 = 'newborn-apgar-score-as-recorded-on-handover' "cd";
          it -> cg.display = 'Apgar score as recorded on handover' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
      it ->  obs.note as n,  n.text = 'The handover form prints one unlabelled A.P.G.A.R box. Every Apgar code in LOINC is tied to a time point -- one, two, five or ten minutes -- and picking one would invent a time the paper does not record.' "note";
    } "measure_newborn_resuscitation";
    g.item as it where ((linkId = 'intranatal/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";
    // Essential newborn care. A panel, because a chart that records vitamin K
    // and tetracycline eye ointment as given with no dose, no route and no
    // time cannot honestly become MedicationAdministrations -- those would
    // claim a dose nobody gave.
    g where (item.where(linkId = 'intranatal/vitamin-k').answer.value.exists() or item.where(linkId = 'intranatal/teo').answer.value.exists() or item.where(linkId = 'intranatal/art-prophylaxis').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 SetProcedureCategory(qr, obs) "category";
      g -> obs.code as cc then {
        g -> cc.coding as cg then {
          g -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          g -> cg.code = 'essential-newborn-care-given' "cd";
          g -> cg.display = 'Essential newborn care given' "dsp";
        } "coding";
      } "code";
      g.item as it where ((linkId = 'intranatal/vitamin-k') 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 = 'newborn-care-vitamin-k-given' "cd";
            it -> cg.display = 'Vitamin K given' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_care_vitamin_k_given";
      g.item as it where ((linkId = 'intranatal/teo') 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 = 'newborn-care-tetracycline-eye-ointment-given' "cd";
            it -> cg.display = 'Tetracycline eye ointment given' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_care_tetracycline_eye_ointment_given";
      g.item as it where ((linkId = 'intranatal/art-prophylaxis') 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 = 'newborn-care-infant-arv-prophylaxis-given' "cd";
            it -> cg.display = 'Infant ARV prophylaxis given' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_care_infant_arv_prophylaxis_given";
    } "essentialNewbornCare";
  } "intranatalGroup";
  // ── The mother's ANC profile ────────────────────────────────────────────
  // Laboratory Observations on the baby, each noting that the specimen was the
  // mother's. Her serology decides the baby's prophylaxis and follow-up, and a
  // result that only exists on her file is a result the paediatric team cannot
  // find.
  qr.item as g where (linkId = 'anc') then {
    g.item as it where ((linkId = 'anc/blood-group') 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 SetLaboratoryCategory(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 = '883-9' "cd";
          it -> cg.display = 'ABO group [Type] in Blood' "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";
      };
      it ->  obs.note as n,  n.text = 'The mother\'s blood group, recorded on the newborn handover' "note";
    } "coded_883_9";
    g.item as it where ((linkId = 'anc/rhesus') 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 SetLaboratoryCategory(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 = '10331-7' "cd";
          it -> cg.display = 'Rh [Type] in Blood' "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";
      };
      it ->  obs.note as n,  n.text = 'The mother\'s rhesus factor, recorded on the newborn handover' "note";
    } "coded_10331_7";
    g.item as it where ((linkId = 'anc/hiv-status') 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 SetLaboratoryCategory(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 = '55277-8' "cd";
          it -> cg.display = 'HIV status' "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";
      };
      it ->  obs.note as n,  n.text = 'The mother\'s HIV status, recorded on the newborn handover' "note";
    } "coded_55277_8";
    g.item as it where ((linkId = 'anc/vdrl') 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 = 'maternal-vdrl-result' "cd";
          it -> cg.display = 'Maternal VDRL result' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_maternal_vdrl_result";
    g.item as it where ((linkId = 'anc/hepatitis-b') 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 = 'maternal-hepatitis-b-result' "cd";
          it -> cg.display = 'Maternal hepatitis B result' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_maternal_hepatitis_b_result";
    g.item as it where ((linkId = 'anc/rbs') 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 SetLaboratoryCategory(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 = '15074-8' "cd";
          it -> cg.display = 'Glucose [Moles/volume] in Blood' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
      it ->  obs.note as n,  n.text = 'The mother\'s random blood sugar' "note";
    } "measure_15074_8";
    g.item as it where ((linkId = 'anc/duration-of-labour') 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 = 'obs-duration-of-labour' "cd";
          it -> cg.display = 'Duration of labour' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_labour_stage_duration2";
    g where (item.where(linkId = 'anc/parity').answer.value.exists() or item.where(linkId = 'anc/maternal-fevers').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 = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          g -> cg.code = 'maternal-history-on-newborn-handover' "cd";
          g -> cg.display = 'Maternal history on newborn handover' "dsp";
        } "coding";
      } "code";
      g.item as it where ((linkId = 'anc/parity') 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-parity' "cd";
            it -> cg.display = 'Maternal parity' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_maternal_parity";
      g.item as it where ((linkId = 'anc/urinalysis-third-trimester') 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-urinalysis-done-in-the-third-trimester' "cd";
            it -> cg.display = 'Urinalysis done in the third trimester' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_maternal_urinalysis_done_in_the_third_trimester";
      g.item as it where ((linkId = 'anc/urinalysis-result') 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-third-trimester-urinalysis-result' "cd";
            it -> cg.display = 'Third-trimester urinalysis result' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_maternal_third_trimester_urinalysis_result";
      g.item as it where ((linkId = 'anc/treatment-given') 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-treatment-given-in-pregnancy' "cd";
            it -> cg.display = 'Treatment given in pregnancy' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_maternal_treatment_given_in_pregnancy";
      g.item as it where ((linkId = 'anc/maternal-fevers') 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-fevers-in-pregnancy' "cd";
            it -> cg.display = 'Maternal fevers in pregnancy' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_maternal_fevers_in_pregnancy";
      g.item as it where ((linkId = 'anc/other-commodities') 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-other-commodities-given-in-pregnancy' "cd";
            it -> cg.display = 'Other commodities given in pregnancy' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_maternal_other_commodities_given_in_pregnancy";
      g.item as it where (linkId = 'anc/history-of-dol') then {
        it.answer first as a then {
          a.value as txt ->  obs.note as n,  n.text = txt "text";
        };
      } "note";
    } "maternalHistory";
  } "ancGroup";
  // ── Birth history ───────────────────────────────────────────────────────
  qr.item as g where (linkId = 'birth') then {
    g where (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 = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          g -> cg.code = 'newborn-resuscitation' "cd";
          g -> cg.display = 'Resuscitation of a newborn' "dsp";
        } "coding";
      } "code";
      g.item as it where ((linkId = 'birth/resuscitated') 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 = 'newborn-resuscitated-at-birth' "cd";
            it -> cg.display = 'Resuscitated at birth' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_resuscitated_at_birth";
      g.item as it where ((linkId = 'birth/oxygen-route') 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 = 'newborn-route-oxygen-was-given-by' "cd";
            it -> cg.display = 'Route oxygen was given by' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_route_oxygen_was_given_by";
      g.item as it where ((linkId = 'birth/resuscitation-duration') 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 = 'newborn-duration-of-resuscitation' "cd";
            it -> cg.display = 'Duration of resuscitation' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_newborn_duration_of_resuscitation";
      g.item as it where ((linkId = 'birth/meconium-stained-liquor') 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 = 'newborn-meconium-stained-liquor' "cd";
            it -> cg.display = 'Meconium stained liquor' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_meconium_stained_liquor";
      g.item as it where ((linkId = 'birth/functioned') 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 = 'newborn-passed-urine-or-stool-since-birth' "cd";
            it -> cg.display = 'Passed urine or stool since birth' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_passed_urine_or_stool_since_birth";
      g.item as it where (linkId = 'birth/presenting-complaints') then {
        it.answer first as a then {
          a.value as txt ->  obs.note as n,  n.text = txt "text";
        };
      } "note2";
    } "birthHistory";
  } "birthGroup";
  // ── The first vitals, and the cord ──────────────────────────────────────
  qr.item as g where (linkId = 'continuation') then {
    g.item as it where ((linkId = 'continuation/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 = 'continuation/respiratory-rate') 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 = '9279-1' "cd";
          it -> cg.display = 'Respiratory rate' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_9279_1";
    g.item as it where ((linkId = 'continuation/oxygen-saturation') 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 = '59408-5' "cd";
          it -> cg.display = 'Oxygen saturation in Arterial blood by Pulse oximetry' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_59408_5";
    g.item as it where ((linkId = 'continuation/cord-state') 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 SetExamCategory(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-condition' "cd";
          it -> cg.display = 'Cord condition' "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";
  } "continuationGroup";
}

// ─────────────────────────────────────────────────────────────────────────────
// 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 SetProcedureCategory(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 = 'procedure' "categoryCode";
      qr -> coding.display = 'Procedure' "categoryDisplay";
    } "categoryCoding";
  } "category";
}

// ── 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-unit-handover' "provenanceCode";
      qr -> t.display = 'Newborn unit handover form' "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";
}