Phase 7+8: Pretix + Sessionize interfaces

- Migration 20260825000000_interfaces.sql: external_id on contacts/
  registrations/sessions (+ partial unique indexes), slots_id_seq, sync_runs
  audit table, and service-role-only sync_pretix_attendees /
  sync_sessionize_sessions RPCs (idempotent upserts).
- sync-trigger Edge Function: admin-JWT or CRON_SECRET auth, pulls from
  Pretix/Sessionize base URLs, normalizes, calls the service-role RPCs.
- interfaces/mock-api: dependency-free Node server (:54330) + fixtures so the
  full pipeline is testable without real tokens.
- APPE Admin 'Interfaces' view: per-source + 'Sync all' triggers, result
  counts, recent sync runs, and QR CSV export; /functions proxy added.
- Docs: new docs/backend/interfaces.md; updated README, roadmap, next-steps,
  schema, rls, rpcs, architecture, admin-app, and docs index.
This commit is contained in:
Lago committed 2026-08-23 03:34:30 +02:00
1 parent 22f5f1d317
commit 16f304d145
26 files changed
+1529 -80

No files matched your search

+9
View File
@@ -74,4 +74,13 @@ server {
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 50M;
}
# Edge Functions (e.g. sync-trigger for the Pretix/Sessionize interfaces).
location /functions/ {
proxy_pass http://__SUPABASE_PROXY_TARGET__;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
+12 -1
View File
@@ -9,9 +9,18 @@ import { Sponsors } from './views/Sponsors';
import { Schedule } from './views/Schedule';
import { Activity } from './views/Activity';
import { Events } from './views/Events';
import { Sync } from './views/Sync';
import { Spinner } from './components/ui';
export type View = 'dashboard' | 'contacts' | 'registrations' | 'sponsors' | 'schedule' | 'activity' | 'events';
export type View =
| 'dashboard'
| 'contacts'
| 'registrations'
| 'sponsors'
| 'schedule'
| 'activity'
| 'events'
| 'sync';
const NAV: { id: View; label: string; ico: string }[] = [
{ id: 'dashboard', label: 'Dashboard', ico: '📊' },
@@ -21,6 +30,7 @@ const NAV: { id: View; label: string; ico: string }[] = [
{ id: 'schedule', label: 'Schedule', ico: '🗓️' },
{ id: 'activity', label: 'Activity', ico: '⚡' },
{ id: 'events', label: 'Events', ico: '📅' },
{ id: 'sync', label: 'Interfaces', ico: '🔄' },
];
function Shell() {
@@ -88,6 +98,7 @@ function Shell() {
{view === 'schedule' && <Schedule />}
{view === 'activity' && <Activity />}
{view === 'events' && <Events />}
{view === 'sync' && <Sync />}
</main>
</div>
);
+69
View File
@@ -13,6 +13,7 @@ import type {
SessionSpeaker,
Slot,
Sponsor,
SyncRun,
} from './types';
export class ApiError extends Error {}
@@ -206,3 +207,71 @@ export async function evaluateSessionFeedback(sessionId: string): Promise<Sessio
// 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 });
}
// ---- Interfaces: Pretix + Sessionize sync (Phase 7 + 8) ---------------------
export interface SyncResult {
ok: boolean;
triggered_by: string;
results: {
pretix?: { created: number; updated: number; skipped: number; errors: string[] };
sessionize?: {
slots_created: number;
sessions_created: number;
sessions_updated: number;
speakers_linked: number;
errors: string[];
};
};
errors: string[];
}
/**
* Trigger a sync from the `sync-trigger` Edge Function. The admin's session
* JWT is passed as the Authorization header; the function verifies it is an
* admin (via the is_admin() RPC) before running.
*/
export async function triggerSync(source: 'pretix' | 'sessionize' | 'both'): Promise<SyncResult> {
const { data } = await supabase.auth.getSession();
const token = data.session?.access_token;
if (!token) throw new ApiError('not signed in');
const res = await fetch('/functions/v1/sync-trigger', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ source }),
});
const body = (await res.json()) as SyncResult & { error?: string };
if (!res.ok) throw new ApiError(body.error ?? `sync failed (${res.status})`);
return body;
}
/** Recent sync runs (audit trail), newest first. */
export const getSyncRuns = (limit = 10) =>
all<SyncRun>('sync_runs', { col: 'started_at', asc: false }).then((rows) => rows.slice(0, limit));
/**
* Build a CSV of lanyard QR codes for the active event's registrations
* (name, email, type, QR token) and trigger a browser download.
*/
export async function exportQrCsv(eventId: string): Promise<number> {
const regs = await getRegistrations(eventId);
const contacts = await getAllContacts();
const byEmail = new Map(contacts.map((c) => [c.email, c]));
const esc = (v: string | null | undefined) => `"${(v ?? '').replace(/"/g, '""')}"`;
const lines = ['name,email,type,qr_token'];
let count = 0;
for (const r of regs) {
const c = byEmail.get(r.contact_email);
if (!c?.qr_token) continue;
lines.push([esc(c.full_name), esc(c.email), esc(r.type), esc(c.qr_token)].join(','));
count++;
}
const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `lanyard-qr-codes-${eventId.slice(0, 8)}.csv`;
a.click();
URL.revokeObjectURL(url);
return count;
}
+12
View File
@@ -142,3 +142,15 @@ export interface ResetQrResult {
email: string;
qr_token: string;
}
export interface SyncRun {
id: string;
source: 'pretix' | 'sessionize';
started_at: string;
finished_at: string | null;
created: number;
updated: number;
skipped: number;
error: string | null;
triggered_by: string;
}
+2
View File
@@ -113,6 +113,8 @@ body {
.pill.swag { background: rgba(219,39,119,.12); border-color: rgba(219,39,119,.4); color: #be185d; }
.pill.catering { background: rgba(234,88,12,.13); border-color: rgba(234,88,12,.4); color: #c2410c; }
.pill.diversity { background: rgba(124,58,237,.12); border-color: rgba(124,58,237,.4); color: #6d28d9; }
/* sync result pills (Interfaces view) */
.sync-result { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 12px; }
.avatar { display: inline-flex; align-items: center; justify-content: center; border-radius: 50%; font-weight: 800; color: #fff; flex-shrink: 0; }
.input, select.input {
width: 100%; padding: 12px 14px; border-radius: 12px; border: 1px solid var(--line);
+240
View File
@@ -0,0 +1,240 @@
import { useCallback, useEffect, useState } from 'react';
import {
exportQrCsv,
getActiveEvent,
getSyncRuns,
triggerSync,
type SyncResult,
} from '../lib/api';
import type { Event, SyncRun } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Spinner } from '../components/ui';
type Source = 'pretix' | 'sessionize' | 'both';
function fmtTime(iso: string | null): string {
if (!iso) return '—';
const d = new Date(iso);
return d.toLocaleString(undefined, {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
}
function SourcePill({ source }: { source: SyncRun['source'] }) {
return <span className={`pill ${source === 'pretix' ? 'gold' : 'green'}`}>{source}</span>;
}
export function Sync() {
const { push } = useToast();
const [event, setEvent] = useState<Event | null>(null);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const [runs, setRuns] = useState<SyncRun[]>([]);
const [busy, setBusy] = useState<Source | null>(null);
const [last, setLast] = useState<SyncResult | null>(null);
const load = useCallback(async () => {
try {
const [ev, r] = await Promise.all([getActiveEvent(), getSyncRuns(8)]);
setEvent(ev);
setRuns(r);
setLoaded(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
}
}, []);
useEffect(() => {
load();
}, [load]);
async function doSync(source: Source) {
setBusy(source);
setLast(null);
try {
const res = await triggerSync(source);
setLast(res);
const bits: string[] = [];
if (res.results.pretix)
bits.push(`Pretix: ${res.results.pretix.updated} updated`);
if (res.results.sessionize)
bits.push(
`Sessionize: ${res.results.sessionize.sessions_created} new, ${res.results.sessionize.sessions_updated} updated`,
);
push(res.ok ? 'success' : 'error', res.ok ? `Sync complete — ${bits.join(' · ')}` : `Sync finished with errors`);
await load();
} catch (e) {
push('error', e instanceof Error ? e.message : 'Sync failed');
} finally {
setBusy(null);
}
}
async function doExport() {
if (!event) return;
try {
const n = await exportQrCsv(event.id);
push('success', `Exported ${n} lanyard QR code${n === 1 ? '' : 's'} to CSV`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Export failed');
}
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
<div className="loading-screen">
<Spinner />
</div>
);
return (
<div>
<div className="page-head">
<div>
<h1>Interfaces</h1>
<div className="sub">
Sync real data from <strong>Pretix</strong> (tickets → contacts + registrations) and{' '}
<strong>Sessionize</strong> (agenda → slots + sessions + speakers).
</div>
</div>
<div className="row" style={{ gap: 8 }}>
<button className="btn" disabled={busy !== null} onClick={() => doExport()}>
⬇ Export QR CSV
</button>
<button className="btn primary" disabled={busy !== null} onClick={() => doSync('both')}>
{busy === 'both' ? 'Syncing…' : '🔄 Sync all'}
</button>
</div>
</div>
{!event && (
<div className="card" style={{ marginBottom: 16 }}>
<Empty icon="📅" text="No active event. Syncs target the active event — set one in the Events view." />
</div>
)}
<div className="grid-2">
<div className="card">
<div className="row between" style={{ marginBottom: 14 }}>
<h2 className="h2">🎟️ Pretix</h2>
<button
className="btn small"
disabled={busy !== null || !event}
onClick={() => doSync('pretix')}
>
{busy === 'pretix' ? 'Syncing…' : 'Sync now'}
</button>
</div>
<p className="muted small" style={{ marginTop: 0 }}>
Pulls ticket holders and upserts <code>contacts</code> + <code>registrations</code> (QR tokens
generated for new ticket holders). Ticket type maps to registration type
(speaker / staff / sponsor / attendee).
</p>
{last?.results.pretix && (
<div className="sync-result">
<span className="pill green">{last.results.pretix.updated} updated</span>
<span className="pill">{last.results.pretix.skipped} skipped</span>
{last.results.pretix.errors.length > 0 && (
<span className="pill red">{last.results.pretix.errors.length} errors</span>
)}
</div>
)}
</div>
<div className="card">
<div className="row between" style={{ marginBottom: 14 }}>
<h2 className="h2">🗓️ Sessionize</h2>
<button
className="btn small"
disabled={busy !== null || !event}
onClick={() => doSync('sessionize')}
>
{busy === 'sessionize' ? 'Syncing…' : 'Sync now'}
</button>
</div>
<p className="muted small" style={{ marginTop: 0 }}>
Pulls the agenda and upserts <code>slots</code> + <code>sessions</code> + speakers. Slots are
matched by date + time; sessions by their Sessionize id.
</p>
{last?.results.sessionize && (
<div className="sync-result">
<span className="pill green">{last.results.sessionize.sessions_created} new</span>
<span className="pill">{last.results.sessionize.sessions_updated} updated</span>
<span className="pill">{last.results.sessionize.slots_created} slots</span>
<span className="pill">{last.results.sessionize.speakers_linked} speakers</span>
</div>
)}
</div>
</div>
{last && last.errors.length > 0 && (
<div className="card" style={{ marginTop: 16, borderColor: 'var(--red, #d50000)' }}>
<h2 className="h2" style={{ color: 'var(--red, #d50000)' }}>
⚠️ Sync errors
</h2>
<ul className="muted small" style={{ margin: '8px 0 0', paddingLeft: 18 }}>
{last.errors.map((e, i) => (
<li key={i}>{e}</li>
))}
</ul>
</div>
)}
<div className="card" style={{ marginTop: 16 }}>
<div className="row between" style={{ marginBottom: 14 }}>
<h2 className="h2">🕘 Recent sync runs</h2>
<button className="btn small ghost" onClick={load}>
Refresh
</button>
</div>
{runs.length === 0 ? (
<Empty icon="🔄" text="No sync runs yet. Trigger one above." />
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Source</th>
<th>Started</th>
<th>Created</th>
<th>Updated</th>
<th>Skipped</th>
<th>Triggered by</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{runs.map((r) => (
<tr key={r.id}>
<td>
<SourcePill source={r.source} />
</td>
<td className="muted small">{fmtTime(r.started_at)}</td>
<td>{r.created}</td>
<td>{r.updated}</td>
<td>{r.skipped}</td>
<td className="muted small">{r.triggered_by}</td>
<td>
{r.error ? (
<span className="pill red" title={r.error}>
error
</span>
) : (
<span className="pill green">ok</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
);
}
+1
View File
@@ -15,6 +15,7 @@ export default defineConfig({
'/rest': { target: SUPABASE_TARGET, changeOrigin: true },
'/realtime': { target: SUPABASE_TARGET, changeOrigin: true, ws: true },
'/storage': { target: SUPABASE_TARGET, changeOrigin: true },
'/functions': { target: SUPABASE_TARGET, changeOrigin: true },
},
},
});