Files
Convivo/supabase/migrations/20260826000000_registration_qr_token.sql
T
2f3952dc71 Fixes & Refinements: QR token on registration, role caps, connection detail + red dot, admin schedule/sponsors
Datamodel:
- Move qr_token from contacts to registrations (per event); new migration
  20260826000000. lanyard_lookup / create_connection_request / checkin_attendee
  resolve via registrations + active event.
- reset_qr_token -> reset_registration_qr_token (fixes ambiguous 'email' col).
- upsert_contact drops the token arg; create_registration generates + syncs it.
- Pretix sync writes the token to the registration (keeps it on re-sync).

Registration types:
- Distinct pill colors; red reserved for Staff (both apps).
- Roles capitalized everywhere (Attendee/Speaker/Sponsor/Staff); 'Attendee'
  hidden only at the Home footer.
- Reset-token button moved from Contacts to Registrations (per registration).

Sessions (APPE Admin):
- Slot types capitalized; material submitted/not-submitted state.
- Speaker selection = multi-select search dropdown.
- Fix 'a session must have a speaker' on edit (diff-based setSessionSpeakers)
  and the file-upload bug (speaker save no longer aborts first).

APPE Admin:
- Sponsors contact lookup = search field (filter + pick).

Convivo App:
- Other people's QR codes hidden; connection detail sheet shows public info +
  points.
- Connect red dot recalculates immediately on accept/decline/send.
- 'My picks today' = 2 rows (current + next); 'tap to change' links to Agenda.

Docs updated across backend + frontend.

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-23 10:39:21 +02:00

