Add Pretix ticketing integration (every-minute sidecar sync)
- docs/backend/pretix.md: Pretix REST API reference (auth, orders/items endpoints, pagination, rate limiting, worked example) - migration 20260909000000_pretix_sync.sql: events.pretix_organizer + pretix_event_slug; _map_ticket_type, _ensure_auth_user (QR token = password), sync_pretix_attendees (service-role-only, idempotent) - sidecar: pretixFetch/fetchPretixOrders/fetchPretixItems/transformPretix, runPretixSync + every-minute runPretixLoop, POST /run-pretix, /status extended with pretix state - admin: Pretix panel + recent runs in Interfaces, per-event Pretix config + Sync button in Events, api/types for Pretix - docker-compose: PRETIX_API_KEY / PRETIX_BASE / PRETIX_SYNC_INTERVAL_MS Verified on VM: 25 paid orders -> 25 attendees, auto-sync every minute, login via QR token works, idempotent (no duplicate registrations). 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]>
This commit is contained in:
1 parent
d5ec009cb5
commit
509e342204
8 files changed
+1009
-10
No files matched your search
+223
-3
@@ -1,13 +1,21 @@
|
||||
// Convivo sidecar — Sessionize sync (on-demand).
|
||||
// Convivo sidecar — Sessionize sync (on-demand) + Pretix sync (every minute).
|
||||
//
|
||||
// A tiny Node HTTP service driven by the APPE Admin "Interfaces" menu.
|
||||
// Endpoints:
|
||||
// GET /health -> { ok: true }
|
||||
// GET /status -> { ok, running, lastRun }
|
||||
// GET /status -> { ok, running, lastRun, pretixRunning, lastPretixRun,
|
||||
// pretixIntervalMs, pretixConfigured }
|
||||
// POST /run -> { event_id } (blocking) -> API sync result
|
||||
// POST /import-excel -> { event_id, file_base64, filename? } (blocking)
|
||||
// -> parses the Sessionize "Sessions and speakers
|
||||
// (advanced)" .xlsx and imports it
|
||||
// POST /run-pretix -> { event_id } (blocking) -> Pretix sync result
|
||||
//
|
||||
// Every-minute Pretix sync: when PRETIX_API_KEY is set, a loop polls each
|
||||
// event's paid Pretix orders (status = 'p'), groups them by email, maps the
|
||||
// ticket item name to a registration type, and calls the service-role-only
|
||||
// sync_pretix_attendees RPC. The position `secret` is the QR token / login
|
||||
// password.
|
||||
//
|
||||
// Flow for /run:
|
||||
// 1. Read the event's sessionize_endpoint from Supabase (service role).
|
||||
@@ -26,6 +34,9 @@
|
||||
// SUPABASE_URL (default http://supabase_kong_Convivo:8000)
|
||||
// SUPABASE_SERVICE_ROLE_KEY (default = standard local service-role JWT)
|
||||
// SESSIONIZE_API_KEY (optional — only needed for /api/ endpoints)
|
||||
// PRETIX_API_KEY (optional — enables the every-minute Pretix sync)
|
||||
// PRETIX_BASE (default https://pretix.eu/api/v1)
|
||||
// PRETIX_SYNC_INTERVAL_MS (default 60000 = every minute)
|
||||
// PORT (default 3002)
|
||||
|
||||
const http = require('http');
|
||||
@@ -36,11 +47,16 @@ const SERVICE_ROLE_KEY =
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY ||
|
||||
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';
|
||||
const SESSIONIZE_API_KEY = process.env.SESSIONIZE_API_KEY || '';
|
||||
const PRETIX_API_KEY = process.env.PRETIX_API_KEY || '';
|
||||
const PRETIX_BASE = (process.env.PRETIX_BASE || 'https://pretix.eu/api/v1').replace(/\/$/, '');
|
||||
const PRETIX_SYNC_INTERVAL_MS = parseInt(process.env.PRETIX_SYNC_INTERVAL_MS || '60000', 10);
|
||||
const PORT = parseInt(process.env.PORT || '3002', 10);
|
||||
|
||||
// In-memory last-run state (the sidecar is otherwise stateless).
|
||||
let running = false;
|
||||
let lastRun = null;
|
||||
let pretixRunning = false;
|
||||
let lastPretixRun = null;
|
||||
|
||||
function log(...args) {
|
||||
console.log(new Date().toISOString(), ...args);
|
||||
@@ -94,6 +110,104 @@ async function supabaseFetch(path, { method = 'GET', body } = {}) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
// Pretix API helper (token auth). Mirrors supabaseFetch's error handling.
|
||||
// `path` may be a relative path (built from PRETIX_BASE) or a full URL (e.g.
|
||||
// a pagination `next` link, fetched as-is but still with the auth header).
|
||||
async function pretixFetch(path, { query } = {}) {
|
||||
const base = /^https?:\/\//.test(path) ? path : PRETIX_BASE + path;
|
||||
const qs = query ? '?' + new URLSearchParams(query).toString() : '';
|
||||
const res = await fetch(base + qs, {
|
||||
headers: { Authorization: 'Token ' + PRETIX_API_KEY, Accept: 'application/json' },
|
||||
});
|
||||
const text = await res.text();
|
||||
let parsed;
|
||||
try {
|
||||
parsed = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
parsed = text;
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = (parsed && (parsed.detail || parsed.message)) || text || res.statusText;
|
||||
if (res.status === 429) {
|
||||
const retryAfter = res.headers.get('Retry-After');
|
||||
msg = `rate limited (429)${retryAfter ? ' — Retry-After: ' + retryAfter : ''}: ${String(msg).slice(0, 200)}`;
|
||||
}
|
||||
throw new Error(`Pretix GET ${path} -> ${res.status}: ${msg}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
// Fetch all paid orders for an event (follow `next` until null).
|
||||
async function fetchPretixOrders(organizer, eventSlug) {
|
||||
const orders = [];
|
||||
let url = `/organizers/${encodeURIComponent(organizer)}/events/${encodeURIComponent(eventSlug)}/orders/?status=p`;
|
||||
let pages = 0;
|
||||
while (url && pages < 200) {
|
||||
const page = await pretixFetch(url);
|
||||
for (const o of page.results || []) orders.push(o);
|
||||
url = page.next || null;
|
||||
pages += 1;
|
||||
}
|
||||
return orders;
|
||||
}
|
||||
|
||||
// Fetch the event's items (follow `next` until null) -> Map<itemId, name>.
|
||||
async function fetchPretixItems(organizer, eventSlug) {
|
||||
const names = new Map();
|
||||
let url = `/organizers/${encodeURIComponent(organizer)}/events/${encodeURIComponent(eventSlug)}/items/`;
|
||||
let pages = 0;
|
||||
while (url && pages < 200) {
|
||||
const page = await pretixFetch(url);
|
||||
for (const item of page.results || []) {
|
||||
names.set(item.id, (item.name && (item.name.en || item.name.de)) || '');
|
||||
}
|
||||
url = page.next || null;
|
||||
pages += 1;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
// Map a Pretix ticket item name to a registration type (mirrors the SQL
|
||||
// _map_ticket_type: case-insensitive substring match, default 'attendee').
|
||||
function mapTicketType(name) {
|
||||
const n = String(name || '').toLowerCase();
|
||||
if (n.includes('speaker')) return 'speaker';
|
||||
if (n.includes('staff')) return 'staff';
|
||||
if (n.includes('sponsor')) return 'sponsor';
|
||||
return 'attendee';
|
||||
}
|
||||
|
||||
// Transform paid Pretix orders into the sync_pretix_attendees payload.
|
||||
// Positions are grouped by email (one entry per unique email). For a given
|
||||
// email we keep the FIRST position's qrToken + externalId, but prefer the
|
||||
// highest-privilege ticket type among that person's positions.
|
||||
const TICKET_PRIORITY = { attendee: 0, speaker: 1, sponsor: 2, staff: 3 };
|
||||
function transformPretix(orders, itemNames) {
|
||||
const byEmail = new Map();
|
||||
let skipped = 0;
|
||||
for (const order of orders) {
|
||||
for (const position of order.positions || []) {
|
||||
if (position.canceled) continue;
|
||||
const email = (position.attendee_email || order.email || '').trim().toLowerCase();
|
||||
const name = (position.attendee_name || (order.invoice_address && order.invoice_address.name) || '').trim();
|
||||
if (!email || !name) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
const ticketType = mapTicketType(itemNames.get(position.item) || '');
|
||||
const qrToken = position.secret || '';
|
||||
const externalId = String(position.id);
|
||||
const existing = byEmail.get(email);
|
||||
if (!existing) {
|
||||
byEmail.set(email, { email, full_name: name, ticket_type: ticketType, qr_token: qrToken, external_id: externalId });
|
||||
} else if ((TICKET_PRIORITY[ticketType] || 0) > (TICKET_PRIORITY[existing.ticket_type] || 0)) {
|
||||
existing.ticket_type = ticketType;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { attendees: [...byEmail.values()], skipped };
|
||||
}
|
||||
|
||||
// Transform the Sessionize API response into the sync_sessionize_event payload.
|
||||
// Speakers are matched by email (the key); speakers without an email are
|
||||
// skipped and reported. Sessions carry their speakers as a list of emails.
|
||||
@@ -343,6 +457,89 @@ async function runExcelImport(eventId, fileBase64) {
|
||||
}
|
||||
}
|
||||
|
||||
// Pretix sync: pull an event's paid orders, transform, and call the
|
||||
// service-role-only sync_pretix_attendees RPC (blocking).
|
||||
async function runPretixSync(eventId) {
|
||||
if (pretixRunning) throw new Error('a pretix sync is already running');
|
||||
pretixRunning = true;
|
||||
const startedAt = new Date().toISOString();
|
||||
log('pretix: start', { eventId });
|
||||
try {
|
||||
const events = await supabaseFetch(
|
||||
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=id,name,pretix_organizer,pretix_event_slug`,
|
||||
);
|
||||
const event = Array.isArray(events) ? events[0] : null;
|
||||
if (!event) throw new Error('event not found');
|
||||
if (!event.pretix_organizer || !event.pretix_event_slug) {
|
||||
const finishedAt = new Date().toISOString();
|
||||
lastPretixRun = {
|
||||
event_id: event.id,
|
||||
started_at: startedAt,
|
||||
finished_at: finishedAt,
|
||||
status: 'skipped',
|
||||
reason: 'no pretix config',
|
||||
};
|
||||
log('pretix: skipped (no pretix config)', { eventId });
|
||||
return lastPretixRun;
|
||||
}
|
||||
|
||||
const orders = await fetchPretixOrders(event.pretix_organizer, event.pretix_event_slug);
|
||||
const itemNames = await fetchPretixItems(event.pretix_organizer, event.pretix_event_slug);
|
||||
const { attendees, skipped } = transformPretix(orders, itemNames);
|
||||
log('pretix: transformed', { orders: orders.length, attendees: attendees.length, skipped });
|
||||
|
||||
const summary = await supabaseFetch('/rest/v1/rpc/sync_pretix_attendees', {
|
||||
method: 'POST',
|
||||
body: { p_event_id: event.id, p_attendees: attendees },
|
||||
});
|
||||
|
||||
const finishedAt = new Date().toISOString();
|
||||
const result = {
|
||||
event_id: event.id,
|
||||
event_name: event.name,
|
||||
started_at: startedAt,
|
||||
finished_at: finishedAt,
|
||||
status: 'success',
|
||||
orders: orders.length,
|
||||
attendees: attendees.length,
|
||||
skipped,
|
||||
summary,
|
||||
};
|
||||
lastPretixRun = result;
|
||||
log('pretix: done', { summary });
|
||||
return result;
|
||||
} catch (e) {
|
||||
const finishedAt = new Date().toISOString();
|
||||
lastPretixRun = {
|
||||
event_id: eventId,
|
||||
started_at: startedAt,
|
||||
finished_at: finishedAt,
|
||||
status: 'error',
|
||||
error: e.message,
|
||||
};
|
||||
log('pretix: error', { error: e.message });
|
||||
throw e;
|
||||
} finally {
|
||||
pretixRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Every-minute loop: sync every event that has a Pretix config. One event's
|
||||
// failure must not stop the others.
|
||||
async function runPretixLoop() {
|
||||
if (pretixRunning) return;
|
||||
const events = await supabaseFetch(
|
||||
'/rest/v1/events?pretix_organizer=not.is.null&select=id,pretix_organizer,pretix_event_slug',
|
||||
);
|
||||
for (const e of Array.isArray(events) ? events : []) {
|
||||
try {
|
||||
await runPretixSync(e.id);
|
||||
} catch (err) {
|
||||
log('pretix loop: event failed', { eventId: e.id, error: err.message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
||||
const path = url.pathname;
|
||||
@@ -351,7 +548,15 @@ const server = http.createServer(async (req, res) => {
|
||||
return json(res, 200, { ok: true });
|
||||
}
|
||||
if (req.method === 'GET' && path === '/status') {
|
||||
return json(res, 200, { ok: true, running, lastRun });
|
||||
return json(res, 200, {
|
||||
ok: true,
|
||||
running,
|
||||
lastRun,
|
||||
pretixRunning,
|
||||
lastPretixRun,
|
||||
pretixIntervalMs: PRETIX_SYNC_INTERVAL_MS,
|
||||
pretixConfigured: Boolean(PRETIX_API_KEY),
|
||||
});
|
||||
}
|
||||
if (req.method === 'POST' && path === '/run') {
|
||||
const body = await readBody(req);
|
||||
@@ -369,6 +574,13 @@ const server = http.createServer(async (req, res) => {
|
||||
const result = await runExcelImport(eventId, fileBase64);
|
||||
return json(res, 200, result);
|
||||
}
|
||||
if (req.method === 'POST' && path === '/run-pretix') {
|
||||
const body = await readBody(req);
|
||||
const eventId = body && body.event_id;
|
||||
if (!eventId) return json(res, 400, { error: 'event_id is required' });
|
||||
const result = await runPretixSync(eventId);
|
||||
return json(res, 200, result);
|
||||
}
|
||||
return json(res, 404, { error: 'not found' });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: e.message });
|
||||
@@ -381,4 +593,12 @@ server.listen(PORT, () => {
|
||||
supabase: SUPABASE_URL,
|
||||
hasSessionizeKey: Boolean(SESSIONIZE_API_KEY),
|
||||
});
|
||||
if (PRETIX_API_KEY) {
|
||||
log('pretix auto-sync scheduled', { intervalMs: PRETIX_SYNC_INTERVAL_MS });
|
||||
setInterval(() => {
|
||||
runPretixLoop().catch((e) => log('pretix loop error', { error: e.message }));
|
||||
}, PRETIX_SYNC_INTERVAL_MS);
|
||||
} else {
|
||||
log('pretix auto-sync disabled (no PRETIX_API_KEY)');
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user