import { supabase } from './supabase'; import type { AgendaRow, CheckinResult, Connection, Contact, Event, EventFeedback, Feedback, FeedbackResult, LeaderboardRow, PointsLogRow, Preference, PublicContact, Registration, Session, Slot, WelcomeCheckinResult, WelcomeCheckinPreview, AcceptConnectionResult, TalkCohortMember, } 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; } /** Resolve a scanned lanyard QR token to public contact info (pre-login + connect). */ export async function lanyardLookup(qrToken: string): Promise { const rows = await rpc('lanyard_lookup', { p_qr_token: qrToken }); return rows && rows.length > 0 ? rows[0] : null; } /** Public directory of contacts registered for the active event (for connection names). */ export async function getPublicContacts(): Promise { return rpc('get_public_contacts', {}); } export async function getAgenda(): Promise { return rpc('get_agenda', {}); } /** Group the flat agenda rows into slots with their sessions. */ export function groupAgenda(rows: AgendaRow[]): { slot: Slot; sessions: Session[] }[] { const map = new Map(); for (const r of rows) { let entry = map.get(r.slot_id); if (!entry) { entry = { slot: { id: r.slot_id, event_id: '', type: r.slot_type, name: r.slot_name, slot_date: r.slot_date, start_time: r.start_time, end_time: r.end_time, }, sessions: [], }; map.set(r.slot_id, entry); } if (r.session_id && r.title) { entry.sessions.push({ id: r.session_id, event_id: '', slot_id: r.slot_id, slot_type: r.slot_type, title: r.title, description: r.description, room: r.room, capacity: r.capacity, average_feedback: r.average_feedback, ai_generated_feedback: r.ai_generated_feedback, material_path: r.material_path, speakers: r.speakers, level: r.level, area: r.area, language: r.language, created_at: '', }); } } // A service slot is only meaningful with a session behind it (break / lunch / // closing …). An orphan service slot — left over from an earlier feed or a // manual edit with no session row — would render as a header-only card, // inconsistent with every other service card. Drop those (mirroring how the // agenda already hides empty talk slots) so the list, its slot count, and // Home's Now/Next all agree. return [...map.values()] .filter(({ slot, sessions }) => slot.type !== 'service_session' || sessions.length > 0) .sort((first, second) => first.slot.slot_date.localeCompare(second.slot.slot_date) || first.slot.start_time.localeCompare(second.slot.start_time) || first.slot.end_time.localeCompare(second.slot.end_time) || first.slot.id - second.slot.id); } /** Submit (or update) the current user's event-level feedback. */ export async function submitEventFeedback(rating: number, comment: string): Promise<{ feedback_id: string; points: number; earned: number }> { const rows = await rpc<{ feedback_id: string; points: number; earned: number }[]>('submit_event_feedback', { p_rating: rating, p_comment: comment }); return rows[0]; } /** Read the current user's own event-level feedback (null if not yet submitted). */ export async function getMyEventFeedback(): Promise { const rows = await rpc('get_my_event_feedback', {}); return rows[0] ?? null; } /** The signed-in contact's own row (filter by email — admins can see all rows). */ export async function getMyContact(email: string): Promise { const { data, error } = await supabase.from('contacts').select('*').eq('email', email).maybeSingle(); if (error) throw new ApiError(error.message); return (data as Contact) ?? null; } /** The signed-in contact's registration for the active event. */ export async function getMyRegistration(email: string): Promise { const event = await getActiveEvent(); if (!event) return null; const { data, error } = await supabase.from('registrations').select('*').eq('contact_email', email).eq('event_id', event.id).maybeSingle(); if (error) throw new ApiError(error.message); return (data as Registration) ?? null; } /** Update the caller's own profile: LinkedIn URL + visibility toggles. */ export async function updateMyProfile(input: { linkedin_url: string | null; show_email: boolean; show_linkedin: boolean; }): Promise { return rpc('update_my_profile', { p_linkedin_url: input.linkedin_url, p_show_email: input.show_email, p_show_linkedin: input.show_linkedin, }); } export async function getActiveEvent(): 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 async function getMyPreferences(): Promise { const { data, error } = await supabase.from('preferences').select('*').order('slot_id'); if (error) throw new ApiError(error.message); return data as Preference[]; } export async function setPreference(sessionId: string): Promise { await rpc('set_preference', { p_session_id: sessionId }); } export async function clearPreference(slotId: number): Promise { await rpc('clear_preference', { p_slot_id: slotId }); } export async function getMyConnections(): Promise { const { data, error } = await supabase.from('connections').select('*').order('created_at', { ascending: false }); if (error) throw new ApiError(error.message); return data as Connection[]; } export async function createConnectionRequest(targetQr: string): Promise { // create_connection_request returns a single composite row (a JSON object). return rpc('create_connection_request', { p_target_qr: targetQr }); } export async function acceptConnection(id: string): Promise { // accept_connection returns a single composite row (a JSON object). return rpc('accept_connection', { p_connection_id: id }); } export async function rejectConnection(id: string): Promise { return rpc('reject_connection', { p_connection_id: id }); } /** Session ids the signed-in contact is checked into. */ export async function getMyCheckins(email: string): Promise { const { data, error } = await supabase.from('checkins').select('session_id').eq('contact_email', email); if (error) throw new ApiError(error.message); return (data as { session_id: string }[]).map((c) => c.session_id); } /** Other attendees (staff excluded, self excluded) checked into the same talk. */ export async function getTalkCohort(sessionId: string): Promise { return rpc('get_talk_cohort', { p_session_id: sessionId }); } export async function checkinAttendee(sessionId: string, attendeeQr: string): Promise { const rows = await rpc('checkin_attendee', { p_session_id: sessionId, p_attendee_qr: attendeeQr }); return rows[0]; } /** Staff welcome check-in: mark an attendee present at the event (no session). */ export async function welcomeCheckin(attendeeQr: string): Promise { const rows = await rpc('welcome_checkin', { p_attendee_qr: attendeeQr }); return rows[0]; } /** Read-only preview of a welcome check-in: resolves the attendee and reports * whether confirming will print their badge. Checks nobody in. */ export async function previewWelcomeCheckin(attendeeQr: string): Promise { const rows = await rpc('preview_welcome_checkin', { p_attendee_qr: attendeeQr }); return rows[0]; } export async function getMyFeedback(email: string): Promise { const { data, error } = await supabase.from('feedback').select('*').eq('contact_email', email); if (error) throw new ApiError(error.message); return data as Feedback[]; } export async function submitFeedback(sessionId: string, rating: number, comment: string): Promise { const rows = await rpc('submit_feedback', { p_session_id: sessionId, p_rating: rating, p_comment: comment }); return rows[0]; } export async function getLeaderboard(): Promise { return rpc('get_leaderboard', {}); } export async function getMyPointsLog(email: string): Promise { const { data, error } = await supabase .from('points_log') .select('*') .eq('contact_email', email) .order('created_at', { ascending: false }); if (error) throw new ApiError(error.message); return data as PointsLogRow[]; } /** Filename of a material object path (`sessions//-`). */ export function materialFilename(path: string): string { const base = path.slice(path.lastIndexOf('/') + 1); return base.replace(/^\d+-/, ''); } /** Download a session material through authenticated storage. The materials * bucket is private and server-side RLS only releases the file to the * session's own speakers/admins at any time, and to everyone else once the * session's scheduled end has passed — so this legitimately fails before the * end for plain attendees even if the UI clock disagrees. */ export async function downloadSessionMaterial(path: string): Promise { const { data, error } = await supabase.storage.from('materials').download(path); if (error) throw new ApiError('Download failed — material unlocks when the session ends.'); const url = URL.createObjectURL(data); const a = document.createElement('a'); a.href = url; a.download = materialFilename(path); document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); } /** Session ids the signed-in contact is a speaker of (for material upload). */ export async function getMySpeakerSessions(email: string): Promise { const { data, error } = await supabase .from('session_speakers') .select('session_id') .eq('contact_email', email); if (error) throw new ApiError(error.message); return (data as { session_id: string }[]).map((s) => s.session_id); } /** Upload a session material file to the `materials` bucket and set material_path. * The path is persisted via the `set_session_material` RPC (the sessions table * is admin-write only, so speakers need the security-definer RPC). */ export async function uploadSessionMaterial(sessionId: string, file: File): Promise { const { data: previous, error: readError } = await supabase.from('sessions').select('material_path').eq('id', sessionId).single(); if (readError) throw new ApiError(readError.message); const path = `sessions/${sessionId}/${crypto.randomUUID()}-${file.name.replace(/[^a-zA-Z0-9._-]/g, '_')}`; const { error: upErr } = await supabase.storage.from('materials').upload(path, file, { upsert: false }); if (upErr) throw new ApiError(upErr.message); const { error: dbErr } = await supabase.rpc('set_session_material', { p_session_id: sessionId, p_material_path: path, }); if (dbErr) { const { error: cleanupError } = await supabase.storage.from('materials').remove([path]); throw new ApiError(`${dbErr.message}${cleanupError ? ' The unattached upload could not be cleaned up.' : ''}`); } if (previous.material_path && previous.material_path !== path) { const { error: cleanupError } = await supabase.storage.from('materials').remove([previous.material_path]); if (cleanupError) throw new ApiError('Material saved, but the previous file could not be removed. Refresh to see the saved material.'); } return path; } /** Remove a session's material (storage object + clear material_path). Speakers * can delete their own material to re-upload; the path is cleared via the * `set_session_material` RPC (sessions is admin-write only). */ export async function removeSessionMaterial(sessionId: string): Promise { const { data, error: readError } = await supabase.from('sessions').select('material_path').eq('id', sessionId).single(); if (readError) throw new ApiError(readError.message); const path = (data as Session | null)?.material_path; const { error: dbErr } = await supabase.rpc('set_session_material', { p_session_id: sessionId, p_material_path: null, }); if (dbErr) throw new ApiError(dbErr.message); if (path) { const { error: rmErr } = await supabase.storage.from('materials').remove([path]); if (rmErr) throw new ApiError('Material detached, but the file could not be removed from storage.'); } }