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: Hormonal Therapy Treatment Plan Extraction

Official URL: https://fhir.slade360.co.ke/fhir/StructureMap/ExtractHormonalTherapyTreatmentPlan Version: 0.1.0
Active as of 2026-10-06 Computable Name: ExtractHormonalTherapyTreatmentPlan

Each cycle on the hormonal therapy sheet out as: a MedicationAdministration for the drug given, as written, on the cycle's date; laboratory Observations for the PSA, serum calcium and alkaline phosphatase; an Observation for the cycle number, so the next cycle can see which one this was; the remarks as a note; and a ServiceRequest for the date to come again. Everything takes the cycle's own date rather than the form's, because the sheet exists to be read as a series.

/// url = 'https://fhir.slade360.co.ke/fhir/StructureMap/ExtractHormonalTherapyTreatmentPlan'
/// name = 'ExtractHormonalTherapyTreatmentPlan'
/// title = 'Hormonal Therapy Treatment Plan Extraction'
/// status = 'active'
/// description = 'Each cycle on the hormonal therapy sheet out as: a MedicationAdministration for the drug given, as written, on the cycle\'s date; laboratory Observations for the PSA, serum calcium and alkaline phosphatase; an Observation for the cycle number, so the next cycle can see which one this was; the remarks as a note; and a ServiceRequest for the date to come again. Everything takes the cycle\'s own date rather than the form\'s, because the sheet exists to be read as a series.'

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

group ExtractHormonalTherapyTreatmentPlan(source qr : QR, target bundle : Bundle) {
  qr -> bundle.type = 'transaction' "setBundleType";
  // ── One cycle at a time ─────────────────────────────────────────────────
  qr.item as c where (linkId = 'cycle') then {
    // The drug given. A MedicationAdministration, because the sheet records
    // what was given at that cycle, not what was ordered. The drug travels as
    // written: the hospital's formulary is not coded, and the strength is part
    // of what the clinician wrote.
    c where (item.where(linkId = 'cycle/drug').answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('MedicationAdministration') as ma then {
      qr ->  ma,  entry then BuildMedicationAdministrationBase(qr, ma, entry) "base";
      c -> ma.status = 'completed' "status";
      qr.encounter as e where ((reference.exists() and (reference.startsWith('Encounter/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Encounter')))) -> ma.encounter = e;
      c.item as it where (linkId = 'cycle/drug') then {
        it.answer first as a then {
          a.value as txt ->  ma.medication as med,  med.concept as mc,  mc.text = txt "medicationText";
          a.value as txt ->  ma.dosage as dos,  dos.text = txt "dosageAsWritten";
        };
      } "drugRule";
      c.item as it where ((linkId = 'cycle/date') and answer.value.exists()) then {
        it.answer first as a then {
          a.value as d -> ma.occurence = cast(d, 'dateTime') "occurrence";
        };
      } "dateRule";
      c.item as it where ((linkId = 'cycle/number') and answer.value.exists()) then {
        it.answer first as a then {
          a.value as n -> ma.note as note then {
            n -> note.text = evaluate(n, 'Hormonal therapy cycle ' & $this.toString()) "cycleText";
            qr.authored as noteTime -> note.time = noteTime "cycleTime";
          } "cycleNote";
        };
      } "cycleRule";
    } "hormonalDrug";
    // The cycle number as an Observation of its own. It is what tells the
    // next cycle which one this was, and a number inside a note cannot be
    // read back as one.
    c.item as it where ((linkId = 'cycle/number') 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 = 'hormonal-therapy-cycle-number' "cd";
          it -> cg.display = 'Hormonal therapy cycle number' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v;
      };
      c -> obs then SetHormonalCycleContext(c, obs) "cycleContext";
    } "cycleNumber";
    c.item as it where ((linkId = 'cycle/psa') and answer.value.ofType(Quantity).exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetLaboratoryCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '2857-1' "cd";
          it -> cg.display = 'Prostate specific Ag [Mass/volume] in Serum or Plasma' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v;
      };
      c -> obs then SetHormonalCycleContext(c, obs) "cycleContext";
    } "cyclePsa";
    // "CA2+" on the paper. Read as serum calcium in mmol/L, the routine
    // measure on a patient with bone disease; an ionised calcium would need a
    // blood gas analyser and its own code, 1995-0.
    c.item as it where ((linkId = 'cycle/calcium') and answer.value.ofType(Quantity).exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetLaboratoryCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '2000-8' "cd";
          it -> cg.display = 'Calcium [Moles/volume] in Serum or Plasma' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v;
      };
      c -> obs then SetHormonalCycleContext(c, obs) "cycleContext";
    } "cycleCalcium";
    c.item as it where ((linkId = 'cycle/alp') and answer.value.ofType(Quantity).exists()) ->  bundle.entry as entry,  entry.resource = create('Observation') as obs then {
      qr ->  obs,  entry then BuildObsBase(qr, obs, entry) "base";
      qr -> obs then SetLaboratoryCategory(qr, obs) "category";
      it -> obs.code as cc then {
        it -> cc.coding as cg then {
          it -> cg.system = 'http://loinc.org' "sys";
          it -> cg.code = '6768-6' "cd";
          it -> cg.display = 'Alkaline phosphatase [Enzymatic activity/volume] in Serum or Plasma' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as v -> obs.value = v;
      };
      c -> obs then SetHormonalCycleContext(c, obs) "cycleContext";
    } "cycleAlp";
    c.item as it where ((linkId = 'cycle/remarks') 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 = 'hormonal-therapy-remarks' "cd";
          it -> cg.display = 'Remarks on a hormonal therapy cycle' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as txt ->  obs.note as n,  n.text = txt "text";
      };
      c -> obs then SetHormonalCycleContext(c, obs) "cycleContext";
    } "cycleRemarks";
    // TCA, "to come again". A ServiceRequest, not an Appointment, for the
    // reason the discharge summary gives: a date with no clinic, clinician or
    // slot is a request for a follow-up, and an Appointment built from it
    // would claim a booking that does not exist.
    c.item as it where ((linkId = 'cycle/next-visit') and answer.value.exists()) ->  bundle.entry as entry,  entry.resource = create('ServiceRequest') as sr then {
      qr ->  sr,  entry then BuildServiceRequestBase(qr, sr, entry) "base";
      it -> sr.status = 'active' "status";
      it -> sr.intent = 'plan' "intent";
      it ->  sr.code as cr,  cr.concept 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 = 'hormonal-therapy-next-review' "cd";
          it -> cg.display = 'Next hormonal therapy review' "dsp";
        } "coding";
      } "code";
      it.answer first as a then {
        a.value as d -> sr.occurrence = cast(d, 'dateTime') "occurrence";
      };
      qr.authored as t -> sr.authoredOn = t "authoredOn";
      qr.encounter as e where ((reference.exists() and (reference.startsWith('Encounter/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Encounter')))) -> sr.encounter = e;
      it ->  sr.note as n,  n.text = 'Date to come again, written on the hormonal therapy treatment plan. Not a booked appointment: the sheet names no clinic, clinician or slot.' "provenanceNote";
    } "nextVisit";
  } "cycleRows";
}

