mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
fix(medications): project daily-schedule intakes for today's window
Schedule-expansion never minted today's intake rows for medications
with `daysOfWeek: null` until the reminder worker entered the RED
phase at the end of the dose window. The database stores `null` to
mean "every day" (the `MedicationSchedule.daysOfWeek` column carries
that annotation in `prisma/schema.prisma`), so daily meds spent the
whole morning with zero scheduled rows. Endpoint
`/api/medications/intake?scope=today` returned `[]` even when two
active daily meds existed; iOS Dashboard tile + Erfassen sheet both
fell to "Heute nichts geplant" / "Keine offene Einnahme" end-to-end.
Adds `expandTodayIntakes` to `src/lib/medication-schedule.ts` — a
pure projection that re-uses the existing `parseScheduleRecurrence`
(empty array == every day) and respects explicit weekday filters
when present. The `scope=today` route projects active schedules
through the helper, then idempotently backfills any missing rows
into `MedicationIntakeEvent` so the iOS POST update path keeps the
existing intakeId contract.
Tests:
- `medication-schedule.test.ts` gains eight cases covering
`daysOfWeek: null`, `""`, `"0,1,2,3,4,5,6"`, explicit-weekday
excludes-today / includes-today, the operator's Ramipril +
Metformin fixture, DST-correct `scheduledFor` anchoring at
`windowStart` in Europe/Berlin, and multi-week cadence skip.
- `intake/route.test.ts` gains two cases: backfill mints the
missing row + does-not-double-mint when the row already exists.
Full vitest suite stays green (4672 passed / 1 skipped).
This commit is contained in:
1 parent
d60115c3ae
commit
10e658f66d
4 files changed
+481
-2
No files matched your search
@@ -7,8 +7,17 @@ vi.mock("@/lib/db", () => ({
|
||||
findMany: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
// v1.4.39 W-SERVER-FIX — `scope=today` now backfills missing
|
||||
// rows for schedules whose window opens today (covers daily
|
||||
// meds with `daysOfWeek: null` whose reminder hasn't fired yet).
|
||||
createMany: vi.fn(),
|
||||
},
|
||||
medication: {
|
||||
update: vi.fn(),
|
||||
// v1.4.39 W-SERVER-FIX — today's projection reads active meds +
|
||||
// their schedules to know what to backfill.
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
medication: { update: vi.fn() },
|
||||
medicationComplianceRollup: {
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
@@ -65,6 +74,13 @@ beforeEach(() => {
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue(
|
||||
[] as never,
|
||||
);
|
||||
// v1.4.39 W-SERVER-FIX — default the today-projection prisma reads
|
||||
// to "no active medications" so existing compliance / POST tests
|
||||
// exercise their original paths without an unmocked-call failure.
|
||||
vi.mocked(prisma.medication.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.createMany).mockResolvedValue({
|
||||
count: 0,
|
||||
} as never);
|
||||
// v1.4.39 W-MED — default the coverage probe to "uncovered" so the
|
||||
// legacy compliance test still exercises the live-fallback branch
|
||||
// and finds the legacy mocked intake events.
|
||||
@@ -123,6 +139,112 @@ describe("GET /api/medications/intake", () => {
|
||||
expect(body.data[0].status).toBe("pending");
|
||||
});
|
||||
|
||||
it("backfills missing today rows for daily meds (daysOfWeek=null)", async () => {
|
||||
// v1.4.39 W-SERVER-FIX regression — the operator's Ramipril
|
||||
// (Morgens) ships `daysOfWeek: null` in the DB ("every day" per
|
||||
// schema). Pre-fix, the endpoint returned `[]` until the reminder
|
||||
// worker entered RED phase. Post-fix, the GET projects the schedule
|
||||
// and idempotently mints any missing rows so the iOS Dashboard +
|
||||
// "Erfassen" sheet have an intake row to mark.
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.medication.findMany).mockResolvedValue([
|
||||
{
|
||||
id: "med-ramipril",
|
||||
schedules: [
|
||||
{
|
||||
id: "sched-morgens",
|
||||
medicationId: "med-ramipril",
|
||||
windowStart: "07:00",
|
||||
windowEnd: "09:00",
|
||||
daysOfWeek: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
] as never);
|
||||
// First findMany call (pre-backfill existence probe) returns empty;
|
||||
// second call (post-backfill list) returns the freshly minted row.
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany)
|
||||
.mockResolvedValueOnce([] as never)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
id: "e-new",
|
||||
medicationId: "med-ramipril",
|
||||
scheduledFor: new Date("2026-05-21T05:00:00.000Z"),
|
||||
takenAt: null,
|
||||
skipped: false,
|
||||
medication: { id: "med-ramipril", snoozedUntil: null },
|
||||
},
|
||||
] as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.createMany).mockResolvedValue({
|
||||
count: 1,
|
||||
} as never);
|
||||
|
||||
const res = await GET(
|
||||
new NextRequest("http://localhost/api/medications/intake?scope=today"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
data: Array<{ id: string; status: string }>;
|
||||
};
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].id).toBe("e-new");
|
||||
expect(body.data[0].status).toBe("pending");
|
||||
expect(prisma.medicationIntakeEvent.createMany).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
vi.mocked(prisma.medicationIntakeEvent.createMany).mock.calls[0][0],
|
||||
).toMatchObject({
|
||||
data: [
|
||||
{
|
||||
userId: "user-1",
|
||||
medicationId: "med-ramipril",
|
||||
skipped: false,
|
||||
source: "REMINDER",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not double-mint when today's rows already exist", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
const scheduledFor = new Date("2026-05-21T05:00:00.000Z");
|
||||
vi.mocked(prisma.medication.findMany).mockResolvedValue([
|
||||
{
|
||||
id: "med-ramipril",
|
||||
schedules: [
|
||||
{
|
||||
id: "sched-morgens",
|
||||
medicationId: "med-ramipril",
|
||||
windowStart: "07:00",
|
||||
windowEnd: "09:00",
|
||||
daysOfWeek: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
] as never);
|
||||
// The existence probe sees a row for the exact projected slot, so
|
||||
// createMany must not fire.
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany)
|
||||
.mockResolvedValueOnce([
|
||||
{ medicationId: "med-ramipril", scheduledFor },
|
||||
] as never)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
id: "e-existing",
|
||||
medicationId: "med-ramipril",
|
||||
scheduledFor,
|
||||
takenAt: null,
|
||||
skipped: false,
|
||||
medication: { id: "med-ramipril", snoozedUntil: null },
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(
|
||||
new NextRequest("http://localhost/api/medications/intake?scope=today"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.medicationIntakeEvent.createMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns compliance buckets for the last N days", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
enqueueUserMedicationComplianceBackfill,
|
||||
type ComplianceBucket as RollupComplianceBucket,
|
||||
} from "@/lib/medications/compliance-rollups";
|
||||
import { expandTodayIntakes } from "@/lib/medication-schedule";
|
||||
|
||||
const querySchema = z.object({
|
||||
scope: z.enum(["today", "compliance"]),
|
||||
@@ -85,6 +86,69 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
if (scope === "today") {
|
||||
const todayStart = startOfDayInTz(new Date(), userTz);
|
||||
const todayEnd = new Date(todayStart.getTime() + 86_400_000);
|
||||
|
||||
// v1.4.39 W-SERVER-FIX — project pending intake rows for every
|
||||
// active schedule whose window opens today, then idempotently
|
||||
// backfill any missing rows. Pre-fix the endpoint returned `[]`
|
||||
// for daily meds (`schedule.daysOfWeek = null` in the DB) until
|
||||
// the reminder worker entered the RED phase at the end of the
|
||||
// dose window — leaving the iOS Dashboard tile + the "Erfassen"
|
||||
// sheet empty for the whole morning. The projection re-uses the
|
||||
// canonical `parseScheduleRecurrence` (null/empty = every day)
|
||||
// so the daysOfWeek semantics stay aligned across every reader.
|
||||
const activeMedications = await prisma.medication.findMany({
|
||||
where: { userId: user.id, active: true },
|
||||
select: {
|
||||
id: true,
|
||||
schedules: {
|
||||
select: {
|
||||
id: true,
|
||||
medicationId: true,
|
||||
windowStart: true,
|
||||
windowEnd: true,
|
||||
daysOfWeek: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const projected = expandTodayIntakes(
|
||||
activeMedications.flatMap((m) => m.schedules),
|
||||
new Date(),
|
||||
userTz,
|
||||
);
|
||||
|
||||
const existing = await prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
scheduledFor: { gte: todayStart, lt: todayEnd },
|
||||
},
|
||||
select: { medicationId: true, scheduledFor: true },
|
||||
});
|
||||
const existingKey = new Set(
|
||||
existing.map((e) => `${e.medicationId}|${e.scheduledFor.toISOString()}`),
|
||||
);
|
||||
const missing = projected.filter(
|
||||
(p) =>
|
||||
!existingKey.has(`${p.medicationId}|${p.scheduledFor.toISOString()}`),
|
||||
);
|
||||
if (missing.length > 0) {
|
||||
await prisma.medicationIntakeEvent.createMany({
|
||||
data: missing.map((m) => ({
|
||||
userId: user.id,
|
||||
medicationId: m.medicationId,
|
||||
scheduledFor: m.scheduledFor,
|
||||
takenAt: null,
|
||||
skipped: false,
|
||||
// `REMINDER` is the same source the reminder worker uses to
|
||||
// mint RED-phase rows — semantically "the server projected
|
||||
// this slot before the user logged anything". The IntakeSource
|
||||
// enum has no separate `SCHEDULER` literal; reusing REMINDER
|
||||
// keeps the doctor-report + analytics filters byte-stable.
|
||||
source: "REMINDER",
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
const events = await prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
@@ -96,7 +160,11 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
annotate({
|
||||
action: { name: "medications.intake.today" },
|
||||
meta: { count: events.length },
|
||||
meta: {
|
||||
count: events.length,
|
||||
projected: projected.length,
|
||||
backfilled: missing.length,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess(
|
||||
|
||||
Reference in new issue
Block a user