test(export): prove the scope holds at the artefact, not just at the switch

Five layers, because the defect had five places to hide.

The catalogue guard checks what the compiler cannot state: every leaf resolves
a label a human can read, every group resolves one, the fenced tier stays last,
and the shipped template intersects the fence at nothing.

The selection guard pins the three minting functions against each other. A
stored blob this build cannot read resolves to the empty selection, never to a
default set — that is what makes the revoked legacy links revocable rather than
silently re-scoped. A request naming an id the server does not know is refused
by name rather than dropped, because dropping it would narrow a scope the
caller did express.

The egress guard freezes the set of aggregator callers with the source of each
one's selection written down. The required brand-typed parameter already stops
a new path compiling without an answer; this stops one being added without a
human writing the answer down, which is the moment a reviewer asks the
question.

The behavioural sweep aggregates every leaf in and out against a fixture that
carries a row for each, and asserts the payload differs. It is parametrised
over the catalogue, so a leaf added later is covered the day it is added. Its
positive control asserts the all-on payload is genuinely populated first, so a
"no difference" result means the gate is inert and not that the account is
empty. Beside it: an unmapped measurement type is excluded rather than passed
through, no table behind an unchosen leaf is queried at all, and an empty
selection produces an empty record.

The artefact layer runs the real route and reads what comes out — the FHIR
bundle, the PDF text and the zip's contents — with a positive control beside
every exclusion.

Mutation-checked: making the gate admit everything reddens the sweep for every
leaf; passing an unmapped type through reddens the fail-closed case; dropping
the mood query's condition reddens the zero-read case; returning the BMI
unconditionally reddens the sweep naming BODY_MASS_INDEX; adding a fenced leaf
to the template reddens the purity guard; removing the panel's seeding block
reddens the first-run and repeat-run cases; dropping the insurance refusal
reddens the share-link case; adding a caller outside the frozen list reddens
the egress guard naming the file.

The panel suite grew past the practice name it was written for and is renamed
for what it now covers: the three states, the fenced tier having no group
control, and the scope line naming its sensitive inclusions.

Integration coverage moves to the leaf model, including the case this release
exists for: an account with data in every domain and a caller that named
nothing gets an empty record.

The OpenAPI contract catches up with the routes — the required selection, the
refused keys, the share summary's new fields, the moved `Patient/$everything`,
the Coverage search and the five typed reads.
This commit is contained in:
Marc-André Bombeck committed 2026-07-26 00:45:08 +02:00
1 parent 582db8a538
commit f42934487d
70 files changed
+5646 -2459

No files matched your search