// The cycle's own date on every Observation from that cycle. It overrides the
// response's authored time: several rows keyed in at one sitting would
// otherwise collapse onto one instant and the series would be gone.
group SetHormonalCycleContext(source c, target obs : Observation) {
  c.item as it where ((linkId = 'cycle/date') and answer.value.exists()) then {
    it.answer first as a then {
      a.value as v where ($this.toString().length() = 10) ->  evaluate(v, $this.toString() + 'T00:00:00+03:00') as midnight,  obs.effective = cast(midnight, 'instant') "effectiveFromCycle";
    };
  } "cycleDateRule";
}

// ─────────────────────────────────────────────────────────────────────────────
// 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.
// ─────────────────────────────────────────────────────────────────────────────
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 where ((reference.exists() and (reference.startsWith('Patient/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Patient')))) -> obs.subject = s;
  qr.encounter as e where ((reference.exists() and (reference.startsWith('Encounter/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Encounter')))) -> obs.encounter = e;
  // 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";
  qr -> obs then ConformObservation(qr, obs) "profileConformance";
}

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

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 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 BuildMedicationAdministrationBase(source qr : QR, target r : MedicationAdministration, target entry) {
  qr -> r then SetResponseProvenance(qr, r) "responseProvenance";
  qr -> r.id = uuid() then SetMedicationAdministrationFullUrl(r, entry) "idAndFullUrl";
  qr -> entry.request as request then {
    qr -> request.method = 'POST' "requestMethod";
    qr -> request.url = 'MedicationAdministration' "requestUrl";
  } "entryRequest";
  qr.subject as s where ((reference.exists() and (reference.startsWith('Patient/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Patient')))) -> r.subject = s;
  // The response's own time, as a floor. A row that names its date overwrites
  // this; without it a row missing its date would produce an administration
  // with no time at all, which is not a record of an administration.
  qr.authored as t -> r.occurence = t "occurrenceFallback";
  qr -> r then ConformMedicationAdministration(qr, r) "profileConformance";
}

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

group BuildServiceRequestBase(source qr : QR, target r : ServiceRequest, target entry) {
  qr -> r then SetResponseProvenance(qr, r) "responseProvenance";
  qr -> r.id = uuid() then SetServiceRequestFullUrl(r, entry) "idAndFullUrl";
  qr -> entry.request as request then {
    qr -> request.method = 'POST' "requestMethod";
    qr -> request.url = 'ServiceRequest' "requestUrl";
  } "entryRequest";
  qr.subject as s where ((reference.exists() and (reference.startsWith('Patient/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Patient')))) -> r.subject = s;
  qr -> r then ConformServiceRequest(qr, r) "profileConformance";
}

