Files
HealthLog/src/lib/fhir/__tests__/lab-observations.test.ts
T
Marc-André Bombeck 9a29de4b02 feat(fhir): code illness conditions and lab observations
Close the three FHIR R4 coding gaps in the health-record export. Both are
export-layer only — no schema column, no migration, no contract change.

Illness Conditions now carry a broad SNOMED CT category concept per
IllnessType (infectious disease, allergy, injury, mental disorder, autoimmune
disease, chronic disease, with the generic Disease root as the fallback for an
unknown type) instead of the single generic placeholder. The user's own label
stays on code.text, the class on category.text, and the unconfirmed +
patient-reported guard rails are unchanged — the export still asserts no
specific diagnosis.

Lab Observations resolve a curated analyte to a real LOINC coding alongside the
user's code.text for the common biomarkers (HbA1c, lipid panel, ferritin, TSH,
vitamin D, creatinine, eGFR, ALT, AST, CRP, fasting glucose, hemoglobin), with
analyte-key and EN/DE alias normalisation. The canonical UCUM code is stamped
on the value only when the recorded unit matches the mapped canonical symbol;
an unmapped analyte or a non-matching unit keeps the honest text-only code and
display-only unit, never a fabricated code. The resolver takes an optional
canonical-name argument so a future Biomarker-catalog link can take precedence
over the free-text analyte without a further change here.
2026-06-20 09:48:22 +02:00

249 lines
8.0 KiB
TypeScript

