feat(export): make the doctor report carry only what was chosen

The report resolved an absent key to "included". A caller that sent no
sections object, or an empty group inside one, received the full record at
server-chosen defaults: roughly fifty metrics plus the medication list, labs,
allergies and family history. The web panel sent every key explicitly so it
looked fine from the browser, but the share link, the FHIR REST face, the MCP
doctor-visit resource and the cycle-only export card all went through paths
where absence meant yes. No arrangement of booleans fixes a default that means
yes, so the shape goes.

A selection is now an inclusion list of leaf ids. A leaf is the smallest thing
that can be released or withheld: every measurement type, and thirteen
structured sections — identity, insurer, the glucose panel, labs, the drug
list, the administration ledger, adherence, the GLP-1 block, allergies,
illness episodes, family history, mood, cycle. Membership is inclusion,
absence is exclusion, and there is no defaults constant anywhere to drift.

Three locks keep a metric added later off a report chosen earlier. A stored
selection is a list of what was chosen, so a leaf that did not exist then is
not in it. The catalogue is keyed over the measurement enum, so adding a
member without deciding its group fails typecheck in the same commit. And the
aggregator's filter inverts: a type the catalogue does not know is excluded and
annotated, where it used to be passed through.

The aggregator's third parameter is now required and brand-typed, which turned
the three surfaces that had no scope at all into compile errors. Each one had
to name a source, and each now replays the owner's saved selection — the same
object reviewed in Settings. An account that never saved one gets nothing
there rather than a guess.

Identity and insurance become selectable, and a share link refuses the
insurance leaf outright. The share view never decrypted the number; that is
structural now instead of incidental. The KVNR is not even read unless the
leaf was chosen.

Two surfaces gain a record they always implied. A share link serves its frozen
selection as a FHIR bundle and as the PDF, behind the same unlock cookie the
document route uses, with its own rate bucket, its own audit row and the same
blunt 404 for every miss. That is what the removed FHIR toggle promised, in
the form a practice actually uses.

The AI summary leaves the report. Its text came from the cached briefing with
no relation to the selection, so its scope could not be proven, and prose whose
scope cannot be proven has no place on a document whose whole point is a proven
scope.

The PDF table stops being a nine-type whitelist. It prints every selected leaf
that has data, sub-headed by group, in the same order the panel shows — so
selecting resting heart rate no longer means seeing it in the bundle and not in
the PDF. The clinician view is grouped the same way and reads real labels
instead of "Phq9 score".

Migration 0273 adds the saved-selection column, drops the orphaned prefs column
and the two retired share-link scope columns, and revokes every live record
share link minted before this model. Their frozen scope was "everything except
mood and cycle", which is a scope nobody chose; narrowing it would still be a
scope nobody chose. Documents-only shares are untouched. The sharing list shows
each closed link in a pick-again state with its label, window and expiry kept.

The retired allowFhirApi and resourceTypes stay on the create and list
responses as the constant false and empty list. The request refuses them. They
come off the response once the native client confirms it does not decode them.

Six files are split at seams this change already touched: the aggregator into
its gate, its dense-bucket query, its series, its glucose panel, its medication
ledger and its clinical records; the export route's three emitters into their
own module; the clinician view into its sections, its document list and its
downloads.
This commit is contained in:
Marc-André Bombeck committed 2026-07-26 00:45:08 +02:00
1 parent f90219784b
commit 5e490f31ec
46 files changed
+3734 -3083

No files matched your search

