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

94% Statements 47/50
70% Branches 35/50
100% Functions 8/8
95.65% Lines 44/46

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                                4x               4x                     4x                                             9x                                                 9x 20x 20x 96x         20x 20x 20x                         20x 20x             16x 16x 20x   20x     20x 12x   6x 6x                                       6x 6x 12x   6x           6x 6x                                                   6x                 6x                           1x 1x                   6x                                                                                 6x   2x         12x                   4x 2x 2x               2x   4x         2x 1x             3x 3x            
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import {
  birthYear,
  ownRecordView,
  patientPseudonym,
  seesPatientIdentity,
} from "@/lib/patient-identity";
import { runQuery } from "@/lib/neo4j";
import { forRoles } from "@/lib/opt-out";
import { ownPatientIdForSession } from "@/lib/overview/patient";
import { ehrSyncFromRow } from "@/lib/patient/ehr-sync";
import { loadOwnHealth } from "@/lib/patient/load-own-health";
 
export const dynamic = "force-dynamic";
 
/**
 * Maps demo patient usernames to their assigned FHIR Patient resource IDs.
 * In production this would come from an identity provider claim or mapping table.
 * patient1 = first Synthea patient (AlphaKlinik Berlin)
 * patient2 = second Synthea patient (Limburg Medical Centre)
 */
const PATIENT_RESOURCE_MAP: Record<string, number> = {
  patient1: 0, // first patient by name order
  patient2: 1, // second patient by name order
};
 
/**
 * Sensitive clinical entries that should not appear in a patient-facing EHR view.
 * Synthea generates death certificates, autopsy, and hospice entries for deceased
 * patients — these are inappropriate for patient self-service portals.
 * Researchers and admins see unfiltered data via /analytics or /graph.
 */
const FILTERED_DISPLAYS = [
  "cause of death",
  "death certification",
  "certificate of death",
  "autopsy",
  "hospice",
  "sudden cardiac death",
] as const;
 
interface TimelineRow {
  fhirType: string;
  fhirId: string;
  date: string;
  display: string;
  /** An Observation's value and unit; null for every other type. */
  value: string | null;
  unit: string | null;
  omopType: string;
  omopId: string;
}
 
/** One patient's clinical events with their OMOP mappings, oldest first. */
async function loadTimeline(patientId: string): Promise<TimelineRow[]> {
  const rows = await runQuery<TimelineRow>(
    `MATCH (p:Patient)
     WHERE coalesce(p.id, p.resourceId) = $patientId
     MATCH (p)-[:HAS_ENCOUNTER|HAS_CONDITION|HAS_OBSERVATION|HAS_MEDICATION|HAS_MEDICATION_REQUEST|HAS_PROCEDURE]->(fhir)
     OPTIONAL MATCH (fhir)-[:MAPPED_TO]->(omop)
     RETURN labels(fhir)[0]                                                          AS fhirType,
            coalesce(fhir.id, fhir.resourceId)                                       AS fhirId,
            coalesce(fhir.date, fhir.onsetDate, fhir.dateTime, fhir.performedStart,
                     fhir.effectiveDate)                                             AS date,
            coalesce(fhir.display, fhir.name, fhir.code)                             AS display,
            // Synthea's observations carry valueUnit, Klarbefund's unit
            // (lib/patient/app-observations.ts); without these the timeline
            // showed every value as a name only.
            toString(fhir.valueQuantity)                                             AS value,
            coalesce(fhir.valueUnit, fhir.unit)                                      AS unit,
            labels(omop)[0]                                                          AS omopType,
            coalesce(omop.id, omop.personId, omop.visitOccurrenceId,
                     omop.conditionOccurrenceId, omop.measurementId,
                     omop.drugExposureId)                                            AS omopId
     ORDER BY date`,
    { patientId },
  );
  // Filter out sensitive end-of-life entries (death certificates, hospice,
  // autopsy) that Synthea generates for deceased synthetic patients. They are
  // inappropriate for patient-facing EHR views.
  return rows.filter((row) => {
    Iif (!row.display) return true;
    const lower = row.display.toLowerCase();
    return !FILTERED_DISPLAYS.some((term) => lower.includes(term));
  });
}
 
