Files
Convivo/supabase/functions/sync-trigger/index.ts
T
Lago b52d8ab007 Fixes & Refinements: QR token on registration, role caps, connection detail + red dot, admin schedule/sponsors
Datamodel:
- Move qr_token from contacts to registrations (per event); new migration
  20260826000000. lanyard_lookup / create_connection_request / checkin_attendee
  resolve via registrations + active event.
- reset_qr_token -> reset_registration_qr_token (fixes ambiguous 'email' col).
- upsert_contact drops the token arg; create_registration generates + syncs it.
- Pretix sync writes the token to the registration (keeps it on re-sync).

Registration types:
- Distinct pill colors; red reserved for Staff (both apps).
- Roles capitalized everywhere (Attendee/Speaker/Sponsor/Staff); 'Attendee'
  hidden only at the Home footer.
- Reset-token button moved from Contacts to Registrations (per registration).

Sessions (APPE Admin):
- Slot types capitalized; material submitted/not-submitted state.
- Speaker selection = multi-select search dropdown.
- Fix 'a session must have a speaker' on edit (diff-based setSessionSpeakers)
  and the file-upload bug (speaker save no longer aborts first).

APPE Admin:
- Sponsors contact lookup = search field (filter + pick).

Convivo App:
- Other people's QR codes hidden; connection detail sheet shows public info +
  points.
- Connect red dot recalculates immediately on accept/decline/send.
- 'My picks today' = 2 rows (current + next); 'tap to change' links to Agenda.

Docs updated across backend + frontend.
2026-08-23 10:39:21 +02:00

198 lines
6.8 KiB
TypeScript

