All files / src/lib/overview derive.ts

97.85% Statements 137/140
90.57% Branches 125/138
100% Functions 29/29
98.23% Lines 111/113

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                                                                                      89x             89x 89x       48x         29x 649x                 1554x 833x 833x 794x 169x         216x 216x 216x                                   178x 1214x 176x 176x 176x 178x   178x 178x   178x 178x 178x 178x   178x 141x 92x 176x         176x         30x 30x 30x 350x 350x   30x                                                 131x   698x 59x 59x 152x 152x 151x 151x 150x   59x 59x 698x   59x                                         126x 125x 125x 125x 81x   80x 80x                                                 176x 176x 175x 151x 87x 40x 40x 39x   84x                                                   49x     2x 2x 2x   49x 49x 49x 49x                                                                             51x 51x 51x 70x   51x 70x       51x 200x     51x 13x               51x 19x 19x 15x 34x   15x 14x                       1x               4x                       65x 65x 65x 51x 6x               51x 2x               65x 1x                       51x 51x 58x   51x 8x             43x                   51x 45x     51x    
/**
 * Derived state for the persona overviews (discussion #265).
 *
 * The four persona views show state, not structure: a value against its
 * expected band, a trend over months, a consumer's chain of trust, a decision
 * clock. Every one of these is a small pure function over data the platform
 * already holds. They live here, not in the browser, so the API route, the
 * page, the activity report and the tests all compute them the same way.
 *
 * Nothing in this file touches Neo4j or the network. The functions take plain
 * records as the API routes return them (ISO date strings, numbers, nulls).
 *
 * Article numbers are those of Regulation (EU) 2025/327 as adopted, see
 * docs/ehds-article-numbering.md.
 */
 
export type Severity = "ok" | "info" | "warn" | "bad";
 
export type OverviewPersona = "patient" | "researcher" | "hdab" | "hospital";
 
export interface SeriesPoint {
  /** ISO date, YYYY-MM-DD */
  date: string;
  value: number;
}
 
export interface Range {
  low?: number | null;
  high?: number | null;
  /** The band as printed, e.g. "4.0 - 6.0 %" or "> 90 mL/min" */
  text?: string;
}
 
export interface Trend {
  dir: "rising" | "falling" | "stable";
  severity: Severity;
  first: number;
  last: number;
  outOfRange: boolean;
  /** Whole months between the first and the last point */
  months: number;
}
 
const SEVERITY_RANK: Record<Severity, number> = {
  ok: 0,
  info: 1,
  warn: 2,
  bad: 3,
};
 
const MS_PER_DAY = 86_400_000;
const MS_PER_MONTH = 2_629_800_000;
 
/** The higher of two severities. */
export function severityMax(a: Severity, b: Severity): Severity {
  return SEVERITY_RANK[a] >= SEVERITY_RANK[b] ? a : b;
}
 
/** Stable sort, worst first: bad, warn, info, ok. */
export function rankSignals<T extends { severity: Severity }>(list: T[]): T[] {
  return [...list].sort(
    (a, b) => SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity],
  );
}
 
/** True when the value lies outside the band. An open end never fails. */
export function isOutOfRange(
  value: number,
  range: Range | null | undefined,
): boolean {
  if (!range) return false;
  const { low, high } = range;
  if (low != null && value < low) return true;
  if (high != null && value > high) return true;
  return false;
}
 
/** Whole days from `from` to `to`, negative when `to` is earlier. */
export function daysBetween(from: string | Date, to: string | Date): number {
  const a = new Date(from).getTime();
  const b = new Date(to).getTime();
  return Math.round((b - a) / MS_PER_DAY);
}
 
/**
 * Direction and severity of a series against its band.
 *
 * The direction is judged relative to the width of the band (or a fifth of
 * the first value when there is no band): a move of less than 15 % of that
 * width is "stable". The severity is "bad" when the last value is outside
 * the band and moving the wrong way, "warn" when it is outside but improving
 * or inside but moving the wrong way, "ok" otherwise. `higherIsWorse` is
 * true by default (HbA1c, refusals, pending applications); false for values
 * where a fall is the problem (eGFR, conformance score, permitted use).
 */
