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 | 1x 8x 8x 8x 1x 7x 1x 6x 6x 6x 1x 1x 5x 5x 1x 4x 4x 4x 4x 8x 136x 108x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 4x 4x | import { getServerSession } from "next-auth/next";
import { NextResponse } from "next/server";
import { runQuery } from "@/lib/neo4j";
import { authOptions } from "@/lib/auth";
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 session = await getServerSession(authOptions);
const roles = (session as { roles?: string[] } | null)?.roles ?? [];
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
if (!roles.includes("PATIENT") && !roles.includes("EDC_ADMIN")) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { searchParams } = new URL(req.url);
const patientId = searchParams.get("patientId");
if (!patientId) {
// List mode — return top 20 patients for demo
const patients = await runQuery<{
id: string;
name: string;
gender: string;
birthDate: string;
conditionCount: number;
}>(
`MATCH (p:Patient)
OPTIONAL MATCH (p)-[:HAS_CONDITION]->(c:Condition)
RETURN coalesce(p.id, p.resourceId, elementId(p)) AS id,
coalesce(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`,
);
return NextResponse.json({ patients });
}
// 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;
}>(
`MATCH (p:Patient)
WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId
RETURN coalesce(p.id, p.resourceId, elementId(p)) AS id,
coalesce(p.name, 'Anonymous') AS name,
coalesce(p.gender, 'unknown') AS gender,
coalesce(p.birthDate, '') AS birthDate
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 patient = patientRows[0];
// 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),
},
},
interests,
gdprRights: {
rightToAccess: "GDPR Art. 15",
rightToPortability: "GDPR Art. 20",
rightToRectification: "GDPR Art. 16",
ehdsAccess: "EHDS Art. 3",
},
});
}
|