import { describe, it, expect } from "vitest";
import { computeGlucoseClinicalMetrics } from "@/lib/analytics/glucose-metrics";
import type { DoctorReportData } from "@/lib/doctor-report-data";
import { buildFhirDocumentBundle } from "../build-bundle";
import type { FhirObservation } from "../types";
const FIXED_NOW = new Date("2026-05-03T12:00:00.000Z");
function makeData(overrides?: Partial<DoctorReportData>): DoctorReportData {
return {
period: {
days: 90,
since: "2026-02-02T00:00:00.000Z",
start: "2026-02-02T00:00:00.000Z",
end: "2026-05-03T12:00:00.000Z",
},
patient: {
username: "sample-user",
dateOfBirth: "1985-06-15T00:00:00.000Z",
gender: "MALE",
heightCm: 182,
},
practiceName: null,
measurements: {},
stats: {},
glucoseStats: {},
glucoseRanges: {},
glucoseClinical: computeGlucoseClinicalMetrics([], { now: FIXED_NOW }),
glucoseUnit: "mg/dL",
bmi: null,
compliance: {},
medications: [],
mood: null,
glp1: null,
...overrides,
};
}
function observationsOf(bundle: ReturnType<typeof buildFhirDocumentBundle>) {
return bundle.entry
.map((e) => e.resource)
.filter((r): r is FhirObservation => r.resourceType === "Observation");
}
describe("lab-result FHIR Observations", () => {
const labResults: NonNullable<DoctorReportData["labResults"]> = [
{
panel: "Lipid panel",
analyte: "LDL",
value: 110,
unit: "mg/dL",
referenceLow: null,
referenceHigh: 116,
takenAt: "2026-04-20T08:00:00.000Z",
count: 2,
},
{
panel: null,
analyte: "HbA1c",
value: 5.4,
unit: "%",
referenceLow: 4,
referenceHigh: 5.6,
takenAt: "2026-04-21T08:00:00.000Z",
count: 1,
},
];
it("emits one laboratory Observation per lab result", () => {
const bundle = buildFhirDocumentBundle(
makeData({ labResults }),
{ insuranceNumber: "A123456780" },
FIXED_NOW,
);
const labObs = observationsOf(bundle).filter((o) =>
o.category?.some((c) =>
c.coding?.some((code) => code.code === "laboratory"),
),
);
// Two lab observations (no glucose in this fixture).
expect(labObs).toHaveLength(2);
});
it("maps the value, unit, and effective date onto the Observation", () => {
const bundle = buildFhirDocumentBundle(
makeData({ labResults }),
{ insuranceNumber: "A123456780" },
FIXED_NOW,
);
const ldl = observationsOf(bundle).find(
(o) => o.code.text === "LDL (Lipid panel)",
);
expect(ldl).toBeDefined();
expect(ldl?.valueQuantity?.value).toBe(110);
expect(ldl?.valueQuantity?.unit).toBe("mg/dL");
expect(ldl?.effectiveDateTime).toBe("2026-04-20T08:00:00.000Z");
});
it("emits a referenceRange with only the high bound when low is null", () => {
const bundle = buildFhirDocumentBundle(
makeData({ labResults }),
{ insuranceNumber: "A123456780" },
FIXED_NOW,
);
const ldl = observationsOf(bundle).find(
(o) => o.code.text === "LDL (Lipid panel)",
);
expect(ldl?.referenceRange).toHaveLength(1);
expect(ldl?.referenceRange?.[0].high?.value).toBe(116);
expect(ldl?.referenceRange?.[0].low).toBeUndefined();
});
it("emits a referenceRange with both bounds", () => {
const bundle = buildFhirDocumentBundle(
makeData({ labResults }),
{ insuranceNumber: "A123456780" },
FIXED_NOW,
);
const a1c = observationsOf(bundle).find((o) => o.code.text === "HbA1c");
expect(a1c?.referenceRange?.[0].low?.value).toBe(4);
expect(a1c?.referenceRange?.[0].high?.value).toBe(5.6);
});
it("omits referenceRange entirely when no bounds are present", () => {
const bundle = buildFhirDocumentBundle(
makeData({
labResults: [
{
panel: null,
analyte: "CRP",
value: 2.1,
unit: "mg/L",
referenceLow: null,
referenceHigh: null,
takenAt: "2026-04-22T08:00:00.000Z",
count: 1,
},
],
}),
{ insuranceNumber: "A123456780" },
FIXED_NOW,
);
const crp = observationsOf(bundle).find((o) => o.code.text === "CRP");
expect(crp).toBeDefined();
expect(crp?.referenceRange).toBeUndefined();
});
it("emits no lab Observations when labResults is null", () => {
const bundle = buildFhirDocumentBundle(
makeData({ labResults: null }),
{ insuranceNumber: "A123456780" },
FIXED_NOW,
);
const labObs = observationsOf(bundle).filter((o) =>
o.category?.some((c) =>
c.coding?.some((code) => code.code === "laboratory"),
),
);
expect(labObs).toHaveLength(0);
});
});
describe("lab-result LOINC + canonical UCUM coding (v1.18.8)", () => {
function labOf(type: string, unit: string, value = 5.4) {
const bundle = buildFhirDocumentBundle(
makeData({
labResults: [
{
panel: null,
analyte: type,
value,
unit,
referenceLow: null,
referenceHigh: null,
takenAt: "2026-04-20T08:00:00.000Z",
count: 1,
},
],
}),
{ insuranceNumber: "A123456780" },
FIXED_NOW,
);
return observationsOf(bundle).find((o) => o.code.text?.startsWith(type));
}
it("emits a LOINC coding alongside code.text for a mapped analyte", () => {
const o = labOf("HbA1c", "%");
expect(o?.code.text).toBe("HbA1c");
expect(o?.code.coding?.[0].system).toBe("http://loinc.org");
expect(o?.code.coding?.[0].code).toBe("4548-4");
expect(o?.code.coding?.[0].display).toContain("Hemoglobin A1c");
});
it("stamps the canonical UCUM code when the unit matches", () => {
const o = labOf("LDL", "mg/dL", 110);
expect(o?.code.coding?.[0].code).toBe("18262-6");
expect(o?.valueQuantity?.system).toBe("http://unitsofmeasure.org");
expect(o?.valueQuantity?.code).toBe("mg/dL");
expect(o?.valueQuantity?.unit).toBe("mg/dL");
});
it("resolves analyte aliases to the same canonical LOINC", () => {
// "LDL", "LDL-C", "LDL Cholesterol" all fold to 18262-6.
for (const name of ["LDL-C", "LDL Cholesterol", "ldl_c"]) {
const o = labOf(name, "mg/dL", 110);
expect(o?.code.coding?.[0].code).toBe("18262-6");
}
// German alias for total cholesterol.
const chol = labOf("Gesamtcholesterin", "mg/dL", 180);
expect(chol?.code.coding?.[0].code).toBe("2093-3");
// German alias for creatinine.
const krea = labOf("Kreatinin", "mg/dL", 0.9);
expect(krea?.code.coding?.[0].code).toBe("2160-0");
});
it("normalises equivalent unit spellings to the canonical UCUM symbol", () => {
// "mg/dl" (lower-case L) normalises to canonical "mg/dL".
const o = labOf("HDL", "mg/dl", 55);
expect(o?.code.coding?.[0].code).toBe("2085-9");
expect(o?.valueQuantity?.code).toBe("mg/dL");
// TSH recorded in mIU/L canonicalises to UCUM m[IU]/L.
const tsh = labOf("TSH", "mIU/L", 2.1);
expect(tsh?.code.coding?.[0].code).toBe("3016-3");
expect(tsh?.valueQuantity?.code).toBe("m[IU]/L");
});
it("omits the UCUM code when the unit does not match the mapped canonical", () => {
// HbA1c mapped (LOINC present) but recorded in an mmol/mol unit we don't
// canonicalise → keep the LOINC coding, drop the UCUM code, keep display.
const o = labOf("HbA1c", "mmol/mol", 36);
expect(o?.code.coding?.[0].code).toBe("4548-4");
expect(o?.valueQuantity?.system).toBe("http://unitsofmeasure.org");
expect(o?.valueQuantity?.code).toBeUndefined();
expect(o?.valueQuantity?.unit).toBe("mmol/mol");
});
it("keeps an unmapped analyte text-only with no fabricated coding", () => {
const o = labOf("Selenium", "ug/L", 95);
expect(o?.code.text).toBe("Selenium");
expect(o?.code.coding).toBeUndefined();
// Display unit stays; no coerced UCUM code is invented.
expect(o?.valueQuantity?.unit).toBe("ug/L");
expect(o?.valueQuantity?.code).toBeUndefined();
expect(o?.valueQuantity?.system).toBe("http://unitsofmeasure.org");
});
});