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

98.27% Statements 57/58
75.49% Branches 77/102
100% Functions 9/9
100% Lines 47/47

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                      1x                     12x 12x 10x 10x   10x 10x   12x   2x                                             2x         8x 8x                 7x                                                                                                             7x 1x     6x   6x     12x 12x 12x   12x 136x 108x   12x                   12x           12x           12x           12x 12x             12x           12x           12x             12x         12x               12x                 12x               12x                       12x               12x 12x     12x 12x 6x 6x 6x 6x   6x                                                                                              
import { NextResponse } from "next/server";
import { runQuery } from "@/lib/neo4j";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import {
  isPatientOnly,
  ownRecordId,
  refuseForeignRecord,
} from "@/lib/patient/own-record";
import { HEALTH_INTERESTS } from "@/lib/patient/interests";
import { ownRecordView } from "@/lib/patient-identity";
 
export const dynamic = "force-dynamic";
 
/**
 * GET /api/patient/profile?patientId=<id>
 *
 * GDPR Art. 15 / EHDS Art. 3 — Patient right to access own health data.
 * Returns patient demographics, conditions, medications, and computed
 * risk scores derived from FHIR clinical events.
 * Requires PATIENT or EDC_ADMIN role (BSI C5 IAM-01 / GDPR Art. 25).
 */
