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: Inpatient Adult General Admission Assessment Extraction

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

Turns a response to the adult general admission assessment into a chief-complaint Observation, one Observation per vital, and a Composition that files the assessment and carries the allergies and medication the assessor reviewed. Nothing is copied: the allergies and medication are already AllergyIntolerance and MedicationRequest resources – the form loads them off the server – so they become section entries. The Composition exists for exactly that reason; without a container those two rows of the assessment extract to nothing at all.

/// url = 'https://fhir.slade360.co.ke/fhir/StructureMap/ExtractInpatientAdultGeneralAdmissionAssessment'
/// name = 'ExtractInpatientAdultGeneralAdmissionAssessment'
/// title = 'Inpatient Adult General Admission Assessment Extraction'
/// status = 'active'
/// description = 'Turns a response to the adult general admission assessment into a chief-complaint Observation, one Observation per vital, and a Composition that files the assessment and carries the allergies and medication the assessor reviewed. Nothing is copied: the allergies and medication are already AllergyIntolerance and MedicationRequest resources -- the form loads them off the server -- so they become section entries. The Composition exists for exactly that reason; without a container those two rows of the assessment extract to nothing at all.'

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

group ExtractInpatientAdultGeneralAdmissionAssessment(source qr : QR, target bundle : Bundle) {
  qr -> bundle.type = 'transaction' "setBundleType";
  // ── Presenting complaint ───────────────────────────────────────────────────
  // Category `social-history` and code 10154-3 match what extract-vital-signs
  // already produces for a chief complaint, so a consumer querying
  // category=social-history&code=10154-3 gets both without knowing which form
  // the complaint came from.
  qr.item as itC where ((linkId = 'complaint') and answer.value.exists()) then {
    itC.answer first as aC then {
      aC ->  bundle.entry as entryC,  entryC.resource = create('Observation') as obsC then {
        qr ->  obsC,  entryC then BuildObsBase(qr, obsC, entryC) "complaintBase";
        qr -> obsC then SetSocialHistoryCategory(qr, obsC) "complaintCategory";
        qr -> obsC.code as code then {
          qr -> code.coding as coding then {
            qr -> coding.system = 'http://loinc.org' "codeSystem";
            qr -> coding.code = '10154-3' "codeCode";
            qr -> coding.display = 'Chief complaint Narrative - Reported' "codeDisplay";
          } "codeCoding";
        } "complaintCode";
        aC.value as v -> obsC.value = v "complaintValue";
      } "complaintObservation";
    } "complaintAnswer";
  } "complaintRule";
  // ── Vitals on admission ────────────────────────────────────────────────────
  // Six items, six Observations, exactly as the form extracted before it had a
  // map. Each answer is already a Quantity -- the item is type `quantity` with
  // a questionnaire-unitOption pinning the unit -- so it is copied through
  // whole. Rebuilding it here would mean restating a unit the client actually
  // sent, which turns a wrong unit into a wrong reading.
  qr.item as gV where (linkId = 'vitals') then {
    gV.item as itS where ((linkId = 'vitals.bpSys') and answer.value.exists()) then {
      itS.answer first as aS then {
        aS ->  bundle.entry as entryS,  entryS.resource = create('Observation') as obsS then {
          qr ->  obsS,  entryS then BuildObsBase(qr, obsS, entryS) "bpSysBase";
          qr -> obsS then SetVitalSignsCategory(qr, obsS) "bpSysCategory";
          qr -> obsS.code as code then {
            qr -> code.coding as coding then {
              qr -> coding.system = 'http://loinc.org' "codeSystem";
              qr -> coding.code = '8480-6' "codeCode";
              qr -> coding.display = 'Systolic blood pressure' "codeDisplay";
            } "codeCoding";
          } "bpSysCode";
          aS.value as v -> obsS.value = v "bpSysValue";
        } "bpSysObservation";
      } "bpSysAnswer";
    } "bpSysRule";
    gV.item as itD where ((linkId = 'vitals.bpDia') and answer.value.exists()) then {
      itD.answer first as aD then {
        aD ->  bundle.entry as entryD,  entryD.resource = create('Observation') as obsD then {
          qr ->  obsD,  entryD then BuildObsBase(qr, obsD, entryD) "bpDiaBase";
          qr -> obsD then SetVitalSignsCategory(qr, obsD) "bpDiaCategory";
          qr -> obsD.code as code then {
            qr -> code.coding as coding then {
              qr -> coding.system = 'http://loinc.org' "codeSystem";
              qr -> coding.code = '8462-4' "codeCode";
              qr -> coding.display = 'Diastolic blood pressure' "codeDisplay";
            } "codeCoding";
          } "bpDiaCode";
          aD.value as v -> obsD.value = v "bpDiaValue";
        } "bpDiaObservation";
      } "bpDiaAnswer";
    } "bpDiaRule";
    gV.item as itP where ((linkId = 'vitals.pulse') and answer.value.exists()) then {
      itP.answer first as aP then {
        aP ->  bundle.entry as entryP,  entryP.resource = create('Observation') as obsP then {
          qr ->  obsP,  entryP then BuildObsBase(qr, obsP, entryP) "pulseBase";
          qr -> obsP then SetVitalSignsCategory(qr, obsP) "pulseCategory";
          qr -> obsP.code as code then {
            qr -> code.coding as coding then {
              qr -> coding.system = 'http://loinc.org' "codeSystem";
              qr -> coding.code = '8867-4' "codeCode";
              qr -> coding.display = 'Heart rate' "codeDisplay";
            } "codeCoding";
          } "pulseCode";
          aP.value as v -> obsP.value = v "pulseValue";
        } "pulseObservation";
      } "pulseAnswer";
    } "pulseRule";
    gV.item as itT where ((linkId = 'vitals.temp') and answer.value.exists()) then {
      itT.answer first as aT then {
        aT ->  bundle.entry as entryT,  entryT.resource = create('Observation') as obsT then {
          qr ->  obsT,  entryT then BuildObsBase(qr, obsT, entryT) "tempBase";
          qr -> obsT then SetVitalSignsCategory(qr, obsT) "tempCategory";
          qr -> obsT.code as code then {
            qr -> code.coding as coding then {
              qr -> coding.system = 'http://loinc.org' "codeSystem";
              qr -> coding.code = '8310-5' "codeCode";
              qr -> coding.display = 'Body temperature' "codeDisplay";
            } "codeCoding";
          } "tempCode";
          aT.value as v -> obsT.value = v "tempValue";
        } "tempObservation";
      } "tempAnswer";
    } "tempRule";
    gV.item as itR where ((linkId = 'vitals.resp') and answer.value.exists()) then {
      itR.answer first as aR then {
        aR ->  bundle.entry as entryR,  entryR.resource = create('Observation') as obsR then {
          qr ->  obsR,  entryR then BuildObsBase(qr, obsR, entryR) "respBase";
          qr -> obsR then SetVitalSignsCategory(qr, obsR) "respCategory";
          qr -> obsR.code as code then {
            qr -> code.coding as coding then {
              qr -> coding.system = 'http://loinc.org' "codeSystem";
              qr -> coding.code = '9279-1' "codeCode";
              qr -> coding.display = 'Respiratory rate' "codeDisplay";
            } "codeCoding";
          } "respCode";
          aR.value as v -> obsR.value = v "respValue";
        } "respObservation";
      } "respAnswer";
    } "respRule";
    gV.item as itO where ((linkId = 'vitals.spo2') and answer.value.exists()) then {
      itO.answer first as aO then {
        aO ->  bundle.entry as entryO,  entryO.resource = create('Observation') as obsO then {
          qr ->  obsO,  entryO then BuildObsBase(qr, obsO, entryO) "spo2Base";
          qr -> obsO then SetVitalSignsCategory(qr, obsO) "spo2Category";
          qr -> obsO.code as code then {
            qr -> code.coding as coding then {
              qr -> coding.system = 'http://loinc.org' "codeSystem";
              qr -> coding.code = '59408-5' "codeCode";
              qr -> coding.display = 'Oxygen saturation in Arterial blood by Pulse oximetry' "codeDisplay";
            } "codeCoding";
          } "spo2Code";
          aO.value as v -> obsO.value = v "spo2Value";
        } "spo2Observation";
      } "spo2Answer";
    } "spo2Rule";
  } "vitalsGroupRule";
  // ── The assessment as a filed document ─────────────────────────────────────
  qr ->  bundle.entry as entry,  entry.resource = create('Composition') as comp then {
    qr ->  comp,  entry then BuildNoteBase(qr, comp, entry) "noteBase";
    qr -> comp.name = 'InpatientAdultGeneralAdmissionAssessment' "noteName";
    qr -> comp.title = 'Adult general admission assessment' "noteTitle";
    qr -> comp.type as ty then {
      qr -> ty.coding as sghi then {
        qr -> sghi.system = 'https://fhir.slade360.co.ke/fhir/CodeSystem/inpatient-document-type-codesystem' "sghiSystem";
        qr -> sghi.code = 'adult-general-admission-assessment' "sghiCode";
        qr -> sghi.display = 'Adult general admission assessment' "sghiDisplay";
      } "sghiCoding";
      qr -> ty.text = 'Adult general admission assessment' "typeText";
    } "noteType";
    qr.item as it where ((linkId = 'complaint') and answer.value.exists()) -> comp.section as sec then {
      it -> sec.title = 'Presenting complaint' "complaintTitle";
      it -> sec then AddSectionText(it, sec) "complaintSectionText";
    } "complaintSectionRule";
    qr.item as itA where ((linkId = 'allergies') and answer.value.exists()) -> comp.section as secA then {
      itA -> secA.title = 'Known allergies' "allergiesTitle";
      itA.answer as aA then {
        aA.value as av -> secA.entry = av "allergiesEntry";
      } "allergiesAnswers";
    } "allergiesRule";
    qr.item as itM where ((linkId = 'meds') and answer.value.exists()) -> comp.section as secM then {
      itM -> secM.title = 'Current medication' "medsTitle";
      itM.answer as aM then {
        aM.value as mv -> secM.entry = mv "medsEntry";
      } "medsAnswers";
    } "medsRule";
  } "composition";
}

