Existing-sponsor link + remove Interfaces (Pretix/Sessionize)

- Sponsor lookup popup can now link an existing sponsor (dropdown + pre-fill)
  or create a new one; save upserts the sponsor linked to the contact and sets
  the registration type to sponsor.
- Remove the Interfaces feature end-to-end: admin nav button + Sync view, sync
  API helpers + SyncRun type, sync-trigger Edge Function, mock-api + its
  docker-compose service, and a migration dropping the sync RPCs, helpers, and
  sync_runs table.
- Update docs (architecture, backend, frontend, README, roadmap, next-steps).
This commit is contained in:
Lago committed 2026-08-24 09:11:25 +02:00
1 parent 1cbbd1b529
commit a54ce69c4d
27 files changed
+147 -1150

No files matched your search

-197
View File
@@ -1,197 +0,0 @@
// 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,
});
});
@@ -0,0 +1,27 @@
-- =============================================================================
-- Convivo — remove the Pretix/Sessionize "Interfaces" feature
--
-- The Interfaces feature (Phases 7 + 8) is being removed: the APPE Admin
-- "Interfaces" view, the `sync-trigger` Edge Function, the local mock API, and
-- the supporting DB objects. This migration drops the DB side:
--
-- * `sync_pretix_attendees(jsonb)` — service-role sync RPC (Pretix tickets)
-- * `sync_sessionize_sessions(jsonb)` — service-role sync RPC (Sessionize agenda)
-- * `_ensure_auth_user(text,text,text)` — helper used only by the sync RPCs
-- * `_map_ticket_type(text)` — helper used only by the sync RPCs
-- * `sync_runs` table (+ index, RLS policies) — sync audit trail
--
-- The `external_id` columns added by the interfaces migration are left in place
-- (they are harmless, nullable, and part of the base table definitions).
-- =============================================================================
-- Drop the sync RPCs first (they reference the helpers + sync_runs).
drop function if exists public.sync_pretix_attendees(jsonb);
drop function if exists public.sync_sessionize_sessions(jsonb);
-- Drop the sync-only helper functions.
drop function if exists public._ensure_auth_user(text, text, text);
drop function if exists public._map_ticket_type(text);
-- Drop the audit table (cascades to its index + RLS policies).
drop table if exists public.sync_runs;