Files
Convivo/supabase/migrations/20260832000000_slots_enum_excel_import.sql
5f8ded56f6 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.

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]>
2026-08-24 20:47:29 +02:00

289 lines
13 KiB
PL/PgSQL
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- =============================================================================
-- 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;