Files
inq-roi-simulador-web/src/persistence/supabase/settings-repo.ts
Marcos Benítez 6be9f6267f
Some checks failed
/ Deploy to Cloudflare Pages (push) Has been cancelled
Pre-Cierre sprint 7.
2026-07-07 10:44:23 -03:00

42 lines
1.4 KiB
TypeScript

import { supabase } from '@/lib/supabase'
import type { AppSettings } from '@/domain/types'
const DEFAULT_SETTINGS: AppSettings = { id: 'singleton', groupLabel: 'Cliente' }
// Elimina artículos iniciales que el usuario pudo haber ingresado por error (ej. "un Cliente" → "Cliente")
function normalizeGroupLabel(raw: string): string {
return raw.replace(/^(un|una|el|la)\s+/i, '').trim() || 'Cliente'
}
export const supabaseSettingsRepo = {
async get(): Promise<AppSettings> {
const { data, error } = await supabase
.from('app_settings')
.select('id, group_label')
.eq('id', 'singleton')
.single()
// PGRST116 = 0 rows — singleton aún no existe, crearlo y retornar el default
if (error?.code === 'PGRST116' || !data) {
await supabase.from('app_settings').upsert({
id: 'singleton',
group_label: 'Cliente',
})
return DEFAULT_SETTINGS
}
return { id: 'singleton', groupLabel: normalizeGroupLabel((data.group_label as string) ?? 'Cliente') }
},
async update(updates: Partial<Omit<AppSettings, 'id'>>): Promise<void> {
const patch: Record<string, unknown> = { updated_at: new Date().toISOString() }
if (updates.groupLabel !== undefined) patch.group_label = normalizeGroupLabel(updates.groupLabel)
const { error } = await supabase
.from('app_settings')
.update(patch)
.eq('id', 'singleton')
if (error) throw error
},
}