group SetServiceRequestFullUrl(source r : ServiceRequest, target entry) {
  r.id as id -> entry.fullUrl = append('https://fhir.slade360.co.ke/fhir/ServiceRequest/', 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 response's
// identifier is copied the same way.
// 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 = 'hormonal-therapy-treatment-plan' "provenanceCode";
      qr -> t.display = 'Hormonal therapy treatment plan' "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";
  // The response's identifiers, as they are. Every profile wants one, and it is
  // the response's to give: nothing here mints one, so a response without an
  // identifier extracts resources without one. One whose assigner is not of a
  // type the profiles allow there is left behind whole, not altered.
  qr.identifier as qid where (assigner.empty() or assigner.where(((reference.exists() and (reference.startsWith('Organization/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Organization'))))).exists()) -> r.identifier = qid;
}

// ── Conformance to the IG profiles ───────────────────────────────────────────
// What the IG's profiles require that the response itself can supply. Called at
// the end of each base group. The encounter and every who-element are the
// response's own; see mapmeta.py for what is and is not here.
// ── Conformance to the IG profiles ───────────────────────────────────────────
group ConformObservation(source qr : QR, target r) {
  qr.authored as t where ($this.toString().length() >= 20) -> r.issued = cast(t, 'instant') "issued";
  qr.authored as t where ($this.toString().length() >= 20) -> r.effective = cast(t, 'instant') "effective";
  qr.author as au where ((reference.exists() and (reference.startsWith('Organization/') or reference.startsWith('Patient/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Organization') or ('/' + type).endsWith('/Patient')))) -> r.performer = au "performerFromAuthor";
  qr where (author.where(((reference.exists() and (reference.startsWith('Organization/') or reference.startsWith('Patient/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Organization') or ('/' + type).endsWith('/Patient'))))).exists().not()) then {
    qr.source as src where ((reference.exists() and (reference.startsWith('Organization/') or reference.startsWith('Patient/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Organization') or ('/' + type).endsWith('/Patient')))) -> r.performer = src "performerFromSource";
  } "performerFallback";
}

group ConformMedicationAdministration(source qr : QR, target r) {
  qr.encounter as e where ((reference.exists() and (reference.startsWith('Encounter/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Encounter')))) -> r.encounter = e;
  qr.author as au where ((reference.exists() and (reference.startsWith('Practitioner/') or reference.startsWith('PractitionerRole/') or reference.startsWith('Patient/') or reference.startsWith('RelatedPerson/') or reference.startsWith('Device/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Practitioner') or ('/' + type).endsWith('/PractitionerRole') or ('/' + type).endsWith('/Patient') or ('/' + type).endsWith('/RelatedPerson') or ('/' + type).endsWith('/Device')))) ->  r.performer as p,  p.actor = create('CodeableReference') as cr,  cr.reference = au "performerFromAuthor";
  qr where (author.where(((reference.exists() and (reference.startsWith('Practitioner/') or reference.startsWith('PractitionerRole/') or reference.startsWith('Patient/') or reference.startsWith('RelatedPerson/') or reference.startsWith('Device/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Practitioner') or ('/' + type).endsWith('/PractitionerRole') or ('/' + type).endsWith('/Patient') or ('/' + type).endsWith('/RelatedPerson') or ('/' + type).endsWith('/Device'))))).exists().not()) then {
    qr.source as src where ((reference.exists() and (reference.startsWith('Practitioner/') or reference.startsWith('PractitionerRole/') or reference.startsWith('Patient/') or reference.startsWith('RelatedPerson/') or reference.startsWith('Device/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Practitioner') or ('/' + type).endsWith('/PractitionerRole') or ('/' + type).endsWith('/Patient') or ('/' + type).endsWith('/RelatedPerson') or ('/' + type).endsWith('/Device')))) ->  r.performer as p,  p.actor = create('CodeableReference') as cr,  cr.reference = src "performerFromSource";
  } "performerFallback";
}

group ConformServiceRequest(source qr : QR, target r) {
  qr.encounter as e where ((reference.exists() and (reference.startsWith('Encounter/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Encounter')))) -> r.encounter = e;
  qr.authored as t -> r.authoredOn = t "authoredOn";
  qr -> r.priority = 'routine' "priority";
  qr.author as au where ((reference.exists() and (reference.startsWith('Organization/') or reference.startsWith('Patient/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Organization') or ('/' + type).endsWith('/Patient')))) -> r.requester = au "requesterFromAuthor";
  qr where (author.where(((reference.exists() and (reference.startsWith('Organization/') or reference.startsWith('Patient/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Organization') or ('/' + type).endsWith('/Patient'))))).exists().not()) then {
    qr.source as src where ((reference.exists() and (reference.startsWith('Organization/') or reference.startsWith('Patient/'))) or (reference.empty() and (type.empty() or ('/' + type).endsWith('/Organization') or ('/' + type).endsWith('/Patient')))) -> r.requester = src "requesterFromSource";
  } "requesterFallback";
}