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: NICU Monitoring Chart Extraction

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

Each hourly round out as vitals under their real LOINC codes, an assessment panel, a ventilator panel and the blood gas as a single panel – all taking the round's own timestamp. Jaundice takes the chart's own 0 / + / +++ scale, which grades by how far down the body the jaundice has spread, face at + and feet at +++, because that is what decides phototherapy. Apnoea is flagged abnormal wherever it is recorded.

/// url = 'https://fhir.slade360.co.ke/fhir/StructureMap/ExtractNicuMonitoringChart'
/// name = 'ExtractNicuMonitoringChart'
/// title = 'NICU Monitoring Chart Extraction'
/// status = 'active'
/// description = 'Each hourly round out as vitals under their real LOINC codes, an assessment panel, a ventilator panel and the blood gas as a single panel -- all taking the round\'s own timestamp. Jaundice takes the chart\'s own 0 / + / +++ scale, which grades by how far down the body the jaundice has spread, face at + and feet at +++, because that is what decides phototherapy. Apnoea is flagged abnormal wherever it is recorded.'

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 ExtractNicuMonitoringChart(source qr : QR, target bundle : Bundle) {
  qr -> bundle.type = 'transaction' "setBundleType";
  qr.item as g where (linkId = 'context') then {
    g.item as it where ((linkId = 'context/day-of-life') 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-day-of-life' "cd";
          it -> cg.display = 'Day of life' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_labour_stage_duration";
    g.item as it where ((linkId = 'context/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 = 'context/diagnosis') 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 = '11450-4' "cd";
          it -> cg.display = 'Problem list - Reported' "dsp";
        } "coding";
        it -> cc.text = 'Diagnosis on the NICU monitoring chart' "codeText";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_11450_4";
  } "contextGroup";
  qr.item as g where ((linkId = 'interventions') 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 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 = 'newborn-intervention-newborn-interventions-in-place' "cd";
        g -> cg.display = 'Newborn interventions in place' "dsp";
      } "coding";
    } "code";
    g.item as it where ((linkId = 'interventions/cpap') 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-intervention-cpap-in-use' "cd";
          it -> cg.display = 'CPAP in use' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_newborn_intervention_cpap_in_use";
    g.item as it where ((linkId = 'interventions/oxygen') 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-intervention-oxygen-in-use' "cd";
          it -> cg.display = 'Oxygen in use' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_newborn_intervention_oxygen_in_use";
    g.item as it where ((linkId = 'interventions/phototherapy') 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-intervention-phototherapy-in-use' "cd";
          it -> cg.display = 'Phototherapy in use' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_newborn_intervention_phototherapy_in_use";
    g.item as it where ((linkId = 'interventions/blood-transfusion') 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-intervention-blood-transfusion-in-progress' "cd";
          it -> cg.display = 'Blood transfusion in progress' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_newborn_intervention_blood_transfusion_in_progress";
    g.item as it where ((linkId = 'interventions/incubator-care') 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-intervention-incubator-care' "cd";
          it -> cg.display = 'Incubator care' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_newborn_intervention_incubator_care";
  } "interventionsPanel";
  // ── One hourly round ────────────────────────────────────────────────────
  qr.item as row where (linkId = 'round') then {
    row.item as it where ((linkId = 'round/temperature') and answer.value.ofType(Quantity).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;
      };
      row -> obs then SetNicuRowTime(row, obs) "rowTime";
    } "vital_round_8310_5";
    row.item as it where ((linkId = 'round/pulse') and answer.value.ofType(Quantity).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 = '8867-4' "cd";
          it -> cg.display = 'Heart rate' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v;
      };
      row -> obs then SetNicuRowTime(row, obs) "rowTime";
    } "vital_round_8867_4";
    row.item as it where ((linkId = 'round/respiratory-rate') and answer.value.ofType(Quantity).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;
      };
      row -> obs then SetNicuRowTime(row, obs) "rowTime";
    } "vital_round_9279_1";
    row.item as it where ((linkId = 'round/oxygen-saturation') and answer.value.ofType(Quantity).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;
      };
      row -> obs then SetNicuRowTime(row, obs) "rowTime";
    } "vital_round_59408_5";
    row.item as it where ((linkId = 'round/mean-bp') and answer.value.ofType(Quantity).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 = '8478-0' "cd";
          it -> cg.display = 'Mean blood pressure' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v;
      };
      row -> obs then SetNicuRowTime(row, obs) "rowTime";
    } "meanBloodPressure";
    // ── The assessment ────────────────────────────────────────────────────
    row.item as asm where ((linkId = 'round/assessment') 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 SetExamCategory(qr, obs) "category";
      asm -> obs.code as cc then {
        asm -> cc.coding as cg then {
          asm -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          asm -> cg.code = 'newborn-intervention-newborn-assessment-on-a-nicu-round' "cd";
          asm -> cg.display = 'Newborn assessment on a NICU round' "dsp";
        } "coding";
      } "code";
      asm.item as it where ((linkId = 'round/assessment/respiratory-distress') 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-intervention-respiratory-distress-grade' "cd";
            it -> cg.display = 'Respiratory distress grade' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_intervention_respiratory_distress_grade";
      asm.item as it where ((linkId = 'round/assessment/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 = 'newborn-intervention-jaundice-grade' "cd";
            it -> cg.display = 'Jaundice grade' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_intervention_jaundice_grade";
      asm.item as it where ((linkId = 'round/assessment/colour') 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-intervention-colour' "cd";
            it -> cg.display = 'Colour' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_newborn_intervention_colour";
      asm.item as it where ((linkId = 'round/assessment/apnoea') 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-intervention-apnoea' "cd";
            it -> cg.display = 'Apnoea' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_intervention_apnoea";
      asm.item as it where ((linkId = 'round/assessment/suction') 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-intervention-suctioned' "cd";
            it -> cg.display = 'Suctioned' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_newborn_intervention_suctioned";
      // Apnoea, flagged. In a neonate it is the finding that brings someone to
      // the cot, and a reader should not have to spot a tick to see it.
      asm.item as ap where (linkId = 'round/assessment/apnoea') then {
        ap.answer first as a then {
          a.value as cv where (code = 'Y') -> obs.interpretation as interp then {
            cv -> interp.coding as icg then {
              cv -> icg.system = 'http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation' "sys";
              cv -> icg.code = 'A' "cd";
              cv -> icg.display = 'Abnormal' "dsp";
            } "coding";
          } "apnoeaInterp";
        };
      } "apnoeaRule";
      row -> obs then SetNicuRowTime(row, obs) "rowTime";
    } "nicuAssessment";
    row.item as asm where (linkId = 'round/assessment') then {
      asm.item as bs where ((linkId = 'round/assessment/blood-sugar') and answer.value.ofType(Quantity).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";
        bs -> obs.code as cc then {
          bs -> cc.coding as cg then {
            bs -> cg.system = 'http://loinc.org' "sys";
            bs -> cg.code = '15074-8' "cd";
            bs -> cg.display = 'Glucose [Moles/volume] in Blood' "dsp";
          } "coding";
        } "code";
        bs.answer first as a then {
          a.value as v -> obs.value = v;
        };
        row -> obs then SetNicuRowTime(row, obs) "rowTime";
      } "nicuBloodSugar";
    } "bloodSugarGroup";
    // ── The ventilator ────────────────────────────────────────────────────
    row.item as v where ((linkId = 'round/vent') 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 SetExamCategory(qr, obs) "category";
      v -> obs.code as cc then {
        v -> cc.coding as cg then {
          v -> cg.system = 'http://loinc.org' "sys";
          v -> cg.code = '20124-4' "cd";
          v -> cg.display = 'Ventilation mode Ventilator' "dsp";
        } "coding";
        v -> cc.text = 'Ventilator settings on the NICU monitoring chart' "codeText";
      } "code";
      v.item as it where ((linkId = 'round/vent/mode') 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 = '20124-4' "cd";
            it -> cg.display = 'Ventilation mode Ventilator' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentCodedValue(it, comp) "value";
      } "comp_20124_4";
      v.item as it where ((linkId = 'round/vent/peep') 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 = '20075-8' "cd";
            it -> cg.display = 'PEEP Respiratory system' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_20075_8";
      v.item as it where ((linkId = 'round/vent/pip') 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 = '20058-4' "cd";
            it -> cg.display = 'Airway pressure Ventilator --at peak inspiratory flow setting' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_20058_4";
      v.item as it where ((linkId = 'round/vent/fio2') 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 = '3150-0' "cd";
            it -> cg.display = 'Inhaled oxygen concentration' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_3150_0";
      v.item as it where ((linkId = 'round/vent/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 = '19834-1' "cd";
            it -> cg.display = 'Breath rate setting Ventilator' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_19834_1";
      v.item as it where ((linkId = 'round/vent/ti') 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 = 'ventilator-setting-inspiratory-time' "cd";
            it -> cg.display = 'Inspiratory time' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_ventilator_setting_inspiratory_time";
      v.item as it where ((linkId = 'round/vent/oxygen-flow') 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 = '3151-8' "cd";
            it -> cg.display = 'Inhaled oxygen flow rate' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_3151_8";
      row -> obs then SetNicuRowTime(row, obs) "rowTime";
    } "nicuVentilator";
    // ── The blood gas, as one panel ───────────────────────────────────────
    row.item as bga where ((linkId = 'round/bga') 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";
      bga -> obs.code as cc then {
        bga -> cc.coding as cg then {
          bga -> cg.system = 'http://loinc.org' "sys";
          bga -> cg.code = '24336-0' "cd";
          bga -> cg.display = 'Gas panel - Arterial blood' "dsp";
        } "coding";
      } "code";
      bga.item as it where ((linkId = 'round/bga/ph') 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 = '2744-1' "cd";
            it -> cg.display = 'pH of Arterial blood' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_2744_1";
      bga.item as it where ((linkId = 'round/bga/pco2') 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 = '2019-8' "cd";
            it -> cg.display = 'Carbon dioxide [Partial pressure] in Arterial blood' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_2019_8";
      bga.item as it where ((linkId = 'round/bga/po2') 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 = '2703-7' "cd";
            it -> cg.display = 'Oxygen [Partial pressure] in Arterial blood' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_2703_7";
      bga.item as it where ((linkId = 'round/bga/hco3') 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 = '1963-8' "cd";
            it -> cg.display = 'Bicarbonate [Moles/volume] in Serum or Plasma' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_1963_8";
      bga.item as it where ((linkId = 'round/bga/sodium') 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 = '2947-0' "cd";
            it -> cg.display = 'Sodium [Moles/volume] in Blood' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_2947_0";
      bga.item as it where ((linkId = 'round/bga/potassium') 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 = '2823-3' "cd";
            it -> cg.display = 'Potassium [Moles/volume] in Serum or Plasma' "dsp";
          } "coding";
        } "code";
        it -> comp then SetComponentValue(it, comp) "value";
      } "comp_2823_3";
      row -> obs then SetNicuRowTime(row, obs) "rowTime";
    } "nicuBloodGas";
  } "roundRows";
}

// The row's own timestamp on everything extracted from that row.
group SetNicuRowTime(source row, target obs : Observation) {
  row.item as it where ((linkId = 'round/at') and answer.value.exists()) then {
    it.answer first as a then {
      a.value as v -> obs.effective = v "effective";
    };
  } "rowTimeRule";
  row.item as it where ((linkId = 'round/completed-by') and answer.value.exists()) then {
    it.answer first as a then {
      a.value as ref -> obs.performer = ref "by";
    };
  } "rowByRule";
}

// ─────────────────────────────────────────────────────────────────────────────
// 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 = 'nicu-monitoring-chart' "provenanceCode";
      qr -> t.display = 'NICU monitoring chart' "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";
}