export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url);
    const patientId = searchParams.get("patientId") ?? "";
 
    // Gated, #357 reopened. This route used to answer a caller with no
    // session, and it was the one route in the inventory reading a session
    // without enforcing it. It now matches the role matrix: no session, no
    // answer. `/patient` joins PROTECTED_PATHS in middleware.ts in the same
    // change, so an anonymous visitor is sent to sign in rather than being
    // shown an empty page.
    //
    // No role argument: any authenticated participant may see the demo
    // cohort. The session still narrows as well as admits, and that is the
    // part the tests pin: a PATIENT sees only their own record (EHDS Art. 3,
    // GDPR Art. 15), anyone else signed in sees the cohort.
    const auth = await requireAuth();
    if (isAuthError(auth)) return auth;
 
    // requireAuth hands back an AuthSession, which carries no
    // preferredUsername; ownPatientIdForSession needs it to resolve which
    // seeded record a login owns (#271). So read the full session too. In the
    // static export requireAuth returns a synthetic admin and this is null,
    // which lands on the cohort branch, which is what the fixtures show.
    const session = await getServerSession(authOptions);
    const roles = (session as { roles?: string[] } | null)?.roles ?? [];
    const username = session?.user?.name ?? "";
    const isPatientRole =
      roles.includes("PATIENT") && !roles.includes("EDC_ADMIN");
 
    // List mode: return patients + cohort stats
    if (!patientId) {
      if (isPatientRole) {
        // PATIENT role: only return their own record (EHDS Art. 3 / GDPR Art. 15)
        const patientIndex = PATIENT_RESOURCE_MAP[username] ?? 0;
        const allPatients = await runQuery<{
          id: string;
          name: string;
          gender: string;
          birthDate: string;
        }>(
          `MATCH (p:Patient)
           WHERE coalesce(p.id, p.resourceId) IS NOT NULL
           RETURN coalesce(p.id, p.resourceId) AS id,
                  // The patient's own record: a Klarbefund one is named by
                  // its account (kb-...), which is how its owner signs in;
                  // every one of them is otherwise "Klarbefund sandbox".
                  coalesce(p.appAccount, p.name) AS name,
                  p.gender    AS gender,
                  p.birthDate AS birthDate
           ORDER BY p.name
           LIMIT 200`,
        );
        // Pick only the patient's own record: the seeded one the login owns
        // (patient1 is P1, issue #271), else the older name-order fallback.
        const owned = ownPatientIdForSession(session);
        const ownRecord = owned
          ? allPatients.find((p) => p.id === owned)
          : undefined;
        const myPatient = ownRecord
          ? [ownRecord]
          : patientIndex < allPatients.length
            ? [allPatients[patientIndex]]
            : allPatients.slice(0, 1);
        // Stats for just this patient
        const myId = myPatient[0]?.id;
        const myStats = myId
          ? await runQuery<{
              encounters: number;
              conditions: number;
              observations: number;
              medications: number;
              procedures: number;
              ehrSyncedAt: string | null;
              ehrSyncSource: string | null;
            }>(
              `MATCH (p:Patient) WHERE coalesce(p.id, p.resourceId) = $myId
               OPTIONAL MATCH (p)-[:HAS_ENCOUNTER]->(e:Encounter)
               WITH p, count(e) AS encounters
               OPTIONAL MATCH (p)-[:HAS_CONDITION]->(c:Condition)
               WITH p, encounters, count(c) AS conditions
               OPTIONAL MATCH (p)-[:HAS_OBSERVATION]->(o:Observation)
               WITH p, encounters, conditions, count(o) AS observations
               OPTIONAL MATCH (p)-[:HAS_MEDICATION|HAS_MEDICATION_REQUEST]->(m:MedicationRequest)
               WITH p, encounters, conditions, observations, count(m) AS medications
               OPTIONAL MATCH (p)-[:HAS_PROCEDURE]->(pr:Procedure)
               RETURN encounters, conditions, observations, medications, count(pr) AS procedures,
                      toString(p.ehrSyncedAt) AS ehrSyncedAt,
                      p.ehrSyncSource         AS ehrSyncSource`,
              { myId },
            )
          : [];
        const { ehrSyncedAt, ehrSyncSource, ...counts } = myStats[0] ?? {
          encounters: 0,
          conditions: 0,
          observations: 0,
          medications: 0,
          procedures: 0,
          ehrSyncedAt: null,
          ehrSyncSource: null,
        };
        return NextResponse.json({
          // Their own record, under its pseudonym and with an age (#475).
          patients: myPatient.map(ownRecordView),
          stats: { patients: 1, ...counts },
          // The page renders this timeline directly for the own record.
          timeline: myId ? await loadTimeline(myId) : [],
          // When the ePA was last transferred into the portal, if ever.
          lastEhrSync: ehrSyncFromRow({ ehrSyncedAt, ehrSyncSource }),
          // A record the Klarbefund app created: the person's own device
          // trends and lab values, for the cards that otherwise show an
          // illustration. Null for a demo persona's synthetic record.
          // A failure here costs the cards, never the record.
          ownHealth: myId
            ? await loadOwnHealth(myId).catch((err) => {
                console.error("GET /api/patient own health:", err);
                return null;
              })
            : null,
          restricted: true, // signal to the UI that patient selector should be hidden
        });
      }
 
      // Non-patient roles: return all patients + full cohort stats. For a data
      // user, an access body or a trust centre that is secondary use, and the
      // persons who opted out are left out (Art. 71, ADR-062).
      const [patients, stats] = await Promise.all([
        runQuery<{
          id: string;
          name: string;
          gender: string;
          birthDate: string;
        }>(
          forRoles(
            `MATCH (p:Patient)
           WHERE coalesce(p.id, p.resourceId) IS NOT NULL
           RETURN coalesce(p.id, p.resourceId) AS id,
                  p.name      AS name,
                  p.gender    AS gender,
                  p.birthDate AS birthDate
           ORDER BY p.name
           LIMIT 200`,
            roles,
          ),
        ),
        runQuery<{
          patients: number;
          encounters: number;
          conditions: number;
          observations: number;
          medications: number;
          procedures: number;
        }>(
          forRoles(
            `MATCH (p:Patient)   WITH count(p) AS patients
           MATCH (e:Encounter)  WITH patients, count(e) AS encounters
           MATCH (c:Condition)  WITH patients, encounters, count(c) AS conditions
           MATCH (o:Observation) WITH patients, encounters, conditions, count(o) AS observations
           OPTIONAL MATCH (m:MedicationRequest) WITH patients, encounters, conditions, observations, count(m) AS medications
           OPTIONAL MATCH (pr:Procedure)
           RETURN patients, encounters, conditions, observations, medications, count(pr) AS procedures`,
            roles,
          ),
        ),
      ]);
      // A researcher, an access body or a trust centre sees the cohort under
      // pseudonyms and birth years, never names and birth dates (#475).
      const shown = seesPatientIdentity(roles)
        ? patients
        : patients.map((p) => ({
            ...p,
            name: patientPseudonym(p.id),
            birthDate: birthYear(p.birthDate) ?? "",
          }));
      return NextResponse.json({
        patients: shown,
        stats: stats[0] ?? {},
        timeline: [],
        restricted: false,
      });
    }
 
    // Timeline mode: FHIR clinical events + OMOP mappings for one patient
    // If PATIENT role, verify they're requesting their own record
    if (isPatientRole) {
      const patientIndex = PATIENT_RESOURCE_MAP[username] ?? 0;
      const allPatients = await runQuery<{ id: string }>(
        `MATCH (p:Patient)
         WHERE coalesce(p.id, p.resourceId) IS NOT NULL
         RETURN coalesce(p.id, p.resourceId) AS id
         ORDER BY p.name LIMIT 200`,
      );
      // The seeded record the login owns (patient1 is P1, issue #271), else
      // the older name-order fallback.
      const owned = ownPatientIdForSession(session);
      const myId =
        owned && allPatients.some((p) => p.id === owned)
          ? owned
          : patientIndex < allPatients.length
            ? allPatients[patientIndex].id
            : allPatients[0]?.id;
      if (patientId !== myId) {
        return NextResponse.json(
          { error: "Access denied — you can only view your own health data" },
          { status: 403 },
        );
      }
    }
 
    const filtered = await loadTimeline(patientId);
    return NextResponse.json({ timeline: filtered });
  } catch (err) {
    console.error("GET /api/patient error:", err);
    return NextResponse.json({ error: "Neo4j unavailable" }, { status: 502 });
  }
}