mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
fix(meds): reconcile one-shot active flag on every intake mutation
Extracts the lifecycle hook into reconcileOneShotState and wires it into POST, PUT, and DELETE on the intake event. A user who logs the single dose then undoes the log gets the medication back; a user who flips skipped does too. The hook is idempotent on non-one-shot medications. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
c7e839f97a
commit
1cc6f500bb
6 files changed
+425
-31
No files matched your search
@@ -11,6 +11,11 @@ vi.mock("@/lib/db", () => ({
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
medication: {
|
||||
findUnique: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
auditLog: { create: vi.fn() },
|
||||
},
|
||||
@@ -39,9 +44,10 @@ vi.mock("next/headers", () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
import { PUT } from "../route";
|
||||
import { PUT, DELETE } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
@@ -70,6 +76,18 @@ beforeEach(() => {
|
||||
medicationId: "m1",
|
||||
scheduledFor: new Date(),
|
||||
} as never);
|
||||
// Default lifecycle stubs: medication is NOT one-shot so the
|
||||
// reconcile is a no-op for the legacy 422-envelope tests below.
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
|
||||
oneShot: false,
|
||||
active: true,
|
||||
} as never);
|
||||
vi.mocked(prisma.medication.updateMany).mockResolvedValue({
|
||||
count: 0,
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValue(
|
||||
null as never,
|
||||
);
|
||||
});
|
||||
|
||||
describe("PUT /api/medications/[id]/intake/[eventId] — 422 multi-issue (v1.4.43 W6)", () => {
|
||||
@@ -139,3 +157,81 @@ describe("PUT /api/medications/[id]/intake/[eventId] — 422 multi-issue (v1.4.4
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
});
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
// v1.5.0 — one-shot lifecycle reconciliation on PUT / DELETE
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
|
||||
function deleteReq(): NextRequest {
|
||||
return new NextRequest("http://localhost/api/medications/m1/intake/e1", {
|
||||
method: "DELETE",
|
||||
});
|
||||
}
|
||||
|
||||
describe("DELETE /api/medications/[id]/intake/[eventId] — one-shot reconcile", () => {
|
||||
it("re-activates a one-shot medication after the deleted event was its last live intake", async () => {
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValueOnce({
|
||||
oneShot: true,
|
||||
active: false,
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValueOnce(
|
||||
null as never,
|
||||
);
|
||||
vi.mocked(prisma.medication.updateMany).mockResolvedValueOnce({
|
||||
count: 1,
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.delete).mockResolvedValueOnce(
|
||||
{} as never,
|
||||
);
|
||||
|
||||
const res = await DELETE(deleteReq(), ROUTE_CTX);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
expect(prisma.medication.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: "m1", userId: "user-1", oneShot: true },
|
||||
data: { active: true },
|
||||
});
|
||||
const calls = vi.mocked(auditLog).mock.calls.map((c) => c[0]);
|
||||
expect(calls).toContain("medication.oneShot.reconciled");
|
||||
});
|
||||
|
||||
it("is idempotent on a non-one-shot medication", async () => {
|
||||
// Default beforeEach: medication is non-one-shot.
|
||||
vi.mocked(prisma.medicationIntakeEvent.delete).mockResolvedValueOnce(
|
||||
{} as never,
|
||||
);
|
||||
const res = await DELETE(deleteReq(), ROUTE_CTX);
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.medication.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/medications/[id]/intake/[eventId] — one-shot reconcile on skip flip", () => {
|
||||
it("re-activates a one-shot medication when its single intake is flipped to skipped", async () => {
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValueOnce({
|
||||
oneShot: true,
|
||||
active: false,
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValueOnce(
|
||||
null as never,
|
||||
);
|
||||
vi.mocked(prisma.medication.updateMany).mockResolvedValueOnce({
|
||||
count: 1,
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
|
||||
id: "e1",
|
||||
userId: "user-1",
|
||||
medicationId: "m1",
|
||||
skipped: true,
|
||||
takenAt: null,
|
||||
} as never);
|
||||
|
||||
const res = await PUT(putReq({ skipped: true, takenAt: null }), ROUTE_CTX);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
expect(prisma.medication.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: "m1", userId: "user-1", oneShot: true },
|
||||
data: { active: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
sanitiseZodIssues,
|
||||
} from "@/lib/api-response";
|
||||
import { updateIntakeEventSchema } from "@/lib/validations/medication";
|
||||
import { reconcileOneShotState } from "@/lib/medications/lifecycle";
|
||||
import { invalidateUserMedications } from "@/lib/cache/invalidate";
|
||||
import { recomputeMedicationComplianceForEvent } from "@/lib/rollups/medication-compliance-rollups";
|
||||
import { NextRequest } from "next/server";
|
||||
@@ -119,6 +120,12 @@ export const PUT = apiHandler(
|
||||
});
|
||||
}
|
||||
|
||||
// v1.5.0 — re-evaluate the one-shot active flag. A skip-flip on the
|
||||
// single live intake of a one-shot medication should reactivate it
|
||||
// (the dose is no longer logged), and the reverse case should
|
||||
// deactivate again. No-op for non-one-shot medications.
|
||||
await reconcileOneShotState(prisma, id, user.id);
|
||||
|
||||
return apiSuccess(updated);
|
||||
},
|
||||
);
|
||||
@@ -169,6 +176,12 @@ export const DELETE = apiHandler(
|
||||
tz: user.timezone,
|
||||
});
|
||||
|
||||
// v1.5.0 — re-evaluate the one-shot active flag. Deleting the
|
||||
// single live intake of a one-shot medication reactivates it so
|
||||
// the dashboard / lists / worker pick it back up. No-op for
|
||||
// non-one-shot medications.
|
||||
await reconcileOneShotState(prisma, id, user.id);
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
},
|
||||
);
|
||||
@@ -24,7 +24,11 @@ import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
medication: { findUnique: vi.fn() },
|
||||
medication: {
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
medicationIntakeEvent: {
|
||||
findMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
@@ -266,3 +270,56 @@ describe("v1.4.43 W6 — multi-issue 422 envelope", () => {
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
});
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
// v1.5.0 — POST intake on a one-shot medication still deactivates
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("POST /api/medications/[id]/intake — one-shot lifecycle", () => {
|
||||
function postReq(body: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/medications/med-1/intake", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
it("flips active to false after logging a live intake on a one-shot medication", async () => {
|
||||
const createdEvent = {
|
||||
id: "evt-1",
|
||||
userId: "user-1",
|
||||
medicationId: "med-1",
|
||||
scheduledFor: new Date(),
|
||||
takenAt: new Date(),
|
||||
skipped: false,
|
||||
};
|
||||
vi.mocked(prisma.$transaction).mockResolvedValue([createdEvent] as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValueOnce(
|
||||
null as never, // dedup probe
|
||||
);
|
||||
// Reconcile probes — first call is the medication shape, second is
|
||||
// the live-intake probe (a live intake exists because the POST just
|
||||
// created one), and the update fires with active:false.
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValueOnce({
|
||||
oneShot: true,
|
||||
active: true,
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValueOnce({
|
||||
id: "evt-1",
|
||||
} as never);
|
||||
vi.mocked(prisma.medication.updateMany).mockResolvedValueOnce({
|
||||
count: 1,
|
||||
} as never);
|
||||
|
||||
const res = await POST(
|
||||
postReq({ takenAt: new Date().toISOString(), skipped: false }),
|
||||
ROUTE_PARAMS,
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
|
||||
expect(prisma.medication.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: "med-1", userId: "user-1", oneShot: true },
|
||||
data: { active: false },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
} from "@/lib/validations/medication";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { consumeOneDose } from "@/lib/medications/inventory/service";
|
||||
import { reconcileOneShotState } from "@/lib/medications/lifecycle";
|
||||
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
|
||||
import { invalidateUserMedications } from "@/lib/cache/invalidate";
|
||||
import { recomputeMedicationComplianceForEvent } from "@/lib/rollups/medication-compliance-rollups";
|
||||
@@ -197,35 +198,15 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
|
||||
tz: user.timezone,
|
||||
});
|
||||
|
||||
// v1.5.0 — one-shot lifecycle. A `oneShot` medication has at most
|
||||
// one intake; once that intake is logged (non-skipped) the
|
||||
// medication auto-deactivates so the reminder worker stops
|
||||
// considering it and the dashboard "Erfassen" sheet drops it. The
|
||||
// flip runs AFTER the intake row is committed (any failure inside
|
||||
// the transaction above re-raises before this line), so a flaky
|
||||
// write never deactivates a medication that didn't actually
|
||||
// receive its dose. Skipped intakes don't qualify — a "skipped"
|
||||
// event on a one-shot leaves the medication open for the eventual
|
||||
// real dose.
|
||||
const medForOneShotCheck = await prisma.medication.findUnique({
|
||||
where: { id },
|
||||
select: { oneShot: true, active: true },
|
||||
});
|
||||
if (medForOneShotCheck?.oneShot && medForOneShotCheck.active && !skipped) {
|
||||
await prisma.medication.update({
|
||||
where: { id },
|
||||
data: { active: false },
|
||||
});
|
||||
await auditLog("medication.oneShot.deactivated", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { medicationId: id, eventId: event.id },
|
||||
});
|
||||
annotate({
|
||||
action: { name: "medication.oneShot.deactivated" },
|
||||
meta: { medication_id: id, event_id: event.id },
|
||||
});
|
||||
// Invalidate again so the next list-meds read sees the flip.
|
||||
// v1.5.0 — one-shot lifecycle reconciliation. A `oneShot` medication
|
||||
// has at most one live intake; the helper re-reads the most recent
|
||||
// non-skipped intake and flips `active` to match. Idempotent on
|
||||
// non-one-shot medications (the underlying updateMany is gated by
|
||||
// `oneShot:true`). The flip runs AFTER the intake row is committed
|
||||
// so a flaky write never deactivates a medication that didn't
|
||||
// actually receive its dose.
|
||||
const reconcileAction = await reconcileOneShotState(prisma, id, user.id);
|
||||
if (reconcileAction !== "noop") {
|
||||
invalidateUserMedications(user.id);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user