-- ============================================================================= -- Convivo — Phase 7 (Pretix) + Phase 8 (Sessionize): external interfaces -- -- Adds the plumbing to sync REAL data from Pretix (tickets → contacts + -- registrations) and Sessionize (agenda → slots + sessions + speakers) into -- the multi-event model. -- -- Design (locked): -- * The sync runs as a Supabase Edge Function (`sync-trigger`) that pulls from -- the external APIs and calls the service-role-only RPCs below. -- * These RPCs are `security definer` and guarded to the `service_role` -- caller (checked via the JWT `role` claim — `session_user` is the owner -- inside a definer function), so they can write to `auth.users` and bypass -- RLS — but ONLY the Edge Function (which holds the service-role key) can -- call them. The apps (anon/authenticated) cannot. -- * Idempotency: external ids are stored on contacts / registrations / -- sessions (partial unique indexes) so re-running a sync updates in place -- instead of duplicating. -- * A `sync_runs` audit table records every run (source, counts, errors). -- ============================================================================= -- ----------------------------------------------------------------------------- -- 1. EXTERNAL ID COLUMNS (idempotency keys for the syncs) -- ----------------------------------------------------------------------------- alter table public.contacts add column if not exists external_id text; alter table public.registrations add column if not exists external_id text; alter table public.sessions add column if not exists external_id text; create unique index if not exists contacts_external_id_uniq on public.contacts (external_id) where external_id is not null; create unique index if not exists registrations_external_id_uniq on public.registrations (external_id) where external_id is not null; create unique index if not exists sessions_external_id_uniq on public.sessions (external_id) where external_id is not null; -- Sequence to assign ids to slots created by the Sessionize sync (slots.id is -- an integer PK with no default; the seed uses explicit ids 1..N). The seed runs -- AFTER migrations, so the table may be empty here — use the standard idiom that -- is safe for both the empty and populated cases (empty → next nextval = 1). create sequence if not exists public.slots_id_seq; select setval('public.slots_id_seq', coalesce((select max(id) from public.slots), 1), (select max(id) from public.slots) is not null); -- ----------------------------------------------------------------------------- -- 2. SYNC RUNS (audit trail of every interface run) -- ----------------------------------------------------------------------------- create table if not exists public.sync_runs ( id uuid primary key default gen_random_uuid(), source text not null check (source in ('pretix', 'sessionize')), started_at timestamptz not null default now(), finished_at timestamptz, created integer not null default 0, updated integer not null default 0, skipped integer not null default 0, error text, triggered_by text not null default 'service_role' ); create index if not exists sync_runs_source_idx on public.sync_runs (source, started_at desc); -- ----------------------------------------------------------------------------- -- 3. 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; $$; -- ----------------------------------------------------------------------------- -- 4. 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; $$; -- ----------------------------------------------------------------------------- -- 5. SYNC RPC: Pretix attendees → contacts + registrations -- p_attendees is a JSON array of: -- { email, full_name, ticket_type, qr_token?, linkedin_url?, external_id? } -- Returns a JSONB summary { created, updated, skipped, errors[] }. -- ----------------------------------------------------------------------------- create or replace function public.sync_pretix_attendees(p_attendees jsonb) returns jsonb language plpgsql security definer set search_path = public as $$ declare v_event_id uuid; 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_contact public.contacts; v_reg public.registrations; 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/current_user are 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; select id into v_event_id from public.events where is_active limit 1; if v_event_id is null then raise exception 'no active event'; end if; insert into public.sync_runs (source, started_at, triggered_by) values ('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). Keep the existing QR token unless a new -- one is supplied (so a re-sync never invalidates a working lanyard). -- Pretix does not provide a token, so generate one for new ticket holders. select qr_token into v_token from public.contacts where email = v_email; v_token := coalesce(v_token, v_item ->> 'qr_token', 'CVV-' || upper(substr(md5(random()::text), 1, 3)) || '-' || lpad((floor(random() * 10000))::int::text, 4, '0')); insert into public.contacts (email, full_name, linkedin_url, is_admin, qr_token, external_id) values (v_email, v_name, v_linkedin, false, v_token, 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) returning * into v_contact; -- Ensure the auth user (QR token = password) exists. perform public._ensure_auth_user(v_email, v_name, v_contact.qr_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 = v_event_id and contact_email = v_email ) then insert into public.sponsors (event_id, type, name, contact_email, paid) values (v_event_id, 'community', v_name, v_email, false); end if; -- Upsert the registration for the active event (by contact). insert into public.registrations (event_id, contact_email, type, external_id) values (v_event_id, v_email, v_type, v_ext) on conflict (event_id, contact_email) do update set type = excluded.type, external_id = coalesce(excluded.external_id, public.registrations.external_id) returning * into v_reg; v_updated := v_updated + 1; exception when others then v_err := coalesce(v_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; return jsonb_build_object('created', v_created, 'updated', v_updated, 'skipped', v_skipped, 'errors', v_errors); end; $$; -- ----------------------------------------------------------------------------- -- 6. SYNC RPC: Sessionize sessions → slots + sessions + speakers -- p_sessions is a JSON array of: -- { external_id, title, description?, room?, capacity?, -- date, start_time, end_time, speakers: [{ email, full_name }] } -- Slots are matched/created by (event, date, start, end). Sessions are -- upserted by external_id. Speakers are upserted as contacts + links. -- Returns a JSONB summary { slots_created, sessions_created, sessions_updated, -- speakers_linked, errors[] }. -- ----------------------------------------------------------------------------- create or replace function public.sync_sessionize_sessions(p_sessions jsonb) returns jsonb language plpgsql security definer set search_path = public as $$ declare v_event_id uuid; v_run_id uuid; v_started timestamptz := now(); v_item jsonb; v_ext text; v_title text; v_desc text; v_room text; v_cap integer; v_date date; v_start time; v_end time; v_slot public.slots; v_session public.sessions; v_spk jsonb; v_spk_email text; v_spk_name text; v_spk_token text; v_slots_created integer := 0; v_sessions_created integer := 0; v_sessions_updated integer := 0; v_speakers_linked integer := 0; v_errors jsonb := '[]'::jsonb; v_err text; v_existing boolean; begin if coalesce(auth.jwt() ->> 'role', '') <> 'service_role' then raise exception 'service_role only'; end if; select id into v_event_id from public.events where is_active limit 1; if v_event_id is null then raise exception 'no active event'; end if; insert into public.sync_runs (source, started_at, triggered_by) values ('sessionize', v_started, 'service_role') returning id into v_run_id; for v_item in select * from jsonb_array_elements(coalesce(p_sessions, '[]'::jsonb)) loop begin v_ext := v_item ->> 'external_id'; v_title := v_item ->> 'title'; v_desc := v_item ->> 'description'; v_room := v_item ->> 'room'; v_cap := (v_item ->> 'capacity')::int; v_date := (v_item ->> 'date')::date; v_start := (v_item ->> 'start_time')::time; v_end := (v_item ->> 'end_time')::time; if v_ext is null or v_title is null or v_date is null or v_start is null or v_end is null then v_errors := v_errors || to_jsonb(coalesce(v_title, '') || ': missing required field'); continue; end if; -- Find or create the slot by (event, date, start, end). select * into v_slot from public.slots where event_id = v_event_id and slot_date = v_date and start_time = v_start and end_time = v_end limit 1; if not found then insert into public.slots (id, event_id, type, name, slot_date, start_time, end_time) values (nextval('public.slots_id_seq'), v_event_id, 'session', 'Slot ' || to_char(v_start, 'HH24:MI') || '–' || to_char(v_end, 'HH24:MI'), v_date, v_start, v_end) returning * into v_slot; v_slots_created := v_slots_created + 1; end if; -- Upsert the session by external_id. select exists (select 1 from public.sessions where event_id = v_event_id and external_id = v_ext) into v_existing; insert into public.sessions (event_id, slot_id, title, description, room, capacity, external_id) values (v_event_id, v_slot.id, v_title, v_desc, v_room, v_cap, v_ext) on conflict (external_id) where external_id is not null do update set slot_id = excluded.slot_id, title = excluded.title, description = coalesce(excluded.description, public.sessions.description), room = coalesce(excluded.room, public.sessions.room), capacity = coalesce(excluded.capacity, public.sessions.capacity) returning * into v_session; if v_existing then v_sessions_updated := v_sessions_updated + 1; else v_sessions_created := v_sessions_created + 1; end if; -- Link speakers (upsert contact + session_speakers). for v_spk in select * from jsonb_array_elements(coalesce(v_item -> 'speakers', '[]'::jsonb)) loop v_spk_email := v_spk ->> 'email'; v_spk_name := v_spk ->> 'full_name'; v_spk_token := v_spk ->> 'qr_token'; if v_spk_email is null or v_spk_name is null then continue; end if; insert into public.contacts (email, full_name, qr_token) values (v_spk_email, v_spk_name, v_spk_token) on conflict (email) do update set full_name = excluded.full_name, qr_token = coalesce(excluded.qr_token, public.contacts.qr_token); perform public._ensure_auth_user(v_spk_email, v_spk_name, v_spk_token); insert into public.session_speakers (session_id, contact_email) values (v_session.id, v_spk_email) on conflict (session_id, contact_email) do nothing; v_speakers_linked := v_speakers_linked + 1; end loop; exception when others then v_err := coalesce(v_title, '') || ': ' || sqlerrm; v_errors := v_errors || to_jsonb(v_err); end; end loop; update public.sync_runs set finished_at = now(), created = v_sessions_created + v_slots_created, updated = v_sessions_updated, skipped = 0, error = case when jsonb_array_length(v_errors) > 0 then v_errors::text else null end where id = v_run_id; return jsonb_build_object('slots_created', v_slots_created, 'sessions_created', v_sessions_created, 'sessions_updated', v_sessions_updated, 'speakers_linked', v_speakers_linked, 'errors', v_errors); end; $$; -- ----------------------------------------------------------------------------- -- 7. RLS + GRANTS -- ----------------------------------------------------------------------------- alter table public.sync_runs enable row level security; -- Only admins can read the sync audit trail. drop policy if exists "sync_runs_select_admin" on public.sync_runs; create policy "sync_runs_select_admin" on public.sync_runs for select to authenticated using (public.is_admin()); -- The sync RPCs are service-role only (guarded inside the function via -- session_user). Grant execute to service_role only — NOT to the apps. grant execute on function public.sync_pretix_attendees(jsonb) to service_role; grant execute on function public.sync_sessionize_sessions(jsonb) to service_role; grant execute on function public._map_ticket_type(text) to service_role; grant execute on function public._ensure_auth_user(text, text, text) to service_role; -- sync_runs is readable by authenticated (RLS restricts to admins). grant select on public.sync_runs to authenticated, service_role;