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: Palliative Care Assessment Extraction

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

The palliative care assessment out as: one symptom-assessment Observation carrying all twenty-two symptoms as components, because the panel is the assessment and a patient with no symptoms ticked has said something a set of absent Observations could not; a Condition for the diagnosis, reconciled against the problem list where the assessor picked an existing one; one Observation for the prior oncological treatment; separate Observations for the patient's own goals and the carer's, because the two often differ and the form asks both; and a CarePlan whose activities are the problem-and-action rows.

/// url = 'https://fhir.slade360.co.ke/fhir/StructureMap/ExtractPalliativeCareAssessment'
/// name = 'ExtractPalliativeCareAssessment'
/// title = 'Palliative Care Assessment Extraction'
/// status = 'active'
/// description = 'The palliative care assessment out as: one symptom-assessment Observation carrying all twenty-two symptoms as components, because the panel is the assessment and a patient with no symptoms ticked has said something a set of absent Observations could not; a Condition for the diagnosis, reconciled against the problem list where the assessor picked an existing one; one Observation for the prior oncological treatment; separate Observations for the patient\'s own goals and the carer\'s, because the two often differ and the form asks both; and a CarePlan whose activities are the problem-and-action rows.'

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

group ExtractPalliativeCareAssessment(source qr : QR, target bundle : Bundle) {
  qr -> bundle.type = 'transaction' "setBundleType";
  // ── The symptom checklist, as one panel ─────────────────────────────────
  // Twenty-two components on one Observation. A palliative assessment is read
  // as a whole -- which symptoms are present today, against which were present
  // last week -- and twenty-two loose Observations make that comparison a
  // twenty-two-query job.
  qr.item as g where ((linkId = 'symptoms') 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 = 'palliative-symptom' "cd";
        g -> cg.display = 'Palliative care symptom' "dsp";
      } "coding";
      g -> cc.text = 'Palliative care symptom checklist' "codeText";
    } "code";
    g.item as it where ((linkId = 'symptoms/abdominal-pain') 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 = 'palliative-abdominal-pain' "cd";
          it -> cg.display = 'Abdominal pain' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_abdominal_pain";
    g.item as it where ((linkId = 'symptoms/nausea-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 = 'palliative-nausea-or-vomiting' "cd";
          it -> cg.display = 'Nausea or vomiting' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_nausea_or_vomiting";
    g.item as it where ((linkId = 'symptoms/constipation') 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 = 'palliative-constipation' "cd";
          it -> cg.display = 'Constipation' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_constipation";
    g.item as it where ((linkId = 'symptoms/diarrhoea') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'palliative-diarrhoea' "cd";
          it -> cg.display = 'Diarrhoea' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_diarrhoea";
    g.item as it where ((linkId = 'symptoms/melaena') 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 = 'palliative-melaena' "cd";
          it -> cg.display = 'Melaena' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_melaena";
    g.item as it where ((linkId = 'symptoms/loss-of-appetite') 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 = 'palliative-loss-of-appetite' "cd";
          it -> cg.display = 'Loss of appetite' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_loss_of_appetite";
    g.item as it where ((linkId = 'symptoms/body-weakness') 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 = 'palliative-body-weakness' "cd";
          it -> cg.display = 'Body weakness' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_body_weakness";
    g.item as it where ((linkId = 'symptoms/pr-bleeding') 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 = 'palliative-per-rectal-bleeding' "cd";
          it -> cg.display = 'Per rectal bleeding' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_per_rectal_bleeding";
    g.item as it where ((linkId = 'symptoms/pr-pain') 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 = 'palliative-per-rectal-pain' "cd";
          it -> cg.display = 'Per rectal pain' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_per_rectal_pain";
    g.item as it where ((linkId = 'symptoms/weight-loss') 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 = 'palliative-weight-loss' "cd";
          it -> cg.display = 'Weight loss' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_weight_loss";
    g.item as it where ((linkId = 'symptoms/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 = 'palliative-jaundice' "cd";
          it -> cg.display = 'Jaundice' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_jaundice";
    g.item as it where ((linkId = 'symptoms/fever') and answer.value.exists()) -> obs.component as comp then {
      it -> comp.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
          it -> cg.code = 'palliative-fever' "cd";
          it -> cg.display = 'Fever' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_fever";
    g.item as it where ((linkId = 'symptoms/chest-pain') 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 = 'palliative-chest-pain' "cd";
          it -> cg.display = 'Chest pain' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_chest_pain";
    g.item as it where ((linkId = 'symptoms/cough') 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 = 'palliative-cough' "cd";
          it -> cg.display = 'Cough' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_cough";
    g.item as it where ((linkId = 'symptoms/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 = 'palliative-incontinence' "cd";
          it -> cg.display = 'Incontinence' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_incontinence";
    g.item as it where ((linkId = 'symptoms/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 = 'palliative-headache' "cd";
          it -> cg.display = 'Headache' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_headache";
    g.item as it where ((linkId = 'symptoms/poor-vision') 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 = 'palliative-poor-vision' "cd";
          it -> cg.display = 'Poor vision' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_poor_vision";
    g.item as it where ((linkId = 'symptoms/weakness-of-limbs') 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 = 'palliative-weakness-of-limbs' "cd";
          it -> cg.display = 'Weakness of limbs' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_weakness_of_limbs";
    g.item as it where ((linkId = 'symptoms/dry-mouth') 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 = 'palliative-dry-mouth' "cd";
          it -> cg.display = 'Dry mouth' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_dry_mouth";
    g.item as it where ((linkId = 'symptoms/excessive-sleep') 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 = 'palliative-excessive-sleep' "cd";
          it -> cg.display = 'Excessive sleep' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_excessive_sleep";
    g.item as it where ((linkId = 'symptoms/hallucinations') 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 = 'palliative-hallucinations' "cd";
          it -> cg.display = 'Hallucinations' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_hallucinations";
    g.item as it where ((linkId = 'symptoms/sore-mouth') 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 = 'palliative-sore-mouth' "cd";
          it -> cg.display = 'Sore mouth' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_palliative_sore_mouth";
  } "symptomPanel";
  // ── Diagnosis ───────────────────────────────────────────────────────────
  // The form asks for both an existing Condition and the diagnosis as written.
  // Where an existing one was picked, the map records the reference as evidence
  // rather than creating a second Condition -- a palliative referral should not
  // fork the problem list of a patient who already has a coded cancer on it.
  qr.item as g where (linkId = 'diagnosis') then {
    g.item as it where ((linkId = 'diagnosis/text') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('Condition') as cond then {
      qr ->  cond,  entry then BuildConditionBase(qr, cond, entry) "base";
      it -> cond.clinicalStatus as cs then {
        it -> cs.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "sys";
          it -> cg.code = 'active' "cd";
          it -> cg.display = 'Active' "dsp";
        } "coding";
      } "clinicalStatus";
      it -> cond.category as cat then {
        it -> cat.coding as cg then {
          it -> cg.system = 'http://terminology.hl7.org/CodeSystem/condition-category' "sys";
          it -> cg.code = 'problem-list-item' "cd";
          it -> cg.display = 'Problem List Item' "dsp";
        } "coding";
      } "category";
      it.answer first as a then {
        a.value as txt ->  cond.code as cc,  cc.text = txt "codeText";
      };
      qr.authored as t -> cond.recordedDate = t "recordedDate";
      qr.encounter as e -> cond.encounter = e;
      g.item as ex where ((linkId = 'diagnosis/condition') and answer.value.exists()) then {
        ex.answer first as ea then {
          ea.value as existing ->  cond.evidence as ev,  ev.reference = existing "evidenceReference";
        };
      } "existingRule";
    } "diagnosisCondition";
  } "diagnosisGroup";
  // ── Prior oncological treatment ─────────────────────────────────────────
  // One Observation with a note per modality. The form takes free text -- "RT
  // 2024, 25 fractions" -- and a Procedure built from that would claim a date
  // and a body site it does not have.
  qr.item as g where ((linkId = 'prior-treatment') 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 = 'prior-oncological-treatment' "cd";
        g -> cg.display = 'Prior oncological treatment' "dsp";
      } "coding";
    } "code";
    g.item as it where (linkId = 'prior-treatment/radiotherapy') then {
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "note";
    g.item as it where (linkId = 'prior-treatment/chemotherapy') then {
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "note2";
    g.item as it where (linkId = 'prior-treatment/surgery') then {
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "note3";
    g.item as it where (linkId = 'prior-treatment/other') then {
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "note4";
    g.item as it where (linkId = 'prior-treatment/p24-markers') then {
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "note5";
    g.item as it where ((linkId = 'prior-treatment/not-discussed') 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 = 'prior-treatment-not-discussed-with-the-patient' "cd";
          it -> cg.display = 'Prior treatment not discussed with the patient' "dsp";
        } "coding";
      } "code";
      it -> comp then SetComponentCodedValue(it, comp) "value";
    } "comp_prior_treatment_not_discussed_with_the_patient";
  } "priorTreatmentPanel";
  // ── Goals, patient's and carer's, kept apart ────────────────────────────
  // Two Observations, deliberately. A carer who wants their relative admitted
  // and a patient who wants to die at home are both recorded, and folding them
  // into one note would hide exactly the conflict a palliative team has to work
  // with.
  qr.item as g where (linkId = 'psychosocial') then {
    g.item as it where ((linkId = 'psychosocial/patient-goals') 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 = 'patient-goals' "cd";
          it -> cg.display = 'Patient goals and expectations' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_patient_goals";
    g.item as it where ((linkId = 'psychosocial/patient-stresses') 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 = 'patient-goals' "cd";
          it -> cg.display = 'Patient goals and expectations' "dsp";
        } "coding";
        it -> cc.text = 'Stresses the patient carries, and the help they feel is appropriate' "codeText";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_patient_goals2";
    g.item as it where ((linkId = 'psychosocial/carer-goals') 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 = 'carer-goals' "cd";
          it -> cg.display = 'Carer goals and expectations' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_carer_goals";
    g.item as it where ((linkId = 'psychosocial/carer-stresses') 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 = 'carer-goals' "cd";
          it -> cg.display = 'Carer goals and expectations' "dsp";
        } "coding";
        it -> cc.text = 'Stresses the carer carries, and the help they feel is appropriate' "codeText";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_carer_goals2";
    g.item as it where ((linkId = 'psychosocial/spiritual-assessment') 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 = 'spiritual-assessment' "cd";
          it -> cg.display = 'Spiritual assessment' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_spiritual_assessment";
    g.item as it where ((linkId = 'psychosocial/social-issues') 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 = '29762-2' "cd";
          it -> cg.display = 'Social history note' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_29762_2";
    g.item as it where ((linkId = 'psychosocial/current-treatment') 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 = '10160-0' "cd";
          it -> cg.display = 'History of Medication use Narrative' "dsp";
        } "coding";
        it -> cc.text = 'Current treatment' "codeText";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_10160_0";
  } "psychosocialGroup";
  qr.item as it where ((linkId = 'history-of-illness') 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 = '10164-2' "cd";
        it -> cg.display = 'History of Present illness Narrative' "dsp";
      } "coding";
    } "code";
    it.answer first as a then {
      a.value as txt ->  obs.note as n,  n.text = txt "text";
    };
  } "narr_10164_2";
  qr.item as g where (linkId = 'referral') then {
    g.item as it where ((linkId = 'referral/source') 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 = 'palliative-referral-source' "cd";
          it -> cg.display = 'Palliative referral source' "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_palliative_symptom";
    g.item as it where ((linkId = 'referral/source-detail') 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 = 'palliative-referral-source' "cd";
          it -> cg.display = 'Palliative referral source' "dsp";
        } "coding";
        it -> cc.text = 'Referral detail' "codeText";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
    } "narr_palliative_referral_source";
  } "referralGroup";
  // ── The problem and action plan ─────────────────────────────────────────
  // One CarePlan, with a row per problem. Each row becomes an activity whose
  // display is the problem and whose progress note is the action -- the plan is
  // the deliverable of a palliative assessment, and the ward picks it up from
  // there rather than from the assessment narrative.
  // Guarded on at least one problem row: a CarePlan with no activities is a
  // plan nobody made.
  qr where (item.where(linkId = 'problem').item.where(linkId = 'problem/description').answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('CarePlan') as plan then {
    qr ->  plan,  entry then BuildCarePlanBase(qr, plan, entry) "base";
    qr -> plan.status = 'active' "status";
    qr -> plan.intent = 'plan' "intent";
    qr -> plan.title = 'Palliative care plan' "title";
    qr.authored as t -> plan.created = t "created";
    qr.encounter as e -> plan.encounter = e;
    qr.source as src -> plan.custodian = src "custodian";
    qr -> plan.category as cat then {
      qr -> cat.coding as cg then {
        qr -> cg.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/concept-codesystem' "sys";
        qr -> cg.code = 'palliative-problem' "cd";
        qr -> cg.display = 'Palliative care problem' "dsp";
      } "coding";
    } "category";
    qr.item as g where (linkId = 'problem') then {
      g.item as it where ((linkId = 'problem/description') and answer.value.exists()) -> plan.activity as act then {
        it.answer first as a then {
          a.value as txt ->  act.plannedActivityReference = create('Reference') as ref,  ref.display = txt "problemDisplay";
        };
      } "problemRow";
      g.item as it where ((linkId = 'problem/action-plan') and answer.value.exists()) then {
        it.answer first as a then {
          a.value as txt ->  plan.note as n,  n.text = txt "actionNote";
        };
      } "actionRow";
    } "problemRows";
  } "palliativeCarePlan";
}

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

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

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

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

// ── 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 = 'palliative-care-assessment' "provenanceCode";
      qr -> t.display = 'Palliative care assessment' "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";
}