All files / src/lib/overview observations.ts

96.42% Statements 27/28
86.66% Branches 39/45
100% Functions 5/5
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225                                                                                                                                                          86x                   86x             86x     16x 16x                 14x 14x   16x                     16x                                                                                     16x   14x                                             14x 14x 578x 577x 578x 577x 578x 578x 97x                           97x   577x           14x 480x   14x    
/**
 * FHIR R4 Observations for the patient overview (issue #271).
 *
 * `rowsToBundle` turns the graph's Observation rows into the searchset
 * Bundle that `GET /api/patient/observations` returns; `bundleToParameters`
 * groups a Bundle by LOINC code into series with the printed reference
 * range. Both are pure and shared by the route, the view builder and the
 * fixture generator.
 */
import type { Range, SeriesPoint } from "./derive";
 
export interface ObservationRow {
  id: string;
  code: string;
  display: string;
  value: number;
  unit: string;
  low?: number | null;
  high?: number | null;
  rangeText?: string | null;
  category?: string | null;
  /** ISO date or timestamp */
  effective: string;
  performer?: string | null;
  /** FHIR status as stored; absent for the synthetic seed, which is `final`. */
  status?: string | null;
  /** Provenance of a value the Klarbefund app sent (#473 phase 3). */
  sourceKind?: string | null;
}
 
export interface FhirQuantity {
  value: number;
  unit: string;
  system?: string;
  code?: string;
}
 
export interface FhirObservation {
  resourceType: "Observation";
  id: string;
  meta?: { tag?: { system?: string; code: string }[] };
  extension?: { url: string; valueCode: string }[];
  status: string;
  category?: { coding: { system?: string; code: string }[] }[];
  code: {
    coding: { system?: string; code: string; display?: string }[];
    text?: string;
  };
  subject: { reference: string; display?: string };
  effectiveDateTime: string;
  performer?: { display: string }[];
  valueQuantity: FhirQuantity;
  referenceRange?: { low?: FhirQuantity; high?: FhirQuantity; text?: string }[];
}
 
/**
 * The other resources a record holds besides Observations (ADR-059): a
 * DiagnosticReport (ECG, imaging), an Immunization or a MedicationStatement.
 * Typed loosely on purpose: the Bundle carries them through, the readers that
 * understand Observations only skip them by `resourceType`.
 */
export interface FhirRecordResource {
  resourceType: "DiagnosticReport" | "Immunization" | "MedicationStatement";
  id: string;
  [key: string]: unknown;
}
 
export interface FhirBundle {
  resourceType: "Bundle";
  id?: string;
  type: "searchset";
  meta?: { tag?: { system?: string; code: string }[] };
  total: number;
  link?: { relation: string; url: string }[];
  entry: { fullUrl?: string; resource: FhirObservation | FhirRecordResource }[];
}
 
const FICTIONAL_TAG = {
  system: "https://ehds.mabu.red/tag",
  code: "fictional",
};
 
/**
 * A record the Klarbefund app created and filled (ADR-054, #473 phase 3):
 * not synthetic, so never tagged `fictional`, and its values carry their own
 * status and provenance.
 */
const SANDBOX_TAG = {
  system: "https://ehds.mabu.red/tag",
  code: "sandbox",
};
 
/** The app's provenance extension, the same URL its FHIR export uses. */
export const SOURCE_KIND_EXTENSION =
  "https://ehds.mabu.red/fhir/StructureDefinition/epa-ingest-source-kind";
 
function toIsoDateTime(v: string): string {
  const s = String(v);
  return s.length === 10 ? `${s}T00:00:00Z` : s;
}
 
/** The searchset Bundle for one patient's Observations. */
export function rowsToBundle(
  rows: ObservationRow[],
  patient: { id: string; name?: string | null; sandbox?: boolean | null },
  selfUrl: string,
): FhirBundle {
  const tag = patient.sandbox ? SANDBOX_TAG : FICTIONAL_TAG;
  const entry = rows.map((r) => {
    const rr: FhirObservation["referenceRange"] =
      r.low != null || r.high != null
        ? [
            {
              ...(r.low != null ? { low: { value: r.low, unit: r.unit } } : {}),
              ...(r.high != null
                ? { high: { value: r.high, unit: r.unit } }
                : {}),
              ...(r.rangeText ? { text: r.rangeText } : {}),
            },
          ]
        : undefined;
    const resource: FhirObservation = {
      resourceType: "Observation",
      id: r.id,
      meta: { tag: [tag] },
      ...(r.sourceKind
        ? {
            extension: [
              { url: SOURCE_KIND_EXTENSION, valueCode: r.sourceKind },
            ],
          }
        : {}),
      status: r.status ?? "final",
      category: [
        {
          coding: [
            {
              system:
                "http://terminology.hl7.org/CodeSystem/observation-category",
              code: r.category ?? "laboratory",
            },
          ],
        },
      ],
      code: {
        coding: [
          { system: "http://loinc.org", code: r.code, display: r.display },
        ],
        text: r.display,
      },
      subject: {
        reference: `Patient/${patient.id}`,
        ...(patient.name ? { display: patient.name } : {}),
      },
      effectiveDateTime: toIsoDateTime(r.effective),
      ...(r.performer ? { performer: [{ display: r.performer }] } : {}),
      valueQuantity: {
        value: r.value,
        unit: r.unit,
        system: "http://unitsofmeasure.org",
        code: r.unit,
      },
      ...(rr ? { referenceRange: rr } : {}),
    };
    return { fullUrl: `urn:uuid:${r.id}`, resource };
  });
  return {
    resourceType: "Bundle",
    id: `observations-${patient.id}`,
    type: "searchset",
    meta: { tag: [tag] },
    total: entry.length,
    link: [{ relation: "self", url: selfUrl }],
    entry,
  };
}
 
export interface Parameter {
  code: string;
  display: string;
  unit: string;
  range: Range | null;
  performer?: string;
  /** Sorted by date, oldest first; `id` is the Observation id */
  series: (SeriesPoint & { id: string })[];
}
 
/** Group a Bundle by LOINC code into series, oldest first. */
export function bundleToParameters(bundle: FhirBundle): Parameter[] {
  const byCode = new Map<string, Parameter>();
  for (const { resource: r } of bundle.entry ?? []) {
    if (r.resourceType !== "Observation") continue;
    const coding = r.code?.coding?.[0];
    Iif (!coding || !r.valueQuantity) continue;
    const rr = r.referenceRange?.[0];
    let p = byCode.get(coding.code);
    if (!p) {
      p = {
        code: coding.code,
        display: coding.display ?? r.code.text ?? coding.code,
        unit: r.valueQuantity.unit,
        range: rr
          ? {
              low: rr.low?.value ?? null,
              high: rr.high?.value ?? null,
              text: rr.text,
            }
          : null,
        performer: r.performer?.[0]?.display,
        series: [],
      };
      byCode.set(coding.code, p);
    }
    p.series.push({
      date: r.effectiveDateTime.slice(0, 10),
      value: r.valueQuantity.value,
      id: r.id,
    });
  }
  for (const p of byCode.values()) {
    p.series.sort((a, b) => a.date.localeCompare(b.date));
  }
  return [...byCode.values()];
}