fix(medications): every intake path converges on the slot, and caches cannot resurrect a pre-write body

The external ingest endpoint was the one intake writer that never
attributed to the minted band: it stored a bare row beside the pending
slot, so an early take through the API showed as the last intake while
the slot kept demanding a dose, the ledger recorded an extra plus a
miss, and the day tally counted both. It now resolves the band and
converges onto the pending row like every other path, the Telegram
confirm and skip buttons do the same preferring the reminder's own
slot, and the nightly convergence pass heals the pairs this has
already produced — one band match, one live anchor row, both days'
rollups recomputed. The cache layer fences in-flight builders on
invalidation so a read can neither join a pre-write build nor have a
background refresh re-cache a pre-write body as fresh. Ad-hoc rows no
longer resolve a different slot through the six-hour radius, a bounded
early grace credits a take up to an hour before the window without
crossing the previous band, day-scale cadences taken early downgrade
the slot-day prompt instead of inviting a double dose, the overdue
pill ignores the projector's pending mints, created intakes carry the
same plausibility bounds as edits, slot moves keep the recorded
injection site and dose, both affected days recompute on a moved
toggle, deliberate slot-less skips converge instead of orphaning, the
coach reads adherence from the ledger, the cards and quick-add run in
the user's timezone with the served next-due as the gate, and
schedule-revision, wipe and restore writes invalidate the caches they
feed.
This commit is contained in:
Marc-André Bombeck committed 2026-06-12 10:43:32 +02:00
1 parent ea29e9cf1b
commit aaecd141ee
53 files changed
+2550 -202

No files matched your search

