Percist local habits to remote db

This commit is contained in:
2025-10-18 13:56:01 +02:00
parent 4d82d4c4b7
commit 9675f42ffc

View File

@@ -208,32 +208,26 @@ export async function syncLocalToRemoteIfNeeded() {
const user = await getAuthUser(); const user = await getAuthUser();
if (!user) return; if (!user) return;
const already = localStorage.getItem(SYNC_FLAG); // Always upsert all local habits to Supabase after login
const { data: remote, error } = await supabase.from('habits').select('id').limit(1); let habits = local.getHabits();
if (error) return; if (habits.length === 0) return localStorage.setItem(SYNC_FLAG, new Date().toISOString());
habits = ensureUUIDs(habits);
if (!already || (remote || []).length === 0) { localStorage.setItem('habitgrid_data', JSON.stringify(habits));
let habits = local.getHabits(); const rows = habits.map(h => ({
if (habits.length === 0) return localStorage.setItem(SYNC_FLAG, new Date().toISOString()); id: h.id,
habits = ensureUUIDs(habits); user_id: user.id,
// Persist back to local so IDs match remote after upsert name: h.name,
localStorage.setItem('habitgrid_data', JSON.stringify(habits)); color: h.color,
const rows = habits.map(h => ({ category: h.category || '',
id: h.id, completions: h.completions || [],
user_id: user.id, current_streak: h.currentStreak ?? 0,
name: h.name, longest_streak: h.longestStreak ?? 0,
color: h.color, sort_order: h.sortOrder ?? 0,
category: h.category || '', created_at: h.createdAt || new Date().toISOString(),
completions: h.completions || [], updated_at: h.updatedAt || new Date().toISOString(),
current_streak: h.currentStreak ?? 0, }));
longest_streak: h.longestStreak ?? 0, await supabase.from('habits').upsert(rows, { onConflict: 'id' });
sort_order: h.sortOrder ?? 0, localStorage.setItem(SYNC_FLAG, new Date().toISOString());
created_at: h.createdAt || new Date().toISOString(),
updated_at: h.updatedAt || new Date().toISOString(),
}));
await supabase.from('habits').upsert(rows, { onConflict: 'id' });
localStorage.setItem(SYNC_FLAG, new Date().toISOString());
}
} }