// ─────────────────────────────────────────────────────────────────────────────
// 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.
// Untyped, it says only that it cannot check the paths.
// `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.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;
  // `effective`, not `effectiveDateTime`: the R5 transform engine writes choice
  // elements by their base name and rejects the typed form. This form asks for
  // no time of its own, so the moment the response was authored is the best
  // available.
  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";
  // `qr.id` already resolves to the type-qualified relative reference under this
  // engine, so it is used unprefixed.
  qr -> obs.derivedFrom = create('Reference') as ref then {
    qr.id as qid -> ref.reference = qid "derivedFromRef";
  } "linkQuestionnaireResponse";
}

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 SetSocialHistoryCategory(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 = 'social-history' "categoryCode";
      qr -> coding.display = 'Social History' "categoryDisplay";
    } "categoryCoding";
  } "category";
}

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

group BuildNoteBase(source qr : QR, target comp : Composition, target entry) {
  qr -> comp.id = uuid() then SetCompositionFullUrl(comp, entry) "idAndFullUrl";
  qr -> entry.request as request then {
    qr -> request.method = 'POST' "requestMethod";
    qr -> request.url = 'Composition' "requestUrl";
  } "entryRequest";
  qr -> comp.status = 'final' "status";
  qr.subject as s -> comp.subject = s;
  qr.encounter as e -> comp.encounter = e;
  // Composition.date is 1..1. `authored` is only 0..1 on the response, so when a
  // client sends none the extraction time stands in. It is a poor substitute for
  // when the note was written, but a document with no date at all is worse, and
  // extraction happens moments after submission in practice.
  qr.authored as t -> comp.date = t "date";
  qr where (authored.exists().not()) then {
    qr -> comp.date = evaluate(qr, now()) "dateFromExtractionTime";
  } "dateFallback";
  // Composition.author is 1..1 minimum. R5 QuestionnaireResponse carries both
  // `author` (who recorded the answers) and `source` (who supplied them); the
  // author is the one who wrote the note, so it wins, and `source` only stands
  // in when the client did not send an author. If the response carries neither,
  // the note comes out unauthored -- there is nothing on a QuestionnaireResponse
  // to invent one from, and guessing at who wrote a clinical note is not a thing
  // a map should do.
  qr.author as a -> comp.author = a "authorFromAuthor";
  qr where (author.exists().not()) then {
    qr.source as src -> comp.author = src "authorFromSource";
  } "authorFallback";
  qr -> comp.relatesTo as rel then {
    qr -> rel.type = 'derived-from' "relatesToType";
    qr -> rel.resourceReference = create('Reference') as ref then {
      qr.id as qid -> ref.reference = qid "relatesToRef";
    } "relatesToTarget";
  } "linkQuestionnaireResponse";
}

group AddSectionText(source it, target sec) {
  it.answer first as a then {
    a.value as v -> sec.text as narrative then {
      v -> narrative.status = 'generated' "narrativeStatus";
      v -> narrative.div = create('xhtml') as xhtml then {
        v -> xhtml.value = evaluate(a, '<div xmlns="http://www.w3.org/1999/xhtml"><p>' + value.toString().escape('html') + '</p></div>') "narrativeDiv";
      } "narrativeXhtml";
    } "sectionText";
  } "sectionAnswer";
}

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