// Convivo — sync-trigger Edge Function (Phase 7 + 8).
//
// Pulls real data from Pretix (tickets) and Sessionize (agenda) and pushes it
// into the multi-event model via the service-role-only sync RPCs
// (`sync_pretix_attendees`, `sync_sessionize_sessions`).
//
// Trigger:
// POST / { "source": "pretix" | "sessionize" | "both" }
//
// Auth (either):
// * A valid **admin** JWT in the `Authorization` header (the APPE Admin app
// calls this from its Sync view). Verified by calling the `is_admin()` RPC.
// * A matching `x-cron-secret` header == CRON_SECRET (for scheduled runs).
//
// Config (env, all optional — defaults point at the local mock API):
// PRETIX_BASE_URL (default http://mock-api:54330)
// PRETIX_API_TOKEN (Pretix org/event API token)
// SESSIONIZE_BASE_URL (default http://mock-api:54330)
// SESSIONIZE_API_KEY (Sessionize API key)
// CRON_SECRET (shared secret for scheduled triggers)
//
// No npm dependencies — uses the global `fetch` + `Deno.serve`.
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? 'http://kong:8000';
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '';
const PRETIX_BASE_URL = (Deno.env.get('PRETIX_BASE_URL') ?? 'http://mock-api:54330').replace(/\/+$/, '');
const PRETIX_API_TOKEN = Deno.env.get('PRETIX_API_TOKEN') ?? '';
const SESSIONIZE_BASE_URL = (Deno.env.get('SESSIONIZE_BASE_URL') ?? 'http://mock-api:54330').replace(/\/+$/, '');
const SESSIONIZE_API_KEY = Deno.env.get('SESSIONIZE_API_KEY') ?? '';
const CRON_SECRET = Deno.env.get('CRON_SECRET') ?? '';
type Source = 'pretix' | 'sessionize' | 'both';
function json(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
// Verify the caller is an admin by calling the is_admin() RPC with their JWT.
async function isAdmin(authorization: string | null): Promise<boolean> {
if (!authorization) return false;
const res = await fetch(`${SUPABASE_URL}/rest/v1/rpc/is_admin`, {
method: 'POST',
headers: {
apikey: SERVICE_ROLE_KEY,
Authorization: authorization,
'Content-Type': 'application/json',
},
body: '{}',
});
if (!res.ok) return false;
return (await res.json()) === true;
}
// Call a service-role sync RPC via PostgREST.
async function callSyncRpc(fn: string, argName: string, payload: unknown): Promise<unknown> {
const res = await fetch(`${SUPABASE_URL}/rest/v1/rpc/${fn}`, {
method: 'POST',
headers: {
apikey: SERVICE_ROLE_KEY,
Authorization: `Bearer ${SERVICE_ROLE_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ [argName]: payload }),
});
const text = await res.text();
if (!res.ok) {
throw new Error(`${fn} failed (${res.status}): ${text}`);
}
return JSON.parse(text);
}
// ---- Pretix: fetch + normalize ---------------------------------------------
async function fetchPretixAttendees(): Promise<Record<string, unknown>[]> {
const res = await fetch(`${PRETIX_BASE_URL}/pretix/attendees`, {
headers: PRETIX_API_TOKEN ? { Authorization: `Bearer ${PRETIX_API_TOKEN}` } : {},
});
if (!res.ok) throw new Error(`Pretix fetch failed (${res.status})`);
const data = (await res.json()) as { results?: PretixOrder[] };
const results = data.results ?? [];
return results.map((a) => ({
email: a.attendee_email,
full_name: a.attendee_name,
ticket_type: a.ticket_type,
external_id: a.order_code,
// Pretix generates a QR token per ticket; it becomes the registration's
// token (and the login password).
qr_token: a.qr_token ?? null,
}));
}
interface PretixOrder {
order_code: string;
attendee_name: string;
attendee_email: string;
ticket_type: string;
qr_token?: string;
}
// ---- Sessionize: fetch + normalize -----------------------------------------
async function fetchSessionizeSessions(): Promise<Record<string, unknown>[]> {
const res = await fetch(`${SESSIONIZE_BASE_URL}/sessionize/sessions`, {
headers: SESSIONIZE_API_KEY ? { 'X-Api-Key': SESSIONIZE_API_KEY } : {},
});
if (!res.ok) throw new Error(`Sessionize fetch failed (${res.status})`);
const data = (await res.json()) as { sessions?: SessionizeSession[] };
const sessions = data.sessions ?? [];
return sessions.map((s) => ({
external_id: s.id,
title: s.title,
description: s.description ?? null,
room: s.room ?? null,
capacity: s.capacity ?? null,
date: s.start_time.slice(0, 10),
start_time: s.start_time.slice(11, 16),
end_time: s.end_time.slice(11, 16),
speakers: (s.speakers ?? []).map((sp) => ({ email: sp.email, full_name: sp.name })),
}));
}
interface SessionizeSession {
id: string;
title: string;
description?: string;
room?: string;
capacity?: number;
start_time: string; // ISO 8601
end_time: string; // ISO 8601
speakers?: { id: string; name: string; email: string }[];
}
// ---- Handler ---------------------------------------------------------------
Deno.serve(async (req: Request) => {
if (req.method === 'OPTIONS') {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Authorization, Content-Type, x-cron-secret',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
},
});
}
if (req.method !== 'POST') {
return json(405, { error: 'method not allowed; use POST' });
}
// Auth: admin JWT or cron secret.
const authorization = req.headers.get('Authorization');
const cronSecret = req.headers.get('x-cron-secret');
const isCron = CRON_SECRET !== '' && cronSecret === CRON_SECRET;
if (!isCron) {
const admin = await isAdmin(authorization);
if (!admin) return json(401, { error: 'admin or cron secret required' });
}
let source: Source = 'both';
try {
const body = await req.json();
if (body && typeof body.source === 'string') source = body.source as Source;
} catch {
// no body → default to 'both'
}
const results: Record<string, unknown> = {};
const errors: string[] = [];
if (source === 'pretix' || source === 'both') {
try {
const attendees = await fetchPretixAttendees();
results.pretix = await callSyncRpc('sync_pretix_attendees', 'p_attendees', attendees);
} catch (e) {
errors.push(`pretix: ${(e as Error).message}`);
}
}
if (source === 'sessionize' || source === 'both') {
try {
const sessions = await fetchSessionizeSessions();
results.sessionize = await callSyncRpc('sync_sessionize_sessions', 'p_sessions', sessions);
} catch (e) {
errors.push(`sessionize: ${(e as Error).message}`);
}
}
return json(errors.length > 0 ? 207 : 200, {
ok: errors.length === 0,
triggered_by: isCron ? 'cron' : 'admin',
results,
errors,
});
});