@@ -11,7 +11,8 @@ import { renderToStaticMarkup } from "react-dom/server";
import { ClinicianView } from "../clinician-view";
import { getServerTranslator } from "@/lib/i18n/server-translator";
import { DEFAULT_DOCTOR_REPORT_PREFS } from "@/lib/validations/doctor-report-prefs";
import { selectionFromLeaves } from "@/lib/report-selection/selection";
import { ALL_LEAF_IDS } from "@/lib/report-selection/catalogue";
import type { DoctorReportData } from "@/lib/doctor-report-data";
import { computeGlucoseClinicalMetrics } from "@/lib/analytics/glucose-metrics";
@@ -76,7 +77,7 @@ function render(
label="Cardiology clinic"
expiresAt="2026-03-01T00:00:00.000Z"
report={report}
sections={{ ...DEFAULT_DOCTOR_REPORT_PREFS }}
selection={selectionFromLeaves(ALL_LEAF_IDS)}
{...extra}
/>,
);
@@ -100,10 +101,12 @@ describe("<ClinicianView>", () => {
it("renders clinical vitals from the scoped report", () => {
const html = render(makeReport());
expect(html).toContain("Vital signs");
// The measurement-type enum renders as its localised label, not the raw
// enum string.
expect(html).toContain("Body weight");
// The measurement rows are grouped the way the selection panel groups
// them, so the page reads in the same order as the PDF.
expect(html).toContain("Body measurements");
// The measurement-type enum renders as the SAME localised label the rest
// of the app uses, not the raw enum string and not a second vocabulary.
expect(html).toContain(">Weight<");
expect(html).not.toContain("WEIGHT");
});
@@ -75,6 +75,7 @@ function buildUser(disableCoach: boolean): AuthUser {
insurerIkNumber: null,
insuranceNumber: null,
lastReportPracticeName: null,
reportSelection: null,
cycleTrackingEnabled: false,
modules: {},
};
@@ -1,97 +0,0 @@
/**
* Settings → Gesundheitsakte: the practice name is remembered between reports.
*
* `User.lastReportPracticeName` is persisted by the export route after a
* successful generation and rides the `/api/auth/me` payload. This suite pins
* the read half: the panel opens pre-filled with the last-used name instead of
* asking for the clinic name again on every report.
*
* SSR-only, per the project convention for this surface (node environment,
* no `@testing-library/react`). The seed runs during render — a `useState`
* initializer would read `undefined` while `useAuth` is still resolving and
* stick at empty — so the static markup already carries the seeded value.
*
* Mutation check: revert the seeding block in the panel and the first case
* goes red.
*/
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import type { AuthUser } from "@/hooks/use-auth";
const authSpy = vi.fn<() => { user: AuthUser | null }>();
vi.mock("@/hooks/use-auth", async () => {
const actual =
await vi.importActual<typeof import("@/hooks/use-auth")>(
"@/hooks/use-auth",
);
return { ...actual, useAuth: () => authSpy() };
});
vi.mock("@tanstack/react-query", () => ({
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
}));
import { I18nProvider } from "@/lib/i18n/context";
import { HealthRecordExportPanel } from "../health-record-export-panel";
function buildUser(lastReportPracticeName: string | null): AuthUser {
return {
id: "user-1",
username: "user",
email: null,
role: "USER",
heightCm: null,
dateOfBirth: null,
gender: null,
timezone: "Europe/Berlin",
onboardingCompletedAt: null,
onboardingTourCompleted: true,
onboardingTourProgress: null,
avatarUrl: null,
glucoseUnit: null,
unitPreference: "metric",
timeFormat: "AUTO",
dateFormat: "AUTO",
disableCoach: false,
fullName: null,
insurerName: null,
insurerIkNumber: null,
insuranceNumber: null,
lastReportPracticeName,
cycleTrackingEnabled: false,
modules: {},
} as AuthUser;
}
function renderPanel(user: AuthUser | null): string {
authSpy.mockReturnValue({ user });
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<HealthRecordExportPanel />
</I18nProvider>,
);
}
function practiceInputValue(html: string): string | null {
const input = html.match(/<input[^>]*id="hr-practice"[^>]*>/)?.[0];
if (!input) return null;
return input.match(/value="([^"]*)"/)?.[1] ?? "";
}
describe("<HealthRecordExportPanel> — remembered practice name", () => {
it("pre-fills the input with the last-used practice name", () => {
const html = renderPanel(buildUser("Sample Practice"));
expect(practiceInputValue(html)).toBe("Sample Practice");
});
it("leaves the input empty when no name was ever remembered", () => {
const html = renderPanel(buildUser(null));
expect(practiceInputValue(html)).toBe("");
});
it("leaves the input empty while the auth payload is still resolving", () => {
const html = renderPanel(null);
expect(practiceInputValue(html)).toBe("");
});
});
@@ -108,6 +108,7 @@ function buildUser(
insurerIkNumber: null,
insuranceNumber: null,
lastReportPracticeName: null,
reportSelection: null,
cycleTrackingEnabled: false,
modules,
moduleAvailability: {},
@@ -0,0 +1,234 @@
/**
* Settings → Gesundheitsakte: what the export panel opens with.
*
* Two things are seeded from `/api/auth/me` during render — the practice name
* and the saved selection. The seed runs during render because a `useState`
* initialiser would read `undefined` while `useAuth` is still resolving and
* stick, and it is gated on the user id so a late re-resolve never clobbers
* edits in flight.
*
* The three panel states are the load-bearing part. First run must open the
* picker EXPANDED with the named template applied and the fenced tier visibly
* empty, so the user presses Generate having seen twelve named groups; a
* repeat run must open collapsed carrying the owner's own last scope. A
* template silently applied behind a collapsed disclosure would be opt-out
* wearing a hat.
*
* SSR-only, per the project convention for this surface.
*
* Mutation checks:
* - remove the seeding block → "pre-fills the input" and "restores the saved
* selection" go red.
* - start `pickerOpen` at `false` → "opens expanded on the first run" goes
* red.
* - add a fenced leaf to `STANDARD_TEMPLATE_LEAVES` → "checks no fenced leaf
* on the first run" goes red.
*/
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import type { AuthUser } from "@/hooks/use-auth";
const authSpy = vi.fn<() => { user: AuthUser | null }>();
vi.mock("@/hooks/use-auth", async () => {
const actual =
await vi.importActual<typeof import("@/hooks/use-auth")>(
"@/hooks/use-auth",
);
return { ...actual, useAuth: () => authSpy() };
});
vi.mock("@tanstack/react-query", () => ({
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
}));
import { I18nProvider } from "@/lib/i18n/context";
import { HealthRecordExportPanel } from "../report-selection/selection-panel";
function buildUser(lastReportPracticeName: string | null): AuthUser {
return {
id: "user-1",
username: "user",
email: null,
role: "USER",
heightCm: null,
dateOfBirth: null,
gender: null,
timezone: "Europe/Berlin",
onboardingCompletedAt: null,
onboardingTourCompleted: true,
onboardingTourProgress: null,
avatarUrl: null,
glucoseUnit: null,
unitPreference: "metric",
timeFormat: "AUTO",
dateFormat: "AUTO",
disableCoach: false,
fullName: null,
insurerName: null,
insurerIkNumber: null,
insuranceNumber: null,
lastReportPracticeName,
reportSelection: null,
cycleTrackingEnabled: false,
modules: {},
} as AuthUser;
}
function withSavedSelection(user: AuthUser, leaves: string[]): AuthUser {
return {
...user,
reportSelection: {
v: 2,
leaves,
format: "fhir",
rangeDays: 180,
includeCharts: false,
},
} as AuthUser;
}
/**
* Whether a leaf row renders as checked. Only the fenced tier and an expanded
* group render leaf rows at all — a collapsed group shows its count chip
* instead, which is the point of the two-interaction repeat path.
*/
function leafChecked(html: string, leaf: string): boolean {
const row = html.match(
new RegExp(`data-testid="report-leaf-${leaf}"[\\s\\S]*?</label>`),
)?.[0];
if (!row) return false;
return /data-state="checked"/.test(row);
}
/** The "n/total" chip a collapsed group row carries. */
function groupChip(html: string, group: string): string | null {
const row = html.match(
new RegExp(`data-testid="report-group-row-${group}"[\\s\\S]*?</div>`),
)?.[0];
return row?.match(/data-slot="tag-chip"[^>]*>([^<]*)</)?.[1] ?? null;
}
function renderPanel(user: AuthUser | null): string {
authSpy.mockReturnValue({ user });
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<HealthRecordExportPanel />
</I18nProvider>,
);
}
function practiceInputValue(html: string): string | null {
const input = html.match(/<input[^>]*id="hr-practice"[^>]*>/)?.[0];
if (!input) return null;
return input.match(/value="([^"]*)"/)?.[1] ?? "";
}
describe("<HealthRecordExportPanel> — remembered practice name", () => {
it("pre-fills the input with the last-used practice name", () => {
const html = renderPanel(buildUser("Sample Practice"));
expect(practiceInputValue(html)).toBe("Sample Practice");
});
it("leaves the input empty when no name was ever remembered", () => {
const html = renderPanel(buildUser(null));
expect(practiceInputValue(html)).toBe("");
});
it("leaves the input empty while the auth payload is still resolving", () => {
const html = renderPanel(null);
expect(practiceInputValue(html)).toBe("");
});
});
describe("<HealthRecordExportPanel> — the first run", () => {
it("opens the picker expanded and names the template it applied", () => {
const html = renderPanel(buildUser(null));
expect(html).toContain('data-testid="health-record-included-data-panel"');
expect(html).toContain('data-testid="report-scope-picker"');
expect(html).toContain("Standard doctor&#x27;s report");
});
it("counts the template's leaves per group, and no others", () => {
const html = renderPanel(buildUser(null));
// Identity: both leaves. Vitals: the three classic ones out of seven.
// Body: weight and BMI out of twelve. Nothing at all from the groups the
// template leaves alone.
expect(groupChip(html, "identity")).toBe("2/2");
expect(groupChip(html, "vitals")).toBe("3/7");
expect(groupChip(html, "body")).toBe("2/12");
expect(groupChip(html, "labs")).toBe("1/1");
expect(groupChip(html, "medications")).toBe("2/4");
expect(groupChip(html, "history")).toBe("2/2");
expect(groupChip(html, "cardio")).toBe("0/14");
expect(groupChip(html, "activity")).toBe("0/8");
expect(groupChip(html, "sleepRecovery")).toBe("0/16");
expect(groupChip(html, "mobility")).toBe("0/11");
expect(groupChip(html, "environment")).toBe("0/4");
});
it("leaves every fenced leaf unchecked and renders the tier", () => {
const html = renderPanel(buildUser(null));
expect(html).toContain('data-testid="report-sensitive-tier"');
for (const leaf of [
"MOOD",
"CYCLE",
"FAMILY_HISTORY",
"PHQ9_SCORE",
"GAD7_SCORE",
"WHO5_SCORE",
"SCI_SCORE",
]) {
expect(leafChecked(html, leaf), leaf).toBe(false);
}
});
it("gives the fenced tier no group checkbox", () => {
const html = renderPanel(buildUser(null));
expect(html).toContain('data-testid="report-group-check-vitals"');
expect(html).not.toContain('data-testid="report-group-check-sensitive"');
});
it("states the scope in one line", () => {
const html = renderPanel(buildUser(null));
expect(html).toContain('data-testid="report-scope-summary"');
expect(html).toContain("14 entries from 7 areas");
});
});
describe("<HealthRecordExportPanel> — a repeat run", () => {
it("restores the saved selection and collapses the picker", () => {
const html = renderPanel(
withSavedSelection(buildUser("Sample Practice"), [
"RESTING_HEART_RATE",
"MOOD",
]),
);
expect(html).not.toContain(
'data-testid="health-record-included-data-panel"',
);
// The scope line still says what will be in the document, and it names the
// fenced inclusion rather than folding it into the count.
expect(html).toContain("2 entries from 2 areas");
expect(html).toContain("incl. Mood");
});
it("restores the saved format and range", () => {
const html = renderPanel(withSavedSelection(buildUser(null), ["WEIGHT"]));
// FHIR was saved, so the practice-name line (PDF only) is not rendered.
expect(practiceInputValue(html)).toBeNull();
expect(html).toContain('<option value="180" selected=""');
});
it("falls back to the template when the saved blob cannot be read", () => {
const user = {
...buildUser(null),
reportSelection: { bp: true, weight: true },
} as AuthUser;
const html = renderPanel(user);
// A shape the server cannot read is not consent to anything, so the panel
// shows the named template rather than a partial scope.
expect(html).toContain("Standard doctor&#x27;s report");
expect(groupChip(html, "body")).toBe("2/12");
});
});
@@ -13,6 +13,7 @@
* TanStack hooks are mocked; the QR (`qrcode`) only ever renders in an effect
* after a create, so it never runs under `renderToStaticMarkup`.
*/
import type { ReportLeafId } from "@/lib/report-selection/catalogue";
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
@@ -110,6 +111,7 @@ describe("buildShareLinkCreatePayload — scope contract", () => {
label: " Blood panel 2026 ",
rangeDays: 30,
expiryDays: 30,
leaves: ["WEIGHT", "LAB_RESULTS"] as ReportLeafId[],
};
it("document-only: empty report scope and the launched doc always rides along", () => {
@@ -123,7 +125,9 @@ describe("buildShareLinkCreatePayload — scope contract", () => {
// so a share link can no longer advertise a face that was never served.
expect(payload).not.toHaveProperty("resourceTypes");
expect(payload).not.toHaveProperty("allowFhirApi");
// No report sections are ever sent for a document link.
// No report scope is ever sent for a document link, whatever the picker
// above happened to be showing.
expect(payload).not.toHaveProperty("selection");
expect(payload).not.toHaveProperty("sections");
// The launched document is always in the created link (pre-attach fix).
expect(payload.documentIds).toEqual(["doc-1"]);
@@ -137,6 +141,11 @@ describe("buildShareLinkCreatePayload — scope contract", () => {
documentOnly: false,
});
expect(payload.rangeEnd).toBeNull();
// A record share carries the leaves the owner chose, and nothing else.
expect(payload.selection).toEqual({
v: 2,
leaves: ["WEIGHT", "LAB_RESULTS"],
});
expect(payload).not.toHaveProperty("resourceTypes");
expect(payload).not.toHaveProperty("allowFhirApi");
expect(payload).not.toHaveProperty("documentIds");
@@ -53,6 +53,7 @@ function buildUser(timeFormat: TimeFormatPreference): AuthUser {
insurerIkNumber: null,
insuranceNumber: null,
lastReportPracticeName: null,
reportSelection: null,
cycleTrackingEnabled: false,
modules: {},
};
@@ -56,6 +56,7 @@ function buildUser(unitPreference: "metric" | "imperial"): AuthUser {
insurerIkNumber: null,
insuranceNumber: null,
lastReportPracticeName: null,
reportSelection: null,
cycleTrackingEnabled: false,
modules: {},
};
@@ -51,8 +51,14 @@ import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { cn } from "@/lib/utils";
import type { ReportLeafId } from "@/lib/report-selection/catalogue";
import { parseSavedProfile } from "@/lib/report-selection/saved-profile";
import { STANDARD_TEMPLATE_LEAVES } from "@/lib/report-selection/template";
import {
parseSavedProfile,
SAVED_PROFILE_FALLBACK,
} from "@/lib/report-selection/saved-profile";
import {
STANDARD_TEMPLATE_LABEL_KEY,
STANDARD_TEMPLATE_LEAVES,
} from "@/lib/report-selection/template";
import { orderLeaves } from "@/lib/report-selection/selection";
import { ReportScopePicker } from "./report-scope-picker";
@@ -68,13 +74,17 @@ export function HealthRecordExportPanel() {
const { user } = useAuth();
const queryClient = useQueryClient();
const [format, setFormat] = useState<ExportFormat>("pdf");
const [days, setDays] = useState<number>(90);
const [format, setFormat] = useState<ExportFormat>(
SAVED_PROFILE_FALLBACK.format,
);
const [days, setDays] = useState<number>(SAVED_PROFILE_FALLBACK.rangeDays);
const [customRange, setCustomRange] = useState(false);
const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");
const [practiceName, setPracticeName] = useState("");
const [includeCharts, setIncludeCharts] = useState(true);
const [includeCharts, setIncludeCharts] = useState(
SAVED_PROFILE_FALLBACK.includeCharts,
);
const [selected, setSelected] = useState<ReadonlySet<ReportLeafId>>(
() => new Set(STANDARD_TEMPLATE_LEAVES),
);
@@ -328,7 +338,7 @@ export function HealthRecordExportPanel() {
data-testid="report-template-note"
>
{t("reportSelection.templateApplied", {
template: t("reportSelection.templateStandard"),
template: t(STANDARD_TEMPLATE_LABEL_KEY),
})}
</p>
) : null}