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

89.25% Statements 108/121
62.58% Branches 92/147
80% Functions 12/15
88.69% Lines 102/115

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                                                                                                      1x   1x       1x                   1x 1x   1x                   43x 43x 43x 42x                             14x 14x     13x 13x     13x   14x         14x 14x 14x 14x   14x 1x         12x 12x 12x 1x                     11x 14x 1x   10x 2x   8x 3x         5x     14x 14x 14x 14x   14x 14x 14x                 14x                                                                                                               3x   14x     3x                                       3x                                               14x 14x   9x   14x 14x             14x                     14x   2x 1x   1x                   1x                 1x 1x   1x 1x 1x 1x 1x 1x   1x                                                                                                           1x   1x                     1x                             1x                       2x 2x   2x                 2x 2x 2x 2x 2x                   2x                                                                                                                               2x       2x                         2x                             1x                       3x 3x   3x                 3x 3x 3x 3x 3x                   3x                                                                                                                                         3x     3x 3x 63x 63x   3x 12x 12x   3x                       3x                            
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions, derivePersonaId } from "@/lib/auth";
import { runQuery } from "@/lib/neo4j";
import {
  OPT_OUT_HISTORY_CYPHER,
  openOptOut,
  type OptOutRecordRow,
} from "@/lib/opt-out";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { GET as profileGET } from "@/app/api/patient/profile/route";
import { GET as insightsGET } from "@/app/api/patient/insights/route";
import { GET as researchGET } from "@/app/api/patient/research/route";
import { GET as observationsGET } from "@/app/api/patient/observations/route";
import { GET as complianceGET } from "@/app/api/compliance/route";
import { GET as permitsGET } from "@/app/api/permits/route";
import { GET as credentialsGET } from "@/app/api/credentials/route";
import { userToParticipantId } from "@/lib/odrl-engine";
import { isTestIdentity } from "@/lib/test-identity";
import {
  buildHdabView,
  type ContractShape,
  type CredentialEntry,
  type HdabAccessEvent,
  type MatrixRow,
  type ParticipantShape,
  type RegisterEntry,
} from "@/lib/overview/hdab";
import {
  buildHospitalView,
  type LabelAssessment,
} from "@/lib/overview/hospital";
import { GET as catalogGET } from "@/app/api/catalog/route";
import {
  buildResearcherView,
  type CatalogDataset,
  type StudyRecord,
} from "@/lib/overview/researcher";
import {
  buildPatientView,
  ownPatientIdForSession,
  type AccessLogEntry,
  type ConsentShape,
  type InsightsShape,
  type ProfileShape,
  type ResearchShape,
  type StudyShape,
} from "@/lib/overview/patient";
import type { FhirBundle } from "@/lib/overview/observations";
import type { OverviewView } from "@/lib/overview/types";
 
export const dynamic = "force-dynamic";
 
const PERSONAS = ["patient", "researcher", "hdab", "hospital"] as const;
type Persona = (typeof PERSONAS)[number];
 
/** Which overview each role may open. EDC_ADMIN may open any. */
const ROLE_PERSONA: Record<string, Persona> = {
  PATIENT: "patient",
  DATA_USER: "researcher",
  HDAB_AUTHORITY: "hdab",
  TRUST_CENTER_OPERATOR: "hdab",
  DATA_HOLDER: "hospital",
};
 
class SubRouteError extends Error {
  constructor(
    public status: number,
    public body: unknown,
  ) {
    super(`sub-route ${status}`);
  }
}
 
/** Call another route handler in-process and return its JSON. */
async function call<T>(
  handler: (req: Request) => Promise<Response>,
  origin: string,
  path: string,
): Promise<T> {
  const res = await handler(new Request(`${origin}${path}`));
  const body = await res.json();
  if (!res.ok) throw new SubRouteError(res.status, body);
  return body as T;
}
 
/**
 * GET /api/overview?persona=patient|researcher|hdab|hospital[&patientId=][&asOf=]
 *
 * One state-first view per persona (issue #271, discussion #265): layers,
 * nodes with status and series, links, and the signals sorted worst first.
 * Derived state (trend, chain of trust, clocks) is computed here from the
 * graph and never persisted. The persona defaults to the session's role;
 * a role may only open its own persona, EDC_ADMIN any.
 *
 * M1 the patient, M2 the access body, M3 the holder, M4 the researcher.
 */
