diff --git a/src/lib/datastore.js b/src/lib/datastore.js index 9f0a7fd..601b6f0 100644 --- a/src/lib/datastore.js +++ b/src/lib/datastore.js @@ -100,7 +100,11 @@ export async function saveHabit(habit) { created_at: now, updated_at: now, }; - const { data, error } = await supabase.from('habits').insert(insert).select('*').single(); + const { data, error } = await supabase + .from('habits') + .upsert(insert, { onConflict: 'id' }) + .select('*') + .single(); if (error) { console.warn('Supabase saveHabit error, writing local:', error.message); return local.saveHabit({ ...habit, id }); @@ -210,6 +214,8 @@ export async function syncLocalToRemoteIfNeeded() { let habits = local.getHabits(); if (habits.length === 0) return localStorage.setItem(SYNC_FLAG, new Date().toISOString()); habits = ensureUUIDs(habits); + // Persist back to local so IDs match remote after upsert + localStorage.setItem('habitgrid_data', JSON.stringify(habits)); const rows = habits.map(h => ({ id: h.id, user_id: user.id, diff --git a/src/lib/storage.js b/src/lib/storage.js index 5d9b4ed..33710e5 100644 --- a/src/lib/storage.js +++ b/src/lib/storage.js @@ -2,6 +2,15 @@ import { supabase } from './supabase'; const STORAGE_KEY = 'habitgrid_data'; +// UUID v4 generator for local/offline usage +function generateUUID() { + if (typeof window !== 'undefined' && window.crypto?.randomUUID) return window.crypto.randomUUID(); + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); + return v.toString(16); + }); +} + export const getHabits = () => { try { const data = localStorage.getItem(STORAGE_KEY); @@ -56,14 +65,21 @@ const remoteMirrorDelete = async (id) => { export const saveHabit = (habit) => { const habits = getHabits(); + // Respect provided id (e.g., UUID from AddEdit or datastore). Generate only if missing. + const id = habit.id || generateUUID(); + const existingIndex = habits.findIndex(h => h.id === id); const newHabit = { ...habit, - id: Date.now().toString(), - sortOrder: habits.length, - createdAt: nowIso(), + id, + sortOrder: habit.sortOrder ?? habits.length, + createdAt: habit.createdAt || nowIso(), updatedAt: nowIso(), }; - habits.push(newHabit); + if (existingIndex >= 0) { + habits[existingIndex] = newHabit; + } else { + habits.push(newHabit); + } localStorage.setItem(STORAGE_KEY, JSON.stringify(habits)); remoteMirrorUpsert(newHabit); return newHabit;