-- ============================================================================= -- Convivo — Sessionize sync (Docker sidecar) -- -- Re-introduces the Sessionize interface as a Docker sidecar (not an Edge -- Function). The sidecar fetches an event's Sessionize data (authenticated API) -- and calls the service-role-only RPC below, which imports, in order: -- 1. speakers as contacts (matched by email), -- 2. sessions (upserted by external_id), -- 3. the agenda/schedule (slots + session_speakers links). -- -- Design (locked): -- * `events.sessionize_endpoint` stores the Sessionize API URL per event. -- The sidecar derives the authenticated API URL from it (/view/ -> /api/) -- and authenticates with a sidecar-held API key. -- * `sync_sessionize_event(uuid, jsonb)` is `security definer`, guarded to the -- `service_role` caller (JWT role claim), so only the sidecar can call it. -- * Idempotency: external ids on contacts/sessions (partial unique indexes, -- added by the earlier interfaces migration and kept) + slots matched by -- (event, date, start, end). Re-running updates in place. -- * Speaker matching is by contact email. Linking a speaker to a session fires -- the `session_speakers_speaker_promote` trigger, which promotes an existing -- registration to 'speaker'. Registrations are NOT created here — they come -- from the ticket sync, which will check session_speakers by email. -- * `sync_runs` (event-scoped) is the audit trail behind the admin "Interfaces" -- view's logs/result. -- ============================================================================= -- ----------------------------------------------------------------------------- -- 1. EVENTS: Sessionize endpoint + last-synced stamp -- ----------------------------------------------------------------------------- alter table public.events add column if not exists sessionize_endpoint text; alter table public.events add column if not exists last_synced_at timestamptz; comment on column public.events.sessionize_endpoint is 'Sessionize API URL for this event (e.g. https://sessionize.com/api/v2//view/All). ' 'The sidecar derives the authenticated API URL from it.'; comment on column public.events.last_synced_at is 'When the Sessionize sync last ran for this event.'; -- ----------------------------------------------------------------------------- -- 2. SYNC RUNS (event-scoped audit trail) -- ----------------------------------------------------------------------------- create table if not exists public.sync_runs ( id uuid primary key default gen_random_uuid(), event_id uuid not null references public.events (id) on delete cascade, source text not null default '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_event_idx on public.sync_runs (event_id, started_at desc); -- ----------------------------------------------------------------------------- -- 3. HELPER: ensure an auth user exists for a contact (placeholder password). -- Creates the user + identity if missing; never touches an existing user's -- password. Mirrors the auth-sync logic in upsert_contact, so an imported -- speaker can log in once a registration token is issued. -- ----------------------------------------------------------------------------- create or replace function public._ensure_auth_user_exists(p_email text, p_full_name text) returns void language plpgsql security definer set search_path = public as $$ declare v_uid uuid; begin select id into v_uid from auth.users where email = p_email; if v_uid is not null then return; -- already exists; leave the password alone end if; 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('no-token-yet', 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()); end; $$; -- ----------------------------------------------------------------------------- -- 4. SYNC RPC: Sessionize payload -> contacts + sessions + agenda -- p_payload is a JSON object: -- { -- speakers: [{ email, full_name, external_id? }], -- sessions: [{ external_id, title, description?, room?, -- date, start_time, end_time, speakers: [email, ...] }] -- } -- Runs in order: (1) speakers -> contacts, (2) sessions, (3) speaker links. -- Per-item failures are collected into errors[] (the run does not abort). -- Returns a JSONB summary. -- ----------------------------------------------------------------------------- create or replace function public.sync_sessionize_event(p_event_id uuid, p_payload 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_ext text; v_title text; v_desc text; v_room text; v_date date; v_start time; v_end time; v_slot public.slots; v_slot_id integer; v_session public.sessions; v_existing boolean; v_spk text; v_speakers_created integer := 0; v_speakers_updated integer := 0; v_sessions_created integer := 0; v_sessions_updated integer := 0; v_slots_created integer := 0; v_speakers_linked 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, 'sessionize', v_started, 'service_role') returning id into v_run_id; -- (1) Speakers -> contacts (matched by email). for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'speakers', '[]'::jsonb)) loop begin v_email := v_item ->> 'email'; v_name := v_item ->> 'full_name'; 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 continue; -- no email/name -> can't match; skip end if; select exists (select 1 from public.contacts where email = v_email) into v_existing; insert into public.contacts (email, full_name, external_id) values (v_email, v_name, v_ext) on conflict (email) do update set full_name = excluded.full_name, external_id = coalesce(excluded.external_id, public.contacts.external_id); perform public._ensure_auth_user_exists(v_email, v_name); if v_existing then v_speakers_updated := v_speakers_updated + 1; else v_speakers_created := v_speakers_created + 1; end if; exception when others then v_err := coalesce(v_email, '') || ': ' || sqlerrm; v_errors := v_errors || to_jsonb(v_err); end; end loop; -- (2) Sessions + (3) agenda (slots + speaker links). for v_item in select * from jsonb_array_elements(coalesce(p_payload -> '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_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 = p_event_id and slot_date = v_date and start_time = v_start and end_time = v_end limit 1; if not found then -- Allocate an id that is safe even if the sequence is behind the -- seeded rows (the seed inserts explicit ids after migrations run). -- GREATEST(nextval, max(id)+1) then re-syncs the sequence so future -- nextval calls never collide. select greatest(nextval('public.slots_id_seq'), (select coalesce(max(id), 0) from public.slots) + 1) into v_slot_id; perform setval('public.slots_id_seq', v_slot_id, true); insert into public.slots (id, event_id, type, name, slot_date, start_time, end_time) values (v_slot_id, p_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 = p_event_id and external_id = v_ext) into v_existing; insert into public.sessions (event_id, slot_id, title, description, room, external_id) values (p_event_id, v_slot.id, v_title, v_desc, v_room, 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) 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; -- (3) Speaker links: DIFF (insert the new set, then delete only removed). -- Inserting first keeps the session at >= 1 speaker so the -- session_needs_speaker trigger never blocks the removals. for v_spk in select * from jsonb_array_elements_text(coalesce(v_item -> 'speakers', '[]'::jsonb)) loop if v_spk is null or btrim(v_spk) = '' then continue; end if; insert into public.session_speakers (session_id, contact_email) values (v_session.id, v_spk) on conflict (session_id, contact_email) do nothing; v_speakers_linked := v_speakers_linked + 1; end loop; -- Delete removed speakers (only if the session keeps >= 1 speaker). if (select count(*) from jsonb_array_elements_text(coalesce(v_item -> 'speakers', '[]'::jsonb))) > 0 then delete from public.session_speakers ss where ss.session_id = v_session.id and not exists ( select 1 from jsonb_array_elements_text(coalesce(v_item -> 'speakers', '[]'::jsonb)) as e where e = ss.contact_email ); end if; 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_speakers_created + v_sessions_created + v_slots_created, updated = v_speakers_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; update public.events set last_synced_at = now() where id = p_event_id; return jsonb_build_object( 'speakers_created', v_speakers_created, 'speakers_updated', v_speakers_updated, 'sessions_created', v_sessions_created, 'sessions_updated', v_sessions_updated, 'slots_created', v_slots_created, 'speakers_linked', v_speakers_linked, 'errors', v_errors ); end; $$; -- ----------------------------------------------------------------------------- -- 5. 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 RPC + helper 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_sessionize_event(uuid, jsonb) to service_role; grant execute on function public._ensure_auth_user_exists(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;