Files
Convivo/apps/admin/src/lib/api.ts
T
Lago d4e4637e7c feat(sessions): material downloads unlock when the session ends
Private materials bucket + RLS read gate (admins/own speakers anytime, all
attendees after the scheduled slot end, event-local Amsterdam time); always
visible uploaded-state, locked download panel, authenticated client downloads,
admin signed URLs. 12 new assertions in material_time_lock_tests.sql.
2026-10-21 18:57:15 +02:00

614 lines
26 KiB
TypeScript

import { supabase } from './supabase';
import type {
BadgeElement,
BadgeLayout,
Checkin,
Connection,
Contact,
DeleteEventScheduleResult,
Event,
EventFeedback,
ExcelSyncResult,
Feedback,
FeedbackSummary,
LlmSettings,
LlmTestResult,
LeaderboardRow,
PointsLogRow,
PretixOptions,
PretixSyncResult,
PrintOverview,
RafflePoolEntry,
RaffleWinner,
Registration,
ResetQrResult,
Session,
SessionSpeaker,
SidecarStatus,
Slot,
Sponsor,
SyncResult,
SyncRun,
} from './types';
export class ApiError extends Error {}
/** The default admin password for @appe.at contacts (set by the DB trigger). */
export const DEFAULT_ADMIN_PASSWORD = 'appe-admin-2026';
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[];
}
/**
* Paged read of one event's rows. PostgREST is configured with
* `max_rows = 1000` (supabase/config.toml) and `all()` above has no paging, so a
* single unsorted select silently truncates at 1000 — fine for contacts at this
* event's size, not fine for check-ins once every attendee has scanned a few
* sessions. `id` is the tiebreaker so rows cannot shift between pages.
*/
async function pagedForEvent<T>(table: string, eventId: string, order: { col: string; asc?: boolean }): Promise<T[]> {
const rows: T[] = [];
for (let offset = 0; ; offset += 500) {
let q = supabase.from(table).select('*').eq('event_id', eventId);
q = q.order(order.col, { ascending: order.asc ?? true }).order('id', { ascending: true });
const { data, error } = await q.range(offset, offset + 499);
if (error) throw new ApiError(error.message);
rows.push(...(data as T[]));
if (data.length < 500) return rows;
}
}
// ---- 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 });
/** Check-ins for one event, paged past the 1000-row PostgREST cap. */
export const getEventCheckins = (eventId: string) =>
pagedForEvent<Checkin>('checkins', eventId, { col: 'created_at', asc: false });
/** Session feedback for one event, paged past the 1000-row cap. */
export const getEventFeedbackRows = (eventId: string) =>
pagedForEvent<Feedback>('feedback', eventId, { col: 'created_at', asc: false });
/**
* Speaker links for one event. `session_speakers` has no event_id column, so
* this filters through the session FK with an inner join — a plain `all()`
* would return every event's links and truncate at 1000 rows.
*/
export async function getEventSessionSpeakers(eventId: string): Promise<SessionSpeaker[]> {
const rows: SessionSpeaker[] = [];
for (let offset = 0; ; offset += 500) {
const { data, error } = await supabase
.from('session_speakers')
.select('session_id, contact_email, sessions!inner(event_id)')
.eq('sessions.event_id', eventId)
.order('session_id', { ascending: true })
.order('contact_email', { ascending: true })
.range(offset, offset + 499);
if (error) throw new ApiError(error.message);
for (const r of data as (SessionSpeaker & { sessions?: unknown })[]) {
delete r.sessions;
rows.push(r);
}
if (data.length < 500) return rows;
}
}
export const getAllEventFeedback = () => all<EventFeedback>('event_feedback', { col: 'created_at', asc: false });
async function eventFeedbackRows<T>(table: 'feedback' | 'event_feedback', eventId: string): Promise<T[]> {
const rows: T[] = [];
for (let offset = 0; ; offset += 500) {
const { data, error } = await supabase.from(table).select('*').eq('event_id', eventId)
.order('created_at', { ascending: false }).order('id', { ascending: false }).range(offset, offset + 499);
if (error) throw new ApiError(error.message);
rows.push(...data as T[]);
if (data.length < 500) return rows;
}
}
export const getEventSessionFeedback = (eventId: string) => eventFeedbackRows<Feedback>('feedback', eventId);
export const getEventFeedback = (eventId: string) => eventFeedbackRows<EventFeedback>('event_feedback', eventId);
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);
}
/** Delete a single contact (admin-only RLS). Cascades to their registrations. */
export async function deleteContact(email: string): Promise<void> {
const { error } = await supabase.from('contacts').delete().eq('email', email);
if (error) throw new ApiError(error.message);
}
/**
* Delete many contacts at once (admin-only). Uses the `bulk_delete_contacts`
* RPC, which bypasses the "a session must have at least one speaker" guard —
* a direct PostgREST delete would fail (P0001) if the batch includes a contact
* who is the sole speaker of a session.
*/
export async function deleteContacts(emails: string[]): Promise<void> {
if (emails.length === 0) return;
await rpc<number>('bulk_delete_contacts', { p_emails: emails });
}
/**
* Change the current admin's own login password. Sets `contacts.password`
* (the `trg_contact_password_sync` trigger re-hashes it into
* `auth.users.encrypted_password`), then re-authenticates with the new
* password so the session reflects the change.
*/
export async function changeMyPassword(email: string, newPassword: string): Promise<void> {
const { error: updateError } = await supabase
.from('contacts')
.update({ password: newPassword })
.eq('email', email);
if (updateError) throw new ApiError(updateError.message);
const { error: signInError } = await supabase.auth.signInWithPassword({
email,
password: newPassword,
});
if (signInError) throw new ApiError(signInError.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 });
}
/**
* Flip an attendee's event check-in state. Turning it OFF removes every point
* this person earned from check-ins in the event; turning it back ON restores the
* points their surviving session check-ins justify (see
* set_registration_checked_in). Only one of the two is ever non-zero.
*/
export async function setCheckedIn(
registrationId: string,
checkedIn: boolean,
): Promise<{ removed: number; added: number }> {
const rows = await rpc<{
registration_id: string;
checked_in: boolean;
points_removed: number;
points_added?: number;
}[]>('set_registration_checked_in', { p_registration_id: registrationId, p_checked_in: checkedIn });
if (!rows?.length) throw new ApiError('Registration no longer exists');
return { removed: rows[0].points_removed ?? 0, added: rows[0].points_added ?? 0 };
}
export const mergeTickets = (sourceId: string, targetId: string) =>
rpc<import('./types').TicketMergeResult>('merge_tickets', { p_source_id: sourceId, p_target_id: targetId });
// ---- 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;
company?: string | null;
sessionize_endpoint?: string | null;
pretix_organizer?: string | null;
pretix_event_slug?: string | null;
pretix_api_key?: string | null;
use_realtime_clock?: boolean;
talk_networking_bonus?: number;
badge_copies?: number;
},
): 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);
}
}
/**
* Set how many badge labels a welcome (front-desk) check-in prints for one
* event. Scoped update on purpose: it touches only this column, so it can never
* overwrite another field the Events form happens to hold stale values for.
* Clamped to 1..4 in the database (events.badge_copies check constraint).
*/
export async function setBadgeCopies(eventId: string, copies: number): Promise<void> {
const value = Math.max(1, Math.min(4, Math.round(copies) || 1));
const { error } = await supabase.from('events').update({ badge_copies: value }).eq('id', eventId);
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 }) });
/** Trigger a (blocking) Pretix sync for an event. Resolves with the result. */
export const runPretixSync = (eventId: string) =>
sidecarFetch<PretixSyncResult>('/run-pretix', { method: 'POST', body: JSON.stringify({ event_id: eventId }) });
/**
* Ask the sidecar to list the given Pretix API key's organizers + their active
* events. Used by the event-settings "paste the API key" flow to populate the
* organizer + event-slug dropdowns from real data.
*/
export const fetchPretixOptions = (apiKey: string) =>
sidecarFetch<PretixOptions>('/pretix-options', { method: 'POST', body: JSON.stringify({ api_key: apiKey }) });
/**
* 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 }),
});
}
/**
* Request an event report from the sidecar (`POST /export`). Returns the
* filename, mime type, and base64 content; the caller decodes and downloads.
*/
export const exportEventReport = (
eventId: string,
format: 'csv' | 'xlsx' | 'pdf',
tables?: string[],
) =>
sidecarFetch<{ filename: string; mime: string; content_base64: string }>('/export', {
method: 'POST',
body: JSON.stringify({ event_id: eventId, format, tables }),
});
/** Decode a base64 report body and trigger a browser download. */
export function downloadReport(res: { filename: string; mime: string; content_base64: string }): void {
const bytes = Uint8Array.from(atob(res.content_base64), (c) => c.charCodeAt(0));
const blob = new Blob([bytes], { type: res.mime });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = res.filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/** 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),
);
/** Recent Pretix sync_runs rows for an event (newest first). */
export const getPretixRuns = (eventId: string) =>
getSyncRuns(eventId).then((rows) => rows.filter((r) => r.source === 'pretix'));
/** 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);
}
export async function deleteEventSchedule(eventId: string): Promise<DeleteEventScheduleResult> {
return await rpc<DeleteEventScheduleResult>('delete_event_schedule', { p_event_id: eventId });
}
// ---- 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 });
}
// ---- Raffle ------------------------------------------------------------------
/** Eligible attendees for the active event: excludes staff/Admin, the
* leaderboard top 3, and everyone already drawn in the current run. */
export async function getRafflePool(): Promise<RafflePoolEntry[]> {
return rpc<RafflePoolEntry[]>('get_raffle_pool', {});
}
/** Winners already drawn in the current run (oldest first). */
export async function getRaffleWinners(): Promise<RaffleWinner[]> {
return all<RaffleWinner>('raffle_draws', { col: 'draw_number' });
}
/** Draw one random eligible attendee and record them as the next winner. */
export async function drawRaffleWinner(): Promise<RaffleWinner> {
const rows = await rpc<Omit<RaffleWinner, 'drawn_at'>[]>('draw_raffle_winner', {});
if (!rows[0]) throw new ApiError('No eligible attendees left to draw');
return { ...rows[0], drawn_at: new Date().toISOString() };
}
/** Clear the current run's winners so a new run can begin. */
export async function resetRaffle(): Promise<void> {
await rpc('reset_raffle', {});
}
// ---- Badge editor (per-event WYSIWYG badge layout) --------------------------
/** All badge layouts for an event (default first, then by name). */
export async function getBadgeLayouts(eventId: string): Promise<BadgeLayout[]> {
const rows = await all<BadgeLayout>('badge_layouts');
return rows
.filter((r) => r.event_id === eventId)
.sort((a, b) => Number(b.is_default) - Number(a.is_default) || a.name.localeCompare(b.name));
}
/** Insert or update a layout (matched on event_id + name). */
export async function saveBadgeLayout(input: {
event_id: string;
name: string;
page_width_mm: number;
page_height_mm: number;
elements: BadgeElement[];
is_default: boolean;
}): Promise<BadgeLayout> {
return rpc<BadgeLayout>('save_badge_layout', {
p_event_id: input.event_id,
p_name: input.name,
p_page_width_mm: input.page_width_mm,
p_page_height_mm: input.page_height_mm,
p_elements: input.elements,
p_is_default: input.is_default,
});
}
/** Promote a layout to the event's default (demoting the previous one). */
export async function setDefaultBadgeLayout(id: string): Promise<void> {
await rpc('set_default_badge_layout', { p_id: id });
}
/** Delete a layout (the sole default may not be removed). */
export async function deleteBadgeLayout(id: string): Promise<void> {
await rpc('delete_badge_layout', { p_id: id });
}
// ---- 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);
}
/** Open a session material in a new tab via a short-lived signed URL. The
* materials bucket is private; storage RLS always allows admins. */
export async function openSessionMaterial(path: string): Promise<void> {
const { data, error } = await supabase.storage.from('materials').createSignedUrl(path, 600);
if (error) throw new ApiError(error.message);
window.open(data.signedUrl, '_blank');
}
async function feedbackSidecarFetch<T>(path: string, init?: RequestInit): Promise<T> {
const { data, error } = await supabase.auth.getSession();
if (error || !data.session) throw new ApiError('Sign in as an administrator');
return sidecarFetch<T>(path, {
...init,
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${data.session.access_token}` },
});
}
export const getLlmSettings = () => feedbackSidecarFetch<LlmSettings>('/llm-settings');
export const saveLlmSettings = (input: { endpoint: string; model: string; api_key?: string }) =>
feedbackSidecarFetch<LlmSettings>('/llm-settings', { method: 'PUT', body: JSON.stringify(input) });
/**
* Ask the sidecar to make one real chat request with the stored settings and
* report a verdict. Returns the verdict rather than throwing on a bad
* connection, because the reason (wrong key, unreachable host, model still
* thinking) is what the UI has to show. Only throws for transport/auth faults.
* Always reads the settings saved in the DB, never the form's current values.
*/
export const testLlmConnection = () => feedbackSidecarFetch<LlmTestResult>('/llm-test', { method: 'POST' });
export async function getFeedbackSummaries(eventId: string): Promise<FeedbackSummary[]> {
const { data, error } = await supabase.from('feedback_summaries').select('*').eq('event_id', eventId);
if (error) throw new ApiError(error.message);
return data as FeedbackSummary[];
}
export const generateFeedbackSummary = (eventId: string, sessionId?: string) =>
feedbackSidecarFetch<FeedbackSummary>('/feedback-summary', {
method: 'POST',
body: JSON.stringify({ event_id: eventId, scope: sessionId ? 'session' : 'event', ...(sessionId ? { session_id: sessionId } : {}) }),
});
// ---- Badge printing (queue + printer stations) -------------------------------
/** Admin dashboard snapshot: stations, queue counters, recent jobs, dead letters. */
export const getPrintOverview = () => rpc<PrintOverview>('get_print_overview', {});
/** Queue one attendee's badge for printing; resolves with the queue msg id. */
export const enqueueBadgePrint = (registrationId: string) =>
rpc<number>('enqueue_badge_print', { p_registration_id: registrationId });
/** Register a printer station. The token is returned only here, never again. */
export async function createPrintStation(name: string): Promise<{ id: string; token: string }> {
// create_print_station returns a one-row table (a JSON array of one object).
const rows = await rpc<{ id: string; token: string }[]>('create_print_station', { p_name: name });
if (!rows[0]) throw new ApiError('Station creation returned no token');
return rows[0];
}
/** Retire a station; its token stops working immediately. */
export const revokePrintStation = (id: string) => rpc<void>('revoke_print_station', { p_id: id });
/** Rename a station (revoked ones included); the Pi adopts the new name. */
export const renamePrintStation = (id: string, name: string) =>
rpc<void>('rename_print_station', { p_id: id, p_name: name });
/** Push a dead letter back onto the live queue; resolves with the new msg id. */
export const requeueDeadBadgePrint = (msgId: number) =>
rpc<number>('requeue_dead_badge_print', { p_msg_id: msgId });
/** Drop a dead letter without retrying it. */
export const discardDeadBadgePrint = (msgId: number) => rpc<void>('discard_dead_badge_print', { p_msg_id: msgId });