All files / src/lib/overview patient.ts

98.11% Statements 208/212
78.72% Branches 185/235
100% Functions 29/29
98.98% Lines 196/198

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 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963                                                                                                                                                                                                                                                                                  85x                                                                                                             85x           85x 174x         85x 148x     13x 13x                                         13x 13x 13x   13x 13x 13x 572x 572x 572x 572x   13x       687x     13x 13x                           52x                 13x 13x 26x 26x 26x                   91x     26x 26x                 26x 91x 91x 91x 91x                       91x         13x 13x 91x 91x                       91x 91x   13x 154x 154x 610x 610x   39x 13x   26x 13x 52x     13x   13x 91x 91x 78x               13x           13x 52x 52x                     130x 52x       13x 26x       13x   13x     13x 26x 26x 26x                             26x           26x                 13x 26x 26x                       26x 52x 52x 52x           13x 36x 13x 26x 1x             13x 13x 13x 37x 37x 62x   37x                                                       37x 74x 24x             37x 36x 36x                   36x   37x 26x 26x 26x 26x                                                       26x           26x           26x 1x                   26x 26x 24x 24x                     24x           11x 11x 11x 11x 11x         187x               13x 5x 5x                                                 5x         5x                       13x                     13x 13x 13x 13x 12x 12x                       12x 12x 12x 26x   19x 12x 19x   12x 11x 132x 11x                                           11x             12x 12x                             13x 96x   13x 104x 104x 13x 13x 13x 96x 96x 96x 96x       96x 96x   96x 96x 96x 96x 576x 576x                                         96x 96x 576x             576x 480x                     96x               576x                                       96x 156x     96x     96x 48x           48x 48x             96x 96x                           13x 12x                       572x 13x                   687x                                     235x 152x   126x                                         114x           113x           114x 194x 194x   6x    
/**
 * The patient overview (issue #271 M1): "which parameters put me at risk,
 * what should I do about them, and who is using my data?"
 *
 * A pure builder over the shapes the existing patient routes return
 * (`/api/patient/profile`, `/api/patient/insights`, `/api/patient/research`,
 * `/api/patient/observations`) plus the holder's access log. The API route
 * gathers those and calls this; the fixture generator calls it with the mock
 * files; the tests call it with both.
 *
 * Article numbers are those of Regulation (EU) 2025/327 as adopted.
 */
import {
  aggregateMonthly,
  isOutOfRange,
  monthRange,
  rankSignals,
  trendOf,
  type AccessEvent,
  type Severity,
} from "./derive";
import { bundleToParameters, type FhirBundle } from "./observations";
import type {
  OverviewLayer,
  OverviewLink,
  OverviewNode,
  OverviewSignal,
  OverviewView,
} from "./types";
import { sandboxPatientId } from "@/lib/sandbox-account";
 
export interface ProfileShape {
  patient: {
    id: string;
    name: string;
    gender?: string;
    birthDate?: string;
    /** set in place of the birth date when the patient reads their own record */
    age?: number | null;
  };
  conditions: { code: string; display: string; onsetDate?: string }[];
  medications: { code: string; display: string }[];
  riskScores: Record<
    string,
    { score: number; level: string; factors: string[] }
  >;
  totalConditionCount?: number;
  gdprRights?: Record<string, string>;
}
 
export interface InsightsShape {
  recommendations: {
    category: string;
    action: string;
    priority: string;
    basedOn: string;
    ehdsArticle?: string;
  }[];
  findings: {
    insightId: string;
    studyId: string;
    finding: string;
    relevantConditions: string[];
    recommendation: string;
    evidenceLevel: string;
  }[];
  privacyNote?: string;
}
 
export interface StudyShape {
  studyId: string;
  studyName: string;
  institution: string;
  purpose?: string;
  description?: string;
  dataNeeded?: string;
  status?: string;
  participantCount?: number;
  countries?: string[];
  ethicsApproval?: string;
}
 
export interface ConsentShape {
  consentId: string;
  studyId: string;
  grantedAt: string;
  revoked: boolean;
  revokedAt?: string | null;
  purpose?: string;
  dataScope?: string;
  trustCenterDid?: string;
  trustCenter?: string;
}
 
