From a1495ff23f14b768c5fbb9cce9e7f3a2e7781e12 Mon Sep 17 00:00:00 2001 From: Petru Paler Date: Thu, 15 Jan 2026 22:06:03 +0000 Subject: [PATCH] Fix garmin-sync to upsert dailyLogs instead of always creating The sync was creating a new record every time it ran, causing duplicate records for the same day. Combined with PocketBase's inability to sort by the 'created' field, this caused the dashboard to display stale data. Now checks for an existing record for the user+date before creating, and updates the existing record if found. Co-Authored-By: Claude Opus 4.5 --- src/app/api/cron/garmin-sync/route.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/app/api/cron/garmin-sync/route.ts b/src/app/api/cron/garmin-sync/route.ts index 59ee4e4..e2e7933 100644 --- a/src/app/api/cron/garmin-sync/route.ts +++ b/src/app/api/cron/garmin-sync/route.ts @@ -206,12 +206,12 @@ export async function POST(request: Request) { user.activeOverrides, ); - // Create DailyLog entry + // Upsert DailyLog entry - update existing record for today or create new one // Store default value 100 for body battery when Garmin returns null. // This prevents PocketBase's number field null-to-0 coercion from // causing the dashboard to display 0 instead of a meaningful value. // Use YYYY-MM-DD format for PocketBase date field compatibility - await pb.collection("dailyLogs").create({ + const dailyLogData = { user: user.id, date: today, cycleDay, @@ -225,7 +225,18 @@ export async function POST(request: Request) { trainingDecision: decision.status, decisionReason: decision.reason, notificationSentAt: null, - }); + }; + + // Check if record already exists for this user today + try { + const existing = await pb + .collection("dailyLogs") + .getFirstListItem(`user="${user.id}" && date="${today}"`); + await pb.collection("dailyLogs").update(existing.id, dailyLogData); + } catch { + // No existing record - create new one + await pb.collection("dailyLogs").create(dailyLogData); + } // Log sync complete with metrics const userSyncDuration = Date.now() - userSyncStartTime;