mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
Let a person name their own medication categories
A medication can be filed under a category the person named, next to the built-in ones (#1041). The labels live in medication_category_labels, encrypted at rest, capped at 20 per account; a medication filed under one carries its custom:<uuid> key in the category column. - GET/POST /api/medications/categories (POST idempotent, 30/min per actor, admitted at MANAGE like the cycle symptom vocabulary) and owner-only PATCH/DELETE /api/medications/categories/{key}. DELETE moves every medication filed under the category to OTHER in the same transaction and answers movedCount. - category is widened to a built-in value or custom:<uuid> on the wire, the create and update bodies refuse a key that is not the caller's (422 medications.category.unknown), and list, detail, the insights medication tiles and the MCP medications resource carry categoryLabel. A key with no owned label reads as OTHER and is counted on the event. - The wizard's class step lists the person's categories under the built-in rows with an inline add row; the list page gains a category filter (session only) and a manage sheet for rename, hide and delete. - Backup carries customMedicationCategories (decrypted labels) and the restore writes them before the medications; wipe plan, encrypted column registry, rotation script, sharing guards and OpenAPI follow.
This commit is contained in:
1 parent
350c646463
commit
4cb8118802
55 files changed
+3201
-187
No files matched your search
+8
@@ -681,6 +681,14 @@ export const ADMITTED_MUTATING_HANDLERS = [
|
||||
"manage",
|
||||
"create",
|
||||
),
|
||||
handler(
|
||||
"app/api/medications/categories/route.ts",
|
||||
"/api/medications/categories",
|
||||
"POST",
|
||||
"medications",
|
||||
"manage",
|
||||
"create",
|
||||
),
|
||||
handler(
|
||||
"app/api/nutrients/water/route.ts",
|
||||
"/api/nutrients/water",
|
||||
|
||||
@@ -66,7 +66,7 @@ import {
|
||||
} from "@/lib/withings/ecg-waveform-codec";
|
||||
import { buildFullBackupPayload } from "@/lib/export/full-backup-payload";
|
||||
import {
|
||||
getMedicationCategories,
|
||||
resolveMedicationCategories,
|
||||
setMedicationCategory,
|
||||
} from "@/lib/medication-category";
|
||||
import { UNREADABLE_EXPORT_MARKER } from "@/lib/export/unreadable-marker";
|
||||
@@ -188,6 +188,7 @@ const COACH_RESULTS_JSON = JSON.stringify([
|
||||
chart: { kind: "line", x: "period", series: ["sys"] },
|
||||
},
|
||||
]);
|
||||
const ROUND_TRIP_CATEGORY_KEY = "custom:5f0c6a52-6a43-4f63-9b39-0c1f4d7e2a10";
|
||||
const DOSE_CHANGE_NOTE = "titration note, encrypted at rest";
|
||||
const EXTRACTED_FACT_SPAN = "Ferritin 91 ng/mL (30 - 400)";
|
||||
const SIDE_EFFECT_NOTE = "nausea for two hours after the evening dose";
|
||||
@@ -223,6 +224,8 @@ const COUNT_BACK: Record<
|
||||
// No own `userId` column — reached through the drug, like the schedules.
|
||||
MedicationCategoryAssignment: (p, userId) =>
|
||||
p.medicationCategoryAssignment.count({ where: { medication: { userId } } }),
|
||||
MedicationCategoryLabel: (p, userId) =>
|
||||
p.medicationCategoryLabel.count({ where: { userId } }),
|
||||
MoodEntry: (p, userId) => p.moodEntry.count({ where: { userId } }),
|
||||
MoodContext: (p, userId) => p.moodContext.count({ where: { userId } }),
|
||||
MoodEntryTagLink: (p, userId) =>
|
||||
@@ -427,9 +430,18 @@ async function seedEveryTwoEndedModel(prisma: PrismaClient): Promise<void> {
|
||||
},
|
||||
});
|
||||
// Not OTHER: a missing row already reads as OTHER, so only a chosen value
|
||||
// proves the category came back.
|
||||
// proves the category came back. A category the person named, so the
|
||||
// assignment can only resolve if the label came back before it.
|
||||
await prisma.medicationCategoryLabel.create({
|
||||
data: {
|
||||
userId: OWNER_ID,
|
||||
key: ROUND_TRIP_CATEGORY_KEY,
|
||||
labelEncrypted: encryptToBytes("Heart and circulation"),
|
||||
sortOrder: 2,
|
||||
},
|
||||
});
|
||||
await prisma.medicationCategoryAssignment.create({
|
||||
data: { medicationId: medication.id, category: "THYROID" },
|
||||
data: { medicationId: medication.id, category: ROUND_TRIP_CATEGORY_KEY },
|
||||
});
|
||||
// The one row in this fixture that is also checked field by field after the
|
||||
// restore — see the assertion at the end of the test for why.
|
||||
@@ -2809,8 +2821,22 @@ describe("every model the plan claims two-ended survives a real restore", () =>
|
||||
await prisma.medication.create({
|
||||
data: { userId: OWNER_ID, name: "Unfiled", dose: "1 tab" },
|
||||
});
|
||||
const travel = await prisma.medication.create({
|
||||
data: { userId: OWNER_ID, name: "Tamiflu", dose: "75 mg" },
|
||||
});
|
||||
await setMedicationCategory(thyroid.id, "THYROID");
|
||||
await setMedicationCategory(mood.id, "MENTAL_HEALTH");
|
||||
// v1.40 — a category the person named. Hidden, because a hidden
|
||||
// category still files the medication and must travel with it.
|
||||
await prisma.medicationCategoryLabel.create({
|
||||
data: {
|
||||
userId: OWNER_ID,
|
||||
key: ROUND_TRIP_CATEGORY_KEY,
|
||||
labelEncrypted: encryptToBytes("Travel kit"),
|
||||
isActive: false,
|
||||
},
|
||||
});
|
||||
await setMedicationCategory(travel.id, ROUND_TRIP_CATEGORY_KEY);
|
||||
|
||||
const { payload } = await buildFullBackupPayload(prisma, OWNER_ID, {
|
||||
purpose,
|
||||
@@ -2824,7 +2850,17 @@ describe("every model the plan claims two-ended survives a real restore", () =>
|
||||
Levothyroxine: "THYROID",
|
||||
Sertraline: "MENTAL_HEALTH",
|
||||
Unfiled: "OTHER",
|
||||
Tamiflu: ROUND_TRIP_CATEGORY_KEY,
|
||||
});
|
||||
expect(payload.customMedicationCategories).toEqual([
|
||||
{
|
||||
key: ROUND_TRIP_CATEGORY_KEY,
|
||||
label: "Travel kit",
|
||||
sortOrder: 0,
|
||||
isActive: false,
|
||||
createdAt: expect.any(String),
|
||||
},
|
||||
]);
|
||||
|
||||
await prisma.user.delete({ where: { id: OWNER_ID } });
|
||||
await createOwner(prisma);
|
||||
@@ -2849,16 +2885,24 @@ describe("every model the plan claims two-ended survives a real restore", () =>
|
||||
where: { userId: OWNER_ID },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
const categories = await getMedicationCategories(
|
||||
const categories = await resolveMedicationCategories(
|
||||
restored.map((m) => m.id),
|
||||
);
|
||||
expect(
|
||||
Object.fromEntries(restored.map((m) => [m.name, categories[m.id]])),
|
||||
).toEqual({
|
||||
Levothyroxine: "THYROID",
|
||||
Sertraline: "MENTAL_HEALTH",
|
||||
Unfiled: "OTHER",
|
||||
Levothyroxine: { category: "THYROID", categoryLabel: null },
|
||||
Sertraline: { category: "MENTAL_HEALTH", categoryLabel: null },
|
||||
Unfiled: { category: "OTHER", categoryLabel: null },
|
||||
Tamiflu: {
|
||||
category: ROUND_TRIP_CATEGORY_KEY,
|
||||
categoryLabel: "Travel kit",
|
||||
},
|
||||
});
|
||||
const label = await prisma.medicationCategoryLabel.findUniqueOrThrow({
|
||||
where: { key: ROUND_TRIP_CATEGORY_KEY },
|
||||
});
|
||||
expect(label.isActive).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* Custom medication categories (#1041) against a real Postgres, through the
|
||||
* shipped route exports.
|
||||
*
|
||||
* What the file pins:
|
||||
* - a category is created, listed with its medication count, renamed and
|
||||
* hidden through its own routes, and capped at twenty per account;
|
||||
* - a medication can be filed under one of the caller's own categories and
|
||||
* the list and detail reads publish the decrypted label beside the key;
|
||||
* - another account's key is refused (422 `medications.category.unknown`)
|
||||
* on create and on update, and never resolves on a read;
|
||||
* - deleting a category moves its medications to OTHER in the same
|
||||
* transaction, so no medication is left pointing at a key that is gone;
|
||||
* - a key left behind anyway (written past the routes) reads as OTHER.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { cookieJar, headerJar } from "./mock-next-headers";
|
||||
import { getPrismaClient, truncateAllTables } from "./setup";
|
||||
|
||||
const OWNER = "user-med-categories";
|
||||
const OTHER_USER = "user-med-categories-other";
|
||||
|
||||
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),
|
||||
}));
|
||||
|
||||
async function signIn(userId: string) {
|
||||
const session = await getPrismaClient().session.create({
|
||||
data: { userId, expiresAt: new Date(Date.now() + 60 * 60 * 1000) },
|
||||
});
|
||||
cookieJar.set("healthlog_session", session.id);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
const prisma = getPrismaClient();
|
||||
await truncateAllTables(prisma);
|
||||
cookieJar.clear();
|
||||
headerJar.clear();
|
||||
for (const id of [OWNER, OTHER_USER]) {
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id,
|
||||
username: id,
|
||||
email: `${id}@example.test`,
|
||||
timezone: "UTC",
|
||||
},
|
||||
});
|
||||
}
|
||||
await signIn(OWNER);
|
||||
});
|
||||
|
||||
function req(method: string, path: string, body?: unknown) {
|
||||
return new NextRequest(`http://localhost${path}`, {
|
||||
method,
|
||||
headers: { "content-type": "application/json" },
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
}
|
||||
|
||||
async function createCategory(label: string): Promise<string> {
|
||||
const { POST } = await import("@/app/api/medications/categories/route");
|
||||
const res = await POST(req("POST", "/api/medications/categories", { label }));
|
||||
const body = await res.json();
|
||||
expect(res.status, JSON.stringify(body)).toBe(201);
|
||||
return body.data.key as string;
|
||||
}
|
||||
|
||||
async function createMedication(category?: string) {
|
||||
const { POST } = await import("@/app/api/medications/route");
|
||||
return POST(
|
||||
req("POST", "/api/medications", {
|
||||
name: "Tamiflu",
|
||||
dose: "75 mg",
|
||||
...(category ? { category } : {}),
|
||||
schedules: [{ windowStart: "08:00", windowEnd: "09:00" }],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
describe("custom medication categories", () => {
|
||||
it("files a medication under an own category and publishes its label", async () => {
|
||||
const key = await createCategory(" Travel kit ");
|
||||
expect(key).toMatch(/^custom:[0-9a-f-]{36}$/);
|
||||
|
||||
const created = await createMedication(key);
|
||||
const createdBody = await created.json();
|
||||
expect(created.status, JSON.stringify(createdBody)).toBe(201);
|
||||
expect(createdBody.data.category).toBe(key);
|
||||
expect(createdBody.data.categoryLabel).toBe("Travel kit");
|
||||
|
||||
const { GET: list } = await import("@/app/api/medications/route");
|
||||
const listBody = await (await list()).json();
|
||||
expect(listBody.data[0]).toMatchObject({
|
||||
category: key,
|
||||
categoryLabel: "Travel kit",
|
||||
});
|
||||
|
||||
const { GET: detail } = await import("@/app/api/medications/[id]/route");
|
||||
const detailBody = await (
|
||||
await detail(req("GET", `/api/medications/${createdBody.data.id}`), {
|
||||
params: Promise.resolve({ id: createdBody.data.id }),
|
||||
})
|
||||
).json();
|
||||
expect(detailBody.data).toMatchObject({
|
||||
category: key,
|
||||
categoryLabel: "Travel kit",
|
||||
});
|
||||
|
||||
const { GET: categories } =
|
||||
await import("@/app/api/medications/categories/route");
|
||||
const categoriesBody = await (await categories()).json();
|
||||
expect(categoriesBody.data.categories).toEqual([
|
||||
{
|
||||
key,
|
||||
label: "Travel kit",
|
||||
sortOrder: 0,
|
||||
isActive: true,
|
||||
medicationCount: 1,
|
||||
},
|
||||
]);
|
||||
|
||||
// The label is ciphertext at rest.
|
||||
const row =
|
||||
await getPrismaClient().medicationCategoryLabel.findUniqueOrThrow({
|
||||
where: { key },
|
||||
});
|
||||
expect(Buffer.from(row.labelEncrypted).toString("utf8")).not.toContain(
|
||||
"Travel kit",
|
||||
);
|
||||
});
|
||||
|
||||
it("refuses another account's key on create and on update", async () => {
|
||||
await signIn(OTHER_USER);
|
||||
const foreignKey = await createCategory("Theirs");
|
||||
await signIn(OWNER);
|
||||
|
||||
const refused = await createMedication(foreignKey);
|
||||
const refusedBody = await refused.json();
|
||||
expect(refused.status).toBe(422);
|
||||
expect(refusedBody.meta.errorCode).toBe("medications.category.unknown");
|
||||
expect(await getPrismaClient().medication.count()).toBe(0);
|
||||
|
||||
const ok = await createMedication("VITAMIN");
|
||||
const okBody = await ok.json();
|
||||
const { PUT } = await import("@/app/api/medications/[id]/route");
|
||||
const updated = await PUT(
|
||||
req("PUT", `/api/medications/${okBody.data.id}`, {
|
||||
category: foreignKey,
|
||||
}),
|
||||
{ params: Promise.resolve({ id: okBody.data.id }) },
|
||||
);
|
||||
expect(updated.status).toBe(422);
|
||||
expect((await updated.json()).meta.errorCode).toBe(
|
||||
"medications.category.unknown",
|
||||
);
|
||||
const assignment =
|
||||
await getPrismaClient().medicationCategoryAssignment.findUniqueOrThrow({
|
||||
where: { medicationId: okBody.data.id },
|
||||
});
|
||||
expect(assignment.category).toBe("VITAMIN");
|
||||
});
|
||||
|
||||
it("keeps the category on an update that does not name it", async () => {
|
||||
const key = await createCategory("Heart");
|
||||
const created = await (await createMedication(key)).json();
|
||||
const { PUT } = await import("@/app/api/medications/[id]/route");
|
||||
const res = await PUT(
|
||||
req("PUT", `/api/medications/${created.data.id}`, { name: "Renamed" }),
|
||||
{ params: Promise.resolve({ id: created.data.id }) },
|
||||
);
|
||||
const body = await res.json();
|
||||
expect(res.status, JSON.stringify(body)).toBe(200);
|
||||
expect(body.data).toMatchObject({ category: key, categoryLabel: "Heart" });
|
||||
});
|
||||
|
||||
it("renames, hides and caps", async () => {
|
||||
const key = await createCategory("Heart");
|
||||
const { PATCH } =
|
||||
await import("@/app/api/medications/categories/[key]/route");
|
||||
const res = await PATCH(
|
||||
req("PATCH", `/api/medications/categories/${key}`, {
|
||||
label: "Heart and vessels",
|
||||
isActive: false,
|
||||
sortOrder: 4,
|
||||
}),
|
||||
{ params: Promise.resolve({ key }) },
|
||||
);
|
||||
expect(await res.json()).toMatchObject({
|
||||
data: {
|
||||
key,
|
||||
label: "Heart and vessels",
|
||||
isActive: false,
|
||||
sortOrder: 4,
|
||||
medicationCount: 0,
|
||||
},
|
||||
});
|
||||
|
||||
// Hidden ones count toward the cap: nineteen more fill it.
|
||||
for (let i = 0; i < 19; i += 1) await createCategory(`Group ${i}`);
|
||||
const { POST } = await import("@/app/api/medications/categories/route");
|
||||
const over = await POST(
|
||||
req("POST", "/api/medications/categories", { label: "One too many" }),
|
||||
);
|
||||
expect(over.status).toBe(422);
|
||||
expect((await over.json()).meta.errorCode).toBe(
|
||||
"medications.category.limitReached",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not let one account rename or delete another's category", async () => {
|
||||
await signIn(OTHER_USER);
|
||||
const foreignKey = await createCategory("Theirs");
|
||||
await signIn(OWNER);
|
||||
const { PATCH, DELETE } =
|
||||
await import("@/app/api/medications/categories/[key]/route");
|
||||
const patched = await PATCH(
|
||||
req("PATCH", `/api/medications/categories/${foreignKey}`, {
|
||||
label: "Mine now",
|
||||
}),
|
||||
{ params: Promise.resolve({ key: foreignKey }) },
|
||||
);
|
||||
expect(patched.status).toBe(404);
|
||||
const deleted = await DELETE(
|
||||
req("DELETE", `/api/medications/categories/${foreignKey}`),
|
||||
{ params: Promise.resolve({ key: foreignKey }) },
|
||||
);
|
||||
expect(deleted.status).toBe(404);
|
||||
expect(
|
||||
await getPrismaClient().medicationCategoryLabel.count({
|
||||
where: { key: foreignKey },
|
||||
}),
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it("moves the medications of a deleted category to OTHER", async () => {
|
||||
const key = await createCategory("Short courses");
|
||||
const first = await (await createMedication(key)).json();
|
||||
const second = await (await createMedication(key)).json();
|
||||
const untouched = await (await createMedication("THYROID")).json();
|
||||
|
||||
const { DELETE } =
|
||||
await import("@/app/api/medications/categories/[key]/route");
|
||||
const res = await DELETE(
|
||||
req("DELETE", `/api/medications/categories/${key}`),
|
||||
{ params: Promise.resolve({ key }) },
|
||||
);
|
||||
expect(await res.json()).toEqual({
|
||||
data: { key, movedCount: 2 },
|
||||
error: null,
|
||||
});
|
||||
|
||||
const rows = await getPrismaClient().medicationCategoryAssignment.findMany({
|
||||
orderBy: { medicationId: "asc" },
|
||||
});
|
||||
const byId = Object.fromEntries(
|
||||
rows.map((r) => [r.medicationId, r.category]),
|
||||
);
|
||||
// The stored value itself, not what a read resolves it to: a dangling key
|
||||
// would also READ as OTHER, which is exactly what this must not rely on.
|
||||
expect(byId[first.data.id]).toBe("OTHER");
|
||||
expect(byId[second.data.id]).toBe("OTHER");
|
||||
expect(byId[untouched.data.id]).toBe("THYROID");
|
||||
expect(rows.filter((r) => r.category.startsWith("custom:"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("reads a key with no label as OTHER", async () => {
|
||||
const created = await (await createMedication("VITAMIN")).json();
|
||||
await getPrismaClient().medicationCategoryAssignment.update({
|
||||
where: { medicationId: created.data.id },
|
||||
data: { category: "custom:00000000-0000-4000-8000-000000000000" },
|
||||
});
|
||||
const { GET } = await import("@/app/api/medications/[id]/route");
|
||||
const body = await (
|
||||
await GET(req("GET", `/api/medications/${created.data.id}`), {
|
||||
params: Promise.resolve({ id: created.data.id }),
|
||||
})
|
||||
).json();
|
||||
expect(body.data).toMatchObject({ category: "OTHER", categoryLabel: null });
|
||||
});
|
||||
});
|
||||
@@ -281,7 +281,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(77);
|
||||
expect(ADMITTED_MUTATING_HANDLERS.length).toBe(78);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2250,6 +2250,18 @@ proveManageRoute("POST /api/cycle/symptoms/custom", {
|
||||
})) === 1,
|
||||
});
|
||||
|
||||
proveManageRoute("POST /api/medications/categories", {
|
||||
route: "/api/medications/categories",
|
||||
prepare: async (ownerId) => ({ ownerId }),
|
||||
body: () => ({ label: "Travel kit" }),
|
||||
ok: 201,
|
||||
auditAction: "medication.category.custom.create",
|
||||
applied: async ({ ownerId }) =>
|
||||
(await getPrismaClient().medicationCategoryLabel.count({
|
||||
where: { userId: ownerId },
|
||||
})) === 1,
|
||||
});
|
||||
|
||||
proveManageRoute("POST /api/nutrients/water", {
|
||||
route: "/api/nutrients/water",
|
||||
prepare: async (ownerId) => {
|
||||
@@ -2580,13 +2592,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(77);
|
||||
expect(STRICT_DRIVER_KEYS.size).toBe(78);
|
||||
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(77);
|
||||
expect(REAL_EFFECT_KEYS.size).toBe(78);
|
||||
expect([...REAL_EFFECT_KEYS].sort()).toEqual(expected);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user