export interface ResearchShape {
  programs: StudyShape[];
  consents: ConsentShape[];
  gdprBasis?: string;
}
 
export interface AccessLogEntry extends AccessEvent {
  consumerName?: string | null;
  providerName?: string | null;
  assetTitle?: string | null;
}
 
export interface PatientViewInput {
  /** ISO date */
  asOf: string;
  profile: ProfileShape;
  insights: InsightsShape;
  research: ResearchShape;
  observations: FhirBundle;
  /** The holder's access log, last twelve months (Art. 9 until a per-record log exists) */
  accessLog?: AccessLogEntry[];
  /** The holder that treats the patient */
  holder?: { did: string; name: string } | null;
  /** The accesses that read this patient's record (Art. 9), when the log knows */
  recordLog?: AccessLogEntry[];
  /** The Art. 71 opt-out from secondary use, when known (ADR-062) */
  optOut?: { optedOut: boolean; since: string | null } | null;
}
 
/**
 * What the eight priority parameters mean to a patient, and which risk
 * domain and factor each one drives. Descriptions in plain words; the
 * printed reference range comes from the Observation, never from here.
 */
const PARAMETER_META: Record<
  string,
  {
    key: string;
    risk?: string;
    factor?: RegExp;
    higherIsWorse?: boolean;
    description: string;
  }
> = {
  "4548-4": {
    key: "HbA1c",
    risk: "diabetes",
    factor: /hba1c/,
    description:
      "The share of haemoglobin with glucose bound to it, which reflects the average blood glucose of the last two to three months. The parameter behind the HbA1c factor of my diabetes risk.",
  },
  "2339-0": {
    key: "Fasting glucose",
    risk: "diabetes",
    description:
      "Blood sugar at the moment of the draw. Only interpretable fasting, since it rises after any meal.",
  },
  "2089-1": {
    key: "LDL cholesterol",
    risk: "cardiovascular",
    description:
      "Cholesterol in low-density lipoproteins, the particles that deposit it in artery walls. The primary target in lipid guidelines, and what the atorvastatin is for.",
  },
  "2093-3": {
    key: "Total cholesterol",
    risk: "cardiovascular",
    description:
      "All cholesterol carried in the blood, in every particle type. A screening figure; LDL carries the risk information.",
  },
  "8480-6": {
    key: "Systolic blood pressure",
    risk: "cardiovascular",
    factor: /hypertension|blood-pressure/,
    description:
      "Pressure in the arteries when the heart contracts. The parameter behind the hypertension diagnosis, and what the lisinopril is for.",
  },
  "8462-4": {
    key: "Diastolic blood pressure",
    risk: "cardiovascular",
    factor: /hypertension|blood-pressure/,
    description: "Pressure in the arteries between heartbeats.",
  },
  "39156-5": {
    key: "BMI",
    risk: "diabetes",
    factor: /bmi|obesity/,
    description:
      "Weight divided by height squared. A population measure; it says nothing about what the weight is made of. The parameter behind the obesity factor.",
  },
  "33914-3": {
    key: "eGFR",
    risk: "diabetes",
    higherIsWorse: false,
    description:
      "The kidney's filtration rate, estimated from creatinine with age and sex. An estimate, not a measurement. Watched because diabetes and hypertension both wear on the kidney.",
  },
};
 
const LEVEL: Record<string, Severity> = {
  high: "bad",
  moderate: "warn",
  low: "ok",
};
 
const slug = (s: string) =>
  s
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "");
 
const fmtDate = (iso?: string | null) =>
  iso ? String(iso).slice(0, 10) : "n/a";
 
