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: Haemodialysis Session Extraction

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

One dialysis session out as: a Procedure for the session itself, coded to SNOMED 302497006, with the treatment time as its period and the access as a note; the pre-, target and post-dialysis weights each as their own Observation, because the nephrologist reads them against each other over weeks; the fluid actually removed as its own Observation; the prescription and the machine's function check as two panels, because neither of their parts means anything alone; and one Observation per timed reading through the run, each keeping the reading's own time, since the flow chart is a time series and the circuit pressures are what a run is judged on.

/// url = 'https://fhir.slade360.co.ke/fhir/StructureMap/ExtractHaemodialysisSession'
/// name = 'ExtractHaemodialysisSession'
/// title = 'Haemodialysis Session Extraction'
/// status = 'active'
/// description = 'One dialysis session out as: a Procedure for the session itself, coded to SNOMED 302497006, with the treatment time as its period and the access as a note; the pre-, target and post-dialysis weights each as their own Observation, because the nephrologist reads them against each other over weeks; the fluid actually removed as its own Observation; the prescription and the machine\'s function check as two panels, because neither of their parts means anything alone; and one Observation per timed reading through the run, each keeping the reading\'s own time, since the flow chart is a time series and the circuit pressures are what a run is judged on.'

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/Procedure" alias Procedure as target

