-- ============================================================================= -- Convivo — Phase 0: initial schema, RLS, and transactional points RPCs -- ============================================================================= create extension if not exists "pgcrypto"; -- ----------------------------------------------------------------------------- -- TABLES -- ----------------------------------------------------------------------------- -- Source of truth for people. `id` is the Supabase Auth user id. -- `qr_token` is the lanyard token; it doubles as the Auth password for the -- QR + email login flow (no email is ever sent). create table public.profiles ( id uuid primary key references auth.users (id) on delete cascade, email text not null unique, full_name text not null, company text, role text not null default 'attendee' check (role in ('attendee', 'staff', 'admin')), qr_token text unique, points integer not null default 0 check (points >= 0), created_at timestamptz not null default now() ); create table public.slots ( id integer primary key, name text not null, slot_date date not null, start_time time not null, end_time time not null ); create table public.sessions ( id uuid primary key default gen_random_uuid(), title text not null, description text, slot_id integer not null references public.slots (id) on delete cascade, room text, capacity integer, speakers text, created_at timestamptz not null default now() ); -- One preferred session per slot per attendee. create table public.preferences ( id uuid primary key default gen_random_uuid(), profile_id uuid not null references public.profiles (id) on delete cascade, session_id uuid not null references public.sessions (id) on delete cascade, slot_id integer not null, created_at timestamptz not null default now(), unique (profile_id, slot_id) ); -- The custom M:N networking relationship. Unique per unordered pair. create table public.connections ( id uuid primary key default gen_random_uuid(), from_id uuid not null references public.profiles (id) on delete cascade, to_id uuid not null references public.profiles (id) on delete cascade, status text not null default 'pending' check (status in ('pending', 'accepted', 'rejected')), created_at timestamptz not null default now(), resolved_at timestamptz ); create unique index connections_pair_uniq on public.connections (least(from_id, to_id), greatest(from_id, to_id)); -- Staff check-in of an attendee into a session. Unique per (attendee, session). create table public.checkins ( id uuid primary key default gen_random_uuid(), profile_id uuid not null references public.profiles (id) on delete cascade, session_id uuid not null references public.sessions (id) on delete cascade, staff_id uuid not null references public.profiles (id) on delete cascade, created_at timestamptz not null default now(), unique (profile_id, session_id) ); -- Post-session feedback. Unique per (attendee, session). create table public.feedback ( id uuid primary key default gen_random_uuid(), profile_id uuid not null references public.profiles (id) on delete cascade, session_id uuid not null references public.sessions (id) on delete cascade, rating integer not null check (rating between 1 and 5), comment text, created_at timestamptz not null default now(), unique (profile_id, session_id) ); -- Public, Realtime-friendly mirror of points for the live leaderboard. -- Kept in sync transactionally by the points RPCs (see _sync_leaderboard). create table public.leaderboard ( profile_id uuid primary key references public.profiles (id) on delete cascade, full_name text not null, company text, points integer not null default 0, updated_at timestamptz not null default now() ); -- Audit trail powering the per-category points breakdown. create table public.points_log ( id uuid primary key default gen_random_uuid(), profile_id uuid not null references public.profiles (id) on delete cascade, delta integer not null, category text not null check (category in ('checkin', 'connection', 'feedback', 'admin')), created_at timestamptz not null default now() ); create index sessions_slot_id_idx on public.sessions (slot_id); create index checkins_session_id_idx on public.checkins (session_id); create index points_log_profile_id_idx on public.points_log (profile_id); create index profiles_qr_token_idx on public.profiles (qr_token); -- ----------------------------------------------------------------------------- -- ROLE HELPER FUNCTIONS (security definer so they can read profiles in RLS) -- ----------------------------------------------------------------------------- create or replace function public.is_admin() returns boolean language sql stable security definer set search_path = public as $$ select exists (select 1 from public.profiles where id = auth.uid() and role = 'admin'); $$; create or replace function public.is_staff_or_admin() returns boolean language sql stable security definer set search_path = public as $$ select exists (select 1 from public.profiles where id = auth.uid() and role in ('staff', 'admin')); $$; -- ----------------------------------------------------------------------------- -- INTERNAL POINTS HELPERS (security definer: bypass RLS, run as owner) -- ----------------------------------------------------------------------------- create or replace function public._sync_leaderboard(p_profile_id uuid) returns void language plpgsql security definer set search_path = public as $$ begin insert into public.leaderboard (profile_id, full_name, company, points) select id, full_name, company, points from public.profiles where id = p_profile_id on conflict (profile_id) do update set full_name = excluded.full_name, company = excluded.company, points = excluded.points, updated_at = now(); end; $$; create or replace function public._award_points(p_profile_id uuid, p_delta integer, p_category text) returns void language plpgsql security definer set search_path = public as $$ begin update public.profiles set points = greatest(0, points + p_delta) where id = p_profile_id; insert into public.points_log (profile_id, delta, category) values (p_profile_id, p_delta, p_category); perform public._sync_leaderboard(p_profile_id); end; $$; -- ----------------------------------------------------------------------------- -- PUBLIC READ FUNCTIONS (security definer: expose only public columns) -- ----------------------------------------------------------------------------- -- Powers the leaderboard initial load and id -> name/company/role lookups. create or replace function public.get_public_profiles() returns table (id uuid, full_name text, company text, role text, points integer) language sql stable security definer set search_path = public as $$ select id, full_name, company, role, points from public.profiles order by points desc, full_name asc; $$; -- Resolves a scanned lanyard QR token to a public profile (pre-login + connect). create or replace function public.lanyard_lookup(p_qr_token text) returns table (id uuid, full_name text, company text, role text) language sql stable security definer set search_path = public as $$ select id, full_name, company, role from public.profiles where qr_token = p_qr_token; $$; -- ----------------------------------------------------------------------------- -- RPCs -- ----------------------------------------------------------------------------- -- Set (or change) the preferred session for the slot that p_session_id belongs to. create or replace function public.set_preference(p_session_id uuid) returns public.preferences language plpgsql security definer set search_path = public as $$ declare v_uid uuid := auth.uid(); v_slot_id integer; v_pref public.preferences; begin if v_uid is null then raise exception 'not authenticated'; end if; select slot_id into v_slot_id from public.sessions where id = p_session_id; if v_slot_id is null then raise exception 'session not found'; end if; delete from public.preferences where profile_id = v_uid and slot_id = v_slot_id; insert into public.preferences (profile_id, session_id, slot_id) values (v_uid, p_session_id, v_slot_id) returning * into v_pref; return v_pref; end; $$; create or replace function public.clear_preference(p_slot_id integer) returns void language plpgsql security definer set search_path = public as $$ declare v_uid uuid := auth.uid(); begin if v_uid is null then raise exception 'not authenticated'; end if; delete from public.preferences where profile_id = v_uid and slot_id = p_slot_id; end; $$; -- Create a pending connection to the attendee whose lanyard QR was scanned. -- Idempotent: returns the existing connection if the pair already has one. 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_uid uuid := auth.uid(); v_target uuid; v_conn public.connections; begin if v_uid is null then raise exception 'not authenticated'; end if; select id into v_target from public.profiles where qr_token = p_target_qr; if v_target is null then raise exception 'no attendee found for that QR code'; end if; if v_target = v_uid then raise exception 'you cannot connect with yourself'; end if; select * into v_conn from public.connections where (from_id = v_uid and to_id = v_target) or (from_id = v_target and to_id = v_uid) limit 1; if found then return v_conn; end if; insert into public.connections (from_id, to_id, status) values (v_uid, v_target, 'pending') returning * into v_conn; return v_conn; end; $$; -- Accept an incoming connection request. Awards +5 to both parties. create or replace function public.accept_connection(p_connection_id uuid) returns public.connections language plpgsql security definer set search_path = public as $$ declare v_uid uuid := auth.uid(); v_conn public.connections; begin if v_uid 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_id <> v_uid 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.from_id, 5, 'connection'); perform public._award_points(v_conn.to_id, 5, 'connection'); select * into v_conn from public.connections where id = p_connection_id; return v_conn; end; $$; create or replace function public.reject_connection(p_connection_id uuid) returns public.connections language plpgsql security definer set search_path = public as $$ declare v_uid uuid := auth.uid(); v_conn public.connections; begin if v_uid 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_id <> v_uid then raise exception 'you can only reject incoming requests'; end if; if v_conn.status <> 'pending' then raise exception 'request already resolved'; end if; update public.connections set status = 'rejected', resolved_at = now() where id = p_connection_id; select * into v_conn from public.connections where id = p_connection_id; return v_conn; end; $$; -- Staff checks an attendee into a session. Awards +10 to the attendee. -- Returns already=true if the attendee was already checked in (no double points). create or replace function public.checkin_attendee(p_session_id uuid, p_attendee_qr text) returns table (checkin_id uuid, attendee_id uuid, attendee_name text, points integer, already boolean) language plpgsql security definer set search_path = public as $$ declare v_uid uuid := auth.uid(); v_attendee uuid; v_name text; v_new_id uuid; v_points integer; v_already boolean := false; begin if v_uid 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 id, full_name into v_attendee, v_name from public.profiles where qr_token = p_attendee_qr; if v_attendee is null then raise exception 'no attendee found for that QR code'; end if; insert into public.checkins (profile_id, session_id, staff_id) values (v_attendee, p_session_id, v_uid) on conflict (profile_id, session_id) do nothing returning id into v_new_id; if v_new_id is null then -- Already checked in: no double points; report the existing check-in. v_already := true; select id into v_new_id from public.checkins where profile_id = v_attendee and session_id = p_session_id; else perform public._award_points(v_attendee, 10, 'checkin'); end if; select p.points into v_points from public.profiles p where p.id = v_attendee; return query select v_new_id, v_attendee, v_name, v_points, v_already; end; $$; -- Post-session feedback. Requires the attendee to be checked in. -- Awards +5 (rating only) or +10 (rating + comment). Idempotent per session. create or replace function public.submit_feedback(p_session_id uuid, p_rating integer, p_comment text) returns table (feedback_id uuid, points integer, earned integer) language plpgsql security definer set search_path = public as $$ declare v_uid uuid := auth.uid(); v_earned integer; v_fb_id uuid; v_points integer; v_clean text; v_exists boolean; begin if v_uid 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; if not exists (select 1 from public.checkins where profile_id = v_uid and session_id = p_session_id) then raise exception 'you must be checked in to this session to give feedback'; end if; v_clean := nullif(btrim(coalesce(p_comment, '')), ''); v_earned := case when v_clean is not null then 10 else 5 end; select exists (select 1 from public.feedback where profile_id = v_uid and session_id = p_session_id) into v_exists; if v_exists then update public.feedback set rating = p_rating, comment = v_clean where profile_id = v_uid and session_id = p_session_id; select id into v_fb_id from public.feedback where profile_id = v_uid and session_id = p_session_id; v_earned := 0; -- already rewarded on first submission else insert into public.feedback (profile_id, session_id, rating, comment) values (v_uid, p_session_id, p_rating, v_clean) returning id into v_fb_id; perform public._award_points(v_uid, v_earned, 'feedback'); end if; select p.points into v_points from public.profiles p where p.id = v_uid; return query select v_fb_id, v_points, v_earned; end; $$; -- Admin-only manual points adjustment. create or replace function public.adjust_points(p_profile_id uuid, p_delta integer, p_reason text) returns void language plpgsql security definer set search_path = public as $$ declare v_uid uuid := auth.uid(); begin if v_uid is null then raise exception 'not authenticated'; end if; if not public.is_admin() then raise exception 'admin only'; end if; perform public._award_points(p_profile_id, p_delta, 'admin'); end; $$; -- Full agenda: slots (ordered) each with their sessions. create or replace function public.get_agenda() returns table ( slot_id integer, slot_name text, slot_date date, start_time time, end_time time, session_id uuid, title text, description text, room text, capacity integer, speakers 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, se.id, se.title, se.description, se.room, se.capacity, se.speakers from public.slots s left join public.sessions se on se.slot_id = s.id order by s.id, se.title; $$; -- ----------------------------------------------------------------------------- -- ROW LEVEL SECURITY -- ----------------------------------------------------------------------------- alter table public.profiles enable row level security; alter table public.slots enable row level security; alter table public.sessions enable row level security; alter table public.preferences enable row level security; alter table public.connections enable row level security; alter table public.checkins enable row level security; alter table public.feedback enable row level security; alter table public.leaderboard enable row level security; alter table public.points_log enable row level security; -- profiles: full row only for self or admin (protects email + qr_token). create policy "profiles_select_own_or_admin" on public.profiles for select to authenticated using (id = auth.uid() or public.is_admin()); create policy "profiles_update_admin" on public.profiles for update to authenticated using (public.is_admin()) with check (public.is_admin()); create policy "profiles_delete_admin" on public.profiles for delete to authenticated using (public.is_admin()); -- slots: readable by all authenticated; writable by admin. create policy "slots_select_all" on public.slots for select to authenticated using (true); create policy "slots_admin_insert" on public.slots for insert to authenticated with check (public.is_admin()); create policy "slots_admin_update" on public.slots for update to authenticated using (public.is_admin()) with check (public.is_admin()); create policy "slots_admin_delete" on public.slots for delete to authenticated using (public.is_admin()); -- sessions: readable by all authenticated; writable by admin. create policy "sessions_select_all" on public.sessions for select to authenticated using (true); create policy "sessions_admin_insert" on public.sessions for insert to authenticated with check (public.is_admin()); create policy "sessions_admin_update" on public.sessions for update to authenticated using (public.is_admin()) with check (public.is_admin()); create policy "sessions_admin_delete" on public.sessions for delete to authenticated using (public.is_admin()); -- preferences: read own; writes happen via RPC (security definer). create policy "prefs_select_own" on public.preferences for select to authenticated using (profile_id = auth.uid()); -- connections: read any row you're part of; writes happen via RPC. create policy "conn_select_involved" on public.connections for select to authenticated using (from_id = auth.uid() or to_id = auth.uid()); -- checkins: read own, or all if staff/admin; writes happen via RPC. create policy "checkins_select_own_or_staff" on public.checkins for select to authenticated using (profile_id = auth.uid() or public.is_staff_or_admin()); -- feedback: read own; writes happen via RPC. create policy "feedback_select_own" on public.feedback for select to authenticated using (profile_id = auth.uid()); -- leaderboard: public to all authenticated (Realtime source). create policy "leaderboard_select_all" on public.leaderboard for select to authenticated using (true); -- points_log: read own or admin. create policy "points_log_select_own_or_admin" on public.points_log for select to authenticated using (profile_id = auth.uid() or public.is_admin()); -- ----------------------------------------------------------------------------- -- GRANTS -- The new Supabase CLI does NOT auto-expose new tables to the Data API roles, -- so grant explicitly. RLS still governs what each role can actually see. -- ----------------------------------------------------------------------------- grant usage on schema public to anon, authenticated, service_role; grant select on public.profiles, public.slots, public.sessions, public.preferences, public.connections, public.checkins, public.feedback, public.leaderboard, public.points_log to anon, authenticated, service_role; grant insert, update, delete on public.profiles, public.slots, public.sessions, public.preferences, public.connections, public.checkins, public.feedback, public.leaderboard, public.points_log to authenticated, service_role; grant execute on function public.is_admin() to authenticated; grant execute on function public.is_staff_or_admin() to authenticated; grant execute on function public.get_public_profiles() to authenticated; grant execute on function public.lanyard_lookup(text) to authenticated; grant execute on function public.set_preference(uuid) to authenticated; grant execute on function public.clear_preference(integer) to authenticated; grant execute on function public.create_connection_request(text) to authenticated; grant execute on function public.accept_connection(uuid) to authenticated; grant execute on function public.reject_connection(uuid) to authenticated; grant execute on function public.checkin_attendee(uuid, text) to authenticated; grant execute on function public.submit_feedback(uuid, integer, text) to authenticated; grant execute on function public.adjust_points(uuid, integer, text) to authenticated; grant execute on function public.get_agenda() to authenticated;