Files
Convivo/docs/backend/rpcs.md
T
Lago cf70f39903 Phase 2: Admin console (admin.appe.at)
A desktop-first React app for organizers, guarded to the admin role.

Backend (supabase/migrations/20260823000000_admin_app.sql):
- Admin-only SELECT policies on preferences, connections, feedback
- reset_qr_token RPC: regenerates a lanyard token, re-hashes it as the
  Auth password (old token stops working), and clears the attendee's
  sessions to force re-login

App (apps/admin, port 3001):
- Login: same QR+email flow, but non-admin sessions are rejected
- Dashboard: live stats + top points + recent activity
- Attendees: search, edit name/company/role, reset QR, adjust points
- Schedule: manage slots + sessions (create/edit/delete)
- Activity: check-ins / connections / feedback tables
- Same-origin proxy (Vite dev / nginx in Docker), same design tokens

Docker + scripts:
- convivo-admin service in docker-compose.yml (:3001)
- admin:dev / admin:build root scripts
- fixed db:reset script (supabase reset -> supabase db reset)

Docs: new frontend/admin-app.md; updated architecture, rls, rpcs,
docker, next-steps, and READMEs.

Verified: build clean, all views + flows browser-tested, Docker build +
proxy + login + admin guard confirmed. DB reset to clean seed.
2026-08-22 19:47:22 +02:00

146 lines
6.8 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 `profiles.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/20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.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.
## 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_profile_id, p_delta, p_category)`
The single place points change. In one transaction it:
1. `update profiles set points = greatest(0, points + p_delta)` (floored at 0),
2. `insert into points_log (profile_id, delta, category)`,
3. calls `_sync_leaderboard(p_profile_id)`.
### `_sync_leaderboard(p_profile_id)`
Upserts the `leaderboard` row for that profile from `profiles`
(`on conflict (profile_id) do update ...`). This is what makes the leaderboard a
consistent, Realtime-friendly mirror.
## Public read functions
| Function | Returns | Used for |
|---|---|---|
| `get_public_profiles()` | `id, full_name, company, role, points` (ordered by points) | Leaderboard initial load, id→name lookups |
| `lanyard_lookup(p_qr_token)` | `id, full_name, company, role` | Resolve a scanned QR (pre-login + connect) |
| `get_agenda()` | slots with their sessions (flat rows) | Agenda + Home |
All three are `security definer` and expose **only public columns** (no email, no
`qr_token`).
## 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 attendee 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), 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_id = auth.uid()`) and the status is still `pending`.
- Sets `status = 'accepted'`, `resolved_at = now()`.
- **Awards +5 to both** `from_id` and `to_id` (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_id, attendee_name, points, already)`
Staff checks an attendee into a session.
- **Role check:** `is_staff_or_admin()` or it raises `staff or admin only`.
- Resolves the attendee by `qr_token`.
- `insert into checkins ... on conflict (profile_id, 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`).
### `adjust_points(p_profile_id, p_delta, p_reason)` → `void`
**Admin-only** manual points adjustment (category `admin`). Used by the Admin
console (Phase 2) to award prizes or correct mistakes. Goes through
`_award_points`, so it floors at 0, writes `points_log`, and re-syncs the
leaderboard.
### `reset_qr_token(p_profile_id)` → `(profile_id, qr_token)`
**Admin-only.** Regenerates an attendee's lanyard QR token.
- Generates a fresh `CVV-XXX-NNNN` token and writes it to `profiles.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
attendee must re-scan with the new one.
- **Deletes the attendee'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:** 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.
Source of truth for this RPC:
[`supabase/migrations/20260823000000_admin_app.sql`](../../supabase/migrations/20260823000000_admin_app.sql).
## Role helper functions
| Function | Returns | Meaning |
|---|---|---|
| `is_admin()` | `boolean` | current user's profile has `role = 'admin'` |
| `is_staff_or_admin()` | `boolean` | current user's profile has `role in ('staff','admin')` |
Both are `security definer` so they can read `profiles` 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`). The frontend surfaces these via toasts — see
[../frontend/api-client.md](../frontend/api-client.md).