19 KiB
Points RPCs (Business Logic)
All mutations go through Postgres RPCs (security definer, transactional).
The app never writes to registrations.points, connections, checkins,
feedback, or leaderboard directly — it calls these functions. This is what
makes the points system race-free and prevents a client from, e.g., setting its
own points.
Source of truth:
supabase/migrations/20260824000000_redesign.sql.
Why RPCs?
security definer→ the function runs as the table owner and bypasses RLS, so it can update points and sync the leaderboard even though the calling user can't write those tables directly.- Transactional → each RPC does update points + insert the related row + re-sync the leaderboard in one transaction. Either all happen or none do.
- Idempotent where it matters → re-check-in and re-feedback are detected and never double-award.
- Event-scoped → points RPCs resolve the active event first. Speaker portal material RPCs instead authorize against the session's own event, including inactive events.
Points rules
| Action | Points | Awarded to |
|---|---|---|
| Checked into a session (by staff) | +10 | the attendee |
| Connection accepted | +5 each | both people |
| Connection accepted with a shared talk | +talk_networking_bonus each (per event, default 2, 0 = off) |
both people (category talk_networking) |
| Feedback — rating only | +5 | the attendee |
| Feedback — rating + comment | +10 | the attendee |
| Admin adjustment | any | the target (audited as admin) |
Internal helpers
_award_points(p_event_id, p_contact_email, p_delta, p_category)
The single place points change. In one transaction it:
update registrations set points = greatest(0, points + p_delta)(floored at 0) for the (event, contact),insert into points_log (event_id, contact_email, delta, category),- calls
_sync_leaderboard(p_event_id, p_contact_email).
_sync_leaderboard(p_event_id, p_contact_email)
Upserts the leaderboard row for that (event, contact) from registrations +
contacts (on conflict (event_id, contact_email) do update ...). This is what
makes the leaderboard a consistent, Realtime-friendly mirror. Staff are
excluded: if the contact's registration type is staff (or there is no
registration), the function deletes any existing leaderboard row instead of
inserting — so staff never appear on the board even if they hold points.
_recalc_event_aggregates(p_event_id)
Recomputes the events aggregate columns (num_sessions, num_speakers,
num_registrations, num_checked_in_registrations, avg_feedback). Called by
triggers and the feedback RPC.
Public read functions
| Function | Returns | Used for |
|---|---|---|
get_leaderboard() |
event_id, contact_email, full_name, points (active event, staff excluded, ordered by points) |
Leaderboard initial load + realtime re-fetch |
lanyard_lookup(p_qr_token) |
email, full_name, linkedin_url (null unless show_linkedin), show_email, registration_type |
Resolve a scanned QR (pre-login + connect) |
get_public_contacts() |
email, full_name, linkedin_url, show_email, registration_type (active-event registrants) |
Connections name/type lookups |
get_agenda() |
flat rows: slot fields + session fields + speakers (string_agg) |
Agenda + Home |
get_active_event() |
the active events row (or none) |
event name/dates/location |
get_talk_cohort(p_session_id) |
email, full_name, registration_type, qr_token of the other attendees checked into that session (staff excluded, self excluded) |
the Networking screen's "also attended" list |
All are security definer and expose only public columns (email is included
because contacts is keyed by email and is the identity; qr_token is never
exposed). lanyard_lookup / get_public_contacts respect the contact's
show_email / show_linkedin visibility toggles.
Mutation RPCs
set_preference(p_session_id) → preferences
Sets (or changes) the preferred session for the slot that p_session_id belongs
to. Deletes the caller's existing pick for that slot, then inserts the new one.
Enforces "one pick per slot".
clear_preference(p_slot_id) → void
Removes the caller's pick for a slot.
create_connection_request(p_target_qr) → connections
Creates a pending connection to the contact whose QR was scanned.
- Resolves the target by
qr_token; errors if not found or if it's yourself. - Idempotent: if the pair already has a connection (either direction) for the active event, returns the existing one instead of creating a duplicate.
accept_connection(p_connection_id) → (event_id, from_email, to_email, status, created_at, resolved_at, shared_talk)
Accepts an incoming request.
- Locks the row (
for update), verifies the caller is the recipient (to_email = current_email()) and the status is stillpending. - Sets
status = 'accepted',resolved_at = now(). - Awards +5 to both
from_emailandto_email(categoryconnection). - Talk networking bonus: computes whether the two parties share a
checked-in session (talk) — i.e. there is a session both were checked into
(
checkinsintersection). If they do and the event'stalk_networking_bonus > 0, it awards that bonus to each party (categorytalk_networking). Returnsshared_talk = truein that case so the app can show a "met at {talk}" note.- Idempotency: the function 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 — it reflects shared attendance at acceptance time.
- The bonus flows through
_award_points, so the leaderboard sync + staff exclusion are inherited automatically.
- Idempotency: the function is one-shot (row locked, status must be
reject_connection(p_connection_id) → connections
Same guards as accept, but sets status = 'rejected'. No points.
checkin_attendee(p_session_id, p_attendee_qr) → (checkin_id, attendee_email, attendee_name, points, already)
Staff checks an attendee into a session.
- Role check:
is_staff_or_admin()(i.e.is_admin()) or it raisesstaff or admin only. - Resolves the attendee by
qr_token. - Service-session guard: if the session's slot is a
service_session, it raisesservice sessions cannot be checked in(there's nothing to check into — everyone is in the room). insert into checkins ... on conflict (event_id, contact_email, session_id) do nothing returning id— if no row was inserted, the attendee was already checked in: setsalready = trueand awards no points.- Otherwise awards +10 to the attendee (category
checkin). - Returns the attendee's current total points.
Implementation note: the "already checked in" case is detected via the
ON CONFLICT ... DO NOTHING returning id(aNULLid means no-op), and the function uses a single finalreturn querywith flag variables — areturn queryinside anifblock would not terminate the function and would double-award.
welcome_checkin(p_attendee_qr) → (attendee_email, attendee_name, already)
Staff welcome check-in: marks an attendee present at the event (distinct
from checkin_attendee, which checks someone into a specific session).
- Role check:
is_staff_or_admin()or it raisesstaff or admin only. - Resolves the attendee by
qr_tokenfor the active event. - Sets
registrations.checked_in = true(no points — that's the session check-in's job). alreadyistrueif the attendee was already checked in to the event.
submit_feedback(p_session_id, p_rating, p_comment) → (feedback_id, points, earned)
Post-session feedback.
- Requires the caller to be checked in to that session (else raises).
- Validates
ratingis 1–5. earned= 10 if a non-empty comment, else 5.- Idempotent: if feedback already exists for (caller, session), it updates the rating/comment and awards 0 (already rewarded on first submission).
- Otherwise inserts and awards
earned(categoryfeedback). - Recalculates
sessions.average_feedback, updates theai_generated_feedbackstate machine, and recalcs the event aggregates.
adjust_points(p_contact_email, p_delta, p_reason) → void
Admin-only manual points adjustment (category admin) for the active event.
Used by the APPE Admin console to award prizes or correct mistakes. Goes through
_award_points, so it floors at 0, writes points_log, and re-syncs the
leaderboard.
reset_registration_qr_token(p_contact_email) → (email, qr_token)
Admin-only. Regenerates the lanyard QR token of a contact's registration for the active event (the token lives on the registration, not the contact).
- Requires the contact to have a registration for the active event.
- Generates a fresh
CVV-XXX-NNNNtoken and writes it toregistrations.qr_token. - Re-hashes it as the Auth password (
extensions.crypt(token, extensions.gen_salt('bf'))onauth.users.encrypted_password), so the old token stops working and the contact must re-scan with the new one. - Deletes the contact's existing
auth.sessions, forcing a re-login. - Returns the new token so the admin can print/show it as a QR code.
Implementation note: the function's output column is named
returns table (email, qr_token)), so any reference toauth.users.emailinside the body must be qualified (auth.users.email) — a bare
Implementation note: pgcrypto's
gen_salt/cryptlive in theextensionsschema (notpublic), so the function — whosesearch_pathis pinned topublic— must qualify them asextensions.gen_salt(...)/extensions.crypt(...). The function owner (postgres) can writeauth.usersandauth.sessions, which is what makes this possible.
upsert_contact(p_email, p_full_name, p_linkedin_url, p_is_admin) → contacts
Admin-only. Creates a contact if it doesn't exist or updates the existing
one. Contacts carry no QR token — the token is generated when a registration
is created. Ensures an auth.users row exists (with a placeholder password) so
the contact can log in once a registration token is issued. Returns the contact
row.
create_registration(p_contact_email, p_type) → registrations
Admin-only. Creates a registration for the active event (enforces the
sponsor-type rule). Generates a CVV-XXX-NNNN token on the registration and
syncs it as the Auth password, so a newly registered contact can log in
immediately.
set_registration_type(p_contact_email, p_type) → registrations
Admin-only. Changes a contact's registration type for the active event.
p_type is text and is cast to the registration_type enum on write.
evaluate_session_feedback(p_session_id) → sessions
Admin-only. The AI-feedback stub: sets ai_generated_feedback to a
placeholder string ("AI evaluation stub: N comment(s) received. (LLM integration
pending.)"). Real LLM integration is a later phase.
set_session_material(p_session_id, p_material_path) → sessions
Sets only a session's material_path, with a row lock. Requires authentication
and either admin access or an own assignment plus speaker or staff registration for the
session's event and a non-service slot. For non-admins, non-null paths must be an
existing uploaded materials object under sessions/<this session UUID>/<filename>.
NULL detaches material. Ownership/path failures use SQLSTATE 42501.
There is no active-event, date, check-in or points condition. Shared by Agenda and
the speaker portal.
Speaker Portal RPCs
Source: 20261006175631_speaker_portal.sql, with staff overlap.
get_my_speaker_sessions()returns own registered non-service talks across all events, ordered by slot date/time, event name, title and session ID. Rows containsession_id,title,description,room,material_path,event_id,event_name,event_start_date,event_end_date,is_active,slot_date,start_time,end_time. Ineligible authenticated users get[].owns_speaker_session(uuid)requires an explicit own talk assignment and a same-eventspeakerorstaffregistration, including registered Admin staff. Registration category remains unchanged; staff points/check-in exclusions remain intact.can_write_session_material(text)validates session object paths for Storage INSERT/UPDATE/DELETE; admins retain their existing management access.set_session_material(uuid, text)follows the mutation contract above and does not mark physical attendance or award points.
All four functions revoke PUBLIC/anon execution and grant authenticated/service_role execution. See RLS details, client lifecycle and regression tests.
Other RPCs
update_my_profile(p_linkedin_url, p_show_email, p_show_linkedin) → contacts
Self-service (any authenticated attendee). Lets a contact edit their own
profile from the Convivo app: the LinkedIn URL and the two visibility toggles
(show_email / show_linkedin).
- Scoped to
current_email()— a user can only ever update their own row. linkedin_urlis trimmed; an empty/blank value is stored asNULL.- The toggles default to
falsewhenNULLis passed. - Why an RPC? The
contactsRLSUPDATEpolicy is admin-only (contacts_admin_update), so an attendee cannot update their own row directly through PostgREST. Thissecurity definerfunction (ownerpostgres) bypasses that, but is deliberately limited to the three self-service columns — it cannot touchis_admin,password,external_id, etc. - Returns the updated contact row.
sync_sessionize_event(p_event_id, p_payload) → jsonb
Service-role only (the Sessionize sync sidecar — see sidecar.md).
Imports an event's Sessionize data in order: (1) speakers → contacts (matched by
email), (2) sessions (upserted by external_id), (3) the agenda (slots
find-or-created by date/start/end + session_speakers links). p_payload is
{ speakers: [{email, full_name, external_id?}], sessions: [{external_id, title, description?, room?, date, start_time, end_time, is_service_session?, speakers: [email,...]}] }.
- Guarded to the
service_rolecaller (JWT role claim); granted toservice_roleonly — the apps cannot call it. - Slots are typed from
is_service_session(service_sessionfor breaks/lunch/closing/plenums, elsesession) with a matching name ("Service Session" vs "Slot HH:MM–HH:MM"). - Idempotent: re-running updates in place (contacts by email, sessions by
external_id, slots by date/start/end). Speaker links are diffed (insert the new set, then delete only removed) so thesession_needs_speakertrigger never blocks a removal. - Service sessions: every registered staff member is linked as a speaker
(via
_assign_service_session_speakers) — a service session has no individual speaker, so the whole staff team "owns" it. - Linking a speaker fires
session_speakers_speaker_promote, which promotes an existing registration tospeaker. No registrations are created — the ticket sync does that (checkingsession_speakersby email). - Per-item failures are collected into
errors[](the run does not abort). Returns a JSONB summary (speakers_created/updated,sessions_created/updated,slots_created,speakers_linked,errors) and stampsevents.last_synced_at. - Writes a
sync_runsaudit row (see schema.md).
sync_sessionize_excel(p_event_id, p_payload) → jsonb
Service-role only (the Sessionize sync sidecar's Excel import path — see
sidecar.md). Imports the Sessionize "Sessions and speakers
(advanced)" .xlsx export (parsed by the sidecar, which carries the speaker
emails the public API lacks). Same shape as sync_sessionize_event plus
is_service_session per session and linkedin_url per speaker, and it runs one
extra step:
- Speakers → contacts (matched by email; also sets
linkedin_url). - Sessions + agenda — slots are typed from
is_service_session(service_sessionfor breaks/lunch/closing/plenums, elsesession), sessions upserted byexternal_id, speaker links diffed. Service sessions also get every registered staff member linked as a speaker (via_assign_service_session_speakers). - Speaker registrations — for every speaker, creates a
speakerregistration or updates an existingattendeeone tospeaker(on conflict (event_id, contact_email)). Never overridesstaff/sponsortickets. This is the "add the missing registrations for the speakers" step the API sync deliberately leaves to the ticket sync.
- Guarded to the
service_rolecaller; granted toservice_roleonly. - Idempotent: re-running updates in place (contacts by email, sessions by
external_id, slots by date/start/end, registrations by event+contact). - Per-item failures are collected into
errors[]. Returns a JSONB summary (speakers_created/updated,sessions_created/updated,slots_created,speakers_linked,registrations_created/updated,errors) and stampsevents.last_synced_at. - Writes a
sync_runsaudit row withsource = 'sessionize_excel'.
Role helper functions
| Function | Returns | Meaning |
|---|---|---|
current_email() |
text |
auth.jwt() ->> 'email' (the identity) |
is_admin() |
boolean |
current contact has is_admin = true |
is_staff_or_admin() |
boolean |
= is_admin() (staff is merged into admin) |
is_speaker_or_admin() |
boolean |
admin, or a speaker of a session in the active event (via session_speakers), or a contact whose registration type is speaker |
All are security definer so they can read contacts / registrations /
session_speakers inside RLS checks and RPC guards.
Internal helpers
| Function | Returns | Meaning |
|---|---|---|
_assign_service_session_speakers(p_session_id, p_event_id) |
integer |
Links every registered staff member of the event as a speaker of the given session (on conflict do nothing). Returns the number of rows affected. Called by both Sessionize sync RPCs for service_session sessions — a service session has no individual speaker, so the whole staff team "owns" it. |
Error handling
RPCs raise Postgres exceptions with human-readable messages (e.g. you cannot connect with yourself, staff or admin only, you must be checked in to this session to give feedback, not a speaker of this session, service sessions cannot be checked in). The frontend surfaces these via toasts — see
../frontend/api-client.md.