All files / src/lib/fhir-documents import.ts

92.13% Statements 164/178
77.05% Branches 131/170
97.61% Functions 41/42
93.97% Lines 156/166

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 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502                                                                                      4x                       5x 5x   5x                                                                             4x 2879x 1022x 4x 1566x 4x 129x               212x   242x         185x 189x       134x 134x           206x         206x 206x                 28x 28x 1x         27x 27x 27x 27x 27x 27x 2x         25x             26x 26x 26x   533x       26x 26x 533x 533x 533x 533x     25x 390x   25x 25x     26x 26x 147x 147x 87x 87x   60x     26x 181x 181x 127x 57x   70x   70x     125x     127x 29x 29x     54x     26x 26x 26x                 39x     26x 26x 39x           26x                   26x 18x 18x 285x       18x   7x   24x 24x                     18x 362x   18x 1x         17x 17x   17x 18x 18x 18x   18x 43x 43x 43x 43x     43x     43x       43x 43x 43x 43x 43x             43x     43x 43x 43x 43x 170x   12x 43x                                     18x 43x 43x   18x               17x 340x 4x 1x 1x 1x   18x                                   7x             7x 7x 52x   45x 7x 76x 76x           40x   7x 45x 130x 130x 130x 130x 130x   34x           34x   3x                   3x       38x   38x       38x 38x     38x                           38x     15x 15x 15x       15x                   15x     1x             1x   39x       7x    
import {
  KLARBEFUND_REPORT_SYSTEM,
  LAB_PROFILES,
  LAB_REPORT_SYSTEM,
  type LabReportInput,
  type LabResultRow,
} from "./lab-report";
import {
  EPS_PROFILES,
  PATIENT_SUMMARY_TYPE,
  type AllergyRow,
  type ConditionRow,
  type ImmunizationRow,
  type MedicationRow,
  type PatientSummaryInput,
  type ProcedureRow,
} from "./patient-summary";
import {
  EXT_SOURCE_KIND,
  EXT_SOURCE_LINE,
  EXT_SOURCE_REGION,
  GRAPH_NODE_SYSTEM,
  LOINC,
  PATIENT_RECORD_SYSTEM,
  SNOMED,
  documentUuid,
} from "./shared";
 
/**
 * Reading a FHIR document back (#1173, EHDS Art. 15(4)): a laboratory report
 * (HL7 Europe Laboratory Report) or a Patient Summary (HL7 Europe Patient
 * Summary, IPS) as the rows the builders of #1171 take, so what is imported
 * is what the record shows and exports again.
 *
 * Pure: no graph, no validator. The route validates first (the HL7 validator
 * through `$validate`), this maps, `store.ts` writes. A resource the record
 * does not hold (a care plan, a device, a coded rather than numeric result)
 * is listed as skipped with the reason, never stored under a shape it does
 * not have.
 */
 
export type DocumentKind = "lab-report" | "patient-summary";
 
const KINDS: Record<string, { kind: DocumentKind; profile: string }> = {
  "11502-2": { kind: "lab-report", profile: LAB_PROFILES.bundle },
  [PATIENT_SUMMARY_TYPE.code]: {
    kind: "patient-summary",
    profile: EPS_PROFILES.bundle,
  },
};
 
/** A document the hub will not take, with the HTTP status to answer. */
export class DocumentRefusedError extends Error {
  constructor(
    message: string,
    readonly status: 409 | 415 | 422,
    readonly problems: string[] = [],
  ) {
    super(message);
  }
}
 
export interface DocumentMeta {
  /** Bundle.identifier as `system|value`, the document's key in the graph */
  documentId: string;
  timestamp: string;
  /** LOINC code of Composition.type */
  typeCode: string;
  title: string;
  authors: string[];
  custodian: string | null;
}
 
export interface Skipped {
  entry: string;
  resourceType: string;
  reason: string;
}
 
export interface ParsedDocument {
  kind: DocumentKind;
  /** The profile the document is validated against */
  profile: string;
  meta: DocumentMeta;
  /** The hub record the document names, when it names one */
  patientRecordId: string | null;
  lab: LabReportInput | null;
  summary: PatientSummaryInput | null;
  /**
   * Ids of graph nodes the document names (its own identifiers in the hub's
   * systems). The store refuses a document naming another person's node.
   */
  graphIds: string[];
  skipped: Skipped[];
}
 
type Json = Record<string, unknown>;
const obj = (v: unknown): Json =>
  v && typeof v === "object" && !Array.isArray(v) ? (v as Json) : {};
