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: Blood Donor Questionnaire Extraction

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

The KTTA donor form out as: one Observation carrying the thirteen deferral questions as components, because eligibility is a judgement over the whole set; the screening measurements each as their own Observation, so a haemoglobin below the 12.5 g/dL line is findable by its LOINC code; the eligibility decision as its own Observation with an abnormal interpretation when the donor was deferred, and the reason beside it; a Consent from the signed declaration, with the research opt-in as a second provision because it is a separate question the form asks separately; a Procedure for the collection itself; and one Observation carrying the nine post-donation adverse events.

/// url = 'https://fhir.slade360.co.ke/fhir/StructureMap/ExtractBloodDonorQuestionnaire'
/// name = 'ExtractBloodDonorQuestionnaire'
/// title = 'Blood Donor Questionnaire Extraction'
/// status = 'active'
/// description = 'The KTTA donor form out as: one Observation carrying the thirteen deferral questions as components, because eligibility is a judgement over the whole set; the screening measurements each as their own Observation, so a haemoglobin below the 12.5 g/dL line is findable by its LOINC code; the eligibility decision as its own Observation with an abnormal interpretation when the donor was deferred, and the reason beside it; a Consent from the signed declaration, with the research opt-in as a second provision because it is a separate question the form asks separately; a Procedure for the collection itself; and one Observation carrying the nine post-donation adverse events.'

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/Consent" alias Consent as target
uses "http://hl7.org/fhir/StructureDefinition/Procedure" alias Procedure as target

