Files
HealthLog/src/lib/fhir/resources/labs.ts
T
Marc-André Bombeck fd2bd67ff3 feat(labs): keep the reference range a report prints beside a value
A lab runs its own method on its own device, so the window a physician
evaluates a value against is the one printed next to it on that report,
not a catalog band averaged over every lab. Reading a report pulled the
value and dropped that range: the extraction asked for it, the commit
handed it to the biomarker resolver, and the resolver only uses it when
it mints a NEW marker. For every analyte the user already had — the
normal case after a first panel — the printed range was read and then
thrown away.

Add `sourceReferenceLow` / `sourceReferenceHigh` / `sourceReferenceText`
to `LabResult` and carry the range from the report to the reading. The
text is stored whether or not numbers can be read out of it, because
"bis 5,0" and "negativ" state a window too; a range that could not be
parsed is kept verbatim, never replaced with invented bounds.

`resolveEffectiveReferenceRange` is the one place the precedence lives:
the source window wins for that single reading, and the catalog stays
the net for readings without one. A printed string with no derivable
bound does not displace the catalog. Every surface that judges a
reading routes through it — the API verdict, the doctor report, the
insights blocks and per-marker assessment, the coach snapshot, the MCP
read and the FHIR `referenceRange` — so a value cannot read in range on
one surface and out on another.

The API keeps `referenceLow` / `referenceHigh` as the window in force,
so a client that reads only those two renders the right range and the
right verdict with no change of its own; the catalog band, the source
window, its origin and a divergence flag ride alongside for clients
that want to show both.

Read side: the chart draws the source window as a second, visually
distinct band with the reading it came from named beneath it, the
reading rows name the printed range and the catalog band where the two
disagree, and the doctor-report PDF prints the report's own string with
a footnote naming the saved range. Entry side: one optional field on
the lab form, folded away until asked for, and the printed range is
editable on the scan review screen.

The range parser covers the notations German and English reports
actually print — two-sided, one-sided, comma or dot decimals, thousands
separators, trailing units — reads units without ever converting them,
and refuses to guess on anything ambiguous.
2026-08-07 21:40:41 +02:00

125 lines
4.8 KiB
TypeScript

/**
* Lab-result Observations (v1.17.1; LOINC + UCUM v1.18.8).
*
* One `laboratory` Observation per recorded analyte. `analyte` + `unit` are
* user-recorded free text (no closed LOINC enum). A curated analyte→LOINC map
* (`resolveLabCoding`) adds a real LOINC `coding` ALONGSIDE the user's
* `code.text` for the common biomarkers, and stamps the canonical UCUM `code`
* on the value WHEN the recorded unit matches the mapped canonical symbol. An
* analyte that does NOT resolve keeps the honest text-only `code` +
* display-only `unit` (no fabricated terminology).
*
* The reference bounds map onto R4 `referenceRange`, and they are the SAME
* bounds the app's own verdict uses: the window the reading's source report
* printed when it carries one, the catalog band otherwise, already resolved
* upstream in `loadLabResults`. When the source report stated its window in
* words the bounds could not be read from ("negativ", "siehe Befund"), that
* string rides on `referenceRange.text` so a receiver still gets what the lab
* wrote rather than a silently empty element.
*/
import type { DoctorReportData } from "@/lib/doctor-report-data";
import { LOINC_SYSTEM, UCUM_SYSTEM } from "@/lib/fhir/loinc-map";
import { resolveLabCoding } from "@/lib/fhir/lab-loinc";
import { qualitativeValueConcept } from "@/lib/fhir/lab-qualitative";
import type {
FhirObservation,
FhirObservationReferenceRange,
} from "@/lib/fhir/types";
import { categoryConcept, patientRef } from "@/lib/fhir/resources/common";
export function labObservations(
data: DoctorReportData,
nextId: () => string,
): FhirObservation[] {
const observations: FhirObservation[] = [];
for (const lab of data.labResults ?? []) {
// Forward-compat: when the DTO carries a resolved canonical analyte name,
// thread it as the third arg so the catalog name wins over the free-text
// `analyte`. Absent today.
const coding = resolveLabCoding(lab.analyte, lab.unit);
const text = lab.panel ? `${lab.analyte} (${lab.panel})` : lab.analyte;
const code = coding
? {
coding: [
{
system: LOINC_SYSTEM,
code: coding.loinc,
display: coding.display,
},
],
text,
}
: { text };
// v1.18.9 — a qualitative result (`value === null`) emits a
// `valueCodeableConcept` (SNOMED qualifier value when confidently known,
// else text-only) and NO `valueQuantity` / `referenceRange` — bounds are
// meaningless for it. A numeric result keeps the established
// valueQuantity + LOINC/UCUM path.
if (lab.value === null) {
const valueText = lab.valueText?.trim() ?? "";
// A row with neither a number nor a result term states nothing. An
// Observation whose only value is an empty concept is worse than no
// Observation: it asserts a result was recorded and then withholds it.
if (valueText === "") continue;
observations.push({
resourceType: "Observation",
id: nextId(),
status: "final",
category: [categoryConcept("laboratory")],
code,
subject: patientRef,
effectiveDateTime: lab.takenAt,
valueCodeableConcept: qualitativeValueConcept(valueText),
});
continue;
}
// A lab quantity: the recorded `unit` is always the display string, and
// the canonical UCUM `code` is stamped only when the analyte map resolved
// one for exactly that unit (no coerced symbol).
const quantity = (value: number) => ({
value,
unit: lab.unit,
system: UCUM_SYSTEM,
...(coding?.ucum ? { code: coding.ucum } : {}),
});
// The bounds are stated in the SAME unit as the value, so they carry the
// SAME coding — a bare unit beside a coded value leaves a receiver unable
// to compare the two.
const sourceText =
lab.referenceOrigin === "source" ? lab.sourceReferenceText : null;
const hasBounds = lab.referenceLow !== null || lab.referenceHigh !== null;
const referenceRange: FhirObservationReferenceRange[] | undefined =
hasBounds || sourceText
? [
{
...(lab.referenceLow !== null
? { low: quantity(lab.referenceLow) }
: {}),
...(lab.referenceHigh !== null
? { high: quantity(lab.referenceHigh) }
: {}),
...(sourceText ? { text: sourceText } : {}),
},
]
: undefined;
observations.push({
resourceType: "Observation",
id: nextId(),
status: "final",
category: [categoryConcept("laboratory")],
code,
subject: patientRef,
effectiveDateTime: lab.takenAt,
valueQuantity: quantity(lab.value),
...(referenceRange ? { referenceRange } : {}),
});
}
return observations;
}