# 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`](../../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 | |---|---|---| | **Welcome (front-desk) check-in**, first time only | **+10** | the attendee | | 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`) | Only eligible registered participants earn points. Staff registrations and Admin contacts (`is_admin` or `@appe.at`) always have zero points and never rank, including when checked in, leaving feedback, accepting connections or receiving manual adjustments. Existing audit history is retained when a role changes. **That exclusion is deliberate and stays — but it is no longer silent.** It used to be invisible: a staff test check-in produced a bare `0` and looked like a broken feature. `_points_eligible` is now consulted by the callers that report outcomes, so every surface says why: - `checkin_attendee` / `welcome_checkin` / `preview_welcome_checkin` return `points_awarded`, and the scanner renders "Checked in · staff earn no points" instead of claiming "+10 pts · now 0". - The admin Registrations table shows "— no points" with a tooltip on the rows the predicate excludes (`canEarnPoints` in [../frontend/admin-app.md](../frontend/admin-app.md) mirrors the SQL exactly), and the Contacts points modal refuses to apply an adjustment to such a contact rather than letting `adjust_points` (which returns `void`) no-op quietly. ## Internal helpers ### `_points_eligible(p_event_id, p_contact_email)` → `boolean` The single source of truth for "may this person earn points": the contact must have a registration in **that event**, with `registrations.type <> 'staff'`, `contacts.is_admin = false` and an email not ending in `@appe.at`. `_award_points` uses it as a gate, and the outcome-reporting RPCs use it to tell the UI whether an award actually happened — both halves read the same predicate, so a screen can never promise points the database would refuse. There is no second copy of the rule anywhere else; the admin app's client-side mirror is commented to that effect. ### `_award_points(p_event_id, p_contact_email, p_delta, p_category)` The shared award path first locks the registration and checks eligibility. Missing registrations, staff and Admin contacts receive no award or new audit entry. Clients cannot call this helper directly. In one transaction it: 1. `update registrations set points = greatest(0, points + p_delta)` (floored at 0) for the (event, contact), 2. `insert into points_log (event_id, contact_email, delta, category)`, 3. synchronizes the leaderboard through the registration write trigger. ### `_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, Admins and missing registrations are excluded:** the function deletes existing excluded rows. Registration writes force excluded balances to zero; role/point changes, registration deletion, contact Admin promotion and name changes refresh rankings. The zero-points guard runs after the existing role-normalization triggers. `leaderboard` belongs to the `supabase_realtime` publication for live updates. ### `_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/Admins excluded**, ordered by points descending, name and email ascending) | 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 still `pending`. - Sets `status = 'accepted'`, `resolved_at = now()`. - **Awards +5 to both** `from_email` and `to_email` (category `connection`). - **Talk networking bonus:** computes whether the two parties share a checked-in session (talk) — i.e. there is a session both were checked into (`checkins` intersection). If they do **and** the event's `talk_networking_bonus > 0`, it awards that bonus to **each** party (category `talk_networking`). Returns `shared_talk = true` in 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. ### `reject_connection(p_connection_id)` → `connections` Same guards as accept, but sets `status = 'rejected'`. No points. ### Staff auto-connect (trigger, `20261020120000_staff_auto_connections.sql`) Every staff member is connected to **every other participant of the same event** without any user action — this is not an RPC: - The staff set equals the points-exempt set (`_points_eligible`): registration type `staff`, Admin contact, or an `@appe.at` address; everyone else is a "person". Only staff × person pairs are created — never staff × staff. - Rows are inserted as `status = 'accepted'`, `auto = true` by the trigger `registrations_autoconnect_staff` (on registration insert / type change) and by the idempotent backfill helper `_autoconnect_staff_event(event)`. - **No points are ever awarded:** these rows never pass through `accept_connection`/`_award_points`. - Existing pairs (including a manually `rejected` one) are never touched — the unique pair index makes every pass a no-op. - Scanning a staff lanyard behaves as already-connected: `create_connection_request`'s idempotency rule returns the existing `accepted` row and the app shows "You're connected!". - `auto = true` rows appear in the attendee's connections list but are excluded from the admin Dashboard feed and the Activity connections table. ### `checkin_attendee(p_session_id, p_attendee_qr)` → `(checkin_id, attendee_email, attendee_name, points, already, points_awarded)` Staff checks an attendee into a session. - **Role check:** `is_staff_or_admin()` (i.e. `is_admin()`) or it raises `staff or admin only`. - Resolves the attendee by `qr_token`. - **Front-desk gate:** when the attendee's `registrations.checked_in` is not `true`, it raises `This attendee needs to be checked in at the front desk first.` Nobody can be checked into a session before the **welcome** check-in at the front desk has marked them present at the event. The scanner shows this as its own sheet instead of a generic error (see [../frontend/screens.md](../frontend/screens.md)). `checkin_attendee` also stopped setting `checked_in = true` as a side effect — the welcome check-in (or an admin's Registrations toggle) is now the only way to earn it. - **Service-session guard:** if the session's slot is a `service_session`, it raises `service 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**: sets `already = true` and awards **no points**. - Otherwise awards **+10** to the attendee (category `checkin`). - Returns the attendee's current total points, and `points_awarded` — whether that +10 actually landed. It is `false` for someone `_points_eligible` excludes, which is the only reason a fresh check-in pays nothing. Without it the scanner had to render "+10 pts · now 0" for a staff badge scan. > **Implementation note:** the "already checked in" case is detected via the > `ON CONFLICT ... DO NOTHING returning id` (a `NULL` id means no-op), and the > function uses a **single final `return query`** with flag variables — a > `return query` inside an `if` block would *not* terminate the function and would > double-award. ### `welcome_checkin(p_attendee_qr)` → `(attendee_email, attendee_name, already, points, points_awarded)` 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 raises `staff or admin only`. - Resolves the attendee by `qr_token` for the active event. - Sets `registrations.checked_in = true` and, on a **first** check-in, awards **+10** (category `checkin`) through `_points_eligible` + `_award_points`. The front desk is a real check-in, so it pays the same as a session scan; before this it paid nothing, which made "check me in" award different amounts depending on *which* check-in a person got. It is once-per-person because the `checked_in` flag already is, so repeating a welcome cannot farm points. - `already` is `true` if the attendee was already checked in to the event; in that case nothing is awarded and `points` is the unchanged total. - `points_awarded` says whether the +10 landed (false for excluded staff/Admin), so the result sheet can say "Checked in · staff earn no points" rather than claiming points that were never written. - On a **first** check-in (and only when the event has a badge layout), enqueues `events.badge_copies` identical `badge_print` jobs in the same transaction — the Pi worker prints exactly one label per job, so N jobs = N labels (see [printing.md](printing.md)). The value is clamped to `1..4` inside the function, so a bad row can never flood the queue. A re-check-in (`already`) enqueues nothing. Manual reprint (`enqueue_badge_print`) still prints **one** label. ### `preview_welcome_checkin(p_attendee_qr)` → `(attendee_email, attendee_name, already, will_print, copies, points_awarded)` Read-only preview shown by the staff scanner **before** a welcome check-in is committed, so the confirmation popup can name the attendee and be honest about printing. - **Role check:** `is_staff_or_admin()` or it raises `staff or admin only` (same guard as `welcome_checkin`). - Resolves the attendee by `qr_token` for the active event; raises `no attendee found for that QR code` otherwise. - `will_print` is `true` only for a genuine first check-in **and** when the event has a badge layout with elements — exactly the condition under which `welcome_checkin` enqueues a job. - `copies` is the number of labels a confirm would queue — the same clamp `welcome_checkin` applies, and `0` when nothing would print. The popup uses it to say "print their badge 3 times" instead of a fixed "this person's label", so it can never over- or under-promise. - Checks nobody in and enqueues nothing; it is a pure lookup. - `points_awarded` predicts the confirm's outcome — `true` only for a genuine first check-in by someone `_points_eligible`. The popup uses it to promise "Checking in awards +10 points" only when it is true, and to say "This person does not earn points (staff or organiser)" otherwise. ### `merge_tickets(p_source_id, p_target_id)` -> `jsonb` Admin-only atomic merge of an imported, QR-less speaker/staff registration into a purchased Pretix registration in the same event. The destination must have a nonempty QR token and Pretix external ID. The source must have `import_source = 'sessionize'`. New Excel imports record this explicitly; legacy QR-less speaker/staff rows with imported contact IDs and no ticket external ID are backfilled as Sessionize imports. Locks event, registrations, contacts and session assignments. Inserts destination speaker links before removing source links, preserving the last-speaker invariant. Staff takes precedence over speaker; a destination sponsor registration adopts the transferred role while its separate sponsor record remains intact. Destination QR, email, points and attendance stay unchanged. Deletes only the source registration and its event leaderboard mirror, never the contact/Auth account or another event. Existing attendee activity on the source must be reconciled first; the RPC rejects it rather than losing or duplicating history. Self-merges and merge chains fail. The admin-readable, RLS-protected `ticket_merges` table retains an event-scoped source-to-destination mapping and actor/time audit. Excel and API speaker imports resolve that mapping, and later Pretix role updates preserve the merged role. Returns source/destination registration IDs, destination email, role and the count of transferred session assignments. There is no implicit check-in or points award. Event registration/check-in aggregates now count only nonblank QR-bearing rows; imported unticketed rows remain visible in Admin but do not increase ticket totals. ### Assigned Speaker Role Registration writes resolve `attendee` to `speaker` whenever the same email has an assignment to a regular `session` in that registration's event. This applies to Pretix ticket inserts/updates, Excel imports and direct Admin changes, so a regular purchased ticket cannot downgrade an assigned speaker on the next sync. Assignments added or updated after ticket import also promote the registration. Staff/sponsor roles retain their existing precedence; service-session links and links in other events do not promote attendees. Unassigned attendees remain attendees. The migration reconciles existing assigned attendees without changing QR tokens, ticket identifiers, attendance, points or session links. Assignments use exact contact email, not fuzzy name matches; different emails require the explicit ticket merge workflow above. ### `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 `rating` is 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` (category `feedback`). - Recalculates `sessions.average_feedback`, updates the `ai_generated_feedback` state machine, and recalcs the event aggregates. ### `submit_event_feedback(p_rating, p_comment)` → `(feedback_id, points, earned)` Event-level feedback ("Rate this event" from Home), one row per (event, contact) in `event_feedback`. - Requires the caller to be **registered** for the active event; `rating` 1–5. - **First submission earns +5** (category `feedback`, `_points_eligible` gate — staff / Admin / `@appe.at` earn nothing). - **Idempotent:** re-submitting upserts the row and earns **0** (an edit of an already-rewarded answer never pays twice). - `get_my_event_feedback()` returns the caller's existing answer for pre-fill. - `20261020130000_event_feedback_points.sql` added the award + the `earned` response column (drop/recreate — the return type changed; ACL restored). ### `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-NNNN` token and writes it to `registrations.qr_token`. - **Re-hashes it as the Auth password** (`extensions.crypt(token, extensions.gen_salt('bf'))` on `auth.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 `email` > (`returns table (email, qr_token)`), so any reference to `auth.users.email` > inside the body must be **qualified** (`auth.users.email`) — a bare `email` > is ambiguous between the output column and the table column. > **Implementation note:** pgcrypto's `gen_salt` / `crypt` live in the > `extensions` schema (not `public`), so the function — whose `search_path` is > pinned to `public` — must qualify them as `extensions.gen_salt(...)` / > `extensions.crypt(...)`. The function owner (`postgres`) can write > `auth.users` and `auth.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` **Deprecated stub.** Migration `20261011163332_feedback_ai_summaries` revokes client execution. Admin now uses the authenticated sidecar for real manual event and session summaries, stored separately from `sessions.ai_generated_feedback`. See [Feedback AI summaries](./feedback-ai.md). ### `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//`. `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](../frontend/screens.md#speaker-portal). ### `delete_event_schedule(p_event_id)` → `jsonb` **Admin-only.** Deletes the slots and sessions for exactly one event in a single transaction. It locks the event plus that event's schedule rows, validates that sessions and dependent `preferences` / `checkins` / `feedback` rows do not cross event boundaries, then deletes `sessions` and `slots` for `p_event_id`. FK cascades remove `session_speakers`, `preferences`, `checkins` and `feedback`. The event row, contacts, registrations, sponsors, connections, points, leaderboard rows and other events are preserved. Session `material_path` values disappear with the deleted session rows, but Storage objects in the `materials` bucket are not physically purged. The function is `security definer` with an empty `search_path`, requires both `auth.uid()` and `public.is_admin()`, revokes execution from `PUBLIC` / `anon` / `authenticated`, then grants execution back only to `authenticated`. It returns counts for deleted slots, sessions and dependent rows plus the number of material paths left unpurged. It does not coordinate with Sessionize/Pretix sync; a concurrent or later import can repopulate the event schedule. ## Speaker Portal RPCs Source: [20261006175631_speaker_portal.sql](../../supabase/migrations/20261006175631_speaker_portal.sql), with [staff overlap](../../supabase/migrations/20261007153957_speaker_portal_staff_overlap.sql). - `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 contain `session_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-event `speaker` or `staff` registration, 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](./rls.md#speaker-portal-authorization), [client lifecycle](../frontend/api-client.md#speaker-portal) and [regression tests](./tests.md#speaker-portal). ## 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_url` is trimmed; an empty/blank value is stored as `NULL`. - The toggles default to `false` when `NULL` is passed. - **Why an RPC?** The `contacts` RLS `UPDATE` policy is **admin-only** (`contacts_admin_update`), so an attendee cannot update their own row directly through PostgREST. This `security definer` function (owner `postgres`) bypasses that, but is deliberately limited to the three self-service columns — it cannot touch `is_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](./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_role` caller (JWT role claim); granted to `service_role` only — the apps cannot call it. - **Slots are typed from `is_service_session`** (`service_session` for breaks/lunch/closing/plenums, else `session`) 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 the `session_needs_speaker` trigger 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 to `speaker`. **No registrations are created** — the ticket sync does that (checking `session_speakers` by 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 stamps `events.last_synced_at`. - Writes a `sync_runs` audit row (see [schema.md](./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](./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: 1. **Speakers → contacts** (matched by email; also sets `linkedin_url`). 2. **Sessions + agenda** — slots are typed from `is_service_session` (`service_session` for breaks/lunch/closing/plenums, else `session`), sessions upserted by `external_id`, speaker links diffed. **Service sessions** also get every registered **staff** member linked as a speaker (via `_assign_service_session_speakers`). 3. **Speaker registrations** — for every speaker, creates a `speaker` registration or updates an existing `attendee` one to `speaker` (`on conflict (event_id, contact_email)`). **Never overrides `staff` / `sponsor`** tickets. This is the "add the missing registrations for the speakers" step the API sync deliberately leaves to the ticket sync. - Guarded to the `service_role` caller; granted to `service_role` only. - **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 stamps `events.last_synced_at`. - Writes a `sync_runs` audit row with `source = '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. | ## Raffle Source: [20261015180640_raffle.sql](../../supabase/migrations/20261015180640_raffle.sql). The admin **Raffle** view draws eligible attendees one at a time for the active event. Winner selection is authoritative **server-side** (random), so the client roulette animation only has to decelerate onto the returned name. - `get_raffle_pool()` → `contact_email, full_name, points` — the eligible attendees: non-staff, non-Admin (`is_admin` or `@appe.at`), **not** in the leaderboard **top 3** (`get_leaderboard() limit 3`), and **not** already drawn in the current run. Returns `[]` for non-admins (guarded by `is_admin()`). - `draw_raffle_winner()` → `contact_email, full_name, points, draw_number` — **admin-only.** Picks one random eligible attendee, records them in `raffle_draws` with the next sequential `draw_number`, and returns the winner. Raises `No eligible attendees left to draw` when the pool is empty. - `reset_raffle()` → `void` — **admin-only.** Deletes the current run's winners for the active event so a new run can begin. The `raffle_draws` table is keyed by `(event_id, contact_email)` (so an attendee can win at most once per run), cascades on event/contact deletion, and is admin-readable via RLS. All three functions are `security definer` with an empty `search_path`, revoke execution from `PUBLIC` / `anon`, and grant it back only to `authenticated` (the admin check is enforced inside each function). ## Badge editor Source: [20261015194531_badge_editor.sql](../../supabase/migrations/20261015194531_badge_editor.sql). The admin **Badges** view is a per-event WYSIWYG badge / PDF layout editor (modelled on pretix's "PDF Editor / Badge layout"). Each event owns one or more named **layouts** in `badge_layouts`: a page size in millimetres plus an ordered `elements` JSON array (text boxes, QR codes, images) with mm-based geometry, so the on-screen canvas maps 1:1 to print. Text/QR elements bind to attendee fields (`attendee_name`, `email`, `ticket_type`, `qr_token`, `event_name`, `company`, …) and are previewed against a real sample registration. The `company` field reads `events.company` (the Pretix organizer name — see [sidecar.md](./sidecar.md#pretix-sync)). - `save_badge_layout(p_event_id, p_name, p_page_width_mm, p_page_height_mm, p_elements, p_is_default)` → `badge_layouts` row — **admin-only.** Upserts the layout matched on `(event_id, name)`. When `p_is_default` is true, every other layout for the event is demoted first, so the "one default per event" invariant holds transactionally. Rejects blank names and non-array `elements`. - `set_default_badge_layout(p_id)` → `void` — **admin-only.** Promotes one layout to the event's default and demotes the previous one. - `delete_badge_layout(p_id)` → `void` — **admin-only.** Removes a layout; the default may not be deleted while other layouts exist (a usable default must remain). `badge_layouts` cascades on event deletion, is admin-readable via RLS (`badge_layouts_admin_read`), and has a partial unique index enforcing a single default per event. All three functions are `security definer` with an empty `search_path`, revoke execution from `PUBLIC` / `anon`, and grant it back only to `authenticated` (the admin check is enforced inside each function). ## Badge printing Source: [20261018170000_badge_print_queue.sql](../../supabase/migrations/20261018170000_badge_print_queue.sql). The full contract — payload, state derivation, token security model, retry / dead-letter semantics — lives in [printing.md](./printing.md#4-rpcs); this is the function inventory. **Admin RPCs** (`security definer`, empty `search_path`, `is_admin()` inside, granted to `authenticated` only): - `enqueue_badge_print(p_registration_id)` → `bigint` — queue one attendee's badge for printing (`kind = reprint`); raises when the event has no usable layout. - `create_print_station(p_name)` → `(id, token)` — register a printer station; the `cvp_…` token is returned **once**, only its SHA-256 digest is stored. - `rename_print_station(p_id, p_name)` → `void` — rename a station (also revoked ones). - `revoke_print_station(p_id)` → `void` — retire a station; its token fails immediately. - `get_print_overview()` → `jsonb` — stations with a derived state, queue counters, the last 20 completed jobs and the dead letters. - `requeue_dead_badge_print(p_msg_id)` → `bigint` / `discard_dead_badge_print(p_msg_id)` → `void` — dead-letter triage. **Printer RPCs** (granted to `anon` — the Pi has no user session; gated by the station token, invalid/revoked raises SQLSTATE `28000`): - `printer_claim_badge_job(p_token, p_vt, p_wait_seconds)` → `(msg_id, read_ct, payload)` — long-poll claim; the wait is clamped to **2 s** because the `anon` role has a 3 s `statement_timeout`; a message read more than 3 times is dead-lettered instead of returned. - `printer_complete_badge_job(p_token, p_msg_id)` → `boolean` — archive the job. - `printer_fail_badge_job(p_token, p_msg_id, p_error, p_retryable)` → `text` — `retry` (backoff via `set_vt`) while attempts remain, else `dead_letter`. - `printer_heartbeat(p_token, p_status)` → `jsonb` — liveness + status beacon; returns the station's current `name` (the worker adopts renames from it). **Changed existing RPC:** `welcome_checkin` re-creates with one addition — on a genuine **first** check-in it enqueues the badge job in the same transaction when the event has a layout with elements (see [welcome_checkin](#welcome_checkinp_attendee_qr--attendee_email-attendee_name-already). ## Front-desk gate and badge copies Source of truth: [`supabase/migrations/20261019110000_front_desk_gate_and_badge_copies.sql`](../../supabase/migrations/20261019110000_front_desk_gate_and_badge_copies.sql) (see [release record](../releases/2026-10-19.md)). - `events.badge_copies` — new `integer not null default 1` with `check (badge_copies between 1 and 4)`. Admins edit it from **Settings → Badge printing** for the active event, and when creating/editing an event (see [../frontend/admin-app.md](../frontend/admin-app.md)). - `checkin_attendee` re-creates: adds the **front-desk gate** and drops the `checked_in = true` side effect. - `welcome_checkin` re-creates: enqueues `badge_copies` jobs instead of one. - `preview_welcome_checkin` **drops and re-creates** (the return type gained `copies`, and Postgres cannot `create or replace` across a signature change); grants are re-applied in the same migration. `checkins` has no `INSERT` policy, so `checkin_attendee` is the only write path for session check-ins — the gate cannot be bypassed from the API. ## 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](../frontend/api-client.md).