+18 -8
View File
@@ -8,18 +8,28 @@
* widen/update path. `expiresAt` is REQUIRED and capped at
* `SHARE_LINK_MAX_DAYS` so no link ever lives forever.
*
* The `resourceTypes` / `allowFhirApi` keys are gone. A share link
* serves a rendered page and the documents frozen onto it; it has never served
* FHIR, and accepting a scope for a face that does not exist only made the
* promise look kept. An unknown key is rejected by `.strict()`, so a caller
* still sending them gets a 422 that names them rather than a silent no-op.
* The `resourceTypes` / `allowFhirApi` request keys are gone. They configured
* a scoped FHIR face for a share link that was never built, and accepting a
* scope for a face that does not exist only made the promise look kept. An
* unknown key is rejected by `.strict()`, so a caller still sending them gets
* a 422 that names them rather than a silent no-op. The link's record IS
* reachable in machine form now — as a download at `/c/{token}/fhir`, behind
* the same unlock the page uses, serving exactly the frozen selection.
*
* Strict: `.strict()` rejects unknown keys; there is intentionally no `userId`
* field (the owner is always narrowed from `requireAuth()`).
*/
import { z } from "zod/v4";
import { exportSectionsSchema } from "@/lib/validations/health-record-export";
import { reportSelectionSchema } from "@/lib/report-selection/selection";
/**
* The one leaf a share link may never carry. The share view has never
* decrypted the insurance number, so refusing it here makes that structural
* instead of incidental: the create route 422s naming the leaf, and no path
* exists by which a link could later be widened to include it.
*/
export const SHARE_LINK_FORBIDDEN_LEAVES = ["INSURANCE"] as const;
/** Maximum lifetime of a share link, in days. No never-expiring share. */
export const SHARE_LINK_MAX_DAYS = 90;
@@ -48,7 +58,7 @@ export const createShareLinkSchema = z
label: z.string().trim().min(1).max(120),
rangeStart: z.iso.datetime({ offset: true }),
rangeEnd: z.iso.datetime({ offset: true }).nullable().optional(),
sections: exportSectionsSchema.optional(),
selection: reportSelectionSchema.optional(),
documentIds: z
.array(z.string().trim().min(1).max(64))
.max(SHARE_LINK_MAX_DOCUMENTS)
@@ -58,7 +68,7 @@ export const createShareLinkSchema = z
* report scope and mints a link that serves ONLY the attached documents —
* never a health metric. "Share this document" means the document, not the
* whole record. A documents-only share MUST carry at least one
* `documentId` (enforced below). Any `sections` sent alongside are ignored
* `documentId` (enforced below). Any `selection` sent alongside is ignored
* server-side so a document link can never widen into a record.
*/
documentOnly: z.boolean().optional(),
-228
View File
@@ -1,228 +0,0 @@
/**
* v1.4.25 W6c — per-user Doctor-Report section toggles.
*
* Persisted as a Json blob on `User.doctorReportPrefsJson`. Null = the
* documented defaults (every section ON except mood). The dialog reads
* the row, lets the user flip checkboxes, and writes the chosen shape
* back. The PDF generator + the report aggregator both consult the
* shape: aggregator drops mood data entirely when `mood = false` so the
* data never leaves the DB row (privacy-by-default), and the generator
* skips each section whose flag is false at render time.
*
* The shape is intentionally additive — every new data type added to the
* report grows the schema with a new optional flag and a new entry in
* `DEFAULT_DOCTOR_REPORT_PREFS`. Forward-compat: an unknown / drifted
* shape falls back to defaults rather than throwing.
*/
import { z } from "zod/v4";
/**
* Section toggle schema. Every key is optional so a partial update from
* the dialog (e.g., "the user only flipped mood") doesn't have to
* re-state every other flag. The route layer fills missing keys from the
* defaults before persisting so the column shape stays stable.
*/
export const doctorReportPrefsSchema = z
.object({
bp: z.boolean(),
weight: z.boolean(),
pulse: z.boolean(),
bmi: z.boolean(),
mood: z.boolean(),
medicationList: z.boolean(),
compliance: z.boolean(),
sleep: z.boolean(),
glucose: z.boolean(),
cycle: z.boolean(),
labs: z.boolean(),
allergies: z.boolean(),
familyHistory: z.boolean(),
oxygenSaturation: z.boolean(),
bodyFat: z.boolean(),
bodyComposition: z.boolean(),
restingHeartRate: z.boolean(),
hrv: z.boolean(),
vo2max: z.boolean(),
steps: z.boolean(),
distance: z.boolean(),
mentalHealthScreeners: z.boolean(),
})
.partial();
export type DoctorReportPrefsInput = z.infer<typeof doctorReportPrefsSchema>;
/**
* Fully-resolved section toggles. Every key required so the consumers
* (PDF renderer + aggregator) don't have to thread an "is this key
* present?" check through their render paths.
*/
export interface DoctorReportPrefs {
bp: boolean;
weight: boolean;
pulse: boolean;
bmi: boolean;
mood: boolean;
/**
* The active-medication list (names, doses, schedules) and the
* per-dose administration ledger. Previously exported unconditionally while
* the only medication control folded into {@link DoctorReportPrefs.compliance}.
*/
medicationList: boolean;
compliance: boolean;
sleep: boolean;
glucose: boolean;
cycle: boolean;
labs: boolean;
allergies: boolean;
familyHistory: boolean;
/**
* The measurement groups the export panel has always rendered a
* control for but nothing gated. Each one now drives
* `MEASUREMENT_TYPE_SECTION` in the aggregator, so it reaches PDF, FHIR and
* the package alike.
*/
oxygenSaturation: boolean;
bodyFat: boolean;
bodyComposition: boolean;
restingHeartRate: boolean;
hrv: boolean;
vo2max: boolean;
steps: boolean;
distance: boolean;
/**
* PHQ-9 / GAD-7 / WHO-5 / SCI screening totals. Depression,
* anxiety, wellbeing and insomnia instruments: opt-in per artefact like
* mood, never carried by an absent key.
*/
mentalHealthScreeners: boolean;
}
/**
* Defaults applied when the user has never opened the dialog. Every
* section is ON by default EXCEPT mood, which is opt-in per the maintainer's
* privacy directive (2026-05-14): mental-health data should never appear
* in a clinical PDF the user didn't explicitly check.
*/
export const DEFAULT_DOCTOR_REPORT_PREFS: DoctorReportPrefs = {
bp: true,
weight: true,
pulse: true,
bmi: true,
mood: false, // privacy default per the maintainer
// The medication list has always ridden along; the flag exists so the panel's
// single "medications" control can actually withhold it, not to change what a
// caller that omits the key receives.
medicationList: true,
compliance: true,
sleep: true,
// Glucose the user recorded to share with a clinician — ON by default,
// like BP / weight / labs. The per-report toggle lets a diabetic user
// withhold glucose from a SPECIFIC shared report without disabling the
// glucose module app-wide (default-on preserves the pre-toggle behaviour,
// where glucose always rendered).
glucose: true,
// Cycle data is opt-in: a user sharing a BP report with a cardiologist
// should not auto-leak reproductive data. Same privacy stance as mood.
cycle: false,
// Lab results the user recorded for exactly this purpose — sharing
// bloodwork with a clinician. ON by default, like BP / weight.
labs: true,
// Structured allergy / intolerance records — the section every clinical
// intake asks for first. Reference data recorded to share, ON by default
// like labs.
allergies: true,
// Structured family history — same stance as allergies.
familyHistory: true,
// The measurement groups that gained a real gate here. They default ON
// because that is what an omitted key has always produced; the point of the
// flags is that a caller who switches one OFF is now obeyed. The web panel
// sends every one of them explicitly.
oxygenSaturation: true,
bodyFat: true,
bodyComposition: true,
restingHeartRate: true,
hrv: true,
vo2max: true,
steps: true,
distance: true,
// Mental-health screening totals are opt-in per artefact, same stance as
// mood: PHQ-9 and GAD-7 are depression and anxiety instruments and must not
// leave the instance because a caller omitted a key. The `mentalHealth`
// module gate still applies on top — it just no longer stands alone, having
// been default-ON since v1.29.1.
mentalHealthScreeners: false,
};
/**
* The "no section" shape — every toggle OFF. A share link that carries ONLY
* documents (the "share this document, not the whole record" flow) persists
* this so the clinician view resolves to an empty report scope and NO health
* data is ever aggregated for it. Distinct from the null / `{}` case, which
* resolves to {@link DEFAULT_DOCTOR_REPORT_PREFS} (a full record share).
*/
export const EMPTY_DOCTOR_REPORT_PREFS: DoctorReportPrefs = {
bp: false,
weight: false,
pulse: false,
bmi: false,
mood: false,
medicationList: false,
compliance: false,
sleep: false,
glucose: false,
cycle: false,
labs: false,
allergies: false,
familyHistory: false,
oxygenSaturation: false,
bodyFat: false,
bodyComposition: false,
restingHeartRate: false,
hrv: false,
vo2max: false,
steps: false,
distance: false,
mentalHealthScreeners: false,
};
/**
* Whether any report section is enabled. A resolved prefs object with every
* flag OFF means "no health report" — the load-bearing signal a documents-only
* share reads to serve zero metrics. The clinician-view data loader gates the
* whole doctor-report aggregation on this: false ⇒ never touch the DB for
* health data.
*/
export function hasAnyReportSection(prefs: DoctorReportPrefs): boolean {
return Object.values(prefs).some(Boolean);
}
/**
* Parse a row's `doctorReportPrefsJson` Json blob into a typed
* `DoctorReportPrefs`, falling back to the documented defaults when the
* row is null OR the persisted shape has drifted (a forward-compat field
* rename, an admin-side hand-edit, etc.). Missing keys are filled from
* the defaults so callers always get a fully-resolved object.
*/
export function parseDoctorReportPrefs(raw: unknown): DoctorReportPrefs {
if (raw == null) return { ...DEFAULT_DOCTOR_REPORT_PREFS };
const parsed = doctorReportPrefsSchema.safeParse(raw);
if (!parsed.success) return { ...DEFAULT_DOCTOR_REPORT_PREFS };
return {
...DEFAULT_DOCTOR_REPORT_PREFS,
...parsed.data,
};
}
/**
* Resolve a partial input (typically from a PUT body) into the full
* canonical shape, layering the supplied keys over the current
* persisted row (or defaults when null). Keeps the route layer free of
* merge plumbing.
*/
export function resolveDoctorReportPrefs(
current: unknown,
incoming: DoctorReportPrefsInput,
): DoctorReportPrefs {
const base = parseDoctorReportPrefs(current);
return { ...base, ...incoming };
}
+20 -204
View File
@@ -1,155 +1,28 @@
/**
* v1.7.0 — health-record / doctor-handover export selection.
* The health-record / doctor-handover export selection.
*
* Single strict Zod schema driving `POST /api/export/health-record`. The
* flagship export route fails loudly on bad input (unlike the legacy
* doctor-report route which tolerates drift) — `.strict()` rejects unknown
* keys, and there is intentionally NO `userId` field (the user is always
* narrowed from `requireAuth()`, never accepted from the body).
* One strict Zod schema driving `POST /api/export/health-record`. `.strict()`
* rejects unknown keys, and there is intentionally NO `userId` field — the
* user is always narrowed from `requireAuth()`, never accepted from the body.
*
* The grouped `sections` shape is additive over the flat
* `DoctorReportPrefs` used by the aggregator + PDF renderer. The
* `toDoctorReportPrefs()` helper folds the grouped toggles down to the
* flat shape the aggregator consumes, so PDF and FHIR describe identical
* numbers (the source-of-truth property the two PDF endpoints share).
* `selection` is REQUIRED and is the leaf inclusion list. The grouped
* `sections` shape it replaces resolved an absent key to "included", so a
* caller who sent nothing received roughly fifty metrics plus the medication
* list, labs, allergies and family history — a scope nobody chose. Sending
* `sections` now 422s with the key named rather than being folded into a
* default, because silently accepting the old shape would mean silently
* choosing a scope the caller did not express.
*
* The AI summary is gone with it. Its text was pulled from the cached
* briefing with no relation to the selection at all, so its scope could not be
* proven — and prose whose scope cannot be proven cannot ride a document whose
* whole point is a proven scope.
*/
import { z } from "zod/v4";
import { locales } from "@/lib/i18n/config";
import {
DEFAULT_DOCTOR_REPORT_PREFS,
parseDoctorReportPrefs,
type DoctorReportPrefs,
} from "@/lib/validations/doctor-report-prefs";
import { reportSelectionSchema } from "@/lib/report-selection/selection";
/** Grouped vital toggles. */
const vitalsGroupSchema = z
.object({
weight: z.boolean(),
bp: z.boolean(),
pulse: z.boolean(),
oxygenSaturation: z.boolean(),
bodyFat: z.boolean(),
bodyComposition: z.boolean(),
})
.partial();
const cardioFitnessGroupSchema = z
.object({
restingHeartRate: z.boolean(),
hrv: z.boolean(),
vo2max: z.boolean(),
})
.partial();
const activityGroupSchema = z
.object({
steps: z.boolean(),
distance: z.boolean(),
sleep: z.boolean(),
})
.partial();
/**
* `list` gates the medication list plus the per-dose administration
* ledger; `compliance` gates the adherence figures and the GLP-1 therapy block.
* The retired `glp1` / `sideEffects` / `activity.energy` keys were accepted and
* discarded: no surface ever rendered them and no code read them. An unknown
* key inside a group is stripped, so a caller still sending one is unaffected.
*/
const medicationsGroupSchema = z
.object({
list: z.boolean(),
compliance: z.boolean(),
})
.partial();
/**
* Grouped section toggles. Every group + key is optional so a partial
* payload (the user flipped one checkbox) doesn't have to re-state the
* whole tree. Missing keys resolve to the documented defaults.
*/
export const exportSectionsSchema = z
.object({
vitals: vitalsGroupSchema,
cardioFitness: cardioFitnessGroupSchema,
activity: activityGroupSchema,
glucose: z.boolean(),
medications: medicationsGroupSchema,
mood: z.boolean(),
bmi: z.boolean(),
// Cycle / reproductive health — opt-in (privacy default OFF, like mood).
cycle: z.boolean(),
// Structured lab results — ON by default (recorded to share with a
// clinician, same stance as BP / weight).
labs: z.boolean(),
// Structured allergy / intolerance records — ON by default (the
// section every clinical intake asks for first; same stance as labs).
allergies: z.boolean(),
// Structured family history — ON by default, same stance as allergies.
familyHistory: z.boolean(),
// PHQ-9 / GAD-7 / WHO-5 / SCI screening totals. OFF unless the
// caller sets it explicitly (`=== true`), like mood and cycle.
mentalHealthScreeners: z.boolean(),
})
.partial();
export type ExportSections = z.infer<typeof exportSectionsSchema>;
/**
* The top-level keys that exist ONLY in the grouped {@link exportSectionsSchema}
* (never in the flat `doctorReportPrefsSchema`). Their presence is the reliable
* signal that a persisted `sectionsJson` blob is the grouped shape rather than
* the flat one — the flat shape carries `bp` / `weight` / `pulse` at the top
* level, the grouped shape nests them under `vitals`.
*
* `glucose` is deliberately NOT a discriminator: it is a top-level boolean in
* BOTH shapes (the flat `DoctorReportPrefs` gained its own `glucose` section
* toggle), so its presence no longer distinguishes grouped from flat. A real
* grouped export always carries one of the nested groups below, so detection
* stays reliable without it — and a bare `{ glucose: false }` blob correctly
* resolves through the flat parser.
*/
const GROUPED_SECTION_KEYS = [
"vitals",
"cardioFitness",
"activity",
"medications",
] as const;
/**
* v1.28.17 — resolve a STORED `sectionsJson` blob (from a clinician share link
* or any consumer that persists the export selection) to the flat
* {@link DoctorReportPrefs} the aggregator + PDF renderer consume.
*
* The share-link create schema accepts the GROUPED {@link exportSectionsSchema}
* and persists it raw, but the report aggregator speaks the FLAT shape. Reading
* a grouped blob through the flat parser silently DROPS every grouped toggle
* (`vitals.bp`, `activity.sleep`, `medications.compliance`) and falls back to
* defaults-ON — so a section the owner switched OFF would still be served. This
* resolver closes that gap: a grouped blob is folded through
* {@link toDoctorReportPrefs}; a flat / empty / `{}` / null blob keeps the exact
* legacy semantics via {@link parseDoctorReportPrefs}. Detection is by the
* grouped-only keys, so it can never misread a flat blob as grouped (or vice
* versa), and it needs no data migration — existing rows resolve correctly.
*/
export function resolveStoredReportSections(raw: unknown): DoctorReportPrefs {
if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
const obj = raw as Record<string, unknown>;
const looksGrouped = GROUPED_SECTION_KEYS.some((k) => k in obj);
if (looksGrouped) {
const parsed = exportSectionsSchema.safeParse(obj);
// A well-formed grouped blob folds down; a drifted one falls through to
// the flat parser, which itself defaults on any shape it cannot read.
if (parsed.success) return toDoctorReportPrefs(parsed.data);
}
}
return parseDoctorReportPrefs(raw);
}
/**
* Flagship export selection. `.strict()` so unknown keys (including any
* attempt to smuggle a `userId`) 422 via `returnAllZodIssues`.
*/
export const exportSelectionSchema = z
.object({
format: z.enum(["pdf", "fhir", "package"]),
@@ -161,11 +34,11 @@ export const exportSelectionSchema = z
})
.strict()
.optional(),
sections: exportSectionsSchema.optional(),
/** The leaf inclusion list. Required: a scope has to be stated. */
selection: reportSelectionSchema,
locale: z.enum(locales).optional(),
practiceName: z.string().max(120).optional(),
includeCharts: z.boolean().optional(),
includeAiSummary: z.boolean().optional(),
// FHIR only: additionally emit the German BfArM ATC URI alongside the WHO
// entry on each medication concept (WHO stays first, byte-identical). When
// omitted, the route derives it from a German-region locale.
@@ -174,60 +47,3 @@ export const exportSelectionSchema = z
.strict();
export type ExportSelection = z.infer<typeof exportSelectionSchema>;
/**
* Fold the grouped selection down to the flat `DoctorReportPrefs` the
* aggregator + PDF renderer consume. A group toggle that is `true` (or
* absent, falling back to the section default) flips the matching flat
* flag. Mood, cycle and the mental-health screeners stay privacy-default-OFF:
* they only flip on when the caller set them explicitly.
*
* The fold used to read twelve of the twenty keys the schema
* accepts and drop the rest on the floor, so a caller that switched off SpO₂,
* body fat, body composition, resting heart rate, HRV, VO₂max, steps or
* distance was silently overruled and the export panel rendered eight controls
* that changed nothing. Every accepted key now resolves to a flat flag, and
* `doctor-report-control-gating-guard.test.ts` fails the build if a control is
* ever added back without one.
*/
export function toDoctorReportPrefs(
sections: ExportSections | undefined,
): DoctorReportPrefs {
const s = sections ?? {};
const v = s.vitals ?? {};
const c = s.cardioFitness ?? {};
const a = s.activity ?? {};
const m = s.medications ?? {};
const fallback = DEFAULT_DOCTOR_REPORT_PREFS;
return {
weight: v.weight ?? fallback.weight,
bp: v.bp ?? fallback.bp,
pulse: v.pulse ?? fallback.pulse,
bmi: s.bmi ?? fallback.bmi,
// Mood is opt-in: only true when explicitly requested.
mood: s.mood === true,
medicationList: m.list ?? fallback.medicationList,
// A caller that sends only `medications.list = false` means "no medication
// data" — the single panel control has always driven both keys together, so
// the list value keeps standing in for a missing compliance value.
compliance: m.compliance ?? m.list ?? fallback.compliance,
sleep: a.sleep ?? fallback.sleep,
glucose: s.glucose ?? fallback.glucose,
// Cycle is opt-in: only true when explicitly requested (privacy).
cycle: s.cycle === true,
labs: s.labs ?? fallback.labs,
allergies: s.allergies ?? fallback.allergies,
familyHistory: s.familyHistory ?? fallback.familyHistory,
oxygenSaturation: v.oxygenSaturation ?? fallback.oxygenSaturation,
bodyFat: v.bodyFat ?? fallback.bodyFat,
bodyComposition: v.bodyComposition ?? fallback.bodyComposition,
restingHeartRate: c.restingHeartRate ?? fallback.restingHeartRate,
hrv: c.hrv ?? fallback.hrv,
vo2max: c.vo2max ?? fallback.vo2max,
steps: a.steps ?? fallback.steps,
distance: a.distance ?? fallback.distance,
// Screening totals are opt-in: only true when explicitly requested.
mentalHealthScreeners: s.mentalHealthScreeners === true,
};
}