fix(medications): converge intake writes onto existing slot rows across sources

A take whose slot the legacy resolver rejected fell back to a standalone
insert that kept the client's scheduledFor, parking a second live row on
an anchor the reminder projector had already minted — the partial unique
index permits that because it spans source. Both intake write routes now
probe the slot source-agnostically and converge onto the existing row
before inserting, and a standalone insert anchors on the take time per
the ad-hoc contract. The compliance rollup counts distinct slots instead
of rows, which also corrects historical duplicates on the next recompute,
and the slot dedup pass runs nightly instead of only at worker boot.
This commit is contained in:
Marc-André Bombeck committed 2026-06-10 11:18:00 +02:00
1 parent 09dbb1131d
commit 9e6d0d5acb
9 files changed
+703 -57

No files matched your search

+75 -26
View File
@@ -269,33 +269,82 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
});
}
} else {
// Unscheduled / PRN / off-slot — keep the original insert behaviour.
[event] = await prisma.$transaction([
prisma.medicationIntakeEvent.create({
data: {
userId: user.id,
medicationId: id,
scheduledFor: incomingScheduledFor,
takenAt: resolvedTakenAt,
skipped,
source: "WEB",
idempotencyKey: idempotencyKey ?? null,
// v1.8.5 — site only on a resolved taken-injection write.
...(resolvedInjectionSite !== null && {
injectionSite: resolvedInjectionSite,
}),
},
}),
// Reset snooze when medication is taken
...(!skipped
? [
prisma.medication.update({
where: { id },
data: { snoozedUntil: null },
// Unscheduled / PRN / off-slot. When the client named an explicit
// `scheduledFor`, converge source-agnostically onto any live row that
// already sits on that instant (e.g. the pending REMINDER row the
// worker minted on a slot the band attribution did not claim) before
// inserting. Without the probe the insert lands a second live row for
// the same slot that differs only by `source` — the partial unique
// index carries `source` and cannot catch it — inflating the
// compliance rollup's scheduled count. A defaulted anchor (takenAt /
// now) never names a slot, so the probe is skipped on that hot path.
const existingSlotRow =
scheduledFor !== undefined
? await prisma.medicationIntakeEvent.findFirst({
where: {
userId: user.id,
medicationId: id,
scheduledFor: incomingScheduledFor,
deletedAt: null,
},
select: { id: true },
})
: null;
if (existingSlotRow) {
const applied = await applyCanonicalSlotWrite({
client: prisma,
userId: user.id,
medicationId: id,
canonicalSlot: incomingScheduledFor,
takenAt: resolvedTakenAt,
skipped,
isExplicitTaken,
isExplicitSkip,
idempotencyKey: idempotencyKey ?? null,
createSource: "WEB",
injectionSite: resolvedInjectionSite,
});
event = applied.row;
consumedTransition = applied.consumedTransition;
if (!skipped && !applied.noDowngradeNoOp) {
await prisma.medication.update({
where: { id },
data: { snoozedUntil: null },
});
}
} else {
// Genuinely standalone. Anchor a taken write on the intake instant —
// the documented ad-hoc contract (`scheduledFor = takenAt`) — so an
// unresolvable client anchor can never park a live row exactly on a
// slot instant a pending REMINDER row is minted for later. A skip
// without a slot keeps the incoming instant (it has no takenAt).
[event] = await prisma.$transaction([
prisma.medicationIntakeEvent.create({
data: {
userId: user.id,
medicationId: id,
scheduledFor: resolvedTakenAt ?? incomingScheduledFor,
takenAt: resolvedTakenAt,
skipped,
source: "WEB",
idempotencyKey: idempotencyKey ?? null,
// v1.8.5 — site only on a resolved taken-injection write.
...(resolvedInjectionSite !== null && {
injectionSite: resolvedInjectionSite,
}),
]
: []),
]);
},
}),
// Reset snooze when medication is taken
...(!skipped
? [
prisma.medication.update({
where: { id },
data: { snoozedUntil: null },
}),
]
: []),
]);
}
}
// v1.4.25 W19b — pen-inventory dose decrement. Only fires for
@@ -18,6 +18,8 @@ vi.mock("@/lib/db", () => ({
// v1.8.2 reconcile — shared slot upsert reads + updates in place.
findMany: vi.fn(),
update: vi.fn(),
// v1.15.19 — resolver-null convergence probe before standalone insert.
findFirst: vi.fn(),
},
auditLog: { create: vi.fn() },
},
@@ -328,3 +330,173 @@ describe("POST /api/medications/intake/bulk — v1.8.2 reconcile", () => {
);
});
});
// ────────────────────────────────────────────────────────────────────
// v1.15.19 — resolver-null convergence (cross-source duplicate slots)
// ────────────────────────────────────────────────────────────────────
describe("POST /api/medications/intake/bulk — v1.15.19 resolver-null convergence", () => {
const SCHEDULED_MED = {
id: "med-1",
startsOn: null,
endsOn: null,
oneShot: false,
createdAt: new Date("2026-01-01T00:00:00Z"),
schedules: [
{
id: "s1",
windowStart: "07:00",
windowEnd: "07:00",
daysOfWeek: null,
timesOfDay: ["07:00", "19:00"],
reminderGraceMinutes: null,
rrule: null,
rollingIntervalDays: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
doseWindows: null,
},
],
};
beforeEach(() => {
// Pin the clock HOURS before the fixture slot so the taken-write
// future-slot guard (TAKEN_FORWARD_GRACE_MS) rejects the snap and the
// resolver returns null — the production shape: the reminder worker has
// already pre-minted the pending REMINDER row at the slot instant, the
// client confirms early with an explicit `scheduledFor` on that instant.
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-06-15T00:30:00.000Z"));
vi.mocked(prisma.medication.findMany).mockResolvedValue([
{ id: "med-1" },
] as never);
vi.mocked(prisma.medication.findFirst).mockResolvedValue(
SCHEDULED_MED as never,
);
});
afterEach(() => {
vi.useRealTimers();
});
it("converges an early taken-write onto the pre-minted pending REMINDER row instead of inserting a sibling", async () => {
// Source-agnostic probe finds the live REMINDER row on the incoming
// instant…
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValueOnce({
id: "row-reminder",
} as never);
// …and the shared slot upsert re-reads + updates it in place.
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValueOnce([
{
id: "row-reminder",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: new Date("2026-06-15T05:00:00Z"),
source: "REMINDER",
createdAt: new Date("2026-06-15T00:00:00Z"),
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.update).mockResolvedValueOnce({
id: "row-reminder",
} as never);
const res = await POST(
postReq({
entries: [
{
medicationId: "med-1",
scheduledFor: "2026-06-15T05:00:00.000Z",
takenAt: "2026-06-15T00:30:00.000Z",
},
],
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: {
inserted: number;
updated: number;
entries: Array<{ status: string; id?: string }>;
};
};
// The slot did NOT fork into a second live event.
expect(body.data.updated).toBe(1);
expect(body.data.inserted).toBe(0);
expect(body.data.entries[0].status).toBe("updated");
expect(body.data.entries[0].id).toBe("row-reminder");
expect(prisma.medicationIntakeEvent.create).not.toHaveBeenCalled();
expect(prisma.medicationIntakeEvent.update).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "row-reminder" } }),
);
});
it("anchors a genuinely standalone resolver-null take on takenAt, not on the client's slot anchor", async () => {
// No live row on the incoming instant — the write is ad-hoc and must
// anchor on the intake instant so a worker mint at the slot instant
// later cannot pair up with it as a cross-source duplicate.
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValueOnce(
null as never,
);
vi.mocked(prisma.medicationIntakeEvent.create).mockResolvedValueOnce({
id: "row-standalone",
} as never);
const res = await POST(
postReq({
entries: [
{
medicationId: "med-1",
scheduledFor: "2026-06-15T05:00:00.000Z",
takenAt: "2026-06-15T00:30:00.000Z",
},
],
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { inserted: number; entries: Array<{ status: string }> };
};
expect(body.data.inserted).toBe(1);
expect(body.data.entries[0].status).toBe("inserted");
expect(prisma.medicationIntakeEvent.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
scheduledFor: new Date("2026-06-15T00:30:00.000Z"),
takenAt: new Date("2026-06-15T00:30:00.000Z"),
}),
}),
);
});
it("keeps the idempotencyKey replay contract: a re-submission reports duplicate, not updated", async () => {
// The replay pre-check fires BEFORE the convergence probe so a re-sent
// entry keeps its historical `duplicate` status.
vi.mocked(prisma.medicationIntakeEvent.findUnique).mockResolvedValueOnce({
id: "row-existing",
} as never);
const res = await POST(
postReq({
entries: [
{
medicationId: "med-1",
scheduledFor: "2026-06-15T05:00:00.000Z",
takenAt: "2026-06-15T00:30:00.000Z",
idempotencyKey: "ios-key-1",
},
],
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { duplicates: number; entries: Array<{ status: string; id?: string }> };
};
expect(body.data.duplicates).toBe(1);
expect(body.data.entries[0].status).toBe("duplicate");
expect(body.data.entries[0].id).toBe("row-existing");
expect(prisma.medicationIntakeEvent.create).not.toHaveBeenCalled();
expect(prisma.medicationIntakeEvent.findFirst).not.toHaveBeenCalled();
});
});
+93 -17
View File
@@ -244,7 +244,10 @@ async function postBulk(request: NextRequest): Promise<Response> {
isTakenWrite: !entry.skipped && entry.takenAt !== undefined,
});
const scheduledFor = canonicalSlot ?? incomingScheduledFor;
// The `scheduledFor` instant the row actually lands on — set by the
// branch that performs the write so the rollup recompute below keys
// the same day the stored row anchors to.
let effectiveScheduledFor = canonicalSlot ?? incomingScheduledFor;
// C2 — classify the incoming write. An offline-sync replay echoes a
// PENDING projection (no `takenAt`, `skipped:false`) for a slot the
@@ -312,28 +315,101 @@ async function postBulk(request: NextRequest): Promise<Response> {
results.push({ index: i, status: "inserted", id: applied.row.id });
}
} else {
// Unscheduled / PRN — insert. The idempotencyKey, when supplied,
// has a UNIQUE index; a re-submission returns the existing row via
// P2002 → status: "duplicate".
const row = await prisma.medicationIntakeEvent.create({
data: {
// Resolver-null: PRN / off-slot / future-slot-guarded. Before the
// standalone insert, two guards keep the slot from forking into a
// second live row:
//
// 1. idempotencyKey replay pre-check — a re-submission returns the
// existing row as "duplicate" (previously reached via the P2002
// catch; the explicit probe keeps that contract now that a
// replay could otherwise converge as "updated" below).
// 2. source-agnostic convergence probe — when ANY live row already
// sits on the incoming instant (e.g. the pending REMINDER row
// the worker pre-minted on a slot the taken-write future guard
// refused to snap to), converge onto THAT row through the shared
// slot upsert instead of inserting a sibling that differs only
// by `source`. The partial unique index carries `source`, so it
// cannot catch this duplicate; the probe must.
if (entry.idempotencyKey) {
const replay = await prisma.medicationIntakeEvent.findUnique({
where: { idempotencyKey: entry.idempotencyKey },
select: { id: true },
});
if (replay) {
duplicates += 1;
results.push({ index: i, status: "duplicate", id: replay.id });
continue;
}
}
// Only an explicit client `scheduledFor` names a slot a row could
// already sit on; a defaulted anchor (takenAt / now) never does, so
// the probe is skipped on that path.
const existingSlotRow =
entry.scheduledFor !== undefined
? await prisma.medicationIntakeEvent.findFirst({
where: {
userId: user.id,
medicationId: entry.medicationId,
scheduledFor: incomingScheduledFor,
deletedAt: null,
},
select: { id: true },
})
: null;
if (existingSlotRow) {
const applied = await applyCanonicalSlotWrite({
client: prisma,
userId: user.id,
medicationId: entry.medicationId,
scheduledFor,
canonicalSlot: incomingScheduledFor,
takenAt: entry.takenAt ?? null,
skipped: entry.skipped,
source: "API",
isExplicitTaken,
isExplicitSkip,
idempotencyKey: entry.idempotencyKey ?? null,
// v1.8.5 — site only on a resolved taken-injection entry.
...(resolvedInjectionSite !== null && {
injectionSite: resolvedInjectionSite,
}),
},
});
inserted += 1;
results.push({ index: i, status: "inserted", id: row.id });
createSource: "API",
injectionSite: resolvedInjectionSite,
});
if (applied.noDowngradeNoOp) {
duplicates += 1;
results.push({ index: i, status: "duplicate", id: applied.row.id });
} else if (applied.outcome === "updated") {
updated += 1;
results.push({ index: i, status: "updated", id: applied.row.id });
} else {
inserted += 1;
results.push({ index: i, status: "inserted", id: applied.row.id });
}
} else {
// Genuinely standalone. Anchor the row on the intake instant —
// the documented ad-hoc contract (`scheduledFor = takenAt`) — so
// an unresolvable client anchor (a future slot instant the taken
// guard rejected) can never park a live row exactly on a slot the
// worker later mints a pending REMINDER row for. A pending echo
// (no takenAt) keeps the incoming instant. The idempotencyKey,
// when supplied, has a UNIQUE index; a racing re-submission
// returns the existing row via P2002 → status: "duplicate".
effectiveScheduledFor = entry.takenAt ?? incomingScheduledFor;
const row = await prisma.medicationIntakeEvent.create({
data: {
userId: user.id,
medicationId: entry.medicationId,
scheduledFor: effectiveScheduledFor,
takenAt: entry.takenAt ?? null,
skipped: entry.skipped,
source: "API",
idempotencyKey: entry.idempotencyKey ?? null,
// v1.8.5 — site only on a resolved taken-injection entry.
...(resolvedInjectionSite !== null && {
injectionSite: resolvedInjectionSite,
}),
},
});
inserted += 1;
results.push({ index: i, status: "inserted", id: row.id });
}
}
const dayKey = dayKeyForScheduledFor(scheduledFor, user.timezone);
const dayKey = dayKeyForScheduledFor(effectiveScheduledFor, user.timezone);
touchedDays.set(`${entry.medicationId}|${dayKey}`, {
medicationId: entry.medicationId,
dayKey,