fix(api): finish the pagination tiebreaker, and state the tie premise correctly

The comment on the measurements list justified the tiebreaker with an Apple
Health import stamping long runs with one instant, and said the unique index
forbids two live measurements of the same type at that instant. The index is
`(userId, type, measuredAt, source, sleepStage)`, so the named example is the
one case it does block — while ties survive across `type` (the `stats:` daily
rollups), across `source` (two writers landing together) and across
`sleepStage`. Same conclusion, honest premise.

The per-day drill-down on the same route still sorted on `measuredAt` alone.
It slices in memory rather than with `skip`, so nothing drifts between pages,
but two identical requests were free to render a tied block in different
orders, and a list that reshuffles on refresh reads as data changing.

Three of the tiebreakered routes had nothing pinning the order: custom-metric
entries, the per-medication intake history (both sort arms, so the NULLS LAST
pin cannot be lost to the tiebreaker) and the mental-health assessment
history. Each now asserts the `orderBy` the way the illness day-log test does.
This commit is contained in:
Marc-André Bombeck committed 2026-09-10 05:07:02 +02:00
1 parent 2c63b0c4a7
commit 42100d94a7
4 files changed
+70 -8

No files matched your search

@@ -208,6 +208,27 @@ describe("GET /api/medications/[id]/intake — status filter", () => {
});
});
it("orders on a unique tiebreaker, keeping NULLS LAST on the takenAt arm", async () => {
// Scheduled slots share an instant by construction — a twice-daily
// medication puts every morning dose on the same `scheduledFor` — so
// offset paging over the sort key alone can repeat a row on one page and
// drop another. The `takenAt` arm keeps its NULLS LAST pin as well: the
// tiebreaker must not push skipped rows back to the top.
await GET(makeRequest("sortBy=takenAt&sortDir=desc"), ROUTE_PARAMS);
expect(
vi.mocked(prisma.medicationIntakeEvent.findMany).mock.calls[0][0]
?.orderBy,
).toEqual([{ takenAt: { sort: "desc", nulls: "last" } }, { id: "desc" }]);
vi.mocked(prisma.medicationIntakeEvent.findMany).mockClear();
await GET(makeRequest("sortBy=scheduledFor&sortDir=asc"), ROUTE_PARAMS);
expect(
vi.mocked(prisma.medicationIntakeEvent.findMany).mock.calls[0][0]
?.orderBy,
).toEqual([{ scheduledFor: "asc" }, { id: "asc" }]);
});
it("rejects unknown status values with a 422", async () => {
const res = await GET(makeRequest("status=junk"), ROUTE_PARAMS);
expect(res.status).toBe(422);