group ExtractHaemodialysisSession(source qr : QR, target bundle : Bundle) {
  qr -> bundle.type = 'transaction' "setBundleType";
  // ── The session, as a Procedure ─────────────────────────────────────────
  // SNOMED 302497006, haemodialysis, checked against tx.fhir.org. The access
  // is a note rather than Procedure.usedCode: usedCode wants a device, and
  // "arteriovenous fistula" is an anatomical route, not a device the unit
  // issued.
  qr.item as g where (linkId = 'session') ->  bundle.entry as entry,  entry.resource = create('Procedure') as proc then {
    qr ->  proc,  entry then BuildProcedureBase(qr, proc, entry) "base";
    g -> proc.status = 'completed' "status";
    g -> proc.code as cc then {
      g -> cc.coding as cg then {
        g -> cg.system = 'http://snomed.info/sct' "sys";
        g -> cg.code = '302497006' "cd";
        g -> cg.display = 'Haemodialysis' "dsp";
      } "coding";
    } "code";
    qr.encounter as e -> proc.encounter = e;
    g.item as d where ((linkId = 'session/date') and answer.value.exists()) then {
      d.answer first as a then {
        a.value as t -> proc.occurrence = t "occurrence";
      };
    } "dateRule";
    g.item as ph where ((linkId = 'session/physician') and answer.value.exists()) then {
      ph.answer first as a then {
        a.value as ref ->  proc.performer as p,  p.actor = ref "physician";
      };
    } "physicianRule";
    g.item as ac where ((linkId = 'session/access') and answer.value.exists()) then {
      ac.answer first as a then {
        a.value as cv then {
          cv.display as d ->  proc.note as n,  n.text = d "accessNote";
        } "display";
      };
    } "accessRule";
    g.item as tn where ((linkId = 'session/treatment-number') and answer.value.exists()) then {
      tn.answer first as a then {
        a.value as txt -> proc.identifier as ident then {
          txt -> ident.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "identSystem";
          txt -> ident.value = txt "identValue";
        } "identifier";
      };
    } "treatmentNumberRule";
    // The nurses who started and finished the run. Both, because a run handed
    // over mid-session is exactly the case where knowing who did what matters.
    qr.item as tg where (linkId = 'timing') then {
      tg.item as nc where ((linkId = 'timing/nurse-commencing') and answer.value.exists()) then {
        nc.answer first as a then {
          a.value as ref ->  proc.performer as p,  p.actor = ref "nurseCommencing";
        };
      } "nurseCommencingRule";
      tg.item as nt where ((linkId = 'timing/nurse-terminating') and answer.value.exists()) then {
        nt.answer first as a then {
          a.value as ref ->  proc.performer as p,  p.actor = ref "nurseTerminating";
        };
      } "nurseTerminatingRule";
    } "timingGroup";
  } "dialysisProcedure";
  // ── The weights ─────────────────────────────────────────────────────────
  // Pre and post are both LOINC 29463-7 body weight, so each carries a note
  // saying which it is: without that a query for the patient's weight on the
  // day of dialysis returns two numbers with no way to tell them apart.
  qr.item as g where (linkId = 'weights') then {
    g.item as it where ((linkId = 'weights/pre-dialysis') 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 = 'Taken before the dialysis session.' "note";
    } "measure_29463_7";
    g.item as it where ((linkId = 'weights/post-dialysis') 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 = 'Taken after the dialysis session.' "note";
    } "measure_29463_72";
    g.item as it where ((linkId = 'weights/target') 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 SetProcedureCategory(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 = 'dialysis-target-weight' "cd";
          it -> cg.display = 'Target 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 = 'The dry weight the session was aiming for.' "note";
    } "measure_fluid_removed";
    g.item as it where ((linkId = 'weights/fluid-lost') 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 SetProcedureCategory(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 = 'fluid-removed' "cd";
          it -> cg.display = 'Fluid removed' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = create('Quantity') as q then {
          v -> q.value = v "qValue";
          v -> q.unit = 'kg' "qUnit";
          v -> q.system = 'http://unitsofmeasure.org' "qSystem";
          v -> q.code = 'kg' "qCode";
        } "quantity";
      };
      it ->  obs.note as n,  n.text = 'The difference between the pre- and post-dialysis weights, which is the fluid actually taken off. The unit is attached by the extraction map.' "note";
    } "measureq_fluid_removed";
  } "weightsGroup";
  // ── The prescription, as one panel ──────────────────────────────────────
  // Five components on one Observation. A treatment time without its dialyser,
  // bath potassium and heparinisation is not a prescription, and splitting them
  // would let one be changed without the others being reviewed.
  qr.item as g where ((linkId = 'prescription') 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 = 'dialysis-prescription' "cd";
        g -> cg.display = 'Dialysis prescription' "dsp";
      } "coding";
    } "code";
    g.item as it where ((linkId = 'prescription/treatment-time') 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 = 'dialysis-treatment-time' "cd";
          it -> cg.display = 'Treatment time' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_treatment_time";
    g.item as it where ((linkId = 'prescription/prime') 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 = 'dialysis-prime' "cd";
          it -> cg.display = 'Prime' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_prime";
    g.item as it where ((linkId = 'prescription/dialyser') 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 = 'dialysis-dialyser' "cd";
          it -> cg.display = 'Dialyser' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_dialyser";
    g.item as it where ((linkId = 'prescription/bath-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 = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'dialysis-bath-k-plus' "cd";
          it -> cg.display = 'Bath K+' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_bath_k_plus";
    g.item as it where ((linkId = 'prescription/heparin-loading-dose') 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 = 'dialysis-heparin-loading-dose' "cd";
          it -> cg.display = 'Heparin loading dose' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_heparin_loading_dose";
    g.item as it where ((linkId = 'prescription/heparin-hourly') 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 = 'dialysis-heparin-units-per-hour' "cd";
          it -> cg.display = 'Heparin units per hour' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_heparin_units_per_hour";
  } "prescriptionPanel";
  // ── The machine's own function check ────────────────────────────────────
  // A panel, and one that is about the machine rather than the patient. It is
  // still an Observation on the patient's record: it is the evidence that the
  // machine the patient was put on had passed its self-test, which is what a
  // review after an adverse event asks for.
  qr.item as g where ((linkId = 'machine-check') 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 = 'machine-function-check' "cd";
        g -> cg.display = 'Machine function check' "dsp";
      } "coding";
    } "code";
    g.item as it where ((linkId = 'machine-check/t1-test-passed') 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 = 'machine-t1-test-passed' "cd";
          it -> cg.display = 'T1 test passed' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_machine_t1_test_passed";
    g.item as it where ((linkId = 'machine-check/temperature') 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 = 'machine-temperature' "cd";
          it -> cg.display = 'Machine temperature' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_machine_temperature";
    g.item as it where ((linkId = 'machine-check/conductivity') 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 = 'machine-conductivity' "cd";
          it -> cg.display = 'Conductivity' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_machine_conductivity";
    g.item as it where ((linkId = 'machine-check/dialyser-flow-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 = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'machine-dialyser-flow-rate' "cd";
          it -> cg.display = 'Dialyser flow rate' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_machine_dialyser_flow_rate";
  } "machineCheckPanel";
  // ── The virology screen ─────────────────────────────────────────────────
  // A laboratory panel. The unit records HIV, HBsAg and HCV status on every
  // flow chart because a positive donor changes which machine and which bay the
  // patient uses, so it belongs on the session record and not only in the lab.
  qr.item as g where ((linkId = 'virology-screen') 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 = 'Virology screen for dialysis' "codeText";
    } "code";
    g.item as it where ((linkId = 'virology-screen/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 = 'dialysis-hiv' "cd";
          it -> cg.display = 'HIV' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_hiv";
    g.item as it where ((linkId = 'virology-screen/hbsag') 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 = 'dialysis-hbs-ag' "cd";
          it -> cg.display = 'HBs Ag' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_hbs_ag";
    g.item as it where ((linkId = 'virology-screen/hcv') 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 = 'dialysis-hcv' "cd";
          it -> cg.display = 'HCV' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_hcv";
  } "virologyPanel";
  // ── The readings through the run ────────────────────────────────────────
  // One Observation per row of the flow chart. The circuit pressures are
  // deliberately coded to local concepts and not to the blood pressure LOINC
  // codes: arterial and venous pressure on an extracorporeal circuit are
  // machine readings on tubing, and coding them as the patient's arterial
  // pressure would put a figure of -180 mmHg into a vital signs chart.
  qr.item as g where ((linkId = 'reading') 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 = 'dialysis-session-reading' "cd";
        g -> cg.display = 'Dialysis session reading' "dsp";
      } "coding";
      g -> cc.text = 'Reading taken during the dialysis run' "codeText";
    } "code";
    g.item as it where ((linkId = 'reading/systolic') 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 = '8480-6' "cd";
          it -> cg.display = 'Systolic blood pressure' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_8480_6";
    g.item as it where ((linkId = 'reading/diastolic') 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 = '8462-4' "cd";
          it -> cg.display = 'Diastolic blood pressure' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_8462_4";
    g.item as it where ((linkId = 'reading/pulse') 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";
    g.item as it where ((linkId = 'reading/blood-pump-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 = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'blood-pump-rate' "cd";
          it -> cg.display = 'Blood pump rate' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_blood_pump_rate";
    g.item as it where ((linkId = 'reading/transmembrane-pressure') 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 = 'transmembrane-pressure' "cd";
          it -> cg.display = 'Transmembrane pressure' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_transmembrane_pressure";
    g.item as it where ((linkId = 'reading/ultrafiltration') 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 = 'ultrafiltration-volume' "cd";
          it -> cg.display = 'Ultrafiltration volume' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_ultrafiltration_volume";
    g.item as it where ((linkId = 'reading/arterial-pressure') 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 = 'arterial-pressure-circuit' "cd";
          it -> cg.display = 'Arterial pressure (extracorporeal circuit)' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_arterial_pressure_circuit";
    g.item as it where ((linkId = 'reading/venous-pressure') 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 = 'venous-pressure-circuit' "cd";
          it -> cg.display = 'Venous pressure (extracorporeal circuit)' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_venous_pressure_circuit";
    g.item as it where ((linkId = 'reading/heparin') 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 = 'dialysis-heparin-given' "cd";
          it -> cg.display = 'Heparin given' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_heparin_given";
    g.item as it where ((linkId = 'reading/clotting-time') 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 = 'dialysis-clotting-time' "cd";
          it -> cg.display = 'Clotting time' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_clotting_time";
    g.item as it where ((linkId = 'reading/fluid') 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 = 'dialysis-fluid' "cd";
          it -> cg.display = 'Fluid' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentValue(it, comp) "value";
    } "comp_dialysis_fluid";
    g.item as it where (linkId = 'reading/comments') then {
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "note";
  } "runReading";
}

// ─────────────────────────────────────────────────────────────────────────────
// 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 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";
}

group BuildProcedureBase(source qr : QR, target r : Procedure, target entry) {
  qr -> r then SetResponseProvenance(qr, r) "responseProvenance";
  qr -> r.id = uuid() then SetProcedureFullUrl(r, entry) "idAndFullUrl";
  qr -> entry.request as request then {
    qr -> request.method = 'POST' "requestMethod";
    qr -> request.url = 'Procedure' "requestUrl";
  } "entryRequest";
  // The response's own time, as a floor, the way BuildObsBase does it. A rule
  // that reads a time off the form overwrites this; without it a procedure whose
  // date column was taken off on review has no time at all, and a procedure with
  // no time cannot be ordered against the rest of the admission.
  qr.authored as t -> r.occurrence = t "occurrenceFallback";
  qr.subject as s -> r.subject = s;
}

group SetProcedureFullUrl(source r : Procedure, target entry) {
  r.id as id -> entry.fullUrl = append('https://fhir.slade360.co.ke/fhir/Procedure/', 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 = 'haemodialysis-session-record' "provenanceCode";
      qr -> t.display = 'Haemodialysis session 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";
}