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
+214
-33
No files matched your search
@@ -8,6 +8,7 @@ import type {
|
|||||||
Feedback,
|
Feedback,
|
||||||
LeaderboardRow,
|
LeaderboardRow,
|
||||||
PointsLogRow,
|
PointsLogRow,
|
||||||
|
PretixOptions,
|
||||||
PretixSyncResult,
|
PretixSyncResult,
|
||||||
Registration,
|
Registration,
|
||||||
ResetQrResult,
|
ResetQrResult,
|
||||||
@@ -168,6 +169,7 @@ export async function upsertEvent(
|
|||||||
sessionize_endpoint?: string | null;
|
sessionize_endpoint?: string | null;
|
||||||
pretix_organizer?: string | null;
|
pretix_organizer?: string | null;
|
||||||
pretix_event_slug?: string | null;
|
pretix_event_slug?: string | null;
|
||||||
|
pretix_api_key?: string | null;
|
||||||
use_realtime_clock?: boolean;
|
use_realtime_clock?: boolean;
|
||||||
},
|
},
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
@@ -209,6 +211,14 @@ export const runSessionizeSync = (eventId: string) =>
|
|||||||
export const runPretixSync = (eventId: string) =>
|
export const runPretixSync = (eventId: string) =>
|
||||||
sidecarFetch<PretixSyncResult>('/run-pretix', { method: 'POST', body: JSON.stringify({ event_id: eventId }) });
|
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.
|
* Upload the Sessionize "Sessions and speakers (advanced)" .xlsx for an event.
|
||||||
* The sidecar parses it and imports speakers/sessions/agenda + speaker
|
* The sidecar parses it and imports speakers/sessions/agenda + speaker
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ export interface Event {
|
|||||||
pretix_organizer?: string | null;
|
pretix_organizer?: string | null;
|
||||||
/** Pretix event slug for this event (e.g. `tickets`). */
|
/** Pretix event slug for this event (e.g. `tickets`). */
|
||||||
pretix_event_slug?: string | null;
|
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. */
|
/** When the Sessionize sync last ran for this event. */
|
||||||
last_synced_at: string | null;
|
last_synced_at: string | null;
|
||||||
avg_feedback: number | null;
|
avg_feedback: number | null;
|
||||||
@@ -138,6 +140,24 @@ export interface PretixRun {
|
|||||||
/** The response of POST /run-pretix (same shape as a successful PretixRun). */
|
/** The response of POST /run-pretix (same shape as a successful PretixRun). */
|
||||||
export type PretixSyncResult = 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. */
|
/** The sidecar's /status response. */
|
||||||
export interface SidecarStatus {
|
export interface SidecarStatus {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
activateEvent,
|
activateEvent,
|
||||||
deactivateEvent,
|
deactivateEvent,
|
||||||
|
fetchPretixOptions,
|
||||||
getAllEvents,
|
getAllEvents,
|
||||||
runPretixSync,
|
runPretixSync,
|
||||||
runSessionizeSync,
|
runSessionizeSync,
|
||||||
upsertEvent,
|
upsertEvent,
|
||||||
} from '../lib/api';
|
} 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 { useToast } from '../context/ToastContext';
|
||||||
import { Empty, Modal, Spinner, Toggle } from '../components/ui';
|
import { Empty, Modal, Spinner, Toggle } from '../components/ui';
|
||||||
|
|
||||||
@@ -66,8 +67,8 @@ export function Events() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function runPretix(ev: Event) {
|
async function runPretix(ev: Event) {
|
||||||
if (!ev.pretix_organizer || !ev.pretix_event_slug) {
|
if (!ev.pretix_organizer || !ev.pretix_event_slug || !ev.pretix_api_key) {
|
||||||
push('error', `Set the Pretix organizer + event slug for ${ev.name} first (Edit)`);
|
push('error', `Set the Pretix API key + organizer + event slug for ${ev.name} first (Edit)`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setPretixSyncingId(ev.id);
|
setPretixSyncingId(ev.id);
|
||||||
@@ -164,12 +165,17 @@ export function Events() {
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
className="btn small"
|
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)}
|
onClick={() => runPretix(ev)}
|
||||||
title={
|
title={
|
||||||
ev.pretix_organizer && ev.pretix_event_slug
|
ev.pretix_organizer && ev.pretix_event_slug && ev.pretix_api_key
|
||||||
? 'Sync with Pretix'
|
? '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'}
|
{pretixSyncingId === ev.id ? 'Syncing…' : 'Sync Pretix'}
|
||||||
@@ -280,10 +286,44 @@ function EventModal({
|
|||||||
const [endDate, setEndDate] = useState(event ? event.end_date.slice(0, 10) : '');
|
const [endDate, setEndDate] = useState(event ? event.end_date.slice(0, 10) : '');
|
||||||
const [location, setLocation] = useState(event?.location ?? '');
|
const [location, setLocation] = useState(event?.location ?? '');
|
||||||
const [endpoint, setEndpoint] = useState(event?.sessionize_endpoint ?? '');
|
const [endpoint, setEndpoint] = useState(event?.sessionize_endpoint ?? '');
|
||||||
|
const [pretixApiKey, setPretixApiKey] = useState(event?.pretix_api_key ?? '');
|
||||||
const [pretixOrganizer, setPretixOrganizer] = useState(event?.pretix_organizer ?? '');
|
const [pretixOrganizer, setPretixOrganizer] = useState(event?.pretix_organizer ?? '');
|
||||||
const [pretixEventSlug, setPretixEventSlug] = useState(event?.pretix_event_slug ?? '');
|
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 [realtimeClock, setRealtimeClock] = useState(event?.use_realtime_clock ?? false);
|
||||||
const [busy, setBusy] = useState(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() {
|
async function save() {
|
||||||
if (!name.trim() || !startDate || !endDate) return;
|
if (!name.trim() || !startDate || !endDate) return;
|
||||||
@@ -297,6 +337,7 @@ function EventModal({
|
|||||||
sessionize_endpoint: endpoint.trim() || null,
|
sessionize_endpoint: endpoint.trim() || null,
|
||||||
pretix_organizer: pretixOrganizer.trim() || null,
|
pretix_organizer: pretixOrganizer.trim() || null,
|
||||||
pretix_event_slug: pretixEventSlug.trim() || null,
|
pretix_event_slug: pretixEventSlug.trim() || null,
|
||||||
|
pretix_api_key: pretixApiKey.trim() || null,
|
||||||
use_realtime_clock: realtimeClock,
|
use_realtime_clock: realtimeClock,
|
||||||
});
|
});
|
||||||
onSaved(event ? 'Event updated' : 'Event created');
|
onSaved(event ? 'Event updated' : 'Event created');
|
||||||
@@ -365,36 +406,76 @@ function EventModal({
|
|||||||
<div className="section-head">
|
<div className="section-head">
|
||||||
<span className="ico">🎟️</span>
|
<span className="ico">🎟️</span>
|
||||||
<h4>Pretix</h4>
|
<h4>Pretix</h4>
|
||||||
{pretixOrganizer.trim() && pretixEventSlug.trim() ? (
|
{pretixApiKey.trim() && pretixOrganizer.trim() && pretixEventSlug.trim() ? (
|
||||||
<span className="pill green">configured</span>
|
<span className="pill green">configured</span>
|
||||||
) : (
|
) : (
|
||||||
<span className="pill">not set</span>
|
<span className="pill">not set</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<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="grid-2">
|
||||||
<div className="field">
|
<div className="field">
|
||||||
<label>Pretix organizer</label>
|
<label>Pretix organizer</label>
|
||||||
<input
|
<select
|
||||||
className="input"
|
className="input"
|
||||||
value={pretixOrganizer}
|
value={pretixOrganizer}
|
||||||
onChange={(e) => setPretixOrganizer(e.target.value)}
|
onChange={(e) => {
|
||||||
placeholder="e.g. appecommday"
|
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>
|
||||||
<div className="field">
|
<div className="field">
|
||||||
<label>Pretix event slug</label>
|
<label>Pretix event slug</label>
|
||||||
<input
|
<select
|
||||||
className="input"
|
className="input"
|
||||||
value={pretixEventSlug}
|
value={pretixEventSlug}
|
||||||
onChange={(e) => setPretixEventSlug(e.target.value)}
|
onChange={(e) => setPretixEventSlug(e.target.value)}
|
||||||
placeholder="e.g. tickets"
|
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>
|
</div>
|
||||||
|
)}
|
||||||
<div className="muted small" style={{ maxWidth: 640 }}>
|
<div className="muted small" style={{ maxWidth: 640 }}>
|
||||||
The sidecar syncs paid Pretix tickets for this event every minute. Set the organizer +
|
The sidecar syncs paid Pretix tickets for this event every minute using the key above.
|
||||||
event slug (e.g. <code>appecommday</code> / <code>tickets</code>). The API key is
|
|
||||||
configured on the sidecar.
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="field">
|
<div className="field">
|
||||||
|
|||||||
+68
-15
@@ -113,11 +113,13 @@ async function supabaseFetch(path, { method = 'GET', body } = {}) {
|
|||||||
// Pretix API helper (token auth). Mirrors supabaseFetch's error handling.
|
// 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.
|
// `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).
|
// 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 base = /^https?:\/\//.test(path) ? path : PRETIX_BASE + path;
|
||||||
const qs = query ? '?' + new URLSearchParams(query).toString() : '';
|
const qs = query ? '?' + new URLSearchParams(query).toString() : '';
|
||||||
|
const token = apiKey || PRETIX_API_KEY;
|
||||||
const res = await fetch(base + qs, {
|
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();
|
const text = await res.text();
|
||||||
let parsed;
|
let parsed;
|
||||||
@@ -138,12 +140,12 @@ async function pretixFetch(path, { query } = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fetch all paid orders for an event (follow `next` until null).
|
// Fetch all paid orders for an event (follow `next` until null).
|
||||||
async function fetchPretixOrders(organizer, eventSlug) {
|
async function fetchPretixOrders(organizer, eventSlug, apiKey) {
|
||||||
const orders = [];
|
const orders = [];
|
||||||
let url = `/organizers/${encodeURIComponent(organizer)}/events/${encodeURIComponent(eventSlug)}/orders/?status=p`;
|
let url = `/organizers/${encodeURIComponent(organizer)}/events/${encodeURIComponent(eventSlug)}/orders/?status=p`;
|
||||||
let pages = 0;
|
let pages = 0;
|
||||||
while (url && pages < 200) {
|
while (url && pages < 200) {
|
||||||
const page = await pretixFetch(url);
|
const page = await pretixFetch(url, { apiKey });
|
||||||
for (const o of page.results || []) orders.push(o);
|
for (const o of page.results || []) orders.push(o);
|
||||||
url = page.next || null;
|
url = page.next || null;
|
||||||
pages += 1;
|
pages += 1;
|
||||||
@@ -152,12 +154,12 @@ async function fetchPretixOrders(organizer, eventSlug) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fetch the event's items (follow `next` until null) -> Map<itemId, name>.
|
// 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();
|
const names = new Map();
|
||||||
let url = `/organizers/${encodeURIComponent(organizer)}/events/${encodeURIComponent(eventSlug)}/items/`;
|
let url = `/organizers/${encodeURIComponent(organizer)}/events/${encodeURIComponent(eventSlug)}/items/`;
|
||||||
let pages = 0;
|
let pages = 0;
|
||||||
while (url && pages < 200) {
|
while (url && pages < 200) {
|
||||||
const page = await pretixFetch(url);
|
const page = await pretixFetch(url, { apiKey });
|
||||||
for (const item of page.results || []) {
|
for (const item of page.results || []) {
|
||||||
names.set(item.id, (item.name && (item.name.en || item.name.de)) || '');
|
names.set(item.id, (item.name && (item.name.en || item.name.de)) || '');
|
||||||
}
|
}
|
||||||
@@ -167,6 +169,35 @@ async function fetchPretixItems(organizer, eventSlug) {
|
|||||||
return names;
|
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 a Pretix ticket item name to a registration type (mirrors the SQL
|
||||||
// _map_ticket_type: case-insensitive substring match, default 'attendee').
|
// _map_ticket_type: case-insensitive substring match, default 'attendee').
|
||||||
function mapTicketType(name) {
|
function mapTicketType(name) {
|
||||||
@@ -466,7 +497,7 @@ async function runPretixSync(eventId) {
|
|||||||
log('pretix: start', { eventId });
|
log('pretix: start', { eventId });
|
||||||
try {
|
try {
|
||||||
const events = await supabaseFetch(
|
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;
|
const event = Array.isArray(events) ? events[0] : null;
|
||||||
if (!event) throw new Error('event not found');
|
if (!event) throw new Error('event not found');
|
||||||
@@ -482,9 +513,22 @@ async function runPretixSync(eventId) {
|
|||||||
log('pretix: skipped (no pretix config)', { eventId });
|
log('pretix: skipped (no pretix config)', { eventId });
|
||||||
return lastPretixRun;
|
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 orders = await fetchPretixOrders(event.pretix_organizer, event.pretix_event_slug, apiKey);
|
||||||
const itemNames = await fetchPretixItems(event.pretix_organizer, event.pretix_event_slug);
|
const itemNames = await fetchPretixItems(event.pretix_organizer, event.pretix_event_slug, apiKey);
|
||||||
const { attendees, skipped } = transformPretix(orders, itemNames);
|
const { attendees, skipped } = transformPretix(orders, itemNames);
|
||||||
log('pretix: transformed', { orders: orders.length, attendees: attendees.length, skipped });
|
log('pretix: transformed', { orders: orders.length, attendees: attendees.length, skipped });
|
||||||
|
|
||||||
@@ -529,7 +573,7 @@ async function runPretixSync(eventId) {
|
|||||||
async function runPretixLoop() {
|
async function runPretixLoop() {
|
||||||
if (pretixRunning) return;
|
if (pretixRunning) return;
|
||||||
const events = await supabaseFetch(
|
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 : []) {
|
for (const e of Array.isArray(events) ? events : []) {
|
||||||
try {
|
try {
|
||||||
@@ -581,6 +625,13 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const result = await runPretixSync(eventId);
|
const result = await runPretixSync(eventId);
|
||||||
return json(res, 200, result);
|
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' });
|
return json(res, 404, { error: 'not found' });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return json(res, 500, { error: e.message });
|
return json(res, 500, { error: e.message });
|
||||||
@@ -593,12 +644,14 @@ server.listen(PORT, () => {
|
|||||||
supabase: SUPABASE_URL,
|
supabase: SUPABASE_URL,
|
||||||
hasSessionizeKey: Boolean(SESSIONIZE_API_KEY),
|
hasSessionizeKey: Boolean(SESSIONIZE_API_KEY),
|
||||||
});
|
});
|
||||||
if (PRETIX_API_KEY) {
|
// The every-minute loop always runs; it only syncs events that have a
|
||||||
log('pretix auto-sync scheduled', { intervalMs: PRETIX_SYNC_INTERVAL_MS });
|
// 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(() => {
|
setInterval(() => {
|
||||||
runPretixLoop().catch((e) => log('pretix loop error', { error: e.message }));
|
runPretixLoop().catch((e) => log('pretix loop error', { error: e.message }));
|
||||||
}, PRETIX_SYNC_INTERVAL_MS);
|
}, PRETIX_SYNC_INTERVAL_MS);
|
||||||
} else {
|
|
||||||
log('pretix auto-sync disabled (no PRETIX_API_KEY)');
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- =============================================================================
|
||||||
|
-- Convivo — per-event Pretix API key
|
||||||
|
--
|
||||||
|
-- Moves the Pretix API key from a sidecar env var to a per-event column so an
|
||||||
|
-- admin can paste it in the event settings. The sidecar's /pretix-options
|
||||||
|
-- endpoint uses it to list the key's organizers + events (so the admin picks
|
||||||
|
-- the organizer + event slug from real data), and the every-minute sync uses
|
||||||
|
-- it to authenticate. The key is stored in plain text and remains visible in
|
||||||
|
-- the event settings (admin-only column, readable/writable by admin via RLS).
|
||||||
|
-- =============================================================================
|
||||||
|
|
||||||
|
alter table public.events add column if not exists pretix_api_key text;
|
||||||
|
comment on column public.events.pretix_api_key is
|
||||||
|
'Pretix API token for this event. Used by the sidecar to list the key''s '
|
||||||
|
'organizers/events (POST /pretix-options) and to authenticate the '
|
||||||
|
'every-minute paid-ticket sync. Stored in plain text; visible in the event '
|
||||||
|
'settings.';
|
||||||
Reference in new issue
Block a user