Files
Convivo/apps/admin/src/lib/api.ts
T
f9a8513620 Real-time clock toggle: per-event use_realtime_clock flag
- Migration 20260834000000: events.use_realtime_clock (boolean, default false)
- Admin: Real-time clock toggle in the Events create/edit modal
- Convivo: useEvent picks new Date() vs simulated DEFAULT_NOW from the flag;
  Home shows a 'Demo clock' badge only in simulated mode
- Docs: app-structure, admin-app, schema, next-steps

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-08-25 09:22:28 +02:00

291 lines
12 KiB
TypeScript

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<T>(fn: string, args: Record<string, unknown>): Promise<T> {
const { data, error } = await supabase.rpc(fn, args);
if (error) throw new ApiError(error.message);
return data as T;
}
async function all<T>(table: string, order?: { col: string; asc?: boolean }): Promise<T[]> {
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<Contact>('contacts', { col: 'full_name' });
export const getAllEvents = () => all<Event>('events', { col: 'start_date', asc: false });
export const getActiveEvent = async (): Promise<Event | null> => {
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<Registration>('registrations', { col: 'points', asc: false }).then((rows) =>
rows.filter((r) => r.event_id === eventId),
);
export const getSponsors = (eventId: string) =>
all<Sponsor>('sponsors', { col: 'name' }).then((rows) => rows.filter((s) => s.event_id === eventId));
export const getSlots = (eventId: string) =>
all<Slot>('slots', { col: 'id' }).then((rows) => rows.filter((s) => s.event_id === eventId));
export const getSessions = (eventId: string) =>
all<Session>('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<SessionSpeaker>('session_speakers');
export const getAllConnections = () => all<Connection>('connections', { col: 'created_at', asc: false });
export const getAllCheckins = () => all<Checkin>('checkins', { col: 'created_at', asc: false });
export const getAllFeedback = () => all<Feedback>('feedback', { col: 'created_at', asc: false });
export const getAllPointsLog = () => all<PointsLogRow>('points_log', { col: 'created_at', asc: false });
export const getLeaderboard = () => all<LeaderboardRow>('leaderboard', { col: 'points', asc: false });
// ---- Contacts ----------------------------------------------------------------
export async function upsertContact(input: {
email: string;
full_name: string;
linkedin_url?: string | null;
is_admin?: boolean;
}): Promise<Contact> {
// 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<Contact>('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<Pick<Contact, 'full_name' | 'linkedin_url' | 'show_email' | 'show_linkedin' | 'is_admin'>>,
): Promise<void> {
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<ResetQrResult> {
const rows = await rpc<ResetQrResult[]>('reset_registration_qr_token', { p_contact_email: email });
return rows[0];
}
// ---- Registrations -----------------------------------------------------------
export async function createRegistration(contactEmail: string, type: Registration['type']): Promise<void> {
await rpc('create_registration', { p_contact_email: contactEmail, p_type: type });
}
export async function setRegistrationType(contactEmail: string, type: Registration['type']): Promise<void> {
await rpc('set_registration_type', { p_contact_email: contactEmail, p_type: type });
}
export async function setCheckedIn(registrationId: string, checkedIn: boolean): Promise<void> {
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<void> {
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<void> {
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<void> {
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<T>(path: string, init?: RequestInit): Promise<T> {
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<SidecarStatus>('/status');
/** Trigger a (blocking) Sessionize sync for an event. Resolves with the result. */
export const runSessionizeSync = (eventId: string) =>
sidecarFetch<SyncResult>('/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<ExcelSyncResult> {
const base64 = await new Promise<string>((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<ExcelSyncResult>('/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<SyncRun>('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<void> {
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<void> {
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<void> {
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<void> {
// 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<string> {
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<void> {
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<Session> {
// evaluate_session_feedback returns a single composite row (a JSON object, not an array).
return await rpc<Session>('evaluate_session_feedback', { p_session_id: sessionId });
}