@@ -12,7 +12,9 @@ vi.mock("@/lib/db", () => ({
},
medicationIntakeEvent: {
findFirst: vi.fn(),
findMany: vi.fn(),
create: vi.fn(),
update: vi.fn(),
},
medication: {
findFirst: vi.fn(),
@@ -38,6 +40,9 @@ vi.mock("@/lib/app-settings", () => ({
vi.mock("@/lib/rollups/medication-compliance-rollups", () => ({
recomputeMedicationComplianceForEvent: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/cache/invalidate", () => ({
invalidateUserMedications: vi.fn(),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
@@ -55,6 +60,7 @@ import { POST } from "../route";
import { prisma } from "@/lib/db";
import { checkRateLimit } from "@/lib/rate-limit";
import { isApiGloballyEnabled } from "@/lib/app-settings";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
function postReq(body: unknown): NextRequest {
return new NextRequest("http://localhost/api/ingest/medication", {
@@ -145,3 +151,156 @@ describe("POST /api/ingest/medication — 422 multi-issue (v1.4.43 W6)", () => {
expect(res.status).toBe(422);
});
});
describe("POST /api/ingest/medication — slot attribution + convergence (v1.16.9)", () => {
// The maintainer's live bug: a daily 09:00 med, the worker pre-minted the
// pending REMINDER row at 09:00 Berlin, the user ingested the take at
// 08:42 Berlin via the external API. The bare create anchored a SECOND
// row at 08:42 and left the 09:00 pending row open — reminder kept
// firing, ledger showed ad-hoc + later missed, today feed said "due".
const SLOT_0900_BERLIN = new Date("2026-06-10T07:00:00.000Z"); // 09:00 CEST
const TAKEN_0842_BERLIN = new Date("2026-06-10T06:42:00.000Z"); // 08:42 CEST
const scheduleRow = {
id: "sched-1",
windowStart: "09:00",
windowEnd: "09:00",
daysOfWeek: null,
timesOfDay: ["09:00"],
reminderGraceMinutes: null,
rrule: "FREQ=DAILY",
rollingIntervalDays: null,
scheduleType: "SCHEDULED",
cyclicOnWeeks: null,
cyclicOffWeeks: null,
doseWindows: null,
};
const pendingReminderRow = {
id: "evt-pending-0900",
takenAt: null,
skipped: false,
idempotencyKey: null,
scheduledFor: SLOT_0900_BERLIN,
source: "REMINDER",
createdAt: new Date("2026-06-10T05:00:00.000Z"),
};
function wireHappyPath() {
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
vi.mocked(isApiGloballyEnabled).mockResolvedValue(true);
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({
id: "tok-1",
userId: "user-1",
permissions: ["*"],
revoked: false,
expiresAt: null,
lastUsedAt: null,
} as never);
vi.mocked(prisma.apiToken.update).mockResolvedValue({} as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
timezone: "Europe/Berlin",
} as never);
// First findFirst (by name) returns the bare medication; the slot
// resolver's findFirst (selects schedules) returns the projection.
vi.mocked(prisma.medication.findFirst).mockImplementation(((args: {
where: Record<string, unknown>;
}) => {
if (args.where && "name" in args.where) {
return Promise.resolve({ id: "med-1", name: "Metformin" });
}
return Promise.resolve({
id: "med-1",
startsOn: null,
endsOn: null,
oneShot: false,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
schedules: [scheduleRow],
scheduleRevisions: [],
});
}) as never);
// Idempotency probe → no replay.
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValue(null);
// The slot's live rows: the worker-minted pending REMINDER row.
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([
pendingReminderRow,
] as never);
vi.mocked(prisma.medicationIntakeEvent.update).mockImplementation(((args: {
where: { id: string };
data: Record<string, unknown>;
}) =>
Promise.resolve({
...pendingReminderRow,
...args.data,
syncVersion: 2,
})) as never);
}
it("converges an 08:42 take onto the pending 09:00 REMINDER row (no second row)", async () => {
wireHappyPath();
const res = await POST(
postReq({
medicationName: "Metformin",
takenAt: TAKEN_0842_BERLIN.toISOString(),
idempotencyKey: "ha-ingest-1",
}),
);
expect(res.status).toBe(201);
const body = (await res.json()) as { data: { id: string } };
// The pending REMINDER row was updated in place — never a bare create.
expect(body.data.id).toBe("evt-pending-0900");
expect(prisma.medicationIntakeEvent.create).not.toHaveBeenCalled();
expect(prisma.medicationIntakeEvent.update).toHaveBeenCalledTimes(1);
const update = vi.mocked(prisma.medicationIntakeEvent.update).mock
.calls[0][0] as {
where: { id: string };
data: { takenAt: Date; skipped: boolean; autoMissed?: boolean };
};
expect(update.where.id).toBe("evt-pending-0900");
expect(update.data.takenAt?.getTime()).toBe(TAKEN_0842_BERLIN.getTime());
expect(update.data.skipped).toBe(false);
// A recorded take clears a prior cron auto-miss.
expect(update.data.autoMissed).toBe(false);
});
it("hard-evicts the user's medication caches after the write", async () => {
wireHappyPath();
await POST(
postReq({
medicationName: "Metformin",
takenAt: TAKEN_0842_BERLIN.toISOString(),
idempotencyKey: "ha-ingest-2",
}),
);
expect(invalidateUserMedications).toHaveBeenCalledWith("user-1", {
evict: true,
});
});
it("keeps the standalone ad-hoc contract for an off-window take", async () => {
wireHappyPath();
// 14:30 Berlin — outside the 09:00 band and its late tail.
const offWindow = new Date("2026-06-10T12:30:00.000Z");
vi.mocked(prisma.medicationIntakeEvent.create).mockResolvedValue({
id: "evt-adhoc",
scheduledFor: offWindow,
takenAt: offWindow,
skipped: false,
source: "API",
} as never);
const res = await POST(
postReq({
medicationName: "Metformin",
takenAt: offWindow.toISOString(),
idempotencyKey: "ha-ingest-3",
}),
);
expect(res.status).toBe(201);
expect(prisma.medicationIntakeEvent.update).not.toHaveBeenCalled();
const create = vi.mocked(prisma.medicationIntakeEvent.create).mock
.calls[0][0] as { data: { scheduledFor: Date; takenAt: Date } };
// Ad-hoc rows anchor on the intake instant (`scheduledFor = takenAt`).
expect(create.data.scheduledFor.getTime()).toBe(offWindow.getTime());
expect(create.data.takenAt.getTime()).toBe(offWindow.getTime());
});
});
+73 -14
View File
@@ -15,6 +15,12 @@ import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { externalIntakeSchema } from "@/lib/validations/medication";
import { isApiGloballyEnabled } from "@/lib/app-settings";
import { recomputeMedicationComplianceForEvent } from "@/lib/rollups/medication-compliance-rollups";
import {
applyCanonicalSlotWrite,
resolveSlotForWriteByBand,
} from "@/lib/medications/scheduling/slot-upsert";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { NextRequest, NextResponse } from "next/server";
/**
@@ -159,17 +165,64 @@ export const POST = apiHandler(async (request: NextRequest) => {
return apiError("API endpoint for this medication is disabled", 403);
}
const event = await prisma.medicationIntakeEvent.create({
data: {
// The external ingest path runs without a User record in scope;
// resolve the timezone once — band attribution and the compliance
// recompute below both anchor on the user's local day.
const ingestUser = await prisma.user.findUnique({
where: { id: apiToken.userId },
select: { timezone: true },
});
const userTz = ingestUser?.timezone || DEFAULT_TIMEZONE;
const effectiveTakenAt = takenAt ?? new Date();
// v1.16.9 — attribute the take to its scheduled slot by window-band
// membership, the SAME engine the per-medication intake route and the
// read ledger consume. The bare create this replaces anchored every
// ingest at `scheduledFor = takenAt`, leaving the slot's pending
// REMINDER row open: the reminder kept firing, the ledger showed an
// ad-hoc take PLUS a missed slot, and the today feed still said "due".
const attribution = await resolveSlotForWriteByBand({
userId: apiToken.userId,
medicationId: medication.id,
userTz,
takenAt: effectiveTakenAt,
});
let event;
if (attribution.slotInstant) {
// Scheduled dose — converge onto the one canonical slot row (the
// pending REMINDER row when one exists) through the shared upsert:
// H1 deterministic selection, C2 no-downgrade, P2002-safe create.
const applied = await applyCanonicalSlotWrite({
client: prisma,
userId: apiToken.userId,
medicationId: medication.id,
scheduledFor: takenAt ?? new Date(),
takenAt: takenAt ?? new Date(),
canonicalSlot: attribution.slotInstant,
takenAt: effectiveTakenAt,
skipped: false,
source: "API",
isExplicitTaken: true,
isExplicitSkip: false,
idempotencyKey,
},
});
createSource: "API",
attributionSource: "AUTO",
});
event = applied.row;
} else {
// Ad-hoc / PRN / off-window — standalone row under the documented
// contract (`scheduledFor = takenAt`).
event = await prisma.medicationIntakeEvent.create({
data: {
userId: apiToken.userId,
medicationId: medication.id,
scheduledFor: effectiveTakenAt,
takenAt: effectiveTakenAt,
skipped: false,
source: "API",
idempotencyKey,
},
});
}
await auditLog("medication.ingest.external", {
userId: apiToken.userId,
@@ -181,15 +234,21 @@ export const POST = apiHandler(async (request: NextRequest) => {
},
});
annotate({ meta: { medication_id: medication.id, event_id: event.id } });
annotate({
meta: {
medication_id: medication.id,
event_id: event.id,
slot_resolved: attribution.slotInstant !== null,
},
});
// v1.16.9 — the ingest is an interactive dose record; the next read
// (today feed, card pill, compliance heatmap) must reflect it rather
// than wait out the TTL.
invalidateUserMedications(apiToken.userId, { evict: true });
// v1.4.39 W-MED — refresh the compliance rollup for the ingested
// event's user-day. The external ingest path runs without a User
// record in scope; resolve the tz once for the recompute.
const ingestUser = await prisma.user.findUnique({
where: { id: apiToken.userId },
select: { timezone: true },
});
// event's user-day.
await recomputeMedicationComplianceForEvent({
userId: apiToken.userId,
medicationId: medication.id,