536 lines
23 KiB
PL/PgSQL
Raw 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 — Fixes & Refinements: QR token is a property of the REGISTRATION
--
-- The QR token is generated by Pretix and changes per event, so it belongs on
-- the registration (per event), not the contact (per person). This migration:
-- * adds `registrations.qr_token` (unique) and drops `contacts.qr_token`.
-- * re-points every token lookup at the active event's registration:
-- lanyard_lookup, create_connection_request, checkin_attendee.
-- * replaces `reset_qr_token(contact)` with `reset_registration_qr_token(email)`
-- (regenerates the active event's registration token + syncs the auth
-- password, since the token doubles as the login password).
-- * `upsert_contact` no longer takes/sets a token (contacts have none).
-- * the Pretix sync writes the token to the registration (Pretix generates it
-- per ticket); the Sessionize sync no longer writes contact tokens.
--
-- The auth password is still the QR token (QR + email login, no email sent).
-- =============================================================================
-- -----------------------------------------------------------------------------
-- 1. MOVE THE COLUMN
-- -----------------------------------------------------------------------------
alter table public.registrations add column if not exists qr_token text;
create unique index if not exists registrations_qr_token_uniq
on public.registrations (qr_token) where qr_token is not null;
-- Copy each contact's token onto their active-event registration (idempotent:
-- only fills rows that don't already have a token).
update public.registrations r
set qr_token = c.qr_token
from public.contacts c
where r.contact_email = c.email
and r.event_id = (select id from public.events where is_active limit 1)
and r.qr_token is null
and c.qr_token is not null;
-- Drop the old column (cascades the old index).
alter table public.contacts drop column if exists qr_token;
-- -----------------------------------------------------------------------------
-- 2. TOKEN LOOKUP: resolve a QR token to the contact + registration type for
-- the ACTIVE event (the token now lives on the registration).
-- -----------------------------------------------------------------------------
create or replace function public.lanyard_lookup(p_qr_token text)
returns table (email text, full_name text, linkedin_url text,
show_email boolean, registration_type text)
language sql stable security definer set search_path = public as $$
select c.email,
c.full_name,
case when c.show_linkedin then c.linkedin_url else null end as linkedin_url,
c.show_email,
r.type as registration_type
from public.registrations r
join public.contacts c on c.email = r.contact_email
where r.qr_token = p_qr_token
and r.event_id = (select id from public.events where is_active limit 1);
$$;
-- -----------------------------------------------------------------------------
-- 3. CONNECTION REQUEST: resolve the scanned token to a contact (active event).
-- -----------------------------------------------------------------------------
create or replace function public.create_connection_request(p_target_qr text)
returns public.connections
language plpgsql security definer set search_path = public as $$
declare
v_email text := public.current_email();
v_target text;
v_event_id uuid;
v_conn public.connections;
begin
if v_email is null then raise exception 'not authenticated'; end if;
select r.contact_email into v_target
from public.registrations r
where r.qr_token = p_target_qr
and r.event_id = (select id from public.events where is_active limit 1);
if v_target is null then raise exception 'no attendee found for that QR code'; end if;
if v_target = v_email then raise exception 'you cannot connect with yourself'; 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;
select * into v_conn from public.connections
where event_id = v_event_id
and ((from_email = v_email and to_email = v_target)
or (from_email = v_target and to_email = v_email))
limit 1;
if found then
return v_conn;
end if;
insert into public.connections (event_id, from_email, to_email, status)
values (v_event_id, v_email, v_target, 'pending')
returning * into v_conn;
return v_conn;
end;
$$;
-- -----------------------------------------------------------------------------
-- 4. CHECK-IN: resolve the scanned token to a contact (active event).
-- -----------------------------------------------------------------------------
create or replace function public.checkin_attendee(p_session_id uuid, p_attendee_qr text)
returns table (checkin_id uuid, attendee_email text, attendee_name text,
points integer, already boolean)
language plpgsql security definer set search_path = public as $$
declare
v_staff text := public.current_email();
v_attendee text;
v_name text;
v_event_id uuid;
v_new_id uuid;
v_points integer;
v_already boolean := false;
begin
if v_staff is null then raise exception 'not authenticated'; end if;
if not public.is_staff_or_admin() then raise exception 'staff or admin only'; end if;
select r.contact_email, c.full_name into v_attendee, v_name
from public.registrations r
join public.contacts c on c.email = r.contact_email
where r.qr_token = p_attendee_qr
and r.event_id = (select id from public.events where is_active limit 1);
if v_attendee is null then raise exception 'no attendee found for that QR code'; end if;
select event_id into v_event_id from public.sessions where id = p_session_id;
if v_event_id is null then raise exception 'session not found'; end if;
insert into public.checkins (event_id, contact_email, session_id, staff_email)
values (v_event_id, v_attendee, p_session_id, v_staff)
on conflict (event_id, contact_email, session_id) do nothing
returning id into v_new_id;
if v_new_id is null then
v_already := true;
select id into v_new_id from public.checkins
where event_id = v_event_id and contact_email = v_attendee and session_id = p_session_id;
else
perform public._award_points(v_event_id, v_attendee, 10, 'checkin');
update public.registrations set checked_in = true
where event_id = v_event_id and contact_email = v_attendee;
end if;
select r.points into v_points from public.registrations r
where r.event_id = v_event_id and r.contact_email = v_attendee;
return query select v_new_id, v_attendee, v_name, coalesce(v_points, 0), v_already;
end;
$$;
-- -----------------------------------------------------------------------------
-- 5. RESET TOKEN: now per registration (active event). Regenerates the token
-- and re-hashes it as the auth password (the old token stops working).
-- -----------------------------------------------------------------------------
create or replace function public.reset_registration_qr_token(p_contact_email text)
returns table (email text, qr_token text)
language plpgsql security definer set search_path = public as $$
declare
v_uid uuid;
v_token text;
v_salt text;
v_event_id uuid;
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;
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 = p_contact_email) then
raise exception 'registration not found';
end if;
v_token := 'CVV-' || upper(substr(md5(random()::text), 1, 3)) || '-'
|| lpad((floor(random() * 10000))::int::text, 4, '0');
update public.registrations set qr_token = v_token
where event_id = v_event_id and contact_email = p_contact_email;
-- Qualify auth.users.email: the function's output column is also named
-- `email` (returns table (email, qr_token)), so a bare `email` is ambiguous.
select id into v_uid from auth.users where auth.users.email = p_contact_email;
if v_uid is not null then
v_salt := extensions.gen_salt('bf');
update auth.users
set encrypted_password = extensions.crypt(v_token, v_salt), updated_at = now()
where id = v_uid;
delete from auth.sessions where user_id = v_uid;
end if;
return query select p_contact_email, v_token;
end;
$$;
-- Drop the old contact-scoped reset function.
drop function if exists public.reset_qr_token(text);
-- -----------------------------------------------------------------------------
-- 6. UPSERT CONTACT: contacts no longer carry a token.
-- -----------------------------------------------------------------------------
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 once a registration
-- token is issued (the token doubles as the password). If no auth user yet,
-- create one with a placeholder password; the registration token (set via
-- create_registration / the sync) is what actually unlocks login.
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('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;
$$;
-- -----------------------------------------------------------------------------
-- 7. CREATE REGISTRATION: generate a token (Pretix-style) + sync the auth
-- password, so a newly registered contact can log in immediately.
-- -----------------------------------------------------------------------------
create or replace function public.create_registration(p_contact_email text, p_type text)
returns public.registrations
language plpgsql security definer set search_path = public as $$
declare
v_email text := public.current_email();
v_event_id uuid;
v_reg public.registrations;
v_token text;
v_uid uuid;
begin
if v_email is null then raise exception 'not authenticated'; end if;
if not public.is_admin() then raise exception 'admin only'; end if;
if not exists (select 1 from public.contacts where email = p_contact_email) then
raise exception 'contact not found';
end if;
if p_type is null or p_type not in ('attendee', 'speaker', 'staff', 'sponsor') then
raise exception 'invalid registration type';
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 p_type = 'sponsor' and not exists (
select 1 from public.sponsors where event_id = v_event_id and contact_email = p_contact_email
) then
raise exception 'a sponsor registration requires a sponsor lookup';
end if;
-- Generate a token for the new registration (Pretix generates one per ticket).
v_token := 'CVV-' || upper(substr(md5(random()::text), 1, 3)) || '-'
|| lpad((floor(random() * 10000))::int::text, 4, '0');
insert into public.registrations (event_id, contact_email, type, qr_token)
values (v_event_id, p_contact_email, p_type, v_token)
on conflict (event_id, contact_email) do update
set type = excluded.type
returning * into v_reg;
-- Sync the auth password to the new token (so login works right away).
select id into v_uid from auth.users where email = p_contact_email;
if v_uid is not null then
update auth.users
set encrypted_password = extensions.crypt(v_reg.qr_token, extensions.gen_salt('bf')),
updated_at = now()
where id = v_uid;
delete from auth.sessions where user_id = v_uid;
end if;
return v_reg;
end;
$$;
-- -----------------------------------------------------------------------------
-- 8. PRETIX SYNC: write the token to the REGISTRATION (Pretix generates it per
-- ticket). The contact no longer stores a token.
-- -----------------------------------------------------------------------------
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
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). No token on the contact anymore.
insert into public.contacts (email, full_name, linkedin_url, is_admin, external_id)
values (v_email, v_name, v_linkedin, false, 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;
-- A `sponsor` registration requires a sponsor lookup (business rule).
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). The QR token
-- lives here (Pretix generates it per ticket). Keep the existing token
-- unless a new one is supplied (so a re-sync never invalidates a lanyard).
select qr_token into v_token
from public.registrations
where event_id = v_event_id and contact_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.registrations (event_id, contact_email, type, external_id, qr_token)
values (v_event_id, v_email, v_type, v_ext, v_token)
on conflict (event_id, contact_email) do update
set type = excluded.type,
external_id = coalesce(excluded.external_id, public.registrations.external_id),
qr_token = coalesce(excluded.qr_token, public.registrations.qr_token)
returning * into v_reg;
-- Ensure the auth user exists (QR token = password).
perform public._ensure_auth_user(v_email, v_name, v_reg.qr_token);
v_updated := v_updated + 1;
exception when others then
v_err := coalesce(v_email, '<no 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;
$$;
-- -----------------------------------------------------------------------------
-- 9. SESSIONIZE SYNC: speakers are upserted as contacts (no token) + links.
-- (Speakers get a login token only if they also hold a ticket/registration.)
-- -----------------------------------------------------------------------------
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_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, '<no title>') || ': missing required field');
continue;
end if;
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;
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;
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';
if v_spk_email is null or v_spk_name is null then
continue;
end if;
insert into public.contacts (email, full_name)
values (v_spk_email, v_spk_name)
on conflict (email) do update
set full_name = excluded.full_name;
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, '<no 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;
$$;
-- -----------------------------------------------------------------------------
-- 10. GRANTS (new/changed function signatures)
-- -----------------------------------------------------------------------------
grant execute on function public.lanyard_lookup(text) to authenticated;
grant execute on function public.create_connection_request(text) to authenticated;
grant execute on function public.checkin_attendee(uuid, text) to authenticated;
grant execute on function public.reset_registration_qr_token(text) to authenticated;
grant execute on function public.upsert_contact(text, text, text, boolean) to authenticated;
grant execute on function public.create_registration(text, text) to authenticated;
grant execute on function public.sync_pretix_attendees(jsonb) to service_role;
grant execute on function public.sync_sessionize_sessions(jsonb) to service_role;