Existing-sponsor link + remove Interfaces (Pretix/Sessionize)

- Sponsor lookup popup can now link an existing sponsor (dropdown + pre-fill)
  or create a new one; save upserts the sponsor linked to the contact and sets
  the registration type to sponsor.
- Remove the Interfaces feature end-to-end: admin nav button + Sync view, sync
  API helpers + SyncRun type, sync-trigger Edge Function, mock-api + its
  docker-compose service, and a migration dropping the sync RPCs, helpers, and
  sync_runs table.
- Update docs (architecture, backend, frontend, README, roadmap, next-steps).

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
This commit is contained in:
committed 2026-08-24 09:11:25 +02:00
1 parent ffb270c140
commit 24909cf8ab
27 files changed
+147 -1150

No files matched your search

+1 -7
View File
@@ -10,7 +10,6 @@ Postgres. This folder documents that core.
| [schema.md](./schema.md) | All 14 tables, columns, constraints, indexes |
| [rpcs.md](./rpcs.md) | The transactional points RPCs (the business logic) |
| [rls.md](./rls.md) | Row Level Security policies + which key the app uses |
| [interfaces.md](./interfaces.md) | Pretix + Sessionize sync (RPCs, `sync-trigger` Edge Function, mock API) |
| [seed.md](./seed.md) | Seed data + the demo accounts |
| [docker.md](./docker.md) | Docker: the app image + root compose (how the core + app run together) |
@@ -20,7 +19,6 @@ Postgres. This folder documents that core.
Postgres 17 ── schema (14 tables, multi-event model)
── RLS (who can read/write what)
── RPCs (security definer, transactional points logic)
── sync RPCs (service-role-only Pretix/Sessionize import)
── seed (demo data)
```
@@ -29,10 +27,7 @@ Postgres 17 ── schema (14 tables, multi-event model)
rules.
- **RLS is the security boundary.** The app uses the **anon key + the user's
session JWT**; RLS decides what that user may see and do. The service-role key
is never shipped to the app. See [rls.md](./rls.md). The one exception is the
**interface sync RPCs**, which are `service_role`-only and are called by the
`sync-trigger` Edge Function (which holds the service-role key server-side).
See [interfaces.md](./interfaces.md).
is never shipped to the app. See [rls.md](./rls.md).
- **Points are transactional.** Each RPC updates points, inserts the related row,
and re-syncs the `leaderboard` mirror in **one transaction**, so the leaderboard
is always consistent and duplicate actions never double-award. See [rpcs.md](./rpcs.md).
@@ -40,7 +35,6 @@ Postgres 17 ── schema (14 tables, multi-event model)
## Source of truth
- Schema + RPCs + RLS (the Redesign, **current**): [`supabase/migrations/20260824000000_redesign.sql`](../../supabase/migrations/20260824000000_redesign.sql)
- Interfaces (Pretix + Sessionize sync): [`supabase/migrations/20260825000000_interfaces.sql`](../../supabase/migrations/20260825000000_interfaces.sql) + [`supabase/functions/sync-trigger/`](../../supabase/functions/sync-trigger/)
- Earlier migrations (still applied, then replaced by the Redesign):
[`20260822000000_init.sql`](../../supabase/migrations/20260822000000_init.sql) and
[`20260823000000_admin_app.sql`](../../supabase/migrations/20260823000000_admin_app.sql)
-209
View File
@@ -1,209 +0,0 @@
# Interfaces — Pretix + Sessionize sync (Phase 7 + 8)
Convivo can pull **real** data from the two systems that run a conference:
- **Pretix** — ticket sales → `contacts` + `registrations` (with generated QR
tokens).
- **Sessionize** — the agenda → `slots` + `sessions` + `session_speakers`.
This replaces the hand-written seed with live event data. The sync is
**idempotent** (safe to re-run) and **audited** (every run is recorded).
> **Local testing:** a mock Pretix/Sessionize API (`interfaces/mock-api/`) serves
> the same response shapes as the real APIs, so the whole pipeline is testable
> end-to-end without real credentials. See [Testing](#testing-with-the-mock-api).
## Architecture
```mermaid
flowchart LR
subgraph Admin["APPE Admin (:3001)"]
UI["Interfaces view<br/>Sync now / Sync all / Export QR CSV"]
end
subgraph Core["Supabase core"]
K["Kong :54321"]
EF["Edge Function<br/>sync-trigger"]
PG[("Postgres<br/>sync RPCs + sync_runs")]
end
P[("Pretix API")]
S[("Sessionize API")]
M[("mock-api :54330<br/>(local fixtures)")]
UI -->|"POST /functions/v1/sync-trigger<br/>(admin JWT)"| K
K --> EF
EF -->|"GET /pretix/attendees"| P
EF -->|"GET /sessionize/sessions"| S
EF -.->|"local: same paths"| M
EF -->|"service-role RPC"| PG
PG --> PG
```
The **Edge Function** is the only component that talks to the external APIs and
holds the **service-role key**. The apps never do.
## Components
| Piece | Where | Role |
|---|---|---|
| `sync-trigger` Edge Function | `supabase/functions/sync-trigger/index.ts` | Auth (admin/cron), fetch + normalize external data, call the sync RPCs |
| `sync_pretix_attendees(jsonb)` | migration `20260825000000_interfaces.sql` | Upsert contacts + registrations (+ auth users) |
| `sync_sessionize_sessions(jsonb)` | same migration | Upsert slots + sessions + speakers |
| `sync_runs` table | same migration | Audit trail of every run |
| `mock-api` service | `interfaces/mock-api/` | Local Pretix/Sessionize stand-in (Docker, :54330) |
| Interfaces view | `apps/admin/src/views/Sync.tsx` | Trigger syncs, show results + run history, export QR CSV |
## The Edge Function (`sync-trigger`)
**Trigger:** `POST /functions/v1/sync-trigger` with body `{ "source": "pretix" | "sessionize" | "both" }`.
**Auth** (either):
- A valid **admin** JWT in the `Authorization` header — the APPE Admin app
passes its session token. The function verifies it by calling the `is_admin()`
RPC with that token.
- A matching `x-cron-secret` header == `CRON_SECRET` — for scheduled runs.
**Flow:**
1. Verify the caller (admin or cron).
2. For each requested source, `fetch` the external API and **normalize** the
response into the shape the sync RPC expects.
3. Call the service-role sync RPC via PostgREST
(`${SUPABASE_URL}/rest/v1/rpc/<fn>`, `apikey` + `Authorization` = service-role key).
4. Return a JSON summary (`{ ok, triggered_by, results, errors }`).
**Config (env, all optional — defaults point at the local mock):**
| Var | Default | Purpose |
|---|---|---|
| `PRETIX_BASE_URL` | `http://mock-api:54330` | Pretix API base |
| `PRETIX_API_TOKEN` | — | Pretix org/event API token |
| `SESSIONIZE_BASE_URL` | `http://mock-api:54330` | Sessionize API base |
| `SESSIONIZE_API_KEY` | — | Sessionize API key |
| `CRON_SECRET` | — | Shared secret for scheduled triggers |
> **Local note:** the local edge runtime bundles functions at `supabase start`
> time, so after adding/editing a function run `npx supabase stop && npx
> supabase start` to register it.
## The sync RPCs (service-role only)
Both RPCs are `security definer` and **guarded to the service-role caller**
(checked via the JWT `role` claim — `session_user` is the owner inside a definer
function). They can write to `auth.users` and bypass RLS, but **only** the Edge
Function (which holds the service-role key) can call them. The apps
(`anon`/`authenticated`) get `service_role only`.
### `sync_pretix_attendees(p_attendees jsonb)`
Input: a JSON array of
`{ email, full_name, ticket_type, qr_token?, linkedin_url?, external_id? }`.
For each item:
- **Upsert the contact** by `email` (no token on the contact).
- **Map the ticket type** to a registration type via `_map_ticket_type`
(case-insensitive substring: `speaker` / `staff` / `sponsor`, else `attendee`).
- **Auto-create a sponsor row** if the type is `sponsor` (the sponsor rule
requires a sponsor lookup).
- **Upsert the registration** for the active event (by contact). The **QR token
lives on the registration**: it keeps the existing token unless a new one is
supplied (so a re-sync never invalidates a lanyard), and **generates a token**
(`CVV-XXX-NNNN`) for new ticket holders (Pretix doesn't always provide one) so
they can log in.
- **Ensure the auth user** exists and **sync the token as the Auth password**
(QR token = password).
Returns `{ created, updated, skipped, errors[] }`.
### `sync_sessionize_sessions(p_sessions jsonb)`
Input: a JSON array of
`{ external_id, title, description?, room?, capacity?, date, start_time, end_time,
speakers: [{ email, full_name }] }`.
For each item:
- **Find or create the slot** by `(event, date, start, end)` (new slots get an
id from the `slots_id_seq` sequence).
- **Upsert the session** by `external_id` (partial unique index).
- **Link speakers** — upsert each speaker as a contact (+ auth user) and insert
into `session_speakers` (idempotent).
Returns `{ slots_created, sessions_created, sessions_updated, speakers_linked, errors[] }`.
### Idempotency
External ids are stored on `contacts.external_id`, `registrations.external_id`,
and `sessions.external_id` (each with a partial unique index `WHERE external_id
IS NOT NULL`). Re-running a sync **updates in place** instead of duplicating —
verified: a second run reports `0 created, N updated`.
### `sync_runs` (audit)
Every run inserts a row: `source`, `started_at`, `finished_at`, `created`,
`updated`, `skipped`, `error`, `triggered_by`. RLS: **admin-only** read. The
Interfaces view shows the last 8 runs.
## Data mapping
| Pretix field | → Convivo |
|---|---|
| `attendee_email` | `contacts.email` (PK) |
| `attendee_name` | `contacts.full_name` |
| `ticket_type` | `registrations.type` (via `_map_ticket_type`) |
| `order_code` | `contacts.external_id` + `registrations.external_id` |
| `qr_token` / *(generated)* | `registrations.qr_token` (Pretix per-ticket, or generated for new holders) |
| Sessionize field | → Convivo |
|---|---|
| `id` | `sessions.external_id` |
| `title` / `description` / `room` / `capacity` | `sessions.*` |
| `start_time` / `end_time` (ISO) | slot `slot_date` + `start_time`/`end_time` (slot matched by date+time) |
| `speakers[].email` / `name` | `contacts` + `session_speakers` |
## Testing with the mock API
The `mock-api` Docker service (`interfaces/mock-api/`) is a dependency-free Node
server that serves the real API shapes from `fixtures/`:
- `GET /pretix/attendees` → 3 ticket holders (2 new emails + 1 existing, to test
create vs update).
- `GET /sessionize/sessions` → 2 sessions (new ids, new time slots, new +
existing speakers).
**Run it:**
```bash
docker compose up -d --build mock-api # :54330
```
**Trigger a sync** (as admin, from the APPE Admin **Interfaces** view, or via
curl with an admin JWT):
```bash
# 1. get an admin JWT
ADMIN_JWT=$(curl -s -X POST "http://127.0.0.1:54321/auth/v1/token?grant_type=password" \
-H "apikey: $ANON" -H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"CVV-ADM-0001"}' | jq -r .access_token)
# 2. trigger the sync
curl -s -X POST "http://127.0.0.1:54321/functions/v1/sync-trigger" \
-H "Content-Type: application/json" -H "Authorization: Bearer $ADMIN_JWT" \
-d '{"source":"both"}'
```
Expected: new contacts get generated QR tokens (and can log in), types are
mapped, sessions/slots/speakers are created, and `sync_runs` records the run.
## Going live (real Pretix / Sessionize)
1. Set the real base URLs + tokens as env on the Edge Function
(`npx supabase secrets set PRETIX_BASE_URL=... PRETIX_API_TOKEN=...` etc.).
2. Adjust the normalizers in `sync-trigger/index.ts` if the real API shapes
differ from the mock fixtures (the field mapping is isolated in
`fetchPretixAttendees` / `fetchSessionizeSessions`).
3. (Optional) schedule a pull with a cron that POSTs to the function with the
`x-cron-secret` header.
## Open questions
1. **Pretix type mapping** — confirm which ticket types map to
speaker/staff/sponsor (the substring matcher is a reasonable default).
2. **Sync cadence** — how often to pull (pre-event vs during the event)?
3. **Webhooks** — Pretix/Sessionize can push on change; the current design is
pull-based (add a webhook endpoint later if real-time is needed).
-7
View File
@@ -52,7 +52,6 @@ Source of truth:
| `feedback` | own **or** admin | — | — | — |
| `leaderboard` | all authenticated | — | — | — |
| `points_log` | own **or** admin | — | — | — |
| `sync_runs` | admin only | — | — | — |
**"—" (no policy)** means normal users have **no direct write access** — those
tables are written only by the `security definer` RPCs, which bypass RLS. This is
@@ -120,10 +119,6 @@ create policy "leaderboard_select_all" on public.leaderboard for select to authe
-- points_log: read own or admin
create policy "points_log_select_own_or_admin" on public.points_log for select to authenticated
using (contact_email = public.current_email() or public.is_admin());
-- sync_runs: admin only (interface sync audit)
create policy "sync_runs_select_admin" on public.sync_runs for select to authenticated
using (public.is_admin());
```
## Storage — `materials` bucket
@@ -158,8 +153,6 @@ grant usage on schema public to anon, authenticated, service_role;
grant select on <all 14 tables> to anon, authenticated, service_role;
grant insert, update, delete on <all 14 tables> to authenticated, service_role;
grant execute on function <all public RPCs + helpers> to authenticated;
grant execute on function sync_pretix_attendees(jsonb), sync_sessionize_sessions(jsonb)
to service_role; -- interface sync RPCs are service-role-only
```
Note `anon` gets `select` but **no** `insert/update/delete`; `authenticated` gets
-17
View File
@@ -202,23 +202,6 @@ profile from the Convivo app: the LinkedIn URL and the two visibility toggles
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 |
+7 -28
View File
@@ -4,11 +4,10 @@ All tables live in the `public` schema. Source of truth:
[`supabase/migrations/20260824000000_redesign.sql`](../../supabase/migrations/20260824000000_redesign.sql)
(the Redesign migration, which **replaces** the old `profiles`-based schema).
There are **14 tables**: people (`contacts`), the event (`events`), participation
There are **13 tables**: people (`contacts`), the event (`events`), participation
(`registrations`, `sponsors`), the schedule (`slots`, `sessions`,
`session_speakers`), the event's activity (`preferences`, `connections`,
`checkins`, `feedback`, `leaderboard`, `points_log`), and the interface audit
(`sync_runs`).
`session_speakers`), and the event's activity (`preferences`, `connections`,
`checkins`, `feedback`, `leaderboard`, `points_log`).
The old `profiles` table is **dropped**. People are now `contacts` (keyed by
email), and every activity table is scoped to an **event** + a **contact email**
@@ -45,8 +44,7 @@ erDiagram
One row per person. **`email` is the primary key** (a natural key that matches
`auth.users.email`). Contacts carry **no QR token** — the token lives on the
registration (it is generated per event by Pretix and doubles as the Auth
password).
registration (it is generated per event and doubles as the Auth password).
| Column | Type | Notes |
|---|---|---|
@@ -57,7 +55,7 @@ password).
| `show_linkedin` | `boolean` | default `false` — visibility toggle |
| `is_admin` | `boolean` | default `false` — **staff = admin (merged)**; grants check-in + APPE Admin access |
| `password` | `text` | nullable — the **login password** (event-independent) for admin/staff. Setting it (e.g. in the Supabase Table Editor) **auto-syncs** the bcrypt hash into `auth.users.encrypted_password` via the `trg_contact_password_sync` trigger, so it works with `signInWithPassword` immediately |
| `external_id` | `text` | nullable — the Pretix order code (set by the sync) |
| `external_id` | `text` | nullable — reserved for an external system's id (currently unused) |
| `created_at` | `timestamptz` | |
Partial unique index: `contacts_external_id_uniq (external_id) WHERE external_id IS NOT NULL`.
@@ -98,7 +96,7 @@ Points are scoped **per event** here (one row per contact per event).
| `checked_in` | `boolean` | default `false` |
| `points` | `integer` | `>= 0`, default 0 |
| `qr_token` | `text` | nullable — the lanyard token; **doubles as the Auth password** (generated per event) |
| `external_id` | `text` | nullable — the Pretix order code (set by the sync) |
| `external_id` | `text` | nullable — reserved for an external system's id (currently unused) |
| `created_at` | `timestamptz` | |
**Constraint:** `unique (event_id, contact_email)` — one registration per contact
@@ -155,7 +153,7 @@ Unpaid sponsors are hidden from non-admins (RLS).
| `average_feedback` | `numeric` | maintained by `submit_feedback` |
| `ai_generated_feedback` | `text` | AI-feedback state (stub) |
| `material_path` | `text` | nullable — storage object path for session material |
| `external_id` | `text` | nullable — the Sessionize session id (set by the sync) |
| `external_id` | `text` | nullable — reserved for an external system's id (currently unused) |
| `created_at` | `timestamptz` | |
> **Speakers are no longer a `text` column** — they live in the `session_speakers`
@@ -274,25 +272,6 @@ Powers the per-category points breakdown on the Profile screen (per event).
Index: `points_log_event_id_idx (event_id)`.
## `sync_runs` — interface sync audit
One row per Pretix/Sessionize sync run, written by the service-role-only sync
RPCs (see [interfaces.md](./interfaces.md)).
| Column | Type | Notes |
|---|---|---|
| `id` | `uuid` PK | `gen_random_uuid()` |
| `source` | `text` | `pretix` \| `sessionize` |
| `started_at` | `timestamptz` | |
| `finished_at` | `timestamptz` | nullable |
| `created` | `integer` | rows created |
| `updated` | `integer` | rows updated |
| `skipped` | `integer` | rows skipped |
| `error` | `text` | nullable — top-level error, if any |
| `triggered_by` | `text` | default `service_role` |
Index: `sync_runs_source_idx (source)`. RLS: admin-only `select`.
## Other indexes
- `slots_event_id_idx (event_id)`, `registrations_event_id_idx (event_id)`,