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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 | 3x 3x 3x 21x 14x 14x 14x 14x 14x 14x 17x 17x 18x 8x 8x 8x 4x 8x 8x 3x 3x 3x 3x 1x 1x 1x 1x 15x 13x 3x 19x 17x 17x 5x 8x 5x 7x 7x 7x 7x 7x 3x 19x 3x 3x 1x 1x 15x 17x 14x 17x 17x 6x 6x 17x 17x 19x 28x 28x 27x 27x 189x 28x 28x 28x 19x 25x 25x 5x 47x 25x 2x 2x 2x 2x | import { NextResponse } from "next/server";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { patientPseudonym, seesPatientIdentity } from "@/lib/patient-identity";
import neo4j from "neo4j-driver";
import { runQuery } from "@/lib/neo4j";
import { secondaryUseView } from "@/lib/opt-out";
import { cached } from "@/lib/server-cache";
import {
LABEL_LAYER,
LAYER_COLORS,
NODE_ROLE_COLORS,
LABEL_SORT_ORDER,
LABEL_GROUP,
PERSONA_VIEWS,
type PersonaId,
} from "@/lib/graph-constants";
export const dynamic = "force-dynamic";
// Governance + catalog labels — always included in researcher overview
const GOVERNANCE_LABELS = [
"Participant",
"DataProduct",
"OdrlPolicy",
"Contract",
"HDABApproval",
"ContractNegotiation",
"HealthDataset",
"Distribution",
"EEHRxFProfile",
"VerifiableCredential",
"EhdsPurpose",
"Catalogue",
"Organization",
"TrustCenter",
"SPESession",
];
/**
* How many of a log-like label a view shows: the newest ones. TransferEvent
* is the access log (one per data access, kept 12 months, Art. 73) and
* DataTransfer one per transfer; both grow with use. Selected in full, the
* default view reached 10,521 TransferEvents and 6 MB per call after a day
* of load tests, and serialising it pinned the UI's CPU (#571).
*/
const NEWEST_EVENTS = 30;
/** The newest `NEWEST_EVENTS` nodes of a log-like label, by timestamp. */
function newestOf(label: "TransferEvent" | "DataTransfer") {
return runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (n:${label})
WITH n ORDER BY n.timestamp DESC LIMIT $limit
RETURN elementId(n) AS id, labels(n) AS labels,
coalesce(n.transferId, n.endpoint + ' ' + n.method, n.endpoint,
n.eventId, n.id, elementId(n)) AS name`,
{ limit: neo4j.int(NEWEST_EVENTS) },
);
}
function toNode(r: { id: string; labels: string[]; name: string }) {
const label = r.labels[0] ?? "Node";
const layer = r.labels.map((l) => LABEL_LAYER[l]).find(Boolean) ?? 0;
const color = NODE_ROLE_COLORS[label] ?? LAYER_COLORS[layer] ?? "#888";
const group = LABEL_GROUP[label] ?? "other";
const sortKey = LABEL_SORT_ORDER[label] ?? 99;
return {
id: r.id,
name: r.name,
label,
layer,
color,
group,
sortKey,
expandable: true,
};
}
function sortAndDedup(rows: { id: string; labels: string[]; name: string }[]) {
const seen = new Set<string>();
return rows
.filter((r) => (seen.has(r.id) ? false : seen.add(r.id) && true))
.sort((a, b) => {
const la = a.labels.map((l) => LABEL_LAYER[l]).find(Boolean) ?? 0;
const lb = b.labels.map((l) => LABEL_LAYER[l]).find(Boolean) ?? 0;
if (la !== lb) return la - lb;
const sa = LABEL_SORT_ORDER[a.labels[0] ?? ""] ?? 99;
const sb = LABEL_SORT_ORDER[b.labels[0] ?? ""] ?? 99;
if (sa !== sb) return sa - sb;
return (a.name ?? "").localeCompare(b.name ?? "");
})
.map(toNode);
}
// ── Persona-specific subgraph builders ───────────────────────────────────────
/** Trust Center: pseudonym resolution chains + governed datasets + cross-border */
async function buildTrustCenterGraph() {
const [tcNodes, speNodes, rpsnNodes, datasetNodes] = await Promise.all([
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (tc:TrustCenter)
OPTIONAL MATCH (tc)-[:GOVERNED_BY]->(ha:HDABApproval)
WITH tc, ha
RETURN elementId(tc) AS id, labels(tc) AS labels, tc.name AS name
UNION
MATCH (ha:HDABApproval)
RETURN elementId(ha) AS id, labels(ha) AS labels,
coalesce(ha.approvalId, elementId(ha)) AS name`,
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (ss:SPESession)
RETURN elementId(ss) AS id, labels(ss) AS labels,
coalesce(ss.studyId, ss.sessionId, elementId(ss)) AS name
ORDER BY ss.createdAt DESC LIMIT 20`,
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (rp:ResearchPseudonym {revoked: false})
RETURN elementId(rp) AS id, labels(rp) AS labels,
coalesce(rp.studyId, rp.rpsnId, elementId(rp)) AS name
LIMIT 20
UNION
MATCH (pp:ProviderPseudonym)
RETURN elementId(pp) AS id, labels(pp) AS labels,
coalesce(pp.providerId, pp.psnId, elementId(pp)) AS name
LIMIT 20`,
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (tc:TrustCenter)-[:RESOLVES_PSEUDONYMS_FOR]->(ds:HealthDataset)
RETURN elementId(ds) AS id, labels(ds) AS labels,
coalesce(ds.title, ds.datasetId, elementId(ds)) AS name`,
),
]);
return sortAndDedup([...tcNodes, ...speNodes, ...rpsnNodes, ...datasetNodes]);
}
/** Hospital / Data Holder: their datasets, data products, active contracts, who has access */
async function buildHospitalGraph() {
const [
participantNodes,
datasetNodes,
productNodes,
contractNodes,
credNodes,
] = await Promise.all([
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (p:Participant)
RETURN elementId(p) AS id, labels(p) AS labels,
coalesce(p.name, p.participantId, elementId(p)) AS name
ORDER BY p.name`,
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (ds:HealthDataset)
RETURN elementId(ds) AS id, labels(ds) AS labels,
coalesce(ds.title, ds.datasetId, elementId(ds)) AS name
ORDER BY ds.title LIMIT 30
UNION
MATCH (d:Distribution)
RETURN elementId(d) AS id, labels(d) AS labels,
coalesce(d.name, d.title, d.format, d.distributionId, elementId(d)) AS name
LIMIT 20
UNION
MATCH (ep:EEHRxFProfile)
RETURN elementId(ep) AS id, labels(ep) AS labels,
coalesce(ep.title, ep.profileId, elementId(ep)) AS name
LIMIT 15`,
),
// DataProduct — the offerings participants publish
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (dp:DataProduct)
RETURN elementId(dp) AS id, labels(dp) AS labels,
coalesce(dp.name, dp.title, dp.productId, elementId(dp)) AS name
LIMIT 20`,
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (c:Contract)
RETURN elementId(c) AS id, labels(c) AS labels,
coalesce(c.name, c.contractId, elementId(c)) AS name
UNION
MATCH (ha:HDABApproval)
RETURN elementId(ha) AS id, labels(ha) AS labels,
coalesce(ha.name, ha.approvalId, elementId(ha)) AS name
UNION
MATCH (aa:AccessApplication)
RETURN elementId(aa) AS id, labels(aa) AS labels,
coalesce(aa.name, aa.applicationId, elementId(aa)) AS name`,
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (vc:VerifiableCredential)
RETURN elementId(vc) AS id, labels(vc) AS labels,
coalesce(vc.credentialType, vc.credentialId, elementId(vc)) AS name
ORDER BY vc.credentialType LIMIT 20`,
),
]);
return sortAndDedup([
...participantNodes,
...datasetNodes,
...productNodes,
...contractNodes,
...credNodes,
]);
}
/** Researcher: datasets + OMOP analytics + pseudonym chain + clinical conditions */
async function buildResearcherGraph() {
// The researcher's view is secondary use: persons who opted out are not in
// it (Art. 71, ADR-062).
const researcherQuery = <T>(cypher: string) =>
runQuery<T>(secondaryUseView(cypher));
const [datasetNodes, omopNodes, conditionNodes, ontologyNodes, speNodes] =
await Promise.all([
researcherQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (ds:HealthDataset)
RETURN elementId(ds) AS id, labels(ds) AS labels,
coalesce(ds.title, ds.datasetId, elementId(ds)) AS name
ORDER BY ds.title LIMIT 20
UNION
MATCH (dp:DataProduct)
RETURN elementId(dp) AS id, labels(dp) AS labels,
coalesce(dp.name, dp.productId, elementId(dp)) AS name
LIMIT 15
UNION
MATCH (ep:EEHRxFProfile)
RETURN elementId(ep) AS id, labels(ep) AS labels,
coalesce(ep.title, ep.profileId, elementId(ep)) AS name
LIMIT 10`,
),
researcherQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (op:OMOPPerson)-[:HAS_CONDITION_OCCURRENCE]->(:OMOPConditionOccurrence)
WITH op, count(*) AS cnt ORDER BY cnt DESC LIMIT 15
RETURN elementId(op) AS id, labels(op) AS labels,
coalesce(op.name, toString(op.personId), elementId(op)) AS name
UNION
MATCH (oc:OMOPConditionOccurrence)<-[:HAS_CONDITION_OCCURRENCE]-(:OMOPPerson)
WITH oc, count(*) AS freq ORDER BY freq DESC LIMIT 30
RETURN elementId(oc) AS id, labels(oc) AS labels,
coalesce(oc.name, toString(oc.conditionConceptId), elementId(oc)) AS name
UNION
MATCH (om:OMOPMeasurement)
RETURN elementId(om) AS id, labels(om) AS labels,
coalesce(om.name, toString(om.measurementConceptId), elementId(om)) AS name
LIMIT 10`,
),
researcherQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (c:Condition)<-[:HAS_CONDITION]-(:Patient)
WITH c, count(*) AS freq ORDER BY freq DESC LIMIT 30
RETURN elementId(c) AS id, labels(c) AS labels,
coalesce(c.display, c.name, c.code, elementId(c)) AS name`,
),
researcherQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (s:SnomedConcept)
WITH s, count{(s)-[]-()} AS deg ORDER BY deg DESC LIMIT 20
RETURN elementId(s) AS id, labels(s) AS labels,
coalesce(s.display, s.code, elementId(s)) AS name
UNION
MATCH (l:LoincCode)
WITH l, count{(l)-[]-()} AS deg ORDER BY deg DESC LIMIT 10
RETURN elementId(l) AS id, labels(l) AS labels,
coalesce(l.display, l.code, elementId(l)) AS name
UNION
MATCH (rx:RxNormConcept)
WITH rx, count{(rx)-[]-()} AS deg ORDER BY deg DESC LIMIT 10
RETURN elementId(rx) AS id, labels(rx) AS labels,
coalesce(rx.display, rx.name, rx.code, elementId(rx)) AS name`,
),
researcherQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (rp:ResearchPseudonym {revoked: false})
RETURN elementId(rp) AS id, labels(rp) AS labels,
coalesce(rp.studyId, rp.rpsnId, elementId(rp)) AS name
LIMIT 10
UNION
MATCH (ss:SPESession {status: "active"})
RETURN elementId(ss) AS id, labels(ss) AS labels,
coalesce(ss.studyId, ss.sessionId, elementId(ss)) AS name
LIMIT 10`,
),
]);
return sortAndDedup([
...datasetNodes,
...omopNodes,
...conditionNodes,
...ontologyNodes,
...speNodes,
]);
}
/** EDC Admin: all participants, products, contracts, negotiations; the newest transfers */
async function buildEdcAdminGraph() {
const [transfers, accesses] = await Promise.all([
newestOf("DataTransfer"),
newestOf("TransferEvent"),
]);
const rows = await runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (n)
WHERE any(l IN labels(n) WHERE l IN $labels)
RETURN elementId(n) AS id, labels(n) AS labels,
coalesce(n.name, n.title, n.display, n.participantId, n.productId,
n.contractId, n.credentialType, n.transferId,
n.endpoint + ' ' + n.method, n.endpoint,
n.eventId, n.id, elementId(n)) AS name
ORDER BY labels(n)[0], coalesce(n.name, n.display, n.id)`,
{
labels: [
"Participant",
"Organization",
"DataProduct",
"OdrlPolicy",
"Contract",
"ContractNegotiation",
"VerifiableCredential",
],
},
);
return sortAndDedup([...rows, ...transfers, ...accesses]);
}
/** HDAB Authority: approval chains, credentials, trust center governance */
async function buildHdabGraph() {
const [govNodes, tcNodes, vcNodes] = await Promise.all([
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (n)
WHERE any(l IN labels(n) WHERE l IN $labels)
RETURN elementId(n) AS id, labels(n) AS labels,
coalesce(n.name, n.display, n.title, n.approvalId, n.applicationId,
n.contractId, n.productId, n.participantId, elementId(n)) AS name
ORDER BY labels(n)[0]`,
{
labels: [
"HDABApproval",
"AccessApplication",
"OdrlPolicy",
"Participant",
"DataProduct",
"Contract",
],
},
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (tc:TrustCenter)
RETURN elementId(tc) AS id, labels(tc) AS labels, tc.name AS name
UNION
MATCH (ss:SPESession)
RETURN elementId(ss) AS id, labels(ss) AS labels,
coalesce(ss.studyId, ss.sessionId, elementId(ss)) AS name
LIMIT 15`,
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (vc:VerifiableCredential)
RETURN elementId(vc) AS id, labels(vc) AS labels,
coalesce(vc.credentialType, vc.credentialId, elementId(vc)) AS name
ORDER BY vc.credentialType LIMIT 30`,
),
]);
return sortAndDedup([...govNodes, ...tcNodes, ...vcNodes]);
}
/** Patient: own FHIR data + governance chain showing who uses it (EHDS Art. 3-12) */
async function buildPatientGraph() {
// Anchor every slice to ONE set of patients.
//
// This previously ran five independent top-N queries: top-20 patients by
// condition count, the globally top-30 conditions, and 15 arbitrary
// OMOPPersons. Because each slice was ranked by its own criterion, the
// selected conditions were mostly not the selected patients' conditions and
// the OMOPPersons belonged to neither — so 66 of 95 returned nodes had no
// edge to anything else in the payload (measured 2026-09-09). The link query
// below is correct; it simply had nothing to join. The graph rendered as a
// dense hub surrounded by ~30 orphans, and clicking an orphan reported
// "0 connections loaded", which is computed from the loaded links.
//
// Ten patients rather than twenty, and their conditions capped per patient,
// because the old view also stacked ~50 condition labels into an unreadable
// arc around a single hub.
const anchors = await runQuery<{ id: string }>(
`MATCH (p:Patient)-[:HAS_CONDITION]->(:Condition)
WITH p, count(*) AS cnt ORDER BY cnt DESC LIMIT 10
RETURN elementId(p) AS id`,
{},
);
const anchorIds = anchors.map((a) => a.id);
const [
patientNodes,
conditionNodes,
omopNodes,
datasetNodes,
speNodes,
govNodes,
] = await Promise.all([
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (p:Patient) WHERE elementId(p) IN $anchorIds
RETURN elementId(p) AS id, labels(p) AS labels,
coalesce(p.name, p.id, elementId(p)) AS name`,
{ anchorIds },
),
// THEIR conditions, capped per patient so one rich record cannot flood
// the view. Previously the global top-30 by frequency.
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (p:Patient)-[:HAS_CONDITION]->(c:Condition)
WHERE elementId(p) IN $anchorIds
WITH p, c ORDER BY coalesce(c.display, c.code)
WITH p, collect(c)[0..4] AS cs
UNWIND cs AS c
RETURN DISTINCT elementId(c) AS id, labels(c) AS labels,
coalesce(c.display, c.code, elementId(c)) AS name`,
{ anchorIds },
),
// THEIR OMOP twins, via Patient-[:MAPPED_TO]->OMOPPerson. Previously an
// unanchored `MATCH (op:OMOPPerson) LIMIT 15`, which is why every OMOP
// node floated free.
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (p:Patient)-[:MAPPED_TO]->(op:OMOPPerson)
WHERE elementId(p) IN $anchorIds
RETURN DISTINCT elementId(op) AS id, labels(op) AS labels,
coalesce(op.name, toString(op.personId), elementId(op)) AS name`,
{ anchorIds },
),
// The datasets those patients belong to — the bridge from the clinical
// layer to the catalog/governance layer, so the two halves of the graph
// are actually joined rather than sitting side by side.
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (p:Patient)-[:FROM_DATASET]->(ds:HealthDataset)
WHERE elementId(p) IN $anchorIds
RETURN DISTINCT elementId(ds) AS id, labels(ds) AS labels,
coalesce(ds.title, ds.datasetId, elementId(ds)) AS name`,
{ anchorIds },
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (rp:ResearchPseudonym {revoked: false})
RETURN elementId(rp) AS id, labels(rp) AS labels,
coalesce(rp.studyId, rp.rpsnId, elementId(rp)) AS name
LIMIT 10
UNION
MATCH (ss:SPESession)
RETURN elementId(ss) AS id, labels(ss) AS labels,
coalesce(ss.studyId, ss.sessionId, elementId(ss)) AS name
LIMIT 5
UNION
MATCH (pc:PatientConsent {revoked: false})
RETURN elementId(pc) AS id, labels(pc) AS labels,
coalesce(pc.studyId, pc.consentId, elementId(pc)) AS name
LIMIT 10`,
{},
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (p:Participant)
RETURN elementId(p) AS id, labels(p) AS labels,
coalesce(p.name, p.participantId, elementId(p)) AS name
ORDER BY p.name
UNION
MATCH (dp:DataProduct)
RETURN elementId(dp) AS id, labels(dp) AS labels,
coalesce(dp.name, dp.productId, elementId(dp)) AS name
LIMIT 15
UNION
MATCH (ha:HDABApproval)
RETURN elementId(ha) AS id, labels(ha) AS labels,
coalesce(ha.approvalId, elementId(ha)) AS name
LIMIT 10`,
{},
),
]);
return sortAndDedup([
...govNodes,
...patientNodes,
...conditionNodes,
...omopNodes,
...datasetNodes,
...speNodes,
]);
}
// ── Default overview (unchanged from before) ─────────────────────────────────
async function buildDefaultGraph() {
const [
govNodes,
patientNodes,
conditionNodes,
snomedNodes,
loincNodes,
rxnormNodes,
accessNodes,
] = await Promise.all([
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (n) WHERE any(l IN labels(n) WHERE l IN $labels)
RETURN elementId(n) AS id, labels(n) AS labels,
coalesce(n.name, n.title, n.display, n.participantId,
n.productId, n.credentialType, n.transferId,
n.endpoint + ' ' + n.method, n.endpoint,
n.eventId, n.code, n.id, elementId(n)) AS name
ORDER BY labels(n)[0], coalesce(n.name, n.display, n.id)`,
{ labels: GOVERNANCE_LABELS },
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (p:Patient)-[:HAS_CONDITION]->(:Condition)
WITH p, count(*) AS cnt ORDER BY cnt DESC LIMIT 20
RETURN elementId(p) AS id, labels(p) AS labels,
coalesce(p.name, p.id, elementId(p)) AS name`,
{},
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (c:Condition)<-[:HAS_CONDITION]-(:Patient)
WITH c, count(*) AS freq ORDER BY freq DESC LIMIT 50
RETURN elementId(c) AS id, labels(c) AS labels,
coalesce(c.display, c.name, c.code, elementId(c)) AS name`,
{},
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (s:SnomedConcept)
WITH s, count{(s)-[]-()} AS deg ORDER BY deg DESC LIMIT 30
RETURN elementId(s) AS id, labels(s) AS labels,
coalesce(s.display, s.code, elementId(s)) AS name`,
{},
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (l:LoincCode)
WITH l, count{(l)-[]-()} AS deg ORDER BY deg DESC LIMIT 20
RETURN elementId(l) AS id, labels(l) AS labels,
coalesce(l.display, l.code, elementId(l)) AS name`,
{},
),
runQuery<{ id: string; labels: string[]; name: string }>(
`MATCH (r:RxNormConcept)
WITH r, count{(r)-[]-()} AS deg ORDER BY deg DESC LIMIT 20
RETURN elementId(r) AS id, labels(r) AS labels,
coalesce(r.display, r.name, r.code, elementId(r)) AS name`,
{},
),
newestOf("TransferEvent"),
]);
return sortAndDedup([
...govNodes,
...accessNodes,
...patientNodes,
...conditionNodes,
...snomedNodes,
...loincNodes,
...rxnormNodes,
]);
}
// ── Patient identity (#475) ─────────────────────────────────────────────────
type GraphNode = ReturnType<typeof toNode>;
const isPerson = (n: GraphNode) =>
n.label === "Patient" || n.label === "OMOPPerson";
/**
* The record id behind each Patient and OMOPPerson node, which the pseudonym
* is derived from, so the label matches the one in the patient index.
*/
async function patientKeysOf(
nodes: GraphNode[],
): Promise<Record<string, string>> {
// OMOP persons too: older transforms copied the patient's name onto them
// (neo4j/fhir-to-omop-transform.cypher step 1b repairs the data). They are
// labelled with their patient's pseudonym, so the two twins still match.
const personIds = nodes.filter(isPerson).map((n) => n.id);
if (personIds.length === 0) return {};
const keys = await runQuery<{ id: string; key: string }>(
`MATCH (p:Patient) WHERE elementId(p) IN $ids
RETURN elementId(p) AS id, coalesce(p.id, p.resourceId, elementId(p)) AS key
UNION
MATCH (p:Patient)-[:MAPPED_TO]->(op:OMOPPerson) WHERE elementId(op) IN $ids
RETURN elementId(op) AS id, coalesce(p.id, p.resourceId, elementId(p)) AS key`,
{ ids: personIds },
);
return Object.fromEntries(keys.map((k) => [k.id, k.key]));
}
/**
* Replaces each Patient node's name with its pseudonym. `own` names a record
* to leave as it is; since 2026-10-07 every caller passes null, a patient
* sees their own node pseudonymised too (#475). Returns new node objects and
* leaves the cached ones alone.
*/
function pseudonymisePatients(
nodes: GraphNode[],
patientKeys: Record<string, string>,
own: string | null,
): GraphNode[] {
return nodes.map((n) => {
Iif (!isPerson(n)) return n;
const key = patientKeys[n.id] ?? n.id;
Iif (key === own) return n;
const label = patientPseudonym(key);
return { ...n, name: n.label === "OMOPPerson" ? `OMOP ${label}` : label };
});
}
// ── One persona's graph, cached ─────────────────────────────────────────────
/**
* How long one persona's graph is reused. The graph changes on seeding and
* onboarding, not per request, and /graph is opened by every visitor: under
* load test the build (up to 34 queries, three over the whole graph) took
* Neo4j to 97 % memory and /api/graph to 10 s p95 at 50 users (#540).
*/
const GRAPH_CACHE_TTL_MS = 60_000;
interface PersonaGraph {
nodes: GraphNode[];
links: { source: string; target: string; type: string }[];
isolatedRemoved: number;
/** Record id per Patient and OMOPPerson node, for the pseudonyms. */
patientKeys: Record<string, string>;
}
/**
* Everything about a persona's graph that is the same for every caller. Who
* may see a patient's name is not: that is applied per request, after the
* cache. The cache holds names; a response carries them only to the roles
* that see identity (#475).
*/
async function buildPersonaGraph(persona: PersonaId): Promise<PersonaGraph> {
let nodes: GraphNode[];
switch (persona) {
case "trust-center":
nodes = await buildTrustCenterGraph();
break;
case "hospital":
nodes = await buildHospitalGraph();
break;
case "researcher":
nodes = await buildResearcherGraph();
break;
case "edc-admin":
nodes = await buildEdcAdminGraph();
break;
case "hdab":
nodes = await buildHdabGraph();
break;
case "patient":
nodes = await buildPatientGraph();
break;
default:
nodes = await buildDefaultGraph();
}
const links = await runQuery<{
source: string;
target: string;
type: string;
}>(
`MATCH (a)-[r]->(b)
WHERE elementId(a) IN $ids AND elementId(b) IN $ids
RETURN DISTINCT elementId(a) AS source, elementId(b) AS target, type(r) AS type`,
{ ids: nodes.map((n) => n.id) },
);
// Drop nodes that ended up with no edge in this payload.
//
// A persona builder selects nodes label-by-label, so it can pick a node
// whose neighbours it did not pick — and the link query above, which only
// joins nodes already in the set, then finds nothing for it. The result is
// a node rendered floating in space with "0 connections loaded" in the
// detail panel, which reads as missing data rather than a narrow query.
//
// The patient view was measured at 66 isolated of 95 nodes on 2026-09-09,
// while the same labels average degree 2-13 in Neo4j — none of those nodes
// is isolated in the database. This is a presentation artefact, so it is
// corrected in presentation. `isolatedRemoved` is returned so a persona
// that starts shedding nodes is visible rather than silently thinner.
const connected = new Set<string>();
for (const l of links) {
connected.add(l.source);
connected.add(l.target);
}
const linked = nodes.filter((n) => connected.has(n.id));
// Never prune the view down to nothing. A persona whose data is not seeded
// (locally, `trust-center` has no TrustCenter nodes at all) would otherwise
// render an empty canvas with no explanation, which is a worse answer than
// showing the disconnected nodes that do exist and letting the caller see
// isolatedRemoved.
const visibleNodes = linked.length > 0 ? linked : nodes;
return {
nodes: visibleNodes,
links,
isolatedRemoved: nodes.length - visibleNodes.length,
patientKeys: await patientKeysOf(visibleNodes),
};
}
// ── Route handler ─────────────────────────────────────────────────────────────
/**
* GET /api/graph?persona=<id>
*
* Returns a persona-specific subgraph. Supported personas:
* default — full researcher overview (~200 nodes)
* trust-center — TC operator: pseudonym chains + governed datasets
* hospital — data holder: datasets + contracts + credentials
* researcher — data user: OMOP + datasets + clinical conditions
* edc-admin — operator: participants + products + transfers
* hdab — authority: approvals + credentials + TC governance
*/
// Any signed-in participant. Until #404 this was public as the demo landing
// view; Every API route needs a session since #404 (ADR-044), and /graph sends an anonymous visitor to sign in.
export async function GET(req: Request) {
const auth = await requireAuth();
if (isAuthError(auth)) return auth;
const { searchParams } = new URL(req.url);
const persona = (searchParams.get("persona") ?? "default") as PersonaId;
// Validate persona
const validPersonas = PERSONA_VIEWS.map((p) => p.id);
const safePersona = validPersonas.includes(persona) ? persona : "default";
try {
const graph = await cached(`graph:${safePersona}`, GRAPH_CACHE_TTL_MS, () =>
buildPersonaGraph(safePersona),
);
// Patients by pseudonym for every role that does not see identity
// (#475). Decided by the session's roles, not by `persona`, which is only
// a query parameter and anyone can set it. A patient's own node is
// pseudonymised too (since 2026-10-07): a patient session sees no name.
let nodes = graph.nodes;
if (!seesPatientIdentity(auth.session.roles)) {
nodes = pseudonymisePatients(nodes, graph.patientKeys, null);
}
const personaMeta = PERSONA_VIEWS.find((p) => p.id === safePersona);
return NextResponse.json({
nodes,
links: graph.links,
persona: safePersona,
question: personaMeta?.question,
isolatedRemoved: graph.isolatedRemoved,
});
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
const code =
err && typeof err === "object" && "code" in err
? String((err as { code?: unknown }).code ?? "")
: "";
console.error("GET /api/graph error:", {
message: msg,
code,
uri: process.env.NEO4J_URI ?? "(unset)",
});
return NextResponse.json(
{
error: "Neo4j unavailable",
detail: msg,
code,
},
{ status: 502 },
);
}
}
|