All files / src/app/api/patient/documents/lab-report route.ts

95% Statements 19/20
100% Branches 10/10
100% Functions 2/2
94.44% Lines 17/18

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                    1x                             6x 6x 5x 5x 5x 4x 4x 4x 4x 1x   3x 3x 2x   6x 1x         2x                    
import { NextResponse } from "next/server";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import {
  documentScope,
  fhirJson,
  neo4jUnavailable,
} from "@/lib/fhir-documents/access";
import { buildLabReportDocument } from "@/lib/fhir-documents/lab-report";
import { loadDocumentPatient, loadLabReports } from "@/lib/fhir-documents/load";
 
export const dynamic = "force-dynamic";
 
/**
 * GET /api/patient/documents/lab-report?patientId=<id>[&reportId=<id>]
 *
 * One laboratory report as a FHIR R4 `document` Bundle (#1171), HL7 Europe
 * Laboratory Report 2.1.0: Composition, DiagnosticReport, its Observations,
 * the performing laboratory and a Provenance; a value the Klarbefund app read
 * off paper keeps the page and line it came from. Without `reportId`, the
 * newest report. `/api/patient/documents` lists the report ids. EHDS
 * Art. 14(1)(e).
 *
 * PATIENT (own record only, shown under their pseudonym) or EDC_ADMIN.
 */
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 scope = await documentScope(auth.session.roles, url);
  if (scope instanceof NextResponse) return scope;
  const reportId = url.searchParams.get("reportId");
  try {
    const patient = await loadDocumentPatient(scope.patientId);
    if (!patient) {
      return NextResponse.json({ error: "Patient not found" }, { status: 404 });
    }
    const reports = await loadLabReports(scope.patientId);
    const report = reportId
      ? reports.find((r) => r.reportId === reportId)
      : reports[0];
    if (!report) {
      return NextResponse.json(
        { error: "Not found", reason: "no such laboratory report" },
        { status: 404 },
      );
    }
    return fhirJson(
      buildLabReportDocument(patient, report, {
        timestamp: new Date().toISOString(),
        identity: scope.identity,
      }),
    );
  } catch (err) {
    return neo4jUnavailable(err);
  }
}