diff --git a/src/lib/withings/__tests__/sync-sleep.test.ts b/src/lib/withings/__tests__/sync-sleep.test.ts index 6ae04f3a1..6cee99863 100644 --- a/src/lib/withings/__tests__/sync-sleep.test.ts +++ b/src/lib/withings/__tests__/sync-sleep.test.ts @@ -240,9 +240,15 @@ describe("syncUserSleep — segment writes + idempotency", () => { const imported = await syncUserSleep("user-1"); expect(imported).toBe(1); expect(prisma.measurement.create).not.toHaveBeenCalled(); + // Re-sync keys on the stable externalId and refreshes value, the + // END-stamped measuredAt (enddate may shift) and the stage. expect(prisma.measurement.update).toHaveBeenCalledWith({ where: { id: "row-1" }, - data: { value: 60 }, + data: { + value: 60, + measuredAt: new Date(1715003600 * 1000), + sleepStage: "DEEP", + }, }); }); diff --git a/src/lib/withings/sync-sleep.ts b/src/lib/withings/sync-sleep.ts index 4b92080d2..27b643baf 100644 --- a/src/lib/withings/sync-sleep.ts +++ b/src/lib/withings/sync-sleep.ts @@ -275,20 +275,25 @@ export async function syncUserSleep( const externalId = `withings:sleep:${userId}:${segment.id ?? "no-id"}:${segmentIndex}`; try { + // Key the re-sync lookup on the STABLE `externalId` (segment id + + // index), not `measuredAt`. Withings re-aggregates a night between + // syncs, so a segment's `enddate` — and therefore its END-stamped + // `measuredAt` — shifts; keying on `measuredAt` would miss the prior + // row and then collide with the unique `externalId`, leaving the night + // stuck at the stale value. Update both `value` and `measuredAt`. const existing = await prisma.measurement.findFirst({ where: { userId, type: SLEEP_TYPE, - measuredAt, source: "WITHINGS", - sleepStage: stage, + externalId, }, select: { id: true }, }); if (existing) { await prisma.measurement.update({ where: { id: existing.id }, - data: { value: minutes }, + data: { value: minutes, measuredAt, sleepStage: stage }, }); } else { await prisma.measurement.create({