export function buildPatientView(input: PatientViewInput): OverviewView {
  const { profile, insights, research, observations } = input;
  const layers: OverviewLayer[] = [
    {
      id: "prevent",
      name: "Prevention: what to do next",
      z: 2,
      color: "#fbbf24",
    },
    {
      id: "risk",
      name: "My risks and the parameters behind them",
      z: 1,
      color: "#f97316",
    },
    { id: "me", name: "My record (FHIR R4)", z: 0, color: "#86efac" },
    {
      id: "use",
      name: "Who uses my data, under which consent",
      z: -1,
      color: "#a78bfa",
    },
  ];
  const nodes: OverviewNode[] = [];
  const links: OverviewLink[] = [];
  const signals: OverviewSignal[] = [];
  /** Measured parameters rank ahead of the risk domains at equal severity */
  const paramSignals: OverviewSignal[] = [];
  const ids = new Set<string>();
  const add = (n: OverviewNode) => {
    Iif (ids.has(n.id)) return n;
    ids.add(n.id);
    nodes.push(n);
    return n;
  };
  const link = (
    source: string,
    target: string,
    o: Partial<OverviewLink> = {},
  ) => links.push({ source, target, ...o });
 
  // ── me ────────────────────────────────────────────────────────────────────
  const me = profile.patient;
  add({
    id: "me",
    label: me.name,
    layer: "me",
    kind: "Patient",
    size: 4,
    color: "#fbbf24",
    pin: [0, 0],
    title: me.name,
    sub: `${
      me.age != null ? `age ${me.age}` : `born ${fmtDate(me.birthDate)}`
    }, ${
      profile.totalConditionCount ?? profile.conditions.length
    } diagnoses on record`,
    facts: Object.entries(profile.gdprRights ?? {}).map(([k, v]) => [k, v]),
    article: "Art. 3: access to my own electronic health data",
    links: [
      { href: "/patient/profile", text: "My profile" },
      { href: "/patient/insights", text: "My insights" },
    ],
  });
 
  // ── risk domains and their factors ────────────────────────────────────────
  const factorNodes = new Map<string, string>(); // factor id -> factor text
  for (const [key, r] of Object.entries(profile.riskScores ?? {})) {
    const id = `risk:${key}`;
    const sev = LEVEL[r.level] ?? "info";
    add({
      id,
      label: `${key} risk ${Math.round(r.score * 100)} %`,
      layer: "risk",
      kind: "Risk",
      size: 3,
      status: sev,
      pulse: r.level === "high",
      title: `${key[0].toUpperCase()}${key.slice(1)} risk`,
      sub: `score ${r.score}, level ${r.level}`,
      facts: r.factors.map((f, i) => [`factor ${i + 1}`, f]),
      article: "Derived from my own record (primary use). Not a diagnosis.",
    });
    link("me", id, { kind: "carries", status: sev, width: 1.4, distance: 70 });
    signals.push({
      severity: sev,
      code: `risk-${key}`,
      nodeId: id,
      text: `${key} risk is ${r.level} (${Math.round(
        r.score * 100,
      )} %): ${r.factors.join(", ")}`,
      article: "Art. 3 access, Art. 14 priority data categories",
    });
    for (const f of r.factors) {
      const fid = `fac:${slug(f)}`;
      Eif (!factorNodes.has(fid)) {
        factorNodes.set(fid, f);
        add({
          id: fid,
          label: f,
          layer: "risk",
          kind: "Risk factor",
          size: 1.4,
          status: "warn",
          title: f,
          sub: "risk factor",
          facts: [["drives", `${key} risk`]],
        });
      }
      link(fid, id, { kind: "drives", status: "warn", distance: 40 });
    }
  }
 
  // ── my record: diagnoses and medications ──────────────────────────────────
  const condByWord = new Map<string, string>();
  for (const c of profile.conditions) {
    const id = `cond:${c.code}`;
    add({
      id,
      label: c.display,
      layer: "me",
      kind: "Diagnosis",
      size: 1.2,
      color: "#86efac",
      title: c.display,
      sub: `since ${fmtDate(c.onsetDate)}`,
      facts: [["code", c.code]],
      article: "FHIR R4 Condition, SNOMED CT or ICD-10 coded",
    });
    link("me", id, { kind: "diagnosis", color: "#4ade80", distance: 55 });
    condByWord.set(c.display.toLowerCase(), id);
  }
  const matchCond = (text: string): string | undefined => {
    const t = text.toLowerCase();
    for (const [w, id] of condByWord) {
      const head = w.split(" ")[0].replace(/[()]/g, "");
      if (head.length >= 4 && t.includes(head)) return id;
    }
    if (/t2d|type 2|diabetes/.test(t)) {
      return condByWord.get("diabetes mellitus type 2");
    }
    if (/bmi|obesity/.test(t)) {
      return [...condByWord.entries()].find(([w]) =>
        w.startsWith("obesity"),
      )?.[1];
    }
    return undefined;
  };
  for (const [fid, f] of factorNodes) {
    const cid = matchCond(f);
    if (cid) {
      link(cid, fid, {
        kind: "behind",
        color: "#fb923c",
        distance: 60,
        particles: 1,
      });
    }
  }
  const medTarget: [RegExp, string][] = [
    [/metformin/i, condByWord.get("diabetes mellitus type 2") ?? "me"],
    [/lisinopril|ramipril|amlodipine/i, condByWord.get("hypertension") ?? "me"],
    [/salbutamol|budesonide/i, condByWord.get("asthma") ?? "me"],
    [/statin/i, ids.has("risk:cardiovascular") ? "risk:cardiovascular" : "me"],
  ];
  for (const m of profile.medications) {
    const id = `med:${m.code}`;
    add({
      id,
      label: m.display.split(" ")[0],
      layer: "me",
      kind: "Medication",
      size: 1,
      color: "#c4b5fd",
      title: m.display,
      sub: "FHIR R4 MedicationRequest",
      facts: [["RxNorm", m.code]],
    });
    const t = medTarget.find(([re]) => re.test(m.display))?.[1] ?? "me";
    link(id, t, { kind: "treats", color: "#a78bfa", distance: 45 });
  }
 
  // ── prevention: recommendations and findings ──────────────────────────────
  const riskTarget = (text: string) => {
    if (
      /cardio|statin|lipid|blood pressure/i.test(text) &&
      ids.has("risk:cardiovascular")
    ) {
      return "risk:cardiovascular";
    }
    Eif (ids.has("risk:diabetes")) return "risk:diabetes";
    return "me";
  };
  (insights.recommendations ?? []).forEach((r, i) => {
    const id = `rec:${i}`;
    const sev: Severity = r.priority === "high" ? "warn" : "info";
    add({
      id,
      label: r.action.replace(/\.$/, ""),
      layer: "prevent",
      kind: "Recommendation",
      size: 2.4,
      status: sev,
      pulse: r.priority === "high",
      title: r.action,
      sub: `${r.category}, priority ${r.priority}`,
      facts: [["based on", r.basedOn]],
      article:
        "Aggregate finding from a secure processing environment, Art. 73",
      links: [{ href: "/patient/insights", text: "My insights" }],
    });
    link(id, riskTarget(r.basedOn + r.action), {
      kind: "addresses",
      status: sev,
      distance: 80,
      arrow: true,
    });
    signals.push({
      severity: sev,
      code: "recommendation",
      nodeId: id,
      text: `${r.priority} priority: ${r.action}`,
      article:
        "Art. 73 SPE result, Art. 58 obligations towards natural persons",
    });
  });
  for (const f of insights.findings ?? []) {
    const id = `find:${f.insightId}`;
    add({
      id,
      label: f.recommendation.replace(/\.$/, "") || f.finding.slice(0, 60),
      layer: "prevent",
      kind: "Study finding",
      size: 1.8,
      status: "info",
      title: f.finding,
      sub: `evidence ${f.evidenceLevel}, from ${f.studyId}`,
      facts: [["applies to", (f.relevantConditions ?? []).join(", ")]],
      article: insights.privacyNote,
    });
    for (const c of f.relevantConditions ?? []) {
      const cid = matchCond(c);
      Eif (cid) {
        link(cid, id, { kind: "informs", color: "#38bdf8", distance: 90 });
      }
    }
  }
 
  // ── who uses my data ──────────────────────────────────────────────────────
  const programs = new Map<string, StudyShape>();
  for (const p of research.programs ?? []) programs.set(p.studyId, p);
  for (const c of research.consents ?? []) {
    if (!programs.has(c.studyId)) {
      programs.set(c.studyId, {
        studyId: c.studyId,
        studyName: c.studyId,
        institution: "",
      });
    }
  }
  let activeConsents = 0;
  let firstConsentId: string | null = null;
  for (const p of programs.values()) {
    const id = `study:${p.studyId}`;
    const consent = (research.consents ?? []).find(
      (c) => c.studyId === p.studyId,
    );
    add({
      id,
      label: p.studyName,
      layer: "use",
      kind: "Study",
      size: 2.2,
      status: consent && !consent.revoked ? "ok" : "info",
      title: p.studyName,
      sub: [
        p.institution,
        p.participantCount != null
          ? `${p.participantCount.toLocaleString("en")} participants`
          : "",
        (p.countries ?? []).join(", "),
      ]
        .filter(Boolean)
        .join(", "),
      description: p.description,
      facts: [
        ["needs", p.dataNeeded ?? "n/a"],
        ["status", p.status ?? "n/a"],
        ["ethics", p.ethicsApproval ?? "n/a"],
      ],
      article: consent
        ? "My consent to this study is on file and can be withdrawn (GDPR Art. 7(3)); the opt-out from all secondary use is separate (Art. 71)"
        : "Not joined. Secondary use under a permit continues unless I opt out (Art. 71); joining a study is a separate consent",
      links: [{ href: "/patient/research", text: "Research programmes" }],
    });
    for (const f of insights.findings ?? []) {
      if (f.studyId === p.studyId) {
        link(`find:${f.insightId}`, id, {
          kind: "from",
          color: "#a78bfa",
          distance: 120,
        });
      }
    }
    if (p.institution) {
      const org = `org:${slug(p.institution)}`;
      add({
        id: org,
        label: p.institution,
        layer: "use",
        kind: "Organisation",
        size: 1.6,
        color: "#f97316",
        title: p.institution,
        sub: "health data user",
      });
      link(id, org, { kind: "conducted by", color: "#f97316", distance: 45 });
    }
    if (consent) {
      const cid = `consent:${consent.consentId}`;
      firstConsentId ??= cid;
      if (!consent.revoked) activeConsents++;
      add({
        id: cid,
        label: consent.revoked
          ? `withdrawn ${fmtDate(consent.revokedAt)}`
          : `consent ${fmtDate(consent.grantedAt)}`,
        layer: "use",
        kind: "Consent",
        size: 1.2,
        status: consent.revoked ? "none" : "ok",
        title: consent.consentId,
        sub: consent.dataScope ?? consent.purpose ?? "",
        facts: [
          ["granted", fmtDate(consent.grantedAt)],
          [
            "state",
            consent.revoked
              ? `withdrawn on ${fmtDate(consent.revokedAt)} (GDPR Art. 7(3))`
              : "active",
          ],
          [
            "pseudonymised by",
            consent.trustCenter ?? consent.trustCenterDid ?? "trust centre",
          ],
        ],
        article:
          research.gdprBasis ??
          "Study consent, GDPR Art. 9(2)(a); withdrawable, Art. 7(3)",
      });
      link("me", cid, {
        kind: "consent",
        status: consent.revoked ? "none" : "ok",
        particles: consent.revoked ? 0 : 2,
        distance: 90,
      });
      link(cid, id, {
        kind: "consent",
        status: consent.revoked ? "none" : "ok",
        particles: consent.revoked ? 0 : 2,
        distance: 50,
      });
      if (consent.revoked) {
        signals.push({
          severity: "info",
          code: "consent-withdrawn",
          nodeId: cid,
          text: `I withdrew my consent to ${p.studyName} on ${fmtDate(
            consent.revokedAt,
          )}; nothing new of mine reaches that study.`,
          article: "Consent withdrawn, GDPR Art. 7(3)",
        });
      }
      const tcName = consent.trustCenter ?? consent.trustCenterDid;
      if (tcName) {
        const tc = `tc:${slug(tcName)}`;
        add({
          id: tc,
          label: tcName,
          layer: "use",
          kind: "Trust centre",
          size: 1.1,
          color: "#ef4444",
          title: "Trust centre",
          sub: tcName,
          article: "Pseudonymisation before the SPE, Art. 73",
        });
        link(cid, tc, {
          kind: "pseudonymised by",
          color: "#ef4444",
          distance: 40,
        });
      }
    } else Eif (p.dataNeeded) {
      const rel = matchCond(p.dataNeeded);
      Eif (rel) {
        link(rel, id, { kind: "matches", status: "info", distance: 130 });
        signals.push({
          severity: "info",
          code: "study-match",
          nodeId: id,
          text: `${p.studyName} is ${p.status ?? "open"} and matches my ${
            nodes.find((n) => n.id === rel)?.label ?? "record"
          }`,
          article: "Study invitation; joining is a consent, GDPR Art. 9(2)(a)",
        });
      }
    }
  }
  // ── the Art. 71 opt-out from all secondary use, separate from any study ───
  if (input.optOut) {
    const out = input.optOut.optedOut;
    add({
      id: "secondary-use",
      label: out
        ? `opted out ${fmtDate(input.optOut.since)}`
        : "secondary use: on",
      layer: "use",
      kind: "Opt-out",
      size: 1.4,
      status: out ? "none" : "info",
      title: "Secondary use of my data",
      sub: out
        ? "left out of every new extraction"
        : "the default, under permits only",
      facts: [
        [
          "state",
          out
            ? `opted out since ${fmtDate(input.optOut.since)}`
            : "not opted out",
        ],
        ["reversible", "yes, at any time and without a reason"],
      ],
      article: "Art. 71 opt-out from secondary use",
      links: [{ href: "/patient/research", text: "Opt out or back in" }],
    });
    link("me", "secondary-use", {
      kind: "opt-out",
      status: out ? "none" : "info",
      distance: 70,
    });
    signals.push({
      severity: "info",
      code: "opt-out",
      nodeId: "secondary-use",
      text: out
        ? `I opted out of secondary use on ${fmtDate(
            input.optOut.since,
          )}; new permits get nothing of mine.`
        : "Secondary use under a permit is the default; I can opt out at any time.",
      article: "Art. 71 opt-out from secondary use",
    });
  }
  signals.push({
    severity: "ok",
    code: "consent-summary",
    nodeId: firstConsentId ?? "me",
    text: `${activeConsents} consents active, all revocable. ${
      (insights.privacyNote ?? "").split(".")[0]
    }`.trim(),
    article: "Art. 9: who accessed my data; study consents, GDPR Art. 7(3)",
  });
 
  // ── the access log of my holder (Art. 9) ──────────────────────────────────
  const log = input.accessLog ?? [];
  const record = input.recordLog ?? [];
  const useRecord = record.length > 0;
  if (input.holder) {
    const hid = `holder:${slug(input.holder.did)}`;
    add({
      id: hid,
      label: input.holder.name,
      layer: "use",
      kind: "Health data holder",
      size: 1.8,
      color: "#38bdf8",
      title: input.holder.name,
      sub: "keeps my record and the access log",
      article:
        "Art. 60 duties of health data holders, Art. 73(1)(e) access log",
    });
    link("me", hid, { kind: "treated at", color: "#38bdf8", distance: 70 });
    const months = monthRange(input.asOf, 12);
    const served = (useRecord ? record : log).filter(
      (e) => (e.statusCode ?? 200) < 400,
    );
    const byConsumer = aggregateMonthly(served, months, (e) => e.consumerDid);
    const names = new Map(
      served.map((e) => [e.consumerDid, e.consumerName ?? e.consumerDid]),
    );
    for (const [did, series] of Object.entries(byConsumer)) {
      const id = `access:${slug(did)}`;
      const total = series.reduce((a, p) => a + p.value, 0);
      add({
        id,
        label: names.get(did) ?? did,
        layer: "use",
        kind: "Data user",
        size: 1.4,
        status: "info",
        title: names.get(did) ?? did,
        sub: useRecord
          ? `read my record ${total} times in the last 12 months`
          : `${total} accesses to my holder's data in the last 12 months`,
        series,
        unit: useRecord ? "reads" : "accesses",
        measure: useRecord
          ? "Reads of my record per month"
          : "Accesses per month",
        higherIsWorse: true,
        facts: [["did", did]],
        article: useRecord
          ? "Art. 9: information on who accessed my data, from the reads of my record in the holder's Art. 73(1)(e) log"
          : "Art. 9: information on who accessed my data. The log is the holder's, per dataset; no read of my record is on file.",
      });
      link(hid, id, {
        kind: "accessed by",
        color: "#38bdf8",
        distance: 60,
        particles: 1,
      });
    }
    const consumers = Object.keys(byConsumer).length;
    signals.push({
      severity: "info",
      code: "access-log",
      nodeId: hid,
      text: useRecord
        ? `${consumers} organisations read my record ${served.length} times in the last 12 months. Click to see who.`
        : consumers > 0
          ? `${consumers} organisations read data from ${input.holder.name} in the last 12 months (${served.length} accesses); no read of my record is on file. Click to see who.`
          : `No access to ${input.holder.name}'s data recorded in the last 12 months.`,
      article: "Art. 9 information on access, Art. 73(1)(e) log",
    });
  }
 
  // ── measured values over time ─────────────────────────────────────────────
  // In the order of PARAMETER_META, so HbA1c leads whatever the Bundle's order
  const byCode = new Map(
    bundleToParameters(observations).map((p) => [p.code, p]),
  );
  const params = Object.keys(PARAMETER_META)
    .map((code) => byCode.get(code))
    .filter((p): p is NonNullable<typeof p> => Boolean(p));
  let paramCount = 0;
  let firstParam: string | null = null;
  for (const p of params) {
    const meta = PARAMETER_META[p.code];
    Iif (!meta || p.series.length === 0) continue;
    paramCount++;
    const trend = trendOf(p.series, {
      range: p.range,
      higherIsWorse: meta.higherIsWorse !== false,
    });
    const last = p.series[p.series.length - 1];
    const first = p.series[0];
    const sev: Severity =
      trend?.severity ?? (isOutOfRange(last.value, p.range) ? "warn" : "ok");
    const id = `param:${p.code}`;
    firstParam ??= id;
    const points = p.series.map((m) => {
      const out = isOutOfRange(m.value, p.range);
      return {
        id: `obs:${m.id}`,
        label: `${m.date.slice(0, 7)} · ${m.value}`,
        layer: "me",
        kind: "Measurement",
        size: 0.9,
        color: out ? "#f59e0b" : "#86efac",
        title: `${meta.key} on ${m.date}`,
        sub: `${m.value} ${p.unit}${
          out ? ", outside the printed range" : ", within the printed range"
        }`,
        facts: [
          ["LOINC", p.code],
          ["reference", p.range?.text ?? "n/a"],
          ["source", p.performer ?? "lab"],
          ["resource", `Observation/${m.id}`],
        ] as [string, string][],
        article:
          "One FHIR R4 Observation. Art. 3: I can read it; Art. 7: portable.",
      } satisfies OverviewNode;
    });
    const expandLinks: OverviewLink[] = [];
    points.forEach((x, i) => {
      expandLinks.push({
        source: id,
        target: x.id,
        kind: "measured",
        color: "#64748b",
        distance: 45,
      });
      if (i > 0) {
        expandLinks.push({
          source: points[i - 1].id,
          target: x.id,
          kind: "next",
          color: "#93c5fd",
          distance: 28,
          arrow: true,
          particles: 1,
        });
      }
    });
    add({
      id,
      label: `${meta.key} ${last.value} ${p.unit}`,
      layer: "risk",
      kind: "Parameter",
      size: 2,
      status: sev,
      pulse: sev === "bad",
      series: p.series.map(({ date, value }) => ({ date, value })),
      unit: p.unit,
      measure: meta.key,
      range: p.range,
      higherIsWorse: meta.higherIsWorse !== false,
      title: p.display,
      sub: `LOINC ${p.code}, ${p.series.length} measurements, ${
        p.performer ?? "lab"
      }`,
      description: meta.description,
      facts: [
        ["latest", `${last.value} ${p.unit} on ${last.date}`],
        ["first", `${first.value} ${p.unit} on ${first.date}`],
        ["reference", p.range?.text ?? "n/a"],
      ],
      article:
        "Art. 14 priority category: laboratory results. FHIR R4 Observation with LOINC code; the range is the one printed on the report, never app-generated.",
      links: [{ href: "/patient/profile", text: "My profile" }],
      expand: { nodes: points, links: expandLinks },
    });
    const factorId = meta.factor
      ? [...factorNodes.keys()].find((fid) => meta.factor!.test(fid))
      : undefined;
    const riskId =
      meta.risk && ids.has(`risk:${meta.risk}`)
        ? `risk:${meta.risk}`
        : undefined;
    if (factorId) {
      link(id, factorId, {
        kind: "behind",
        status: sev,
        distance: 40,
        particles: 1,
      });
    } else if (riskId) {
      link(id, riskId, {
        kind: "drives",
        status: sev,
        distance: 60,
        particles: 1,
      });
    } else Elink(id, "me", { kind: "measured", status: sev, distance: 60 });
    Eif (sev !== "ok" && trend) {
      paramSignals.push({
        severity: sev,
        code: trend.outOfRange ? "parameter-out-of-range" : "parameter-trend",
        nodeId: id,
        text: `${meta.key} ${trend.dir}${
          trend.dir === "stable"
            ? ""
            : ` from ${first.value} to ${last.value} ${p.unit}`
        }${trend.outOfRange ? ", outside the printed range" : ""}`,
        article:
          "Art. 14 laboratory results; click to see the trend and unfold the measurements",
      });
    }
  }
  if (paramCount > 0) {
    signals.push({
      severity: "info",
      code: "parameters",
      nodeId: firstParam ?? "me",
      text: `${paramCount} parameters from ${
        observations.total ?? observations.entry.length
      } FHIR Observations. Click a parameter to see its trend and unfold the single measurements.`,
      article:
        "Art. 14 priority category: laboratory results; Art. 7 portability",
    });
  }
 
  const known = new Set(nodes.map((n) => n.id));
  return {
    persona: "patient",
    asOf: input.asOf,
    me: { id: me.id, name: me.name },
    title: "My health, in one view",
    question:
      "Which parameters put me at risk, what should I do about them, and who is using my data?",
    article: "Regulation (EU) 2025/327 Art. 3, 7, 9, 14, 71, 73",
    layers,
    nodes,
    links: links.filter((l) => known.has(l.source) && known.has(l.target)),
    signals: rankSignals([...paramSignals, ...signals]),
    legend: [
      { color: "#ef4444", text: "high risk / act" },
      { color: "#f59e0b", text: "moderate / watch" },
      { color: "#38bdf8", text: "information" },
      { color: "#22c55e", text: "consented, in order" },
      { color: "#86efac", text: "diagnosis" },
      { color: "#c4b5fd", text: "medication" },
    ],
    dataNote: "Every patient and organisation shown is fictional.",
  };
}
 
