All files / src/app/api/patient/observations route.ts

100% Statements 26/26
94.44% Branches 17/18
100% Functions 2/2
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                1x                                       13x 13x 11x 11x 11x 11x 11x 1x         10x 10x     3x 3x 1x                   9x 9x         8x 1x   7x 2x 2x 3x         2x   7x   1x                  
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";
import { loadObservationBundle } from "@/lib/patient/observation-bundle";
import { loadRecordExtras } from "@/lib/patient/record-extras";
import { ownPatientIdForSession } from "@/lib/overview/patient";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
 
export const dynamic = "force-dynamic";
 
/**
 * GET /api/patient/observations?patientId=<id>[&code=<loinc>][&include=all]
 *
 * With `include=all` the Bundle also carries the record's DiagnosticReports
 * (ECG, imaging), Immunizations and MedicationStatements (ADR-059), the
 * EHDS Art. 14 categories an ePA or EHR integrator asks for next; without it
 * the Bundle is Observations only, as the Klarbefund app expects.
 *
 * Regulation (EU) 2025/327 Art. 3 (access to one's own electronic health
 * data) and Art. 14 (priority category: laboratory results). Returns the
 * patient's Observations as a FHIR R4 searchset Bundle, each with the
 * reference range the laboratory printed, grouped by nothing: one entry per
 * measurement, oldest first per code.
 *
 * Requires PATIENT or EDC_ADMIN. A PATIENT reads their own record only
 * (issue #271 M1); the demo users patient1 and patient2 own P1 and P2.
 */
export async function GET(req: Request) {
  const auth = await requireAuth(["PATIENT", "EDC_ADMIN"]);
  if (isAuthError(auth)) return auth;
  const url = new URL(req.url);
  const patientId = url.searchParams.get("patientId");
  const code = url.searchParams.get("code");
  const includeAll = url.searchParams.get("include") === "all";
  if (!patientId) {
    return NextResponse.json(
      { error: "patientId is required" },
      { status: 400 },
    );
  }
  const { roles } = auth.session;
  if (roles.includes("PATIENT") && !roles.includes("EDC_ADMIN")) {
    // ownPatientIdForSession needs preferredUsername, which AuthSession does
    // not carry, so read the full session as well (as /api/patient does).
    const own = ownPatientIdForSession(await getServerSession(authOptions));
    if (!own || own !== patientId) {
      return NextResponse.json(
        {
          error: "Forbidden",
          reason: "Art. 3: a patient reads their own record only",
        },
        { status: 403 },
      );
    }
  }
 
  try {
    const bundle = await loadObservationBundle(
      patientId,
      `${url.pathname}${url.search}`,
      code,
    );
    if (!bundle) {
      return NextResponse.json({ error: "Patient not found" }, { status: 404 });
    }
    if (includeAll) {
      const extras = await loadRecordExtras(patientId);
      bundle.entry.push(
        ...extras.map((resource) => ({
          fullUrl: `urn:uuid:${resource.id}`,
          resource,
        })),
      );
      bundle.total = bundle.entry.length;
    }
    return NextResponse.json(bundle);
  } catch (err) {
    return NextResponse.json(
      {
        error: "Neo4j unavailable",
        detail: err instanceof Error ? err.message : String(err),
      },
      { status: 502 },
    );
  }
}