export function trendOf(
  series: SeriesPoint[],
  opts: { range?: Range | null; higherIsWorse?: boolean } = {},
): Trend | null {
  if (!series || series.length < 2) return null;
  const sorted = [...series].sort((a, b) => a.date.localeCompare(b.date));
  const first = sorted[0].value;
  const last = sorted[sorted.length - 1].value;
  const lo = opts.range?.low;
  const hi = opts.range?.high;
  const width =
    lo != null && hi != null && hi > lo ? hi - lo : Math.abs(first) * 0.2 || 1;
  const rel = (last - first) / width;
  const dir: Trend["dir"] =
    Math.abs(rel) < 0.15 ? "stable" : rel > 0 ? "rising" : "falling";
  const outOfRange = isOutOfRange(last, opts.range);
  const higherIsWorse = opts.higherIsWorse !== false;
  const wrongWay = higherIsWorse ? dir === "rising" : dir === "falling";
  let severity: Severity;
  if (dir === "stable") severity = outOfRange ? "warn" : "ok";
  else if (wrongWay) severity = outOfRange ? "bad" : "warn";
  else severity = outOfRange ? "warn" : "ok";
  const months = Math.round(
    (new Date(sorted[sorted.length - 1].date).getTime() -
      new Date(sorted[0].date).getTime()) /
      MS_PER_MONTH,
  );
  return { dir, severity, first, last, outOfRange, months };
}
 
/** The first day of each of the last `months` months up to `asOf`, oldest first. */
export function monthRange(asOf: string | Date, months = 12): string[] {
  const d = new Date(asOf);
  const out: string[] = [];
  for (let i = months - 1; i >= 0; i--) {
    const m = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() - i, 1));
    out.push(m.toISOString().slice(0, 10));
  }
  return out;
}
 
export interface AccessEvent {
  id?: string;
  /** ISO timestamp */
  accessedAt: string;
  consumerDid: string;
  providerDid?: string | null;
  datasetId?: string | null;
  statusCode?: number | null;
  permitId?: string | null;
  contractId?: string | null;
  responseBytes?: number | null;
}
 
/**
 * Group events by `keyOf` and count (or sum `valueOf`) per month, with every
 * month of the window present, zero-filled. Events outside the window and
 * events whose key is null are dropped.
 */
export function aggregateMonthly<E extends { accessedAt: string }>(
  events: E[],
  months: string[],
  keyOf: (e: E) => string | null,
  valueOf: (e: E) => number = () => 1,
): Record<string, SeriesPoint[]> {
  const index = new Map(months.map((m, i) => [m.slice(0, 7), i]));
  const out: Record<string, number[]> = {};
  for (const e of events) {
    const key = keyOf(e);
    if (key == null) continue;
    const i = index.get(e.accessedAt.slice(0, 7));
    if (i == null) continue;
    (out[key] ??= new Array(months.length).fill(0))[i] += valueOf(e);
  }
  const result: Record<string, SeriesPoint[]> = {};
  for (const [key, values] of Object.entries(out)) {
    result[key] = months.map((date, i) => ({ date, value: values[i] }));
  }
  return result;
}
 
export type CredentialState = "active" | "expiring" | "expired" | "revoked";
 
export interface CredentialLike {
  credentialType?: string | null;
  status?: string | null;
  expiresAt?: string | null;
  revoked?: boolean | null;
}
 
/**
 * The state of a credential derived from its dates, never from its `status`
 * flag alone: the fixtures keep "active" on credentials past their expiry.
 */