export async function GET(req: Request): Promise<Response> {
  const auth = await requireAuth();
  if (isAuthError(auth)) return auth;
  // The persona is derived from preferredUsername, which AuthSession does
  // not carry, so read the full session as well (as /api/patient does).
  const session = await getServerSession(authOptions);
  Iif (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const roles = (session as { roles?: string[] }).roles ?? [];
  const username =
    (session.user as { preferredUsername?: string } | undefined)
      ?.preferredUsername ||
    (session as { preferredUsername?: string }).preferredUsername ||
    session.user?.name ||
    null;
  const url = new URL(req.url);
  const requested = url.searchParams.get("persona");
  const derived = derivePersonaId(roles, username);
  const persona = (requested ??
    (PERSONAS.includes(derived as Persona) ? derived : "patient")) as Persona;
  if (!PERSONAS.includes(persona)) {
    return NextResponse.json(
      { error: `Unknown persona "${persona}"`, personas: PERSONAS },
      { status: 400 },
    );
  }
  const isAdmin = roles.includes("EDC_ADMIN");
  const allowed = roles.map((r) => ROLE_PERSONA[r]).filter(Boolean);
  if (!isAdmin && !allowed.includes(persona)) {
    return NextResponse.json(
      {
        error: "Forbidden",
        reason: `Your role opens the ${
          allowed[0] ?? "no"
        } overview, not ${persona}`,
      },
      { status: 403 },
    );
  }
  const asOf =
    url.searchParams.get("asOf") ?? new Date().toISOString().slice(0, 10);
  if (persona === "hdab") {
    return hdabView(url, roles, username, asOf);
  }
  if (persona === "hospital") {
    return hospitalView(url, roles, username, asOf);
  }
  if (persona === "researcher") {
    return researcherView(url, roles, username, asOf);
  }
 
  // The patient a PATIENT session owns; anyone else picks one, P1 by default.
  const own =
    roles.includes("PATIENT") && !isAdmin
      ? ownPatientIdForSession(session)
      : null;
  const patientId = own ?? url.searchParams.get("patientId") ?? "P1";
  const since = new Date(asOf);
  since.setUTCMonth(since.getUTCMonth() - 12);
  since.setUTCDate(1);
 
  try {
    const origin = url.origin;
    const q = encodeURIComponent(patientId);
    const [
      profile,
      insights,
      research,
      observations,
      holderRows,
      studyRows,
      consentRows,
    ] = await Promise.all([
      call<ProfileShape>(
        profileGET,
        origin,
        `/api/patient/profile?patientId=${q}`,
      ),
      call<InsightsShape>(
        insightsGET,
        origin,
        `/api/patient/insights?patientId=${q}`,
      ),
      call<ResearchShape>(
        researchGET,
        origin,
        `/api/patient/research?patientId=${q}`,
      ),
      call<FhirBundle>(
        observationsGET,
        origin,
        `/api/patient/observations?patientId=${q}`,
      ),
      runQuery<{ did: string; name: string }>(
        `MATCH (p:Patient)-[:TREATED_AT]->(h:Participant)
           WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId
           RETURN h.participantId AS did, coalesce(h.name, h.participantId) AS name
           LIMIT 1`,
        { patientId },
      ),
      runQuery<StudyShape>(
        `MATCH (st:ResearchStudy)
           OPTIONAL MATCH (inst:Participant)-[:CONDUCTS]->(st)
           RETURN st.studyId AS studyId,
                  coalesce(st.name, st.studyId) AS studyName,
                  coalesce(inst.name, st.institutionDid, '') AS institution,
                  coalesce(st.purpose, 'secondary-use') AS purpose,
                  st.description AS description,
                  st.dataNeeded AS dataNeeded,
                  st.status AS status,
                  st.participantCount AS participantCount,
                  st.countries AS countries,
                  st.ethicsApproval AS ethicsApproval
           ORDER BY st.studyId
           LIMIT 50`,
      ),
      runQuery<{
        consentId: string;
        dataScope: string | null;
        trustCenter: string | null;
      }>(
        `MATCH (pc:PatientConsent {patientId: $patientId})
           OPTIONAL MATCH (pc)-[:RESOLVED_BY]->(tc:TrustCenter)
           RETURN pc.consentId AS consentId, pc.dataScope AS dataScope, tc.name AS trustCenter`,
        { patientId },
      ),
    ]);
 
    const holder = holderRows[0] ?? null;
    // The Art. 71 opt-out from secondary use, separate from any study (ADR-062).
    const optOut = openOptOut(
      await runQuery<OptOutRecordRow>(OPT_OUT_HISTORY_CYPHER, { patientId }),
    );
    const recordLog = await runQuery<AccessLogEntry>(
      `MATCH (te:TransferEvent)-[:READ]->(p:Patient)
       WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId
         AND te.timestamp >= datetime($since)
       WITH te, coalesce(te.consumerDid, te.participant) AS consumerDid
       OPTIONAL MATCH (c:Participant {participantId: consumerDid})
       RETURN te.eventId AS id,
              toString(te.timestamp) AS accessedAt,
              consumerDid,
              c.name AS consumerName,
              te.providerDid AS providerDid,
              te.datasetId AS datasetId,
              te.statusCode AS statusCode,
              te.permitId AS permitId,
              te.contractId AS contractId,
              te.responseBytes AS responseBytes
       ORDER BY te.timestamp DESC
       LIMIT 2000`,
      { patientId, since: since.toISOString() },
    );
    const accessLog = holder
      ? await runQuery<AccessLogEntry>(
          `MATCH (te:TransferEvent)
           WHERE te.providerDid = $did AND te.timestamp >= datetime($since)
           WITH te, coalesce(te.consumerDid, te.participant) AS consumerDid
           OPTIONAL MATCH (c:Participant {participantId: consumerDid})
           RETURN te.eventId AS id,
                  toString(te.timestamp) AS accessedAt,
                  consumerDid,
                  c.name AS consumerName,
                  te.providerDid AS providerDid,
                  te.datasetId AS datasetId,
                  te.statusCode AS statusCode,
                  te.permitId AS permitId,
                  te.contractId AS contractId,
                  te.responseBytes AS responseBytes
           ORDER BY te.timestamp DESC
           LIMIT 2000`,
          { did: holder.did, since: since.toISOString() },
        )
      : [];
 
    // Studies from the registry first, then the programmes the research
    // route lists that the registry does not know.
    const known = new Set(studyRows.map((s) => s.studyId));
    const programs = [
      ...studyRows,
      ...(research.programs ?? []).filter((p) => !known.has(p.studyId)),
    ];
    const extra = new Map(consentRows.map((c) => [c.consentId, c]));
    const consents: ConsentShape[] = (research.consents ?? []).map((c) => ({
      ...c,
      dataScope: c.dataScope ?? extra.get(c.consentId)?.dataScope ?? undefined,
      trustCenter:
        c.trustCenter ?? extra.get(c.consentId)?.trustCenter ?? undefined,
    }));
 
    const view: OverviewView = buildPatientView({
      asOf,
      profile,
      insights,
      research: { ...research, programs, consents },
      observations,
      accessLog,
      recordLog,
      holder,
      optOut: { optedOut: optOut !== null, since: optOut?.optedOutAt ?? null },
    });
    return NextResponse.json(view);
  } catch (err) {
    if (err instanceof SubRouteError) {
      return NextResponse.json(err.body, { status: err.status });
    }
    return NextResponse.json(
      {
        error: "Neo4j unavailable",
        detail: err instanceof Error ? err.message : String(err),
      },
      { status: 502 },
    );
  }
}
 
const DEFAULT_HDAB = { did: "did:web:medreg.de:hdab", name: "MedReg DE" };
 
/** The access body's own view: chains of trust per consumer, its own clocks. */
async function hdabView(
  url: URL,
  roles: string[],
  username: string | null,
  asOf: string,
): Promise<Response> {
  const requestedMe = url.searchParams.get("me");
  const fromUser = username ? userToParticipantId(username, roles) : "";
  const meDid =
    requestedMe ?? (fromUser.endsWith(":hdab") ? fromUser : DEFAULT_HDAB.did);
  const since = new Date(asOf);
  since.setUTCMonth(since.getUTCMonth() - 12);
  since.setUTCDate(1);
  try {
    const origin = url.origin;
    const [compliance, register, credentials, contractRows, events, meRows] =
      await Promise.all([
        call<{
          consumers: ParticipantShape[];
          datasets: { id: string; title: string }[];
          matrix: MatrixRow[];
        }>(complianceGET, origin, "/api/compliance"),
        call<{ entries: RegisterEntry[] }>(permitsGET, origin, "/api/permits"),
        call<{ credentials: CredentialEntry[] }>(
          credentialsGET,
          origin,
          "/api/credentials",
        ),
        runQuery<ContractShape>(
          `MATCH (c:Contract)
           OPTIONAL MATCH (consumer:Participant)-[:PARTY_TO|CONSUMER_OF|SIGNED]->(c)
           OPTIONAL MATCH (c)-[:GOVERNS|COVERS]->(dp:DataProduct)
           OPTIONAL MATCH (dp)-[:DESCRIBED_BY]->(ds:HealthDataset)
           RETURN c.contractId AS contractId,
                  coalesce(c.consumerDid, consumer.participantId) AS consumerDid,
                  coalesce(c.datasetId, ds.datasetId, dp.productId) AS datasetId,
                  toString(c.validUntil) AS validUntil,
                  c.status AS status
           LIMIT 200`,
        ),
        runQuery<HdabAccessEvent>(
          `MATCH (te:TransferEvent)
           WHERE te.timestamp >= datetime($since)
           WITH te, coalesce(te.consumerDid, te.participant) AS consumerDid
           OPTIONAL MATCH (c:Participant {participantId: consumerDid})
           OPTIONAL MATCH (p:Participant {participantId: te.providerDid})
           OPTIONAL MATCH (ds:HealthDataset {datasetId: te.datasetId})
           RETURN te.eventId AS id,
                  toString(te.timestamp) AS accessedAt,
                  consumerDid,
                  c.name AS consumerName,
                  te.providerDid AS providerDid,
                  p.name AS providerName,
                  te.datasetId AS datasetId,
                  ds.title AS assetTitle,
                  te.statusCode AS statusCode,
                  te.permitId AS permitId,
                  te.contractId AS contractId,
                  te.responseBytes AS responseBytes
           ORDER BY te.timestamp DESC
           LIMIT 5000`,
          { since: since.toISOString() },
        ),
        runQuery<{ did: string; name: string }>(
          `MATCH (p:Participant {participantId: $did})
           RETURN p.participantId AS did, coalesce(p.name, p.participantId) AS name`,
          { did: meDid },
        ),
      ]);
    const me =
      meRows[0] ??
      (meDid === DEFAULT_HDAB.did ? DEFAULT_HDAB : { did: meDid, name: meDid });
    const view: OverviewView = buildHdabView({
      asOf,
      me,
      consumers: compliance.consumers ?? [],
      datasets: compliance.datasets ?? [],
      matrix: compliance.matrix ?? [],
      register: register.entries ?? [],
      credentials: credentials.credentials ?? [],
      contracts: contractRows.filter((c) => c.contractId),
      events,
    });
    return NextResponse.json(view);
  } catch (err) {
    if (err instanceof SubRouteError) {
      return NextResponse.json(err.body, { status: err.status });
    }
    return NextResponse.json(
      {
        error: "Neo4j unavailable",
        detail: err instanceof Error ? err.message : String(err),
      },
      { status: 502 },
    );
  }
}
 
const DEFAULT_HOLDER = {
  did: "did:web:alpha-klinik.de:participant",
  name: "AlphaKlinik Berlin",
};
 
/** The holder's own view: who reads its data with what cover, its own duties. */
async function hospitalView(
  url: URL,
  roles: string[],
  username: string | null,
  asOf: string,
): Promise<Response> {
  const requestedMe = url.searchParams.get("me");
  const fromUser = username ? userToParticipantId(username, roles) : "";
  const meDid =
    requestedMe ??
    (fromUser &&
    !fromUser.startsWith("did:web:unknown") &&
    // A forged test session has no organisation of its own: like an
    // unknown login it sees the demo participant's view.
    !isTestIdentity(fromUser) &&
    !fromUser.endsWith(":hdab")
      ? fromUser
      : DEFAULT_HOLDER.did);
  const since = new Date(asOf);
  since.setUTCMonth(since.getUTCMonth() - 12);
  since.setUTCDate(1);
  try {
    const origin = url.origin;
    const [
      compliance,
      register,
      credentials,
      catalog,
      contractRows,
      events,
      meRows,
      assessments,
    ] = await Promise.all([
      call<{
        consumers: ParticipantShape[];
        datasets: { id: string; title: string }[];
        matrix: MatrixRow[];
      }>(complianceGET, origin, "/api/compliance"),
      call<{ entries: RegisterEntry[] }>(permitsGET, origin, "/api/permits"),
      call<{ credentials: CredentialEntry[] }>(
        credentialsGET,
        origin,
        "/api/credentials",
      ),
      call<CatalogDataset[]>(catalogGET, origin, "/api/catalog"),
      runQuery<ContractShape>(
        `MATCH (c:Contract)
           OPTIONAL MATCH (consumer:Participant)-[:PARTY_TO|CONSUMER_OF|SIGNED]->(c)
           OPTIONAL MATCH (c)-[:GOVERNS|COVERS]->(dp:DataProduct)
           OPTIONAL MATCH (dp)-[:DESCRIBED_BY]->(ds:HealthDataset)
           RETURN c.contractId AS contractId,
                  coalesce(c.consumerDid, consumer.participantId) AS consumerDid,
                  coalesce(c.datasetId, ds.datasetId, dp.productId) AS datasetId,
                  toString(c.validUntil) AS validUntil,
                  c.status AS status
           LIMIT 200`,
      ),
      runQuery<HdabAccessEvent>(
        `MATCH (te:TransferEvent)
           WHERE te.timestamp >= datetime($since) AND te.providerDid = $did
           WITH te, coalesce(te.consumerDid, te.participant) AS consumerDid
           OPTIONAL MATCH (c:Participant {participantId: consumerDid})
           OPTIONAL MATCH (ds:HealthDataset {datasetId: te.datasetId})
           RETURN te.eventId AS id,
                  toString(te.timestamp) AS accessedAt,
                  consumerDid,
                  c.name AS consumerName,
                  te.providerDid AS providerDid,
                  te.datasetId AS datasetId,
                  ds.title AS assetTitle,
                  te.statusCode AS statusCode,
                  te.permitId AS permitId,
                  te.contractId AS contractId,
                  te.responseBytes AS responseBytes
           ORDER BY te.timestamp DESC
           LIMIT 5000`,
        { since: since.toISOString(), did: meDid },
      ),
      runQuery<{ did: string; name: string }>(
        `MATCH (p:Participant {participantId: $did})
           RETURN p.participantId AS did, coalesce(p.name, p.participantId) AS name`,
        { did: meDid },
      ),
      runQuery<LabelAssessment>(
        `MATCH (p:Participant {participantId: $did})-[:HOLDS_CREDENTIAL]->(vc:VerifiableCredential)-[:HAS_ASSESSMENT]->(qa:QualityAssessment)
           RETURN vc.credentialId AS credentialId,
                  toString(qa.assessedAt) AS date,
                  qa.conformance AS conformance,
                  qa.completeness AS completeness,
                  qa.timeliness AS timeliness,
                  qa.period AS period
           ORDER BY qa.assessedAt`,
        { did: meDid },
      ),
    ]);
    const me =
      meRows[0] ??
      (meDid === DEFAULT_HOLDER.did
        ? DEFAULT_HOLDER
        : { did: meDid, name: meDid });
    const view: OverviewView = buildHospitalView({
      asOf,
      me,
      consumers: compliance.consumers ?? [],
      datasets: compliance.datasets ?? [],
      matrix: compliance.matrix ?? [],
      register: register.entries ?? [],
      credentials: credentials.credentials ?? [],
      contracts: contractRows.filter((c) => c.contractId),
      events,
      assessments,
      catalog: Array.isArray(catalog) ? catalog : [],
    });
    return NextResponse.json(view);
  } catch (err) {
    if (err instanceof SubRouteError) {
      return NextResponse.json(err.body, { status: err.status });
    }
    return NextResponse.json(
      {
        error: "Neo4j unavailable",
        detail: err instanceof Error ? err.message : String(err),
      },
      { status: 502 },
    );
  }
}
 
const DEFAULT_USER = {
  did: "did:web:pharmaco.de:research",
  name: "PharmaCo Research AG",
};
 
/** The researcher's own view: what is permitted, pending, blocked, missing. */
async function researcherView(
  url: URL,
  roles: string[],
  username: string | null,
  asOf: string,
): Promise<Response> {
  const requestedMe = url.searchParams.get("me");
  const fromUser = username ? userToParticipantId(username, roles) : "";
  const meDid =
    requestedMe ??
    (fromUser &&
    !fromUser.startsWith("did:web:unknown") &&
    // A forged test session has no organisation of its own: like an
    // unknown login it sees the demo participant's view.
    !isTestIdentity(fromUser) &&
    !fromUser.endsWith(":hdab")
      ? fromUser
      : DEFAULT_USER.did);
  const since = new Date(asOf);
  since.setUTCMonth(since.getUTCMonth() - 12);
  since.setUTCDate(1);
  try {
    const origin = url.origin;
    const [
      compliance,
      register,
      credentials,
      catalog,
      contractRows,
      events,
      meRows,
      studyRows,
    ] = await Promise.all([
      call<{
        consumers: ParticipantShape[];
        datasets: { id: string; title: string }[];
        matrix: MatrixRow[];
      }>(complianceGET, origin, "/api/compliance"),
      call<{ entries: RegisterEntry[] }>(permitsGET, origin, "/api/permits"),
      call<{ credentials: CredentialEntry[] }>(
        credentialsGET,
        origin,
        "/api/credentials",
      ),
      call<CatalogDataset[]>(catalogGET, origin, "/api/catalog"),
      runQuery<ContractShape>(
        `MATCH (c:Contract)
           OPTIONAL MATCH (consumer:Participant)-[:PARTY_TO|CONSUMER_OF|SIGNED]->(c)
           OPTIONAL MATCH (c)-[:GOVERNS|COVERS]->(dp:DataProduct)
           OPTIONAL MATCH (dp)-[:DESCRIBED_BY]->(ds:HealthDataset)
           RETURN c.contractId AS contractId,
                  coalesce(c.consumerDid, consumer.participantId) AS consumerDid,
                  coalesce(c.datasetId, ds.datasetId, dp.productId) AS datasetId,
                  toString(c.validUntil) AS validUntil,
                  c.status AS status
           LIMIT 200`,
      ),
      runQuery<HdabAccessEvent>(
        `MATCH (te:TransferEvent)
           WHERE te.timestamp >= datetime($since)
             AND coalesce(te.consumerDid, te.participant) = $did
           OPTIONAL MATCH (ds:HealthDataset {datasetId: te.datasetId})
           RETURN te.eventId AS id,
                  toString(te.timestamp) AS accessedAt,
                  $did AS consumerDid,
                  te.providerDid AS providerDid,
                  te.datasetId AS datasetId,
                  ds.title AS assetTitle,
                  te.statusCode AS statusCode,
                  te.permitId AS permitId,
                  te.contractId AS contractId,
                  te.responseBytes AS responseBytes
           ORDER BY te.timestamp DESC
           LIMIT 5000`,
        { since: since.toISOString(), did: meDid },
      ),
      runQuery<{ did: string; name: string }>(
        `MATCH (p:Participant {participantId: $did})
           RETURN p.participantId AS did, coalesce(p.name, p.participantId) AS name`,
        { did: meDid },
      ),
      runQuery<StudyRecord>(
        `MATCH (st:ResearchStudy)
           OPTIONAL MATCH (inst:Participant)-[:CONDUCTS]->(st)
           OPTIONAL MATCH (st)-[:HAS_ENROLMENT]->(en:StudyEnrolment)
           WITH st, inst, en ORDER BY en.asOf
           RETURN st.studyId AS studyId,
                  coalesce(st.name, st.studyId) AS studyName,
                  coalesce(inst.name, st.institutionDid, '') AS institution,
                  coalesce(inst.participantId, st.institutionDid) AS institutionDid,
                  st.status AS status,
                  st.dataNeeded AS dataNeeded,
                  st.description AS description,
                  st.countries AS countries,
                  st.participantCount AS participantCount,
                  [x IN collect(CASE WHEN en IS NULL THEN null ELSE {date: toString(en.asOf), value: en.participants} END) WHERE x IS NOT NULL] AS enrolment
           ORDER BY st.studyId
           LIMIT 100`,
      ),
    ]);
    const me =
      meRows[0] ??
      (meDid === DEFAULT_USER.did ? DEFAULT_USER : { did: meDid, name: meDid });
    // The catalogue's descriptions, keyed by dataset id or title
    const byKey = new Map<string, CatalogDataset>();
    for (const c of Array.isArray(catalog) ? catalog : []) {
      byKey.set(c.id, c);
      byKey.set(c.title, c);
    }
    const datasets: CatalogDataset[] = (compliance.datasets ?? []).map((d) => {
      const c = byKey.get(d.id) ?? byKey.get(d.title);
      return { ...(c ?? {}), id: d.id, title: d.title };
    });
    const view: OverviewView = buildResearcherView({
      asOf,
      me,
      consumers: compliance.consumers ?? [],
      datasets,
      matrix: compliance.matrix ?? [],
      register: register.entries ?? [],
      credentials: credentials.credentials ?? [],
      contracts: contractRows.filter((c) => c.contractId),
      events,
      studies: studyRows,
    });
    return NextResponse.json(view);
  } catch (err) {
    if (err instanceof SubRouteError) {
      return NextResponse.json(err.body, { status: err.status });
    }
    return NextResponse.json(
      {
        error: "Neo4j unavailable",
        detail: err instanceof Error ? err.message : String(err),
      },
      { status: 502 },
    );
  }
}