/**
 * The patient a demo login owns. The demo users patient1 and patient2 map to
 * the seeded records P1 and P2; anyone else is not a patient here.
 */
export function ownPatientId(username?: string | null): string | null {
  if (username === "patient1") return "P1";
  if (username === "patient2") return "P2";
  // A sandbox login the Klarbefund app created owns its own record (ADR-054).
  return username ? sandboxPatientId(username) : null;
}
 
/**
 * The patient a session owns. Keycloak puts the display name ("Maria
 * Schmidt") in `user.name` and the login name in `preferredUsername`; the
 * static demo and the unit tests carry the login name in `user.name`.
 */
export function ownPatientIdForSession(
  session:
    | {
        preferredUsername?: string | null;
        user?: {
          name?: string | null;
          email?: string | null;
          preferredUsername?: string | null;
        } | null;
      }
    | null
    | undefined,
): string | null {
  if (!session) return null;
  // The session callback in auth.ts puts the login name on user.preferredUsername
  // (a Keycloak login and a wallet login alike); the top-level field is what
  // the static demo and older callers pass. The wallet session has no email,
  // so without the first candidate a patient signed in with d-you was refused
  // their own record.
  const candidates = [
    session.user?.preferredUsername,
    session.preferredUsername,
    session.user?.name,
    session.user?.email?.split("@")[0],
  ];
  for (const c of candidates) {
    const id = ownPatientId(c ?? null);
    if (id) return id;
  }
  return null;
}