const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
const str = (v: unknown): string | null =>
  typeof v === "string" && v.trim() ? v : null;
const num = (v: unknown): number | null =>
  typeof v === "number" && Number.isFinite(v) ? v : null;
 
interface Entry {
  fullUrl: string;
  resource: Json;
}
 
function codings(cc: unknown): Json[] {
  return arr(obj(cc).coding)
    .map(obj)
    .filter((c) => str(c.code));
}
 
/** The first coding, in the given system when there is one. */
function coding(cc: unknown, prefer?: string): Json | null {
  const all = codings(cc);
  return all.find((c) => c.system === prefer) ?? all[0] ?? null;
}
 
function textOf(cc: unknown, fallback: string): string {
  const c = obj(cc);
  return (
    str(c.text) ?? str(coding(c)?.display) ?? str(coding(c)?.code) ?? fallback
  );
}
 
function identifierIn(resource: Json, system: string): string | null {
  const ids = Array.isArray(resource.identifier)
    ? resource.identifier
    : resource.identifier
      ? [resource.identifier]
      : [];
  const found = ids.map(obj).find((i) => i.system === system);
  return found ? str(found.value) : null;
}
 
/** The document type and the profile it is checked against, or a refusal. */
export function documentKind(bundle: unknown): {
  kind: DocumentKind;
  profile: string;
  typeCode: string;
} {
  const b = obj(bundle);
  if (b.resourceType !== "Bundle" || b.type !== "document") {
    throw new DocumentRefusedError(
      "only a FHIR document Bundle is imported",
      415,
    );
  }
  const composition = obj(obj(arr(b.entry)[0]).resource);
  const code = codings(composition.type)
    .filter((c) => c.system === LOINC)
    .map((c) => String(c.code))
    .find((c) => c in KINDS);
  if (!code) {
    throw new DocumentRefusedError(
      "only a laboratory report (LOINC 11502-2) or a Patient Summary (LOINC 60591-5) is imported",
      415,
    );
  }
  return { ...KINDS[code], typeCode: code };
}
 
export function parseDocument(
  bundle: unknown,
  patientId: string,
): ParsedDocument {
  const { kind, profile, typeCode } = documentKind(bundle);
  const b = obj(bundle);
  const entries: Entry[] = arr(b.entry)
    .map(obj)
    .map((e) => ({
      fullUrl: String(e.fullUrl ?? ""),
      resource: obj(e.resource),
    }));
  const byRef = new Map<string, Entry>();
  for (const e of entries) {
    Eif (e.fullUrl) byRef.set(e.fullUrl, e);
    const { resourceType, id } = e.resource;
    Eif (typeof resourceType === "string" && typeof id === "string") {
      byRef.set(`${resourceType}/${id}`, e);
    }
  }
  const resolve = (ref: unknown): Entry | null =>
    byRef.get(String(obj(ref).reference ?? "")) ?? null;
 
  const identifier = obj(b.identifier);
  const documentId = `${String(identifier.system ?? "")}|${String(
    identifier.value ?? "",
  )}`;
  const graphIds = new Set<string>();
  const keyOf = (e: Entry): string => {
    const own = identifierIn(e.resource, GRAPH_NODE_SYSTEM);
    if (own) {
      graphIds.add(own);
      return own;
    }
    return `imp-${documentUuid(`${patientId}|${documentId}|${e.fullUrl}`)}`;
  };
 
  const nameOf = (ref: unknown): string | null => {
    const target = resolve(ref)?.resource;
    if (target) {
      if (target.resourceType === "Organization" && str(target.name)) {
        return String(target.name);
      }
      const name = obj(arr(target.name)[0]);
      const spelled =
        str(name.text) ??
        str(
          [...arr(name.prefix), ...arr(name.given), name.family]
            .filter((x) => typeof x === "string")
            .join(" "),
        );
      if (spelled) return spelled;
      Eif (target.resourceType === "PractitionerRole") {
        return nameOf(target.organization) ?? nameOf(target.practitioner);
      }
    }
    return str(obj(ref).display);
  };
 
  const composition = entries[0].resource;
  const subject = resolve(composition.subject)?.resource ?? {};
  const meta: DocumentMeta = {
    documentId,
    timestamp: String(b.timestamp ?? ""),
    typeCode,
    title:
      str(composition.title) ??
      (kind === "lab-report" ? "Laboratory report" : "Patient Summary"),
    authors: arr(composition.author)
      .map(nameOf)
      .filter((n): n is string => !!n),
    custodian: nameOf(composition.custodian),
  };
  const skipped: Skipped[] = [];
  const skip = (e: Entry, reason: string) =>
    skipped.push({
      entry: e.fullUrl,
      resourceType: String(e.resource.resourceType ?? "unknown"),
      reason,
    });
 
  const parsed: ParsedDocument = {
    kind,
    profile,
    meta,
    patientRecordId: identifierIn(subject, PATIENT_RECORD_SYSTEM),
    lab: null,
    summary: null,
    graphIds: [],
    skipped,
  };
  if (kind === "lab-report") {
    parsed.lab = labReport(entries, resolve, keyOf, nameOf, skip, meta);
    const reportKey = identifierIn(
      entries.find((e) => e.resource.resourceType === "DiagnosticReport")
        ?.resource ?? {},
      LAB_REPORT_SYSTEM,
    );
    if (reportKey) graphIds.add(reportKey);
  } else {
    parsed.summary = patientSummary(composition, resolve, keyOf, skip);
  }
  parsed.graphIds = [...graphIds];
  return parsed;
}
 
