mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
Merge tickets part 2 into release/v1.42.0
# Conflicts: # src/__tests__/i18n-reverse-coverage.test.ts
This commit is contained in:
commit
9d4a50282e
80 files changed
+3975
-818
No files matched your search
+25
@@ -457,6 +457,31 @@ export const ADMITTED_MUTATING_HANDLERS = [
|
||||
"write",
|
||||
"upsert",
|
||||
),
|
||||
// v1.42 (#1005) — the record's own vaccine definitions.
|
||||
handler(
|
||||
"app/api/vaccinations/custom/route.ts",
|
||||
"/api/vaccinations/custom",
|
||||
"POST",
|
||||
"profile",
|
||||
"write",
|
||||
"create",
|
||||
),
|
||||
handler(
|
||||
"app/api/vaccinations/custom/[id]/route.ts",
|
||||
"/api/vaccinations/custom/[id]",
|
||||
"PATCH",
|
||||
"profile",
|
||||
"manage",
|
||||
"update",
|
||||
),
|
||||
handler(
|
||||
"app/api/vaccinations/custom/[id]/route.ts",
|
||||
"/api/vaccinations/custom/[id]",
|
||||
"DELETE",
|
||||
"profile",
|
||||
"manage",
|
||||
"delete",
|
||||
),
|
||||
handler(
|
||||
"app/api/illness/episodes/[id]/day-logs/route.ts",
|
||||
"/api/illness/episodes/[id]/day-logs",
|
||||
|
||||
@@ -288,6 +288,7 @@ const COUNT_BACK: Record<
|
||||
p.vaccinationRecord.count({ where: { userId } }),
|
||||
VaccinationDocumentLink: (p, userId) =>
|
||||
p.vaccinationDocumentLink.count({ where: { userId } }),
|
||||
CustomVaccine: (p, userId) => p.customVaccine.count({ where: { userId } }),
|
||||
MeasurementReminder: (p, userId) =>
|
||||
p.measurementReminder.count({ where: { userId } }),
|
||||
MeasurementReminderEvent: (p, userId) =>
|
||||
@@ -1284,10 +1285,23 @@ async function seedEveryTwoEndedModel(prisma: PrismaClient): Promise<void> {
|
||||
// the skip test below). `reminderId` used to be deliberately absent here —
|
||||
// it was the one reference that could never resolve — and is deliberately
|
||||
// present since v1.37.20, because resolving is now the behaviour under test.
|
||||
// v1.42 (#1005) — the person's own vaccine definition the dose also names.
|
||||
// The catalogue slug still wins on read; the reference is what has to
|
||||
// survive the trip, and it can only if the definition comes back first.
|
||||
const customVaccine = await prisma.customVaccine.create({
|
||||
data: {
|
||||
userId: OWNER_ID,
|
||||
name: "Round-trip travel combo",
|
||||
components: ["typhoid", "hepatitis-a"],
|
||||
typicalSeriesDoses: 2,
|
||||
boosterIntervalMonths: 36,
|
||||
},
|
||||
});
|
||||
const vaccination = await prisma.vaccinationRecord.create({
|
||||
data: {
|
||||
userId: OWNER_ID,
|
||||
occurredAt: AT("2026-05-14T00:00:00.000Z"),
|
||||
customVaccineId: customVaccine.id,
|
||||
antigenSlug: "tdap",
|
||||
vaccineName: "Tetanus, diphtheria and pertussis",
|
||||
doseNumber: 3,
|
||||
@@ -2097,6 +2111,7 @@ describe("every model the plan claims two-ended survives a real restore", () =>
|
||||
practitioner: { select: { name: true } },
|
||||
encounter: { select: { occurredAt: true } },
|
||||
reminder: { select: { label: true } },
|
||||
customVaccine: true,
|
||||
documentLinks: { select: { documentId: true } },
|
||||
},
|
||||
});
|
||||
@@ -2114,6 +2129,14 @@ describe("every model the plan claims two-ended survives a real restore", () =>
|
||||
// the id survived the round trip instead of dropping to NULL the way it
|
||||
// had to before the reminders travelled.
|
||||
reminder: dose.reminder?.label ?? null,
|
||||
customVaccine: dose.customVaccine
|
||||
? {
|
||||
name: dose.customVaccine.name,
|
||||
components: dose.customVaccine.components,
|
||||
typicalSeriesDoses: dose.customVaccine.typicalSeriesDoses,
|
||||
boosterIntervalMonths: dose.customVaccine.boosterIntervalMonths,
|
||||
}
|
||||
: null,
|
||||
links: dose.documentLinks.length,
|
||||
note: dose.noteEncrypted ? decryptFromBytes(dose.noteEncrypted) : null,
|
||||
}).toEqual({
|
||||
@@ -2127,6 +2150,12 @@ describe("every model the plan claims two-ended survives a real restore", () =>
|
||||
practitioner: "Round-trip practice",
|
||||
encounterAt: "2026-06-30T08:00:00.000Z",
|
||||
reminder: "Blutdruck messen",
|
||||
customVaccine: {
|
||||
name: "Round-trip travel combo",
|
||||
components: ["typhoid", "hepatitis-a"],
|
||||
typicalSeriesDoses: 2,
|
||||
boosterIntervalMonths: 36,
|
||||
},
|
||||
links: 1,
|
||||
note: "sore arm for a day, nothing else",
|
||||
});
|
||||
|
||||
@@ -377,4 +377,89 @@ describe("runDenseIntradayRetention (real Postgres)", () => {
|
||||
// Both raw samples survive — the intra-day shape is preserved.
|
||||
expect(live).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("folds Health Connect raw heart rate past the window into its own hourly rows, beside Apple Health's", async () => {
|
||||
const prisma = getPrismaClient();
|
||||
// Berlin UTC+2 on 1 May: 08:xx UTC is local hour 10 — far past 90 days.
|
||||
const at = (minute: number) =>
|
||||
new Date(`2026-05-01T08:${String(minute).padStart(2, "0")}:00.000Z`);
|
||||
await prisma.measurement.createMany({
|
||||
data: [
|
||||
...[60, 70, 80].map((value, i) => ({
|
||||
userId: TEST_USER_ID,
|
||||
type: "PULSE" as const,
|
||||
value,
|
||||
unit: "bpm",
|
||||
source: "HEALTH_CONNECT" as const,
|
||||
measuredAt: at(i * 10 + 1),
|
||||
externalId: `hc:00000000-0000-0000-0000-00000000000a:${i}`,
|
||||
})),
|
||||
{
|
||||
userId: TEST_USER_ID,
|
||||
type: "PULSE" as const,
|
||||
value: 100,
|
||||
unit: "bpm",
|
||||
source: "APPLE_HEALTH" as const,
|
||||
measuredAt: at(5),
|
||||
externalId: "hk-pulse-1",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const summary = await runDenseIntradayRetention(prisma, {
|
||||
userId: TEST_USER_ID,
|
||||
// The default 90-day window: the samples are well past it.
|
||||
log: () => {},
|
||||
});
|
||||
expect(summary.totals.perSampleRowsSoftDeleted).toBe(4);
|
||||
|
||||
const rows = await prisma.measurement.findMany({
|
||||
where: { userId: TEST_USER_ID, type: "PULSE" },
|
||||
orderBy: { source: "asc" },
|
||||
});
|
||||
// Raw rows of both sources are gone outright, not tombstoned.
|
||||
expect(rows.every((row) => row.externalId?.startsWith("stats:"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(rows.every((row) => row.deletedAt === null)).toBe(true);
|
||||
const id = "stats:HKQuantityTypeIdentifierHeartRate:2026-05-01T10";
|
||||
// One mean per source: the two sources never share a row.
|
||||
expect(rows.map((row) => [row.source, row.externalId, row.value])).toEqual([
|
||||
["APPLE_HEALTH", id, 100],
|
||||
["HEALTH_CONNECT", id, 70],
|
||||
]);
|
||||
|
||||
// A second run finds nothing left to fold.
|
||||
const again = await runDenseIntradayRetention(prisma, {
|
||||
userId: TEST_USER_ID,
|
||||
log: () => {},
|
||||
});
|
||||
expect(again.totals.daysConsolidated).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps Health Connect raw heart rate inside the window raw", async () => {
|
||||
const prisma = getPrismaClient();
|
||||
const recent = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000);
|
||||
await prisma.measurement.create({
|
||||
data: {
|
||||
userId: TEST_USER_ID,
|
||||
type: "PULSE",
|
||||
value: 64,
|
||||
unit: "bpm",
|
||||
source: "HEALTH_CONNECT",
|
||||
measuredAt: recent,
|
||||
externalId: "hc:00000000-0000-0000-0000-00000000000b:1",
|
||||
},
|
||||
});
|
||||
const summary = await runDenseIntradayRetention(prisma, {
|
||||
userId: TEST_USER_ID,
|
||||
log: () => {},
|
||||
});
|
||||
expect(summary.totals.daysConsolidated).toBe(0);
|
||||
expect(
|
||||
await prisma.measurement.count({
|
||||
where: { userId: TEST_USER_ID, source: "HEALTH_CONNECT" },
|
||||
}),
|
||||
).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
zipHealthConnectDb,
|
||||
} from "../fixtures/health-connect/build-fixture";
|
||||
import { importHealthConnectExport } from "@/lib/import/health-connect/import";
|
||||
import { runDenseIntradayRetention } from "@/lib/measurements/dense-intraday-retention";
|
||||
import {
|
||||
HEALTH_CONNECT_IMPORT_KIND,
|
||||
HEALTH_CONNECT_IMPORT_QUEUE,
|
||||
@@ -406,6 +407,53 @@ describe("Health Connect import, heart rate history", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Health Connect import, folded heart rate", () => {
|
||||
it("folds raw heart rate once it ages out, and a later import does not put it back", async () => {
|
||||
const prisma = getPrismaClient();
|
||||
const user = await createUser("hc-folded");
|
||||
// A day of minute-by-minute heart rate, 120 days back, imported while it
|
||||
// was recent so it lands raw.
|
||||
const { path, endUtc } = fixtureDb("folded", {
|
||||
days: 1,
|
||||
endUtc: today - 120 * DAY,
|
||||
});
|
||||
const args = {
|
||||
prisma,
|
||||
dbPath: path,
|
||||
userId: user.id,
|
||||
userTimezone: "Europe/Berlin",
|
||||
connectedIntegrations: [],
|
||||
now: new Date(endUtc),
|
||||
} as const;
|
||||
await importHealthConnectExport(args);
|
||||
expect((await countBy(user.id)).PULSE).toBe(24 * 60);
|
||||
|
||||
// The nightly fold, at today's clock: the samples are past the window.
|
||||
await runDenseIntradayRetention(prisma, {
|
||||
userId: user.id,
|
||||
log: () => {},
|
||||
});
|
||||
const folded = await prisma.measurement.findMany({
|
||||
where: { userId: user.id, type: "PULSE", source: "HEALTH_CONNECT" },
|
||||
});
|
||||
expect(folded).toHaveLength(24);
|
||||
expect(
|
||||
folded.every(
|
||||
(row) =>
|
||||
row.deletedAt === null &&
|
||||
row.externalId?.startsWith(
|
||||
"stats:HKQuantityTypeIdentifierHeartRate:",
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
// The same export again: every raw sample's hour is folded already.
|
||||
const again = await importHealthConnectExport(args);
|
||||
expect(again.skipped["PULSE::folded_window"]).toBe(24 * 60);
|
||||
expect((await countBy(user.id)).PULSE).toBe(24);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Health Connect import, worker", () => {
|
||||
async function stagedJob(name: string, zipBuilder: (zip: string) => void) {
|
||||
const prisma = getPrismaClient();
|
||||
|
||||
@@ -282,7 +282,7 @@ const ROUTE_IMPORTS = import.meta.glob<Record<string, unknown>>(
|
||||
|
||||
describe("the complete MANAGE handler matrix", () => {
|
||||
it("starts with a non-empty, exact handler inventory", () => {
|
||||
expect(ADMITTED_MUTATING_HANDLERS.length).toBe(84);
|
||||
expect(ADMITTED_MUTATING_HANDLERS.length).toBe(87);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -552,6 +552,12 @@ async function makeVaccination(userId: string) {
|
||||
});
|
||||
}
|
||||
|
||||
async function makeCustomVaccine(userId: string) {
|
||||
return getPrismaClient().customVaccine.create({
|
||||
data: { userId, name: "Travel combo", components: ["typhoid"] },
|
||||
});
|
||||
}
|
||||
|
||||
async function makeFamilyHistory(userId: string) {
|
||||
return getPrismaClient().familyHistoryEntry.create({
|
||||
data: { userId, relationship: "MOTHER", condition: "Hypertension" },
|
||||
@@ -1794,6 +1800,81 @@ manageContract("POST /api/vaccinations/[id]/restore", {
|
||||
)?.deletedAt === null,
|
||||
});
|
||||
|
||||
writeEffectContract("POST /api/vaccinations/custom", {
|
||||
contract: ADMITTED_MUTATING_HANDLERS.find(
|
||||
(entry) =>
|
||||
entry.route === "/api/vaccinations/custom" && entry.action === "POST",
|
||||
)!,
|
||||
prepare: async (ownerId) => ({ ownerId }),
|
||||
act: async () => {
|
||||
const { POST } = await import("@/app/api/vaccinations/custom/route");
|
||||
return call(POST as Handler, "POST", "/api/vaccinations/custom", {
|
||||
name: "Cholera oral",
|
||||
components: ["cholera"],
|
||||
});
|
||||
},
|
||||
ok: 201,
|
||||
auditAction: "vaccination.custom.create",
|
||||
applied: async ({ ownerId }) =>
|
||||
(await getPrismaClient().customVaccine.count({
|
||||
where: { userId: ownerId },
|
||||
})) === 1,
|
||||
});
|
||||
|
||||
manageContract("PATCH /api/vaccinations/custom/[id]", {
|
||||
contract: ADMITTED_MUTATING_HANDLERS.find(
|
||||
(entry) =>
|
||||
entry.route === "/api/vaccinations/custom/[id]" &&
|
||||
entry.action === "PATCH",
|
||||
)!,
|
||||
prepare: (ownerId) => makeCustomVaccine(ownerId),
|
||||
act: async (row) => {
|
||||
const { PATCH } = await import("@/app/api/vaccinations/custom/[id]/route");
|
||||
return call(
|
||||
PATCH as Handler,
|
||||
"PATCH",
|
||||
`/api/vaccinations/custom/${row.id}`,
|
||||
{ boosterIntervalMonths: 36 },
|
||||
{ id: row.id },
|
||||
);
|
||||
},
|
||||
ok: 200,
|
||||
auditAction: "vaccination.custom.update",
|
||||
applied: async (row) =>
|
||||
(
|
||||
await getPrismaClient().customVaccine.findUnique({
|
||||
where: { id: row.id },
|
||||
})
|
||||
)?.boosterIntervalMonths === 36,
|
||||
});
|
||||
|
||||
manageContract("DELETE /api/vaccinations/custom/[id]", {
|
||||
contract: ADMITTED_MUTATING_HANDLERS.find(
|
||||
(entry) =>
|
||||
entry.route === "/api/vaccinations/custom/[id]" &&
|
||||
entry.action === "DELETE",
|
||||
)!,
|
||||
prepare: (ownerId) => makeCustomVaccine(ownerId),
|
||||
act: async (row) => {
|
||||
const { DELETE } = await import("@/app/api/vaccinations/custom/[id]/route");
|
||||
return call(
|
||||
DELETE as Handler,
|
||||
"DELETE",
|
||||
`/api/vaccinations/custom/${row.id}`,
|
||||
undefined,
|
||||
{ id: row.id },
|
||||
);
|
||||
},
|
||||
ok: 200,
|
||||
auditAction: "vaccination.custom.delete",
|
||||
applied: async (row) =>
|
||||
(
|
||||
await getPrismaClient().customVaccine.findUnique({
|
||||
where: { id: row.id },
|
||||
})
|
||||
)?.deletedAt !== null,
|
||||
});
|
||||
|
||||
proveWriteRoute("POST /api/vaccinations/[id]/booster", {
|
||||
route: "/api/vaccinations/[id]/booster",
|
||||
// The dose the booster is planned against. `makeVaccination` records a
|
||||
@@ -2765,13 +2846,13 @@ describe("the conditions the admissions were granted on", () => {
|
||||
describe("the complete MANAGE handler matrix", () => {
|
||||
it("registers one strict actor-and-effect driver for every admission", () => {
|
||||
const expected = ADMITTED_MUTATING_HANDLERS.map(matrixKey).sort();
|
||||
expect(STRICT_DRIVER_KEYS.size).toBe(84);
|
||||
expect(STRICT_DRIVER_KEYS.size).toBe(87);
|
||||
expect([...STRICT_DRIVER_KEYS].sort()).toEqual(expected);
|
||||
});
|
||||
|
||||
it("executes every registered driver through its owned effect and actor audit", () => {
|
||||
const expected = ADMITTED_MUTATING_HANDLERS.map(matrixKey).sort();
|
||||
expect(REAL_EFFECT_KEYS.size).toBe(84);
|
||||
expect(REAL_EFFECT_KEYS.size).toBe(87);
|
||||
expect([...REAL_EFFECT_KEYS].sort()).toEqual(expected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,424 @@
|
||||
/**
|
||||
* v1.42 (#1005) — the record's own vaccine definitions, through the real
|
||||
* routes and a real Postgres.
|
||||
*
|
||||
* Pinned here: a definition is created, listed, renamed and removed under the
|
||||
* resolved record; a dose logged against it counts into every listed
|
||||
* antigen's series and clears a booster keyed to one of them, the way a
|
||||
* catalogue combination does; an id another record holds is refused; removing
|
||||
* the definition leaves every dose standing with a name; the booster mint keys
|
||||
* on its first antigen; and the sharing levels hold — a READ delegate lists
|
||||
* but cannot add, a WRITE delegate adds onto the owner's record but cannot
|
||||
* edit, and a Guardian inside a managed profile writes to the profile.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
process.env.ENCRYPTION_KEY ??=
|
||||
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
import {
|
||||
GET as listCustom,
|
||||
POST as createCustom,
|
||||
} from "@/app/api/vaccinations/custom/route";
|
||||
import {
|
||||
DELETE as deleteCustom,
|
||||
PATCH as patchCustom,
|
||||
} from "@/app/api/vaccinations/custom/[id]/route";
|
||||
import {
|
||||
GET as listVaccinations,
|
||||
POST as createVaccination,
|
||||
} from "@/app/api/vaccinations/route";
|
||||
import { POST as planBooster } from "@/app/api/vaccinations/[id]/booster/route";
|
||||
|
||||
import { cookieJar, headerJar } from "./mock-next-headers";
|
||||
import { getPrismaClient, switchSessionTo, truncateAllTables } from "./setup";
|
||||
|
||||
vi.mock("next/headers", async () => {
|
||||
const { cookieJar, headerJar } = await import("./mock-next-headers");
|
||||
return {
|
||||
headers: vi.fn(async () => ({
|
||||
get: (name: string) => headerJar.get(name.toLowerCase()) ?? null,
|
||||
})),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: (name: string) => {
|
||||
const value = cookieJar.get(name);
|
||||
return value ? { name, value } : undefined;
|
||||
},
|
||||
set: (name: string, value: string) => cookieJar.set(name, value),
|
||||
delete: (name: string) => cookieJar.delete(name),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const daysAgo = (days: number) => new Date(Date.now() - days * DAY_MS);
|
||||
const daysFromNow = (days: number) => new Date(Date.now() + days * DAY_MS);
|
||||
|
||||
let sequence = 0;
|
||||
|
||||
interface Person {
|
||||
id: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
async function person(label: string): Promise<Person> {
|
||||
const suffix = sequence++;
|
||||
const prisma = getPrismaClient();
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
username: `${label}-${suffix}`,
|
||||
email: `${label}-${suffix}@example.test`,
|
||||
timezone: "Europe/Berlin",
|
||||
},
|
||||
});
|
||||
const session = await prisma.session.create({
|
||||
data: { userId: user.id, expiresAt: daysFromNow(1) },
|
||||
});
|
||||
return { id: user.id, sessionId: session.id };
|
||||
}
|
||||
|
||||
function signIn(who: Person): void {
|
||||
headerJar.delete("authorization");
|
||||
cookieJar.set("healthlog_session", who.sessionId);
|
||||
}
|
||||
|
||||
function json(method: string, url: string, body?: unknown): Request {
|
||||
return new Request(`http://localhost${url}`, {
|
||||
method,
|
||||
headers: { "content-type": "application/json" },
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
}
|
||||
|
||||
const params = (id: string) => ({ params: Promise.resolve({ id }) }) as never;
|
||||
|
||||
async function addCustom(body: unknown): Promise<Response> {
|
||||
return createCustom(json("POST", "/api/vaccinations/custom", body) as never);
|
||||
}
|
||||
async function getCustoms(): Promise<Response> {
|
||||
// The GET takes no request; the wrapper still hands one through.
|
||||
return (listCustom as (request: Request) => Promise<Response>)(
|
||||
json("GET", "/api/vaccinations/custom"),
|
||||
);
|
||||
}
|
||||
async function editCustom(id: string, body: unknown): Promise<Response> {
|
||||
return patchCustom(
|
||||
json("PATCH", `/api/vaccinations/custom/${id}`, body) as never,
|
||||
params(id),
|
||||
);
|
||||
}
|
||||
async function removeCustom(id: string): Promise<Response> {
|
||||
return deleteCustom(
|
||||
json("DELETE", `/api/vaccinations/custom/${id}`) as never,
|
||||
params(id),
|
||||
);
|
||||
}
|
||||
async function postDose(body: unknown): Promise<Response> {
|
||||
return createVaccination(json("POST", "/api/vaccinations", body) as never);
|
||||
}
|
||||
|
||||
interface DoseDto {
|
||||
id: string;
|
||||
customVaccineId: string | null;
|
||||
customVaccine: { name: string } | null;
|
||||
series: { antigen: string; position: number; total: number | null }[];
|
||||
reminderId: string | null;
|
||||
}
|
||||
|
||||
async function doses(): Promise<DoseDto[]> {
|
||||
const res = await listVaccinations(json("GET", "/api/vaccinations") as never);
|
||||
expect(res.status).toBe(200);
|
||||
return ((await res.json()) as { data: { vaccinations: DoseDto[] } }).data
|
||||
.vaccinations;
|
||||
}
|
||||
|
||||
const TRAVEL = {
|
||||
name: "Travel combo",
|
||||
components: ["typhoid", "hepatitis-a"],
|
||||
typicalSeriesDoses: 2,
|
||||
boosterIntervalMonths: 36,
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
await truncateAllTables(getPrismaClient());
|
||||
cookieJar.clear();
|
||||
headerJar.clear();
|
||||
});
|
||||
|
||||
describe("an owner's own vaccine definitions", () => {
|
||||
it("creates, lists and refuses a second definition of the same name", async () => {
|
||||
const owner = await person("owner");
|
||||
signIn(owner);
|
||||
|
||||
const created = await addCustom(TRAVEL);
|
||||
expect(created.status).toBe(201);
|
||||
const def = ((await created.json()) as { data: { id: string } }).data;
|
||||
|
||||
const listed = await getCustoms();
|
||||
expect(listed.status).toBe(200);
|
||||
expect(
|
||||
((await listed.json()) as { data: { id: string; name: string }[] }).data,
|
||||
).toEqual([expect.objectContaining({ id: def.id, name: "Travel combo" })]);
|
||||
|
||||
// The same product, typed differently, is one product to the reader.
|
||||
const clash = await addCustom({ ...TRAVEL, name: "travel COMBO" });
|
||||
expect(clash.status).toBe(409);
|
||||
expect((await clash.json()).meta?.errorCode).toBe(
|
||||
"vaccination.custom.name-taken",
|
||||
);
|
||||
|
||||
// An antigen outside the closed list is refused.
|
||||
const bad = await addCustom({ name: "Other", components: ["unicorn-pox"] });
|
||||
expect(bad.status).toBe(422);
|
||||
});
|
||||
|
||||
it("counts a dose into every listed antigen and clears a booster keyed to one", async () => {
|
||||
const owner = await person("owner");
|
||||
signIn(owner);
|
||||
const prisma = getPrismaClient();
|
||||
const def = (
|
||||
(await (await addCustom(TRAVEL)).json()) as { data: { id: string } }
|
||||
).data;
|
||||
// A hepatitis A booster already planned and due.
|
||||
const reminder = await prisma.measurementReminder.create({
|
||||
data: {
|
||||
userId: owner.id,
|
||||
label: "hepatitis A booster",
|
||||
intervalDays: 3650,
|
||||
notifyHour: 9,
|
||||
vaccinationAntigen: "hepatitis-a",
|
||||
nextDueAt: daysAgo(1),
|
||||
},
|
||||
});
|
||||
|
||||
const res = await postDose({
|
||||
occurredAt: daysAgo(3).toISOString(),
|
||||
customVaccineId: def.id,
|
||||
});
|
||||
expect(res.status, JSON.stringify(await res.clone().json())).toBe(201);
|
||||
const dto = ((await res.json()) as { data: DoseDto }).data;
|
||||
expect(dto.customVaccine?.name).toBe("Travel combo");
|
||||
expect(dto.series).toEqual([
|
||||
expect.objectContaining({ antigen: "typhoid", position: 1, total: 2 }),
|
||||
expect.objectContaining({
|
||||
antigen: "hepatitis-a",
|
||||
position: 1,
|
||||
total: 2,
|
||||
}),
|
||||
]);
|
||||
expect(dto.reminderId).toBe(reminder.id);
|
||||
expect(
|
||||
(
|
||||
await prisma.measurementReminder.findUniqueOrThrow({
|
||||
where: { id: reminder.id },
|
||||
})
|
||||
).lastSatisfiedAt,
|
||||
).not.toBeNull();
|
||||
|
||||
// An edit to the definition is read by every dose that names it.
|
||||
expect((await editCustom(def.id, { components: ["typhoid"] })).status).toBe(
|
||||
200,
|
||||
);
|
||||
expect((await doses())[0].series.map((p) => p.antigen)).toEqual([
|
||||
"typhoid",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keys the booster mint on the definition's first antigen", async () => {
|
||||
const owner = await person("owner");
|
||||
signIn(owner);
|
||||
const def = (
|
||||
(await (await addCustom(TRAVEL)).json()) as { data: { id: string } }
|
||||
).data;
|
||||
const dose = (
|
||||
(await (
|
||||
await postDose({
|
||||
occurredAt: daysAgo(3).toISOString(),
|
||||
customVaccineId: def.id,
|
||||
})
|
||||
).json()) as { data: { id: string } }
|
||||
).data;
|
||||
|
||||
const res = await planBooster(
|
||||
json("POST", `/api/vaccinations/${dose.id}/booster`, {
|
||||
intervalMonths: 36,
|
||||
label: "Travel combo booster",
|
||||
}) as never,
|
||||
params(dose.id),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
const minted = await getPrismaClient().measurementReminder.findFirstOrThrow(
|
||||
{ where: { userId: owner.id } },
|
||||
);
|
||||
expect(minted.vaccinationAntigen).toBe("typhoid");
|
||||
});
|
||||
|
||||
it("refuses a definition another record holds", async () => {
|
||||
const stranger = await person("stranger");
|
||||
signIn(stranger);
|
||||
const foreign = (
|
||||
(await (await addCustom(TRAVEL)).json()) as { data: { id: string } }
|
||||
).data;
|
||||
|
||||
const owner = await person("owner");
|
||||
signIn(owner);
|
||||
const res = await postDose({
|
||||
occurredAt: daysAgo(3).toISOString(),
|
||||
customVaccineId: foreign.id,
|
||||
});
|
||||
expect(res.status).toBe(404);
|
||||
expect((await res.json()).meta?.errorCode).toBe(
|
||||
"vaccination.custom-vaccine-not-found",
|
||||
);
|
||||
expect((await editCustom(foreign.id, { name: "Mine" })).status).toBe(404);
|
||||
expect((await removeCustom(foreign.id)).status).toBe(404);
|
||||
expect(
|
||||
await getPrismaClient().vaccinationRecord.count({
|
||||
where: { userId: owner.id },
|
||||
}),
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it("removing a definition keeps every dose, each with a name, and the name can be used again", async () => {
|
||||
const owner = await person("owner");
|
||||
signIn(owner);
|
||||
const prisma = getPrismaClient();
|
||||
const def = (
|
||||
(await (await addCustom(TRAVEL)).json()) as { data: { id: string } }
|
||||
).data;
|
||||
await postDose({
|
||||
occurredAt: daysAgo(30).toISOString(),
|
||||
customVaccineId: def.id,
|
||||
});
|
||||
await postDose({
|
||||
occurredAt: daysAgo(3).toISOString(),
|
||||
customVaccineId: def.id,
|
||||
vaccineName: "as the pass says",
|
||||
});
|
||||
|
||||
expect((await removeCustom(def.id)).status).toBe(200);
|
||||
// Removing twice succeeds.
|
||||
expect((await removeCustom(def.id)).status).toBe(200);
|
||||
|
||||
const rows = await prisma.vaccinationRecord.findMany({
|
||||
where: { userId: owner.id, deletedAt: null },
|
||||
orderBy: { occurredAt: "asc" },
|
||||
});
|
||||
expect(rows.map((row) => [row.customVaccineId, row.vaccineName])).toEqual([
|
||||
[null, "Travel combo"],
|
||||
[null, "as the pass says"],
|
||||
]);
|
||||
expect(
|
||||
((await (await getCustoms()).json()) as { data: unknown[] }).data,
|
||||
).toEqual([]);
|
||||
const audit = await prisma.auditLog.findFirstOrThrow({
|
||||
where: { action: "vaccination.custom.delete" },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
const details =
|
||||
typeof audit.details === "string"
|
||||
? JSON.parse(audit.details)
|
||||
: audit.details;
|
||||
expect(details).toMatchObject({ dosesUnlinked: 2 });
|
||||
|
||||
// The same name again brings the definition back, without its old doses.
|
||||
const again = await addCustom({ ...TRAVEL, boosterIntervalMonths: 12 });
|
||||
expect(again.status).toBe(201);
|
||||
expect(((await again.json()) as { data: { id: string } }).data.id).toBe(
|
||||
def.id,
|
||||
);
|
||||
expect(
|
||||
await prisma.vaccinationRecord.count({
|
||||
where: { userId: owner.id, customVaccineId: def.id },
|
||||
}),
|
||||
).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sharing and managed profiles", () => {
|
||||
async function switchInAs(
|
||||
ownerId: string,
|
||||
access: "READ" | "WRITE",
|
||||
): Promise<Person> {
|
||||
const { inviteGrant, acceptGrant } = await import("@/lib/sharing/grants");
|
||||
const delegate = await person("delegate");
|
||||
const invited = await inviteGrant({
|
||||
grantorId: ownerId,
|
||||
granteeId: delegate.id,
|
||||
access,
|
||||
scope: ["profile"],
|
||||
});
|
||||
await acceptGrant({ grantId: invited.id, granteeId: delegate.id });
|
||||
signIn(delegate);
|
||||
await switchSessionTo(delegate.sessionId, ownerId);
|
||||
return delegate;
|
||||
}
|
||||
|
||||
it("lets a READ delegate list the definitions but not add one", async () => {
|
||||
const owner = await person("owner");
|
||||
await getPrismaClient().customVaccine.create({
|
||||
data: { userId: owner.id, name: "Owner's own", components: ["rabies"] },
|
||||
});
|
||||
await switchInAs(owner.id, "READ");
|
||||
|
||||
const listed = await getCustoms();
|
||||
expect(listed.status).toBe(200);
|
||||
expect(
|
||||
((await listed.json()) as { data: { name: string }[] }).data.map(
|
||||
(row) => row.name,
|
||||
),
|
||||
).toEqual(["Owner's own"]);
|
||||
|
||||
const res = await addCustom(TRAVEL);
|
||||
expect(res.status).toBe(403);
|
||||
expect((await res.json()).meta?.errorCode).toBe("sharing.access.denied");
|
||||
});
|
||||
|
||||
it("lets a WRITE delegate add onto the owner's record but not edit or remove", async () => {
|
||||
const owner = await person("owner");
|
||||
const delegate = await switchInAs(owner.id, "WRITE");
|
||||
|
||||
const res = await addCustom(TRAVEL);
|
||||
expect(res.status).toBe(201);
|
||||
const def = ((await res.json()) as { data: { id: string } }).data;
|
||||
const prisma = getPrismaClient();
|
||||
expect(
|
||||
(await prisma.customVaccine.findUniqueOrThrow({ where: { id: def.id } }))
|
||||
.userId,
|
||||
).toBe(owner.id);
|
||||
expect(
|
||||
await prisma.customVaccine.count({ where: { userId: delegate.id } }),
|
||||
).toBe(0);
|
||||
|
||||
expect((await editCustom(def.id, { name: "Renamed" })).status).toBe(403);
|
||||
expect((await removeCustom(def.id)).status).toBe(403);
|
||||
});
|
||||
|
||||
it("writes a Guardian's definition to the managed profile", async () => {
|
||||
const { createManagedProfile } =
|
||||
await import("@/lib/managed-profiles/create");
|
||||
const guardian = await person("guardian");
|
||||
const { profile } = await createManagedProfile({
|
||||
creatorId: guardian.id,
|
||||
displayName: "Child record",
|
||||
dateOfBirth: null,
|
||||
locale: "en",
|
||||
timezone: "Europe/Berlin",
|
||||
});
|
||||
signIn(guardian);
|
||||
await switchSessionTo(guardian.sessionId, profile.id);
|
||||
|
||||
expect((await addCustom(TRAVEL)).status).toBe(201);
|
||||
const prisma = getPrismaClient();
|
||||
expect(
|
||||
await prisma.customVaccine.count({ where: { userId: profile.id } }),
|
||||
).toBe(1);
|
||||
expect(
|
||||
await prisma.customVaccine.count({ where: { userId: guardian.id } }),
|
||||
).toBe(0);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user