pretix: per-event API key + live organizer/event picker
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
0ad02970a0
commit
f74db9dc26
5 files changed
+228
-47
No files matched your search
@@ -8,6 +8,7 @@ import type {
|
||||
Feedback,
|
||||
LeaderboardRow,
|
||||
PointsLogRow,
|
||||
PretixOptions,
|
||||
PretixSyncResult,
|
||||
Registration,
|
||||
ResetQrResult,
|
||||
@@ -168,6 +169,7 @@ export async function upsertEvent(
|
||||
sessionize_endpoint?: string | null;
|
||||
pretix_organizer?: string | null;
|
||||
pretix_event_slug?: string | null;
|
||||
pretix_api_key?: string | null;
|
||||
use_realtime_clock?: boolean;
|
||||
},
|
||||
): Promise<void> {
|
||||
@@ -209,6 +211,14 @@ export const runSessionizeSync = (eventId: string) =>
|
||||
export const runPretixSync = (eventId: string) =>
|
||||
sidecarFetch<PretixSyncResult>('/run-pretix', { method: 'POST', body: JSON.stringify({ event_id: eventId }) });
|
||||
|
||||
/**
|
||||
* Ask the sidecar to list the given Pretix API key's organizers + their active
|
||||
* events. Used by the event-settings "paste the API key" flow to populate the
|
||||
* organizer + event-slug dropdowns from real data.
|
||||
*/
|
||||
export const fetchPretixOptions = (apiKey: string) =>
|
||||
sidecarFetch<PretixOptions>('/pretix-options', { method: 'POST', body: JSON.stringify({ api_key: apiKey }) });
|
||||
|
||||
/**
|
||||
* Upload the Sessionize "Sessions and speakers (advanced)" .xlsx for an event.
|
||||
* The sidecar parses it and imports speakers/sessions/agenda + speaker
|
||||
|
||||
@@ -39,6 +39,8 @@ export interface Event {
|
||||
pretix_organizer?: string | null;
|
||||
/** Pretix event slug for this event (e.g. `tickets`). */
|
||||
pretix_event_slug?: string | null;
|
||||
/** Pretix API token for this event (stored in plain text, visible in settings). */
|
||||
pretix_api_key?: string | null;
|
||||
/** When the Sessionize sync last ran for this event. */
|
||||
last_synced_at: string | null;
|
||||
avg_feedback: number | null;
|
||||
@@ -138,6 +140,24 @@ export interface PretixRun {
|
||||
/** The response of POST /run-pretix (same shape as a successful PretixRun). */
|
||||
export type PretixSyncResult = PretixRun;
|
||||
|
||||
/** A Pretix event (slug + name) under an organizer. */
|
||||
export interface PretixEventOption {
|
||||
slug: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** A Pretix organizer + its active events, from POST /pretix-options. */
|
||||
export interface PretixOrganizerOption {
|
||||
slug: string;
|
||||
name: string;
|
||||
events: PretixEventOption[];
|
||||
}
|
||||
|
||||
/** The response of POST /pretix-options. */
|
||||
export interface PretixOptions {
|
||||
organizers: PretixOrganizerOption[];
|
||||
}
|
||||
|
||||
/** The sidecar's /status response. */
|
||||
export interface SidecarStatus {
|
||||
ok: boolean;
|
||||
|
||||
+110
-29
@@ -1,13 +1,14 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
activateEvent,
|
||||
deactivateEvent,
|
||||
fetchPretixOptions,
|
||||
getAllEvents,
|
||||
runPretixSync,
|
||||
runSessionizeSync,
|
||||
upsertEvent,
|
||||
} from '../lib/api';
|
||||
import type { Event, PretixSyncResult, SyncResult } from '../lib/types';
|
||||
import type { Event, PretixOptions, PretixSyncResult, SyncResult } from '../lib/types';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { Empty, Modal, Spinner, Toggle } from '../components/ui';
|
||||
|
||||
@@ -66,8 +67,8 @@ export function Events() {
|
||||
}
|
||||
|
||||
async function runPretix(ev: Event) {
|
||||
if (!ev.pretix_organizer || !ev.pretix_event_slug) {
|
||||
push('error', `Set the Pretix organizer + event slug for ${ev.name} first (Edit)`);
|
||||
if (!ev.pretix_organizer || !ev.pretix_event_slug || !ev.pretix_api_key) {
|
||||
push('error', `Set the Pretix API key + organizer + event slug for ${ev.name} first (Edit)`);
|
||||
return;
|
||||
}
|
||||
setPretixSyncingId(ev.id);
|
||||
@@ -164,12 +165,17 @@ export function Events() {
|
||||
</button>
|
||||
<button
|
||||
className="btn small"
|
||||
disabled={pretixSyncingId === ev.id || !ev.pretix_organizer || !ev.pretix_event_slug}
|
||||
disabled={
|
||||
pretixSyncingId === ev.id ||
|
||||
!ev.pretix_organizer ||
|
||||
!ev.pretix_event_slug ||
|
||||
!ev.pretix_api_key
|
||||
}
|
||||
onClick={() => runPretix(ev)}
|
||||
title={
|
||||
ev.pretix_organizer && ev.pretix_event_slug
|
||||
ev.pretix_organizer && ev.pretix_event_slug && ev.pretix_api_key
|
||||
? 'Sync with Pretix'
|
||||
: 'Set the Pretix organizer + event slug first (Edit)'
|
||||
: 'Set the Pretix API key + organizer + event slug first (Edit)'
|
||||
}
|
||||
>
|
||||
{pretixSyncingId === ev.id ? 'Syncing…' : 'Sync Pretix'}
|
||||
@@ -280,10 +286,44 @@ function EventModal({
|
||||
const [endDate, setEndDate] = useState(event ? event.end_date.slice(0, 10) : '');
|
||||
const [location, setLocation] = useState(event?.location ?? '');
|
||||
const [endpoint, setEndpoint] = useState(event?.sessionize_endpoint ?? '');
|
||||
const [pretixApiKey, setPretixApiKey] = useState(event?.pretix_api_key ?? '');
|
||||
const [pretixOrganizer, setPretixOrganizer] = useState(event?.pretix_organizer ?? '');
|
||||
const [pretixEventSlug, setPretixEventSlug] = useState(event?.pretix_event_slug ?? '');
|
||||
const [pretixOptions, setPretixOptions] = useState<PretixOptions | null>(null);
|
||||
const [pretixLoading, setPretixLoading] = useState(false);
|
||||
const [pretixError, setPretixError] = useState<string | null>(null);
|
||||
const [realtimeClock, setRealtimeClock] = useState(event?.use_realtime_clock ?? false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const lastFetchedKey = useRef<string | null>(null);
|
||||
|
||||
// When the API key changes, fetch the key's organizers + events (debounced)
|
||||
// so the admin can pick the organizer + event slug from real data.
|
||||
useEffect(() => {
|
||||
const key = pretixApiKey.trim();
|
||||
if (!key) {
|
||||
setPretixOptions(null);
|
||||
setPretixError(null);
|
||||
lastFetchedKey.current = null;
|
||||
return;
|
||||
}
|
||||
if (lastFetchedKey.current === key) return; // already fetched for this key
|
||||
const t = setTimeout(async () => {
|
||||
setPretixLoading(true);
|
||||
setPretixError(null);
|
||||
try {
|
||||
const opts = await fetchPretixOptions(key);
|
||||
setPretixOptions(opts);
|
||||
lastFetchedKey.current = key;
|
||||
// If the current selection isn't in the fetched list, keep it (it may
|
||||
// be a valid slug the API just didn't return, e.g. inactive event).
|
||||
} catch (e) {
|
||||
setPretixError(e instanceof Error ? e.message : 'Failed to load Pretix options');
|
||||
} finally {
|
||||
setPretixLoading(false);
|
||||
}
|
||||
}, 500);
|
||||
return () => clearTimeout(t);
|
||||
}, [pretixApiKey]);
|
||||
|
||||
async function save() {
|
||||
if (!name.trim() || !startDate || !endDate) return;
|
||||
@@ -297,6 +337,7 @@ function EventModal({
|
||||
sessionize_endpoint: endpoint.trim() || null,
|
||||
pretix_organizer: pretixOrganizer.trim() || null,
|
||||
pretix_event_slug: pretixEventSlug.trim() || null,
|
||||
pretix_api_key: pretixApiKey.trim() || null,
|
||||
use_realtime_clock: realtimeClock,
|
||||
});
|
||||
onSaved(event ? 'Event updated' : 'Event created');
|
||||
@@ -365,36 +406,76 @@ function EventModal({
|
||||
<div className="section-head">
|
||||
<span className="ico">🎟️</span>
|
||||
<h4>Pretix</h4>
|
||||
{pretixOrganizer.trim() && pretixEventSlug.trim() ? (
|
||||
{pretixApiKey.trim() && pretixOrganizer.trim() && pretixEventSlug.trim() ? (
|
||||
<span className="pill green">configured</span>
|
||||
) : (
|
||||
<span className="pill">not set</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid-2">
|
||||
<div className="field">
|
||||
<label>Pretix organizer</label>
|
||||
<input
|
||||
className="input"
|
||||
value={pretixOrganizer}
|
||||
onChange={(e) => setPretixOrganizer(e.target.value)}
|
||||
placeholder="e.g. appecommday"
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Pretix event slug</label>
|
||||
<input
|
||||
className="input"
|
||||
value={pretixEventSlug}
|
||||
onChange={(e) => setPretixEventSlug(e.target.value)}
|
||||
placeholder="e.g. tickets"
|
||||
/>
|
||||
<div className="field">
|
||||
<label>Pretix API key</label>
|
||||
<input
|
||||
className="input mono"
|
||||
value={pretixApiKey}
|
||||
onChange={(e) => setPretixApiKey(e.target.value)}
|
||||
placeholder="Paste the Pretix API token"
|
||||
autoComplete="off"
|
||||
/>
|
||||
<div className="muted small" style={{ marginTop: 4 }}>
|
||||
Paste the token — the organizers + events below load automatically. The key is stored
|
||||
with this event and stays visible here.
|
||||
</div>
|
||||
</div>
|
||||
{pretixApiKey.trim() && pretixLoading && (
|
||||
<div className="muted small">Loading Pretix organizers…</div>
|
||||
)}
|
||||
{pretixApiKey.trim() && pretixError && (
|
||||
<div className="pill red" style={{ display: 'inline-block', alignSelf: 'flex-start' }}>
|
||||
{pretixError}
|
||||
</div>
|
||||
)}
|
||||
{pretixOptions && (
|
||||
<div className="grid-2">
|
||||
<div className="field">
|
||||
<label>Pretix organizer</label>
|
||||
<select
|
||||
className="input"
|
||||
value={pretixOrganizer}
|
||||
onChange={(e) => {
|
||||
setPretixOrganizer(e.target.value);
|
||||
setPretixEventSlug('');
|
||||
}}
|
||||
>
|
||||
<option value="">— select —</option>
|
||||
{pretixOptions.organizers.map((o) => (
|
||||
<option key={o.slug} value={o.slug}>
|
||||
{o.name} ({o.slug})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Pretix event slug</label>
|
||||
<select
|
||||
className="input"
|
||||
value={pretixEventSlug}
|
||||
onChange={(e) => setPretixEventSlug(e.target.value)}
|
||||
disabled={!pretixOrganizer}
|
||||
>
|
||||
<option value="">— select —</option>
|
||||
{(pretixOptions.organizers.find((o) => o.slug === pretixOrganizer)?.events || []).map(
|
||||
(ev) => (
|
||||
<option key={ev.slug} value={ev.slug}>
|
||||
{ev.name} ({ev.slug})
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="muted small" style={{ maxWidth: 640 }}>
|
||||
The sidecar syncs paid Pretix tickets for this event every minute. Set the organizer +
|
||||
event slug (e.g. <code>appecommday</code> / <code>tickets</code>). The API key is
|
||||
configured on the sidecar.
|
||||
The sidecar syncs paid Pretix tickets for this event every minute using the key above.
|
||||
</div>
|
||||
</div>
|
||||
<div className="field">
|
||||
|
||||
+71
-18
@@ -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);
|
||||
});
|
||||
Reference in new issue
Block a user