All files / src/lib/patient load-own-health.ts

94.73% Statements 18/19
78.57% Branches 11/14
100% Functions 4/4
100% Lines 16/16

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                                            6x                               5x   1x 1x 3x 3x 3x 3x 2x             2x   3x   1x 2x 1x 2x 2x      
import { runQuery } from "@/lib/neo4j";
import { SOURCE_KIND as DEVICE_KIND } from "@/lib/patient/app-wearables";
import type { OwnHealth, OwnSeries } from "@/lib/patient/own-health";
 
interface Row {
  kind: "device" | "lab" | null;
  code: string | null;
  display: string | null;
  unit: string | null;
  date: string | null;
  value: number | null;
}
 
/**
 * The values the Klarbefund app put into a record it created, grouped into
 * series. Null for any other record: a demo persona's record is synthetic
 * and keeps the illustrative cards. Only the patient's own record reaches
 * this (GET /api/patient, own-record branch).
 */
export async function loadOwnHealth(
  patientId: string,
): Promise<OwnHealth | null> {
  const rows = await runQuery<Row>(
    `MATCH (p:Patient {id: $patientId, sandbox: true})
     OPTIONAL MATCH (p)-[:HAS_OBSERVATION]->(o:Observation {contributedBy: 'klarbefund-app'})
     WHERE o.code IS NOT NULL AND toFloat(o.valueQuantity) IS NOT NULL
     RETURN CASE WHEN o IS NULL THEN null
                 WHEN o.sourceKind = $deviceKind THEN 'device'
                 ELSE 'lab' END                              AS kind,
            o.code                                           AS code,
            coalesce(o.display, o.code)                      AS display,
            coalesce(o.unit, '')                             AS unit,
            toString(coalesce(o.effectiveDate, o.effectiveStart)) AS date,
            toFloat(o.valueQuantity)                         AS value
     ORDER BY date`,
    { patientId, deviceKind: DEVICE_KIND },
  );
  // No row at all: not a record the app created.
  if (rows.length === 0) return null;
 
  const series = new Map<string, OwnSeries & { kind: "device" | "lab" }>();
  for (const r of rows) {
    Iif (!r.kind || !r.code || r.value === null || !r.date) continue;
    const key = `${r.kind}|${r.code}|${r.unit}`;
    let s = series.get(key);
    if (!s) {
      s = {
        kind: r.kind,
        code: r.code,
        display: r.display ?? r.code,
        unit: r.unit ?? "",
        points: [],
      };
      series.set(key, s);
    }
    s.points.push({ date: r.date, value: r.value });
  }
  const all = [...series.values()];
  const strip = ({ kind: _kind, ...s }: OwnSeries & { kind: string }) => s;
  return {
    devices: all.filter((s) => s.kind === "device").map(strip),
    labs: all.filter((s) => s.kind === "lab").map(strip),
  };
}