export async function GET(req: Request) {
  const auth = await requireAuth(["PATIENT", "EDC_ADMIN"]);
  if (isAuthError(auth)) return auth;
  const { searchParams } = new URL(req.url);
  const patientId = searchParams.get("patientId");
  // A patient lists and opens their own record, nobody else's (#475).
  const patientOnly = isPatientOnly(auth.session.roles);
  const own = patientOnly ? await ownRecordId() : null;
 
  if (!patientId) {
    // List mode — top 20 patients for the demo; a patient's own record only.
    const patients = await runQuery<{
      id: string;
      name: string;
      gender: string;
      birthDate: string;
      conditionCount: number;
    }>(
      `MATCH (p:Patient)
       WITH p WHERE $own IS NULL
                OR coalesce(p.id, p.resourceId, elementId(p)) = $own
       OPTIONAL MATCH (p)-[:HAS_CONDITION]->(c:Condition)
       RETURN coalesce(p.id, p.resourceId, elementId(p)) AS id,
              // A Klarbefund record by its account (kb-...), as its owner
              // signs in; otherwise every one is "Klarbefund sandbox".
              coalesce(p.appAccount, p.name, 'Anonymous') AS name,
              coalesce(p.gender, 'unknown') AS gender,
              coalesce(p.birthDate, '') AS birthDate,
              count(c) AS conditionCount
       ORDER BY conditionCount DESC
       LIMIT 20`,
      { own: patientOnly ? own ?? "__no_record__" : null },
    );
    // A patient sees their own record under its pseudonym, with an age (#475).
    return NextResponse.json({
      patients: patientOnly ? patients.map(ownRecordView) : patients,
    });
  }
 
  const foreign = await refuseForeignRecord(auth.session.roles, patientId);
  if (foreign) return foreign;
 
  // Profile mode — full health profile for one patient
  const [
    patientRows,
    conditionRows,
    medicationRows,
    observationRows,
    totalCountRows,
  ] = await Promise.all([
    runQuery<{
      id: string;
      name: string;
      gender: string;
      birthDate: string;
      chosenInterests: string[] | 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.appAccount, p.name, 'Anonymous') AS name,
                coalesce(p.gender, 'unknown') AS gender,
                coalesce(p.birthDate, '') AS birthDate,
                p.interests AS chosenInterests
         LIMIT 1`,
      { patientId },
    ),
    runQuery<{ code: string; display: string; onsetDate: string }>(
      `MATCH (p:Patient)-[:HAS_CONDITION]->(c:Condition)
         WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId
         RETURN coalesce(c.code, '') AS code,
                coalesce(c.display, c.code, 'Unknown') AS display,
                coalesce(c.onsetDate, c.date, '') AS onsetDate
         ORDER BY c.onsetDate DESC
         LIMIT 20`,
      { patientId },
    ),
    runQuery<{ code: string; display: string }>(
      `MATCH (p:Patient)-[:HAS_MEDICATION_REQUEST]->(m:MedicationRequest)
         WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId
         RETURN coalesce(m.medicationCode, '') AS code,
                coalesce(m.medicationDisplay, m.medicationCode, 'Unknown') AS display
         LIMIT 10`,
      { patientId },
    ),
    runQuery<{ code: string; display: string; value: string; unit: string }>(
      `MATCH (p:Patient)-[:HAS_OBSERVATION]->(o:Observation)
         WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId
           AND o.category = 'laboratory'
         RETURN coalesce(o.code, '') AS code,
                coalesce(o.display, o.code, 'Unknown') AS display,
                coalesce(toString(o.valueQuantity), '') AS value,
                coalesce(o.unit, '') AS unit
         LIMIT 10`,
      { patientId },
    ),
    runQuery<{ total: number }>(
      `MATCH (p:Patient)-[:HAS_CONDITION]->(c:Condition)
         WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId
         RETURN count(c) AS total`,
      { patientId },
    ),
  ]);
 
  if (patientRows.length === 0) {
    return NextResponse.json({ error: "Patient not found" }, { status: 404 });
  }
 
  const { chosenInterests, ...patientRow } = patientRows[0];
  // A patient sees their own record under its pseudonym, with an age (#475).
  const patient = patientOnly ? ownRecordView(patientRow) : patientRow;
 
  // Compute risk scores: ICD codes + SNOMED codes + social determinants of health
  const conditionCodes = conditionRows.map((c) => c.code.toLowerCase());
  const conditionDisplays = conditionRows.map((c) => c.display.toLowerCase());
  const totalConditionCount = totalCountRows[0]?.total ?? conditionRows.length;
 
  const has = (codes: string[], terms: string[]) =>
    codes.some((c) => terms.some((t) => c.includes(t))) ||
    conditionDisplays.some((d) => terms.some((t) => d.includes(t)));
 
  const hasCardioCondition = has(conditionCodes, [
    "i21",
    "i10",
    "410.",
    "414.",
    "z82.49",
    "38341003",
    "53741008",
    "44054006",
  ]);
  const hasDiabetes = has(conditionCodes, [
    "e11",
    "250.",
    "73211009",
    "44054006",
  ]);
  const hasHypertension = has(conditionCodes, [
    "i10",
    "38341003",
    "hypertension",
    "blood pressure",
  ]);
  const hasObesity = has(conditionCodes, [
    "e66",
    "obesity",
    "overweight",
    "bmi",
  ]);
  const hasAtrial = has(conditionCodes, ["i48", "atrial", "fibrillation"]);
  const hasSmoking = has(conditionCodes, [
    "tobacco",
    "smoke",
    "nicotine",
    "f17",
  ]);
  // Social determinants — clinically validated cardiovascular risk amplifiers
  const hasStress = has(conditionCodes, [
    "73595000",
    "stress",
    "anxiety",
    "f41",
  ]);
  const hasSocialIsolation = has(conditionCodes, [
    "423315002",
    "social contact",
    "isolation",
    "lonely",
  ]);
  const hasAdverseEvents = has(conditionCodes, [
    "706893006",
    "abuse",
    "violence",
    "trauma",
    "victim",
  ]);
  const hasUnemployment = has(conditionCodes, [
    "73438004",
    "unemployed",
    "employment",
  ]);
  const hasDepression = has(conditionCodes, [
    "f32",
    "f33",
    "depression",
    "depressive",
  ]);
 
  // SDOH risk contribution (evidence-based: each adds 10-15% CVD risk)
  const sdohScore =
    (hasStress ? 0.15 : 0) +
    (hasSocialIsolation ? 0.1 : 0) +
    (hasAdverseEvents ? 0.12 : 0) +
    (hasUnemployment ? 0.08 : 0) +
    (hasDepression ? 0.1 : 0);
 
  // Condition burden: high count signals multimorbidity
  const burdenScore =
    totalConditionCount >= 20
      ? 0.2
      : totalConditionCount >= 10
        ? 0.15
        : totalConditionCount >= 5
          ? 0.1
          : 0.05;
 
  const cardiovascularScore = Math.min(
    1,
    (hasCardioCondition ? 0.4 : 0) +
      (hasDiabetes ? 0.2 : 0) +
      (hasHypertension ? 0.2 : 0) +
      (hasAtrial ? 0.2 : 0) +
      (hasObesity ? 0.1 : 0) +
      (hasSmoking ? 0.15 : 0) +
      sdohScore +
      burdenScore,
  );
 
  const diabetesScore = Math.min(
    1,
    (hasDiabetes ? 0.6 : 0) +
      (hasObesity ? 0.2 : 0) +
      (hasSmoking ? 0.1 : 0) +
      burdenScore,
  );
 
  const riskLevel = (score: number) =>
    score >= 0.5 ? "high" : score >= 0.25 ? "moderate" : "low";
 
  // Interests derived from conditions
  const interests: string[] = ["preventive-care"];
  if (hasCardioCondition || hasHypertension) interests.push("cardiology");
  if (hasDiabetes) interests.push("endocrinology");
  Iif (totalConditionCount > 5) interests.push("chronic-disease-management");
  if (hasStress || hasDepression) interests.push("mental-health");
  interests.push("longevity");
 
  return NextResponse.json({
    patient,
    conditions: conditionRows,
    medications: medicationRows,
    observations: observationRows,
    totalConditionCount,
    riskScores: {
      cardiovascular: {
        score: Math.round(cardiovascularScore * 100) / 100,
        level: riskLevel(cardiovascularScore),
        factors: [
          hasCardioCondition && "cardiovascular disease history",
          hasDiabetes && "diabetes",
          hasHypertension && "hypertension",
          hasAtrial && "atrial fibrillation",
          hasObesity && "obesity",
          hasSmoking && "smoking",
          hasStress && "chronic stress (SDOH)",
          hasSocialIsolation && "social isolation (SDOH)",
          hasAdverseEvents && "adverse life events (SDOH)",
          hasUnemployment && "unemployment (SDOH)",
          hasDepression && "depression",
        ].filter(Boolean),
      },
      diabetes: {
        score: Math.round(diabetesScore * 100) / 100,
        level: riskLevel(diabetesScore),
        factors: [
          hasDiabetes && "diabetes mellitus diagnosis",
          hasObesity && "obesity",
          hasSmoking && "smoking",
        ].filter(Boolean),
      },
    },
    // The patient's own choice when they made one, else what the record
    // suggests (PUT /api/patient/profile/interests).
    interests: chosenInterests ?? interests,
    interestsChosen: Array.isArray(chosenInterests),
    suggestedInterests: HEALTH_INTERESTS,
    gdprRights: {
      rightToAccess: "GDPR Art. 15",
      rightToPortability: "GDPR Art. 20",
      rightToRectification: "GDPR Art. 16",
      ehdsAccess: "EHDS Art. 3",
    },
  });
}