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

@@ -0,0 +1,179 @@
/**
* v1.40 (#1041) — the one helper that resolves and writes a medication's
* category. Prisma is stubbed; the real-database contract lives in
* `tests/integration/medication-custom-categories.test.ts`.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
assignmentFindMany: vi.fn(),
assignmentUpsert: vi.fn(),
assignmentUpdateMany: vi.fn(),
labelFindMany: vi.fn(),
labelFindFirst: vi.fn(),
labelDelete: vi.fn(),
medicationFindUnique: vi.fn(),
annotate: vi.fn(),
order: [] as string[],
}));
vi.mock("@/lib/db", () => {
const client = {
medicationCategoryAssignment: {
findMany: mocks.assignmentFindMany,
upsert: mocks.assignmentUpsert,
updateMany: mocks.assignmentUpdateMany,
},
medicationCategoryLabel: {
findMany: mocks.labelFindMany,
findFirst: mocks.labelFindFirst,
delete: mocks.labelDelete,
},
medication: { findUnique: mocks.medicationFindUnique },
};
return {
prisma: {
...client,
$transaction: async (fn: (tx: typeof client) => unknown) => fn(client),
},
};
});
vi.mock("@/lib/logging/context", () => ({ annotate: mocks.annotate }));
vi.mock("@/lib/ai/coach/bytes-codec", () => ({
encryptToBytes: (s: string) => new TextEncoder().encode(`sealed:${s}`),
decryptFromBytes: (b: Uint8Array) =>
new TextDecoder().decode(b).replace(/^sealed:/, ""),
}));
import {
deleteMedicationCategoryLabel,
isAssignableCategory,
resolveMedicationCategories,
setMedicationCategory,
} from "@/lib/medication-category";
const OWN = "custom:11111111-1111-4111-8111-111111111111";
const FOREIGN = "custom:22222222-2222-4222-8222-222222222222";
const GONE = "custom:33333333-3333-4333-8333-333333333333";
const sealed = (s: string) => new TextEncoder().encode(`sealed:${s}`);
beforeEach(() => {
vi.clearAllMocks();
mocks.order.length = 0;
});
describe("resolveMedicationCategories", () => {
it("resolves built-ins, the owner's own key with its label, and nothing else", async () => {
mocks.assignmentFindMany.mockResolvedValue([
{ medicationId: "m1", category: "THYROID", medication: { userId: "u1" } },
{ medicationId: "m2", category: OWN, medication: { userId: "u1" } },
{ medicationId: "m3", category: FOREIGN, medication: { userId: "u1" } },
{ medicationId: "m4", category: GONE, medication: { userId: "u1" } },
{
medicationId: "m5",
category: "NOT_A_VALUE",
medication: { userId: "u1" },
},
]);
mocks.labelFindMany.mockResolvedValue([
{ key: OWN, userId: "u1", labelEncrypted: sealed("Travel kit") },
{ key: FOREIGN, userId: "u2", labelEncrypted: sealed("Theirs") },
]);
const result = await resolveMedicationCategories([
"m1",
"m2",
"m3",
"m4",
"m5",
"m6",
]);
expect(result).toEqual({
m1: { category: "THYROID", categoryLabel: null },
m2: { category: OWN, categoryLabel: "Travel kit" },
// Another account's label never resolves, even by its exact key.
m3: { category: "OTHER", categoryLabel: null },
m4: { category: "OTHER", categoryLabel: null },
m5: { category: "OTHER", categoryLabel: null },
// No row at all reads as OTHER.
m6: { category: "OTHER", categoryLabel: null },
});
// The two custom keys that resolved to nothing are counted, not thrown.
expect(mocks.annotate).toHaveBeenCalledWith({
meta: { "medication.category.dangling": 2 },
});
});
it("skips the label read when no custom key is in play", async () => {
mocks.assignmentFindMany.mockResolvedValue([
{ medicationId: "m1", category: "VITAMIN", medication: { userId: "u1" } },
]);
await resolveMedicationCategories(["m1"]);
expect(mocks.labelFindMany).not.toHaveBeenCalled();
expect(mocks.annotate).not.toHaveBeenCalled();
});
});
describe("isAssignableCategory / setMedicationCategory", () => {
it("admits built-ins and the owner's own key only", async () => {
mocks.labelFindFirst.mockImplementation(
async ({ where }: { where: { key: string; userId: string } }) =>
where.key === OWN && where.userId === "u1" ? { key: OWN } : null,
);
expect(await isAssignableCategory("u1", "MENTAL_HEALTH")).toBe(true);
expect(await isAssignableCategory("u1", OWN)).toBe(true);
expect(await isAssignableCategory("u1", FOREIGN)).toBe(false);
expect(await isAssignableCategory("u1", "custom")).toBe(false);
expect(await isAssignableCategory("u1", "PIZZA")).toBe(false);
});
it("writes OTHER for a key the medication's owner does not hold", async () => {
mocks.medicationFindUnique.mockResolvedValue({ userId: "u1" });
mocks.labelFindFirst.mockResolvedValue(null);
const written = await setMedicationCategory("m1", FOREIGN);
expect(written).toBe("OTHER");
expect(mocks.assignmentUpsert).toHaveBeenCalledWith(
expect.objectContaining({
create: { medicationId: "m1", category: "OTHER" },
update: { category: "OTHER" },
}),
);
});
it("writes the owner's own key", async () => {
mocks.medicationFindUnique.mockResolvedValue({ userId: "u1" });
mocks.labelFindFirst.mockResolvedValue({ key: OWN });
expect(await setMedicationCategory("m1", OWN)).toBe(OWN);
});
});
describe("deleteMedicationCategoryLabel", () => {
it("moves the category's medications to OTHER before the label goes", async () => {
mocks.labelFindFirst.mockResolvedValue({ id: "label-1" });
mocks.assignmentUpdateMany.mockImplementation(async () => {
mocks.order.push("move");
return { count: 3 };
});
mocks.labelDelete.mockImplementation(async () => {
mocks.order.push("delete");
return {};
});
const result = await deleteMedicationCategoryLabel("u1", OWN);
expect(result).toEqual({ movedCount: 3 });
expect(mocks.assignmentUpdateMany).toHaveBeenCalledWith({
where: { category: OWN, medication: { userId: "u1" } },
data: { category: "OTHER" },
});
expect(mocks.order).toEqual(["move", "delete"]);
});
it("answers null and touches nothing for a key that is not the caller's", async () => {
mocks.labelFindFirst.mockResolvedValue(null);
expect(await deleteMedicationCategoryLabel("u1", FOREIGN)).toBeNull();
expect(mocks.assignmentUpdateMany).not.toHaveBeenCalled();
expect(mocks.labelDelete).not.toHaveBeenCalled();
});
});
+2 -1
View File
@@ -210,10 +210,11 @@ export const ENCRYPTED_COLUMNS: readonly EncryptedColumn[] = [
kind: "string",
},
// ───── Custom labels (mood + cycle) ─────
// ───── Custom labels (mood, cycle, medication categories) ─────
{ model: "MoodTag", field: "labelEncrypted", kind: "string" },
{ model: "MoodTagCategory", field: "labelEncrypted", kind: "string" },
{ model: "CycleSymptom", field: "labelEncrypted", kind: "string" },
{ model: "MedicationCategoryLabel", field: "labelEncrypted", kind: "bytes" },
// ───── Notification + push secrets ─────
{ model: "NotificationChannel", field: "config", kind: "string" },
+3
View File
@@ -73,6 +73,9 @@ export const WIPE_MODELS = [
"MedicationInventoryItem",
"MedicationIntakeImportJob",
"MedicationComplianceRollup",
// The account's own category names (v1.40, #1041). No child rows; the
// medications that name one go with their own entry.
"MedicationCategoryLabel",
// ── Mood ────────────────────────────────────────────────────────────────
// The day context, before the entry it hangs off: it cascades either way,
@@ -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 ────────────────
+19
View File
@@ -10,6 +10,9 @@ vi.mock("@/lib/db", () => ({
},
}));
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
vi.mock("@/lib/medication-category", () => ({
resolveMedicationCategories: vi.fn(),
}));
vi.mock("@/lib/doctor-report-data", () => ({
collectDoctorReportData: vi.fn(),
}));
@@ -27,6 +30,7 @@ import { prisma } from "@/lib/db";
import { collectDoctorReportData } from "@/lib/doctor-report-data";
import { buildCoachDataInventory } from "@/lib/ai/coach/tools/inventory";
import { metricStatusDiscoveryRows } from "@/lib/mcp/rich-reads";
import { resolveMedicationCategories } from "@/lib/medication-category";
import type { McpAuthContext } from "../auth";
const CTX: McpAuthContext = {
@@ -104,8 +108,15 @@ describe("healthlog://profile", () => {
describe("healthlog://medications", () => {
it("lists medications + schedules scoped to the session user", async () => {
vi.mocked(resolveMedicationCategories).mockResolvedValue({
"med-a": {
category: "custom:5f0c6a52-6a43-4f63-9b39-0c1f4d7e2a10",
categoryLabel: "Travel kit",
},
});
vi.mocked(prisma.medication.findMany).mockResolvedValue([
{
id: "med-a",
name: "Med A",
dose: "10mg",
treatmentClass: "GENERIC",
@@ -139,6 +150,14 @@ describe("healthlog://medications", () => {
expect(result.present).toBe(true);
expect(result.count).toBe(1);
expect(Array.isArray(result.medications)).toBe(true);
// v1.40 (#1041) — the custom category rides with its label, fenced as
// the person's own text.
expect(
(result.medications as Array<Record<string, unknown>>)[0],
).toMatchObject({
category: "custom:5f0c6a52-6a43-4f63-9b39-0c1f4d7e2a10",
categoryLabel: "<<<USER_TEXT_START>>>Travel kit<<<USER_TEXT_END>>>",
});
});
it("returns { present: false } when no medications are tracked", async () => {
+15
View File
@@ -26,6 +26,8 @@
* external-assistant boundary.
*/
import { prisma } from "@/lib/db";
import { fenceUserText } from "@/lib/ai/coach/data-fence";
import { resolveMedicationCategories } from "@/lib/medication-category";
import { annotate } from "@/lib/logging/context";
import { executeCoachTool } from "@/lib/ai/coach/tools/executor";
import { buildCoachDataInventory } from "@/lib/ai/coach/tools/inventory";
@@ -130,6 +132,11 @@ function ageYears(dateOfBirth: Date | null): number | null {
*/
const MODULE_DISABLED = { present: false, reason: "module_disabled" } as const;
/** A person-written label, fenced as user text; null stays null. */
function fenceOptional(text: string | null | undefined): string | null {
return text ? fenceUserText(text) : null;
}
function firstVar(value: string | string[] | undefined): string {
if (Array.isArray(value)) return value[0] ?? "";
return value ?? "";
@@ -193,6 +200,9 @@ export const MCP_RESOURCES: McpResourceDefinition[] = [
meta: { resource: "medications", present: medications.length > 0 },
});
if (medications.length === 0) return { present: false, count: 0 };
const categories = await resolveMedicationCategories(
medications.map((med) => med.id),
);
return {
present: true,
count: medications.length,
@@ -200,6 +210,11 @@ export const MCP_RESOURCES: McpResourceDefinition[] = [
name: med.name,
dose: med.dose,
treatmentClass: med.treatmentClass,
// v1.40 (#1041) — the clinical category: a built-in value or
// `custom:<uuid>`, with the person's own label (their text, fenced)
// for a custom one.
category: categories[med.id]?.category ?? "OTHER",
categoryLabel: fenceOptional(categories[med.id]?.categoryLabel),
asNeeded: med.asNeeded,
// v1.39.1 (#1033) — false: kept as a record, nothing is due and
// no adherence applies; the schedules below are information.
+252 -16
View File
@@ -1,11 +1,31 @@
import { randomUUID } from "node:crypto";
import type { Prisma } from "@/generated/prisma/client";
import { decryptFromBytes, encryptToBytes } from "@/lib/ai/coach/bytes-codec";
import { prisma } from "@/lib/db";
import { MEDICATION_CATEGORY_VALUES } from "@/lib/validations/medication";
import { annotate } from "@/lib/logging/context";
import {
CUSTOM_MEDICATION_CATEGORY_PREFIX,
MEDICATION_CATEGORY_VALUES,
isCustomMedicationCategoryKey,
} from "@/lib/validations/medication";
const MEDICATION_CATEGORIES = MEDICATION_CATEGORY_VALUES;
export type MedicationCategory = (typeof MEDICATION_CATEGORIES)[number];
/**
* What a medication's `category` resolves to: a built-in value, or the
* `custom:<uuid>` key of one of its owner's own categories.
*/
export type MedicationCategoryKey = MedicationCategory | `custom:${string}`;
export interface ResolvedMedicationCategory {
category: MedicationCategoryKey;
/** The decrypted label of a custom category; null for a built-in one. */
categoryLabel: string | null;
}
const DEFAULT_CATEGORY: MedicationCategory = "OTHER";
/**
@@ -16,43 +36,139 @@ const DEFAULT_CATEGORY: MedicationCategory = "OTHER";
*/
type CategoryClient = Pick<
Prisma.TransactionClient,
"medicationCategoryAssignment"
"medicationCategoryAssignment" | "medicationCategoryLabel"
>;
function normalizeCategory(input: unknown): MedicationCategory {
if (typeof input !== "string") return DEFAULT_CATEGORY;
return MEDICATION_CATEGORIES.includes(input as MedicationCategory)
? (input as MedicationCategory)
: DEFAULT_CATEGORY;
function isBuiltIn(input: string): input is MedicationCategory {
return MEDICATION_CATEGORIES.includes(input as MedicationCategory);
}
export async function getMedicationCategories(
/**
* Each medication's category, resolved against its owner's own labels. A
* custom key resolves only to a label owned by the medication's owner (active
* or hidden: hiding affects the picker, not what a medication shows). A key
* with no such label — a restore that carried the medication but not the
* label — reads as OTHER and is counted on the wide event, never a 500.
*/
export async function resolveMedicationCategories(
medicationIds: string[],
client: CategoryClient = prisma,
): Promise<Record<string, MedicationCategory>> {
): Promise<Record<string, ResolvedMedicationCategory>> {
if (medicationIds.length === 0) return {};
const rows = await client.medicationCategoryAssignment.findMany({
where: { medicationId: { in: medicationIds } },
select: { medicationId: true, category: true },
select: {
medicationId: true,
category: true,
medication: { select: { userId: true } },
},
});
const map: Record<string, MedicationCategory> = {};
const customKeys = [
...new Set(
rows
.map((row) => row.category)
.filter((c) => isCustomMedicationCategoryKey(c)),
),
];
const labels =
customKeys.length === 0
? []
: await client.medicationCategoryLabel.findMany({
where: { key: { in: customKeys } },
select: { key: true, userId: true, labelEncrypted: true },
});
const labelByKey = new Map(labels.map((l) => [l.key, l]));
const map: Record<string, ResolvedMedicationCategory> = {};
for (const id of medicationIds) {
map[id] = DEFAULT_CATEGORY;
map[id] = { category: DEFAULT_CATEGORY, categoryLabel: null };
}
let dangling = 0;
for (const row of rows) {
map[row.medicationId] = normalizeCategory(row.category);
if (isBuiltIn(row.category)) {
map[row.medicationId] = { category: row.category, categoryLabel: null };
continue;
}
const label = labelByKey.get(row.category);
if (
isCustomMedicationCategoryKey(row.category) &&
label &&
label.userId === row.medication.userId
) {
map[row.medicationId] = {
category: row.category as MedicationCategoryKey,
categoryLabel: decryptFromBytes(label.labelEncrypted),
};
continue;
}
if (isCustomMedicationCategoryKey(row.category)) dangling += 1;
}
if (dangling > 0) {
annotate({ meta: { "medication.category.dangling": dangling } });
}
return map;
}
/** Each medication's resolved category key (built-in or custom), no labels. */
export async function getMedicationCategories(
medicationIds: string[],
client: CategoryClient = prisma,
): Promise<Record<string, MedicationCategoryKey>> {
const resolved = await resolveMedicationCategories(medicationIds, client);
return Object.fromEntries(
Object.entries(resolved).map(([id, r]) => [id, r.category]),
);
}
/**
* Whether `category` may be written onto a medication of `userId`: any
* built-in value, or a custom key whose label belongs to that account.
*/
export async function isAssignableCategory(
userId: string,
category: string,
client: CategoryClient = prisma,
): Promise<boolean> {
if (isBuiltIn(category)) return true;
if (!isCustomMedicationCategoryKey(category)) return false;
const label = await client.medicationCategoryLabel.findFirst({
where: { key: category, userId },
select: { key: true },
});
return label !== null;
}
/**
* Write a medication's category. A built-in value is stored as given; a
* custom key only when it belongs to the medication's owner, otherwise the
* write falls back to OTHER (the routes refuse a foreign key with a 422
* before they get here; this is the floor for every other caller).
*/
export async function setMedicationCategory(
medicationId: string,
category: unknown,
client: CategoryClient = prisma,
) {
const normalized = normalizeCategory(category);
client: CategoryClient &
Pick<Prisma.TransactionClient, "medication"> = prisma,
): Promise<MedicationCategoryKey> {
let normalized: MedicationCategoryKey = DEFAULT_CATEGORY;
if (typeof category === "string") {
if (isBuiltIn(category)) {
normalized = category;
} else if (isCustomMedicationCategoryKey(category)) {
const owner = await client.medication.findUnique({
where: { id: medicationId },
select: { userId: true },
});
if (
owner &&
(await isAssignableCategory(owner.userId, category, client))
) {
normalized = category as MedicationCategoryKey;
}
}
}
await client.medicationCategoryAssignment.upsert({
where: { medicationId },
@@ -71,3 +187,123 @@ export async function deleteMedicationCategory(
where: { medicationId },
});
}
// ── The person's own categories ─────────────────────────────────────────────
export interface MedicationCategoryLabelDto {
key: string;
label: string;
sortOrder: number;
isActive: boolean;
/** How many of the owner's medications are filed under it. */
medicationCount: number;
}
/** Mint the key of a new custom category. */
export function mintCustomMedicationCategoryKey(): string {
return `${CUSTOM_MEDICATION_CATEGORY_PREFIX}${randomUUID()}`;
}
export function encryptCategoryLabel(label: string): Uint8Array<ArrayBuffer> {
return encryptToBytes(label);
}
export function decryptCategoryLabel(bytes: Uint8Array): string {
return decryptFromBytes(bytes);
}
/** Every custom category of `userId`, hidden ones included, in picker order. */
export async function listMedicationCategoryLabels(
userId: string,
client: CategoryClient = prisma,
): Promise<MedicationCategoryLabelDto[]> {
const rows = await client.medicationCategoryLabel.findMany({
where: { userId },
orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }],
select: {
key: true,
labelEncrypted: true,
sortOrder: true,
isActive: true,
},
});
if (rows.length === 0) return [];
const counts = await client.medicationCategoryAssignment.groupBy({
by: ["category"],
where: {
category: { in: rows.map((r) => r.key) },
medication: { userId },
},
_count: { _all: true },
});
const countByKey = new Map(counts.map((c) => [c.category, c._count._all]));
return rows.map((r) => ({
key: r.key,
label: decryptCategoryLabel(r.labelEncrypted),
sortOrder: r.sortOrder,
isActive: r.isActive,
medicationCount: countByKey.get(r.key) ?? 0,
}));
}
/**
* Every custom category of `userId` as the backup carries it: the decrypted
* label (re-encrypted under the restoring instance's key) and its creation
* instant, hidden ones included.
*/
export async function readMedicationCategoryLabelsForBackup(
userId: string,
client: CategoryClient = prisma,
): Promise<
Array<{
key: string;
label: string;
sortOrder: number;
isActive: boolean;
createdAt: string;
}>
> {
const rows = await client.medicationCategoryLabel.findMany({
where: { userId },
orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }],
select: {
key: true,
labelEncrypted: true,
sortOrder: true,
isActive: true,
createdAt: true,
},
});
return rows.map((r) => ({
key: r.key,
label: decryptCategoryLabel(r.labelEncrypted),
sortOrder: r.sortOrder,
isActive: r.isActive,
createdAt: r.createdAt.toISOString(),
}));
}
/**
* Delete one of `userId`'s custom categories. Its medications move to OTHER
* in the same transaction, so no medication is ever left pointing at a key
* that no longer exists. Returns how many moved, or null when the key is not
* one of the caller's.
*/
export async function deleteMedicationCategoryLabel(
userId: string,
key: string,
): Promise<{ movedCount: number } | null> {
return prisma.$transaction(async (tx) => {
const owned = await tx.medicationCategoryLabel.findFirst({
where: { key, userId },
select: { id: true },
});
if (!owned) return null;
const moved = await tx.medicationCategoryAssignment.updateMany({
where: { category: key, medication: { userId } },
data: { category: DEFAULT_CATEGORY },
});
await tx.medicationCategoryLabel.delete({ where: { id: owned.id } });
return { movedCount: moved.count };
});
}
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import {
ALL_MEDICATION_CATEGORIES,
effectiveCategoryFilter,
filterMedicationsByCategory,
medicationCategoryOptions,
} from "@/lib/medications/category-filter";
import { getMedicationCategoryLabel } from "@/lib/medications/category-label";
const KEY = "custom:11111111-1111-4111-8111-111111111111";
const t = (key: string) => `t:${key}`;
const MEDS = [
{ id: "a", active: true, category: "THYROID", categoryLabel: null },
{ id: "b", active: true, category: KEY, categoryLabel: "Travel kit" },
{ id: "c", active: false, category: KEY, categoryLabel: "Travel kit" },
{ id: "d", active: false, category: "THYROID", categoryLabel: null },
];
describe("medication category filter (v1.40, #1041)", () => {
it("offers each category in use once, labelled like the card badge", () => {
expect(medicationCategoryOptions(MEDS, t)).toEqual([
{ value: "THYROID", label: "t:medications.categoryThyroid" },
{ value: KEY, label: "Travel kit" },
]);
});
it("narrows the active and the inactive block alike", () => {
const active = MEDS.filter((m) => m.active);
const inactive = MEDS.filter((m) => !m.active);
expect(filterMedicationsByCategory(active, KEY).map((m) => m.id)).toEqual([
"b",
]);
expect(filterMedicationsByCategory(inactive, KEY).map((m) => m.id)).toEqual(
["c"],
);
expect(
filterMedicationsByCategory(active, ALL_MEDICATION_CATEGORIES).map(
(m) => m.id,
),
).toEqual(["a", "b"]);
});
it("falls back to All when the stored pick is no longer in use", () => {
const options = medicationCategoryOptions(MEDS, t);
expect(effectiveCategoryFilter(KEY, options)).toBe(KEY);
expect(
effectiveCategoryFilter(
"custom:99999999-9999-4999-8999-999999999999",
options,
),
).toBe(ALL_MEDICATION_CATEGORIES);
});
it("labels a custom category by its own label and an unresolved key as Other", () => {
expect(getMedicationCategoryLabel(KEY, t, "Travel kit")).toBe("Travel kit");
expect(getMedicationCategoryLabel(KEY, t, null)).toBe(
"t:medications.categoryOther",
);
expect(getMedicationCategoryLabel("VITAMIN", t)).toBe(
"t:medications.categoryVitamin",
);
});
});
+66
View File
@@ -0,0 +1,66 @@
/**
* v1.40 (#1041) — the category filter on the medications list. Pure, so the
* page and its tests share one definition of what the filter offers and what
* it keeps.
*/
import { getMedicationCategoryLabel } from "@/lib/medications/category-label";
type Translator = (
key: string,
params?: Record<string, string | number>,
) => string;
/** The "no filter" sentinel, the value `FilterBarSelect` resets to. */
export const ALL_MEDICATION_CATEGORIES = "ALL";
interface CategorisedMedication {
category: string;
categoryLabel?: string | null;
}
/**
* The categories the given medications use, each once, labelled the way the
* card badge labels it, sorted by label. The filter offers only these, so a
* pick can never empty the list.
*/
export function medicationCategoryOptions(
medications: readonly CategorisedMedication[],
t: Translator,
): { value: string; label: string }[] {
const byValue = new Map<string, string>();
for (const m of medications) {
if (!byValue.has(m.category)) {
byValue.set(
m.category,
getMedicationCategoryLabel(m.category, t, m.categoryLabel),
);
}
}
return [...byValue.entries()]
.map(([value, label]) => ({ value, label }))
.sort((a, b) => a.label.localeCompare(b.label));
}
/**
* The filter value that actually applies: a stored pick whose category no
* medication uses any more (deleted, or every medication moved) falls back to
* All rather than showing an empty list.
*/
export function effectiveCategoryFilter(
stored: string,
options: readonly { value: string }[],
): string {
return options.some((option) => option.value === stored)
? stored
: ALL_MEDICATION_CATEGORIES;
}
/** Keep the medications the filter admits, in their order. */
export function filterMedicationsByCategory<T extends CategorisedMedication>(
medications: readonly T[],
filter: string,
): T[] {
return filter === ALL_MEDICATION_CATEGORIES
? [...medications]
: medications.filter((m) => m.category === filter);
}
+13
View File
@@ -38,10 +38,23 @@ const MEDICATION_CATEGORY_KEYS: Record<string, string> = {
OTHER: "medications.categoryOther",
};
/**
* v1.40 (#1041) — a category the person named themselves arrives as
* `custom:<uuid>` with its decrypted label beside it (`categoryLabel` on the
* medication wire); that label wins. A custom key without a label (the server
* resolved it to nothing) reads as Other, like any unknown value.
*/
export function getMedicationCategoryLabel(
category: string,
t: Translator,
customLabel?: string | null,
): string {
if (customLabel) return customLabel;
const key = MEDICATION_CATEGORY_KEYS[category] ?? "medications.categoryOther";
return t(key);
}
/** The built-in category values, in the order the filter row lists them. */
export const BUILT_IN_MEDICATION_CATEGORIES = Object.keys(
MEDICATION_CATEGORY_KEYS,
);
+12 -4
View File
@@ -14,7 +14,10 @@
*/
import { prisma } from "@/lib/db";
import { annotate, getEvent } from "@/lib/logging/context";
import { getMedicationCategories } from "@/lib/medication-category";
import {
resolveMedicationCategories,
type ResolvedMedicationCategory,
} from "@/lib/medication-category";
import {
effectiveUnitsPerDose,
estimateUnitsRunwayDays,
@@ -200,9 +203,11 @@ export async function buildMedicationsList(
}
const trackedMedIds = new Set(inventoryCounts.map((e) => e.medicationId));
let categoryMap: Record<string, string> = {};
let categoryMap: Record<string, ResolvedMedicationCategory> = {};
try {
categoryMap = await getMedicationCategories(medications.map((m) => m.id));
categoryMap = await resolveMedicationCategories(
medications.map((m) => m.id),
);
} catch {
getEvent()?.addWarning("Medication categories could not be loaded");
}
@@ -300,7 +305,10 @@ export async function buildMedicationsList(
// v1.39.1 (#1033) — `schedules: []` plus `recordedSchedules` when
// intake tracking is off (see `scheduleWireFields`).
...scheduleWireFields(m.trackIntake, schedulesDto),
category: categoryMap[m.id] ?? "OTHER",
category: categoryMap[m.id]?.category ?? "OTHER",
// v1.40 (#1041) — the decrypted label of a custom category; null for
// a built-in one, which every client localises from `category`.
categoryLabel: categoryMap[m.id]?.categoryLabel ?? null,
// v1.32.25 — provenance echo. Surfacing the mirror source lets the
// web UI and an operator tell an externally-mirrored row (today only
// Apple Health) from a native HealthLog medication. NULL for a native
+3
View File
@@ -249,6 +249,9 @@ export const ERROR_CODE_CATALOGUE: Readonly<Record<string, readonly string[]>> =
],
medication: ["medication.intake.import.invalid_format"],
medications: [
"medications.category.invalid",
"medications.category.limitReached",
"medications.category.unknown",
"medications.intake.bulk.apple_health_not_mirrored",
"medications.intake.bulk.invalid",
"medications.intake.bulk.too_large",
+142 -2
View File
@@ -20,6 +20,8 @@ import {
glp1PostBodySchema,
bulkDeleteIntakeEventsSchema,
updateIntakeEventSchema,
createMedicationCategoryLabelSchema,
updateMedicationCategoryLabelSchema,
} from "@/lib/validations/medication";
import {
scheduleRevisionCreateSchema,
@@ -50,12 +52,31 @@ const setMedicationEfficacyTargetRequest = efficacyTargetOverrideSchema.meta({
"Set or clear the user's explicit efficacy-target override for a medication. `clear:true` removes the override so the resolver reverts to the derived (ATC class prefix → name inference) target; otherwise pin exactly ONE of `measurementType` (a metric series) / `biomarkerId` (a lab analyte). `userId` is never a field — ownership is narrowed through the medication (and the biomarker for a lab target).",
});
const createMedicationCategoryRequest =
createMedicationCategoryLabelSchema.meta({
id: "CreateMedicationCategoryRequest",
description:
"v1.40 — name a new medication category. The label is trimmed, 1 to 40 characters, and encrypted at rest.",
});
const updateMedicationCategoryRequest =
updateMedicationCategoryLabelSchema.meta({
id: "UpdateMedicationCategoryRequest",
description:
"v1.40 — rename, reorder or hide a custom medication category. At least one field. Hiding (`isActive: false`) removes it from the picker; medications filed under it keep it.",
});
const categoryKeyPath = z.object({
key: z.string().describe("`custom:<uuid>`, the category's key."),
});
const medicationEfficacyResponse = medicationEfficacyResponseSchema.meta({
id: "MedicationEfficacyResponse",
description:
"Server-authoritative, strictly-descriptive efficacy view relating a medication to the outcome metric(s)/lab(s) its class is prescribed to move, around its start. Carries the resolved target(s) with their series, the start/dose-change/pause markers, a before/after-start comparison (honest `{present:false}` below the per-side data floor), an adherence lane (cadence-aware per-day rate, never recomputed), an optional conservative level-shift note, and the retarget options. There is NO verdict / score / assessment field by construction — the client renders numbers and neutral connective phrasing only, never a causal or dose-advice claim.",
});
import {
medicationCategoryLabelResource,
medicationListEntry,
medicationDetailEntry,
medicationInventoryItemResource,
@@ -923,7 +944,7 @@ export const medicationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
tags: ["Medications"],
summary: "Create a medication with at least one schedule",
description:
"Validates the body against `CreateMedicationRequest`, applies the v1.5 cross-field invariants (one-shot consistency, recurring default `FREQ=DAILY`, `timesOfDay` dual-write), and creates the medication + its schedules in a single Prisma write. Audits as `medication.create`. v1.28 — a mirror create (`externalSource` + `externalId`) re-posting a pair the caller already holds returns the existing medication with 200 instead of a duplicate. v1.32.25 — a NEW mirror create is refused with 422 (`meta.errorCode = medications.mirror.limit_exceeded`) once the caller already holds 30 medications mirrored from the same external source; an idempotent re-post of a medication already mirrored is unaffected, and native creates are never gated.",
"Validates the body against `CreateMedicationRequest`, applies the v1.5 cross-field invariants (one-shot consistency, recurring default `FREQ=DAILY`, `timesOfDay` dual-write), and creates the medication + its schedules in a single Prisma write. Audits as `medication.create`. v1.28 — a mirror create (`externalSource` + `externalId`) re-posting a pair the caller already holds returns the existing medication with 200 instead of a duplicate. v1.32.25 — a NEW mirror create is refused with 422 (`meta.errorCode = medications.mirror.limit_exceeded`) once the caller already holds 30 medications mirrored from the same external source; an idempotent re-post of a medication already mirrored is unaffected, and native creates are never gated. v1.40 — `category` may be the key of one of the caller's own categories; any other `custom:` key is 422 `medications.category.unknown`.",
requestBody: {
required: true,
content: { "application/json": { schema: createMedicationSchema } },
@@ -946,6 +967,125 @@ export const medicationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/medications/categories": {
get: {
tags: ["Medications"],
summary: "List the record's own medication categories",
description:
"v1.40 (#1041) — every custom category of the record, hidden ones included, in picker order (`sortOrder`, then creation), each with the number of medications filed under it. The built-in categories are not listed; they are the fixed values of `MedicationCategory`. Delegable at READ level over the `medications` section.",
responses: {
...recordRefusal(),
"200": {
description: "The custom categories.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({
categories: z.array(medicationCategoryLabelResource),
}),
"ListMedicationCategoriesResponse",
),
},
},
},
...stdResponses,
},
},
post: {
parameters: [idempotencyKeyParameter],
tags: ["Medications"],
summary: "Create a custom medication category",
description:
"v1.40 (#1041) — mints a `custom:<uuid>` key and stores the label encrypted. At most 20 per account, hidden ones included: one more is 422 `medications.category.limitReached`; an invalid body is 422 `medications.category.invalid`. Rate-limited 30/min keyed on the actor. Delegable at MANAGE level over the `medications` section. The label never reaches an audit row.",
requestBody: {
required: true,
content: {
"application/json": { schema: createMedicationCategoryRequest },
},
},
responses: {
...idempotentWrite(),
...recordRefusal(),
"201": {
description: "The new category.",
content: {
"application/json": {
schema: dataEnvelope(
medicationCategoryLabelResource,
"CreateMedicationCategoryResponse",
),
},
},
},
...stdResponses,
},
},
},
"/api/medications/categories/{key}": {
patch: {
tags: ["Medications"],
summary: "Rename, reorder or hide a custom medication category",
description:
"v1.40 (#1041) — field-by-field update of one of the record's own categories. Another account's key, or a built-in value, is 404. Owner-only: not delegable, refused under a record switch. Rate-limited 30/min.",
requestParams: { path: categoryKeyPath },
requestBody: {
required: true,
content: {
"application/json": { schema: updateMedicationCategoryRequest },
},
},
responses: {
"200": {
description: "The updated category.",
content: {
"application/json": {
schema: dataEnvelope(
medicationCategoryLabelResource,
"UpdateMedicationCategoryResponse",
),
},
},
},
"404": {
description: "Not one of the record's own categories.",
content: { "application/json": { schema: errorEnvelope } },
},
...stdResponses,
},
},
delete: {
tags: ["Medications"],
summary: "Delete a custom medication category",
description:
"v1.40 (#1041) — deletes the category and, in the same transaction, moves every medication filed under it to OTHER; `movedCount` says how many moved. No medication is left pointing at a key that no longer exists. Another account's key, or a built-in value, is 404. Owner-only: not delegable, refused under a record switch.",
requestParams: { path: categoryKeyPath },
responses: {
"200": {
description: "Deleted.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({
key: z.string(),
movedCount: z
.number()
.int()
.nonnegative()
.describe("Medications moved to OTHER."),
}),
"DeleteMedicationCategoryResponse",
),
},
},
},
"404": {
description: "Not one of the record's own categories.",
content: { "application/json": { schema: errorEnvelope } },
},
...stdResponses,
},
},
},
"/api/medications/layout": {
get: {
tags: ["Medications"],
@@ -1055,7 +1195,7 @@ export const medicationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
tags: ["Medications"],
summary: "Replace a medication (partial fields)",
description:
"Every field on the body is optional; omitted fields are left untouched. Supplying `schedules` REPLACES the medication's full schedule list (the route deletes existing rows before re-creating). Flipping `active` to false stamps `pausedAt`; flipping back to true clears it. v1.5 invariants on the `schedules` array match `POST /api/medications`. Audits as `medication.update`.",
"Every field on the body is optional; omitted fields are left untouched. Supplying `schedules` REPLACES the medication's full schedule list (the route deletes existing rows before re-creating). Flipping `active` to false stamps `pausedAt`; flipping back to true clears it. v1.5 invariants on the `schedules` array match `POST /api/medications`. Audits as `medication.update`. v1.40 — an absent `category` leaves the stored one untouched (send it only when the person changed it); a `custom:` key that is not the caller's is 422 `medications.category.unknown`.",
requestParams: {
path: z.object({ id: z.string() }),
},
+45 -3
View File
@@ -33,12 +33,52 @@ import { MEDICATION_IMPORT_SKIP_REASONS } from "@/lib/jobs/medication-intake-imp
// schema description AND enforced by the route + a DB CHECK constraint
// so iOS code-gen surfaces the mutual exclusion.
export const medicationCategoryEnum = z.enum(MEDICATION_CATEGORY_VALUES).meta({
// v1.40 (#1041) — widened from the built-in enum to a string: a category is
// a built-in value or the `custom:<uuid>` key of one of the caller's own
// categories. The component id stays `MedicationCategory` so a generated
// client keeps its type name; a client decodes unknown values tolerantly and
// shows `categoryLabel` when present.
export const medicationCategoryEnum = z.string().meta({
id: "MedicationCategory",
description:
"Clinical taxonomy stored in the `medication_categories` side-table. Orthogonal to `MedicationTreatmentClass`.",
description: `Clinical category. One of the built-in values (${MEDICATION_CATEGORY_VALUES.join(", ")}) or, since v1.40, \`custom:<uuid>\`, the key of one of the caller's own categories (see \`GET /api/medications/categories\`), whose label rides beside it as \`categoryLabel\`. A client must decode an unknown value tolerantly and must not write \`category\` back unless the person changed it. Orthogonal to \`MedicationTreatmentClass\`.`,
});
const medicationCategoryLabelField = z
.string()
.nullable()
.describe(
"v1.40 — the decrypted label of a custom category (`category` = `custom:<uuid>`); null for a built-in category, which a client localises from `category`. Read-only.",
);
export const medicationCategoryLabelResource = z
.object({
key: z
.string()
.describe(
"`custom:<uuid>`, the value a medication's `category` carries when it is filed under this category.",
),
label: z.string().describe("The person's own label, 1 to 40 characters."),
sortOrder: z
.number()
.int()
.describe("Position in the picker and the filter row, ascending."),
isActive: z
.boolean()
.describe(
"false = hidden from the picker. Medications filed under a hidden category keep it.",
),
medicationCount: z
.number()
.int()
.nonnegative()
.describe("How many of the record's medications are filed under it."),
})
.meta({
id: "MedicationCategoryLabel",
description:
"v1.40 (#1041) — a medication category the person named themselves, shown next to the built-in ones. At most 20 per account (hidden ones count).",
});
export const medicationTreatmentClassEnum = z
.enum(MEDICATION_TREATMENT_CLASS_VALUES)
.meta({
@@ -250,6 +290,7 @@ export const medicationResource = z
export const medicationListEntry = medicationResource
.extend({
category: medicationCategoryEnum,
categoryLabel: medicationCategoryLabelField,
// v1.32.25 — mirrored-medication provenance echoed on the list read so
// the web UI and an operator can tell a mirror row from a native one.
externalSource: z
@@ -315,6 +356,7 @@ export const medicationListEntry = medicationResource
export const medicationDetailEntry = medicationResource
.extend({
category: medicationCategoryEnum,
categoryLabel: medicationCategoryLabelField,
courseStatus: z
.enum(["UPCOMING", "CURRENT", "ENDED"])
.describe(
+7
View File
@@ -52,6 +52,13 @@ export const medicationKeys = {
* layout PUT's response.
*/
medicationListLayout: () => ["medication-list-layout"] as const,
/**
* v1.40 (#1041) — the record's own medication categories
* (`GET /api/medications/categories`). Under the `["medications"]` prefix:
* a delete moves medications to Other, so the list must refetch with it,
* and a medication write changes the per-category counts.
*/
medicationCategories: () => ["medications", "categories"] as const,
medicationCadence: (medicationId: string) =>
["medications", medicationId, "cadence"] as const,
medicationGlp1Details: (medicationId: string) =>
+4
View File
@@ -225,6 +225,10 @@ export function recordActivityVerbLine(
case "medication.update":
return t("recordSharing.activityVerb.medicationUpdate", { name });
case "medication.category.custom.create":
return t("recordSharing.activityVerb.medicationCategoryCreate", {
name,
});
case "medication.delete":
return t("recordSharing.activityVerb.medicationDelete", { name });
case "medication.glp1.update":
+22 -1
View File
@@ -333,6 +333,22 @@ const medicationEfficacyTargetSchema = z
})
.passthrough();
/**
* v1.40 (#1041) — a medication category the account named itself. Carried
* with its decrypted label (the label is re-encrypted on restore under the
* restoring instance's key) and restored BEFORE the medications, whose
* `category` names it by `key`.
*/
const customMedicationCategorySchema = z
.object({
key: z.string().regex(/^custom:[0-9a-f-]{36}$/),
label: z.string().trim().min(1).max(40),
sortOrder: z.number().int().min(0).default(0),
isActive: z.boolean().default(true),
createdAt: isoDateTime.optional(),
})
.passthrough();
const medicationSchema = z
.object({
id: z.string().min(1).optional(),
@@ -361,7 +377,8 @@ const medicationSchema = z
// v1.39.4 — the clinical category. Absent in older files. A string, not
// the enum: a file from a newer server may name a category this one does
// not know, and the restore reads that as OTHER rather than refusing the
// whole file.
// whole file. Since v1.40 it may be `custom:<uuid>`, the key of an entry
// in `customMedicationCategories`.
category: z.string().max(64).optional(),
deliveryForm: z.enum(MedicationDeliveryForm).optional(),
trackInjectionSites: z.boolean().optional(),
@@ -1834,6 +1851,10 @@ export const backupPayloadSchema = z
accountSettings: accountSettingsBackupSchema.nullable().default(null),
measurements: z.array(measurementSchema).default([]),
medications: z.array(medicationSchema).default([]),
// v1.40 — absent in older files, which carry no custom category either.
customMedicationCategories: z
.array(customMedicationCategorySchema)
.default([]),
intakeEvents: z.array(intakeEventSchema).default([]),
moodEntries: z.array(moodEntrySchema).default([]),
// v1.15.0 — cycle-tracking tables. Default to empty arrays / null so a
+59 -2
View File
@@ -63,8 +63,8 @@ export const rxNormCodeField = z
"Optional RxNorm RxCUI (numeric, US identifier, e.g. `2601723`). Secondary coding emitted under `http://www.nlm.nih.gov/research/umls/rxnorm` alongside any ATC code, never instead of the free-text name. NULL clears it; absent leaves it untouched.",
);
/**
* Clinical-category values stored in the `medication_categories` side-
* table (TEXT column). v1.5.4 adds `DIABETES` and `ANTIBIOTIC` so the
* Clinical-category values stored in the `medication_categories` table
* (TEXT column, the `MedicationCategoryAssignment` model). v1.5.4 adds `DIABETES` and `ANTIBIOTIC` so the
* wizard's Step 2 taxonomy can write a first-class bucket for those
* two rows instead of collapsing them into `OTHER`. The column is a
* plain TEXT field — no Prisma enum exists to migrate; the Zod values
@@ -91,6 +91,63 @@ export const MEDICATION_CATEGORY_VALUES = [
export type MedicationCategoryValue =
(typeof MEDICATION_CATEGORY_VALUES)[number];
/**
* v1.40 (#1041) — a category the person named themselves is addressed by the
* key of its `MedicationCategoryLabel` row, `custom:<uuid>`. The `category`
* field on the medication wire is a built-in value or such a key.
*/
export const CUSTOM_MEDICATION_CATEGORY_PREFIX = "custom:";
/** Per-account ceiling on custom medication categories (hidden ones count). */
export const MAX_CUSTOM_MEDICATION_CATEGORIES = 20;
const CUSTOM_MEDICATION_CATEGORY_KEY = /^custom:[0-9a-f-]{36}$/;
/** Is `value` a custom-category key rather than a built-in value? */
export function isCustomMedicationCategoryKey(value: string): boolean {
return value.startsWith(CUSTOM_MEDICATION_CATEGORY_PREFIX);
}
/**
* The `category` a create or update body may carry: a built-in value or a
* well-formed custom key. Ownership of a custom key is checked by the route
* (422 `medications.category.unknown`), not here.
*/
export const medicationCategoryInputSchema = z
.union([
z.enum(MEDICATION_CATEGORY_VALUES),
z.string().regex(CUSTOM_MEDICATION_CATEGORY_KEY, "Unknown category"),
])
.describe(
"A built-in clinical category (BLOOD_PRESSURE, VITAMIN, SUPPLEMENT, PAIN_RELIEF, ALLERGY, DIGESTIVE, THYROID, HORMONE, SKIN, SLEEP_AID, DIABETES, ANTIBIOTIC, MENTAL_HEALTH, OTHER) or `custom:<uuid>`, the key of one of the caller's own categories.",
);
const customCategoryLabelSchema = z
.string()
.trim()
.min(1, "Label must not be empty")
.max(40, "Label must be at most 40 characters");
/** `POST /api/medications/categories` body. */
export const createMedicationCategoryLabelSchema = z.object({
label: customCategoryLabelSchema,
});
/** `PATCH /api/medications/categories/{key}` body: at least one field. */
export const updateMedicationCategoryLabelSchema = z
.object({
label: customCategoryLabelSchema.optional(),
sortOrder: z.number().int().min(0).max(1000).optional(),
isActive: z.boolean().optional(),
})
.refine(
(v) =>
v.label !== undefined ||
v.sortOrder !== undefined ||
v.isActive !== undefined,
"At least one field is required",
);
/**
* v1.4.25 W4d — Prisma-level treatment class. Orthogonal to
* `MEDICATION_CATEGORY_VALUES` (the clinical taxonomy that lives in the
@@ -1,7 +1,7 @@
import { z } from "zod/v4";
import {
MEDICATION_CATEGORY_VALUES,
medicationCategoryInputSchema,
MEDICATION_DELIVERY_FORM_VALUES,
MEDICATION_TREATMENT_CLASS_VALUES,
atcCodeField,
@@ -99,7 +99,7 @@ export const createMedicationSchema = z
.object({
name: z.string().min(1).max(100),
dose: z.string().min(1).max(50),
category: z.enum(MEDICATION_CATEGORY_VALUES).optional(),
category: medicationCategoryInputSchema.optional(),
/** v1.4.25 W4d — treatment-class discriminator (GENERIC | GLP1). */
treatmentClass: z.enum(MEDICATION_TREATMENT_CLASS_VALUES).optional(),
/** v1.4.25 W4d — doses per pen/vial for inventory tracking.
@@ -267,7 +267,7 @@ export const updateMedicationSchema = z
.object({
name: z.string().min(1).max(100).optional(),
dose: z.string().min(1).max(50).optional(),
category: z.enum(MEDICATION_CATEGORY_VALUES).optional(),
category: medicationCategoryInputSchema.optional(),
treatmentClass: z.enum(MEDICATION_TREATMENT_CLASS_VALUES).optional(),
dosesPerUnit: z.number().int().min(1).max(1000).nullable().optional(),
/** v1.16.10 — inventory units one dose consumes. Default 1.