Fix garmin-sync to upsert dailyLogs instead of always creating
All checks were successful
Deploy / deploy (push) Successful in 1m39s

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 <noreply@anthropic.com>
This commit is contained in:
2026-01-15 22:06:03 +00:00
parent 4dad370e66
commit a1495ff23f

View File

@@ -206,12 +206,12 @@ export async function POST(request: Request) {
user.activeOverrides, 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. // Store default value 100 for body battery when Garmin returns null.
// This prevents PocketBase's number field null-to-0 coercion from // This prevents PocketBase's number field null-to-0 coercion from
// causing the dashboard to display 0 instead of a meaningful value. // causing the dashboard to display 0 instead of a meaningful value.
// Use YYYY-MM-DD format for PocketBase date field compatibility // Use YYYY-MM-DD format for PocketBase date field compatibility
await pb.collection("dailyLogs").create({ const dailyLogData = {
user: user.id, user: user.id,
date: today, date: today,
cycleDay, cycleDay,
@@ -225,7 +225,18 @@ export async function POST(request: Request) {
trainingDecision: decision.status, trainingDecision: decision.status,
decisionReason: decision.reason, decisionReason: decision.reason,
notificationSentAt: null, 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 // Log sync complete with metrics
const userSyncDuration = Date.now() - userSyncStartTime; const userSyncDuration = Date.now() - userSyncStartTime;