function labReport(
  entries: Entry[],
  resolve: (ref: unknown) => Entry | null,
  keyOf: (e: Entry) => string,
  nameOf: (ref: unknown) => string | null,
  skip: (e: Entry, reason: string) => void,
  meta: DocumentMeta,
): LabReportInput {
  const reports = entries.filter(
    (e) => e.resource.resourceType === "DiagnosticReport",
  );
  if (reports.length !== 1) {
    throw new DocumentRefusedError(
      "a laboratory report document holds exactly one DiagnosticReport",
      422,
    );
  }
  const dr = reports[0];
  const r = dr.resource;
  const reportEffective =
    str(r.effectiveDateTime) ?? str(obj(r.effectivePeriod).start);
  const reportPerformer = nameOf(arr(r.performer)[0]);
  const results: LabResultRow[] = [];
  const seen = new Set<string>();
 
  const take = (e: Entry) => {
    Iif (seen.has(e.fullUrl)) return;
    seen.add(e.fullUrl);
    const o = e.resource;
    Iif (o.resourceType !== "Observation") {
      return skip(e, "a result that is not an Observation");
    }
    const members = arr(o.hasMember)
      .map(resolve)
      .filter((m): m is Entry => !!m);
    Iif (!o.valueQuantity && members.length) {
      members.forEach(take);
      return;
    }
    const loinc = coding(o.code, LOINC);
    Iif (!loinc || loinc.system !== LOINC) return skip(e, "no LOINC code");
    const q = obj(o.valueQuantity);
    const value = num(q.value);
    Iif (value === null) {
      return skip(
        e,
        "not a number with a unit; the record holds numeric results only",
      );
    }
    const effective =
      str(o.effectiveDateTime) ??
      str(obj(o.effectivePeriod).start) ??
      reportEffective;
    Iif (!effective) return skip(e, "no date");
    const unit = str(q.code) ?? str(q.unit) ?? "1";
    const range = obj(arr(o.referenceRange)[0]);
    const ext = (url: string) =>
      arr(o.extension)
        .map(obj)
        .find((x) => x.url === url);
    results.push({
      id: keyOf(e),
      code: String(loinc.code),
      display: textOf(o.code, String(loinc.code)),
      value,
      unit,
      low: num(obj(range.low).value),
      high: num(obj(range.high).value),
      rangeText: str(range.text),
      effective,
      status: str(o.status),
      performer: nameOf(arr(o.performer)[0]) ?? reportPerformer,
      sourceKind:
        str(ext(EXT_SOURCE_KIND)?.valueCode) ??
        str(ext(EXT_SOURCE_KIND)?.valueString),
      sourceLine: str(ext(EXT_SOURCE_LINE)?.valueString),
      sourceRegion: str(ext(EXT_SOURCE_REGION)?.valueString),
    });
  };
  arr(r.result).forEach((ref) => {
    const e = resolve(ref);
    Eif (e) take(e);
  });
  Iif (results.length === 0) {
    throw new DocumentRefusedError(
      "the report has no numeric, LOINC-coded result the record can hold",
      422,
    );
  }
  // The paper a Klarbefund report was read from, as the Provenance names it.
  const sourceReport =
    entries
      .filter((e) => e.resource.resourceType === "Provenance")
      .flatMap((e) => arr(e.resource.entity).map(obj))
      .map((en) => obj(obj(en.what).identifier))
      .filter((id) => id.system === KLARBEFUND_REPORT_SYSTEM)
      .map((id) => str(id.value))
      .find(Boolean) ?? null;
  return {
    reportId: identifierIn(r, LAB_REPORT_SYSTEM) ?? keyOf(dr),
    title: str(obj(r.code).text) ?? meta.title,
    effective: reportEffective ?? results[0].effective,
    issued: str(r.issued),
    performer: reportPerformer ?? results[0].performer,
    conclusion: str(r.conclusion),
    sourceReport,
    results,
  };
}
 