export function credentialState(
  cred: CredentialLike,
  asOf: string | Date,
  expiringDays = 30,
): CredentialState {
  if (cred.revoked || cred.status === "revoked") return "revoked";
  Eif (cred.expiresAt) {
    const left = daysBetween(asOf, cred.expiresAt);
    if (left < 0) return "expired";
    if (left <= expiringDays) return "expiring";
  }
  Iif (cred.status === "expired") return "expired";
  return "active";
}
 
export type PermitState =
  | "valid"
  | "expiring"
  | "expired"
  | "refused"
  | "revoked"
  | "pending";
 
export interface PermitLike {
  permitId?: string | null;
  status?: string | null;
  validUntil?: string | null;
  revokedAt?: string | null;
  outcome?: string | null;
}
 
/** The state of an Art. 68 permit as of a date. */
export function permitState(
  permit: PermitLike,
  asOf: string | Date,
  expiringDays = 30,
): PermitState {
  const status = (permit.status ?? permit.outcome ?? "").toUpperCase();
  if (permit.revokedAt || status.includes("REVOKED")) return "revoked";
  if (status.includes("REJECT") || status.includes("REFUSED")) return "refused";
  if (status === "PENDING" || status === "UNDER_REVIEW") return "pending";
  if (permit.validUntil) {
    const left = daysBetween(asOf, permit.validUntil);
    if (left < 0) return "expired";
    if (left <= expiringDays) return "expiring";
  }
  return "valid";
}
 
export interface DecisionClock {
  /** ISO date the decision is due */
  dueAt: string;
  /** Days left as of `asOf`; negative when overdue */
  daysLeft: number;
  overdue: boolean;
  decided: boolean;
}
 
/**
 * The Art. 68(4) clock: an access body decides within three months of a
 * complete application. Art. 69(4) applies the same period to a health data
 * request. A decided application has no clock left to run.
 */
export function decisionClock(
  app: {
    submittedAt: string;
    decidedAt?: string | null;
    decisionDue?: string | null;
  },
  asOf: string | Date,
  months = 3,
): DecisionClock {
  const due = app.decisionDue
    ? new Date(app.decisionDue)
    : (() => {
        const d = new Date(app.submittedAt);
        d.setUTCMonth(d.getUTCMonth() + months);
        return d;
      })();
  const dueAt = due.toISOString().slice(0, 10);
  const decided = Boolean(app.decidedAt);
  const daysLeft = daysBetween(asOf, due);
  return { dueAt, daysLeft, overdue: !decided && daysLeft < 0, decided };
}
 
export interface Finding {
  severity: Severity;
  /** Stable machine code, e.g. "access-after-credential-expiry" */
  code: string;
  /** The id of the node the finding attaches to (consumer DID, permit id) */
  subject: string;
  text: string;
  /** The article the finding rests on, adopted numbering */
  article: string;
}
 
export interface ChainInput {
  consumerDid: string;
  consumerName?: string;
  credentials: CredentialLike[];
  permits: PermitLike[];
  contracts: { contractId: string; consumerDid?: string | null }[];
  events: AccessEvent[];
}
 
export interface ChainOfTrust {
  trusted: boolean;
  severity: Severity;
  findings: Finding[];
}
 
/**
 * Trust, in EHDS terms, is a chain and not a flag: DCP credentials
 * (membership, participant, purpose), an Art. 68 permit, a DSP contract, and
 * an access log that agrees with all three. This computes it that way for one
 * consumer, as of a date.
 */
