All files / src/lib/patient observation-bundle.ts

100% Statements 5/5
100% Branches 5/5
100% Functions 2/2
100% Lines 4/4

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                                          14x                                                                 13x 12x 14x          
import { runQuery } from "@/lib/neo4j";
import {
  rowsToBundle,
  type FhirBundle,
  type ObservationRow,
} from "@/lib/overview/observations";
 
/**
 * One patient's Observations as a FHIR R4 searchset Bundle, each with the
 * range the laboratory printed. Shared by `/api/patient/observations` (a
 * session) and `/api/patient/app/record` (the Klarbefund app, #473), so the
 * phone and the browser read the record the same way.
 *
 * Null when there is no such patient. Throws when Neo4j does; the routes
 * answer that with 502.
 */
export async function loadObservationBundle(
  patientId: string,
  selfUrl: string,
  code: string | null = null,
): Promise<FhirBundle | null> {
  const [patientRows, rows] = await Promise.all([
    runQuery<{ id: string; name: string; sandbox: boolean | null }>(
      `MATCH (p:Patient)
       WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId
       RETURN coalesce(p.id, p.resourceId, elementId(p)) AS id,
              coalesce(p.name, 'Anonymous') AS name,
              p.sandbox AS sandbox
       LIMIT 1`,
      { patientId },
    ),
    runQuery<ObservationRow>(
      `MATCH (p:Patient)-[:HAS_OBSERVATION]->(o:Observation)
       WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId
         AND o.valueQuantity IS NOT NULL
         AND ($code IS NULL OR o.code = $code)
       RETURN coalesce(o.resourceId, elementId(o)) AS id,
              coalesce(o.code, '') AS code,
              coalesce(o.display, o.name, o.code, 'Unknown') AS display,
              toFloat(o.valueQuantity) AS value,
              coalesce(o.unit, o.valueUnit, '') AS unit,
              o.referenceLow AS low,
              o.referenceHigh AS high,
              o.referenceText AS rangeText,
              o.category AS category,
              coalesce(toString(o.effectiveDate), o.dateTime, '') AS effective,
              o.performer AS performer,
              o.status AS status,
              o.sourceKind AS sourceKind
       ORDER BY code, effective
       LIMIT 2000`,
      { patientId, code },
    ),
  ]);
  if (patientRows.length === 0) return null;
  return rowsToBundle(
    rows.filter((r) => r.code && Number.isFinite(r.value)),
    patientRows[0],
    selfUrl,
  );
}