mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
style: apply prettier across the tree
One-shot prettier pass so the new format:check gate starts from a clean baseline. Formatting only — no behaviour change. Generator-owned and vendored artifacts stay untouched via .prettierignore.
This commit is contained in:
1 parent
b3fea2ef59
commit
1f4ba5939d
1000 files changed
+12130
-8385
No files matched your search
@@ -170,10 +170,7 @@ describe("PUT /api/medications/[id] — v1.5 scheduling primitives", () => {
|
||||
// Re-stub deps the outer beforeEach's resetAllMocks cleared.
|
||||
vi.mocked(getMedicationCategories).mockResolvedValue({});
|
||||
vi.mocked(auditLog).mockResolvedValue(undefined);
|
||||
const res = await PUT(
|
||||
putReq({ endsOn: "2026-12-31" }),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
const res = await PUT(putReq({ endsOn: "2026-12-31" }), ROUTE_CTX);
|
||||
expect(res.status).toBe(200);
|
||||
const call = lastUpdateCall();
|
||||
expect(call.data.endsOn).toBeInstanceOf(Date);
|
||||
@@ -251,9 +248,7 @@ describe("PUT /api/medications/[id] — schedule replace archives a revision (v1
|
||||
vi.mocked(getMedicationCategories).mockResolvedValue({});
|
||||
vi.mocked(auditLog).mockResolvedValue(undefined);
|
||||
vi.mocked(dayKeyForScheduledFor).mockReturnValue("2026-06-10");
|
||||
vi.mocked(recomputeMedicationComplianceForDay).mockResolvedValue(
|
||||
undefined,
|
||||
);
|
||||
vi.mocked(recomputeMedicationComplianceForDay).mockResolvedValue(undefined);
|
||||
vi.mocked(prisma.medicationSchedule.findMany).mockResolvedValue([
|
||||
PREVIOUS_ROW,
|
||||
] as never);
|
||||
@@ -379,9 +374,7 @@ describe("PUT /api/medications/[id] — schedule replace migrates open slots", (
|
||||
skipped: false,
|
||||
autoMissed: false,
|
||||
});
|
||||
expect(
|
||||
(arg.where.scheduledFor as { gte: Date }).gte,
|
||||
).toBeInstanceOf(Date);
|
||||
expect((arg.where.scheduledFor as { gte: Date }).gte).toBeInstanceOf(Date);
|
||||
expect(arg.data.deletedAt).toBeInstanceOf(Date);
|
||||
expect(arg.data.syncVersion).toEqual({ increment: 1 });
|
||||
});
|
||||
@@ -394,8 +387,8 @@ describe("PUT /api/medications/[id] — schedule replace migrates open slots", (
|
||||
{ scheduledFor: new Date("2026-06-10T18:00:00Z") },
|
||||
{ scheduledFor: new Date("2026-06-11T06:00:00Z") },
|
||||
] as never);
|
||||
vi.mocked(dayKeyForScheduledFor).mockImplementation(
|
||||
(scheduledFor: Date) => scheduledFor.toISOString().slice(0, 10),
|
||||
vi.mocked(dayKeyForScheduledFor).mockImplementation((scheduledFor: Date) =>
|
||||
scheduledFor.toISOString().slice(0, 10),
|
||||
);
|
||||
|
||||
const res = await PUT(
|
||||
@@ -642,17 +635,15 @@ describe("PUT /api/medications/[id] — as-needed (v1.16.11, #316)", () => {
|
||||
asNeeded: true,
|
||||
schedules: [],
|
||||
} as never);
|
||||
const res = await PUT(
|
||||
putReq({ asNeeded: true, schedules: [] }),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
const res = await PUT(putReq({ asNeeded: true, schedules: [] }), ROUTE_CTX);
|
||||
expect(res.status).toBe(200);
|
||||
// Wholesale replace ran: delete-all, recreate none.
|
||||
expect(prisma.medicationSchedule.deleteMany).toHaveBeenCalledWith({
|
||||
where: { medicationId: "m1" },
|
||||
});
|
||||
const updateData = vi.mocked(prisma.medication.update).mock
|
||||
.calls[0][0] as { data: Record<string, unknown> };
|
||||
const updateData = vi.mocked(prisma.medication.update).mock.calls[0][0] as {
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
expect(updateData.data.asNeeded).toBe(true);
|
||||
expect(updateData.data.schedules).toEqual({ create: [] });
|
||||
});
|
||||
@@ -695,8 +686,9 @@ describe("PUT /api/medications/[id] — as-needed (v1.16.11, #316)", () => {
|
||||
ROUTE_CTX,
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const updateData = vi.mocked(prisma.medication.update).mock
|
||||
.calls[0][0] as { data: Record<string, unknown> };
|
||||
const updateData = vi.mocked(prisma.medication.update).mock.calls[0][0] as {
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
expect(updateData.data.asNeeded).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -111,9 +111,7 @@ describe("GET /api/medications/[id]/cadence", () => {
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([]);
|
||||
|
||||
const res = await GET(
|
||||
new NextRequest(
|
||||
"http://localhost/api/medications/med-1/cadence?days=14",
|
||||
),
|
||||
new NextRequest("http://localhost/api/medications/med-1/cadence?days=14"),
|
||||
{ params: Promise.resolve({ id: "med-1" }) },
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
@@ -20,11 +20,7 @@ import { z } from "zod";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
returnAllZodIssues,
|
||||
} from "@/lib/api-response";
|
||||
import { apiError, apiSuccess, returnAllZodIssues } from "@/lib/api-response";
|
||||
import {
|
||||
buildCadenceTimeline,
|
||||
computeNextDose,
|
||||
@@ -81,7 +77,9 @@ export const GET = apiHandler(
|
||||
// Pull intake events covering the window + a small buffer so a dose
|
||||
// logged at the edge can still pair with its slot.
|
||||
const bufferMs = 24 * 60 * 60 * 1000;
|
||||
const from = new Date(asOf.getTime() - windowDays * 24 * 60 * 60 * 1000 - bufferMs);
|
||||
const from = new Date(
|
||||
asOf.getTime() - windowDays * 24 * 60 * 60 * 1000 - bufferMs,
|
||||
);
|
||||
const events = await prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
medicationId: id,
|
||||
|
||||
@@ -82,7 +82,12 @@ const TZ = "UTC";
|
||||
|
||||
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, timezone: TZ },
|
||||
user: {
|
||||
id: "user-1",
|
||||
username: "testuser",
|
||||
role: "USER" as const,
|
||||
timezone: TZ,
|
||||
},
|
||||
};
|
||||
|
||||
const ROUTE_PARAMS = { params: Promise.resolve({ id: "med-1" }) };
|
||||
@@ -340,31 +345,29 @@ describe("GET /api/medications/[id]/compliance — complianceDisplay", () => {
|
||||
});
|
||||
|
||||
it("35-day-interval med → steps the windows up past 7 / 30 days", async () => {
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValue(
|
||||
{
|
||||
id: "med-1",
|
||||
userId: "user-1",
|
||||
createdAt: new Date(Date.now() - 400 * 24 * 60 * 60 * 1000),
|
||||
startsOn: new Date(Date.now() - 380 * 24 * 60 * 60 * 1000),
|
||||
endsOn: null,
|
||||
oneShot: false,
|
||||
schedules: [
|
||||
{
|
||||
id: "sched-1",
|
||||
windowStart: "10:00",
|
||||
windowEnd: "11:00",
|
||||
timesOfDay: ["10:00"],
|
||||
daysOfWeek: null,
|
||||
rrule: null,
|
||||
rollingIntervalDays: 35,
|
||||
reminderGraceMinutes: null,
|
||||
scheduleType: "SCHEDULED",
|
||||
cyclicOnWeeks: null,
|
||||
cyclicOffWeeks: null,
|
||||
},
|
||||
],
|
||||
} as never,
|
||||
);
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
|
||||
id: "med-1",
|
||||
userId: "user-1",
|
||||
createdAt: new Date(Date.now() - 400 * 24 * 60 * 60 * 1000),
|
||||
startsOn: new Date(Date.now() - 380 * 24 * 60 * 60 * 1000),
|
||||
endsOn: null,
|
||||
oneShot: false,
|
||||
schedules: [
|
||||
{
|
||||
id: "sched-1",
|
||||
windowStart: "10:00",
|
||||
windowEnd: "11:00",
|
||||
timesOfDay: ["10:00"],
|
||||
daysOfWeek: null,
|
||||
rrule: null,
|
||||
rollingIntervalDays: 35,
|
||||
reminderGraceMinutes: null,
|
||||
scheduleType: "SCHEDULED",
|
||||
cyclicOnWeeks: null,
|
||||
cyclicOffWeeks: null,
|
||||
},
|
||||
],
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([
|
||||
{
|
||||
takenAt: new Date(Date.now() - 25 * 24 * 60 * 60 * 1000),
|
||||
|
||||
@@ -7,11 +7,7 @@ import {
|
||||
complianceCacheKey,
|
||||
type CompliancePayload,
|
||||
} from "@/lib/medications/compliance-payload";
|
||||
import {
|
||||
cachedSwr,
|
||||
caches,
|
||||
type ServerCache,
|
||||
} from "@/lib/cache/server-cache";
|
||||
import { cachedSwr, caches, type ServerCache } from "@/lib/cache/server-cache";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
@@ -117,7 +117,9 @@ beforeEach(() => {
|
||||
},
|
||||
],
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue(
|
||||
[] as never,
|
||||
);
|
||||
});
|
||||
|
||||
describe("GET /api/medications/[id]/dose-history", () => {
|
||||
|
||||
@@ -20,11 +20,7 @@ import { z } from "zod/v4";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
returnAllZodIssues,
|
||||
} from "@/lib/api-response";
|
||||
import { apiError, apiSuccess, returnAllZodIssues } from "@/lib/api-response";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
import { lastNonSkippedTakenAt } from "@/lib/analytics/compliance";
|
||||
import type { SlotBand } from "@/lib/medications/scheduling/attribution";
|
||||
|
||||
@@ -17,7 +17,9 @@ vi.mock("@/lib/db", () => ({
|
||||
// v1.17.0 — the GET reads the caller's notificationPrefs to resolve
|
||||
// the reorder-lead-aware low-stock trigger. Default null = the
|
||||
// documented defaults (alert on, 7-day floor, 10-day lead).
|
||||
user: { findUnique: vi.fn().mockResolvedValue({ notificationPrefs: null }) },
|
||||
user: {
|
||||
findUnique: vi.fn().mockResolvedValue({ notificationPrefs: null }),
|
||||
},
|
||||
medicationDoseChange: { create: vi.fn() },
|
||||
medicationInventoryEvent: { create: vi.fn() },
|
||||
},
|
||||
|
||||
@@ -269,7 +269,12 @@ import { localHmAsUtc } from "@/lib/tz/local-day";
|
||||
const TZ = "Europe/Berlin";
|
||||
const SESSION_TZ = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: { id: "user-1", username: "tester", role: "USER" as const, timezone: TZ },
|
||||
user: {
|
||||
id: "user-1",
|
||||
username: "tester",
|
||||
role: "USER" as const,
|
||||
timezone: TZ,
|
||||
},
|
||||
};
|
||||
const ATTR_DAY = new Date("2026-06-05T12:00:00Z");
|
||||
function at(h: number, m: number): Date {
|
||||
@@ -541,9 +546,7 @@ describe("PUT — v1.15.18 band re-attribution", () => {
|
||||
const body = (await res.json()) as {
|
||||
meta?: { errorCode?: string };
|
||||
};
|
||||
expect(body.meta?.errorCode).toBe(
|
||||
"medications.intake.force_slot.occupied",
|
||||
);
|
||||
expect(body.meta?.errorCode).toBe("medications.intake.force_slot.occupied");
|
||||
expect(prisma.medicationIntakeEvent.update).not.toHaveBeenCalled();
|
||||
expect(prisma.medicationIntakeEvent.create).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -588,9 +591,8 @@ describe("PUT / DELETE — v1.16.10 inventory consumption", () => {
|
||||
});
|
||||
|
||||
it("an edit into taken consumes on the row (no slot move)", async () => {
|
||||
const { consumeForIntake, restoreForIntake } = await import(
|
||||
"@/lib/medications/inventory/consumption"
|
||||
);
|
||||
const { consumeForIntake, restoreForIntake } =
|
||||
await import("@/lib/medications/inventory/consumption");
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst)
|
||||
// PUT lookup — pending row anchored on the 07:00 slot.
|
||||
.mockResolvedValueOnce({
|
||||
@@ -610,7 +612,10 @@ describe("PUT / DELETE — v1.16.10 inventory consumption", () => {
|
||||
skipped: false,
|
||||
} as never);
|
||||
|
||||
const res = await PUT(putReq({ takenAt: at(7, 5).toISOString() }), ROUTE_CTX);
|
||||
const res = await PUT(
|
||||
putReq({ takenAt: at(7, 5).toISOString() }),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(consumeForIntake).toHaveBeenCalledTimes(1);
|
||||
expect(consumeForIntake).toHaveBeenCalledWith(
|
||||
@@ -624,9 +629,8 @@ describe("PUT / DELETE — v1.16.10 inventory consumption", () => {
|
||||
});
|
||||
|
||||
it("an in-place time correction on an already-taken row never consumes (pre-stamp legacy rows must not retro-charge)", async () => {
|
||||
const { consumeForIntake, restoreForIntake } = await import(
|
||||
"@/lib/medications/inventory/consumption"
|
||||
);
|
||||
const { consumeForIntake, restoreForIntake } =
|
||||
await import("@/lib/medications/inventory/consumption");
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst)
|
||||
// PUT lookup — a row already taken BEFORE the edit, stamp NULL
|
||||
// (pre-v1.16.10: its stock moved through the legacy hook at take
|
||||
@@ -658,9 +662,8 @@ describe("PUT / DELETE — v1.16.10 inventory consumption", () => {
|
||||
});
|
||||
|
||||
it("a taken → skipped edit restores the row's stamp and never consumes", async () => {
|
||||
const { consumeForIntake, restoreForIntake } = await import(
|
||||
"@/lib/medications/inventory/consumption"
|
||||
);
|
||||
const { consumeForIntake, restoreForIntake } =
|
||||
await import("@/lib/medications/inventory/consumption");
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst)
|
||||
.mockResolvedValueOnce({
|
||||
id: "e1",
|
||||
@@ -688,9 +691,8 @@ describe("PUT / DELETE — v1.16.10 inventory consumption", () => {
|
||||
});
|
||||
|
||||
it("a slot-moving taken edit refunds the old row before tombstoning and consumes the converged row — net one", async () => {
|
||||
const { consumeForIntake, restoreForIntake } = await import(
|
||||
"@/lib/medications/inventory/consumption"
|
||||
);
|
||||
const { consumeForIntake, restoreForIntake } =
|
||||
await import("@/lib/medications/inventory/consumption");
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst)
|
||||
.mockResolvedValueOnce({
|
||||
id: "e1",
|
||||
@@ -730,17 +732,16 @@ describe("PUT / DELETE — v1.16.10 inventory consumption", () => {
|
||||
expect.objectContaining({ eventId: "e2" }),
|
||||
);
|
||||
// The refund runs BEFORE the tombstone write.
|
||||
const restoreOrder = vi.mocked(restoreForIntake).mock
|
||||
const restoreOrder =
|
||||
vi.mocked(restoreForIntake).mock.invocationCallOrder[0];
|
||||
const tombstoneOrder = vi.mocked(prisma.medicationIntakeEvent.update).mock
|
||||
.invocationCallOrder[0];
|
||||
const tombstoneOrder = vi.mocked(prisma.medicationIntakeEvent.update)
|
||||
.mock.invocationCallOrder[0];
|
||||
expect(restoreOrder).toBeLessThan(tombstoneOrder);
|
||||
});
|
||||
|
||||
it("DELETE refunds the row's stamp before the tombstone", async () => {
|
||||
const { consumeForIntake, restoreForIntake } = await import(
|
||||
"@/lib/medications/inventory/consumption"
|
||||
);
|
||||
const { consumeForIntake, restoreForIntake } =
|
||||
await import("@/lib/medications/inventory/consumption");
|
||||
vi.mocked(prisma.medicationIntakeEvent.findUnique).mockResolvedValue({
|
||||
id: "e1",
|
||||
userId: "user-1",
|
||||
@@ -768,10 +769,10 @@ describe("PUT / DELETE — v1.16.10 inventory consumption", () => {
|
||||
expect.objectContaining({ userId: "user-1", eventId: "e1" }),
|
||||
);
|
||||
expect(consumeForIntake).not.toHaveBeenCalled();
|
||||
const restoreOrder = vi.mocked(restoreForIntake).mock
|
||||
const restoreOrder =
|
||||
vi.mocked(restoreForIntake).mock.invocationCallOrder[0];
|
||||
const tombstoneOrder = vi.mocked(prisma.medicationIntakeEvent.update).mock
|
||||
.invocationCallOrder[0];
|
||||
const tombstoneOrder = vi.mocked(prisma.medicationIntakeEvent.update)
|
||||
.mock.invocationCallOrder[0];
|
||||
expect(restoreOrder).toBeLessThan(tombstoneOrder);
|
||||
});
|
||||
});
|
||||
@@ -226,7 +226,10 @@ describe("v1.4.43 W6 — multi-issue 422 envelope", () => {
|
||||
}
|
||||
|
||||
it("GET surfaces TWO simultaneous validation errors", async () => {
|
||||
const res = await GET(makeRequest("status=junk&sortBy=garbage"), ROUTE_PARAMS);
|
||||
const res = await GET(
|
||||
makeRequest("status=junk&sortBy=garbage"),
|
||||
ROUTE_PARAMS,
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
const body = (await res.json()) as {
|
||||
data: null;
|
||||
@@ -284,7 +287,9 @@ describe("v1.4.43 W6 — multi-issue 422 envelope", () => {
|
||||
expect(prisma.auditLog.create).toHaveBeenCalled();
|
||||
const actions = vi
|
||||
.mocked(prisma.auditLog.create)
|
||||
.mock.calls.map((c) => (c[0] as { data: { action: string } }).data.action);
|
||||
.mock.calls.map(
|
||||
(c) => (c[0] as { data: { action: string } }).data.action,
|
||||
);
|
||||
expect(actions).toContain("medications.intake.list.validation-failed");
|
||||
expect(actions).toContain("medications.intake.create.validation-failed");
|
||||
});
|
||||
@@ -413,9 +418,8 @@ describe("POST /api/medications/[id]/intake — v1.8.2 reconcile (M2 inventory)"
|
||||
});
|
||||
|
||||
it("does NOT decrement inventory on a re-post of an already-taken slot (M2)", async () => {
|
||||
const { consumeForIntake } = await import(
|
||||
"@/lib/medications/inventory/consumption"
|
||||
);
|
||||
const { consumeForIntake } =
|
||||
await import("@/lib/medications/inventory/consumption");
|
||||
// Resolver load → scheduled med.
|
||||
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(
|
||||
SCHEDULED_MED as never,
|
||||
@@ -463,9 +467,8 @@ describe("POST /api/medications/[id]/intake — v1.8.2 reconcile (M2 inventory)"
|
||||
});
|
||||
|
||||
it("DOES decrement inventory on a genuine pending→taken move (M2)", async () => {
|
||||
const { consumeForIntake } = await import(
|
||||
"@/lib/medications/inventory/consumption"
|
||||
);
|
||||
const { consumeForIntake } =
|
||||
await import("@/lib/medications/inventory/consumption");
|
||||
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(
|
||||
SCHEDULED_MED as never,
|
||||
);
|
||||
@@ -626,9 +629,8 @@ describe("POST /api/medications/[id]/intake — as-needed (schedule-less) medica
|
||||
|
||||
// Inventory consumption fires exactly as for a scheduled medication —
|
||||
// the seam is medication-level (eventId + intakeAt), no schedule input.
|
||||
const { consumeForIntake } = await import(
|
||||
"@/lib/medications/inventory/consumption"
|
||||
);
|
||||
const { consumeForIntake } =
|
||||
await import("@/lib/medications/inventory/consumption");
|
||||
expect(consumeForIntake).toHaveBeenCalledTimes(1);
|
||||
expect(consumeForIntake).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -674,9 +676,8 @@ describe("POST /api/medications/[id]/intake — as-needed (schedule-less) medica
|
||||
const res = await POST(postReq({ skipped: true }), ROUTE_PARAMS);
|
||||
expect(res.status).toBe(201);
|
||||
|
||||
const { consumeForIntake, restoreForIntake } = await import(
|
||||
"@/lib/medications/inventory/consumption"
|
||||
);
|
||||
const { consumeForIntake, restoreForIntake } =
|
||||
await import("@/lib/medications/inventory/consumption");
|
||||
expect(consumeForIntake).not.toHaveBeenCalled();
|
||||
expect(restoreForIntake).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -100,11 +100,14 @@ const SESSION_OK = {
|
||||
const ROUTE_PARAMS = { params: Promise.resolve({ id: "med-1" }) };
|
||||
|
||||
function postWithBody(body: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/medications/med-1/intake/bulk-delete", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return new NextRequest(
|
||||
"http://localhost/api/medications/med-1/intake/bulk-delete",
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -119,7 +122,9 @@ beforeEach(() => {
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
timezone: "Europe/Berlin",
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue(
|
||||
[] as never,
|
||||
);
|
||||
vi.mocked(prisma.medicationIntakeEvent.updateMany).mockResolvedValue({
|
||||
count: 0,
|
||||
} as never);
|
||||
@@ -142,10 +147,7 @@ describe("POST /api/medications/[id]/intake/bulk-delete", () => {
|
||||
vi.mocked(assertMedicationOwnership).mockResolvedValueOnce(
|
||||
new Response(null, { status: 404 }) as never,
|
||||
);
|
||||
const res = await POST(
|
||||
postWithBody({ eventIds: ["evt-1"] }),
|
||||
ROUTE_PARAMS,
|
||||
);
|
||||
const res = await POST(postWithBody({ eventIds: ["evt-1"] }), ROUTE_PARAMS);
|
||||
expect(res.status).toBe(404);
|
||||
expect(prisma.medicationIntakeEvent.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -226,10 +228,7 @@ describe("POST /api/medications/[id]/intake/bulk-delete — F-1 H-6 rate limit",
|
||||
remaining: 0,
|
||||
resetAt: Date.now() + 60_000,
|
||||
});
|
||||
const res = await POST(
|
||||
postWithBody({ eventIds: ["evt-a"] }),
|
||||
ROUTE_PARAMS,
|
||||
);
|
||||
const res = await POST(postWithBody({ eventIds: ["evt-a"] }), ROUTE_PARAMS);
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.headers.get("X-RateLimit-Remaining")).toBe("0");
|
||||
expect(prisma.medicationIntakeEvent.findMany).not.toHaveBeenCalled();
|
||||
@@ -248,9 +247,8 @@ describe("POST /api/medications/[id]/intake/bulk-delete — F-1 H-6 rate limit",
|
||||
|
||||
describe("POST /api/medications/[id]/intake/bulk-delete — v1.16.10 inventory refund", () => {
|
||||
it("restores each stamped row before the tombstone sweep and ignores unstamped rows", async () => {
|
||||
const { restoreForIntake } = await import(
|
||||
"@/lib/medications/inventory/consumption"
|
||||
);
|
||||
const { restoreForIntake } =
|
||||
await import("@/lib/medications/inventory/consumption");
|
||||
const day1 = new Date(Date.UTC(2026, 4, 27, 8, 0, 0));
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValueOnce([
|
||||
{
|
||||
@@ -275,10 +273,10 @@ describe("POST /api/medications/[id]/intake/bulk-delete — v1.16.10 inventory r
|
||||
expect.objectContaining({ userId: "user-1", eventId: "evt-stamped" }),
|
||||
);
|
||||
// The refund runs BEFORE the soft-delete sweep.
|
||||
const restoreOrder = vi.mocked(restoreForIntake).mock
|
||||
const restoreOrder =
|
||||
vi.mocked(restoreForIntake).mock.invocationCallOrder[0];
|
||||
const sweepOrder = vi.mocked(prisma.medicationIntakeEvent.updateMany).mock
|
||||
.invocationCallOrder[0];
|
||||
const sweepOrder = vi.mocked(prisma.medicationIntakeEvent.updateMany)
|
||||
.mock.invocationCallOrder[0];
|
||||
expect(restoreOrder).toBeLessThan(sweepOrder);
|
||||
});
|
||||
});
|
||||
@@ -59,9 +59,12 @@ const SESSION_OK = {
|
||||
const ROUTE_PARAMS = { params: Promise.resolve({ id: "med-1" }) };
|
||||
|
||||
function deleteReq(): NextRequest {
|
||||
return new NextRequest("http://localhost/api/medications/med-1/intake/purge", {
|
||||
method: "DELETE",
|
||||
});
|
||||
return new NextRequest(
|
||||
"http://localhost/api/medications/med-1/intake/purge",
|
||||
{
|
||||
method: "DELETE",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -30,7 +30,7 @@ vi.mock("@/lib/medications/inventory/service", () => ({
|
||||
// v1.16.12 — the route serialises its Decimal unit columns to numbers
|
||||
// on the way out; a passthrough keeps these update-logic assertions
|
||||
// focused on the Prisma call, not the response shape.
|
||||
serializeInventoryItem: <T,>(item: T) => item,
|
||||
serializeInventoryItem: <T>(item: T) => item,
|
||||
}));
|
||||
vi.mock("@/lib/medications/route-guards", () => ({
|
||||
assertMedicationOwnership: vi.fn().mockResolvedValue(null),
|
||||
@@ -63,14 +63,11 @@ const SESSION_OK = {
|
||||
};
|
||||
|
||||
function patchReq(body: unknown): NextRequest {
|
||||
return new NextRequest(
|
||||
"http://localhost/api/medications/m1/inventory/i1",
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
);
|
||||
return new NextRequest("http://localhost/api/medications/m1/inventory/i1", {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
const ROUTE_CTX = {
|
||||
@@ -166,7 +163,9 @@ describe("PATCH /api/medications/[id]/inventory/[itemId] — unitsRemaining stoc
|
||||
const res = await PATCH(patchReq({ unitsRemaining: 0 }), ROUTE_CTX);
|
||||
expect(res.status).toBe(200);
|
||||
const update = vi.mocked(prisma.medicationInventoryItem.update).mock
|
||||
.calls[0][0] as unknown as { data: { unitsRemaining: number; state: string } };
|
||||
.calls[0][0] as unknown as {
|
||||
data: { unitsRemaining: number; state: string };
|
||||
};
|
||||
expect(update.data.unitsRemaining).toBe(0);
|
||||
expect(update.data.state).toBe("USED_UP");
|
||||
});
|
||||
|
||||
@@ -108,7 +108,10 @@ export const PATCH = apiHandler(
|
||||
// state-machine re-run below owns every state consequence (0 ⇒
|
||||
// USED_UP, a raise out of 0 re-evaluates against the expiry
|
||||
// clocks).
|
||||
nextUnitsRemaining = Math.min(unitsRemaining, Number(existing.unitsTotal));
|
||||
nextUnitsRemaining = Math.min(
|
||||
unitsRemaining,
|
||||
Number(existing.unitsTotal),
|
||||
);
|
||||
}
|
||||
|
||||
if (markAsUsedUp === true) {
|
||||
|
||||
@@ -360,9 +360,12 @@ describe("DELETE /api/medications/[id]/inventory/[itemId]", () => {
|
||||
} as never);
|
||||
|
||||
const res = await DELETE(
|
||||
new NextRequest("http://localhost/api/medications/med-1/inventory/inv-1", {
|
||||
method: "DELETE",
|
||||
}),
|
||||
new NextRequest(
|
||||
"http://localhost/api/medications/med-1/inventory/inv-1",
|
||||
{
|
||||
method: "DELETE",
|
||||
},
|
||||
),
|
||||
{ params: Promise.resolve({ id: "med-1", itemId: "inv-1" }) },
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
@@ -109,7 +109,8 @@ describe("PUT /api/medications/[id]/phase-config — F-1 H-4 field-by-field upse
|
||||
};
|
||||
await PUT(putReq(body), ROUTE_PARAMS);
|
||||
|
||||
const callArg = vi.mocked(prisma.reminderPhaseConfig.upsert).mock.calls[0][0];
|
||||
const callArg = vi.mocked(prisma.reminderPhaseConfig.upsert).mock
|
||||
.calls[0][0];
|
||||
// create payload contains exactly the eight enumerated phase fields
|
||||
// plus the `medicationId` route binding — nothing else.
|
||||
expect(Object.keys(callArg.create).sort()).toEqual([
|
||||
@@ -150,8 +151,13 @@ describe("PUT /api/medications/[id]/phase-config — F-1 H-4 field-by-field upse
|
||||
maliciousField: "owned",
|
||||
};
|
||||
await PUT(putReq(body), ROUTE_PARAMS);
|
||||
const callArg = vi.mocked(prisma.reminderPhaseConfig.upsert).mock.calls[0][0];
|
||||
expect((callArg.create as Record<string, unknown>).maliciousField).toBeUndefined();
|
||||
expect((callArg.update as Record<string, unknown>).maliciousField).toBeUndefined();
|
||||
const callArg = vi.mocked(prisma.reminderPhaseConfig.upsert).mock
|
||||
.calls[0][0];
|
||||
expect(
|
||||
(callArg.create as Record<string, unknown>).maliciousField,
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
(callArg.update as Record<string, unknown>).maliciousField,
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -369,7 +369,9 @@ export const PUT = apiHandler(
|
||||
|
||||
// Invariant 3 — dual-write timesOfDay from windowStart.
|
||||
const effectiveTimesOfDay =
|
||||
s.timesOfDay && s.timesOfDay.length > 0 ? s.timesOfDay : [s.windowStart];
|
||||
s.timesOfDay && s.timesOfDay.length > 0
|
||||
? s.timesOfDay
|
||||
: [s.windowStart];
|
||||
|
||||
// Invariant 4 — window / times consistency. See
|
||||
// `reconcileScheduleWindow`: a times-only edit that echoes the
|
||||
@@ -571,11 +573,18 @@ export const PUT = apiHandler(
|
||||
// key). Best-effort like every other rollup write-hook: a failure
|
||||
// is annotated, never blocks the schedule replace.
|
||||
const staleDayKeys = new Set(
|
||||
tombstoned.map((row) => dayKeyForScheduledFor(row.scheduledFor, userTz)),
|
||||
tombstoned.map((row) =>
|
||||
dayKeyForScheduledFor(row.scheduledFor, userTz),
|
||||
),
|
||||
);
|
||||
for (const dayKey of staleDayKeys) {
|
||||
try {
|
||||
await recomputeMedicationComplianceForDay(user.id, id, dayKey, userTz);
|
||||
await recomputeMedicationComplianceForDay(
|
||||
user.id,
|
||||
id,
|
||||
dayKey,
|
||||
userTz,
|
||||
);
|
||||
} catch (err) {
|
||||
annotate({
|
||||
meta: {
|
||||
|
||||
@@ -147,10 +147,10 @@ export const PATCH = apiHandler(
|
||||
// `createdAt`). The edited era's own recorded end counts — an
|
||||
// ARCHIVED era adjacent to the live plan may keep its boundary,
|
||||
// but no correction may extend into tracked live history.
|
||||
const liveBoundary = [target.validUntil, ...others.map((r) => r.validUntil)].reduce(
|
||||
(latest, v) => (v > latest ? v : latest),
|
||||
med.createdAt,
|
||||
);
|
||||
const liveBoundary = [
|
||||
target.validUntil,
|
||||
...others.map((r) => r.validUntil),
|
||||
].reduce((latest, v) => (v > latest ? v : latest), med.createdAt);
|
||||
if (validUntil.getTime() > liveBoundary.getTime()) {
|
||||
return {
|
||||
ok: false as const,
|
||||
@@ -290,10 +290,7 @@ export const DELETE = apiHandler(
|
||||
}
|
||||
|
||||
if (revision.source !== "MANUAL") {
|
||||
return apiError(
|
||||
"Only manually added schedule eras can be deleted",
|
||||
409,
|
||||
);
|
||||
return apiError("Only manually added schedule eras can be deleted", 409);
|
||||
}
|
||||
|
||||
// Deleting a correction restores the archived original it had
|
||||
|
||||
@@ -325,8 +325,8 @@ describe("POST /api/medications/[id]/schedule-revisions", () => {
|
||||
const res = await POST(postReq(VALID_BODY), ROUTE_CTX);
|
||||
expect(res.status).toBe(201);
|
||||
|
||||
const createArgs = vi.mocked(prisma.medicationScheduleRevision.create)
|
||||
.mock.calls[0][0] as unknown as {
|
||||
const createArgs = vi.mocked(prisma.medicationScheduleRevision.create).mock
|
||||
.calls[0][0] as unknown as {
|
||||
data: {
|
||||
medicationId: string;
|
||||
source: string;
|
||||
@@ -374,8 +374,8 @@ describe("POST /api/medications/[id]/schedule-revisions", () => {
|
||||
ROUTE_CTX,
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
const createArgs = vi.mocked(prisma.medicationScheduleRevision.create)
|
||||
.mock.calls[0][0] as unknown as {
|
||||
const createArgs = vi.mocked(prisma.medicationScheduleRevision.create).mock
|
||||
.calls[0][0] as unknown as {
|
||||
data: { payload: Array<{ timesOfDay: string[] }> };
|
||||
};
|
||||
// The Zod transform dedupes + sorts — a double-tapped chip must
|
||||
@@ -386,9 +386,7 @@ describe("POST /api/medications/[id]/schedule-revisions", () => {
|
||||
|
||||
describe("DELETE /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
it("404s when the revision belongs to another medication", async () => {
|
||||
vi.mocked(
|
||||
prisma.medicationScheduleRevision.findUnique,
|
||||
).mockResolvedValue({
|
||||
vi.mocked(prisma.medicationScheduleRevision.findUnique).mockResolvedValue({
|
||||
id: "rev-x",
|
||||
medicationId: "other-med",
|
||||
source: "MANUAL",
|
||||
@@ -399,9 +397,7 @@ describe("DELETE /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
});
|
||||
|
||||
it("409s for a write-path archive", async () => {
|
||||
vi.mocked(
|
||||
prisma.medicationScheduleRevision.findUnique,
|
||||
).mockResolvedValue({
|
||||
vi.mocked(prisma.medicationScheduleRevision.findUnique).mockResolvedValue({
|
||||
id: "rev-a",
|
||||
medicationId: "m1",
|
||||
source: "ARCHIVED",
|
||||
@@ -412,9 +408,7 @@ describe("DELETE /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
});
|
||||
|
||||
it("deletes a MANUAL era, restores a superseded original, and enqueues the rollup backfill", async () => {
|
||||
vi.mocked(
|
||||
prisma.medicationScheduleRevision.findUnique,
|
||||
).mockResolvedValue({
|
||||
vi.mocked(prisma.medicationScheduleRevision.findUnique).mockResolvedValue({
|
||||
id: "rev-m",
|
||||
medicationId: "m1",
|
||||
source: "MANUAL",
|
||||
@@ -422,9 +416,9 @@ describe("DELETE /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
vi.mocked(prisma.medicationScheduleRevision.delete).mockResolvedValue(
|
||||
{} as never,
|
||||
);
|
||||
vi.mocked(
|
||||
prisma.medicationScheduleRevision.updateMany,
|
||||
).mockResolvedValue({ count: 0 } as never);
|
||||
vi.mocked(prisma.medicationScheduleRevision.updateMany).mockResolvedValue({
|
||||
count: 0,
|
||||
} as never);
|
||||
const res = await DELETE(deleteReq("rev-m"), deleteCtx("rev-m"));
|
||||
expect(res.status).toBe(200);
|
||||
const json = await res.json();
|
||||
@@ -452,9 +446,7 @@ describe("PATCH /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
};
|
||||
|
||||
function mockTarget(overrides: Record<string, unknown> = {}) {
|
||||
vi.mocked(
|
||||
prisma.medicationScheduleRevision.findUnique,
|
||||
).mockResolvedValue({
|
||||
vi.mocked(prisma.medicationScheduleRevision.findUnique).mockResolvedValue({
|
||||
id: "rev-t",
|
||||
medicationId: "m1",
|
||||
source: "MANUAL",
|
||||
@@ -466,20 +458,14 @@ describe("PATCH /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
|
||||
it("404s when the revision belongs to another medication", async () => {
|
||||
mockTarget({ medicationId: "other-med" });
|
||||
const res = await PATCH(
|
||||
patchReq("rev-t", PATCH_BODY),
|
||||
deleteCtx("rev-t"),
|
||||
);
|
||||
const res = await PATCH(patchReq("rev-t", PATCH_BODY), deleteCtx("rev-t"));
|
||||
expect(res.status).toBe(404);
|
||||
expect(prisma.medicationScheduleRevision.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("409s when the era has already been corrected", async () => {
|
||||
mockTarget({ source: "ARCHIVED", supersededByRevisionId: "rev-fix" });
|
||||
const res = await PATCH(
|
||||
patchReq("rev-t", PATCH_BODY),
|
||||
deleteCtx("rev-t"),
|
||||
);
|
||||
const res = await PATCH(patchReq("rev-t", PATCH_BODY), deleteCtx("rev-t"));
|
||||
expect(res.status).toBe(409);
|
||||
expect(prisma.medicationScheduleRevision.update).not.toHaveBeenCalled();
|
||||
expect(prisma.medicationScheduleRevision.create).not.toHaveBeenCalled();
|
||||
@@ -494,7 +480,10 @@ describe("PATCH /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
},
|
||||
] as never);
|
||||
const res = await PATCH(
|
||||
patchReq("rev-t", { ...PATCH_BODY, validUntil: "2025-07-01T00:00:00.000Z" }),
|
||||
patchReq("rev-t", {
|
||||
...PATCH_BODY,
|
||||
validUntil: "2025-07-01T00:00:00.000Z",
|
||||
}),
|
||||
deleteCtx("rev-t"),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
@@ -528,17 +517,14 @@ describe("PATCH /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
source: "MANUAL",
|
||||
} as never);
|
||||
|
||||
const res = await PATCH(
|
||||
patchReq("rev-t", PATCH_BODY),
|
||||
deleteCtx("rev-t"),
|
||||
);
|
||||
const res = await PATCH(patchReq("rev-t", PATCH_BODY), deleteCtx("rev-t"));
|
||||
expect(res.status).toBe(200);
|
||||
const json = await res.json();
|
||||
expect(json.data.id).toBe("rev-t");
|
||||
expect(json.data.entries[0].timesOfDay).toEqual(["08:00", "20:00"]);
|
||||
|
||||
const updateArgs = vi.mocked(prisma.medicationScheduleRevision.update)
|
||||
.mock.calls[0][0] as unknown as {
|
||||
const updateArgs = vi.mocked(prisma.medicationScheduleRevision.update).mock
|
||||
.calls[0][0] as unknown as {
|
||||
where: { id: string };
|
||||
data: { payload: Array<{ timesOfDay: string[]; rrule: string }> };
|
||||
};
|
||||
@@ -567,10 +553,7 @@ describe("PATCH /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
{} as never,
|
||||
);
|
||||
|
||||
const res = await PATCH(
|
||||
patchReq("rev-t", PATCH_BODY),
|
||||
deleteCtx("rev-t"),
|
||||
);
|
||||
const res = await PATCH(patchReq("rev-t", PATCH_BODY), deleteCtx("rev-t"));
|
||||
expect(res.status).toBe(200);
|
||||
const json = await res.json();
|
||||
// The response carries the correction, which now takes the
|
||||
@@ -578,8 +561,8 @@ describe("PATCH /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
expect(json.data.id).toBe("rev-fix");
|
||||
expect(json.data.source).toBe("MANUAL");
|
||||
|
||||
const createArgs = vi.mocked(prisma.medicationScheduleRevision.create)
|
||||
.mock.calls[0][0] as unknown as {
|
||||
const createArgs = vi.mocked(prisma.medicationScheduleRevision.create).mock
|
||||
.calls[0][0] as unknown as {
|
||||
data: { source: string; payload: Array<{ timesOfDay: string[] }> };
|
||||
};
|
||||
expect(createArgs.data.source).toBe("MANUAL");
|
||||
|
||||
@@ -65,7 +65,8 @@ function summariseEntries(payload: unknown): Array<{
|
||||
: [],
|
||||
label: typeof e.label === "string" ? e.label : null,
|
||||
dose: typeof e.dose === "string" ? e.dose : null,
|
||||
scheduleType: typeof e.scheduleType === "string" ? e.scheduleType : "SCHEDULED",
|
||||
scheduleType:
|
||||
typeof e.scheduleType === "string" ? e.scheduleType : "SCHEDULED",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -142,7 +142,8 @@ describe("GET /api/medications/[id]/side-effects", () => {
|
||||
{ params: Promise.resolve({ id: "med-1" }) },
|
||||
);
|
||||
|
||||
const call = vi.mocked(prisma.medicationSideEffect.findMany).mock.calls[0][0];
|
||||
const call = vi.mocked(prisma.medicationSideEffect.findMany).mock
|
||||
.calls[0][0];
|
||||
expect(call).toMatchObject({
|
||||
where: {
|
||||
userId: "user-1",
|
||||
|
||||
@@ -94,9 +94,9 @@ beforeEach(() => {
|
||||
// Default happy-path stub: return the data shape the caller passed in
|
||||
// so test assertions can inspect what the route actually forwarded
|
||||
// to Prisma without re-implementing the create-returning DB.
|
||||
vi.mocked(prisma.medication.create).mockImplementation((async (
|
||||
args: { data: Record<string, unknown> },
|
||||
) => ({
|
||||
vi.mocked(prisma.medication.create).mockImplementation((async (args: {
|
||||
data: Record<string, unknown>;
|
||||
}) => ({
|
||||
id: "med-1",
|
||||
userId: "user-1",
|
||||
...args.data,
|
||||
@@ -463,9 +463,7 @@ describe("POST /api/medications — as-needed (v1.16.11, #316)", () => {
|
||||
details: { issues: Array<{ message: string }> };
|
||||
};
|
||||
expect(
|
||||
body.details.issues.some((i) =>
|
||||
i.message.includes("mutually exclusive"),
|
||||
),
|
||||
body.details.issues.some((i) => i.message.includes("mutually exclusive")),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
@@ -494,8 +492,8 @@ describe("POST /api/medications — as-needed (v1.16.11, #316)", () => {
|
||||
const body = (await res.json()) as {
|
||||
details: { issues: Array<{ path: string; message: string }> };
|
||||
};
|
||||
expect(
|
||||
body.details.issues.some((i) => i.path.includes("schedules")),
|
||||
).toBe(true);
|
||||
expect(body.details.issues.some((i) => i.path.includes("schedules"))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -9,11 +9,7 @@ import {
|
||||
complianceCacheKey,
|
||||
type CompliancePayload,
|
||||
} from "@/lib/medications/compliance-payload";
|
||||
import {
|
||||
cachedSwr,
|
||||
caches,
|
||||
type ServerCache,
|
||||
} from "@/lib/cache/server-cache";
|
||||
import { cachedSwr, caches, type ServerCache } from "@/lib/cache/server-cache";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
/**
|
||||
|
||||
@@ -52,10 +52,9 @@ vi.mock("@/lib/ai/consent-guard", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/ai/provider-runner", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("@/lib/ai/provider-runner")>(
|
||||
"@/lib/ai/provider-runner",
|
||||
);
|
||||
const actual = await vi.importActual<
|
||||
typeof import("@/lib/ai/provider-runner")
|
||||
>("@/lib/ai/provider-runner");
|
||||
return {
|
||||
...actual,
|
||||
runRawCompletionWithFallback: vi.fn(),
|
||||
@@ -65,17 +64,17 @@ vi.mock("@/lib/ai/provider-runner", async () => {
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
getEvent: vi.fn(() => null),
|
||||
eventStorage: { getStore: () => undefined, run: (_s: unknown, f: () => unknown) => f() },
|
||||
eventStorage: {
|
||||
getStore: () => undefined,
|
||||
run: (_s: unknown, f: () => unknown) => f(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { requireAuth, HttpError } from "@/lib/api-handler";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { enforceBudget } from "@/lib/ai/coach/budget";
|
||||
import {
|
||||
resolveProvider,
|
||||
resolveProviderChain,
|
||||
} from "@/lib/ai/provider";
|
||||
import { resolveProvider, resolveProviderChain } from "@/lib/ai/provider";
|
||||
import { runRawCompletionWithFallback } from "@/lib/ai/provider-runner";
|
||||
import { assertConsentForChain } from "@/lib/ai/consent-guard";
|
||||
|
||||
@@ -136,9 +135,7 @@ describe("POST /api/medications/extract — rate limit", () => {
|
||||
remaining: 0,
|
||||
resetAt: Date.now() + 60_000,
|
||||
});
|
||||
const res = await POST(
|
||||
postReq({ text: "Mounjaro 5mg weekly" }) as never,
|
||||
);
|
||||
const res = await POST(postReq({ text: "Mounjaro 5mg weekly" }) as never);
|
||||
expect(res.status).toBe(429);
|
||||
const body = await res.json();
|
||||
expect(body.error).toMatch(/Too many requests/i);
|
||||
@@ -233,9 +230,7 @@ describe("POST /api/medications/extract — validation + provider errors", () =>
|
||||
type: "none",
|
||||
} as never);
|
||||
|
||||
const res = await POST(
|
||||
postReq({ text: "Mounjaro 5mg weekly" }) as never,
|
||||
);
|
||||
const res = await POST(postReq({ text: "Mounjaro 5mg weekly" }) as never);
|
||||
expect(res.status).toBe(503);
|
||||
});
|
||||
|
||||
@@ -252,9 +247,7 @@ describe("POST /api/medications/extract — validation + provider errors", () =>
|
||||
fallbackHops: [],
|
||||
});
|
||||
|
||||
const res = await POST(
|
||||
postReq({ text: "Mounjaro 5mg weekly" }) as never,
|
||||
);
|
||||
const res = await POST(postReq({ text: "Mounjaro 5mg weekly" }) as never);
|
||||
expect(res.status).toBe(502);
|
||||
});
|
||||
});
|
||||
@@ -466,7 +466,9 @@ describe("POST /api/medications/intake", () => {
|
||||
scheduleRevisions: [],
|
||||
} as never);
|
||||
vi.mocked(prisma.$transaction).mockImplementation(async (arg: unknown) =>
|
||||
Array.isArray(arg) ? Promise.all(arg) : (arg as (c: unknown) => unknown)(prisma),
|
||||
Array.isArray(arg)
|
||||
? Promise.all(arg)
|
||||
: (arg as (c: unknown) => unknown)(prisma),
|
||||
);
|
||||
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValue({
|
||||
id: "e1",
|
||||
@@ -561,10 +563,10 @@ describe("POST /api/medications/intake", () => {
|
||||
expect.objectContaining({ eventId: "e2" }),
|
||||
);
|
||||
// The refund runs BEFORE the tombstone write on the source row.
|
||||
const restoreOrder = vi.mocked(restoreForIntake).mock
|
||||
const restoreOrder =
|
||||
vi.mocked(restoreForIntake).mock.invocationCallOrder[0];
|
||||
const tombstoneOrder = vi.mocked(prisma.medicationIntakeEvent.update).mock
|
||||
.invocationCallOrder[0];
|
||||
const tombstoneOrder = vi.mocked(prisma.medicationIntakeEvent.update)
|
||||
.mock.invocationCallOrder[0];
|
||||
expect(restoreOrder).toBeLessThan(tombstoneOrder);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -695,7 +695,10 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
// outstanding, so it neither clears the reminder nor changes the badge.
|
||||
if (status === "taken" || status === "skipped") {
|
||||
void (async () => {
|
||||
const badgeCount = await countOutstandingDosesToday(user.id, userTzForHook);
|
||||
const badgeCount = await countOutstandingDosesToday(
|
||||
user.id,
|
||||
userTzForHook,
|
||||
);
|
||||
await dispatchMedicationIntakeWebClear({
|
||||
userId: user.id,
|
||||
medicationId: existing.medicationId,
|
||||
|
||||
@@ -63,90 +63,90 @@ async function buildMedicationsList(
|
||||
usableStock,
|
||||
inventoryCounts,
|
||||
] = await Promise.all([
|
||||
prisma.medication.findMany({
|
||||
where: { userId },
|
||||
include: { schedules: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
prisma.medicationIntakeEvent.groupBy({
|
||||
by: ["medicationId"],
|
||||
// v1.7.0 sync — exclude tombstoned rows from the last-taken map.
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
skipped: false,
|
||||
takenAt: { not: null },
|
||||
},
|
||||
_max: { takenAt: true },
|
||||
}),
|
||||
prisma.medicationIntakeEvent.groupBy({
|
||||
by: ["medicationId"],
|
||||
// v1.7.0 sync — exclude tombstoned rows from the today-count map.
|
||||
// v1.16.9 — count only ACTIONED rows (taken or skipped). The
|
||||
// dashboard projector mints pending rows for every slot of the
|
||||
// day, so counting all rows made `todayEventCount` cover every
|
||||
// passed dose after any dashboard visit — and the cards'
|
||||
// overdue-pill suppression (`todayEventCount < passedDoseCount`)
|
||||
// went dark nondeterministically for genuinely overdue doses.
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
scheduledFor: { gte: todayStartUtc, lte: todayEndUtc },
|
||||
OR: [{ takenAt: { not: null } }, { skipped: true }],
|
||||
},
|
||||
_count: { id: true },
|
||||
}),
|
||||
prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
scheduledFor: { gte: resolvedWindowStart, lte: resolvedWindowEnd },
|
||||
OR: [
|
||||
{ takenAt: { not: null } },
|
||||
{ skipped: true },
|
||||
{ autoMissed: true },
|
||||
],
|
||||
},
|
||||
// v1.16.9 — `takenAt` rides along so the ad-hoc shape
|
||||
// (`scheduledFor === takenAt`) is detectable: such a row must not
|
||||
// ±6h-resolve a DIFFERENT slot (a 14:30 ad-hoc take hid tonight's
|
||||
// genuinely-due 20:00 dose).
|
||||
select: { medicationId: true, scheduledFor: true, takenAt: true },
|
||||
}),
|
||||
// v1.16.4 — current-era floor per medication: the newest revision's
|
||||
// `validUntil` is where the LIVE schedule rows became valid. The
|
||||
// open-overdue search mints from the live rows, so it must not reach
|
||||
// past this boundary into a previous era's cadence.
|
||||
prisma.medicationScheduleRevision.groupBy({
|
||||
by: ["medicationId"],
|
||||
// Superseded rows are audit records — a correction may have
|
||||
// shortened the era, so the boundary reads only active rows.
|
||||
where: { medication: { userId }, supersededByRevisionId: null },
|
||||
_max: { validUntil: true },
|
||||
}),
|
||||
// v1.16.10 — usable stock per medication (one batched aggregate,
|
||||
// not per-row): the sum of `unitsRemaining` over ACTIVE / IN_USE
|
||||
// containers with units left — the same usable-container filter
|
||||
// the GLP-1 details endpoint applies. Feeds the list payload's
|
||||
// `stockUnitsRemaining` / `stockDosesRemaining` for the table view.
|
||||
prisma.medicationInventoryItem.groupBy({
|
||||
by: ["medicationId"],
|
||||
where: {
|
||||
userId,
|
||||
state: { in: ["ACTIVE", "IN_USE"] },
|
||||
unitsRemaining: { gt: 0 },
|
||||
},
|
||||
_sum: { unitsRemaining: true },
|
||||
}),
|
||||
// …and the any-state item count, so a medication whose containers
|
||||
// are all used up / expired reads as stock 0 (tracking is ON, the
|
||||
// supply ran out) instead of null (tracking off).
|
||||
prisma.medicationInventoryItem.groupBy({
|
||||
by: ["medicationId"],
|
||||
where: { userId },
|
||||
_count: { id: true },
|
||||
}),
|
||||
]);
|
||||
prisma.medication.findMany({
|
||||
where: { userId },
|
||||
include: { schedules: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
prisma.medicationIntakeEvent.groupBy({
|
||||
by: ["medicationId"],
|
||||
// v1.7.0 sync — exclude tombstoned rows from the last-taken map.
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
skipped: false,
|
||||
takenAt: { not: null },
|
||||
},
|
||||
_max: { takenAt: true },
|
||||
}),
|
||||
prisma.medicationIntakeEvent.groupBy({
|
||||
by: ["medicationId"],
|
||||
// v1.7.0 sync — exclude tombstoned rows from the today-count map.
|
||||
// v1.16.9 — count only ACTIONED rows (taken or skipped). The
|
||||
// dashboard projector mints pending rows for every slot of the
|
||||
// day, so counting all rows made `todayEventCount` cover every
|
||||
// passed dose after any dashboard visit — and the cards'
|
||||
// overdue-pill suppression (`todayEventCount < passedDoseCount`)
|
||||
// went dark nondeterministically for genuinely overdue doses.
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
scheduledFor: { gte: todayStartUtc, lte: todayEndUtc },
|
||||
OR: [{ takenAt: { not: null } }, { skipped: true }],
|
||||
},
|
||||
_count: { id: true },
|
||||
}),
|
||||
prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
scheduledFor: { gte: resolvedWindowStart, lte: resolvedWindowEnd },
|
||||
OR: [
|
||||
{ takenAt: { not: null } },
|
||||
{ skipped: true },
|
||||
{ autoMissed: true },
|
||||
],
|
||||
},
|
||||
// v1.16.9 — `takenAt` rides along so the ad-hoc shape
|
||||
// (`scheduledFor === takenAt`) is detectable: such a row must not
|
||||
// ±6h-resolve a DIFFERENT slot (a 14:30 ad-hoc take hid tonight's
|
||||
// genuinely-due 20:00 dose).
|
||||
select: { medicationId: true, scheduledFor: true, takenAt: true },
|
||||
}),
|
||||
// v1.16.4 — current-era floor per medication: the newest revision's
|
||||
// `validUntil` is where the LIVE schedule rows became valid. The
|
||||
// open-overdue search mints from the live rows, so it must not reach
|
||||
// past this boundary into a previous era's cadence.
|
||||
prisma.medicationScheduleRevision.groupBy({
|
||||
by: ["medicationId"],
|
||||
// Superseded rows are audit records — a correction may have
|
||||
// shortened the era, so the boundary reads only active rows.
|
||||
where: { medication: { userId }, supersededByRevisionId: null },
|
||||
_max: { validUntil: true },
|
||||
}),
|
||||
// v1.16.10 — usable stock per medication (one batched aggregate,
|
||||
// not per-row): the sum of `unitsRemaining` over ACTIVE / IN_USE
|
||||
// containers with units left — the same usable-container filter
|
||||
// the GLP-1 details endpoint applies. Feeds the list payload's
|
||||
// `stockUnitsRemaining` / `stockDosesRemaining` for the table view.
|
||||
prisma.medicationInventoryItem.groupBy({
|
||||
by: ["medicationId"],
|
||||
where: {
|
||||
userId,
|
||||
state: { in: ["ACTIVE", "IN_USE"] },
|
||||
unitsRemaining: { gt: 0 },
|
||||
},
|
||||
_sum: { unitsRemaining: true },
|
||||
}),
|
||||
// …and the any-state item count, so a medication whose containers
|
||||
// are all used up / expired reads as stock 0 (tracking is ON, the
|
||||
// supply ran out) instead of null (tracking off).
|
||||
prisma.medicationInventoryItem.groupBy({
|
||||
by: ["medicationId"],
|
||||
where: { userId },
|
||||
_count: { id: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const resolvedSlotsByMedId = new Map<string, ResolvedSlotMark[]>();
|
||||
for (const e of resolvedEvents) {
|
||||
@@ -158,7 +158,8 @@ async function buildMedicationsList(
|
||||
|
||||
const eraStartByMedId = new Map<string, Date>();
|
||||
for (const f of eraFloors) {
|
||||
if (f._max.validUntil) eraStartByMedId.set(f.medicationId, f._max.validUntil);
|
||||
if (f._max.validUntil)
|
||||
eraStartByMedId.set(f.medicationId, f._max.validUntil);
|
||||
}
|
||||
|
||||
const lastTakenAtByMedicationId = Object.fromEntries(
|
||||
@@ -354,10 +355,7 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
);
|
||||
}
|
||||
const s = scheduleInputs[0];
|
||||
if (
|
||||
s &&
|
||||
(s.rrule !== undefined || s.rollingIntervalDays !== undefined)
|
||||
) {
|
||||
if (s && (s.rrule !== undefined || s.rollingIntervalDays !== undefined)) {
|
||||
return apiError(
|
||||
"A one-shot medication cannot have a recurrence (rrule or rollingIntervalDays)",
|
||||
422,
|
||||
|
||||
Reference in new issue
Block a user