Files
Convivo/apps/convivo/src/lib/api.ts
T
0221b1a8c0 Admin password login + attendee profile self-service
- contacts.password: admin-only APPE Admin login password (event-independent);
  must match the bcrypt hash in auth.users.encrypted_password (set in Supabase).
- APPE Admin login is now email + password (was QR token).
- update_my_profile RPC (security definer, scoped to current_email()): attendees
  set their LinkedIn URL + show_email / show_linkedin toggles from the Profile.
- Convivo Profile gains a 'Profile settings' card (LinkedIn + 2 toggles + Save).
- Visibility enforced server-side in the public projection (linkedin nulled when
  show_linkedin off, email omitted when show_email off).
- Seed: admin password appe-admin-2026; staff keep QR tokens as auth passwords.
- Docs updated (schema, rpcs, seed, admin-app, screens, api-client,
  architecture, next-steps, README, docker-compose).

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-23 14:11:26 +02:00

215 lines
7.8 KiB
TypeScript

import { supabase } from './supabase';
import type {
AgendaRow,
CheckinResult,
Connection,
Contact,
Event,
Feedback,
FeedbackResult,
LeaderboardRow,
PointsLogRow,
Preference,
PublicContact,
Registration,
Session,
Slot,
} 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;
}
/** Resolve a scanned lanyard QR token to public contact info (pre-login + connect). */
export async function lanyardLookup(qrToken: string): Promise<PublicContact | null> {
const rows = await rpc<PublicContact[]>('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<PublicContact[]> {
return rpc<PublicContact[]>('get_public_contacts', {});
}
export async function getAgenda(): Promise<AgendaRow[]> {
return rpc<AgendaRow[]>('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<number, { slot: Slot; sessions: Session[] }>();
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,
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,
created_at: '',
});
}
}
return [...map.values()].sort((a, b) => a.slot.id - b.slot.id);
}
/** The signed-in contact's own row (filter by email — admins can see all rows). */
export async function getMyContact(email: string): Promise<Contact | null> {
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<Registration | null> {
const { data, error } = await supabase.from('registrations').select('*').eq('contact_email', email).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<Contact> {
return rpc<Contact>('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<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 async function getMyPreferences(): Promise<Preference[]> {
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<void> {
await rpc('set_preference', { p_session_id: sessionId });
}
export async function clearPreference(slotId: number): Promise<void> {
await rpc('clear_preference', { p_slot_id: slotId });
}
export async function getMyConnections(): Promise<Connection[]> {
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<Connection> {
// create_connection_request returns a single composite row (a JSON object).
return rpc<Connection>('create_connection_request', { p_target_qr: targetQr });
}
export async function acceptConnection(id: string): Promise<Connection> {
return rpc<Connection>('accept_connection', { p_connection_id: id });
}
export async function rejectConnection(id: string): Promise<Connection> {
return rpc<Connection>('reject_connection', { p_connection_id: id });
}
/** Session ids the signed-in contact is checked into. */
export async function getMyCheckins(email: string): Promise<string[]> {
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);
}
export async function checkinAttendee(sessionId: string, attendeeQr: string): Promise<CheckinResult> {
const rows = await rpc<CheckinResult[]>('checkin_attendee', { p_session_id: sessionId, p_attendee_qr: attendeeQr });
return rows[0];
}
export async function getMyFeedback(email: string): Promise<Feedback[]> {
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<FeedbackResult> {
const rows = await rpc<FeedbackResult[]>('submit_feedback', { p_session_id: sessionId, p_rating: rating, p_comment: comment });
return rows[0];
}
export async function getLeaderboard(): Promise<LeaderboardRow[]> {
return rpc<LeaderboardRow[]>('get_leaderboard', {});
}
export async function getMyPointsLog(email: string): Promise<PointsLogRow[]> {
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[];
}
/** Public URL for a session material stored in the `materials` bucket. */
export function sessionMaterialUrl(path: string): string {
const { data } = supabase.storage.from('materials').getPublicUrl(path);
return data.publicUrl;
}
/** Session ids the signed-in contact is a speaker of (for material upload). */
export async function getMySpeakerSessions(email: string): Promise<string[]> {
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<string> {
const path = `sessions/${sessionId}/${Date.now()}-${file.name.replace(/[^a-zA-Z0-9._-]/g, '_')}`;
const { error: upErr } = await supabase.storage.from('materials').upload(path, file, { upsert: true });
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) throw new ApiError(dbErr.message);
return path;
}