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:
Marc-André Bombeck committed 2026-10-03 21:38:03 +02:00
1 parent 350c646463
commit 4cb8118802
55 files changed
+3201 -187

No files matched your search

@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({
// through it is proven in tests/integration/backup-round-trip.test.ts.
vi.mock("@/lib/medication-category", () => ({
getMedicationCategories: vi.fn(async () => ({})),
readMedicationCategoryLabelsForBackup: vi.fn(async () => []),
setMedicationCategory: vi.fn(async () => "OTHER"),
}));
vi.mock("@/lib/export/paged-measurements", () => ({
@@ -35,6 +35,9 @@ const mocks = vi.hoisted(() => ({
// through it is proven in tests/integration/backup-round-trip.test.ts.
vi.mock("@/lib/medication-category", () => ({
getMedicationCategories: vi.fn(async () => ({})),
readMedicationCategoryLabelsForBackup: vi.fn(async () => []),
encryptCategoryLabel: vi.fn(() => new Uint8Array()),
mintCustomMedicationCategoryKey: vi.fn(() => "custom:minted"),
setMedicationCategory: vi.fn(async () => "OTHER"),
}));
vi.mock("@/lib/db", () => ({
+4
View File
@@ -83,6 +83,9 @@ export const BACKED_UP_MODELS = [
// formats and is written back in the restore transaction. Without it every
// restored medication reads as Other.
"MedicationCategoryAssignment",
// The categories the person named themselves (v1.40, #1041). A medication
// filed under one carries its key; without the row the key reads as Other.
"MedicationCategoryLabel",
// ── Mood ──────────────────────────────────────────────────────────────────
"MoodEntry",
@@ -310,6 +313,7 @@ export const TWO_ENDED_MODELS = [
"MedicationPauseEra",
"MedicationDoseChange",
"MedicationCategoryAssignment",
"MedicationCategoryLabel",
"MoodEntry",
"MoodContext",
"MoodEntryTagLink",
+11 -1
View File
@@ -122,7 +122,10 @@ import {
buildAccountSettingsBackupSection,
type AccountSettingsBackupSection,
} from "@/lib/export/account-settings-backup";
import { getMedicationCategories } from "@/lib/medication-category";
import {
getMedicationCategories,
readMedicationCategoryLabelsForBackup,
} from "@/lib/medication-category";
export interface FullBackupCounts
extends
@@ -970,6 +973,12 @@ export async function buildFullBackupPayload(
medications.map((m) => m.id),
prisma,
);
// v1.40 (#1041) — the account's own categories, restored before the
// medications that name them by key. Labels travel decrypted so a file
// restores on an instance with a different key; every one is carried,
// hidden ones included, because a medication can still be filed under it.
const customMedicationCategories =
await readMedicationCategoryLabelsForBackup(userId, prisma);
// Where each archived era sits in its OWN drug's ordered list. Built once
// here rather than per row, and scoped per medication because the supersede
@@ -1001,6 +1010,7 @@ export async function buildFullBackupPayload(
: null,
...accountSettingsSection,
measurements: bulk.measurements,
customMedicationCategories,
medications: medications.map((m) => ({
...(disasterRecovery
? {
+38 -2
View File
@@ -107,7 +107,11 @@ import { restoreAwardsData } from "@/lib/export/awards-backup";
import { restoreEnvironmentData } from "@/lib/export/environment-backup";
import { restoreEcgData } from "@/lib/export/ecg-backup";
import { restoredMedicationCreatedAt } from "@/lib/export/medication-created-at";
import { setMedicationCategory } from "@/lib/medication-category";
import {
encryptCategoryLabel,
mintCustomMedicationCategoryKey,
setMedicationCategory,
} from "@/lib/medication-category";
import { invalidateUserData } from "@/lib/cache/invalidate";
import { TOMBSTONE_RETENTION_DAYS } from "@/lib/auth/native-client";
import { stampSyncReset } from "@/lib/sync/reset";
@@ -1049,6 +1053,34 @@ export async function restoreBackup(
// is where an operator has to go to see what the position meant, and
// an id would be one the restore never wrote.
const unresolvedRevisionLinks: string[] = [];
// v1.40 (#1041) — the account's own medication categories, before
// the medications that name them by key. Delete-then-recreate like
// the medications themselves. A key held by another account on this
// instance (a portable file from elsewhere) is re-minted, and the
// medications below are mapped onto the new key.
await tx.medicationCategoryLabel.deleteMany({
where: { userId: ownerId },
});
const categoryKeyRemap = new Map<string, string>();
for (const c of payload.customMedicationCategories) {
const taken = await tx.medicationCategoryLabel.findUnique({
where: { key: c.key },
select: { id: true },
});
const key = taken ? mintCustomMedicationCategoryKey() : c.key;
if (key !== c.key) categoryKeyRemap.set(c.key, key);
await tx.medicationCategoryLabel.create({
data: {
userId: ownerId,
key,
labelEncrypted: encryptCategoryLabel(c.label),
sortOrder: c.sortOrder,
isActive: c.isActive,
...(c.createdAt ? { createdAt: new Date(c.createdAt) } : {}),
},
});
}
let medicationIndex = 0;
reportSection("medications");
const restoreStartedAt = new Date();
@@ -1262,7 +1294,11 @@ export async function restoreBackup(
// medication id, so it is written after the row exists and inside the
// same transaction. OTHER is what a missing row already reads as.
if (m.category && m.category !== "OTHER") {
await setMedicationCategory(created.id, m.category, tx);
await setMedicationCategory(
created.id,
categoryKeyRemap.get(m.category) ?? m.category,
tx,
);
}
// ── The archived schedule eras, in two passes ────────────────