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 | 3x 3x 3x 3x 5x 3x 3x 3x 3x 3x 3x 4x 7x 7x 13x 1x 1x 12x 12x 3x 3x 3x 3x 4x 4x 1x 3x 3x 3x 1x 2x 10x 10x 2x 8x 5x 5x 5x 5x 1x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 2x 5x 5x 4x 4x 4x 1x 3x 3x | /**
* Consent to a bonus program (#934, step 4; ADR-080, decision 6).
*
* A person joins one program, sees that they joined, and withdraws, each on
* their own record. It is its own record, (:ProgrammeConsent), next to two
* that sound close and are not this one: study consent (PatientConsent) and
* the Art. 71 opt-out (OptOutRecord). The opt-out governs secondary use and
* does not stop sharing the person directs themselves, so nothing here reads
* it; joining a program never enrolls anyone in research.
*
* Withdrawal ends transfers at once: programmeTransferAllowed() is the one
* gate every transfer of a program's answer passes, and it asks for an open
* consent (GDPR Art. 7(3), Art. 9(2)(a)).
*/
import { randomUUID } from "node:crypto";
import { NextResponse } from "next/server";
import { runQuery } from "@/lib/neo4j";
import type {
BonusProgramme,
ProgrammeConsent,
} from "@/lib/patient/bonus-programme";
import { memberReference } from "@/lib/patient/member-reference";
import { ownRecordId, refuseForeignRecord } from "@/lib/patient/own-record";
import {
evaluateYear,
ruleYear,
type YearEvaluation,
} from "@/lib/patient/programme-rule";
const PATIENT_BY_KEY = `MATCH (p:Patient)
WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId`;
/** One consent of one person to one program; open while withdrawnAt is null. */
export type ProgrammeConsentRow = ProgrammeConsent;
/**
* Join: an open consent for the program, or the one already open. A program
* the crawler has not indexed, or a record that does not exist, returns no
* row. MERGE on a consent id made by the caller, so a retried request with
* the same id writes nothing twice.
*/
export const JOIN_PROGRAMME_CYPHER = `${PATIENT_BY_KEY}
MATCH (s:BonusProgramme {serviceId: $programmeId})
OPTIONAL MATCH (p)-[:GAVE_PROGRAMME_CONSENT]->(open:ProgrammeConsent {programmeId: $programmeId})
WHERE open.withdrawnAt IS NULL
WITH p, s, open
CALL (p, s, open) {
WITH p, s, open WHERE open IS NULL
MERGE (c:ProgrammeConsent {consentId: $consentId})
ON CREATE SET c.patientId = $patientId,
c.programmeId = $programmeId,
c.joinedAt = datetime(),
c.source = $source
MERGE (p)-[:GAVE_PROGRAMME_CONSENT]->(c)
MERGE (c)-[:FOR_PROGRAMME]->(s)
RETURN c
UNION
WITH open WHERE open IS NOT NULL
RETURN open AS c
}
RETURN c.consentId AS consentId, c.programmeId AS programmeId,
toString(c.joinedAt) AS joinedAt, toString(c.withdrawnAt) AS withdrawnAt`;
/** Withdraw: close the open consent. No row when none is open. */
export const WITHDRAW_PROGRAMME_CYPHER = `MATCH (c:ProgrammeConsent {patientId: $patientId, programmeId: $programmeId})
WHERE c.withdrawnAt IS NULL
SET c.withdrawnAt = datetime()
RETURN c.consentId AS consentId, c.programmeId AS programmeId,
toString(c.joinedAt) AS joinedAt, toString(c.withdrawnAt) AS withdrawnAt`;
/**
* Every consent of the person to any program, newest first, with the date
* the insurer last collected an answer under it (step 8, ADR-091): the
* neo4j-proxy stamps deliveredAt on the transfer it hands over.
*/
export const PROGRAMME_CONSENTS_CYPHER = `MATCH (c:ProgrammeConsent {patientId: $patientId})
OPTIONAL MATCH (t:ProgrammeTransfer)-[:UNDER_CONSENT]->(c)
WHERE t.deliveredAt IS NOT NULL
WITH c, max(t.deliveredAt) AS collectedAt
RETURN c.consentId AS consentId, c.programmeId AS programmeId,
toString(c.joinedAt) AS joinedAt, toString(c.withdrawnAt) AS withdrawnAt,
toString(collectedAt) AS collectedAt
ORDER BY c.joinedAt DESC`;
/** A consent as the member reads it: with the reference its answers carry. */
function withReference(row: ProgrammeConsentRow): ProgrammeConsentRow {
return { ...row, memberReference: memberReference(row.consentId) };
}
/** The open consent, if any: what the transfer gate reads. */
export const OPEN_PROGRAMME_CONSENT_CYPHER = `MATCH (c:ProgrammeConsent {patientId: $patientId, programmeId: $programmeId})
WHERE c.withdrawnAt IS NULL
RETURN c.consentId AS consentId
LIMIT 1`;
/**
* A transfer the person asked for (ADR-080, decision 4, second path). What it
* carries is the program, the year and goal met, nothing else: the hub has
* evaluated the ended year inside the record (step 6, ADR-087), and the
* breakdown behind the answer is not stored with it. The insurer collects
* it over its agreement with the hub (step 8, ADR-091): the neo4j-proxy's
* /programmes/answers hands it over with the member's reference and sets
* the status to delivered. Until then the status says it is ready.
*/
export const RECORD_TRANSFER_CYPHER = `MATCH (c:ProgrammeConsent {consentId: $consentId})
MERGE (t:ProgrammeTransfer {transferId: $transferId})
ON CREATE SET t.patientId = $patientId,
t.programmeId = $programmeId,
t.year = toInteger($year),
t.goalMet = $goalMet,
t.status = 'evaluated',
t.requestedAt = datetime()
MERGE (t)-[:UNDER_CONSENT]->(c)
RETURN t.transferId AS transferId, t.programmeId AS programmeId, t.year AS year,
t.goalMet AS goalMet, t.status AS status, toString(t.requestedAt) AS requestedAt`;
export interface ProgrammeTransferRow {
transferId: string;
programmeId: string;
year: number;
goalMet: boolean | null;
status: string;
requestedAt: string;
}
/**
* Where a join came from. The API collection marks its own with
* "api-collection", so the live clean-up removes them and nothing else
* (neo4j/remove-api-collection-runs.cypher).
*/
export const PROGRAMME_CONSENT_SOURCES = [
"patient-portal",
"klarbefund",
"api-collection",
] as const;
/** The legal basis the routes name in their answers. */
const PROGRAMME_CONSENT_BASIS =
"Explicit consent to one program, GDPR Art. 9(2)(a), withdrawable at any time, Art. 7(3); EHDS Art. 7(3) (ADR-080)";
/** A program's rule version, or no row when the crawler never indexed it. */
export const PROGRAMME_RULE_CYPHER = `MATCH (s:BonusProgramme {serviceId: $programmeId})
RETURN s.ruleVersion AS ruleVersion
LIMIT 1`;
/** The open consent of a person to a program, or null. */
export function openConsent(
rows: ProgrammeConsentRow[],
programmeId: string,
): ProgrammeConsentRow | null {
return (
rows.find((r) => r.programmeId === programmeId && !r.withdrawnAt) ?? null
);
}
/**
* The gate: the consent id a transfer may go out under, or null when the
* person has not joined the program or has withdrawn.
*/
async function programmeTransferAllowed(
patientId: string,
programmeId: string,
): Promise<string | null> {
const [row] = await runQuery<{ consentId: string }>(
OPEN_PROGRAMME_CONSENT_CYPHER,
{ patientId, programmeId },
);
return row?.consentId ?? null;
}
/**
* Whose record a program route acts on, after the route's own requireAuth()
* (ADR-044: the gate stays visible in each handler). A PATIENT acts on their
* own record only (a foreign patientId is refused with 403, #475); EDC_ADMIN
* names one. With required=false a session without a record (an operator who
* names none) gets { patientId: null }, which the list route answers without
* consents.
*/
export async function resolveProgrammePatient(
roles: readonly string[],
named: string | null,
required = true,
): Promise<{ patientId: string | null } | NextResponse> {
const patientId = named ?? (await ownRecordId());
Eif (!patientId) {
return required
? NextResponse.json({ error: "patientId is required" }, { status: 400 })
: { patientId: null };
}
const refused = await refuseForeignRecord(roles, patientId);
return refused ?? { patientId };
}
/**
* The bonus programs the crawler indexed, as the enricher wrote it (DCAT-AP
* dcat:DataService typed ehds:BonusProgramme, #934 step 3). Only those the
* publisher's latest catalogue still lists: the enricher stamps lastSeenAt
* on each crawl and never deletes, so a programme a catalogue dropped
* (2027 became 2025, ADR-087) is left out here, while the consents given to
* it stay on record.
*/
export const BONUS_PROGRAMMES_CYPHER = `MATCH (s:DataService:BonusProgramme)
OPTIONAL MATCH (s)-[:PUBLISHED_BY]->(p:Participant)
WITH s, p, coalesce(p.participantId, s.publisherDid, s.serviceId) AS publisher
WITH publisher, collect({s: s, p: p}) AS offers, max(s.lastSeenAt) AS latest
UNWIND offers AS offer
WITH offer.s AS s, offer.p AS p, latest
WHERE s.lastSeenAt IS NULL OR latest IS NULL
OR s.lastSeenAt >= latest - duration('PT1H')
RETURN s.serviceId AS programmeId,
s.title AS title,
s.description AS description,
coalesce(p.name, s.publisherName, s.publisherDid) AS publisherName,
s.publisherDid AS publisherDid,
p.dataSpace AS dataSpace,
s.endpointUrl AS endpointUrl,
s.ruleTitle AS ruleTitle,
s.ruleDescription AS ruleDescription,
s.ruleVersion AS ruleVersion,
toString(s.lastSeenAt) AS lastSeenAt
ORDER BY s.title`;
/**
* What happens once a route has decided whose record it acts on. The portal
* routes (a session, requireAuth) and the Klarbefund routes (an app token,
* requireAppToken, ADR-049) each keep their own gate and call these, so the
* phone and the browser get the same answers from the same queries.
*/
/** The offer and the person's own consents; none for a record left unnamed. */
export async function listProgrammes(patientId: string | null) {
const programmes = await runQuery<BonusProgramme>(BONUS_PROGRAMMES_CYPHER);
const consents = patientId
? (
await runQuery<ProgrammeConsentRow>(PROGRAMME_CONSENTS_CYPHER, {
patientId,
})
).map(withReference)
: [];
return {
programmes,
consents,
legalBasis:
"Primary use the person directs, EHDS Art. 2(2)(d) and 7(3); explicit consent, GDPR Art. 9(2)(a) (ADR-080)",
};
}
/** Join: 201 with the open consent, or 404 for an unknown program or record. */
export async function joinProgramme(
patientId: string,
programmeId: string,
source: (typeof PROGRAMME_CONSENT_SOURCES)[number],
): Promise<NextResponse> {
const [consent] = await runQuery<ProgrammeConsentRow>(JOIN_PROGRAMME_CYPHER, {
patientId,
programmeId,
consentId: randomUUID(),
source,
});
if (!consent) {
return NextResponse.json(
{
error: `No bonus program '${programmeId}', or no record '${patientId}'`,
},
{ status: 404 },
);
}
return NextResponse.json(
{ consent: withReference(consent), legalBasis: PROGRAMME_CONSENT_BASIS },
{ status: 201 },
);
}
/** Withdraw: 200 with the closed consent, or 404 when none is open. */
export async function withdrawProgramme(
patientId: string,
programmeId: string,
): Promise<NextResponse> {
const [consent] = await runQuery<ProgrammeConsentRow>(
WITHDRAW_PROGRAMME_CYPHER,
{ patientId, programmeId },
);
if (!consent) {
return NextResponse.json(
{ error: "There is no open consent to this program to withdraw" },
{ status: 404 },
);
}
return NextResponse.json({ consent, legalBasis: PROGRAMME_CONSENT_BASIS });
}
/** A transfer body's program and calendar year, or a 400. */
export function parseTransferRequest(body: {
programmeId?: unknown;
year?: unknown;
}): { programmeId: string; year: number } | NextResponse {
const year = Number(body.year);
if (
typeof body.programmeId !== "string" ||
!body.programmeId ||
!Number.isInteger(year) ||
year < 2000 ||
year > 2100
) {
return NextResponse.json(
{ error: "programmeId and a calendar year are required" },
{ status: 400 },
);
}
return { programmeId: body.programmeId, year };
}
/**
* Checks that the program exists and that its rule covers the year: 404 for
* a program the crawler never indexed, 400 for a year its rule does not
* cover. A rule version that names no year covers any.
*/
async function checkProgrammeYear(
programmeId: string,
year: number,
): Promise<NextResponse | null> {
const [programme] = await runQuery<{ ruleVersion: string | null }>(
PROGRAMME_RULE_CYPHER,
{ programmeId },
);
Iif (!programme) {
return NextResponse.json(
{ error: `No bonus program '${programmeId}'` },
{ status: 404 },
);
}
const covered = ruleYear(programme.ruleVersion);
if (covered !== null && covered !== year) {
return NextResponse.json(
{ error: `This program's rule covers ${covered}, not ${year}` },
{ status: 400 },
);
}
return null;
}
/** The year the request names, or the program's rule year, or a 400. */
export function parseEvaluationRequest(
params: URLSearchParams,
): { programmeId: string; year: number | null } | NextResponse {
const programmeId = params.get("programmeId");
const raw = params.get("year");
const year = raw === null ? null : Number(raw);
Iif (
!programmeId ||
(year !== null && (!Number.isInteger(year) || year < 2000 || year > 2100))
) {
return NextResponse.json(
{ error: "programmeId is required, and year must be a calendar year" },
{ status: 400 },
);
}
return { programmeId, year };
}
/**
* The member's own result for a program year, before anything is sent
* (ADR-080, decision 3). The breakdown is in the answer because the member
* is the one reading it; it is never stored with a transfer.
*/
export async function evaluateProgrammeYear(
patientId: string,
programmeId: string,
year: number | null,
now: Date = new Date(),
): Promise<NextResponse> {
let target = year;
if (target === null) {
const [programme] = await runQuery<{ ruleVersion: string | null }>(
PROGRAMME_RULE_CYPHER,
{ programmeId },
);
Iif (!programme) {
return NextResponse.json(
{ error: `No bonus program '${programmeId}'` },
{ status: 404 },
);
}
target = ruleYear(programme.ruleVersion) ?? now.getUTCFullYear() - 1;
} else E{
const refused = await checkProgrammeYear(programmeId, target);
if (refused) return refused;
}
const evaluation = await evaluateYear(patientId, target, now);
Iif (!evaluation) {
return NextResponse.json({ error: "Patient not found" }, { status: 404 });
}
return NextResponse.json({ programmeId, evaluation });
}
/**
* The person's instruction to send a year's answer. Only under an open
* consent (403 otherwise, and nothing is recorded, GDPR Art. 7(3)); only for
* a year the program's rule covers (400) and that has ended (409, with the
* date it can be evaluated). Then the hub evaluates the year inside the
* record and records the program, the year and goal met: 202.
*/
export async function requestProgrammeTransfer(
patientId: string,
programmeId: string,
year: number,
now: Date = new Date(),
): Promise<NextResponse> {
const consentId = await programmeTransferAllowed(patientId, programmeId);
if (!consentId) {
return NextResponse.json(
{
error:
"No open consent to this program: join it first. After a withdrawal nothing is sent.",
},
{ status: 403 },
);
}
const refused = await checkProgrammeYear(programmeId, year);
if (refused) return refused;
const evaluation: YearEvaluation | null = await evaluateYear(
patientId,
year,
now,
);
Iif (!evaluation) {
return NextResponse.json({ error: "Patient not found" }, { status: 404 });
}
if (evaluation.status === "year-not-over") {
return NextResponse.json(
{
error: `${year} is not over: the hub evaluates it from ${evaluation.evaluableFrom}, and nothing is sent before.`,
evaluation,
},
{ status: 409 },
);
}
const [transfer] = await runQuery<ProgrammeTransferRow>(
RECORD_TRANSFER_CYPHER,
{
consentId,
transferId: randomUUID(),
patientId,
programmeId,
year,
goalMet: evaluation.goalMet,
},
);
return NextResponse.json(
{ transfer, legalBasis: PROGRAMME_CONSENT_BASIS },
{ status: 202 },
);
}
|