function patientSummary(
  composition: Json,
  resolve: (ref: unknown) => Entry | null,
  keyOf: (e: Entry) => string,
  skip: (e: Entry, reason: string) => void,
): PatientSummaryInput {
  const out: Required<PatientSummaryInput> = {
    conditions: [],
    allergies: [],
    medications: [],
    immunizations: [],
    procedures: [],
  };
  const seen = new Set<string>();
  const sections = (s: unknown): Json[] =>
    arr(s)
      .map(obj)
      .flatMap((x) => [x, ...sections(x.section)]);
  const code = (cc: unknown, prefer: string) => {
    const c = coding(cc, prefer);
    return {
      code: c ? String(c.code) : null,
      system: c ? str(c.system) ?? null : null,
      display: textOf(cc, "Unnamed"),
    };
  };
  const statusCode = (cc: unknown) => str(coding(cc)?.code);
 
  for (const section of sections(composition.section)) {
    for (const ref of arr(section.entry)) {
      const e = resolve(ref);
      Iif (!e || seen.has(e.fullUrl)) continue;
      seen.add(e.fullUrl);
      const r = e.resource;
      switch (r.resourceType) {
        case "Condition":
          out.conditions.push({
            id: keyOf(e),
            ...code(r.code, SNOMED),
            clinicalStatus: statusCode(r.clinicalStatus),
            onset: str(r.onsetDateTime) ?? str(obj(r.onsetPeriod).start),
          } satisfies ConditionRow);
          break;
        case "AllergyIntolerance":
          out.allergies.push({
            id: keyOf(e),
            ...code(r.code, SNOMED),
            clinicalStatus: statusCode(r.clinicalStatus),
            verificationStatus: statusCode(r.verificationStatus),
            type: str(r.type),
            category: str(arr(r.category)[0]),
            criticality: str(r.criticality),
            onset: str(r.onsetDateTime) ?? str(obj(r.onsetPeriod).start),
          } satisfies AllergyRow);
          break;
        case "MedicationStatement":
        case "MedicationRequest": {
          const medication =
            r.medicationCodeableConcept ??
            obj(resolve(r.medicationReference)?.resource).code;
          Iif (!medication) {
            skip(e, "no medication named");
            break;
          }
          const statement = r.resourceType === "MedicationStatement";
          const dosage = obj(
            arr(statement ? r.dosage : r.dosageInstruction)[0],
          );
          out.medications.push({
            id: keyOf(e),
            kind: statement ? "statement" : "request",
            ...code(medication, "http://www.whocc.no/atc"),
            status: str(r.status),
            date: statement
              ? str(obj(r.effectivePeriod).start) ?? str(r.effectiveDateTime)
              : str(r.authoredOn),
            dosage: str(dosage.text),
            reason: statement
              ? str(obj(arr(r.reasonCode)[0]).text) ??
                str(coding(arr(r.reasonCode)[0])?.display)
              : null,
          } satisfies MedicationRow);
          break;
        }
        case "Immunization": {
          const c = coding(r.vaccineCode);
          const occurrence = str(r.occurrenceDateTime);
          Iif (!c || !occurrence) {
            skip(e, "no coded vaccine or no date");
            break;
          }
          out.immunizations.push({
            id: keyOf(e),
            code: String(c.code),
            system: str(c.system),
            display: textOf(r.vaccineCode, String(c.code)),
            status: str(r.status),
            occurrence,
            lot: str(r.lotNumber),
            performer: str(obj(obj(arr(r.performer)[0]).actor).display),
          } satisfies ImmunizationRow);
          break;
        }
        case "Procedure":
          out.procedures.push({
            id: keyOf(e),
            ...code(r.code, SNOMED),
            status: str(r.status),
            performed:
              str(r.performedDateTime) ?? str(obj(r.performedPeriod).start),
          } satisfies ProcedureRow);
          break;
        default:
          skip(e, `the record does not hold ${String(r.resourceType)} yet`);
      }
    }
  }
  return out;
}