import { supabase } from './supabase'; import type { Checkin, Connection, Contact, Event, ExcelSyncResult, Feedback, LeaderboardRow, PointsLogRow, Registration, ResetQrResult, Session, SessionSpeaker, SidecarStatus, Slot, Sponsor, SyncResult, SyncRun, } from './types'; export class ApiError extends Error {} async function rpc(fn: string, args: Record): Promise { const { data, error } = await supabase.rpc(fn, args); if (error) throw new ApiError(error.message); return data as T; } async function all(table: string, order?: { col: string; asc?: boolean }): Promise { let q = supabase.from(table).select('*'); if (order) q = q.order(order.col, { ascending: order.asc ?? true }); const { data, error } = await q; if (error) throw new ApiError(error.message); return data as T[]; } // ---- Reads (admin can read all rows via RLS) -------------------------------- export const getAllContacts = () => all('contacts', { col: 'full_name' }); export const getAllEvents = () => all('events', { col: 'start_date', asc: false }); export const getActiveEvent = async (): Promise => { const { data, error } = await supabase.from('events').select('*').eq('is_active', true).maybeSingle(); if (error) throw new ApiError(error.message); return (data as Event) ?? null; }; export const getRegistrations = (eventId: string) => all('registrations', { col: 'points', asc: false }).then((rows) => rows.filter((r) => r.event_id === eventId), ); export const getSponsors = (eventId: string) => all('sponsors', { col: 'name' }).then((rows) => rows.filter((s) => s.event_id === eventId)); export const getSlots = (eventId: string) => all('slots', { col: 'id' }).then((rows) => rows.filter((s) => s.event_id === eventId)); export const getSessions = (eventId: string) => all('sessions', { col: 'slot_id' }).then((rows) => rows.filter((s) => s.event_id === eventId)); // session_speakers has no event_id; callers filter by the event's session ids. export const getAllSessionSpeakers = () => all('session_speakers'); export const getAllConnections = () => all('connections', { col: 'created_at', asc: false }); export const getAllCheckins = () => all('checkins', { col: 'created_at', asc: false }); export const getAllFeedback = () => all('feedback', { col: 'created_at', asc: false }); export const getAllPointsLog = () => all('points_log', { col: 'created_at', asc: false }); export const getLeaderboard = () => all('leaderboard', { col: 'points', asc: false }); // ---- Contacts ---------------------------------------------------------------- export async function upsertContact(input: { email: string; full_name: string; linkedin_url?: string | null; is_admin?: boolean; }): Promise { // upsert_contact returns a single composite row (a JSON object, not an array). // Contacts no longer carry a QR token — the token lives on the registration. return await rpc('upsert_contact', { p_email: input.email, p_full_name: input.full_name, p_linkedin_url: input.linkedin_url ?? null, p_is_admin: input.is_admin ?? false, }); } export async function updateContact( email: string, patch: Partial>, ): Promise { const { error } = await supabase.from('contacts').update(patch).eq('email', email); if (error) throw new ApiError(error.message); } /** * Regenerate the QR token of a contact's registration for the active event * (syncs the auth password, forces re-login). The token lives on the * registration, not the contact. */ export async function resetQrToken(email: string): Promise { const rows = await rpc('reset_registration_qr_token', { p_contact_email: email }); return rows[0]; } // ---- Registrations ----------------------------------------------------------- export async function createRegistration(contactEmail: string, type: Registration['type']): Promise { await rpc('create_registration', { p_contact_email: contactEmail, p_type: type }); } export async function setRegistrationType(contactEmail: string, type: Registration['type']): Promise { await rpc('set_registration_type', { p_contact_email: contactEmail, p_type: type }); } export async function setCheckedIn(registrationId: string, checkedIn: boolean): Promise { const { error } = await supabase.from('registrations').update({ checked_in: checkedIn }).eq('id', registrationId); if (error) throw new ApiError(error.message); } // ---- Sponsors ---------------------------------------------------------------- export async function upsertSponsor( id: string | null, input: { event_id: string; type: Sponsor['type']; name: string; email?: string | null; phone?: string | null; paid?: boolean; amount_eur?: number | null; contact_email?: string | null; }, ): Promise { if (id) { const { error } = await supabase.from('sponsors').update(input).eq('id', id); if (error) throw new ApiError(error.message); } else { const { error } = await supabase.from('sponsors').insert(input); if (error) throw new ApiError(error.message); } } export async function deleteSponsor(id: string): Promise { const { error } = await supabase.from('sponsors').delete().eq('id', id); if (error) throw new ApiError(error.message); } // ---- Events ------------------------------------------------------------------ export async function upsertEvent( id: string | null, input: { name: string; start_date: string; end_date: string; location?: string | null; sessionize_endpoint?: string | null; use_realtime_clock?: boolean; }, ): Promise { if (id) { const { error } = await supabase.from('events').update(input).eq('id', id); if (error) throw new ApiError(error.message); } else { const { error } = await supabase.from('events').insert(input); if (error) throw new ApiError(error.message); } } // ---- Sessionize sync (sidecar) --------------------------------------------- // The sidecar is a separate Docker service (not Supabase), so these use raw // fetch against the same-origin /sidecar proxy (see nginx.conf.template). async function sidecarFetch(path: string, init?: RequestInit): Promise { let res: Response; try { res = await fetch(`/sidecar${path}`, { headers: { 'Content-Type': 'application/json' }, ...init, }); } catch { throw new ApiError('Could not reach the sync sidecar (is it running?)'); } const body = (await res.json().catch(() => ({}))) as T & { error?: string }; if (!res.ok) throw new ApiError(body.error || `sidecar error (${res.status})`); return body; } export const getSidecarStatus = () => sidecarFetch('/status'); /** Trigger a (blocking) Sessionize sync for an event. Resolves with the result. */ export const runSessionizeSync = (eventId: string) => sidecarFetch('/run', { method: 'POST', body: JSON.stringify({ event_id: eventId }) }); /** * Upload the Sessionize "Sessions and speakers (advanced)" .xlsx for an event. * The sidecar parses it and imports speakers/sessions/agenda + speaker * registrations. Resolves with the result (blocking). */ export async function importSessionizeExcel(eventId: string, file: File): Promise { const base64 = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { const url = reader.result as string; resolve(url.slice(url.indexOf(',') + 1)); }; reader.onerror = () => reject(new Error('Could not read the file')); reader.readAsDataURL(file); }); return sidecarFetch('/import-excel', { method: 'POST', body: JSON.stringify({ event_id: eventId, file_base64: base64, filename: file.name }), }); } /** Recent sync_runs rows for an event (newest first). */ export const getSyncRuns = (eventId: string) => all('sync_runs', { col: 'started_at', asc: false }).then((rows) => rows.filter((r) => r.event_id === eventId), ); /** Set an event active (deactivates all others via trigger). */ export async function activateEvent(id: string): Promise { const { error } = await supabase.from('events').update({ is_active: true }).eq('id', id); if (error) throw new ApiError(error.message); } /** Deactivate an event (sets is_active = false). */ export async function deactivateEvent(id: string): Promise { const { error } = await supabase.from('events').update({ is_active: false }).eq('id', id); if (error) throw new ApiError(error.message); } // ---- Points ------------------------------------------------------------------ /** Admin manual points adjustment for the active event (audited as 'admin'). */ export async function adjustPoints(contactEmail: string, delta: number, reason: string): Promise { await rpc('adjust_points', { p_contact_email: contactEmail, p_delta: delta, p_reason: reason }); } // ---- Sessions: speakers, material, AI feedback ------------------------------- export async function setSessionSpeakers(sessionId: string, emails: string[]): Promise { // Replace the speaker set with a diff: insert the new set first, then delete // only the speakers that are no longer in the set. Deleting first would trip // the `session_needs_speaker` trigger (it counts the row being deleted, so // removing the last speaker always fails) and abort the whole save. if (emails.length > 0) { const rows = emails.map((contact_email) => ({ session_id: sessionId, contact_email })); // upsert (on conflict do nothing) so re-adding an existing speaker is a no-op. const { error: insErr } = await supabase .from('session_speakers') .upsert(rows, { onConflict: 'session_id,contact_email', ignoreDuplicates: true }); if (insErr) throw new ApiError(insErr.message); const { error: delErr } = await supabase .from('session_speakers') .delete() .eq('session_id', sessionId) .not('contact_email', 'in', `(${emails.join(',')})`); if (delErr) throw new ApiError(delErr.message); } } /** Upload a session material file to the `materials` bucket and store the path. */ export async function uploadSessionMaterial(sessionId: string, file: File): Promise { const path = `sessions/${sessionId}/${Date.now()}-${file.name}`; const { error } = await supabase.storage.from('materials').upload(path, file, { upsert: true }); if (error) throw new ApiError(error.message); const { error: upErr } = await supabase.from('sessions').update({ material_path: path }).eq('id', sessionId); if (upErr) throw new ApiError(upErr.message); return path; } export async function removeSessionMaterial(sessionId: string): Promise { const { data } = await supabase.from('sessions').select('material_path').eq('id', sessionId).maybeSingle(); const path = (data as Session | null)?.material_path; if (path) { await supabase.storage.from('materials').remove([path]); } const { error } = await supabase.from('sessions').update({ material_path: null }).eq('id', sessionId); if (error) throw new ApiError(error.message); } export function sessionMaterialUrl(path: string): string { const { data } = supabase.storage.from('materials').getPublicUrl(path); return data.publicUrl; } /** Trigger the (stub) AI feedback evaluation for a session. */ export async function evaluateSessionFeedback(sessionId: string): Promise { // evaluate_session_feedback returns a single composite row (a JSON object, not an array). return await rpc('evaluate_session_feedback', { p_session_id: sessionId }); }