fix(medications): every taken dose moves the stock, in units that match the product

Stock only decremented on the web card's take button — the status
toggle, the phone sync, the Telegram buttons and the token API all
recorded the dose and left the inventory untouched, which is why a
fresh pack kept reading full. Consumption now stamps the intake row
itself: every path that turns a row taken consumes through one module
— open container first, then earliest expiry with auto-open, spilling
into the next pack and flooring at zero — and every path that takes it
back (undo, delete, a take turned skip, a converged duplicate)
refunds exactly what the stamp recorded. Replays and pending sync
echoes can never double-charge, and the nightly convergence pass
refunds the rows it tombstones. A medication can declare units per
dose, so two 2 mg tablets book as one 4 mg dose and stock reads in
doses with the unit count alongside; containers carry a named type
including tablet packs, hold up to a thousand units for inhalers, and
the GLP-1 card reads the same stock as the inventory tab instead of a
separate ledger. The inventory endpoints join the documented API.
This commit is contained in:
Marc-André Bombeck committed 2026-06-12 17:42:31 +02:00
1 parent dacdcccfd2
commit 7d3557a3fd
53 files changed
+4118 -641

No files matched your search

@@ -40,6 +40,10 @@ vi.mock("@/lib/app-settings", () => ({
vi.mock("@/lib/rollups/medication-compliance-rollups", () => ({
recomputeMedicationComplianceForEvent: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/medications/inventory/consumption", () => ({
consumeForIntake: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/cache/invalidate", () => ({
invalidateUserMedications: vi.fn(),
}));
@@ -303,4 +307,49 @@ describe("POST /api/ingest/medication — slot attribution + convergence (v1.16.
expect(create.data.scheduledFor.getTime()).toBe(offWindow.getTime());
expect(create.data.takenAt.getTime()).toBe(offWindow.getTime());
});
// ── v1.16.10 — inventory consumption seam ───────────────────────────
it("consumes inventory exactly once on the landed row", async () => {
const { consumeForIntake } = await import(
"@/lib/medications/inventory/consumption"
);
wireHappyPath();
const res = await POST(
postReq({
medicationName: "Metformin",
takenAt: TAKEN_0842_BERLIN.toISOString(),
idempotencyKey: "ha-ingest-inv-1",
}),
);
expect(res.status).toBe(201);
expect(consumeForIntake).toHaveBeenCalledTimes(1);
expect(consumeForIntake).toHaveBeenCalledWith(
expect.objectContaining({
userId: "user-1",
medicationId: "med-1",
eventId: "evt-pending-0900",
}),
);
});
it("an idempotency replay returns the original row without consuming", async () => {
const { consumeForIntake } = await import(
"@/lib/medications/inventory/consumption"
);
wireHappyPath();
// The replay probe finds the original event.
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValue({
id: "evt-original",
} as never);
const res = await POST(
postReq({
medicationName: "Metformin",
takenAt: TAKEN_0842_BERLIN.toISOString(),
idempotencyKey: "ha-ingest-inv-1",
}),
);
expect(res.status).toBe(200);
expect(consumeForIntake).not.toHaveBeenCalled();
});
});
+12
View File
@@ -19,6 +19,7 @@ import {
applyCanonicalSlotWrite,
resolveSlotForWriteByBand,
} from "@/lib/medications/scheduling/slot-upsert";
import { consumeForIntake } from "@/lib/medications/inventory/consumption";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { NextRequest, NextResponse } from "next/server";
@@ -224,6 +225,17 @@ export const POST = apiHandler(async (request: NextRequest) => {
});
}
// v1.16.10 — the external ingest records a take; consume inventory
// units. The stamp on the row keeps a retried POST exactly-once (the
// idempotency probe above already short-circuits the common replay).
await consumeForIntake({
client: prisma,
userId: apiToken.userId,
medicationId: medication.id,
eventId: event.id,
intakeAt: effectiveTakenAt,
});
await auditLog("medication.ingest.external", {
userId: apiToken.userId,
ipAddress: ip,