Files
Convivo/docs/backend/rpcs.md
T
Lago 698bf13551 Staff exclusions + contact-password auth sync
- contacts.password now auto-syncs to auth.users.encrypted_password via
  trg_contact_password_sync, so setting a password on the contact row in the
  Supabase UI makes it work with signInWithPassword immediately (fixes staff
  like Bruno not being able to log in with a UI-set password). One-time
  reconciliation in the migration.
- Staff excluded from the leaderboard: _sync_leaderboard skips/removes staff
  rows, get_leaderboard() filters type='staff', seed no longer inserts staff.
  Affects the attendee Leaderboard and the admin Dashboard 'Top points'.
- Home/Agenda/Profile identical for all roles: Home quick-action always
  'Scan & connect' (no 'Check-in' relabel), footer role badge removed, tab
  label always 'Scan' (staff keep check-in via the Scan screen mode toggle).
- Profile: removed the duplicate Staff pill (type pill already shows Staff).
- Agenda session sheet: 'Download material' moved to the bottom of the button
  stack with spacing.
- Docs updated (schema, rpcs, seed, screens, architecture, next-steps).
2026-08-23 18:27:01 +02:00

231 lines
13 KiB
Markdown
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.
# 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** → every RPC resolves the **active event** first and scopes all
reads/writes to it.
## Points rules
| Action | Points | Awarded to |
|---|---|---|
| Checked into a session (by staff) | **+10** | the attendee |
| Connection accepted | **+5 each** | both people |
| 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:
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. 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 |
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)` → `connections`
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`).
### `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 raises
`staff or admin only`.
- Resolves the attendee by `qr_token`.
- `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.
> **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.
### `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.
### `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.
### `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 a session's `material_path`. Allowed for **admins and for any speaker of the
session** (the `sessions` table is admin-write only, so speakers need this
security-definer RPC to attach their uploaded material). The attendee app calls
this after uploading a file to the `materials` bucket.
### `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.
## Interface sync RPCs (service-role-only)
Two additional `security definer` RPCs import external data. They are **not**
called by the apps — they are called by the `sync-trigger` Edge Function using the
**service-role key**, and each guards with
`if coalesce(auth.jwt() ->> 'role', '') <> 'service_role' then raise exception`.
Full details (payloads, mapping, the Edge Function, the mock API) live in
[interfaces.md](./interfaces.md).
| Function | Input | Effect |
|---|---|---|
| `sync_pretix_attendees(p_attendees jsonb)` | array of `{email, full_name, ticket_type, qr_token?, linkedin_url?, external_id?}` | Upserts `contacts` (by email) + `registrations` (by event+contact); creates the `auth.users` row if missing; auto-creates a `sponsors` row for `sponsor` ticket types; records a `sync_runs` row. Returns `{created, updated, skipped, errors[]}`. |
| `sync_sessionize_sessions(p_sessions jsonb)` | array of `{external_id, title, description?, room?, capacity?, date, start_time, end_time, speakers[]}` | Find-or-creates a `slots` row per time window, upserts `sessions` by `external_id`, upserts speaker `contacts` + `session_speakers`; records a `sync_runs` row. Returns `{slots_created, sessions_created, sessions_updated, speakers_linked, errors[]}`. |
Both are **idempotent** — re-running a sync updates existing rows instead of
duplicating them (keyed on email / `external_id`).
## 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.
## 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`). The frontend
surfaces these via toasts — see
[../frontend/api-client.md](../frontend/api-client.md).