pretix: per-event API key + live organizer/event picker

This commit is contained in:
Lago committed 2026-09-09 18:03:18 +02:00
1 parent d288fbf2f8
commit 08ab41898b
5 files changed
+228 -47

No files matched your search

+71 -18
View File
@@ -113,11 +113,13 @@ async function supabaseFetch(path, { method = 'GET', body } = {}) {
// 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 } = {}) {
// `apiKey` is the per-event token (falls back to the global PRETIX_API_KEY).
async function pretixFetch(path, { query, apiKey } = {}) {
const base = /^https?:\/\//.test(path) ? path : PRETIX_BASE + path;
const qs = query ? '?' + new URLSearchParams(query).toString() : '';
const token = apiKey || PRETIX_API_KEY;
const res = await fetch(base + qs, {
headers: { Authorization: 'Token ' + PRETIX_API_KEY, Accept: 'application/json' },
headers: { Authorization: 'Token ' + token, Accept: 'application/json' },
});
const text = await res.text();
let parsed;
@@ -138,12 +140,12 @@ async function pretixFetch(path, { query } = {}) {
}
// Fetch all paid orders for an event (follow `next` until null).
async function fetchPretixOrders(organizer, eventSlug) {
async function fetchPretixOrders(organizer, eventSlug, apiKey) {
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);
const page = await pretixFetch(url, { apiKey });
for (const o of page.results || []) orders.push(o);
url = page.next || null;
pages += 1;
@@ -152,12 +154,12 @@ async function fetchPretixOrders(organizer, eventSlug) {
}
// Fetch the event's items (follow `next` until null) -> Map<itemId, name>.
async function fetchPretixItems(organizer, eventSlug) {
async function fetchPretixItems(organizer, eventSlug, apiKey) {
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);
const page = await pretixFetch(url, { apiKey });
for (const item of page.results || []) {
names.set(item.id, (item.name && (item.name.en || item.name.de)) || '');
}
@@ -167,6 +169,35 @@ async function fetchPretixItems(organizer, eventSlug) {
return names;
}
// List the key's organizers, and for each organizer its events (active only).
// Used by the admin "paste the API key" flow to populate the organizer +
// event-slug dropdowns from real data.
async function fetchPretixOptions(apiKey) {
const organizers = await pretixFetch('/organizers/', { apiKey });
const out = [];
for (const org of organizers.results || []) {
const events = await pretixFetch(
`/organizers/${encodeURIComponent(org.slug)}/events/?is_active=true`,
{ apiKey },
);
// Pretix `name` fields are localized objects ({ en, de, ... }) or strings.
const pickName = (n) => {
if (!n) return '';
if (typeof n === 'string') return n;
return n.en || n.de || n['*'] || Object.values(n)[0] || '';
};
out.push({
slug: org.slug,
name: pickName(org.name) || org.slug,
events: (events.results || []).map((e) => ({
slug: e.slug,
name: pickName(e.name) || e.slug,
})),
});
}
return out;
}
// 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) {
@@ -466,7 +497,7 @@ async function runPretixSync(eventId) {
log('pretix: start', { eventId });
try {
const events = await supabaseFetch(
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=id,name,pretix_organizer,pretix_event_slug`,
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=id,name,pretix_organizer,pretix_event_slug,pretix_api_key`,
);
const event = Array.isArray(events) ? events[0] : null;
if (!event) throw new Error('event not found');
@@ -482,9 +513,22 @@ async function runPretixSync(eventId) {
log('pretix: skipped (no pretix config)', { eventId });
return lastPretixRun;
}
const apiKey = event.pretix_api_key || PRETIX_API_KEY;
if (!apiKey) {
const finishedAt = new Date().toISOString();
lastPretixRun = {
event_id: event.id,
started_at: startedAt,
finished_at: finishedAt,
status: 'skipped',
reason: 'no pretix api key',
};
log('pretix: skipped (no pretix api key)', { 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 orders = await fetchPretixOrders(event.pretix_organizer, event.pretix_event_slug, apiKey);
const itemNames = await fetchPretixItems(event.pretix_organizer, event.pretix_event_slug, apiKey);
const { attendees, skipped } = transformPretix(orders, itemNames);
log('pretix: transformed', { orders: orders.length, attendees: attendees.length, skipped });
@@ -529,7 +573,7 @@ async function runPretixSync(eventId) {
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',
'/rest/v1/events?pretix_organizer=not.is.null&select=id,pretix_organizer,pretix_event_slug,pretix_api_key',
);
for (const e of Array.isArray(events) ? events : []) {
try {
@@ -581,6 +625,13 @@ const server = http.createServer(async (req, res) => {
const result = await runPretixSync(eventId);
return json(res, 200, result);
}
if (req.method === 'POST' && path === '/pretix-options') {
const body = await readBody(req);
const apiKey = body && body.api_key;
if (!apiKey) return json(res, 400, { error: 'api_key is required' });
const organizers = await fetchPretixOptions(apiKey);
return json(res, 200, { organizers });
}
return json(res, 404, { error: 'not found' });
} catch (e) {
return json(res, 500, { error: e.message });
@@ -593,12 +644,14 @@ 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)');
}
// The every-minute loop always runs; it only syncs events that have a
// Pretix config (organizer + slug) and an API key (per-event column, or the
// global PRETIX_API_KEY fallback). Events without a key are skipped.
log('pretix auto-sync scheduled', {
intervalMs: PRETIX_SYNC_INTERVAL_MS,
globalKeySet: Boolean(PRETIX_API_KEY),
});
setInterval(() => {
runPretixLoop().catch((e) => log('pretix loop error', { error: e.message }));
}, PRETIX_SYNC_INTERVAL_MS);
});