mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 23:33:29 +00:00
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:
1 parent
582db8a538
commit
f42934487d
70 files changed
+5646
-2459
No files matched your search
@@ -1,11 +1,16 @@
|
||||
/**
|
||||
* v1.7.0 — POST /api/export/health-record unit coverage.
|
||||
* POST /api/export/health-record unit coverage.
|
||||
*
|
||||
* Mock-based (no testcontainers): pins the route contract — strict Zod
|
||||
* rejection paths (422 via returnAllZodIssues), rate-limit (429), the
|
||||
* three format outputs (PDF magic bytes, application/fhir+json valid
|
||||
* Bundle, application/zip), and that the user is narrowed from the
|
||||
* session (never the body).
|
||||
* rejection paths (422 via returnAllZodIssues), rate-limit (429), the three
|
||||
* format outputs (PDF magic bytes, application/fhir+json valid Bundle,
|
||||
* application/zip), and that the user is narrowed from the session, never the
|
||||
* body.
|
||||
*
|
||||
* The second half is the artefact-level proof that the selection means the
|
||||
* same thing in every format: each case runs the real route end to end and
|
||||
* reads what comes out, with a positive control beside each exclusion so
|
||||
* nothing can pass on an empty fixture.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
@@ -24,6 +29,23 @@ vi.mock("@/lib/db", () => ({
|
||||
familyHistoryEntry: { findMany: vi.fn() },
|
||||
user: { findUnique: vi.fn(), update: vi.fn() },
|
||||
},
|
||||
toJson: (value: unknown) => value,
|
||||
}));
|
||||
// The cycle summary has its own aggregation behind it; this suite is about the
|
||||
// route, so it is stubbed to a fixed shape. Whether it is CALLED at all is the
|
||||
// property that matters here, and the aggregator sweep asserts that directly.
|
||||
vi.mock("@/lib/cycle/export-data", () => ({
|
||||
buildCycleExportSummary: vi.fn(async () => ({
|
||||
lastPeriodStart: "2026-02-01",
|
||||
recentCycles: [
|
||||
{ startDate: "2026-02-01", lengthDays: 28, periodLengthDays: 5 },
|
||||
],
|
||||
observedCycleCount: 1,
|
||||
averageCycleLengthDays: 28,
|
||||
cycleLengthVariabilityDays: null,
|
||||
averagePeriodLengthDays: 5,
|
||||
currentPhase: "FOLLICULAR",
|
||||
})),
|
||||
}));
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn() }));
|
||||
@@ -57,6 +79,7 @@ vi.mock("@/lib/modules/gate", async (importOriginal) => {
|
||||
});
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { ALL_LEAF_IDS } from "@/lib/report-selection/catalogue";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import {
|
||||
@@ -69,6 +92,16 @@ const SESSION_OK = {
|
||||
user: { id: "user-1", email: "test@example.com", role: "USER" },
|
||||
} as const;
|
||||
|
||||
/** A selection body carrying exactly these leaves. */
|
||||
function sel(...leaves: string[]) {
|
||||
return { v: 2, leaves };
|
||||
}
|
||||
|
||||
/** Everything the catalogue knows — the positive-control scope. */
|
||||
function allLeaves() {
|
||||
return { v: 2, leaves: [...ALL_LEAF_IDS] };
|
||||
}
|
||||
|
||||
function mkReq(
|
||||
body: unknown,
|
||||
headers: Record<string, string> = {},
|
||||
@@ -129,19 +162,21 @@ beforeEach(() => {
|
||||
describe("POST /api/export/health-record — validation", () => {
|
||||
it("rejects an unknown format with 422", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "xml" }));
|
||||
const res = await POST(mkReq({ format: "xml", selection: sel() }));
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
|
||||
it("rejects a missing format with 422", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({}));
|
||||
const res = await POST(mkReq({ selection: sel() }));
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
|
||||
it("rejects a userId smuggled into the body with 422", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "pdf", userId: "user-2" }));
|
||||
const res = await POST(
|
||||
mkReq({ format: "pdf", selection: sel(), userId: "user-2" }),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
|
||||
@@ -155,7 +190,7 @@ describe("POST /api/export/health-record — validation", () => {
|
||||
}),
|
||||
} as never);
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "fhir" }));
|
||||
const res = await POST(mkReq({ format: "fhir", selection: sel() }));
|
||||
expect(res.status).toBe(403);
|
||||
expect(requireModuleEnabled).toHaveBeenCalledWith("user-1", "doctorReport");
|
||||
});
|
||||
@@ -167,7 +202,7 @@ describe("POST /api/export/health-record — validation", () => {
|
||||
resetAt: Date.now() + 3_600_000,
|
||||
} as never);
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "fhir" }));
|
||||
const res = await POST(mkReq({ format: "fhir", selection: sel() }));
|
||||
expect(res.status).toBe(429);
|
||||
});
|
||||
});
|
||||
@@ -175,7 +210,7 @@ describe("POST /api/export/health-record — validation", () => {
|
||||
describe("POST /api/export/health-record — outputs", () => {
|
||||
it("format=fhir returns a valid FHIR document Bundle", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "fhir" }));
|
||||
const res = await POST(mkReq({ format: "fhir", selection: allLeaves() }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toContain("application/fhir+json");
|
||||
const bundle = await res.json();
|
||||
@@ -186,7 +221,7 @@ describe("POST /api/export/health-record — outputs", () => {
|
||||
|
||||
it("format=pdf returns a PDF with the %PDF- magic bytes", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "pdf" }));
|
||||
const res = await POST(mkReq({ format: "pdf", selection: allLeaves() }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toBe("application/pdf");
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
@@ -195,7 +230,9 @@ describe("POST /api/export/health-record — outputs", () => {
|
||||
|
||||
it("format=package returns a zip", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "package" }));
|
||||
const res = await POST(
|
||||
mkReq({ format: "package", selection: allLeaves() }),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toBe("application/zip");
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
@@ -206,7 +243,12 @@ describe("POST /api/export/health-record — outputs", () => {
|
||||
it("renders the PDF in the explicit selection locale", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(
|
||||
mkReq({ format: "pdf", locale: "de", practiceName: "Sample Practice" }),
|
||||
mkReq({
|
||||
format: "pdf",
|
||||
locale: "de",
|
||||
selection: allLeaves(),
|
||||
practiceName: "Sample Practice",
|
||||
}),
|
||||
);
|
||||
const text = await pdfText(res);
|
||||
// German cover label.
|
||||
@@ -217,7 +259,11 @@ describe("POST /api/export/health-record — outputs", () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(
|
||||
mkReq(
|
||||
{ format: "pdf", practiceName: "Sample Practice" },
|
||||
{
|
||||
format: "pdf",
|
||||
selection: allLeaves(),
|
||||
practiceName: "Sample Practice",
|
||||
},
|
||||
{
|
||||
// Browser default English, but the in-app cookie says German — the
|
||||
// cookie must win over Accept-Language.
|
||||
@@ -235,7 +281,11 @@ describe("POST /api/export/health-record — outputs", () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(
|
||||
mkReq(
|
||||
{ format: "pdf", practiceName: "Sample Practice" },
|
||||
{
|
||||
format: "pdf",
|
||||
selection: allLeaves(),
|
||||
practiceName: "Sample Practice",
|
||||
},
|
||||
{ "accept-language": "en-US,en;q=0.9" },
|
||||
),
|
||||
);
|
||||
@@ -245,10 +295,12 @@ describe("POST /api/export/health-record — outputs", () => {
|
||||
|
||||
it("scopes the aggregator measurement read to the session user", async () => {
|
||||
const { POST } = await import("../route");
|
||||
await POST(mkReq({ format: "fhir", userId: "user-2" } as never));
|
||||
await POST(
|
||||
mkReq({ format: "fhir", selection: sel(), userId: "user-2" } as never),
|
||||
);
|
||||
// userId smuggle is rejected above; here we confirm the read uses the
|
||||
// session user, not anything from the body, for a clean payload.
|
||||
await POST(mkReq({ format: "fhir" }));
|
||||
await POST(mkReq({ format: "fhir", selection: allLeaves() }));
|
||||
expect(prisma.measurement.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({ userId: "user-1", deletedAt: null }),
|
||||
@@ -335,11 +387,12 @@ describe("POST /api/export/health-record — the selection reaches every format"
|
||||
}
|
||||
|
||||
/** Resource types present in the bundle a given selection produces. */
|
||||
async function bundleResourceTypes(
|
||||
sections: Record<string, unknown>,
|
||||
): Promise<string[]> {
|
||||
async function bundleResourceTypes(selection: {
|
||||
v: number;
|
||||
leaves: string[];
|
||||
}): Promise<string[]> {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "fhir", sections }));
|
||||
const res = await POST(mkReq({ format: "fhir", selection }));
|
||||
expect(res.status).toBe(200);
|
||||
const bundle = (await res.json()) as {
|
||||
entry: { resource: { resourceType: string; code?: unknown } }[];
|
||||
@@ -348,11 +401,12 @@ describe("POST /api/export/health-record — the selection reaches every format"
|
||||
}
|
||||
|
||||
/** The LOINC/HealthKit codes of every Observation a selection produces. */
|
||||
async function observationCodes(
|
||||
sections: Record<string, unknown>,
|
||||
): Promise<string[]> {
|
||||
async function observationCodes(selection: {
|
||||
v: number;
|
||||
leaves: string[];
|
||||
}): Promise<string[]> {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "fhir", sections }));
|
||||
const res = await POST(mkReq({ format: "fhir", selection }));
|
||||
expect(res.status).toBe(200);
|
||||
const bundle = (await res.json()) as {
|
||||
entry: {
|
||||
@@ -382,36 +436,35 @@ describe("POST /api/export/health-record — the selection reaches every format"
|
||||
measurement("WALKING_RUNNING_DISTANCE", 6200),
|
||||
] as never);
|
||||
|
||||
// Positive control: with every switch on, all eight are emitted. Without
|
||||
// this the exclusion assertion below could pass on an empty bundle.
|
||||
const on = await observationCodes({
|
||||
vitals: { oxygenSaturation: true, bodyFat: true, bodyComposition: true },
|
||||
cardioFitness: { restingHeartRate: true, hrv: true, vo2max: true },
|
||||
activity: { steps: true, distance: true },
|
||||
});
|
||||
// Positive control: with all eight leaves chosen, all eight are emitted.
|
||||
// Without this the exclusion assertion below could pass on an empty bundle.
|
||||
const on = await observationCodes(
|
||||
sel(
|
||||
"BODY_FAT",
|
||||
"OXYGEN_SATURATION",
|
||||
"BONE_MASS",
|
||||
"RESTING_HEART_RATE",
|
||||
"HEART_RATE_VARIABILITY",
|
||||
"VO2_MAX",
|
||||
"ACTIVITY_STEPS",
|
||||
"WALKING_RUNNING_DISTANCE",
|
||||
),
|
||||
);
|
||||
expect(on.length).toBeGreaterThanOrEqual(8);
|
||||
|
||||
const off = await observationCodes({
|
||||
vitals: {
|
||||
oxygenSaturation: false,
|
||||
bodyFat: false,
|
||||
bodyComposition: false,
|
||||
},
|
||||
cardioFitness: { restingHeartRate: false, hrv: false, vo2max: false },
|
||||
activity: { steps: false, distance: false },
|
||||
});
|
||||
// A selection naming something else entirely carries none of them —
|
||||
// absence of a leaf is exclusion, not a default.
|
||||
const off = await observationCodes(sel("PULSE"));
|
||||
expect(off).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps the deselected measurement rows out of the query in the first place", async () => {
|
||||
await bundleResourceTypes({
|
||||
vitals: { bodyFat: false },
|
||||
cardioFitness: { vo2max: false },
|
||||
});
|
||||
await bundleResourceTypes(sel("PULSE"));
|
||||
const lastCall = vi.mocked(prisma.measurement.findMany).mock.calls.at(-1)!;
|
||||
const where = lastCall[0]!.where as { type?: { notIn?: string[] } };
|
||||
expect(where.type?.notIn).toContain("BODY_FAT");
|
||||
expect(where.type?.notIn).toContain("VO2_MAX");
|
||||
expect(where.type?.notIn).not.toContain("PULSE");
|
||||
});
|
||||
|
||||
it("omits the deselected vitals from the PDF table", async () => {
|
||||
@@ -426,22 +479,22 @@ describe("POST /api/export/health-record — the selection reaches every format"
|
||||
mkReq({
|
||||
format: "pdf",
|
||||
locale: "en",
|
||||
sections: { vitals: { bodyFat: true, oxygenSaturation: true } },
|
||||
selection: sel("BODY_FAT", "OXYGEN_SATURATION"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(withBoth).toContain("Body fat");
|
||||
expect(withBoth).toContain("Body Fat");
|
||||
|
||||
const without = await pdfText(
|
||||
await POST(
|
||||
mkReq({
|
||||
format: "pdf",
|
||||
locale: "en",
|
||||
sections: { vitals: { bodyFat: false, oxygenSaturation: false } },
|
||||
selection: sel("PULSE"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(without).not.toContain("Body fat");
|
||||
expect(without).not.toContain("Body Fat");
|
||||
});
|
||||
|
||||
it("holds the mental-health screening totals back unless they are asked for by name", async () => {
|
||||
@@ -450,12 +503,13 @@ describe("POST /api/export/health-record — the selection reaches every format"
|
||||
measurement("GAD7_SCORE", 8),
|
||||
] as never);
|
||||
|
||||
// The module is on (the default since v1.29.1) and the caller sends no
|
||||
// screening key: the totals must stay in the database.
|
||||
expect(await observationCodes({ labs: true })).toEqual([]);
|
||||
// And an omitted `sections` object entirely — the MCP / share-link case.
|
||||
// The module is on (the default since v1.29.1) and the caller names other
|
||||
// leaves: the totals must stay in the database.
|
||||
expect(await observationCodes(sel("LAB_RESULTS"))).toEqual([]);
|
||||
// And an empty selection — the "I said nothing" case, which used to mean
|
||||
// "give me everything".
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "fhir" }));
|
||||
const res = await POST(mkReq({ format: "fhir", selection: sel() }));
|
||||
const bundle = (await res.json()) as {
|
||||
entry: { resource: { resourceType: string } }[];
|
||||
};
|
||||
@@ -463,8 +517,8 @@ describe("POST /api/export/health-record — the selection reaches every format"
|
||||
bundle.entry.filter((e) => e.resource.resourceType === "Observation"),
|
||||
).toEqual([]);
|
||||
|
||||
// Asked for explicitly, they are emitted — the data is withheld, not lost.
|
||||
const asked = await observationCodes({ mentalHealthScreeners: true });
|
||||
// Asked for by name, they are emitted — the data is withheld, not lost.
|
||||
const asked = await observationCodes(sel("PHQ9_SCORE", "GAD7_SCORE"));
|
||||
expect(asked).toContain("44261-6");
|
||||
expect(asked).toContain("70274-6");
|
||||
});
|
||||
@@ -474,11 +528,11 @@ describe("POST /api/export/health-record — the selection reaches every format"
|
||||
medicationRow(),
|
||||
] as never);
|
||||
|
||||
expect(await bundleResourceTypes(sel("MEDICATION_LIST"))).toContain(
|
||||
"MedicationStatement",
|
||||
);
|
||||
expect(
|
||||
await bundleResourceTypes({ medications: { list: true } }),
|
||||
).toContain("MedicationStatement");
|
||||
expect(
|
||||
await bundleResourceTypes({ medications: { list: false } }),
|
||||
await bundleResourceTypes(sel("MEDICATION_COMPLIANCE")),
|
||||
).not.toContain("MedicationStatement");
|
||||
});
|
||||
|
||||
@@ -490,23 +544,17 @@ describe("POST /api/export/health-record — the selection reaches every format"
|
||||
familyHistoryRow(),
|
||||
] as never);
|
||||
|
||||
const on = await bundleResourceTypes({
|
||||
allergies: true,
|
||||
familyHistory: true,
|
||||
});
|
||||
const on = await bundleResourceTypes(sel("ALLERGIES", "FAMILY_HISTORY"));
|
||||
expect(on).toContain("AllergyIntolerance");
|
||||
expect(on).toContain("FamilyMemberHistory");
|
||||
|
||||
const off = await bundleResourceTypes({
|
||||
allergies: false,
|
||||
familyHistory: false,
|
||||
});
|
||||
const off = await bundleResourceTypes(sel("PULSE"));
|
||||
expect(off).not.toContain("AllergyIntolerance");
|
||||
expect(off).not.toContain("FamilyMemberHistory");
|
||||
});
|
||||
|
||||
it("never reads the deselected records from the database", async () => {
|
||||
await bundleResourceTypes({ allergies: false, familyHistory: false });
|
||||
await bundleResourceTypes(sel("PULSE"));
|
||||
expect(prisma.allergy.findMany).not.toHaveBeenCalled();
|
||||
expect(prisma.familyHistoryEntry.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -521,10 +569,7 @@ describe("POST /api/export/health-record — the selection reaches every format"
|
||||
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(
|
||||
mkReq({
|
||||
format: "package",
|
||||
sections: { allergies: false, familyHistory: false },
|
||||
}),
|
||||
mkReq({ format: "package", selection: sel("PULSE") }),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const files = unzipSync(new Uint8Array(await res.arrayBuffer()));
|
||||
@@ -539,53 +584,111 @@ describe("POST /api/export/health-record — the selection reaches every format"
|
||||
});
|
||||
|
||||
/**
|
||||
* The practice name is a remembered preference (`User.lastReportPracticeName`),
|
||||
* so a monthly report does not ask for the clinic name again every time. The
|
||||
* write happens only once the artefact exists — a generation that throws must
|
||||
* not overwrite the remembered value with a half-typed one.
|
||||
* What the route remembers: the practice name and the scope the owner chose,
|
||||
* so the panel opens carrying both next time and the surfaces that cannot ask
|
||||
* a human have a real act to replay.
|
||||
*
|
||||
* Mutation check: drop the `rememberPracticeName` call in the route and the
|
||||
* first two cases go red; move it above the generation and the
|
||||
* failed-generation case goes red.
|
||||
* The write happens only once the artefact exists — a generation that throws
|
||||
* must not overwrite the remembered values with a half-typed name or a scope
|
||||
* that produced nothing.
|
||||
*
|
||||
* Mutation checks: drop the `rememberChoices` call and the first cases go red;
|
||||
* move it above the generation and the failed-generation case goes red; drop
|
||||
* `reportSelectionJson` from the update and "remembers the chosen scope" goes
|
||||
* red.
|
||||
*/
|
||||
describe("POST /api/export/health-record — remembered practice name", () => {
|
||||
describe("POST /api/export/health-record — what the route remembers", () => {
|
||||
it("persists the sanitised practice name after a PDF export", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(
|
||||
mkReq({ format: "pdf", practiceName: " Sample Practice " }),
|
||||
mkReq({
|
||||
format: "pdf",
|
||||
selection: sel("WEIGHT"),
|
||||
practiceName: " Sample Practice ",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.user.update).toHaveBeenCalledWith({
|
||||
where: { id: "user-1" },
|
||||
data: { lastReportPracticeName: "Sample Practice" },
|
||||
data: expect.objectContaining({
|
||||
lastReportPracticeName: "Sample Practice",
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("remembers the chosen scope, in catalogue order", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(
|
||||
mkReq({
|
||||
format: "fhir",
|
||||
selection: sel("LAB_RESULTS", "WEIGHT"),
|
||||
range: { days: 180 },
|
||||
includeCharts: false,
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.user.update).toHaveBeenCalledWith({
|
||||
where: { id: "user-1" },
|
||||
data: expect.objectContaining({
|
||||
reportSelectionJson: {
|
||||
v: 2,
|
||||
leaves: ["WEIGHT", "LAB_RESULTS"],
|
||||
format: "fhir",
|
||||
rangeDays: 180,
|
||||
includeCharts: false,
|
||||
},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses a leaf id this build does not know, and remembers nothing", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(
|
||||
mkReq({ format: "pdf", selection: sel("SOMETHING_NEW") }),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
const body = (await res.json()) as { error: string };
|
||||
expect(body.error).toContain("SOMETHING_NEW");
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("persists the practice name after a FHIR export", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(
|
||||
mkReq({ format: "fhir", practiceName: "Sample Practice" }),
|
||||
mkReq({
|
||||
format: "fhir",
|
||||
selection: sel("WEIGHT"),
|
||||
practiceName: "Sample Practice",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.user.update).toHaveBeenCalledWith({
|
||||
where: { id: "user-1" },
|
||||
data: { lastReportPracticeName: "Sample Practice" },
|
||||
data: expect.objectContaining({
|
||||
lastReportPracticeName: "Sample Practice",
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("persists null when the user cleared the practice name", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "pdf" }));
|
||||
const res = await POST(mkReq({ format: "pdf", selection: sel("WEIGHT") }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.user.update).toHaveBeenCalledWith({
|
||||
where: { id: "user-1" },
|
||||
data: { lastReportPracticeName: null },
|
||||
data: expect.objectContaining({ lastReportPracticeName: null }),
|
||||
});
|
||||
});
|
||||
|
||||
it("writes nothing when the selection is rejected", async () => {
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(mkReq({ format: "xml", practiceName: "Sample" }));
|
||||
const res = await POST(
|
||||
mkReq({
|
||||
format: "xml",
|
||||
selection: sel("WEIGHT"),
|
||||
practiceName: "Sample",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -596,7 +699,11 @@ describe("POST /api/export/health-record — remembered practice name", () => {
|
||||
);
|
||||
const { POST } = await import("../route");
|
||||
const res = await POST(
|
||||
mkReq({ format: "pdf", practiceName: "Sample Practice" }),
|
||||
mkReq({
|
||||
format: "pdf",
|
||||
selection: sel("WEIGHT"),
|
||||
practiceName: "Sample Practice",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(500);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
@@ -604,7 +711,13 @@ describe("POST /api/export/health-record — remembered practice name", () => {
|
||||
|
||||
it("narrows the update to the session user, never the body", async () => {
|
||||
const { POST } = await import("../route");
|
||||
await POST(mkReq({ format: "fhir", practiceName: "Sample Practice" }));
|
||||
await POST(
|
||||
mkReq({
|
||||
format: "fhir",
|
||||
selection: sel("WEIGHT"),
|
||||
practiceName: "Sample Practice",
|
||||
}),
|
||||
);
|
||||
expect(prisma.user.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { id: "user-1" } }),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* GET /api/fhir/Coverage/{id} — FHIR R4 `read` of one Coverage from the
|
||||
* caller's own record.
|
||||
*
|
||||
* The id space is the export's own (`coverage-1`), stable for a given record and
|
||||
* reporting window. A `read` is a filter over the same emitter the search
|
||||
* route pages, so a resource can never differ between the two faces; an id the
|
||||
* caller's record does not hold is a `not-found` OperationOutcome.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { requireModuleEnabled } from "@/lib/modules/gate";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { coverageResource } from "@/lib/fhir/resources";
|
||||
import {
|
||||
FHIR_READ_SCOPE,
|
||||
loadFhirContext,
|
||||
operationOutcome,
|
||||
readResponse,
|
||||
} from "@/lib/fhir/rest";
|
||||
|
||||
export const GET = apiHandler(
|
||||
async (_request: NextRequest, ctx: { params: Promise<{ id: string }> }) => {
|
||||
const { user } = await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.coverage.read" } });
|
||||
|
||||
// REFUSE, NOT OMIT. The FHIR face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record`, right down to the decrypted insurance number
|
||||
// on the Patient resource, so it gates on the same `doctorReport` module.
|
||||
// There is no partial answer that is still a truthful FHIR Bundle, and no
|
||||
// background client depends on this draining to stay consistent. The 403
|
||||
// `module.disabled` envelope (rather than an OperationOutcome) keeps the
|
||||
// errorCode clients already branch on for a disabled module.
|
||||
const gate = await requireModuleEnabled(user.id, "doctorReport");
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return operationOutcome(429, "throttled", "Rate limit exceeded");
|
||||
}
|
||||
const { id } = await ctx.params;
|
||||
const context = await loadFhirContext(user.id);
|
||||
annotate({ meta: { resourceId: id } });
|
||||
return readResponse([coverageResource(context.data, context.identity)].filter(
|
||||
(resource) => resource !== null,
|
||||
), id);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* GET /api/fhir/Coverage — FHIR R4 `searchset` of the caller's own insurance Coverage.
|
||||
*
|
||||
* Present only when an insurer is known — R4 requires a payor, and a record
|
||||
* that carries only a member id has none, so the search is empty rather than
|
||||
* carrying a Coverage that names nobody.
|
||||
*
|
||||
* Read-only. `userId` is narrowed from `requireAuth`; the shared emitters in
|
||||
* `@/lib/fhir/resources` are the single source of the coding, so this face and
|
||||
* the document export can never describe the same record differently. Offset
|
||||
* paging via `_count` (clamped ≤200) / `_offset`.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { requireModuleEnabled } from "@/lib/modules/gate";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { coverageResource } from "@/lib/fhir/resources";
|
||||
import {
|
||||
FHIR_READ_SCOPE,
|
||||
loadFhirContext,
|
||||
operationOutcome,
|
||||
parsePaging,
|
||||
searchsetResponse,
|
||||
} from "@/lib/fhir/rest";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.coverage.search" } });
|
||||
|
||||
// REFUSE, NOT OMIT. The FHIR face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record`, right down to the decrypted insurance number
|
||||
// on the Patient resource, so it gates on the same `doctorReport` module.
|
||||
// There is no partial answer that is still a truthful FHIR Bundle, and no
|
||||
// background client depends on this draining to stay consistent. The 403
|
||||
// `module.disabled` envelope (rather than an OperationOutcome) keeps the
|
||||
// errorCode clients already branch on for a disabled module.
|
||||
const gate = await requireModuleEnabled(user.id, "doctorReport");
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return operationOutcome(429, "throttled", "Rate limit exceeded");
|
||||
}
|
||||
const { count, offset } = parsePaging(request.nextUrl.searchParams);
|
||||
const context = await loadFhirContext(user.id);
|
||||
|
||||
const all = [coverageResource(context.data, context.identity)].filter(
|
||||
(resource) => resource !== null,
|
||||
);
|
||||
const page = all.slice(offset, offset + count);
|
||||
annotate({ meta: { total: all.length, count, offset } });
|
||||
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* GET /api/fhir/MedicationAdministration/{id} — FHIR R4 `read` of one MedicationAdministration from the
|
||||
* caller's own record.
|
||||
*
|
||||
* The id space is the export's own (`medadmin-7`), stable for a given record and
|
||||
* reporting window. A `read` is a filter over the same emitter the search
|
||||
* route pages, so a resource can never differ between the two faces; an id the
|
||||
* caller's record does not hold is a `not-found` OperationOutcome.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { requireModuleEnabled } from "@/lib/modules/gate";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { medicationAdministrationsFromReportData } from "@/lib/fhir/resources";
|
||||
import {
|
||||
FHIR_READ_SCOPE,
|
||||
loadFhirContext,
|
||||
operationOutcome,
|
||||
readResponse,
|
||||
} from "@/lib/fhir/rest";
|
||||
|
||||
export const GET = apiHandler(
|
||||
async (_request: NextRequest, ctx: { params: Promise<{ id: string }> }) => {
|
||||
const { user } = await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.medicationadministration.read" } });
|
||||
|
||||
// REFUSE, NOT OMIT. The FHIR face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record`, right down to the decrypted insurance number
|
||||
// on the Patient resource, so it gates on the same `doctorReport` module.
|
||||
// There is no partial answer that is still a truthful FHIR Bundle, and no
|
||||
// background client depends on this draining to stay consistent. The 403
|
||||
// `module.disabled` envelope (rather than an OperationOutcome) keeps the
|
||||
// errorCode clients already branch on for a disabled module.
|
||||
const gate = await requireModuleEnabled(user.id, "doctorReport");
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return operationOutcome(429, "throttled", "Rate limit exceeded");
|
||||
}
|
||||
const { id } = await ctx.params;
|
||||
const context = await loadFhirContext(user.id);
|
||||
annotate({ meta: { resourceId: id } });
|
||||
return readResponse(
|
||||
medicationAdministrationsFromReportData(context.data, {
|
||||
germanAtc: context.germanAtc,
|
||||
}),
|
||||
id,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1,10 +1,12 @@
|
||||
/**
|
||||
* GET /api/fhir/MedicationAdministration — FHIR R4 `searchset` of the caller's
|
||||
* own acted intakes (`completed` taken / `not-done` skip), with the same
|
||||
* ATC/RxNorm + dose/route/site coding the document export carries.
|
||||
* GET /api/fhir/MedicationAdministration — FHIR R4 `searchset` of the caller's own acted
|
||||
* intakes (`completed` taken / `not-done` skip), with the same ATC/RxNorm +
|
||||
* dose/route/site coding the document export carries.
|
||||
*
|
||||
* Read-only. `userId` narrowed from `requireAuth`; shared emitter is the
|
||||
* single source of the coding. Offset paging via `_count` (≤200) / `_offset`.
|
||||
* Read-only. `userId` is narrowed from `requireAuth`; the shared emitters in
|
||||
* `@/lib/fhir/resources` are the single source of the coding, so this face and
|
||||
* the document export can never describe the same record differently. Offset
|
||||
* paging via `_count` (clamped ≤200) / `_offset`.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
@@ -25,18 +27,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.medicationadministration.search" } });
|
||||
|
||||
// v1.30 — the FHIR REST face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record` (the doctor-report builder), right down to
|
||||
// the decrypted insurance number on the Patient resource. That export
|
||||
// gates on the `doctorReport` module; this surface did not, so the module
|
||||
// could be off and `/api/fhir/*` still handed out the full record.
|
||||
//
|
||||
// REFUSE, NOT OMIT — deliberately, and unlike the sync delta feed. This is
|
||||
// a whole-record export, not an incremental feed: there is no partial
|
||||
// answer that is still a truthful FHIR Bundle, and no background client
|
||||
// depends on it draining to stay consistent. Mirroring the sibling export's
|
||||
// 403 `module.disabled` envelope (rather than an OperationOutcome) keeps
|
||||
// the errorCode the clients already branch on for a disabled module.
|
||||
// REFUSE, NOT OMIT. The FHIR face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record`, right down to the decrypted insurance number
|
||||
// on the Patient resource, so it gates on the same `doctorReport` module.
|
||||
// There is no partial answer that is still a truthful FHIR Bundle, and no
|
||||
// background client depends on this draining to stay consistent. The 403
|
||||
// `module.disabled` envelope (rather than an OperationOutcome) keeps the
|
||||
// errorCode clients already branch on for a disabled module.
|
||||
const gate = await requireModuleEnabled(user.id, "doctorReport");
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
@@ -44,11 +41,12 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
if (!rl.allowed) {
|
||||
return operationOutcome(429, "throttled", "Rate limit exceeded");
|
||||
}
|
||||
|
||||
const { count, offset } = parsePaging(request.nextUrl.searchParams);
|
||||
const { data, germanAtc } = await loadFhirContext(user.id);
|
||||
const context = await loadFhirContext(user.id);
|
||||
|
||||
const all = medicationAdministrationsFromReportData(data, { germanAtc });
|
||||
const all = medicationAdministrationsFromReportData(context.data, {
|
||||
germanAtc: context.germanAtc,
|
||||
});
|
||||
const page = all.slice(offset, offset + count);
|
||||
annotate({ meta: { total: all.length, count, offset } });
|
||||
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* GET /api/fhir/MedicationStatement/{id} — FHIR R4 `read` of one MedicationStatement from the
|
||||
* caller's own record.
|
||||
*
|
||||
* The id space is the export's own (`med-2`), stable for a given record and
|
||||
* reporting window. A `read` is a filter over the same emitter the search
|
||||
* route pages, so a resource can never differ between the two faces; an id the
|
||||
* caller's record does not hold is a `not-found` OperationOutcome.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { requireModuleEnabled } from "@/lib/modules/gate";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { medicationStatementsFromReportData } from "@/lib/fhir/resources";
|
||||
import {
|
||||
FHIR_READ_SCOPE,
|
||||
loadFhirContext,
|
||||
operationOutcome,
|
||||
readResponse,
|
||||
} from "@/lib/fhir/rest";
|
||||
|
||||
export const GET = apiHandler(
|
||||
async (_request: NextRequest, ctx: { params: Promise<{ id: string }> }) => {
|
||||
const { user } = await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.medicationstatement.read" } });
|
||||
|
||||
// REFUSE, NOT OMIT. The FHIR face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record`, right down to the decrypted insurance number
|
||||
// on the Patient resource, so it gates on the same `doctorReport` module.
|
||||
// There is no partial answer that is still a truthful FHIR Bundle, and no
|
||||
// background client depends on this draining to stay consistent. The 403
|
||||
// `module.disabled` envelope (rather than an OperationOutcome) keeps the
|
||||
// errorCode clients already branch on for a disabled module.
|
||||
const gate = await requireModuleEnabled(user.id, "doctorReport");
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return operationOutcome(429, "throttled", "Rate limit exceeded");
|
||||
}
|
||||
const { id } = await ctx.params;
|
||||
const context = await loadFhirContext(user.id);
|
||||
annotate({ meta: { resourceId: id } });
|
||||
return readResponse(
|
||||
medicationStatementsFromReportData(context.data, {
|
||||
germanAtc: context.germanAtc,
|
||||
}),
|
||||
id,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -3,9 +3,10 @@
|
||||
* active-medication statements (one per active medication, with additive
|
||||
* ATC/RxNorm codings).
|
||||
*
|
||||
* Read-only. `userId` narrowed from `requireAuth`; shared emitter is the
|
||||
* single source of the drug coding. Offset paging via `_count` (≤200) /
|
||||
* `_offset`.
|
||||
* Read-only. `userId` is narrowed from `requireAuth`; the shared emitters in
|
||||
* `@/lib/fhir/resources` are the single source of the coding, so this face and
|
||||
* the document export can never describe the same record differently. Offset
|
||||
* paging via `_count` (clamped ≤200) / `_offset`.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
@@ -26,18 +27,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.medicationstatement.search" } });
|
||||
|
||||
// v1.30 — the FHIR REST face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record` (the doctor-report builder), right down to
|
||||
// the decrypted insurance number on the Patient resource. That export
|
||||
// gates on the `doctorReport` module; this surface did not, so the module
|
||||
// could be off and `/api/fhir/*` still handed out the full record.
|
||||
//
|
||||
// REFUSE, NOT OMIT — deliberately, and unlike the sync delta feed. This is
|
||||
// a whole-record export, not an incremental feed: there is no partial
|
||||
// answer that is still a truthful FHIR Bundle, and no background client
|
||||
// depends on it draining to stay consistent. Mirroring the sibling export's
|
||||
// 403 `module.disabled` envelope (rather than an OperationOutcome) keeps
|
||||
// the errorCode the clients already branch on for a disabled module.
|
||||
// REFUSE, NOT OMIT. The FHIR face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record`, right down to the decrypted insurance number
|
||||
// on the Patient resource, so it gates on the same `doctorReport` module.
|
||||
// There is no partial answer that is still a truthful FHIR Bundle, and no
|
||||
// background client depends on this draining to stay consistent. The 403
|
||||
// `module.disabled` envelope (rather than an OperationOutcome) keeps the
|
||||
// errorCode clients already branch on for a disabled module.
|
||||
const gate = await requireModuleEnabled(user.id, "doctorReport");
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
@@ -45,11 +41,12 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
if (!rl.allowed) {
|
||||
return operationOutcome(429, "throttled", "Rate limit exceeded");
|
||||
}
|
||||
|
||||
const { count, offset } = parsePaging(request.nextUrl.searchParams);
|
||||
const { data, germanAtc } = await loadFhirContext(user.id);
|
||||
const context = await loadFhirContext(user.id);
|
||||
|
||||
const all = medicationStatementsFromReportData(data, { germanAtc });
|
||||
const all = medicationStatementsFromReportData(context.data, {
|
||||
germanAtc: context.germanAtc,
|
||||
});
|
||||
const page = all.slice(offset, offset + count);
|
||||
annotate({ meta: { total: all.length, count, offset } });
|
||||
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* GET /api/fhir/Observation/{id} — FHIR R4 `read` of one Observation from the
|
||||
* caller's own record.
|
||||
*
|
||||
* The id space is the export's own (`obs-3`), stable for a given record and
|
||||
* reporting window. A `read` is a filter over the same emitter the search
|
||||
* route pages, so a resource can never differ between the two faces; an id the
|
||||
* caller's record does not hold is a `not-found` OperationOutcome.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { requireModuleEnabled } from "@/lib/modules/gate";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { observationsFromReportData } from "@/lib/fhir/resources";
|
||||
import {
|
||||
FHIR_READ_SCOPE,
|
||||
loadFhirContext,
|
||||
operationOutcome,
|
||||
readResponse,
|
||||
} from "@/lib/fhir/rest";
|
||||
|
||||
export const GET = apiHandler(
|
||||
async (_request: NextRequest, ctx: { params: Promise<{ id: string }> }) => {
|
||||
const { user } = await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.observation.read" } });
|
||||
|
||||
// REFUSE, NOT OMIT. The FHIR face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record`, right down to the decrypted insurance number
|
||||
// on the Patient resource, so it gates on the same `doctorReport` module.
|
||||
// There is no partial answer that is still a truthful FHIR Bundle, and no
|
||||
// background client depends on this draining to stay consistent. The 403
|
||||
// `module.disabled` envelope (rather than an OperationOutcome) keeps the
|
||||
// errorCode clients already branch on for a disabled module.
|
||||
const gate = await requireModuleEnabled(user.id, "doctorReport");
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return operationOutcome(429, "throttled", "Rate limit exceeded");
|
||||
}
|
||||
const { id } = await ctx.params;
|
||||
const context = await loadFhirContext(user.id);
|
||||
annotate({ meta: { resourceId: id } });
|
||||
return readResponse(observationsFromReportData(context.data), id);
|
||||
},
|
||||
);
|
||||
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* GET /api/fhir/Observation — FHIR R4 `searchset` of the caller's own
|
||||
* Observations (vitals / activity / lab / survey), one latest reading per
|
||||
* type plus the BP panel, BMI, glucose, adherence, mood and wellness scores.
|
||||
* GET /api/fhir/Observation — FHIR R4 `searchset` of the caller's own Observations
|
||||
* (vitals / activity / lab / survey): one latest reading per type plus the BP
|
||||
* panel, BMI, glucose, adherence, mood and the wellness composites.
|
||||
*
|
||||
* Read-only. `userId` is narrowed from `requireAuth`; the shared emitter is
|
||||
* the single source of the LOINC/UCUM coding. Offset paging via `_count`
|
||||
* (clamped ≤200) / `_offset`.
|
||||
* Read-only. `userId` is narrowed from `requireAuth`; the shared emitters in
|
||||
* `@/lib/fhir/resources` are the single source of the coding, so this face and
|
||||
* the document export can never describe the same record differently. Offset
|
||||
* paging via `_count` (clamped ≤200) / `_offset`.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
@@ -26,18 +27,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.observation.search" } });
|
||||
|
||||
// v1.30 — the FHIR REST face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record` (the doctor-report builder), right down to
|
||||
// the decrypted insurance number on the Patient resource. That export
|
||||
// gates on the `doctorReport` module; this surface did not, so the module
|
||||
// could be off and `/api/fhir/*` still handed out the full record.
|
||||
//
|
||||
// REFUSE, NOT OMIT — deliberately, and unlike the sync delta feed. This is
|
||||
// a whole-record export, not an incremental feed: there is no partial
|
||||
// answer that is still a truthful FHIR Bundle, and no background client
|
||||
// depends on it draining to stay consistent. Mirroring the sibling export's
|
||||
// 403 `module.disabled` envelope (rather than an OperationOutcome) keeps
|
||||
// the errorCode the clients already branch on for a disabled module.
|
||||
// REFUSE, NOT OMIT. The FHIR face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record`, right down to the decrypted insurance number
|
||||
// on the Patient resource, so it gates on the same `doctorReport` module.
|
||||
// There is no partial answer that is still a truthful FHIR Bundle, and no
|
||||
// background client depends on this draining to stay consistent. The 403
|
||||
// `module.disabled` envelope (rather than an OperationOutcome) keeps the
|
||||
// errorCode clients already branch on for a disabled module.
|
||||
const gate = await requireModuleEnabled(user.id, "doctorReport");
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
@@ -45,11 +41,10 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
if (!rl.allowed) {
|
||||
return operationOutcome(429, "throttled", "Rate limit exceeded");
|
||||
}
|
||||
|
||||
const { count, offset } = parsePaging(request.nextUrl.searchParams);
|
||||
const { data, identity, germanAtc } = await loadFhirContext(user.id);
|
||||
const context = await loadFhirContext(user.id);
|
||||
|
||||
const all = observationsFromReportData(data, identity, { germanAtc });
|
||||
const all = observationsFromReportData(context.data);
|
||||
const page = all.slice(offset, offset + count);
|
||||
annotate({ meta: { total: all.length, count, offset } });
|
||||
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
|
||||
|
||||
+32
-24
@@ -1,11 +1,19 @@
|
||||
/**
|
||||
* GET /api/fhir/$everything — FHIR R4 `$everything` operation.
|
||||
* GET /api/fhir/Patient/$everything — FHIR R4 `Patient-everything`.
|
||||
*
|
||||
* Returns every resource in the caller's own record — Patient, Coverage,
|
||||
* Observations, MedicationStatements, MedicationAdministrations — in one
|
||||
* `searchset` Bundle, in the canonical document order. Read-only; `userId`
|
||||
* narrowed from `requireAuth`. Offset paging applies across the flattened
|
||||
* resource list via `_count` (clamped ≤200) / `_offset`.
|
||||
* Returns every resource in the caller's own record in one `searchset` Bundle:
|
||||
* the Composition, the authoring Device, Patient, Coverage, every Observation
|
||||
* (vitals / glucose / labs / adherence / mood / wellness AND the cycle set),
|
||||
* MedicationStatements, MedicationAdministrations, Conditions, Encounters,
|
||||
* AllergyIntolerances, FamilyMemberHistories and the DiagnosticReport.
|
||||
*
|
||||
* The set is the document export's, flattened — same builder, same order, same
|
||||
* `urn:uuid` entry identities, so a reference between two resources still
|
||||
* resolves inside the response and the operation can never quietly carry less
|
||||
* than the document does.
|
||||
*
|
||||
* Read-only; `userId` narrowed from `requireAuth`. Offset paging applies across
|
||||
* the flattened resource list via `_count` (clamped ≤200) / `_offset`.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
@@ -13,20 +21,13 @@ import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { requireModuleEnabled } from "@/lib/modules/gate";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import {
|
||||
coverageResource,
|
||||
medicationAdministrationsFromReportData,
|
||||
medicationStatementsFromReportData,
|
||||
observationsFromReportData,
|
||||
patientResource,
|
||||
} from "@/lib/fhir/resources";
|
||||
import type { FhirResource } from "@/lib/fhir/types";
|
||||
import { buildFhirDocumentBundle } from "@/lib/fhir/build-bundle";
|
||||
import {
|
||||
FHIR_READ_SCOPE,
|
||||
loadFhirContext,
|
||||
operationOutcome,
|
||||
parsePaging,
|
||||
searchsetResponse,
|
||||
searchsetResponseFromEntries,
|
||||
} from "@/lib/fhir/rest";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
@@ -54,16 +55,23 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
}
|
||||
|
||||
const { count, offset } = parsePaging(request.nextUrl.searchParams);
|
||||
const { data, identity, germanAtc } = await loadFhirContext(user.id);
|
||||
|
||||
const all: FhirResource[] = [patientResource(data, identity)];
|
||||
const coverage = coverageResource(data, identity);
|
||||
if (coverage) all.push(coverage);
|
||||
all.push(...observationsFromReportData(data, identity, { germanAtc }));
|
||||
all.push(...medicationStatementsFromReportData(data, { germanAtc }));
|
||||
all.push(...medicationAdministrationsFromReportData(data, { germanAtc }));
|
||||
const { data, identity, germanAtc, records } = await loadFhirContext(user.id);
|
||||
|
||||
const document = buildFhirDocumentBundle(
|
||||
data,
|
||||
identity,
|
||||
undefined,
|
||||
{ germanAtc },
|
||||
records,
|
||||
);
|
||||
const all = document.entry;
|
||||
const page = all.slice(offset, offset + count);
|
||||
annotate({ meta: { total: all.length, count, offset } });
|
||||
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
|
||||
return searchsetResponseFromEntries(
|
||||
request.nextUrl,
|
||||
page,
|
||||
all.length,
|
||||
count,
|
||||
offset,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* GET /api/fhir/Patient/{id} — FHIR R4 `read` of one Patient from the
|
||||
* caller's own record.
|
||||
*
|
||||
* The id space is the export's own (`patient-1`), stable for a given record and
|
||||
* reporting window. A `read` is a filter over the same emitter the search
|
||||
* route pages, so a resource can never differ between the two faces; an id the
|
||||
* caller's record does not hold is a `not-found` OperationOutcome.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { requireModuleEnabled } from "@/lib/modules/gate";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { patientResource } from "@/lib/fhir/resources";
|
||||
import {
|
||||
FHIR_READ_SCOPE,
|
||||
loadFhirContext,
|
||||
operationOutcome,
|
||||
readResponse,
|
||||
} from "@/lib/fhir/rest";
|
||||
|
||||
export const GET = apiHandler(
|
||||
async (_request: NextRequest, ctx: { params: Promise<{ id: string }> }) => {
|
||||
const { user } = await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.patient.read" } });
|
||||
|
||||
// REFUSE, NOT OMIT. The FHIR face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record`, right down to the decrypted insurance number
|
||||
// on the Patient resource, so it gates on the same `doctorReport` module.
|
||||
// There is no partial answer that is still a truthful FHIR Bundle, and no
|
||||
// background client depends on this draining to stay consistent. The 403
|
||||
// `module.disabled` envelope (rather than an OperationOutcome) keeps the
|
||||
// errorCode clients already branch on for a disabled module.
|
||||
const gate = await requireModuleEnabled(user.id, "doctorReport");
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
|
||||
if (!rl.allowed) {
|
||||
return operationOutcome(429, "throttled", "Rate limit exceeded");
|
||||
}
|
||||
const { id } = await ctx.params;
|
||||
const context = await loadFhirContext(user.id);
|
||||
annotate({ meta: { resourceId: id } });
|
||||
return readResponse([patientResource(context.data, context.identity)], id);
|
||||
},
|
||||
);
|
||||
@@ -1,10 +1,14 @@
|
||||
/**
|
||||
* GET /api/fhir/Patient — FHIR R4 `searchset` of the caller's own Patient.
|
||||
* GET /api/fhir/Patient — FHIR R4 `searchset` of the caller's own Patient resource.
|
||||
*
|
||||
* Read-only. A FHIR `Patient` search always yields exactly the authenticated
|
||||
* user's single Patient resource (the `userId` is narrowed from `requireAuth`;
|
||||
* there is no cross-user search). Returned as a one-entry `searchset` Bundle
|
||||
* so a generic FHIR client can page it like any other resource type.
|
||||
* A Patient search always yields exactly the authenticated user's single
|
||||
* Patient (there is no cross-user search); it is returned as a one-entry
|
||||
* Bundle so a generic FHIR client can page it like any other resource type.
|
||||
*
|
||||
* Read-only. `userId` is narrowed from `requireAuth`; the shared emitters in
|
||||
* `@/lib/fhir/resources` are the single source of the coding, so this face and
|
||||
* the document export can never describe the same record differently. Offset
|
||||
* paging via `_count` (clamped ≤200) / `_offset`.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
@@ -25,18 +29,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.patient.search" } });
|
||||
|
||||
// v1.30 — the FHIR REST face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record` (the doctor-report builder), right down to
|
||||
// the decrypted insurance number on the Patient resource. That export
|
||||
// gates on the `doctorReport` module; this surface did not, so the module
|
||||
// could be off and `/api/fhir/*` still handed out the full record.
|
||||
//
|
||||
// REFUSE, NOT OMIT — deliberately, and unlike the sync delta feed. This is
|
||||
// a whole-record export, not an incremental feed: there is no partial
|
||||
// answer that is still a truthful FHIR Bundle, and no background client
|
||||
// depends on it draining to stay consistent. Mirroring the sibling export's
|
||||
// 403 `module.disabled` envelope (rather than an OperationOutcome) keeps
|
||||
// the errorCode the clients already branch on for a disabled module.
|
||||
// REFUSE, NOT OMIT. The FHIR face serves the SAME whole-record aggregate as
|
||||
// `/api/export/health-record`, right down to the decrypted insurance number
|
||||
// on the Patient resource, so it gates on the same `doctorReport` module.
|
||||
// There is no partial answer that is still a truthful FHIR Bundle, and no
|
||||
// background client depends on this draining to stay consistent. The 403
|
||||
// `module.disabled` envelope (rather than an OperationOutcome) keeps the
|
||||
// errorCode clients already branch on for a disabled module.
|
||||
const gate = await requireModuleEnabled(user.id, "doctorReport");
|
||||
if (!gate.enabled) return gate.response;
|
||||
|
||||
@@ -44,11 +43,10 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
if (!rl.allowed) {
|
||||
return operationOutcome(429, "throttled", "Rate limit exceeded");
|
||||
}
|
||||
|
||||
const { count, offset } = parsePaging(request.nextUrl.searchParams);
|
||||
const { data, identity } = await loadFhirContext(user.id);
|
||||
const context = await loadFhirContext(user.id);
|
||||
|
||||
const all = [patientResource(data, identity)];
|
||||
const all = [patientResource(context.data, context.identity)];
|
||||
const page = all.slice(offset, offset + count);
|
||||
annotate({ meta: { total: all.length, count, offset } });
|
||||
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
/**
|
||||
* The CapabilityStatement must describe a face that exists, and
|
||||
* `Patient/$everything` must return the whole record.
|
||||
*
|
||||
* A statement is a promise a generic FHIR client acts on: it will issue a
|
||||
* `read` because the statement said `read` is there. So the advertised set is
|
||||
* checked against the route tree on disk, not against a second list. And the
|
||||
* whole-record operation is checked against the document export it mirrors —
|
||||
* "everything" that quietly omits a resource family is the kind of gap only a
|
||||
* clinician notices, when the family is the one they needed.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { existsSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn() }));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/modules/gate", () => ({
|
||||
requireModuleEnabled: vi.fn(),
|
||||
isModuleEnabled: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/fhir/rest", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/fhir/rest")>();
|
||||
return { ...actual, loadFhirContext: vi.fn() };
|
||||
});
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
import { GET as metadataGet } from "../metadata/route";
|
||||
import { GET as everythingGet } from "../Patient/$everything/route";
|
||||
import { GET as observationRead } from "../Observation/[id]/route";
|
||||
import { GET as patientRead } from "../Patient/[id]/route";
|
||||
import { GET as coverageRead } from "../Coverage/[id]/route";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { loadFhirContext, FHIR_REST_RESOURCE_TYPES } from "@/lib/fhir/rest";
|
||||
import { requireModuleEnabled, isModuleEnabled } from "@/lib/modules/gate";
|
||||
import { buildFhirDocumentBundle } from "@/lib/fhir/build-bundle";
|
||||
import { computeGlucoseClinicalMetrics } from "@/lib/analytics/glucose-metrics";
|
||||
import type { DoctorReportData } from "@/lib/doctor-report-data";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: { id: "user-1", username: "tester", role: "USER" as const },
|
||||
};
|
||||
|
||||
const FIXED_NOW = new Date("2026-05-03T12:00:00.000Z");
|
||||
|
||||
const DATA = {
|
||||
period: {
|
||||
days: 90,
|
||||
since: "2026-02-02T00:00:00.000Z",
|
||||
start: "2026-02-02T00:00:00.000Z",
|
||||
end: "2026-05-03T12:00:00.000Z",
|
||||
},
|
||||
patient: {
|
||||
username: "sample-user",
|
||||
dateOfBirth: "1985-06-15T00:00:00.000Z",
|
||||
gender: "MALE",
|
||||
heightCm: 182,
|
||||
fullName: "Sample Patient",
|
||||
insurerName: "Example Insurer",
|
||||
insurerIkNumber: "101234567",
|
||||
},
|
||||
practiceName: null,
|
||||
measurements: {
|
||||
WEIGHT: [{ value: 79.5, measuredAt: "2026-04-30T08:00:00.000Z" }],
|
||||
},
|
||||
stats: {},
|
||||
glucoseStats: {},
|
||||
glucoseRanges: {},
|
||||
glucoseClinical: computeGlucoseClinicalMetrics([], { now: FIXED_NOW }),
|
||||
glucoseUnit: "mg/dL",
|
||||
bmi: 24.1,
|
||||
compliance: {},
|
||||
medications: [{ name: "Example Drug", dose: "5mg", schedules: [] }],
|
||||
medicationAdministrations: [
|
||||
{
|
||||
medicationName: "Example Drug",
|
||||
effectiveAt: "2026-04-30T08:00:00.000Z",
|
||||
status: "completed",
|
||||
doseText: "5mg",
|
||||
dose: { value: 5, unit: "mg" },
|
||||
injectionSite: null,
|
||||
atcCode: null,
|
||||
rxNormCode: null,
|
||||
deliveryForm: "ORAL",
|
||||
},
|
||||
],
|
||||
illnessEpisodes: [
|
||||
{
|
||||
label: "Erkältung",
|
||||
type: "INFECTION",
|
||||
lifecycle: "ACUTE",
|
||||
onsetAt: "2026-04-01T00:00:00.000Z",
|
||||
resolvedAt: "2026-04-10T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
cycle: {
|
||||
lastPeriodStart: "2026-04-20",
|
||||
recentCycles: [],
|
||||
observedCycleCount: 3,
|
||||
averageCycleLengthDays: 27.5,
|
||||
cycleLengthVariabilityDays: 0.5,
|
||||
averagePeriodLengthDays: 5,
|
||||
currentPhase: "LUTEAL",
|
||||
},
|
||||
mood: { avg: 3.8, count: 20 },
|
||||
glp1: null,
|
||||
} as unknown as DoctorReportData;
|
||||
|
||||
const RECORDS = {
|
||||
allergies: [
|
||||
{
|
||||
id: "a1",
|
||||
substance: "Penicillin",
|
||||
category: "MEDICATION",
|
||||
type: "ALLERGY",
|
||||
status: "ACTIVE",
|
||||
severity: "SEVERE",
|
||||
reaction: "Rash",
|
||||
onsetAt: null,
|
||||
note: null,
|
||||
},
|
||||
],
|
||||
familyHistory: [
|
||||
{
|
||||
id: "f1",
|
||||
relationship: "MOTHER",
|
||||
condition: "Hypertension",
|
||||
ageAtOnset: 50,
|
||||
note: null,
|
||||
},
|
||||
],
|
||||
} as never;
|
||||
|
||||
function req(pathname: string): NextRequest {
|
||||
return new NextRequest(`http://localhost${pathname}`);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(checkRateLimit).mockResolvedValue({
|
||||
allowed: true,
|
||||
count: 1,
|
||||
resetAt: Date.now(),
|
||||
} as never);
|
||||
vi.mocked(requireModuleEnabled).mockResolvedValue({ enabled: true });
|
||||
vi.mocked(isModuleEnabled).mockResolvedValue(true);
|
||||
vi.mocked(loadFhirContext).mockResolvedValue({
|
||||
data: DATA,
|
||||
identity: { insuranceNumber: "A123456780" },
|
||||
germanAtc: false,
|
||||
records: RECORDS,
|
||||
});
|
||||
});
|
||||
|
||||
interface CapabilityStatement {
|
||||
resourceType: string;
|
||||
implementation?: { description: string; url: string };
|
||||
software?: { name: string; version: string };
|
||||
description?: string;
|
||||
rest: Array<{
|
||||
resource: Array<{
|
||||
type: string;
|
||||
interaction?: Array<{ code: string }>;
|
||||
operation?: Array<{ name: string }>;
|
||||
}>;
|
||||
}>;
|
||||
}
|
||||
|
||||
describe("GET /api/fhir/metadata — CapabilityStatement", () => {
|
||||
it("describes the instance it speaks for (cpb-2)", async () => {
|
||||
const res = await metadataGet(req("/api/fhir/metadata"));
|
||||
const body = (await res.json()) as CapabilityStatement;
|
||||
expect(body.resourceType).toBe("CapabilityStatement");
|
||||
expect(body.description?.length).toBeGreaterThan(0);
|
||||
expect(body.software?.name).toBe("HealthLog");
|
||||
expect(body.software?.version.length).toBeGreaterThan(0);
|
||||
expect(body.implementation?.description.length).toBeGreaterThan(0);
|
||||
expect(body.implementation?.url).toBe("http://localhost/api/fhir");
|
||||
});
|
||||
|
||||
it("describes Patient exactly once, carrying the operation (cpb-9)", async () => {
|
||||
const res = await metadataGet(req("/api/fhir/metadata"));
|
||||
const body = (await res.json()) as CapabilityStatement;
|
||||
const resources = body.rest[0].resource;
|
||||
const types = resources.map((r) => r.type);
|
||||
expect(types.filter((t) => t === "Patient")).toHaveLength(1);
|
||||
expect(new Set(types).size).toBe(types.length);
|
||||
const patient = resources.find((r) => r.type === "Patient");
|
||||
expect(patient?.operation?.[0].name).toBe("everything");
|
||||
expect(patient?.interaction?.map((i) => i.code)).toEqual([
|
||||
"read",
|
||||
"search-type",
|
||||
]);
|
||||
});
|
||||
|
||||
it("advertises no interaction without a route behind it", async () => {
|
||||
const res = await metadataGet(req("/api/fhir/metadata"));
|
||||
const body = (await res.json()) as CapabilityStatement;
|
||||
const root = path.join(process.cwd(), "src/app/api/fhir");
|
||||
|
||||
for (const resource of body.rest[0].resource) {
|
||||
for (const { code } of resource.interaction ?? []) {
|
||||
const file =
|
||||
code === "read"
|
||||
? path.join(root, resource.type, "[id]", "route.ts")
|
||||
: path.join(root, resource.type, "route.ts");
|
||||
expect(existsSync(file), `${resource.type} ${code} → ${file}`).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
for (const { name } of resource.operation ?? []) {
|
||||
const file = path.join(root, resource.type, `$${name}`, "route.ts");
|
||||
expect(existsSync(file), `${resource.type} $${name} → ${file}`).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
// …and the catalogue the statement derives from is the routed set.
|
||||
expect(body.rest[0].resource.map((r) => r.type)).toEqual([
|
||||
...FHIR_REST_RESOURCE_TYPES,
|
||||
]);
|
||||
});
|
||||
|
||||
it("advertises no write interaction", async () => {
|
||||
const res = await metadataGet(req("/api/fhir/metadata"));
|
||||
const body = (await res.json()) as CapabilityStatement;
|
||||
const codes = body.rest[0].resource.flatMap((r) =>
|
||||
(r.interaction ?? []).map((i) => i.code),
|
||||
);
|
||||
for (const code of codes) {
|
||||
expect(["read", "search-type"]).toContain(code);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/fhir/{type}/{id} — read", () => {
|
||||
it("serves the resource the searchset fullUrl points at", async () => {
|
||||
const res = await observationRead(req("/api/fhir/Observation/obs-1"), {
|
||||
params: Promise.resolve({ id: "obs-1" }),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toContain("application/fhir+json");
|
||||
const body = (await res.json()) as { resourceType: string; id: string };
|
||||
expect(body.resourceType).toBe("Observation");
|
||||
expect(body.id).toBe("obs-1");
|
||||
});
|
||||
|
||||
it("answers an id the record does not hold with a not-found OperationOutcome", async () => {
|
||||
const res = await observationRead(req("/api/fhir/Observation/obs-999"), {
|
||||
params: Promise.resolve({ id: "obs-999" }),
|
||||
});
|
||||
expect(res.status).toBe(404);
|
||||
const body = (await res.json()) as {
|
||||
resourceType: string;
|
||||
issue: Array<{ code: string }>;
|
||||
};
|
||||
expect(body.resourceType).toBe("OperationOutcome");
|
||||
expect(body.issue[0].code).toBe("not-found");
|
||||
});
|
||||
|
||||
it("reads the Patient", async () => {
|
||||
const res = await patientRead(req("/api/fhir/Patient/patient-1"), {
|
||||
params: Promise.resolve({ id: "patient-1" }),
|
||||
});
|
||||
const body = (await res.json()) as { resourceType: string };
|
||||
expect(body.resourceType).toBe("Patient");
|
||||
});
|
||||
|
||||
it("reads the Coverage", async () => {
|
||||
const res = await coverageRead(req("/api/fhir/Coverage/coverage-1"), {
|
||||
params: Promise.resolve({ id: "coverage-1" }),
|
||||
});
|
||||
const body = (await res.json()) as { resourceType: string };
|
||||
expect(body.resourceType).toBe("Coverage");
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/fhir/Patient/$everything", () => {
|
||||
it("returns every resource family the document bundle carries", async () => {
|
||||
const res = await everythingGet(
|
||||
req("/api/fhir/Patient/$everything?_count=200"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const bundle = (await res.json()) as {
|
||||
type: string;
|
||||
total: number;
|
||||
entry: Array<{ fullUrl: string; resource: { resourceType: string } }>;
|
||||
};
|
||||
expect(bundle.type).toBe("searchset");
|
||||
|
||||
const document = buildFhirDocumentBundle(
|
||||
DATA,
|
||||
{ insuranceNumber: "A123456780" },
|
||||
FIXED_NOW,
|
||||
{ germanAtc: false },
|
||||
RECORDS,
|
||||
);
|
||||
const expected = new Set(
|
||||
document.entry.map((e) => e.resource.resourceType),
|
||||
);
|
||||
const served = new Set(bundle.entry.map((e) => e.resource.resourceType));
|
||||
expect(served).toEqual(expected);
|
||||
expect(bundle.total).toBe(document.entry.length);
|
||||
|
||||
// The families the operation used to drop.
|
||||
for (const type of [
|
||||
"Composition",
|
||||
"Device",
|
||||
"Condition",
|
||||
"Encounter",
|
||||
"AllergyIntolerance",
|
||||
"FamilyMemberHistory",
|
||||
"DiagnosticReport",
|
||||
"Coverage",
|
||||
]) {
|
||||
expect(served.has(type), `missing ${type}`).toBe(true);
|
||||
}
|
||||
// …including the cycle Observations, which share a resourceType with the
|
||||
// vitals and would hide inside the set check above.
|
||||
const ids = bundle.entry.map(
|
||||
(e) => (e.resource as unknown as { id: string }).id,
|
||||
);
|
||||
expect(ids.some((id) => id.startsWith("obs-cycle-"))).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the entry identities the references resolve against", async () => {
|
||||
const res = await everythingGet(
|
||||
req("/api/fhir/Patient/$everything?_count=200"),
|
||||
);
|
||||
const bundle = (await res.json()) as {
|
||||
entry: Array<{
|
||||
fullUrl: string;
|
||||
search: { mode: string };
|
||||
resource: { subject?: { reference?: string } };
|
||||
}>;
|
||||
};
|
||||
const urls = new Set(bundle.entry.map((e) => e.fullUrl));
|
||||
for (const entry of bundle.entry) {
|
||||
expect(entry.fullUrl.startsWith("urn:uuid:")).toBe(true);
|
||||
expect(entry.search.mode).toBe("match");
|
||||
const subject = entry.resource.subject?.reference;
|
||||
if (subject) expect(urls.has(subject)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -47,9 +47,12 @@ vi.mock("@/lib/fhir/rest", async (importOriginal) => {
|
||||
});
|
||||
vi.mock("@/lib/fhir/resources", () => ({
|
||||
GERMAN_ATC_DEFAULT_LOCALES: ["de"],
|
||||
patientResource: vi.fn(() => ({ resourceType: "Patient", id: "p-1" })),
|
||||
PATIENT_RESOURCE_ID: "patient-1",
|
||||
patientResource: vi.fn(() => ({ resourceType: "Patient", id: "patient-1" })),
|
||||
coverageResource: vi.fn(() => null),
|
||||
observationsFromReportData: vi.fn(() => []),
|
||||
cycleObservationsFromReportData: vi.fn(() => []),
|
||||
conditionsFromReportData: vi.fn(() => ({ conditions: [], encounters: [] })),
|
||||
medicationStatementsFromReportData: vi.fn(() => []),
|
||||
medicationAdministrationsFromReportData: vi.fn(() => []),
|
||||
}));
|
||||
@@ -63,10 +66,16 @@ vi.mock("next/headers", () => ({
|
||||
}));
|
||||
|
||||
import { GET as patientGet } from "../Patient/route";
|
||||
import { GET as coverageGet } from "../Coverage/route";
|
||||
import { GET as patientRead } from "../Patient/[id]/route";
|
||||
import { GET as coverageRead } from "../Coverage/[id]/route";
|
||||
import { GET as observationRead } from "../Observation/[id]/route";
|
||||
import { GET as medStatementRead } from "../MedicationStatement/[id]/route";
|
||||
import { GET as medAdminRead } from "../MedicationAdministration/[id]/route";
|
||||
import { GET as observationGet } from "../Observation/route";
|
||||
import { GET as medStatementGet } from "../MedicationStatement/route";
|
||||
import { GET as medAdminGet } from "../MedicationAdministration/route";
|
||||
import { GET as everythingGet } from "../$everything/route";
|
||||
import { GET as everythingGet } from "../Patient/$everything/route";
|
||||
import { GET as metadataGet } from "../metadata/route";
|
||||
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
@@ -95,15 +104,42 @@ const SESSION_OK = {
|
||||
user: { id: "user-1", username: "tester", role: "USER" as const },
|
||||
};
|
||||
|
||||
/** Every data route under `/api/fhir`, by the path a caller would hit. */
|
||||
/**
|
||||
* Every data route under `/api/fhir`, by the path a caller would hit. The
|
||||
* `/{type}/{id}` reads are here too: a route that 403s on search and serves on
|
||||
* read would leak the same record through the other door.
|
||||
*/
|
||||
const DATA_ROUTES: ReadonlyArray<
|
||||
[string, (req: NextRequest) => Promise<Response>]
|
||||
> = [
|
||||
["Patient", patientGet],
|
||||
["Coverage", coverageGet],
|
||||
["Observation", observationGet],
|
||||
["MedicationStatement", medStatementGet],
|
||||
["MedicationAdministration", medAdminGet],
|
||||
["$everything", everythingGet],
|
||||
["Patient/$everything", everythingGet],
|
||||
];
|
||||
|
||||
/**
|
||||
* The `/{type}/{id}` reads. Same gate, different success shape (a bare
|
||||
* resource, not a Bundle) — a route that 403s on search and serves on read
|
||||
* would leak the same record through the other door.
|
||||
*/
|
||||
function idCtx(id: string) {
|
||||
return { params: Promise.resolve({ id }) };
|
||||
}
|
||||
|
||||
const READ_ROUTES: ReadonlyArray<
|
||||
[string, (req: NextRequest) => Promise<Response>]
|
||||
> = [
|
||||
["Patient/patient-1", (req) => patientRead(req, idCtx("patient-1"))],
|
||||
["Coverage/coverage-1", (req) => coverageRead(req, idCtx("coverage-1"))],
|
||||
["Observation/obs-1", (req) => observationRead(req, idCtx("obs-1"))],
|
||||
["MedicationStatement/med-1", (req) => medStatementRead(req, idCtx("med-1"))],
|
||||
[
|
||||
"MedicationAdministration/medadmin-1",
|
||||
(req) => medAdminRead(req, idCtx("medadmin-1")),
|
||||
],
|
||||
];
|
||||
|
||||
function req(path: string): NextRequest {
|
||||
@@ -124,9 +160,18 @@ beforeEach(() => {
|
||||
Object.fromEntries(MODULE_KEYS.map((k) => [k, true])) as never,
|
||||
);
|
||||
vi.mocked(loadFhirContext).mockResolvedValue({
|
||||
data: {} as never,
|
||||
data: {
|
||||
period: {
|
||||
days: 90,
|
||||
since: "2026-02-02T00:00:00.000Z",
|
||||
start: "2026-02-02T00:00:00.000Z",
|
||||
end: "2026-05-03T00:00:00.000Z",
|
||||
},
|
||||
patient: {},
|
||||
} as never,
|
||||
identity: { insuranceNumber: "A123456789" },
|
||||
germanAtc: false,
|
||||
records: {},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -168,10 +213,37 @@ describe("/api/fhir/* — doctorReport module gate", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe.each(READ_ROUTES)("GET /api/fhir/%s", (path, handler) => {
|
||||
it("403s with module.disabled when the module is off", async () => {
|
||||
setDoctorReportModule(false);
|
||||
|
||||
const res = await handler(req(path));
|
||||
expect(res.status).toBe(403);
|
||||
const body = (await res.json()) as {
|
||||
meta?: { errorCode?: string; module?: string };
|
||||
};
|
||||
expect(body.meta?.errorCode).toBe(MODULE_DISABLED_ERROR_CODE);
|
||||
expect(body.meta?.module).toBe("doctorReport");
|
||||
expect(loadFhirContext).not.toHaveBeenCalled();
|
||||
expect(JSON.stringify(body)).not.toContain("A123456789");
|
||||
});
|
||||
|
||||
it("reaches the record when the module is on", async () => {
|
||||
setDoctorReportModule(true);
|
||||
|
||||
const res = await handler(req(path));
|
||||
// The emitters are stubbed empty here, so the honest answer is a
|
||||
// `not-found` OperationOutcome — what matters is that the gate did not
|
||||
// refuse and the aggregate was assembled.
|
||||
expect(res.status).not.toBe(403);
|
||||
expect(loadFhirContext).toHaveBeenCalledWith("user-1");
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves the static CapabilityStatement reachable while the module is off", async () => {
|
||||
// Server metadata, no user data — the one FHIR route that stays open.
|
||||
setDoctorReportModule(false);
|
||||
const res = await metadataGet();
|
||||
const res = await metadataGet(req("metadata"));
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { resourceType: string };
|
||||
expect(body.resourceType).toBe("CapabilityStatement");
|
||||
|
||||
@@ -78,6 +78,7 @@ beforeEach(() => {
|
||||
data: {} as never,
|
||||
identity: { insuranceNumber: null },
|
||||
germanAtc: false,
|
||||
records: {},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
/**
|
||||
* GET /api/fhir/metadata — FHIR R4 `CapabilityStatement`.
|
||||
*
|
||||
* Declares the read-only REST face: the resource types served, the search
|
||||
* parameters honoured (`_count`, `_offset`), the `$everything` operation, and
|
||||
* the `application/fhir+json` format. Static — no per-user data — but still
|
||||
* gated behind the `fhir:read` scope so the whole `/api/fhir` tree answers
|
||||
* Declares the read-only REST face: the resource types served, the `read` +
|
||||
* `search-type` interactions on each, the search parameters honoured
|
||||
* (`_count`, `_offset`), the `Patient-everything` operation, and the
|
||||
* `application/fhir+json` format. Static — no per-user data — but still gated
|
||||
* behind the `fhir:read` scope so the whole `/api/fhir` tree answers
|
||||
* uniformly. Read-only: no write interactions are advertised.
|
||||
*
|
||||
* Every entry here is backed by a route. `FHIR_REST_RESOURCE_TYPES` is the one
|
||||
* catalogue the resource entries derive from, and each type in it has both a
|
||||
* `/{type}` search route and a `/{type}/{id}` read route; the operation is
|
||||
* routed at `/api/fhir/Patient/$everything`. A statement that advertises an
|
||||
* interaction a client cannot reach is worse than one that stays quiet.
|
||||
*/
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
import packageJson from "../../../../../package.json";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
@@ -16,15 +26,32 @@ import {
|
||||
fhirJsonResponse,
|
||||
} from "@/lib/fhir/rest";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
await requireAuth(FHIR_READ_SCOPE);
|
||||
annotate({ action: { name: "fhir.metadata.read" } });
|
||||
|
||||
// Same resolution order as `/api/version`: the image build arg wins so a
|
||||
// deployed instance names its release, with the package version as the
|
||||
// local-dev fallback.
|
||||
const version =
|
||||
process.env.NEXT_PUBLIC_APP_VERSION?.trim() || packageJson.version;
|
||||
|
||||
const capability = {
|
||||
resourceType: "CapabilityStatement",
|
||||
status: "active",
|
||||
date: new Date().toISOString(),
|
||||
kind: "instance",
|
||||
description:
|
||||
"Read-only HL7 FHIR R4 face over a single HealthLog account's own health record.",
|
||||
software: { name: "HealthLog", version },
|
||||
// `cpb-2` — a `kind: "instance"` statement SHALL describe the instance it
|
||||
// speaks for. The URL is the deployment answering this request, not a
|
||||
// hardcoded host: a self-hosted instance is reachable at its own origin
|
||||
// and nowhere else.
|
||||
implementation: {
|
||||
description: "HealthLog self-hosted instance",
|
||||
url: new URL("/api/fhir", request.nextUrl.origin).toString(),
|
||||
},
|
||||
fhirVersion: "4.0.1",
|
||||
format: ["application/fhir+json"],
|
||||
rest: [
|
||||
@@ -32,26 +59,28 @@ export const GET = apiHandler(async () => {
|
||||
mode: "server",
|
||||
documentation:
|
||||
"Read-only access to the authenticated user's own health record.",
|
||||
resource: [
|
||||
...FHIR_REST_RESOURCE_TYPES.map((type) => ({
|
||||
type,
|
||||
interaction: [{ code: "read" }, { code: "search-type" }],
|
||||
searchParam: FHIR_SEARCH_PARAMS.map((name) => ({
|
||||
name,
|
||||
type: "number",
|
||||
})),
|
||||
// `cpb-9` — one entry per resource type. The Patient entry carries the
|
||||
// `$everything` operation alongside its interactions rather than
|
||||
// appearing a second time.
|
||||
resource: FHIR_REST_RESOURCE_TYPES.map((type) => ({
|
||||
type,
|
||||
interaction: [{ code: "read" }, { code: "search-type" }],
|
||||
searchParam: FHIR_SEARCH_PARAMS.map((name) => ({
|
||||
name,
|
||||
type: "number",
|
||||
})),
|
||||
{
|
||||
type: "Patient",
|
||||
operation: [
|
||||
{
|
||||
name: "everything",
|
||||
definition:
|
||||
"http://hl7.org/fhir/OperationDefinition/Patient-everything",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
...(type === "Patient"
|
||||
? {
|
||||
operation: [
|
||||
{
|
||||
name: "everything",
|
||||
definition:
|
||||
"http://hl7.org/fhir/OperationDefinition/Patient-everything",
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
})),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -59,7 +59,10 @@ import {
|
||||
FHIR_SEARCH_PARAMS,
|
||||
} from "@/lib/fhir/rest";
|
||||
import { SHARE_LINK_MAX_DAYS } from "@/lib/validations/clinician-share-link";
|
||||
import { exportSectionsSchema } from "@/lib/validations/health-record-export";
|
||||
import {
|
||||
ALL_LEAF_IDS,
|
||||
REPORT_GROUP_ORDER,
|
||||
} from "@/lib/report-selection/catalogue";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
@@ -92,8 +95,10 @@ type CapabilitiesBody = {
|
||||
share: {
|
||||
supported: boolean;
|
||||
maxDays: number;
|
||||
fhirApi: boolean;
|
||||
sections: string[];
|
||||
reportDownload: string[];
|
||||
selectionVersion: number;
|
||||
groups: string[];
|
||||
leaves: string[];
|
||||
};
|
||||
};
|
||||
};
|
||||
@@ -175,11 +180,14 @@ describe("GET /api/meta/capabilities — drift guards", () => {
|
||||
const body = (await res.json()) as CapabilitiesBody;
|
||||
expect(body.data.share.supported).toBe(true);
|
||||
expect(body.data.share.maxDays).toBe(SHARE_LINK_MAX_DAYS);
|
||||
// The share serves the rendered record view only; no `/api/fhir/*` route
|
||||
// honours a share token yet, so the share→FHIR face is advertised off.
|
||||
expect(body.data.share.fhirApi).toBe(false);
|
||||
expect([...body.data.share.sections].sort()).toEqual(
|
||||
Object.keys(exportSectionsSchema.shape).sort(),
|
||||
// The record IS reachable in machine form now — as a download under the
|
||||
// token, not as a bearer API. The old `fhirApi: false` described a face
|
||||
// that was never built.
|
||||
expect(body.data.share.reportDownload).toEqual(["fhir", "pdf"]);
|
||||
expect(body.data.share.selectionVersion).toBe(2);
|
||||
expect(body.data.share.groups).toEqual([...REPORT_GROUP_ORDER]);
|
||||
expect([...body.data.share.leaves].sort()).toEqual(
|
||||
[...ALL_LEAF_IDS].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -41,7 +41,10 @@ vi.mock("next/headers", () => ({
|
||||
|
||||
import { POST, GET } from "../route";
|
||||
import { DELETE } from "../[id]/route";
|
||||
import { EMPTY_DOCTOR_REPORT_PREFS } from "@/lib/validations/doctor-report-prefs";
|
||||
import {
|
||||
selectionToBlob,
|
||||
selectionFromLeaves,
|
||||
} from "@/lib/report-selection/selection";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
@@ -81,6 +84,8 @@ function storedRow(overrides: Record<string, unknown> = {}) {
|
||||
revokedAt: null,
|
||||
lastAccessAt: null,
|
||||
accessCount: 0,
|
||||
documentOnly: false,
|
||||
sectionsJson: selectionToBlob(selectionFromLeaves(["WEIGHT"])),
|
||||
_count: { documents: 0 },
|
||||
...overrides,
|
||||
};
|
||||
@@ -277,7 +282,7 @@ describe("POST /api/share-links — create", () => {
|
||||
postReq(
|
||||
validBody({
|
||||
documentOnly: true,
|
||||
sections: { vitals: { bp: true }, labs: true },
|
||||
selection: { v: 2, leaves: ["BLOOD_PRESSURE_SYS", "LAB_RESULTS"] },
|
||||
documentIds: ["doc-a"],
|
||||
}),
|
||||
),
|
||||
@@ -289,9 +294,9 @@ describe("POST /api/share-links — create", () => {
|
||||
// The retired FHIR scope columns are never written at all.
|
||||
expect(createArg.data).not.toHaveProperty("resourceTypes");
|
||||
expect(createArg.data).not.toHaveProperty("allowFhirApi");
|
||||
// Sections persist as an explicit all-OFF blob (distinct from `{}` = full
|
||||
// record defaults). The clinician view reads this as "no report".
|
||||
expect(createArg.data.sectionsJson).toEqual(EMPTY_DOCTOR_REPORT_PREFS);
|
||||
// The scope persists as an explicit EMPTY leaf list. The clinician view
|
||||
// reads that as "no report" and never calls the aggregator.
|
||||
expect(createArg.data.sectionsJson).toEqual({ v: 2, leaves: [] });
|
||||
// v1.28.16 — the frozen documents-only flag is persisted so the view path
|
||||
// gates on the column, not on inferring "all sections off". This is what a
|
||||
// future report section can never re-open.
|
||||
@@ -362,3 +367,120 @@ describe("DELETE /api/share-links/[id] — revoke", () => {
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The frozen scope, and the two things a share link may never carry.
|
||||
*
|
||||
* Mutation checks:
|
||||
* - drop the `SHARE_LINK_FORBIDDEN_LEAVES` check in the route → "refuses the
|
||||
* insurance leaf by name" goes red.
|
||||
* - drop `RETIRED_FHIR_SCOPE_FIELDS` from the create response → "keeps the
|
||||
* retired scope fields on the response" goes red.
|
||||
* - make `needsReselection` always false → "flags a link whose frozen scope
|
||||
* predates the selection model" goes red.
|
||||
*/
|
||||
describe("POST /api/share-links — the frozen scope", () => {
|
||||
it("persists exactly the leaves the owner chose", async () => {
|
||||
vi.mocked(prisma.clinicianShareLink.create).mockResolvedValue(
|
||||
storedRow() as never,
|
||||
);
|
||||
const res = await POST(
|
||||
postReq(
|
||||
validBody({
|
||||
selection: { v: 2, leaves: ["LAB_RESULTS", "WEIGHT"] },
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
const createArg = vi.mocked(prisma.clinicianShareLink.create).mock
|
||||
.calls[0][0];
|
||||
// Canonical order, not the caller's.
|
||||
expect(createArg.data.sectionsJson).toEqual({
|
||||
v: 2,
|
||||
leaves: ["WEIGHT", "LAB_RESULTS"],
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses the insurance leaf by name", async () => {
|
||||
// The share view has never decrypted the insurance number. Refusing the
|
||||
// leaf at create makes that structural: there is no path by which a link
|
||||
// could later carry it.
|
||||
const res = await POST(
|
||||
postReq(validBody({ selection: { v: 2, leaves: ["INSURANCE"] } })),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
const body = (await res.json()) as { error: string };
|
||||
expect(body.error).toContain("INSURANCE");
|
||||
expect(prisma.clinicianShareLink.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses a leaf id this build does not know", async () => {
|
||||
const res = await POST(
|
||||
postReq(validBody({ selection: { v: 2, leaves: ["SOMETHING_NEW"] } })),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
expect(prisma.clinicianShareLink.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("mints an empty scope when the body names none", async () => {
|
||||
vi.mocked(prisma.clinicianShareLink.create).mockResolvedValue(
|
||||
storedRow() as never,
|
||||
);
|
||||
const res = await POST(postReq(validBody()));
|
||||
expect(res.status).toBe(201);
|
||||
const createArg = vi.mocked(prisma.clinicianShareLink.create).mock
|
||||
.calls[0][0];
|
||||
expect(createArg.data.sectionsJson).toEqual({ v: 2, leaves: [] });
|
||||
});
|
||||
|
||||
it("keeps the retired scope fields on the response", async () => {
|
||||
// Response-only, serving constants. The request refuses them and the
|
||||
// columns are gone; they stay here until the native client confirms it
|
||||
// does not decode them.
|
||||
vi.mocked(prisma.clinicianShareLink.create).mockResolvedValue(
|
||||
storedRow() as never,
|
||||
);
|
||||
const res = await POST(
|
||||
postReq(validBody({ selection: { v: 2, leaves: ["WEIGHT"] } })),
|
||||
);
|
||||
const body = (await res.json()) as {
|
||||
data: { allowFhirApi: boolean; resourceTypes: string[] };
|
||||
};
|
||||
expect(body.data.allowFhirApi).toBe(false);
|
||||
expect(body.data.resourceTypes).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/share-links — the pick-again state", () => {
|
||||
it("flags a link whose frozen scope predates the selection model", async () => {
|
||||
vi.mocked(prisma.clinicianShareLink.findMany).mockResolvedValue([
|
||||
storedRow({
|
||||
id: "legacy",
|
||||
revokedAt: new Date(),
|
||||
sectionsJson: { bp: true, weight: true, pulse: true },
|
||||
}),
|
||||
storedRow({ id: "current" }),
|
||||
storedRow({ id: "docs", documentOnly: true, sectionsJson: {} }),
|
||||
] as never);
|
||||
const res = await GET();
|
||||
const body = (await res.json()) as {
|
||||
data: {
|
||||
shareLinks: Array<{
|
||||
id: string;
|
||||
needsReselection: boolean;
|
||||
allowFhirApi: boolean;
|
||||
resourceTypes: string[];
|
||||
}>;
|
||||
};
|
||||
};
|
||||
const byId = new Map(body.data.shareLinks.map((l) => [l.id, l]));
|
||||
expect(byId.get("legacy")!.needsReselection).toBe(true);
|
||||
expect(byId.get("current")!.needsReselection).toBe(false);
|
||||
// A documents-only link carried no report scope to begin with, so it was
|
||||
// never revoked and is not asked to pick again.
|
||||
expect(byId.get("docs")!.needsReselection).toBe(false);
|
||||
// The retired fields ride the list response too.
|
||||
expect(byId.get("current")!.allowFhirApi).toBe(false);
|
||||
expect(byId.get("current")!.resourceTypes).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user