group ExtractBloodDonorQuestionnaire(source qr : QR, target bundle : Bundle) {
  qr -> bundle.type = 'transaction' "setBundleType";
  // ── The thirteen deferral questions, as one panel ───────────────────────
  // Eligibility is decided by reading all thirteen together, so they travel
  // together. A single "yes" to any of several of them defers the donor, and a
  // reviewer has to be able to see which.
  qr.item as g where ((linkId = 'eligibility') and item.answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
    qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
    qr -> obs then SetSurveyCategory(qr, obs) "category";
    g -> obs.code as cc then {
      g -> cc.coding as cg then {
        g -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
        g -> cg.code = 'donor-eligibility-question' "cd";
        g -> cg.display = 'Donor eligibility question' "dsp";
      } "coding";
      g -> cc.text = 'KTTA donor eligibility questionnaire' "codeText";
    } "code";
    g.item as it where ((linkId = 'eligibility/feeling-well-today') 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 = 'donor-q-feeling-well-today' "cd";
          it -> cg.display = 'Feeling well today' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_feeling_well_today";
    g.item as it where ((linkId = 'eligibility/eaten-in-last-6-hours') 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 = 'donor-q-eaten-in-the-last-6-hours' "cd";
          it -> cg.display = 'Eaten in the last 6 hours' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_eaten_in_the_last_6_hours";
    g.item as it where ((linkId = 'eligibility/fainted-in-past-year') 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 = 'donor-q-fainted-within-the-past-one-year' "cd";
          it -> cg.display = 'Fainted within the past one year' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_fainted_within_the_past_one_year";
    g.item as it where ((linkId = 'eligibility/pregnant-or-lactating') 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 = 'donor-q-pregnant-or-lactating' "cd";
          it -> cg.display = 'Pregnant or lactating' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_pregnant_or_lactating";
    g.item as it where ((linkId = 'eligibility/travelled-in-last-14-days') 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 = 'donor-q-travelled-in-the-last-14-days-outside-the-usual-area' "cd";
          it -> cg.display = 'Travelled in the last 14 days outside the usual area of residence' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_travelled_in_the_last_14_days_outside_the_usual_area";
    g.item as it where ((linkId = 'eligibility/regular-medication') 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 = 'donor-q-on-regular-medication-antibiotics-or-analgesics' "cd";
          it -> cg.display = 'On regular medication, antibiotics or analgesics' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_on_regular_medication_antibiotics_or_analgesics";
    g.item as it where ((linkId = 'eligibility/tattoo-or-piercing-3-months') 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 = 'donor-q-tattooing-or-body-piercing-in-the-last-3-months' "cd";
          it -> cg.display = 'Tattooing or body piercing in the last 3 months' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_tattooing_or_body_piercing_in_the_last_3_months";
    g.item as it where ((linkId = 'eligibility/sexual-activity-unknown-status') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'donor-q-sexual-activity-in-the-last-3-months-with-a-person' "cd";
          it -> cg.display = 'Sexual activity in the last 3 months with a person of unknown health status' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_sexual_activity_in_the_last_3_months_with_a_person";
    g.item as it where ((linkId = 'eligibility/vaccination-3-months') 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 = 'donor-q-vaccination-in-the-last-3-months' "cd";
          it -> cg.display = 'Vaccination in the last 3 months' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_vaccination_in_the_last_3_months";
    g.item as it where ((linkId = 'eligibility/surgery-or-treatment-6-months') 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 = 'donor-q-surgery-or-medical-treatment-in-the-past-6-months' "cd";
          it -> cg.display = 'Surgery or medical treatment in the past 6 months' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_surgery_or_medical_treatment_in_the_past_6_months";
    g.item as it where ((linkId = 'eligibility/received-blood-6-months') 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 = 'donor-q-received-blood-or-blood-products-in-the-past-6' "cd";
          it -> cg.display = 'Received blood or blood products in the past 6 months' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_received_blood_or_blood_products_in_the_past_6";
    g.item as it where ((linkId = 'eligibility/hepatitis-or-yellow-eyes') 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 = 'donor-q-ever-had-hepatitis-or-yellow-eyes' "cd";
          it -> cg.display = 'Ever had hepatitis or yellow eyes' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_ever_had_hepatitis_or_yellow_eyes";
    g.item as it where ((linkId = 'eligibility/covid-exposure-14-days') 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 = 'donor-q-exposed-to-a-suspected-case-of-covid-19-in-the-last' "cd";
          it -> cg.display = 'Exposed to a suspected case of COVID-19 in the last 14 days' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_q_exposed_to_a_suspected_case_of_covid_19_in_the_last";
  } "eligibilityPanel";
  // ── Screening measurements ──────────────────────────────────────────────
  qr.item as g where (linkId = 'screening') then {
    g.item as it where ((linkId = 'screening/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";
      };
    } "measure_29463_7";
    g.item as it where ((linkId = 'screening/haemoglobin') 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 = '718-7' "cd";
          it -> cg.display = 'Hemoglobin [Mass/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 KTTA form prints the acceptance threshold on the line: over 12.5 g/dL.' "note";
    } "measure_718_7";
    g.item as it where ((linkId = 'screening/pulse') 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 = '8867-4' "cd";
          it -> cg.display = 'Heart rate' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_8867_4";
    g.item as it where ((linkId = 'screening/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 bpS where ((linkId = 'screening/systolic') 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";
      bpS -> obs.code as cc then {
        bpS -> cc.coding as cg then {
          bpS -> cg.system = 'http://loinc.org' "sys";
          bpS -> cg.code = '85354-9' "cd";
          bpS -> cg.display = 'Blood pressure panel with all children optional' "dsp";
        } "coding";
      } "code";
      g.item as it where ((linkId = 'screening/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 = 'screening/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";
    } "screeningBloodPressure";
    // ── The eligibility decision ──────────────────────────────────────────
    // Its own Observation with an interpretation, because this is the finding
    // the whole form exists to produce, and a blood bank filters on it.
    g.item as it where ((linkId = 'screening/eligible') 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 = 'donor-eligible' "cd";
          it -> cg.display = 'Donor is eligible' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as cv -> obs.value = create('CodeableConcept') as vc then {
          cv -> vc.coding = cv "valueCoding";
          cv.display as d -> vc.text = d "valueText";
        } "codedValue";
      };
      it.answer first as a then {
        a.value as cv where (code = 'N') -> 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";
        } "deferredInterp";
      } "eligibilityInterpretation";
      // The deferral reason travels on the same Observation. A deferral without
      // a reason cannot be reviewed, and the questionnaire only asks for the
      // reason when the answer was no -- so this rule fires only then too.
      g.item as dr where ((linkId = 'screening/deferral-reason') and answer.value.exists()) then {
        dr.answer first as da then {
          da.value as txt ->  obs.note as n,  n.text = txt "deferralReasonNote";
        };
      } "deferralReasonRule";
    } "eligibilityObservation";
    g.item as it where ((linkId = 'screening/donor-type') 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 = 'donor-type' "cd";
          it -> cg.display = 'Type of donor' "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_donor_type";
    g.item as it where ((linkId = 'screening/donation-type') 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 = 'donation-type' "cd";
          it -> cg.display = 'Type of donation' "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_donation_type";
  } "screeningGroup";
  // ── The declaration and consent ─────────────────────────────────────────
  // Two provisions on one Consent, not two Consents. The donor signed one form,
  // and the research opt-in is a checkbox inside it -- but it is a *separate*
  // permission and the form prints its own yes and no boxes, so it cannot be
  // inferred from the signature. Where the donor did not answer it, no
  // provision is written, which reads as "not asked" rather than "declined".
  qr.item as g where (linkId = 'declaration') then {
    g.item as it where ((linkId = 'declaration/signed') and (answer.value = true)) ->  bundle.entry as entry,  entry.resource = create('Consent') as consent then {
      qr ->  consent,  entry then BuildConsentBase(qr, consent, entry) "base";
      it -> consent.status = 'active' "status";
      it -> consent.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '64293-4' "cd";
          it -> cg.display = 'Procedure consent Document' "dsp";
        } "coding";
        it -> cat.text = 'KTTA blood donor declaration and consent' "categoryText";
      } "category";
      it -> consent.decision = 'permit' "decision";
      qr.source as src -> consent.grantee = src "grantee";
      g.item as dt where ((linkId = 'declaration/signed-on') and answer.value.exists()) then {
        dt.answer first as a then {
          a.value as d -> consent.date = d "signedDate";
        };
      } "signedOnRule";
      it ->  consent.provision as prov,  prov.code as pc,  pc.text = 'The donor signed the KTTA declaration: that the form was filled truthfully, that they consent to give blood, that the donation will be screened for HIV, hepatitis B and C and syphilis, and that a reactive result will be communicated to them with counselling offered.' "declarationNote";
      // The research opt-in, as its own provision.
      g.item as ru where ((linkId = 'declaration/research-use') and (answer.value.ofType(Coding).code = 'Y')) -> consent.provision as prov then {
        ru -> prov.purpose as pur then {
          ru -> pur.system = 'http://terminology.hl7.org/CodeSystem/v3-ActReason' "purposeSystem";
          ru -> pur.code = 'HRESCH' "purposeCode";
          ru -> pur.display = 'healthcare research' "purposeDisplay";
        } "purpose";
      } "researchProvision";
    } "createConsent";
  } "declarationGroup";
  // ── The donation itself ─────────────────────────────────────────────────
  // A Procedure. `status = 'completed'` only when a volume was actually taken:
  // a form filled in for a donor who was then deferred records no collection,
  // and a completed Procedure would say blood was drawn that never was.
  qr.item as g where ((linkId = 'donation') and item.where(linkId = 'donation/volume').answer.value.exists()) ->  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 = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
        g -> cg.code = 'blood-donation' "cd";
        g -> cg.display = 'Blood donation' "dsp";
      } "coding";
    } "code";
    qr.authored as t -> proc.occurrence = t "occurrence";
    qr.encounter as e -> proc.encounter = e;
    qr.source as src ->  proc.performer as p,  p.actor = src "performer";
    g.item as bt where ((linkId = 'donation/bag-type') and answer.value.exists()) then {
      bt.answer first as a then {
        a.value as txt ->  proc.note as n,  n.text = txt "bagTypeNote";
      };
    } "bagTypeRule";
  } "donationProcedure";
  qr.item as g where (linkId = 'donation') then {
    g.item as it where ((linkId = 'donation/volume') 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 = 'volume-donated' "cd";
          it -> cg.display = 'Volume donated' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_volume_donated";
  } "volumeGroup";
  // ── Post-donation adverse events ────────────────────────────────────────
  // One panel. Nine questions the KTTA form asks after every donation, and the
  // set is the haemovigilance record: a donation with no events recorded and a
  // donation where nobody asked look identical unless the panel exists.
  qr.item as g where ((linkId = 'donation') and item.answer.value.ofType(Coding).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 = 'donation-adverse-event' "cd";
        g -> cg.display = 'Post-donation adverse event' "dsp";
      } "coding";
    } "code";
    g.item as it where ((linkId = 'donation/underweight-unit') 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 = 'donor-ae-underweight-unit' "cd";
          it -> cg.display = 'Underweight unit' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_ae_underweight_unit";
    g.item as it where ((linkId = 'donation/more-than-one-venipuncture') 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 = 'donor-ae-more-than-one-venipuncture' "cd";
          it -> cg.display = 'More than one venipuncture' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_ae_more_than_one_venipuncture";
    g.item as it where ((linkId = 'donation/haematoma') 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 = 'donor-ae-haematoma' "cd";
          it -> cg.display = 'Haematoma' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_ae_haematoma";
    g.item as it where ((linkId = 'donation/fainting') 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 = 'donor-ae-fainting' "cd";
          it -> cg.display = 'Fainting' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_ae_fainting";
    g.item as it where ((linkId = 'donation/nausea') 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 = 'donor-ae-nausea' "cd";
          it -> cg.display = 'Nausea' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_ae_nausea";
    g.item as it where ((linkId = 'donation/vomiting') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'donor-ae-vomiting' "cd";
          it -> cg.display = 'Vomiting' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_ae_vomiting";
    g.item as it where ((linkId = 'donation/headache') 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 = 'donor-ae-headache' "cd";
          it -> cg.display = 'Headache' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_ae_headache";
    g.item as it where ((linkId = 'donation/convulsion') 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 = 'donor-ae-convulsion' "cd";
          it -> cg.display = 'Convulsion' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_ae_convulsion";
    g.item as it where ((linkId = 'donation/incontinence') 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 = 'donor-ae-incontinence-of-urine-or-stool' "cd";
          it -> cg.display = 'Incontinence of urine or stool' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_donor_ae_incontinence_of_urine_or_stool";
  } "adverseEventPanel";
  // ── Previous donations ──────────────────────────────────────────────────
  qr.item as g where (linkId = 'donor') then {
    g.item as it where ((linkId = 'donor/previous-donations') 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 = 'previous-donation-count' "cd";
          it -> cg.display = 'Number of previous donations' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v "set";
      };
    } "measure_previous_donation_count";
  } "donorGroup";
}

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

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

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 = 'blood-donor-questionnaire' "provenanceCode";
      qr -> t.display = 'Blood donor questionnaire' "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";
}