- docs/backend/pretix.md: Pretix REST API reference (auth, orders/items endpoints, pagination, rate limiting, worked example) - migration 20260909000000_pretix_sync.sql: events.pretix_organizer + pretix_event_slug; _map_ticket_type, _ensure_auth_user (QR token = password), sync_pretix_attendees (service-role-only, idempotent) - sidecar: pretixFetch/fetchPretixOrders/fetchPretixItems/transformPretix, runPretixSync + every-minute runPretixLoop, POST /run-pretix, /status extended with pretix state - admin: Pretix panel + recent runs in Interfaces, per-event Pretix config + Sync button in Events, api/types for Pretix - docker-compose: PRETIX_API_KEY / PRETIX_BASE / PRETIX_SYNC_INTERVAL_MS Verified on VM: 25 paid orders -> 25 attendees, auto-sync every minute, login via QR token works, idempotent (no duplicate registrations). Co-authored-by: Stephan Charles <[email protected]> Co-authored-by: Amelia Hernandez <[email protected]> Co-authored-by: Markus Franz <[email protected]> Co-authored-by: Sabrina Hota <[email protected]> Co-authored-by: Nilüfer Doğan <[email protected]>
225 lines
11 KiB
PL/PgSQL
225 lines
11 KiB
PL/PgSQL
-- =============================================================================
|
|
-- 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;
|