feat: add sidecar service for Sessionize sync

- Introduced a new Node HTTP service (sidecar) to sync event agendas from Sessionize into Convivo.
- Implemented two import paths: API sync and Excel import for session and speaker data.
- Added necessary database migrations for sessionize integration, including new columns and audit tables.
- Created functions for handling speaker and session imports, ensuring proper error handling and logging.
- Established row-level security and grants for new functions to restrict access to service-role only.
This commit is contained in:
Lago committed 2026-08-24 20:47:29 +02:00
1 parent 8054d0ace2
commit f7aea663d8
31 files changed
+2729 -390

No files matched your search

@@ -0,0 +1,294 @@
-- =============================================================================
-- 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/<id>/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, '<no 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, '<no 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, '<no 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;
@@ -0,0 +1,288 @@
-- =============================================================================
-- Convivo — Slots optionset + Excel import
--
-- 1. `slots.type` becomes a Postgres ENUM (`slot_type`) — a true optionset of
-- exactly two values, 'session' and 'service_session' (service sessions are
-- breaks / lunch / closing, i.e. Sessionize's isServiceSession). Enforced at
-- the database level, not freetext.
-- 2. `slots.id` gets a sequence default so the admin UI (and the sidecar) can
-- create a slot WITHOUT supplying an explicit id. The seed still inserts
-- explicit ids and re-syncs the sequence afterwards.
-- 3. `sync_sessionize_excel(uuid, jsonb)` — service-role-only RPC that imports
-- the Sessionize "Sessions and speakers (advanced)" Excel export. The sidecar
-- parses the .xlsx and calls this. It upserts speakers (by email), sessions
-- (by external_id), and the agenda (slots + speaker links), and — unlike the
-- API sync — also creates/updates a 'speaker' registration for every speaker
-- (the Excel carries emails, so the contact-level match is reliable).
-- =============================================================================
-- -----------------------------------------------------------------------------
-- 1. SLOTS TYPE OPTIONSET (Postgres ENUM)
-- -----------------------------------------------------------------------------
do $$
begin
if not exists (select 1 from pg_type where typname = 'slot_type') then
create type public.slot_type as enum ('session', 'service_session');
end if;
end $$;
-- Convert the text column to the enum. Existing values map cleanly:
-- 'session' -> 'session'; everything else (keynote/lunch_break/coffee_break/
-- close_up) -> 'service_session' (they are all non-talk agenda items).
-- The text default can't auto-cast, so drop it, convert, then set the enum
-- default in a separate statement.
alter table public.slots drop constraint if exists slots_type_check;
alter table public.slots alter column type drop default;
alter table public.slots
alter column type type public.slot_type
using case when type = 'session' then 'session'::public.slot_type
else 'service_session'::public.slot_type end;
alter table public.slots alter column type set default 'session'::public.slot_type;
-- -----------------------------------------------------------------------------
-- 2. SLOTS ID DEFAULT (so the UI can create slots without an explicit id)
-- -----------------------------------------------------------------------------
-- The seed inserts explicit ids (1..N) and then re-syncs the sequence, so the
-- default is safe for both the seed and runtime inserts.
do $$
begin
if not exists (select 1 from pg_class where relname = 'slots_id_seq') then
create sequence public.slots_id_seq;
end if;
if (select column_default from information_schema.columns
where table_name = 'slots' and column_name = 'id') is null then
alter table public.slots alter column id set default nextval('public.slots_id_seq');
end if;
end $$;
-- -----------------------------------------------------------------------------
-- 3. EXCEL IMPORT RPC
-- p_payload is a JSON object:
-- {
-- speakers: [{ email, full_name, external_id?, linkedin_url? }],
-- sessions: [{ external_id, title, description?, room?,
-- date, start_time, end_time, is_service_session?,
-- speakers: [email, ...] }]
-- }
-- Runs in order: (1) speakers -> contacts, (2) sessions + agenda (slots +
-- speaker links), (3) speaker registrations (create/update to 'speaker').
-- Per-item failures are collected into errors[] (the run does not abort).
-- Returns a JSONB summary.
-- -----------------------------------------------------------------------------
create or replace function public.sync_sessionize_excel(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_linkedin text;
v_title text;
v_desc text;
v_room text;
v_date date;
v_start time;
v_end time;
v_service boolean;
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_regs_created integer := 0;
v_regs_updated integer := 0;
v_errors jsonb := '[]'::jsonb;
v_err text;
begin
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_excel', 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';
v_linkedin := v_item ->> 'linkedin_url';
if v_email is null or btrim(v_email) = '' or v_name is null or btrim(v_name) = '' then
continue;
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, linkedin_url)
values (v_email, v_name, v_ext, v_linkedin)
on conflict (email) do update
set full_name = excluded.full_name,
external_id = coalesce(excluded.external_id, public.contacts.external_id),
linkedin_url = coalesce(excluded.linkedin_url, public.contacts.linkedin_url);
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, '<no email>') || ': ' || sqlerrm;
v_errors := v_errors || to_jsonb(v_err);
end;
end loop;
-- (2) Sessions + 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;
v_service := coalesce((v_item ->> 'is_service_session')::boolean, false);
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, '<no 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 safe even if the sequence is behind seeded rows.
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,
case when v_service then 'service_session'::public.slot_type
else 'session'::public.slot_type end,
case when v_service then 'Service Session'
else 'Slot ' || to_char(v_start, 'HH24:MI') || '–' || to_char(v_end, 'HH24:MI') end,
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;
-- Speaker links: DIFF (insert the new set, then delete only removed).
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;
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, '<no title>') || ': ' || sqlerrm;
v_errors := v_errors || to_jsonb(v_err);
end;
end loop;
-- (3) Speaker registrations: create/update to 'speaker' for every speaker.
-- The Excel carries emails, so the contact-level match is reliable. This
-- is the "add the missing registrations for the speakers" step.
for v_item in select * from jsonb_array_elements(coalesce(p_payload -> 'speakers', '[]'::jsonb))
loop
begin
v_email := v_item ->> 'email';
if v_email is null or btrim(v_email) = '' then
continue;
end if;
if not exists (select 1 from public.contacts where email = v_email) then
continue; -- speaker had no valid contact; skip
end if;
select exists (select 1 from public.registrations
where event_id = p_event_id and contact_email = v_email) into v_existing;
insert into public.registrations (event_id, contact_email, type)
values (p_event_id, v_email, 'speaker'::public.registration_type)
on conflict (event_id, contact_email) do update
set type = case when public.registrations.type in ('staff', 'sponsor')
then public.registrations.type
else 'speaker'::public.registration_type end
where public.registrations.type not in ('staff', 'sponsor');
if v_existing then
v_regs_updated := v_regs_updated + 1;
else
v_regs_created := v_regs_created + 1;
end if;
exception when others then
v_err := coalesce(v_email, '<no email>') || ': ' || 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 + v_regs_created,
updated = v_speakers_updated + v_sessions_updated + v_regs_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,
'registrations_created', v_regs_created,
'registrations_updated', v_regs_updated,
'errors', v_errors
);
end;
$$;
-- -----------------------------------------------------------------------------
-- 4. GRANTS
-- -----------------------------------------------------------------------------
grant execute on function public.sync_sessionize_excel(uuid, jsonb) to service_role;