export function chainOfTrust(
  input: ChainInput,
  asOf: string | Date,
): ChainOfTrust {
  const who = input.consumerName ?? input.consumerDid;
  const findings: Finding[] = [];
  const served = input.events.filter(
    (e) => (e.statusCode ?? 200) < 400 && e.consumerDid === input.consumerDid,
  );
  const refused = input.events.filter(
    (e) => (e.statusCode ?? 200) >= 400 && e.consumerDid === input.consumerDid,
  );
 
  // 1. Credentials in the wallet
  const byType = (t: string) =>
    input.credentials.filter((c) =>
      (c.credentialType ?? "").toLowerCase().includes(t),
    );
  if (byType("membership").length === 0) {
    findings.push({
      severity: "bad",
      code: "no-membership-credential",
      subject: input.consumerDid,
      text: `${who} presents no membership credential; nothing in the wallet says who they are.`,
      article: "DCP v1.0 membership credential; Art. 61(1)",
    });
  }
  for (const purpose of byType("purpose")) {
    const state = credentialState(purpose, asOf);
    if (state === "expired" || state === "revoked") {
      const after = purpose.expiresAt
        ? served.filter((e) => e.accessedAt > purpose.expiresAt!)
        : served;
      if (after.length > 0) {
        findings.push({
          severity: "bad",
          code: "access-after-credential-expiry",
          subject: input.consumerDid,
          text: `${who}: ${
            after.length
          } accesses served after the purpose credential ${state} on ${(
            purpose.expiresAt ?? ""
          ).slice(0, 10)}.`,
          article: "Art. 53(1), Art. 61(1)",
        });
      } else {
        findings.push({
          severity: "warn",
          code: "credential-expired",
          subject: input.consumerDid,
          text: `${who}: the purpose credential ${state}; the next access will have no valid purpose.`,
          article: "Art. 53(1)",
        });
      }
    } else Iif (state === "expiring") {
      findings.push({
        severity: "warn",
        code: "credential-expiring",
        subject: input.consumerDid,
        text: `${who}: the purpose credential expires within 30 days.`,
        article: "Art. 53(1)",
      });
    }
  }
 
  // 2. Permits
  const states = input.permits.map((p) => ({ p, s: permitState(p, asOf) }));
  const valid = states.filter((x) => x.s === "valid" || x.s === "expiring");
  const refusedPermit = states.find((x) => x.s === "refused");
  if (refusedPermit && refused.length > 0) {
    findings.push({
      severity: "bad",
      code: "access-attempt-after-refusal",
      subject: input.consumerDid,
      text: `${who}: ${refused.length} access attempts refused after the application was refused; a matter for enforcement.`,
      article: "Art. 61(1), Art. 63",
    });
  }
  if (served.length > 0 && valid.length === 0) {
    findings.push({
      severity: "bad",
      code: "access-without-permit",
      subject: input.consumerDid,
      text: `${who}: ${served.length} accesses served with no valid permit as of today.`,
      article: "Art. 61(1), Art. 68",
    });
  }
  for (const { p } of states.filter((x) => x.s === "expiring")) {
    findings.push({
      severity: "warn",
      code: "permit-expiring",
      subject: p.permitId ?? input.consumerDid,
      text: `${who}: permit ${p.permitId ?? ""} expires on ${(
        p.validUntil ?? ""
      ).slice(0, 10)}; renewal or the end of access.`,
      article: "Art. 68(6)",
    });
  }
 
  // 3. Contracts behind the served accesses
  const contractIds = new Set(input.contracts.map((c) => c.contractId));
  const uncovered = served.filter(
    (e) => !e.contractId || !contractIds.has(e.contractId),
  );
  if (served.length > 0 && uncovered.length === served.length) {
    findings.push({
      severity: valid.length > 0 ? "warn" : "bad",
      code: "transfer-without-contract",
      subject: input.consumerDid,
      text: `${who}: ${uncovered.length} accesses served with no DSP contract on file.`,
      article: "DSP 2025-1 contract agreement; Art. 60(1)",
    });
  } else Iif (uncovered.length > 0) {
    findings.push({
      severity: "warn",
      code: "transfer-partly-without-contract",
      subject: input.consumerDid,
      text: `${who}: ${uncovered.length} of ${served.length} accesses carry no contract reference.`,
      article: "DSP 2025-1 contract agreement",
    });
  }
 
  const severity = findings.reduce<Severity>(
    (acc, f) => severityMax(acc, f.severity),
    "ok",
  );
  return { trusted: severity !== "bad", severity, findings };
}