Post-event reporting + talk networking incentives

- Talk networking: per-event talk_networking_bonus awarded when two people
  who shared a checked-in talk accept a connection (accept_connection
  re-created, shared_talk flag, get_talk_cohort RPC, points_log category
  check widened); Convivo Networking sub-tab inside the Connect screen
  (Home quick action deep-links in; Connect button reflects existing
  connection state and is disabled for sent/connected/declined); admin
  Events view bonus input (0-10).
- Reports: sidecar POST /export (CSV / multi-sheet XLSX / PDF report via
  new pdfkit dep); APPE Admin Reports view (any event: on-screen summary,
  session feedback summary, top-5, CSV/Excel/PDF downloads); Activity
  session-feedback per-session aggregate header.
- Also carried: @appe.at admin trigger + default password, bulk contact
  delete, session level/area + event-level feedback, agenda level/area
  filters, admin password self-service, schedule level/area fields.
- 18/18 RPC tests; both apps build; exports verified end-to-end.
This commit is contained in:
Lago committed 2026-09-21 22:34:25 +02:00
1 parent 08ab41898b
commit 3adc0fd58f
35 files changed
+3973 -54

No files matched your search

@@ -0,0 +1,189 @@
-- =============================================================================
-- Convivo — Default admin password for @appe.at contacts
--
-- Business rule: any @appe.at contact (admin) logs in with the default admin
-- password `appe-admin-2026` out of the box, without manual setup. A custom
-- password set on the contact row is always respected (never overwritten).
--
-- Implementation:
-- 1. The @appe.at BEFORE trigger now also sets contacts.password to the
-- default when it's null (respects an explicitly-set custom password).
-- 2. The auth-user-creation helpers use the contact's password (when set)
-- instead of a placeholder, so a freshly-created @appe.at admin can log in
-- immediately (the AFTER UPDATE OF password trigger only fires on UPDATE,
-- not INSERT, so the creation path must set the hash itself).
-- 3. The Pretix auth helper uses the contact's password (or the default) for
-- @appe.at emails — admins log in with the default, not a QR token.
-- 4. One-time reconciliation: existing @appe.at contacts with a null password
-- get the default, and it's synced into auth.users.
-- =============================================================================
-- -----------------------------------------------------------------------------
-- 1. @appe.at BEFORE trigger: default admin password when null
-- -----------------------------------------------------------------------------
create or replace function public._set_appe_at_admin()
returns trigger
language plpgsql security definer set search_path = public as $$
begin
if new.email like '%@appe.at' then
new.is_admin := true;
if new.password is null then
new.password := 'appe-admin-2026';
end if;
end if;
return new;
end;
$$;
-- Re-attach the (existing) trigger to the updated function.
drop trigger if exists trg_contacts_appe_at_admin on public.contacts;
create trigger trg_contacts_appe_at_admin
before insert or update on public.contacts
for each row execute function public._set_appe_at_admin();
-- -----------------------------------------------------------------------------
-- 2. upsert_contact: use the contact's password when creating the auth user
-- -----------------------------------------------------------------------------
create or replace function public.upsert_contact(
p_email text, p_full_name text, p_linkedin_url text,
p_is_admin boolean
)
returns public.contacts
language plpgsql security definer set search_path = public as $$
declare
v_uid uuid;
v_contact public.contacts;
begin
if auth.uid() is null then raise exception 'not authenticated'; end if;
if not public.is_admin() then raise exception 'admin only'; end if;
if p_email is null or btrim(p_email) = '' then raise exception 'email is required'; end if;
if p_full_name is null or btrim(p_full_name) = '' then raise exception 'full_name is required'; end if;
insert into public.contacts (email, full_name, linkedin_url, is_admin)
values (p_email, p_full_name, p_linkedin_url, coalesce(p_is_admin, false))
on conflict (email) do update
set full_name = excluded.full_name,
linkedin_url = excluded.linkedin_url,
is_admin = excluded.is_admin
returning * into v_contact;
-- Ensure an auth user exists so the contact can log in. If no auth user yet,
-- create one. Use the contact's password when set (e.g. the @appe.at default
-- admin password); otherwise a placeholder that a registration token replaces.
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(coalesce(v_contact.password, '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 if;
return v_contact;
end;
$$;
-- -----------------------------------------------------------------------------
-- 3. _ensure_auth_user_exists (sidecar): use the contact's password
-- -----------------------------------------------------------------------------
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;
v_pw text;
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;
select password into v_pw from public.contacts where email = p_email;
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(coalesce(v_pw, '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. _ensure_auth_user (pretix): @appe.at admins use the default password
-- -----------------------------------------------------------------------------
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;
v_pw text;
begin
select password into v_pw from public.contacts where email = p_email;
if p_email like '%@appe.at' then
v_pw := coalesce(v_pw, 'appe-admin-2026'); -- respect a custom password, else default
else
if p_qr_token is null or btrim(p_qr_token) = '' then
return; -- no token → no login (e.g. an external speaker)
end if;
v_pw := p_qr_token;
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(v_pw, 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(v_pw, extensions.gen_salt('bf')),
updated_at = now()
where id = v_uid;
delete from auth.sessions where user_id = v_uid;
end if;
end;
$$;
-- -----------------------------------------------------------------------------
-- 5. One-time reconciliation: existing @appe.at contacts with a null password
-- get the default (fires the password-sync trigger), and any @appe.at hash
-- is re-synced from the contact row so it matches.
-- -----------------------------------------------------------------------------
update public.contacts
set password = 'appe-admin-2026'
where email like '%@appe.at'
and password is null;
update auth.users u
set encrypted_password = extensions.crypt(c.password, extensions.gen_salt('bf'))
from public.contacts c
where u.email = c.email
and c.email like '%@appe.at'
and c.password is not null;
@@ -0,0 +1,73 @@
-- =============================================================================
-- Convivo — Bulk contact delete (admin) that bypasses the session-speaker guard
--
-- The admin "Delete all contacts for this event" action deletes a batch of
-- contacts in one PostgREST call. Deleting a contact cascades to their
-- session_speakers rows, which fires the `session_needs_speaker` BEFORE DELETE
-- trigger — and that trigger raises "a session must have at least one speaker"
-- when the contact is the sole speaker of a session. So a bulk wipe that
-- includes a lone speaker fails with P0001.
--
-- This adds an admin-only RPC that deletes the batch in a single transaction
-- with the guard temporarily disabled (the "at least one speaker" rule is a
-- data-integrity nicety for single edits; a deliberate bulk wipe is allowed to
-- leave a session speaker-less). The caller's own email is excluded by the app
-- (never passed in), so the admin can't delete themselves.
-- =============================================================================
create or replace function public.bulk_delete_contacts(p_emails text[])
returns integer
language plpgsql security definer set search_path = public as $$
declare
v_deleted integer;
begin
if auth.uid() is null then raise exception 'not authenticated'; end if;
if not public.is_admin() then raise exception 'admin only'; end if;
if p_emails is null or array_length(p_emails, 1) is null then
raise exception 'no emails provided';
end if;
-- Disable the guard for the duration of this transaction, then delete the
-- batch (cascades to registrations, session_speakers, checkins, connections,
-- feedback, leaderboard, points_log, preferences, sponsors).
perform public._disable_session_speaker_guard();
delete from public.contacts where email = any (p_emails);
get diagnostics v_deleted = row_count;
perform public._enable_session_speaker_guard();
return v_deleted;
end;
$$;
-- The session_needs_speaker trigger is a normal (non-deferrable) trigger, so we
-- toggle it with a GUC the trigger function checks. This keeps the trigger
-- object intact (no drop/create) and is safe to call from a security-definer
-- function.
create or replace function public._disable_session_speaker_guard()
returns void
language sql security definer set search_path = public as $$
select set_config('convivo.session_speaker_guard', 'off', false);
$$;
create or replace function public._enable_session_speaker_guard()
returns void
language sql security definer set search_path = public as $$
select set_config('convivo.session_speaker_guard', 'on', false);
$$;
-- Re-create the guard function to honor the GUC (off = skip the check).
create or replace function public._trg_session_needs_speaker() returns trigger
language plpgsql security definer set search_path = public as $$
begin
if coalesce(current_setting('convivo.session_speaker_guard', true), 'on') = 'off' then
return old;
end if;
if exists (select 1 from public.sessions where id = old.session_id)
and (select count(*) from public.session_speakers where session_id = old.session_id) <= 1 then
raise exception 'a session must have at least one speaker';
end if;
return old;
end;
$$;
grant execute on function public.bulk_delete_contacts(text[]) to authenticated;
@@ -0,0 +1,575 @@
-- =============================================================================
-- Convivo — Session level/area + event-level feedback
--
-- 1. `sessions.level` + `sessions.area` — free-text classification so the
-- attendee app can filter the agenda by level (e.g. 100/200/300 or
-- Beginner/Intermediate) and by area/topic (e.g. Power Apps, Power
-- Automate, Governance). Values come from the Sessionize sync (API +
-- Excel) and/or manual entry in the admin Schedule.
--
-- 2. `event_feedback` — a separate, event-level feedback form (distinct from
-- the per-session `feedback` table). Any registered participant can rate
-- the event overall (1–5) + leave a comment. One row per (event, contact).
-- Admins can read all of it (shown in the admin Activity view).
--
-- 3. `get_agenda()` is re-created to expose `level` + `area` (the original
-- lives in 20260824000000_redesign.sql; append-only migrations can't edit
-- it, so we replace it here).
--
-- 4. The Sessionize sync RPCs (`sync_sessionize_event` / `sync_sessionize_excel`)
-- are re-created to upsert `level` + `area` (the originals live in
-- 20260833000000_service_sessions_feedback.sql).
-- =============================================================================
-- -----------------------------------------------------------------------------
-- 1. sessions.level + sessions.area
-- -----------------------------------------------------------------------------
alter table public.sessions add column if not exists level text;
alter table public.sessions add column if not exists area text;
comment on column public.sessions.level is
'Free-text level classification (e.g. 100/200/300 or Beginner/Intermediate). '
'Used by the attendee app to filter the agenda. Set via the Sessionize sync '
'or manual entry in the admin Schedule.';
comment on column public.sessions.area is
'Free-text area/topic classification (e.g. Power Apps, Power Automate, '
'Governance). Used by the attendee app to filter the agenda.';
-- -----------------------------------------------------------------------------
-- 2. event_feedback table
-- -----------------------------------------------------------------------------
create table if not exists public.event_feedback (
id uuid primary key default gen_random_uuid(),
event_id uuid not null references public.events (id) on delete cascade,
contact_email text not null references public.contacts (email) on delete cascade,
rating integer not null check (rating between 1 and 5),
comment text,
created_at timestamptz not null default now(),
unique (event_id, contact_email)
);
create index if not exists event_feedback_event_id_idx
on public.event_feedback (event_id);
-- -----------------------------------------------------------------------------
-- 3. get_agenda() — re-created to expose level + area
-- (The return type changes, so we must drop the existing function first —
-- `create or replace` cannot change a function's return type.)
-- -----------------------------------------------------------------------------
drop function if exists public.get_agenda();
create or replace function public.get_agenda()
returns table (
slot_id integer, slot_name text, slot_date date, start_time time, end_time time,
slot_type text,
session_id uuid, title text, description text, room text, capacity integer,
average_feedback numeric, ai_generated_feedback text, material_path text,
speakers text, level text, area text
)
language sql stable security definer set search_path = public as $$
select s.id, s.name, s.slot_date, s.start_time, s.end_time, s.type,
se.id, se.title, se.description, se.room, se.capacity,
se.average_feedback, se.ai_generated_feedback, se.material_path,
(select string_agg(c.full_name, ', ' order by c.full_name)
from public.session_speakers ss
join public.contacts c on c.email = ss.contact_email
where ss.session_id = se.id) as speakers,
se.level, se.area
from public.slots s
left join public.sessions se on se.slot_id = s.id
where s.event_id = (select id from public.events where is_active limit 1)
order by s.id, se.title;
$$;
-- -----------------------------------------------------------------------------
-- 4. Event-level feedback RPCs
-- -----------------------------------------------------------------------------
-- Submit (or update) the current user's event-level feedback. Any registered
-- participant can do this (no check-in requirement — it's about the event as a
-- whole, not a specific session). Idempotent: one row per (event, contact).
create or replace function public.submit_event_feedback(p_rating integer, p_comment text)
returns table (feedback_id uuid, points integer)
language plpgsql security definer set search_path = public as $$
declare
v_email text := public.current_email();
v_event_id uuid;
v_fb_id uuid;
v_points integer;
v_clean text;
begin
if v_email is null then raise exception 'not authenticated'; end if;
if p_rating is null or p_rating < 1 or p_rating > 5 then
raise exception 'rating must be between 1 and 5';
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;
if not exists (select 1 from public.registrations
where event_id = v_event_id and contact_email = v_email) then
raise exception 'you must be registered for this event to give feedback';
end if;
v_clean := nullif(btrim(coalesce(p_comment, '')), '');
insert into public.event_feedback (event_id, contact_email, rating, comment)
values (v_event_id, v_email, p_rating, v_clean)
on conflict (event_id, contact_email) do update
set rating = excluded.rating, comment = excluded.comment
returning id into v_fb_id;
select r.points into v_points from public.registrations r
where r.event_id = v_event_id and r.contact_email = v_email;
return query select v_fb_id, coalesce(v_points, 0);
end;
$$;
-- Read the current user's own event feedback (for the "you already rated" state).
create or replace function public.get_my_event_feedback()
returns public.event_feedback
language sql stable security definer set search_path = public as $$
select * from public.event_feedback ef
where ef.contact_email = public.current_email()
and ef.event_id = (select id from public.events where is_active limit 1)
limit 1;
$$;
-- Admin: read all event feedback for the active event (for the admin Activity view).
create or replace function public.get_all_event_feedback()
returns setof public.event_feedback
language sql stable security definer set search_path = public as $$
select * from public.event_feedback ef
where ef.event_id = (select id from public.events where is_active limit 1)
order by ef.created_at desc;
$$;
-- -----------------------------------------------------------------------------
-- 5. RLS + grants
-- -----------------------------------------------------------------------------
alter table public.event_feedback enable row level security;
-- Read own, or all if admin.
create policy "event_feedback_select_own_or_admin" on public.event_feedback for select to authenticated
using (contact_email = public.current_email() or public.is_admin());
-- Writes happen via the submit_event_feedback RPC (security definer), so no
-- direct insert/update/delete policies are needed.
grant select on public.event_feedback to anon, authenticated, service_role;
grant insert, update, delete on public.event_feedback to authenticated, service_role;
grant execute on function public.submit_event_feedback(integer, text) to authenticated;
grant execute on function public.get_my_event_feedback() to authenticated;
grant execute on function public.get_all_event_feedback() to authenticated;
-- -----------------------------------------------------------------------------
-- 6. Re-create the Sessionize sync RPCs to upsert level + area
-- (The originals live in 20260833000000_service_sessions_feedback.sql;
-- append-only migrations can't edit them, so we replace them here. The
-- only change is adding level + area to the session upsert.)
-- -----------------------------------------------------------------------------
-- 6a. sync_sessionize_event (API sync) — adds level + area to the session upsert.
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_service boolean;
v_level text;
v_area text;
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
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;
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;
v_service := coalesce((v_item ->> 'is_service_session')::boolean, false);
v_level := nullif(btrim(coalesce(v_item ->> 'level', '')), '');
v_area := nullif(btrim(coalesce(v_item ->> 'area', '')), '');
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
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 (now including level + area).
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, level, area)
values (p_event_id, v_slot.id, v_title, v_desc, v_room, v_ext, v_level, v_area)
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),
level = coalesce(excluded.level, public.sessions.level),
area = coalesce(excluded.area, public.sessions.area)
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).
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;
-- Service sessions: every registered staff member is a speaker.
if v_service then
perform public._assign_service_session_speakers(v_session.id, p_event_id);
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;
$$;
-- 6b. sync_sessionize_excel (Excel import) — adds level + area to the session upsert.
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_level text;
v_area text;
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);
v_level := nullif(btrim(coalesce(v_item ->> 'level', '')), '');
v_area := nullif(btrim(coalesce(v_item ->> 'area', '')), '');
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
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 (now including level + area).
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, level, area)
values (p_event_id, v_slot.id, v_title, v_desc, v_room, v_ext, v_level, v_area)
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),
level = coalesce(excluded.level, public.sessions.level),
area = coalesce(excluded.area, public.sessions.area)
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;
-- Service sessions: every registered staff member is a speaker.
if v_service then
perform public._assign_service_session_speakers(v_session.id, p_event_id);
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.
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;
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;
$$;
grant execute on function public.sync_sessionize_event(uuid, jsonb) to service_role;
grant execute on function public.sync_sessionize_excel(uuid, jsonb) to service_role;
@@ -0,0 +1,123 @@
-- =============================================================================
-- Convivo — Talk networking incentives
--
-- A per-event configurable bonus awarded when two people who were checked into
-- the SAME session (talk) accept a connection. This rewards "networking around
-- talks": meeting someone who was in the same talk and making a connection.
--
-- 1. `events.talk_networking_bonus` (integer, default 2) — the bonus points
-- awarded to EACH party when they share a checked-in session and accept a
-- connection. **0 disables the feature** (no bonus, the +5 connection award
-- still applies).
--
-- 2. `accept_connection(uuid)` is re-created (append-only migrations can't
-- edit it, and the return type changes, so we drop + recreate) to:
-- - keep the existing +5-to-both connection award,
-- - compute whether both parties share a checked-in session,
-- - if they do AND `talk_networking_bonus > 0`, award the bonus to each
-- party (category `talk_networking`),
-- - return a new `shared_talk` column (so the app can show a "met at
-- {talk}" note).
--
-- Idempotency: `accept_connection` is one-shot (row locked, status must be
-- `pending`), so the bonus can never double-award. Documented limitation:
-- check-ins that happen AFTER acceptance do not retro-award the bonus — the
-- bonus reflects shared attendance at acceptance time.
--
-- The bonus flows through `_award_points`, so the leaderboard sync + staff
-- exclusion are inherited automatically (no change to `_sync_leaderboard`).
-- =============================================================================
-- -----------------------------------------------------------------------------
-- 1. events.talk_networking_bonus
-- -----------------------------------------------------------------------------
alter table public.events add column if not exists talk_networking_bonus integer not null default 2;
comment on column public.events.talk_networking_bonus is
'Bonus points awarded to EACH party when two people who were checked into the '
'same session (talk) accept a connection. 0 disables the feature. '
'Awarded with category "talk_networking".';
-- Widen the points_log.category CHECK to include the new `talk_networking`
-- category (the original constraint only allowed the four original categories).
alter table public.points_log drop constraint if exists points_log_category_check;
alter table public.points_log add constraint points_log_category_check
check (category in ('checkin', 'connection', 'feedback', 'admin', 'talk_networking'));
-- -----------------------------------------------------------------------------
-- 2. accept_connection — re-created to add the talk networking bonus
-- (The return type changes from `public.connections` to a table that adds
-- `shared_talk`, so we must drop the existing function first.)
-- -----------------------------------------------------------------------------
drop function if exists public.accept_connection(uuid);
create or replace function public.accept_connection(p_connection_id uuid)
returns table (
event_id uuid, from_email text, to_email text, status text,
created_at timestamptz, resolved_at timestamptz, shared_talk boolean
)
language plpgsql security definer set search_path = public as $$
declare
v_email text := public.current_email();
v_conn public.connections;
v_shared boolean;
v_bonus integer;
begin
if v_email is null then raise exception 'not authenticated'; end if;
select * into v_conn from public.connections where id = p_connection_id for update;
if not found then raise exception 'connection not found'; end if;
if v_conn.to_email <> v_email then raise exception 'you can only accept incoming requests'; end if;
if v_conn.status <> 'pending' then raise exception 'request already resolved'; end if;
update public.connections set status = 'accepted', resolved_at = now() where id = p_connection_id;
perform public._award_points(v_conn.event_id, v_conn.from_email, 5, 'connection');
perform public._award_points(v_conn.event_id, v_conn.to_email, 5, 'connection');
-- Talk networking bonus: do the two parties share a checked-in session (talk)?
select count(*) > 0 into v_shared
from public.checkins a
where a.event_id = v_conn.event_id
and a.contact_email = v_conn.from_email
and exists (
select 1 from public.checkins b
where b.event_id = v_conn.event_id
and b.contact_email = v_conn.to_email
and b.session_id = a.session_id
);
select coalesce(talk_networking_bonus, 0) into v_bonus
from public.events where id = v_conn.event_id;
if v_shared and v_bonus > 0 then
perform public._award_points(v_conn.event_id, v_conn.from_email, v_bonus, 'talk_networking');
perform public._award_points(v_conn.event_id, v_conn.to_email, v_bonus, 'talk_networking');
end if;
select * into v_conn from public.connections where id = p_connection_id;
-- A single final `return query` (a `return query` inside an `if` block would
-- not terminate the function and would double-award).
return query select v_conn.event_id, v_conn.from_email, v_conn.to_email,
v_conn.status, v_conn.created_at, v_conn.resolved_at, v_shared;
end;
$$;
grant execute on function public.accept_connection(uuid) to authenticated;
-- -----------------------------------------------------------------------------
-- 3. get_talk_cohort(p_session_id) — who else was checked into the same talk
-- The `checkins` RLS policy is own-or-admin, so an attendee cannot read
-- other people's check-ins directly. This security-definer RPC returns the
-- other attendees (email + full_name + registration type + QR token, for
-- the Connect action) who were checked into the given session. The caller's
-- own row is excluded. Staff are excluded (they are not "attendees" of the
-- networking game).
-- -----------------------------------------------------------------------------
create or replace function public.get_talk_cohort(p_session_id uuid)
returns table (email text, full_name text, registration_type public.registration_type, qr_token text)
language sql stable security definer set search_path = public as $$
select c.email, c.full_name, r."type", r.qr_token
from public.checkins ck
join public.registrations r
on r.event_id = ck.event_id and r.contact_email = ck.contact_email
join public.contacts c on c.email = ck.contact_email
where ck.session_id = p_session_id
and r."type" <> 'staff'
and c.email <> public.current_email();
$$;
grant execute on function public.get_talk_cohort(uuid) to authenticated;