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).
This commit is contained in:
1 parent
692df23149
commit
c7d095aff7
8 files changed
+1009
-10
No files matched your search
@@ -8,6 +8,7 @@ import type {
|
|||||||
Feedback,
|
Feedback,
|
||||||
LeaderboardRow,
|
LeaderboardRow,
|
||||||
PointsLogRow,
|
PointsLogRow,
|
||||||
|
PretixSyncResult,
|
||||||
Registration,
|
Registration,
|
||||||
ResetQrResult,
|
ResetQrResult,
|
||||||
Session,
|
Session,
|
||||||
@@ -152,6 +153,8 @@ export async function upsertEvent(
|
|||||||
end_date: string;
|
end_date: string;
|
||||||
location?: string | null;
|
location?: string | null;
|
||||||
sessionize_endpoint?: string | null;
|
sessionize_endpoint?: string | null;
|
||||||
|
pretix_organizer?: string | null;
|
||||||
|
pretix_event_slug?: string | null;
|
||||||
use_realtime_clock?: boolean;
|
use_realtime_clock?: boolean;
|
||||||
},
|
},
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
@@ -189,6 +192,10 @@ export const getSidecarStatus = () => sidecarFetch<SidecarStatus>('/status');
|
|||||||
export const runSessionizeSync = (eventId: string) =>
|
export const runSessionizeSync = (eventId: string) =>
|
||||||
sidecarFetch<SyncResult>('/run', { method: 'POST', body: JSON.stringify({ event_id: eventId }) });
|
sidecarFetch<SyncResult>('/run', { method: 'POST', body: JSON.stringify({ event_id: eventId }) });
|
||||||
|
|
||||||
|
/** Trigger a (blocking) Pretix sync for an event. Resolves with the result. */
|
||||||
|
export const runPretixSync = (eventId: string) =>
|
||||||
|
sidecarFetch<PretixSyncResult>('/run-pretix', { method: 'POST', body: JSON.stringify({ event_id: eventId }) });
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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
|
||||||
@@ -216,6 +223,10 @@ export const getSyncRuns = (eventId: string) =>
|
|||||||
rows.filter((r) => r.event_id === eventId),
|
rows.filter((r) => r.event_id === eventId),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/** Recent Pretix sync_runs rows for an event (newest first). */
|
||||||
|
export const getPretixRuns = (eventId: string) =>
|
||||||
|
getSyncRuns(eventId).then((rows) => rows.filter((r) => r.source === 'pretix'));
|
||||||
|
|
||||||
/** Set an event active (deactivates all others via trigger). */
|
/** Set an event active (deactivates all others via trigger). */
|
||||||
export async function activateEvent(id: string): Promise<void> {
|
export async function activateEvent(id: string): Promise<void> {
|
||||||
const { error } = await supabase.from('events').update({ is_active: true }).eq('id', id);
|
const { error } = await supabase.from('events').update({ is_active: true }).eq('id', id);
|
||||||
|
|||||||
@@ -35,6 +35,10 @@ export interface Event {
|
|||||||
use_realtime_clock: boolean;
|
use_realtime_clock: boolean;
|
||||||
/** Sessionize API URL for this event (e.g. .../api/v2/<id>/view/All). */
|
/** Sessionize API URL for this event (e.g. .../api/v2/<id>/view/All). */
|
||||||
sessionize_endpoint: string | null;
|
sessionize_endpoint: string | null;
|
||||||
|
/** Pretix organizer for this event (e.g. `appecommday`). */
|
||||||
|
pretix_organizer?: string | null;
|
||||||
|
/** Pretix event slug for this event (e.g. `tickets`). */
|
||||||
|
pretix_event_slug?: 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;
|
||||||
@@ -108,11 +112,41 @@ export interface ExcelSyncResult {
|
|||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The summary returned by the sync_pretix_attendees RPC. */
|
||||||
|
export interface PretixSyncSummary {
|
||||||
|
created: number;
|
||||||
|
updated: number;
|
||||||
|
skipped: number;
|
||||||
|
errors: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The result of a (blocking) sidecar Pretix sync run. */
|
||||||
|
export interface PretixRun {
|
||||||
|
event_id: string;
|
||||||
|
event_name?: string;
|
||||||
|
started_at: string;
|
||||||
|
finished_at: string;
|
||||||
|
status: 'success' | 'error' | 'skipped';
|
||||||
|
reason?: string;
|
||||||
|
orders?: number;
|
||||||
|
attendees?: number;
|
||||||
|
skipped?: number;
|
||||||
|
summary?: PretixSyncSummary;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The response of POST /run-pretix (same shape as a successful PretixRun). */
|
||||||
|
export type PretixSyncResult = PretixRun;
|
||||||
|
|
||||||
/** The sidecar's /status response. */
|
/** The sidecar's /status response. */
|
||||||
export interface SidecarStatus {
|
export interface SidecarStatus {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
running: boolean;
|
running: boolean;
|
||||||
lastRun: SyncResult | null;
|
lastRun: SyncResult | null;
|
||||||
|
pretixRunning?: boolean;
|
||||||
|
lastPretixRun?: PretixRun | null;
|
||||||
|
pretixIntervalMs?: number;
|
||||||
|
pretixConfigured?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Registration {
|
export interface Registration {
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { activateEvent, deactivateEvent, getAllEvents, runSessionizeSync, upsertEvent } from '../lib/api';
|
import {
|
||||||
import type { Event, SyncResult } from '../lib/types';
|
activateEvent,
|
||||||
|
deactivateEvent,
|
||||||
|
getAllEvents,
|
||||||
|
runPretixSync,
|
||||||
|
runSessionizeSync,
|
||||||
|
upsertEvent,
|
||||||
|
} from '../lib/api';
|
||||||
|
import type { Event, 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';
|
||||||
|
|
||||||
@@ -12,6 +19,8 @@ export function Events() {
|
|||||||
const [modal, setModal] = useState<{ event: Event | null } | null>(null);
|
const [modal, setModal] = useState<{ event: Event | null } | null>(null);
|
||||||
const [syncingId, setSyncingId] = useState<string | null>(null);
|
const [syncingId, setSyncingId] = useState<string | null>(null);
|
||||||
const [syncResult, setSyncResult] = useState<SyncResult | null>(null);
|
const [syncResult, setSyncResult] = useState<SyncResult | null>(null);
|
||||||
|
const [pretixSyncingId, setPretixSyncingId] = useState<string | null>(null);
|
||||||
|
const [pretixResult, setPretixResult] = useState<PretixSyncResult | null>(null);
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
try {
|
try {
|
||||||
@@ -56,6 +65,29 @@ 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)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setPretixSyncingId(ev.id);
|
||||||
|
try {
|
||||||
|
const result = await runPretixSync(ev.id);
|
||||||
|
setPretixResult(result);
|
||||||
|
await load();
|
||||||
|
push(
|
||||||
|
'success',
|
||||||
|
result.status === 'success'
|
||||||
|
? `Pretix synced ${ev.name} (${result.attendees ?? 0} attendees)`
|
||||||
|
: `Pretix ${result.status} for ${ev.name}`,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
push('error', e instanceof Error ? e.message : 'Pretix sync failed');
|
||||||
|
} finally {
|
||||||
|
setPretixSyncingId(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (error) return <Empty icon="⚠️" text={error} />;
|
if (error) return <Empty icon="⚠️" text={error} />;
|
||||||
if (!loaded)
|
if (!loaded)
|
||||||
return (
|
return (
|
||||||
@@ -130,6 +162,18 @@ export function Events() {
|
|||||||
>
|
>
|
||||||
{syncingId === ev.id ? 'Syncing…' : 'Sync'}
|
{syncingId === ev.id ? 'Syncing…' : 'Sync'}
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn small"
|
||||||
|
disabled={pretixSyncingId === ev.id || !ev.pretix_organizer || !ev.pretix_event_slug}
|
||||||
|
onClick={() => runPretix(ev)}
|
||||||
|
title={
|
||||||
|
ev.pretix_organizer && ev.pretix_event_slug
|
||||||
|
? 'Sync with Pretix'
|
||||||
|
: 'Set the Pretix organizer + event slug first (Edit)'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{pretixSyncingId === ev.id ? 'Syncing…' : 'Sync Pretix'}
|
||||||
|
</button>
|
||||||
<button className="btn small" onClick={() => setModal({ event: ev })}>
|
<button className="btn small" onClick={() => setModal({ event: ev })}>
|
||||||
Edit
|
Edit
|
||||||
</button>
|
</button>
|
||||||
@@ -156,10 +200,72 @@ export function Events() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{syncResult && <SyncResultModal result={syncResult} onClose={() => setSyncResult(null)} />}
|
{syncResult && <SyncResultModal result={syncResult} onClose={() => setSyncResult(null)} />}
|
||||||
|
{pretixResult && <PretixResultModal result={pretixResult} onClose={() => setPretixResult(null)} />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function PretixResultModal({ result, onClose }: { result: PretixSyncResult; onClose: () => void }) {
|
||||||
|
const s = result.summary;
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open
|
||||||
|
title={`Pretix sync — ${result.event_name ?? result.event_id}`}
|
||||||
|
onClose={onClose}
|
||||||
|
footer={
|
||||||
|
<button className="btn primary" onClick={onClose}>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{result.status === 'error' || result.status === 'skipped' ? (
|
||||||
|
<div className="pill red" style={{ display: 'inline-block', padding: '8px 12px' }}>
|
||||||
|
{result.error ?? result.reason ?? 'Pretix sync failed'}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="stat-grid">
|
||||||
|
<div className="stat">
|
||||||
|
<div className="val">{result.orders ?? 0}</div>
|
||||||
|
<div className="lbl">Orders</div>
|
||||||
|
</div>
|
||||||
|
<div className="stat">
|
||||||
|
<div className="val">{result.attendees ?? 0}</div>
|
||||||
|
<div className="lbl">Attendees</div>
|
||||||
|
</div>
|
||||||
|
<div className="stat">
|
||||||
|
<div className="val">{s?.created ?? 0}</div>
|
||||||
|
<div className="lbl">Created</div>
|
||||||
|
</div>
|
||||||
|
<div className="stat">
|
||||||
|
<div className="val">{s?.updated ?? 0}</div>
|
||||||
|
<div className="lbl">Updated</div>
|
||||||
|
</div>
|
||||||
|
<div className="stat">
|
||||||
|
<div className="val">{result.skipped ?? 0}</div>
|
||||||
|
<div className="lbl">Skipped</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{s && s.errors.length > 0 && (
|
||||||
|
<div style={{ marginTop: 12 }}>
|
||||||
|
<div className="pill red" style={{ display: 'inline-block', marginBottom: 8 }}>
|
||||||
|
{s.errors.length} error(s)
|
||||||
|
</div>
|
||||||
|
<ul style={{ margin: 0, paddingLeft: 18 }}>
|
||||||
|
{s.errors.map((e, i) => (
|
||||||
|
<li key={i} className="small">
|
||||||
|
{e}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function EventModal({
|
function EventModal({
|
||||||
event,
|
event,
|
||||||
onClose,
|
onClose,
|
||||||
@@ -174,6 +280,8 @@ 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 [pretixOrganizer, setPretixOrganizer] = useState(event?.pretix_organizer ?? '');
|
||||||
|
const [pretixEventSlug, setPretixEventSlug] = useState(event?.pretix_event_slug ?? '');
|
||||||
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);
|
||||||
|
|
||||||
@@ -187,6 +295,8 @@ function EventModal({
|
|||||||
end_date: endDate,
|
end_date: endDate,
|
||||||
location: location.trim() || null,
|
location: location.trim() || null,
|
||||||
sessionize_endpoint: endpoint.trim() || null,
|
sessionize_endpoint: endpoint.trim() || null,
|
||||||
|
pretix_organizer: pretixOrganizer.trim() || null,
|
||||||
|
pretix_event_slug: pretixEventSlug.trim() || null,
|
||||||
use_realtime_clock: realtimeClock,
|
use_realtime_clock: realtimeClock,
|
||||||
});
|
});
|
||||||
onSaved(event ? 'Event updated' : 'Event created');
|
onSaved(event ? 'Event updated' : 'Event created');
|
||||||
@@ -244,6 +354,31 @@ function EventModal({
|
|||||||
“Run sync” button. You can also import the .xlsx export in the Interfaces menu.
|
“Run sync” button. You can also import the .xlsx export in the Interfaces menu.
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</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>
|
||||||
|
</div>
|
||||||
|
<div className="muted small" style={{ marginBottom: 12, 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.
|
||||||
|
</div>
|
||||||
<div className="field">
|
<div className="field">
|
||||||
<div className="row between" style={{ alignItems: 'center' }}>
|
<div className="row between" style={{ alignItems: 'center' }}>
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -1,6 +1,22 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { getAllEvents, getSidecarStatus, getSyncRuns, importSessionizeExcel, runSessionizeSync } from '../lib/api';
|
import {
|
||||||
import type { Event, ExcelSyncResult, SidecarStatus, SyncResult, SyncRun } from '../lib/types';
|
getAllEvents,
|
||||||
|
getPretixRuns,
|
||||||
|
getSidecarStatus,
|
||||||
|
getSyncRuns,
|
||||||
|
importSessionizeExcel,
|
||||||
|
runPretixSync,
|
||||||
|
runSessionizeSync,
|
||||||
|
} from '../lib/api';
|
||||||
|
import type {
|
||||||
|
Event,
|
||||||
|
ExcelSyncResult,
|
||||||
|
PretixRun,
|
||||||
|
PretixSyncResult,
|
||||||
|
SidecarStatus,
|
||||||
|
SyncResult,
|
||||||
|
SyncRun,
|
||||||
|
} from '../lib/types';
|
||||||
import { useToast } from '../context/ToastContext';
|
import { useToast } from '../context/ToastContext';
|
||||||
import { Empty, Modal, Spinner } from '../components/ui';
|
import { Empty, Modal, Spinner } from '../components/ui';
|
||||||
|
|
||||||
@@ -18,6 +34,9 @@ export function Interfaces() {
|
|||||||
const [excelFile, setExcelFile] = useState<File | null>(null);
|
const [excelFile, setExcelFile] = useState<File | null>(null);
|
||||||
const [excelBusy, setExcelBusy] = useState(false);
|
const [excelBusy, setExcelBusy] = useState(false);
|
||||||
const [excelResult, setExcelResult] = useState<ExcelSyncResult | null>(null);
|
const [excelResult, setExcelResult] = useState<ExcelSyncResult | null>(null);
|
||||||
|
const [pretixRuns, setPretixRuns] = useState<SyncRun[]>([]);
|
||||||
|
const [pretixRunning, setPretixRunning] = useState(false);
|
||||||
|
const [pretixResult, setPretixResult] = useState<PretixSyncResult | null>(null);
|
||||||
const fileRef = useRef<HTMLInputElement>(null);
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const loadableEvents = events.filter((e) => e.sessionize_endpoint);
|
const loadableEvents = events.filter((e) => e.sessionize_endpoint);
|
||||||
@@ -52,13 +71,24 @@ export function Interfaces() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function loadPretixRuns(eventId: string) {
|
||||||
|
try {
|
||||||
|
setPretixRuns(await getPretixRuns(eventId));
|
||||||
|
} catch {
|
||||||
|
setPretixRuns([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
load();
|
load();
|
||||||
loadStatus();
|
loadStatus();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedId) loadRuns(selectedId);
|
if (selectedId) {
|
||||||
|
loadRuns(selectedId);
|
||||||
|
loadPretixRuns(selectedId);
|
||||||
|
}
|
||||||
}, [selectedId]);
|
}, [selectedId]);
|
||||||
|
|
||||||
// Poll the sidecar status while a sync is running (the run call is blocking,
|
// Poll the sidecar status while a sync is running (the run call is blocking,
|
||||||
@@ -67,10 +97,10 @@ export function Interfaces() {
|
|||||||
loadStatus();
|
loadStatus();
|
||||||
}, []);
|
}, []);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!running) return;
|
if (!running && !pretixRunning) return;
|
||||||
const t = setInterval(pollStatus, 3000);
|
const t = setInterval(pollStatus, 3000);
|
||||||
return () => clearInterval(t);
|
return () => clearInterval(t);
|
||||||
}, [running, pollStatus]);
|
}, [running, pretixRunning, pollStatus]);
|
||||||
|
|
||||||
async function runSync() {
|
async function runSync() {
|
||||||
if (!selectedId) return;
|
if (!selectedId) return;
|
||||||
@@ -87,6 +117,21 @@ export function Interfaces() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function runPretixNow() {
|
||||||
|
if (!selectedId) return;
|
||||||
|
setPretixRunning(true);
|
||||||
|
try {
|
||||||
|
const res = await runPretixSync(selectedId);
|
||||||
|
setPretixResult(res);
|
||||||
|
await Promise.all([load(), loadStatus(), loadPretixRuns(selectedId)]);
|
||||||
|
push('success', 'Pretix sync finished');
|
||||||
|
} catch (e) {
|
||||||
|
push('error', e instanceof Error ? e.message : 'Pretix sync failed');
|
||||||
|
} finally {
|
||||||
|
setPretixRunning(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function importExcel() {
|
async function importExcel() {
|
||||||
if (!selectedId || !excelFile) return;
|
if (!selectedId || !excelFile) return;
|
||||||
setExcelBusy(true);
|
setExcelBusy(true);
|
||||||
@@ -239,6 +284,109 @@ export function Interfaces() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Pretix */}
|
||||||
|
<div className="card" style={{ marginBottom: 18 }}>
|
||||||
|
<h2 className="h2">🎟 Pretix</h2>
|
||||||
|
<div style={{ marginBottom: 12 }}>
|
||||||
|
{status?.pretixConfigured === false ? (
|
||||||
|
<span className="pill amber" style={{ display: 'inline-block', padding: '8px 12px' }}>
|
||||||
|
Pretix not configured (no API key on the sidecar)
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<div className="muted small" style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||||
|
<span>
|
||||||
|
Pretix auto-sync: every {status?.pretixIntervalMs ? status.pretixIntervalMs / 1000 : 60}s
|
||||||
|
</span>
|
||||||
|
{status?.lastPretixRun && (
|
||||||
|
<span>
|
||||||
|
last run {fmtTime(status.lastPretixRun.finished_at)} —{' '}
|
||||||
|
<span
|
||||||
|
className={`pill ${
|
||||||
|
status.lastPretixRun.status === 'success'
|
||||||
|
? 'green'
|
||||||
|
: status.lastPretixRun.status === 'skipped'
|
||||||
|
? 'amber'
|
||||||
|
: 'red'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{status.lastPretixRun.status}
|
||||||
|
</span>
|
||||||
|
{status.lastPretixRun.status === 'success' && (
|
||||||
|
<span className="muted">
|
||||||
|
{' '}
|
||||||
|
· {status.lastPretixRun.orders ?? 0} orders · {status.lastPretixRun.attendees ?? 0}{' '}
|
||||||
|
attendees · {status.lastPretixRun.skipped ?? 0} skipped
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{(status.lastPretixRun.status === 'error' || status.lastPretixRun.status === 'skipped') &&
|
||||||
|
(status.lastPretixRun.error || status.lastPretixRun.reason) && (
|
||||||
|
<span className="muted"> · {status.lastPretixRun.error || status.lastPretixRun.reason}</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||||
|
<select
|
||||||
|
className="input"
|
||||||
|
style={{ maxWidth: 320 }}
|
||||||
|
value={selectedId}
|
||||||
|
onChange={(e) => setSelectedId(e.target.value)}
|
||||||
|
>
|
||||||
|
{events.map((e) => (
|
||||||
|
<option key={e.id} value={e.id}>
|
||||||
|
{e.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<button className="btn primary" disabled={pretixRunning || !selectedId} onClick={runPretixNow}>
|
||||||
|
{pretixRunning ? 'Syncing…' : 'Run Pretix now'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Recent Pretix runs (audit) */}
|
||||||
|
<div className="card" style={{ marginBottom: 18 }}>
|
||||||
|
<h2 className="h2">📜 Recent Pretix runs {selected ? `— ${selected.name}` : ''}</h2>
|
||||||
|
{pretixRuns.length === 0 ? (
|
||||||
|
<Empty icon="🎟" text="No Pretix sync runs recorded for this event yet." />
|
||||||
|
) : (
|
||||||
|
<div className="table-wrap">
|
||||||
|
<table className="data">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Started</th>
|
||||||
|
<th>Finished</th>
|
||||||
|
<th>Created</th>
|
||||||
|
<th>Updated</th>
|
||||||
|
<th>Status</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{pretixRuns.map((r) => (
|
||||||
|
<tr key={r.id}>
|
||||||
|
<td className="muted">{fmtTime(r.started_at)}</td>
|
||||||
|
<td className="muted">{r.finished_at ? fmtTime(r.finished_at) : '—'}</td>
|
||||||
|
<td className="muted">{r.created}</td>
|
||||||
|
<td className="muted">{r.updated}</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>
|
||||||
|
|
||||||
{/* Recent runs (audit) */}
|
{/* Recent runs (audit) */}
|
||||||
<div className="card">
|
<div className="card">
|
||||||
<h2 className="h2">📜 Recent runs {selected ? `— ${selected.name}` : ''}</h2>
|
<h2 className="h2">📜 Recent runs {selected ? `— ${selected.name}` : ''}</h2>
|
||||||
@@ -282,10 +430,72 @@ export function Interfaces() {
|
|||||||
|
|
||||||
{result && <SyncResultModal result={result} onClose={() => setResult(null)} />}
|
{result && <SyncResultModal result={result} onClose={() => setResult(null)} />}
|
||||||
{excelResult && <ExcelResultModal result={excelResult} onClose={() => setExcelResult(null)} />}
|
{excelResult && <ExcelResultModal result={excelResult} onClose={() => setExcelResult(null)} />}
|
||||||
|
{pretixResult && <PretixResultModal result={pretixResult} onClose={() => setPretixResult(null)} />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function PretixResultModal({ result, onClose }: { result: PretixRun; onClose: () => void }) {
|
||||||
|
const s = result.summary;
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open
|
||||||
|
title={`Pretix sync — ${result.event_name ?? result.event_id}`}
|
||||||
|
onClose={onClose}
|
||||||
|
footer={
|
||||||
|
<button className="btn primary" onClick={onClose}>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{result.status === 'error' || result.status === 'skipped' ? (
|
||||||
|
<div className="pill red" style={{ display: 'inline-block', padding: '8px 12px' }}>
|
||||||
|
{result.error ?? result.reason ?? 'Pretix sync failed'}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="stat-grid">
|
||||||
|
<div className="stat">
|
||||||
|
<div className="val">{result.orders ?? 0}</div>
|
||||||
|
<div className="lbl">Orders</div>
|
||||||
|
</div>
|
||||||
|
<div className="stat">
|
||||||
|
<div className="val">{result.attendees ?? 0}</div>
|
||||||
|
<div className="lbl">Attendees</div>
|
||||||
|
</div>
|
||||||
|
<div className="stat">
|
||||||
|
<div className="val">{s?.created ?? 0}</div>
|
||||||
|
<div className="lbl">Created</div>
|
||||||
|
</div>
|
||||||
|
<div className="stat">
|
||||||
|
<div className="val">{s?.updated ?? 0}</div>
|
||||||
|
<div className="lbl">Updated</div>
|
||||||
|
</div>
|
||||||
|
<div className="stat">
|
||||||
|
<div className="val">{result.skipped ?? 0}</div>
|
||||||
|
<div className="lbl">Skipped</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{s && s.errors.length > 0 && (
|
||||||
|
<div style={{ marginTop: 12 }}>
|
||||||
|
<div className="pill red" style={{ display: 'inline-block', marginBottom: 8 }}>
|
||||||
|
{s.errors.length} error(s)
|
||||||
|
</div>
|
||||||
|
<ul style={{ margin: 0, paddingLeft: 18 }}>
|
||||||
|
{s.errors.map((e, i) => (
|
||||||
|
<li key={i} className="small">
|
||||||
|
{e}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function ExcelResultModal({ result, onClose }: { result: ExcelSyncResult; onClose: () => void }) {
|
function ExcelResultModal({ result, onClose }: { result: ExcelSyncResult; onClose: () => void }) {
|
||||||
const s = result.summary;
|
const s = result.summary;
|
||||||
return (
|
return (
|
||||||
|
|||||||
+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.
|
// A tiny Node HTTP service driven by the APPE Admin "Interfaces" menu.
|
||||||
// Endpoints:
|
// Endpoints:
|
||||||
// GET /health -> { ok: true }
|
// 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 /run -> { event_id } (blocking) -> API sync result
|
||||||
// POST /import-excel -> { event_id, file_base64, filename? } (blocking)
|
// POST /import-excel -> { event_id, file_base64, filename? } (blocking)
|
||||||
// -> parses the Sessionize "Sessions and speakers
|
// -> parses the Sessionize "Sessions and speakers
|
||||||
// (advanced)" .xlsx and imports it
|
// (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:
|
// Flow for /run:
|
||||||
// 1. Read the event's sessionize_endpoint from Supabase (service role).
|
// 1. Read the event's sessionize_endpoint from Supabase (service role).
|
||||||
@@ -26,6 +34,9 @@
|
|||||||
// SUPABASE_URL (default http://supabase_kong_Convivo:8000)
|
// SUPABASE_URL (default http://supabase_kong_Convivo:8000)
|
||||||
// SUPABASE_SERVICE_ROLE_KEY (default = standard local service-role JWT)
|
// SUPABASE_SERVICE_ROLE_KEY (default = standard local service-role JWT)
|
||||||
// SESSIONIZE_API_KEY (optional — only needed for /api/ endpoints)
|
// 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)
|
// PORT (default 3002)
|
||||||
|
|
||||||
const http = require('http');
|
const http = require('http');
|
||||||
@@ -36,11 +47,16 @@ const SERVICE_ROLE_KEY =
|
|||||||
process.env.SUPABASE_SERVICE_ROLE_KEY ||
|
process.env.SUPABASE_SERVICE_ROLE_KEY ||
|
||||||
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';
|
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';
|
||||||
const SESSIONIZE_API_KEY = process.env.SESSIONIZE_API_KEY || '';
|
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);
|
const PORT = parseInt(process.env.PORT || '3002', 10);
|
||||||
|
|
||||||
// In-memory last-run state (the sidecar is otherwise stateless).
|
// In-memory last-run state (the sidecar is otherwise stateless).
|
||||||
let running = false;
|
let running = false;
|
||||||
let lastRun = null;
|
let lastRun = null;
|
||||||
|
let pretixRunning = false;
|
||||||
|
let lastPretixRun = null;
|
||||||
|
|
||||||
function log(...args) {
|
function log(...args) {
|
||||||
console.log(new Date().toISOString(), ...args);
|
console.log(new Date().toISOString(), ...args);
|
||||||
@@ -94,6 +110,104 @@ async function supabaseFetch(path, { method = 'GET', body } = {}) {
|
|||||||
return parsed;
|
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.
|
// Transform the Sessionize API response into the sync_sessionize_event payload.
|
||||||
// Speakers are matched by email (the key); speakers without an email are
|
// Speakers are matched by email (the key); speakers without an email are
|
||||||
// skipped and reported. Sessions carry their speakers as a list of emails.
|
// 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 server = http.createServer(async (req, res) => {
|
||||||
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
||||||
const path = url.pathname;
|
const path = url.pathname;
|
||||||
@@ -351,7 +548,15 @@ const server = http.createServer(async (req, res) => {
|
|||||||
return json(res, 200, { ok: true });
|
return json(res, 200, { ok: true });
|
||||||
}
|
}
|
||||||
if (req.method === 'GET' && path === '/status') {
|
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') {
|
if (req.method === 'POST' && path === '/run') {
|
||||||
const body = await readBody(req);
|
const body = await readBody(req);
|
||||||
@@ -369,6 +574,13 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const result = await runExcelImport(eventId, fileBase64);
|
const result = await runExcelImport(eventId, fileBase64);
|
||||||
return json(res, 200, result);
|
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' });
|
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 });
|
||||||
@@ -381,4 +593,12 @@ server.listen(PORT, () => {
|
|||||||
supabase: SUPABASE_URL,
|
supabase: SUPABASE_URL,
|
||||||
hasSessionizeKey: Boolean(SESSIONIZE_API_KEY),
|
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)');
|
||||||
|
}
|
||||||
});
|
});
|
||||||
@@ -91,6 +91,13 @@ services:
|
|||||||
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY:-eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU}
|
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY:-eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU}
|
||||||
# Sessionize API key (required to run a sync). Set to your key.
|
# Sessionize API key (required to run a sync). Set to your key.
|
||||||
SESSIONIZE_API_KEY: ${SESSIONIZE_API_KEY:-}
|
SESSIONIZE_API_KEY: ${SESSIONIZE_API_KEY:-}
|
||||||
|
# Pretix API key (enables the every-minute paid-ticket sync). Set to your
|
||||||
|
# team-level token. When empty, the Pretix auto-sync is disabled.
|
||||||
|
PRETIX_API_KEY: ${PRETIX_API_KEY:-}
|
||||||
|
# Pretix API base URL (default: the pretix.eu hosted service).
|
||||||
|
PRETIX_BASE: ${PRETIX_BASE:-https://pretix.eu/api/v1}
|
||||||
|
# How often the sidecar polls Pretix (default: 60000 ms = every minute).
|
||||||
|
PRETIX_SYNC_INTERVAL_MS: ${PRETIX_SYNC_INTERVAL_MS:-60000}
|
||||||
networks:
|
networks:
|
||||||
- supabase
|
- supabase
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
# Pretix — ticket order sync
|
||||||
|
|
||||||
|
The **Pretix integration** pulls paid ticket orders from
|
||||||
|
[pretix.eu](https://pretix.eu) (pretix Hosted) into Convivo so that ticket
|
||||||
|
buyers become registered attendees. The **sidecar** owns the polling and the
|
||||||
|
transform; the database owns the write (a service-role-only RPC).
|
||||||
|
|
||||||
|
- Consumer: [`apps/sidecar/`](../../apps/sidecar/) — see
|
||||||
|
[sidecar.md](./sidecar.md)
|
||||||
|
- DB side: the `sync_pretix_attendees` RPC — see [rpcs.md](./rpcs.md)
|
||||||
|
|
||||||
|
## Service & credentials
|
||||||
|
|
||||||
|
| What | Value |
|
||||||
|
|---|---|
|
||||||
|
| Service | pretix.eu (pretix Hosted) |
|
||||||
|
| REST API base URL | `https://pretix.eu/api/v1/` |
|
||||||
|
| Authentication | token-based — header `Authorization: Token <API_KEY>` |
|
||||||
|
| API key | `zkex2grqjxpcialy9msnm6zd7x1i2bc08gm8k5b7vlstpit7xb98p33oq7zggxqy` |
|
||||||
|
| Organizer | "Austrian Power Platform Enthusiasts" (slug `appecommday`) |
|
||||||
|
| Event | "Community Day 2026" (slug `tickets`), live, currency EUR, 2026-10-23 |
|
||||||
|
|
||||||
|
The API key is a **team-level token** created in the pretix web UI under an
|
||||||
|
organizer team (Organizer → Teams → create token). It is **shown once** at
|
||||||
|
creation — there is no way to retrieve it later, only regenerate.
|
||||||
|
|
||||||
|
## Endpoints we use
|
||||||
|
|
||||||
|
### 1. List paid orders
|
||||||
|
|
||||||
|
```
|
||||||
|
GET https://pretix.eu/api/v1/organizers/appecommday/events/tickets/orders/?status=p
|
||||||
|
```
|
||||||
|
|
||||||
|
Order resource fields we rely on:
|
||||||
|
|
||||||
|
| Field | Type | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `code` | string | the order code (e.g. `BZWHN`) |
|
||||||
|
| `status` | string | one of `n`=pending, `p`=paid, `e`=expired, `c`=canceled |
|
||||||
|
| `email` | string | the buyer email |
|
||||||
|
| `invoice_address` | object or null | has `name` |
|
||||||
|
| `positions` | list | order-position objects (see below) |
|
||||||
|
|
||||||
|
Order-position fields we rely on:
|
||||||
|
|
||||||
|
| Field | Type | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `id` | integer | the position id |
|
||||||
|
| `item` | integer | the item id |
|
||||||
|
| `attendee_name` | string or null | |
|
||||||
|
| `attendee_email` | string or null | **often null in practice** — fall back to the order `email` |
|
||||||
|
| `secret` | string | the per-ticket secret — **we use this as the QR token / login password** |
|
||||||
|
| `canceled` | boolean | |
|
||||||
|
|
||||||
|
### 2. List items (to map ticket type by name)
|
||||||
|
|
||||||
|
```
|
||||||
|
GET https://pretix.eu/api/v1/organizers/appecommday/events/tickets/items/
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Type | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `id` | integer | |
|
||||||
|
| `name` | multi-lingual object | e.g. `{"en": "Regular ticket"}` |
|
||||||
|
| `active` | boolean | |
|
||||||
|
|
||||||
|
Currently the event has a **single item**: id `1074118`, name "Regular ticket".
|
||||||
|
|
||||||
|
## Pagination
|
||||||
|
|
||||||
|
List responses are:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "count": 42, "next": "https://.../orders/?status=p&page=2", "previous": null, "results": [ ... ] }
|
||||||
|
```
|
||||||
|
|
||||||
|
50 results per page by default; **follow `next` until it is null**. You can
|
||||||
|
pass `page_size` (max 50) and `page` query parameters.
|
||||||
|
|
||||||
|
## Conditional fetching (optional optimization)
|
||||||
|
|
||||||
|
The orders list returns an **`X-Page-Generated`** header (ISO 8601 server
|
||||||
|
time). Pass it back as the **`modified_since`** query parameter on the next
|
||||||
|
call to fetch only changed orders.
|
||||||
|
|
||||||
|
## Errors
|
||||||
|
|
||||||
|
4xx responses are JSON:
|
||||||
|
|
||||||
|
- General errors: `{"detail": "..."}`
|
||||||
|
- Field errors: `{"<field>": ["message", ...]}`
|
||||||
|
|
||||||
|
| Status | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `401` | auth failure (bad/missing token) |
|
||||||
|
| `403` | no permission / not found |
|
||||||
|
| `404` | not found |
|
||||||
|
|
||||||
|
## Rate limiting (pretix.eu only)
|
||||||
|
|
||||||
|
**360 requests/minute per organizer account.** Exceeding it returns
|
||||||
|
`429 Too Many Requests` with a **`Retry-After`** header (seconds to wait).
|
||||||
|
Our usage (~2–4 requests/minute) is far below the limit.
|
||||||
|
|
||||||
|
## Worked example (anonymized)
|
||||||
|
|
||||||
|
A real paid-order response shape, based on verified data:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "BZWHN",
|
||||||
|
"status": "p",
|
||||||
|
"email": "[email protected]",
|
||||||
|
"invoice_address": { "name": "Markus Franz" },
|
||||||
|
"positions": [
|
||||||
|
{
|
||||||
|
"id": 48560142,
|
||||||
|
"item": 1074118,
|
||||||
|
"attendee_name": "Markus Franz",
|
||||||
|
"attendee_email": null,
|
||||||
|
"secret": "awu65383xd8kyte8xkh...",
|
||||||
|
"canceled": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Note `attendee_email` is null — the sync falls back to the order `email`
|
||||||
|
(`[email protected]`) as the attendee's identity.
|
||||||
|
|
||||||
|
## How Convivo uses this
|
||||||
|
|
||||||
|
The sidecar **polls paid orders every minute** and, for each order:
|
||||||
|
|
||||||
|
1. **Groups positions by attendee email** — using `attendee_email`, falling
|
||||||
|
back to the order `email` when `attendee_email` is null (one buyer, several
|
||||||
|
tickets → several attendees under the same email).
|
||||||
|
2. **Maps the ticket item name to a registration type** — `speaker` / `staff` /
|
||||||
|
`sponsor` / `attendee` by substring match on the item name, **defaulting to
|
||||||
|
`attendee`**.
|
||||||
|
3. **Uses the position `secret` as the QR token** — which doubles as the
|
||||||
|
contact's **login password** (the same convention as
|
||||||
|
`create_registration` / `reset_registration_qr_token` in
|
||||||
|
[rpcs.md](./rpcs.md)).
|
||||||
|
4. **Writes via the service-role-only `sync_pretix_attendees` RPC** — the
|
||||||
|
sidecar is the only component that holds the service-role key (see
|
||||||
|
[sidecar.md](./sidecar.md)); the RPC upserts contacts + registrations
|
||||||
|
transactionally and is idempotent on re-run.
|
||||||
|
|
||||||
|
## Source
|
||||||
|
|
||||||
|
- [REST API overview](https://docs.pretix.eu/dev/api/)
|
||||||
|
- [Fundamentals — auth, pagination, errors, conditional fetching](https://docs.pretix.eu/dev/api/fundamentals.html)
|
||||||
|
- [Token authentication](https://docs.pretix.eu/dev/api/tokenauth.html)
|
||||||
|
- [Orders resource](https://docs.pretix.eu/dev/api/resources/orders.html)
|
||||||
|
- [Items resource](https://docs.pretix.eu/dev/api/resources/items.html)
|
||||||
|
- [Rate limiting](https://docs.pretix.eu/dev/api/ratelimit.html)
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
-- =============================================================================
|
||||||
|
-- Convivo — Pretix sync (Docker sidecar)
|
||||||
|
--
|
||||||
|
-- Re-introduces the Pretix interface (previously in 20260825, removed in
|
||||||
|
-- 20260830) as a service-role-only RPC driven by the sidecar's every-minute
|
||||||
|
-- loop. The sidecar pulls an event's Pretix orders (authenticated API), keeps
|
||||||
|
-- only paid orders (status = 'p'), groups them by email (one registration per
|
||||||
|
-- unique email per event), and calls the RPC below with the already-filtered
|
||||||
|
-- attendee array.
|
||||||
|
--
|
||||||
|
-- Design (locked):
|
||||||
|
-- * `events.pretix_organizer` + `events.pretix_event_slug` hold the Pretix
|
||||||
|
-- slugs per event. The API key is a sidecar env var, NOT stored here.
|
||||||
|
-- * The QR token is the Pretix per-ticket `secret`, stored on the
|
||||||
|
-- REGISTRATION (`registrations.qr_token`). It doubles as the login
|
||||||
|
-- password (hashed into `auth.users.encrypted_password`).
|
||||||
|
-- * `sync_pretix_attendees(uuid, jsonb)` is `security definer`, guarded to
|
||||||
|
-- the `service_role` caller (JWT role claim), so only the sidecar can call
|
||||||
|
-- it. It takes `p_event_id` explicitly (no "resolve the active event").
|
||||||
|
-- * Idempotency: the existing `external_id` columns (partial unique indexes)
|
||||||
|
-- + `unique (event_id, contact_email)` on registrations. Re-running a sync
|
||||||
|
-- updates in place instead of duplicating.
|
||||||
|
-- * `sync_runs` (event-scoped) is the audit trail behind the admin
|
||||||
|
-- "Interfaces" view's logs/result.
|
||||||
|
-- =============================================================================
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 1. EVENTS: per-event Pretix config
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
alter table public.events add column if not exists pretix_organizer text;
|
||||||
|
alter table public.events add column if not exists pretix_event_slug text;
|
||||||
|
comment on column public.events.pretix_organizer is
|
||||||
|
'Pretix organizer slug for this event (e.g. "convivo"). Used by the sidecar '
|
||||||
|
'every-minute sync to build the Pretix API URL. The API key is a sidecar env '
|
||||||
|
'var, not stored here.';
|
||||||
|
comment on column public.events.pretix_event_slug is
|
||||||
|
'Pretix event slug for this event (e.g. "convivo-2026"). Used by the sidecar '
|
||||||
|
'every-minute sync to build the Pretix API URL. The API key is a sidecar env '
|
||||||
|
'var, not stored here.';
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 2. HELPER: map a Pretix ticket type to a registration type
|
||||||
|
-- (case-insensitive substring match; defaults to 'attendee')
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
create or replace function public._map_ticket_type(p_ticket_type text)
|
||||||
|
returns text
|
||||||
|
language sql immutable as $$
|
||||||
|
select case
|
||||||
|
when lower(coalesce(p_ticket_type, '')) like '%speaker%' then 'speaker'
|
||||||
|
when lower(coalesce(p_ticket_type, '')) like '%staff%' then 'staff'
|
||||||
|
when lower(coalesce(p_ticket_type, '')) like '%sponsor%' then 'sponsor'
|
||||||
|
else 'attendee'
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 3. HELPER: ensure an auth.user exists for a contact (QR token = password).
|
||||||
|
-- Creates the user + identity if missing; updates the password if present.
|
||||||
|
-- (Mirrors the auth-sync logic in upsert_contact, but callable by the
|
||||||
|
-- service-role sync RPCs.)
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
create or replace function public._ensure_auth_user(p_email text, p_full_name text, p_qr_token text)
|
||||||
|
returns void
|
||||||
|
language plpgsql security definer set search_path = public as $$
|
||||||
|
declare
|
||||||
|
v_uid uuid;
|
||||||
|
begin
|
||||||
|
if p_qr_token is null or btrim(p_qr_token) = '' then
|
||||||
|
return; -- no token → no login (e.g. an external speaker)
|
||||||
|
end if;
|
||||||
|
select id into v_uid from auth.users where email = p_email;
|
||||||
|
if v_uid is null then
|
||||||
|
insert into auth.users (instance_id, id, aud, role, email, encrypted_password,
|
||||||
|
email_confirmed_at, confirmation_token, recovery_token, email_change_token_new,
|
||||||
|
email_change, raw_app_meta_data, raw_user_meta_data,
|
||||||
|
created_at, updated_at, confirmation_sent_at, last_sign_in_at)
|
||||||
|
values ('00000000-0000-0000-0000-000000000000', gen_random_uuid(), 'authenticated',
|
||||||
|
'authenticated', p_email, extensions.crypt(p_qr_token, extensions.gen_salt('bf')),
|
||||||
|
now(), '', '', '', '', '{"provider":"email","providers":["email"]}',
|
||||||
|
jsonb_build_object('full_name', p_full_name), now(), now(), now(), now())
|
||||||
|
returning id into v_uid;
|
||||||
|
insert into auth.identities (id, provider_id, identity_data, provider, user_id,
|
||||||
|
created_at, updated_at, last_sign_in_at)
|
||||||
|
values (v_uid, v_uid::text,
|
||||||
|
jsonb_build_object('sub', v_uid::text, 'email', p_email),
|
||||||
|
'email', v_uid, now(), now(), now());
|
||||||
|
else
|
||||||
|
update auth.users
|
||||||
|
set encrypted_password = extensions.crypt(p_qr_token, extensions.gen_salt('bf')),
|
||||||
|
updated_at = now()
|
||||||
|
where id = v_uid;
|
||||||
|
delete from auth.sessions where user_id = v_uid;
|
||||||
|
end if;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 4. SYNC RPC: Pretix attendees -> contacts + registrations
|
||||||
|
-- p_attendees is a JSON array of (already-filtered to paid orders, grouped
|
||||||
|
-- by email by the sidecar):
|
||||||
|
-- { email, full_name, ticket_type, qr_token, linkedin_url?, external_id? }
|
||||||
|
-- `ticket_type` is already mapped by the sidecar; `qr_token` is the Pretix
|
||||||
|
-- per-ticket secret. Returns a JSONB summary { created, updated, skipped,
|
||||||
|
-- errors[] }.
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
create or replace function public.sync_pretix_attendees(p_event_id uuid, p_attendees jsonb)
|
||||||
|
returns jsonb
|
||||||
|
language plpgsql security definer set search_path = public as $$
|
||||||
|
declare
|
||||||
|
v_run_id uuid;
|
||||||
|
v_started timestamptz := now();
|
||||||
|
v_item jsonb;
|
||||||
|
v_email text;
|
||||||
|
v_name text;
|
||||||
|
v_type text;
|
||||||
|
v_token text;
|
||||||
|
v_linkedin text;
|
||||||
|
v_ext text;
|
||||||
|
v_existed boolean;
|
||||||
|
v_created integer := 0;
|
||||||
|
v_updated integer := 0;
|
||||||
|
v_skipped integer := 0;
|
||||||
|
v_errors jsonb := '[]'::jsonb;
|
||||||
|
v_err text;
|
||||||
|
begin
|
||||||
|
-- Inside a security definer function, session_user is the owner (postgres),
|
||||||
|
-- so detect the caller via the JWT role claim instead.
|
||||||
|
if coalesce(auth.jwt() ->> 'role', '') <> 'service_role' then
|
||||||
|
raise exception 'service_role only';
|
||||||
|
end if;
|
||||||
|
if not exists (select 1 from public.events where id = p_event_id) then
|
||||||
|
raise exception 'event not found';
|
||||||
|
end if;
|
||||||
|
insert into public.sync_runs (event_id, source, started_at, triggered_by)
|
||||||
|
values (p_event_id, 'pretix', v_started, 'service_role')
|
||||||
|
returning id into v_run_id;
|
||||||
|
|
||||||
|
for v_item in select * from jsonb_array_elements(coalesce(p_attendees, '[]'::jsonb))
|
||||||
|
loop
|
||||||
|
begin
|
||||||
|
v_email := v_item ->> 'email';
|
||||||
|
v_name := v_item ->> 'full_name';
|
||||||
|
v_type := public._map_ticket_type(v_item ->> 'ticket_type');
|
||||||
|
v_token := v_item ->> 'qr_token';
|
||||||
|
v_linkedin := v_item ->> 'linkedin_url';
|
||||||
|
v_ext := v_item ->> 'external_id';
|
||||||
|
|
||||||
|
if v_email is null or btrim(v_email) = '' or v_name is null or btrim(v_name) = '' then
|
||||||
|
v_skipped := v_skipped + 1;
|
||||||
|
continue;
|
||||||
|
end if;
|
||||||
|
|
||||||
|
-- Upsert the contact (by email). The QR token lives on the registration,
|
||||||
|
-- not the contact, so the contact upsert carries no token.
|
||||||
|
select exists (select 1 from public.contacts where email = v_email) into v_existed;
|
||||||
|
insert into public.contacts (email, full_name, linkedin_url, is_admin, external_id)
|
||||||
|
values (v_email, v_name, v_linkedin, false, v_ext)
|
||||||
|
on conflict (email) do update
|
||||||
|
set full_name = excluded.full_name,
|
||||||
|
linkedin_url = coalesce(excluded.linkedin_url, public.contacts.linkedin_url),
|
||||||
|
external_id = coalesce(excluded.external_id, public.contacts.external_id);
|
||||||
|
if v_existed then
|
||||||
|
v_updated := v_updated + 1;
|
||||||
|
else
|
||||||
|
v_created := v_created + 1;
|
||||||
|
end if;
|
||||||
|
|
||||||
|
-- Ensure the auth user (QR token = password) exists.
|
||||||
|
perform public._ensure_auth_user(v_email, v_name, v_token);
|
||||||
|
|
||||||
|
-- A `sponsor` registration requires a sponsor lookup (business rule).
|
||||||
|
-- Pretix doesn't carry sponsor details, so create a minimal one.
|
||||||
|
if v_type = 'sponsor' and not exists (
|
||||||
|
select 1 from public.sponsors
|
||||||
|
where event_id = p_event_id and contact_email = v_email
|
||||||
|
) then
|
||||||
|
insert into public.sponsors (event_id, type, name, contact_email, paid)
|
||||||
|
values (p_event_id, 'community', v_name, v_email, false);
|
||||||
|
end if;
|
||||||
|
|
||||||
|
-- Upsert the registration for this event (by contact). The QR token is
|
||||||
|
-- the Pretix per-ticket secret, stored on the registration. `type` is a
|
||||||
|
-- Postgres ENUM (registration_type), so cast the mapped text value.
|
||||||
|
insert into public.registrations (event_id, contact_email, type, qr_token, external_id)
|
||||||
|
values (p_event_id, v_email, v_type::public.registration_type, v_token, v_ext)
|
||||||
|
on conflict (event_id, contact_email) do update
|
||||||
|
set type = excluded.type,
|
||||||
|
qr_token = coalesce(excluded.qr_token, public.registrations.qr_token),
|
||||||
|
external_id = coalesce(excluded.external_id, public.registrations.external_id);
|
||||||
|
exception when others then
|
||||||
|
v_err := coalesce(v_email, '<no email>') || ': ' || sqlerrm;
|
||||||
|
v_errors := v_errors || to_jsonb(v_err);
|
||||||
|
v_skipped := v_skipped + 1;
|
||||||
|
end;
|
||||||
|
end loop;
|
||||||
|
|
||||||
|
update public.sync_runs
|
||||||
|
set finished_at = now(), created = v_created, updated = v_updated,
|
||||||
|
skipped = v_skipped, error = case when jsonb_array_length(v_errors) > 0
|
||||||
|
then v_errors::text else null end
|
||||||
|
where id = v_run_id;
|
||||||
|
|
||||||
|
update public.events set last_synced_at = now() where id = p_event_id;
|
||||||
|
|
||||||
|
return jsonb_build_object('created', v_created, 'updated', v_updated,
|
||||||
|
'skipped', v_skipped, 'errors', v_errors);
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- 5. RLS + GRANTS
|
||||||
|
-- -----------------------------------------------------------------------------
|
||||||
|
-- The sync_runs table + its admin-select RLS policy already exist (added by the
|
||||||
|
-- Sessionize sidecar migration); only the grants for the new functions are
|
||||||
|
-- added here.
|
||||||
|
|
||||||
|
-- The sync RPC + helpers are service-role only (guarded inside via the JWT role
|
||||||
|
-- claim). Grant execute to service_role only — NOT to the apps.
|
||||||
|
grant execute on function public.sync_pretix_attendees(uuid, jsonb) to service_role;
|
||||||
|
grant execute on function public._ensure_auth_user(text, text, text) to service_role;
|
||||||
|
grant execute on function public._map_ticket_type(text) to service_role;
|
||||||
|
|
||||||
|
-- sync_runs is readable by authenticated (RLS restricts to admins).
|
||||||
|
grant select on public.sync_runs to authenticated, service_role;
|
||||||
Reference in new issue
Block a user