feat(medications): low-stock notifications with a runway threshold

A daily job projects each tracked medication's remaining supply against
its schedules and notifies through the normal channel cascade when the
runway falls below the user's threshold (default seven days, 1-60 or
off, set beside the reminder thresholds). One notification per
crossing: a stamp on the medication row re-arms on refill or threshold
change, and a failed dispatch leaves it clear for the next day's retry.
The GLP-1 card's fixed four-dose flag stays as the locked iOS read
contract; the engine covers it like any other medication.
This commit is contained in:
Marc-André Bombeck committed 2026-06-12 21:04:09 +02:00
1 parent 159de9b78f
commit cac9a32756
19 files changed
+1741 -59

No files matched your search

@@ -7,7 +7,7 @@ vi.mock("@/lib/db", () => ({
update: vi.fn(),
},
},
toJson: <T,>(v: T) => v,
toJson: <T>(v: T) => v,
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
@@ -88,10 +88,20 @@ describe("GET /api/auth/me/notification-prefs", () => {
data: { medication: { clientManaged: boolean } };
};
expect(env.data).toEqual({
medication: { clientManaged: false, deliveryDefault: "server" },
medication: {
clientManaged: false,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 22 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
});
});
@@ -109,10 +119,20 @@ describe("GET /api/auth/me/notification-prefs", () => {
data: { medication: { clientManaged: boolean } };
};
expect(env.data).toEqual({
medication: { clientManaged: true, deliveryDefault: "server" },
medication: {
clientManaged: true,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 22 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
});
});
@@ -132,10 +152,20 @@ describe("GET /api/auth/me/notification-prefs", () => {
data: { medication: { clientManaged: boolean } };
};
expect(env.data).toEqual({
medication: { clientManaged: false, deliveryDefault: "server" },
medication: {
clientManaged: false,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 22 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
});
});
});
@@ -166,20 +196,40 @@ describe("PATCH /api/auth/me/notification-prefs", () => {
data: { medication: { clientManaged: boolean } };
};
expect(env.data).toEqual({
medication: { clientManaged: true, deliveryDefault: "server" },
medication: {
clientManaged: true,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 22 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
});
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: "user-1" },
data: {
notificationPrefs: {
medication: { clientManaged: true, deliveryDefault: "server" },
medication: {
clientManaged: true,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 22 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
},
},
});
@@ -190,16 +240,36 @@ describe("PATCH /api/auth/me/notification-prefs", () => {
userId: "user-1",
details: expect.objectContaining({
previous: {
medication: { clientManaged: false, deliveryDefault: "server" },
medication: {
clientManaged: false,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 22 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
},
next: {
medication: { clientManaged: true, deliveryDefault: "server" },
medication: {
clientManaged: true,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 22 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
},
changed: ["medication"],
}),
@@ -210,14 +280,11 @@ describe("PATCH /api/auth/me/notification-prefs", () => {
it("rejects malformed JSON with 422", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const req = new Request(
"http://localhost/api/auth/me/notification-prefs",
{
method: "PATCH",
body: "{ not valid json",
headers: { "Content-Type": "application/json" },
},
);
const req = new Request("http://localhost/api/auth/me/notification-prefs", {
method: "PATCH",
body: "{ not valid json",
headers: { "Content-Type": "application/json" },
});
const res = await (PATCH as (r: Request) => Promise<Response>)(req);
expect(res.status).toBe(422);
@@ -258,10 +325,20 @@ describe("PATCH /api/auth/me/notification-prefs", () => {
where: { id: "user-1" },
data: {
notificationPrefs: {
medication: { clientManaged: true, deliveryDefault: "server" },
medication: {
clientManaged: true,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 22 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
},
},
});
@@ -276,28 +353,46 @@ describe("PATCH /api/auth/me/notification-prefs", () => {
} as never);
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({}),
);
const res = await (PATCH as (r: Request) => Promise<Response>)(mkPatch({}));
expect(res.status).toBe(200);
const env = (await res.json()) as {
data: { medication: { clientManaged: boolean } };
};
expect(env.data).toEqual({
medication: { clientManaged: true, deliveryDefault: "server" },
medication: {
clientManaged: true,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 22 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
});
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: "user-1" },
data: {
notificationPrefs: {
medication: { clientManaged: true, deliveryDefault: "server" },
medication: {
clientManaged: true,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 22 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
},
},
});
@@ -323,10 +418,20 @@ describe("PATCH /api/auth/me/notification-prefs", () => {
where: { id: "user-1" },
data: {
notificationPrefs: {
medication: { clientManaged: false, deliveryDefault: "server" },
medication: {
clientManaged: false,
deliveryDefault: "server",
lowStockRunwayDays: 7,
},
mood: { reminderHour: 9 },
cycle: { clientManaged: false },
coach: { nudgesEnabled: true, nudgeMedication: true, nudgeVitals: true, nudgeRoutine: true, nudgeFrequency: "weekly" },
coach: {
nudgesEnabled: true,
nudgeMedication: true,
nudgeVitals: true,
nudgeRoutine: true,
nudgeFrequency: "weekly",
},
},
},
});
@@ -342,6 +447,65 @@ describe("PATCH /api/auth/me/notification-prefs", () => {
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("v1.16.11 — round-trips a custom lowStockRunwayDays", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
notificationPrefs: null,
} as never);
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({ medication: { lowStockRunwayDays: 14 } }),
);
expect(res.status).toBe(200);
const env = (await res.json()) as {
data: { medication: { lowStockRunwayDays: number | null } };
};
expect(env.data.medication.lowStockRunwayDays).toBe(14);
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: "user-1" },
data: {
notificationPrefs: expect.objectContaining({
medication: {
clientManaged: false,
deliveryDefault: "server",
lowStockRunwayDays: 14,
},
}),
},
});
});
it("v1.16.11 — persists the explicit null (alert off)", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
notificationPrefs: { medication: { lowStockRunwayDays: 14 } },
} as never);
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({ medication: { lowStockRunwayDays: null } }),
);
expect(res.status).toBe(200);
const env = (await res.json()) as {
data: { medication: { lowStockRunwayDays: number | null } };
};
expect(env.data.medication.lowStockRunwayDays).toBe(null);
});
it("v1.16.11 — rejects a lowStockRunwayDays outside 1..60 with 422", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
for (const value of [0, 61]) {
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({ medication: { lowStockRunwayDays: value } }),
);
expect(res.status).toBe(422);
}
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("returns 429 when the per-user rate-limit fires", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(checkRateLimit).mockResolvedValueOnce({
@@ -0,0 +1,116 @@
/**
* v1.16.11 — reminder-thresholds GET: the operator-level late / missed
* minutes ride along unchanged; the new `lowStockRunwayDays` field is
* PER-USER (from `notificationPrefs.medication`), so the endpoint
* reflects whatever the notification-prefs PATCH persisted — the read
* half of the settings round-trip.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
user: {
findUnique: vi.fn(),
},
appSettings: {
findUnique: vi.fn(),
},
},
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function mkGet(): Request {
return new Request("http://localhost/api/settings/reminder-thresholds");
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue({
reminderLateMinutes: 120,
reminderMissedMinutes: 240,
} as never);
});
describe("GET /api/settings/reminder-thresholds", () => {
it("rejects an unauthenticated request with 401", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const res = await (GET as (r: Request) => Promise<Response>)(mkGet());
expect(res.status).toBe(401);
});
it("returns the default low-stock threshold (7) for a fresh user", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
notificationPrefs: null,
} as never);
const res = await (GET as (r: Request) => Promise<Response>)(mkGet());
expect(res.status).toBe(200);
const env = (await res.json()) as {
data: {
lateMinutes: number;
missedMinutes: number;
lowStockRunwayDays: number | null;
};
};
expect(env.data).toEqual({
lateMinutes: 120,
missedMinutes: 240,
lowStockRunwayDays: 7,
});
});
it("reflects the per-user threshold persisted by the prefs PATCH", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
notificationPrefs: { medication: { lowStockRunwayDays: 21 } },
} as never);
const res = await (GET as (r: Request) => Promise<Response>)(mkGet());
expect(res.status).toBe(200);
const env = (await res.json()) as {
data: { lowStockRunwayDays: number | null };
};
expect(env.data.lowStockRunwayDays).toBe(21);
});
it("reflects the OFF state as null", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
notificationPrefs: { medication: { lowStockRunwayDays: null } },
} as never);
const res = await (GET as (r: Request) => Promise<Response>)(mkGet());
expect(res.status).toBe(200);
const env = (await res.json()) as {
data: { lowStockRunwayDays: number | null };
};
expect(env.data.lowStockRunwayDays).toBe(null);
});
});
@@ -2,15 +2,31 @@ import { apiSuccess } from "@/lib/api-response";
import { getReminderThresholds } from "@/lib/app-settings";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { prisma } from "@/lib/db";
import { resolveLowStockRunwayDays } from "@/lib/validations/notification-prefs";
export const dynamic = "force-dynamic";
export const GET = apiHandler(async () => {
await requireAuth();
const { user } = await requireAuth();
const thresholds = await getReminderThresholds();
// v1.16.11 — the low-stock runway threshold rides along so every
// threshold consumer reads one endpoint. Unlike `lateMinutes` /
// `missedMinutes` (operator-level singleton) this one is PER-USER:
// it lives in `notificationPrefs.medication.lowStockRunwayDays`
// (1–60 days, `null` = alert off, default 7) and is written through
// the established `PATCH /api/auth/me/notification-prefs` path.
const row = await prisma.user.findUnique({
where: { id: user.id },
select: { notificationPrefs: true },
});
const lowStockRunwayDays = resolveLowStockRunwayDays(
row?.notificationPrefs ?? null,
);
annotate({ action: { name: "settings.reminder-thresholds.get" } });
return apiSuccess(thresholds);
return apiSuccess({ ...thresholds, lowStockRunwayDays });
});