From e4c8815e520ade77d7677ead9dc962e3bb912978 Mon Sep 17 00:00:00 2001 From: Jose Lago Date: Tue, 8 Sep 2026 21:04:30 +0200 Subject: [PATCH] Check-in gate + fixes, RPC test suite, docs - Convivo: not-checked-in gate for non-staff (see-a-staff screen with QR code + logout); lifts automatically once staff checks them in - Convivo: fix check-in 'pick a session first' race (synchronous default session fallback) - Add RPC test suite (npm run test:rpc): points idempotency, role guards, service-session guard, speaker auto-promote, leaderboard staff exclusion - Fix db:types script (create packages/shared/src); gitignore generated types - Docs: README/roadmap drift fixes, tests.md, backend README link --- .gitignore | 3 + README.md | 42 ++-- apps/convivo/src/App.tsx | 47 +++- apps/convivo/src/screens/Scan.tsx | 24 +- docs/backend/README.md | 1 + docs/backend/tests.md | 50 ++++ package.json | 3 +- packages/shared/src/.gitkeep | 1 + roadmap.md | 15 +- supabase/tests/rpc_tests.sql | 363 ++++++++++++++++++++++++++++++ supabase/tests/run-rpc-tests.js | 48 ++++ 11 files changed, 559 insertions(+), 38 deletions(-) create mode 100644 docs/backend/tests.md create mode 100644 packages/shared/src/.gitkeep create mode 100644 supabase/tests/rpc_tests.sql create mode 100644 supabase/tests/run-rpc-tests.js diff --git a/.gitignore b/.gitignore index 31c5ef4..8022c14 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,9 @@ dist/ build/ *.tsbuildinfo +# Generated types (regenerate with `npm run db:types`) +packages/shared/src/database.types.ts + # Environment (keep the example) .env .env.* diff --git a/README.md b/README.md index 0f31c02..10fd5c6 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,9 @@ > - **Phase 5** — Convivo App: 24h login, 5s polling, QR type badge, red dot, speaker material. > - **Phase 6** — Branding: APPE favicon + icons for both apps. > -> **Next:** cross-cutting work (real event clock, deployment, automated testing). -> See [`roadmap.md`](./roadmap.md). +> **Next:** cross-cutting work (deployment, automated testing, push +> notifications). The real event clock is implemented as a per-event +> `use_realtime_clock` toggle (see §4.7). See [`roadmap.md`](./roadmap.md). --- @@ -30,22 +31,15 @@ Conferences are full of people who want to meet each other but don't know how to ## 2. Event format -| | | -|---|---| -| **Date** | Wednesday, 23 October | -| **Hours** | 09:00 – 17:00 | -| **Structure** | 6 slots × 45 minutes, **3 parallel sessions per slot** | -| **Breaks** | 09:45–10:00 · coffee 10:45–11:30 · lunch 12:15–13:15 · 14:45–15:00 · closing 15:45–17:00 | +The schedule is **data-driven** (stored in Postgres), so times and sessions can +be changed without an app update. The seed uses the real **Global Power +Platform Bootcamp (Austria)** agenda — 2026-02-20, Vienna — with 10 slots +(7 `session` + 3 `service_session`) and 22 sessions. -| Slot | Time | Slot | Time | -|---|---|---|---| -| 1 | 09:00–09:45 | 4 | 13:15–14:00 | -| 2 | 10:00–10:45 | 5 | 14:00–14:45 | -| 3 | 11:30–12:15 | 6 | 15:00–15:45 | - -The schedule is **data-driven** (stored in Postgres), so times and sessions can be changed without an app update. - -> **Demo clock:** the app uses a simulated "now" of `2026-10-23 10:20` so Slot 1 is *done* and Slot 2 is *live* — matching the mockup. See `apps/convivo/src/lib/time.ts`. +> **Demo clock:** by default the app uses a simulated "now" of +> `2026-02-20 10:20` so a slot is *live* — matching the mockup. A per-event +> `use_realtime_clock` flag (toggled in the admin Events view) switches the +> app to the real system clock. See `apps/convivo/src/lib/time.ts`. ## 3. Roles @@ -69,7 +63,7 @@ Check-in tab. **How it works:** the QR token is stored as the Supabase Auth **password** and the email as the **identifier**. Login is a standard `signInWithPassword({ email, password: qrToken })` — no custom JWT, no separate backend, and **no email is ever sent** (`enable_confirmations = false`). ### 4.2 Agenda & preferences -- The agenda shows all 6 slots and their 3 parallel sessions (title, room, speaker, description). +- The agenda shows every slot and its parallel sessions (title, room, speaker, description). - Attendees mark **one preferred session per slot** (they can change their pick until the slot starts). - Home shows "Now / Next" based on the current time and the user's picks. @@ -93,6 +87,11 @@ Check-in tab. - Your own row is highlighted. - **Live:** the leaderboard table is a Realtime source, so it updates in every open app the moment points change. +### 4.7 Real-time clock toggle +- A per-event `use_realtime_clock` flag (default `false`), toggled in the admin Events view. +- When `false`, the app drives slot status (Live/Next/Done) from a **simulated mid-event clock** so the demo always looks live. When `true`, it uses the **real system clock**. +- The Home header shows a "🎬 Demo clock" badge only in simulated mode. + ## 5. Points system | Action | Points | @@ -153,8 +152,8 @@ The model is **multi-event**: people (`contacts`) register for `events` via | `events` | id, name, start_date, end_date, location, is_active, + aggregates | Partial unique index → at most one active event | | `registrations` | id, event_id, contact_email, type (attendee/speaker/staff/sponsor), checked_in, points, external_id | Unique (event_id, contact_email); points live here | | `sponsors` | id, event_id, type, name, email, phone, paid, amount_eur, contact_email | `paid` gates visibility to non-admins | -| `slots` | id, event_id, type (session/lunch_break/coffee_break/keynote/close_up), name, slot_date, start_time, end_time | 6 rows for 23 Oct | -| `sessions` | id, event_id, slot_id, title, description, room, capacity, average_feedback, ai_generated_feedback, material_path, external_id | 18 rows (3 per session slot); `external_id` reserved for an external system | +| `slots` | id, event_id, type (`session`/`service_session` enum), name, slot_date, start_time, end_time | 10 rows in the seed (7 session + 3 service) | +| `sessions` | id, event_id, slot_id, title, description, room, capacity, average_feedback, ai_generated_feedback, material_path, external_id | 22 rows in the seed; `external_id` reserved for an external system | | `session_speakers` | session_id, contact_email | Join; a session must have ≥1 speaker | | `preferences` | event_id, contact_email, session_id, slot_id | Unique per (event, contact, slot) — one pick per slot | | `connections` | event_id, from_email, to_email, status, created_at, resolved_at | Unique per unordered pair (via `least`/`greatest` index) | @@ -195,9 +194,10 @@ Convivo/ │ └─ src/ # screens, components, lib, context ├─ supabase/ │ ├─ config.toml # Local stack config (ports, auth, RLS defaults) -│ ├─ migrations/ # 20260824000000_redesign.sql + follow-up migrations +│ ├─ migrations/ # 13 migrations (init → real-time clock toggle) │ └─ seed.sql # 1 real event (Power Platform Bootcamp AT), 10 slots, 22 sessions, 54 contacts ├─ apps/admin/ # APPE Admin console (React + Vite + TS) +├─ apps/sidecar/ # Sessionize sync sidecar (Node, one dep: xlsx) ├─ docker-compose.yml # Runs the app sidecars on the Supabase network └─ mockup/index.html # Original interactive mockup (design reference) ``` diff --git a/apps/convivo/src/App.tsx b/apps/convivo/src/App.tsx index 86e56f2..170f154 100644 --- a/apps/convivo/src/App.tsx +++ b/apps/convivo/src/App.tsx @@ -9,7 +9,7 @@ import { Connections } from './screens/Connections'; import { Leaderboard } from './screens/Leaderboard'; import { Profile } from './screens/Profile'; import { Feedback } from './screens/Feedback'; -import { Spinner } from './components/ui'; +import { QrImage, Spinner } from './components/ui'; import { getMyConnections } from './lib/api'; import { usePolling } from './lib/usePolling'; @@ -23,7 +23,7 @@ const TABS: { id: Tab; ico: string; label: string }[] = [ ]; function Shell() { - const { session, contact, loading } = useAuth(); + const { session, contact, registration, loading, refresh, signOut } = useAuth(); const [tab, setTab] = useState('home'); const [feedbackSession, setFeedbackSession] = useState(null); const [pendingIncoming, setPendingIncoming] = useState(0); @@ -46,6 +46,13 @@ function Shell() { // Keep the Connect red-dot fresh: poll every 5s while visible. usePolling(() => void loadPending(), 5000, !!email); + // Gate: a non-staff member must be checked in by staff before using the app. + // (Staff are never gated — they're the ones doing the checking in.) + const isGated = !!contact && !contact.is_admin && !registration?.checked_in; + + // While gated, poll so the gate lifts as soon as staff checks them in. + usePolling(() => { if (isGated) void refresh(); }, 4000, isGated); + // Recalc immediately when a connection is accepted/declined/sent. useEffect(() => { const onChanged = () => void loadPending(); @@ -71,6 +78,42 @@ function Shell() { ); } + // Not checked in yet: a non-staff member must be checked in by staff before + // they can use the app. The gate lifts automatically (4s poll) once staff + // checks them in. + if (isGated) { + return ( +
+
+
🏷️
+
Please see a staff member
+
+ You haven’t been checked in yet. Find a staff member and have them + scan your lanyard to get checked in — then you can start using the app. +
+ {registration?.qr_token && ( +
+
Your QR code
+ +
+ Show this to staff to get checked in. +
+
+ )} +
+ Checking in… this screen updates automatically. +
+ + +
+
+ ); + } + // Feedback is a full-screen takeover (no tab bar). if (feedbackSession) { return ( diff --git a/apps/convivo/src/screens/Scan.tsx b/apps/convivo/src/screens/Scan.tsx index 96491a0..a3d36d8 100644 --- a/apps/convivo/src/screens/Scan.tsx +++ b/apps/convivo/src/screens/Scan.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useMemo, useState } from 'react'; import { useAuth } from '../context/AuthContext'; import { useEvent } from '../lib/useEvent'; import { checkinAttendee, createConnectionRequest, lanyardLookup, welcomeCheckin } from '../lib/api'; @@ -20,13 +20,16 @@ export function Scan() { const [busy, setBusy] = useState(false); const { toast } = useToast(); + // The first checkable (non-service) session, computed synchronously so a fast + // scan never races the async default-selection effect below. + const defaultSessionId = useMemo( + () => slots.flatMap((s) => s.sessions).find((s) => s.slot_type !== 'service_session')?.id ?? '', + [slots], + ); + useEffect(() => { - if (slots.length > 0 && !sessionId) { - // Default to the first checkable (non-service) session. - const first = slots.flatMap((s) => s.sessions).find((s) => s.slot_type !== 'service_session'); - if (first) setSessionId(first.id); - } - }, [slots, sessionId]); + if (defaultSessionId && !sessionId) setSessionId(defaultSessionId); + }, [defaultSessionId, sessionId]); if (loading || !contact) { return ( @@ -49,11 +52,14 @@ export function Scan() { const res = await welcomeCheckin(token); setWelcome(res); } else { - if (!sessionId) { + // Fall back to the first checkable session so a fast scan (before the + // async default-selection effect runs) never fails with "pick a session". + const targetSession = sessionId || defaultSessionId; + if (!targetSession) { toast('Pick a session first', 'err'); return; } - const res = await checkinAttendee(sessionId, token); + const res = await checkinAttendee(targetSession, token); setCheckin(res); } } else { diff --git a/docs/backend/README.md b/docs/backend/README.md index 077cdb5..08091fe 100644 --- a/docs/backend/README.md +++ b/docs/backend/README.md @@ -13,6 +13,7 @@ Postgres. This folder documents that core. | [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) | | [sidecar.md](./sidecar.md) | The Sessionize sync sidecar (on-demand, service-role) | +| [tests.md](./tests.md) | The RPC test suite (`npm run test:rpc`) | ## The big picture diff --git a/docs/backend/tests.md b/docs/backend/tests.md new file mode 100644 index 0000000..c00bf5a --- /dev/null +++ b/docs/backend/tests.md @@ -0,0 +1,50 @@ +# Backend — RPC Test Suite + +A self-contained, idempotent test suite for the transactional points RPCs, role +guards, and the speaker auto-promote trigger. It runs directly against the local +Supabase Postgres container. + +## Run it + +```bash +npm run db:start # the Supabase core must be running +npm run test:rpc # runs supabase/tests/rpc_tests.sql, exits non-zero on failure +``` + +Or manually: + +```bash +docker exec -i supabase_db_Convivo psql -U postgres < supabase/tests/rpc_tests.sql +``` + +## How it works + +- **No seed mutation.** Everything runs in a single transaction that **rolls + back** at the end, so the seed data is never changed. Safe to run repeatedly. +- **Current user = PostgREST-style JWT claim.** Each test sets the user the same + way PostgREST does: + `set_config('request.jwt.claims', '{"email":"..."}', false)`, which is what + [`public.current_email()`](./rpcs.md) and `public.is_admin()` read. +- **Every test always runs.** Each test is a `DO` block that catches its own + exceptions and records a pass/fail row into a temp table, so one failure never + aborts the rest. A summary is printed before the rollback. +- **The runner fails the process** (`npm run test:rpc`) if any test failed, so it + can be wired into CI. + +## What it covers + +| Area | Tests | +|---|---| +| `checkin_attendee` | awards +10, marks `checked_in`, idempotent re-check-in, service-session guard, non-admin role guard | +| `submit_feedback` | +5 rating-only, idempotent re-submit, requires check-in | +| `accept_connection` | +5 to both parties | +| `adjust_points` | admin-only role guard | +| Speaker auto-promote trigger | attendee → speaker, never overrides staff | +| Leaderboard | excludes staff | + +## Files + +- [`supabase/tests/rpc_tests.sql`](../../supabase/tests/rpc_tests.sql) — the test + script (fixtures + assertions + summary). +- [`supabase/tests/run-rpc-tests.js`](../../supabase/tests/run-rpc-tests.js) — the + runner (executes the script, parses the summary, sets the exit code). diff --git a/package.json b/package.json index 77780d2..c48c4a0 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,8 @@ "app:build": "npm --prefix apps/convivo run build", "admin:dev": "npm --prefix apps/admin run dev", "admin:build": "npm --prefix apps/admin run build", - "sidecar:dev": "SUPABASE_URL=http://127.0.0.1:54321 node apps/sidecar/src/server.js" + "sidecar:dev": "SUPABASE_URL=http://127.0.0.1:54321 node apps/sidecar/src/server.js", + "test:rpc": "node supabase/tests/run-rpc-tests.js" }, "devDependencies": { "supabase": "^2.28.1" diff --git a/packages/shared/src/.gitkeep b/packages/shared/src/.gitkeep new file mode 100644 index 0000000..1f3f9e5 --- /dev/null +++ b/packages/shared/src/.gitkeep @@ -0,0 +1 @@ +# Generated by `npm run db:types` (supabase gen types typescript --local). diff --git a/roadmap.md b/roadmap.md index d8180ad..810acb0 100644 --- a/roadmap.md +++ b/roadmap.md @@ -4,8 +4,9 @@ Living roadmap. The top section is the **current focus**; completed phases are summarized below. For *how* each piece works, see [`docs/`](./docs/README.md). > **Status:** Phases 0–6 are complete and verified. The **Redesign** (Phases -> 3–6) is done. Remaining work is cross-cutting (real event clock, deployment, -> automated testing). +> 3–6) is done. The real event clock is implemented as a per-event +> `use_realtime_clock` toggle. Remaining work is cross-cutting (deployment, +> automated testing, push notifications). --- @@ -54,14 +55,18 @@ Convivo App gains several behaviors. Details live in ## Cross-cutting / later -- **Real event clock** — replace the simulated `DEFAULT_NOW` with `new Date()`. +- **Real event clock** — ✅ done as a per-event `use_realtime_clock` toggle + (migration `20260834`); the simulated `DEFAULT_NOW` is the default, the real + system clock is opt-in per event. - **Subdomains** — `convivo.appe.at`, `admin.appe.at`, `db.appe.at` don't exist yet; everything runs on localhost. DNS + TLS + a reverse proxy in front of the Supabase core will be needed for a real deployment. - **Push notifications** — connection requests are currently seen when the app is opened (or via the 5s poll while visible). -- **Testing** — no automated tests yet. Candidates: RPC unit tests (points - idempotency, role guards, sponsor-type rule), and an E2E smoke test. +- **Testing** — ✅ RPC test suite added (`npm run test:rpc`, see + [docs/backend/tests.md](./docs/backend/tests.md)): points idempotency, role + guards, service-session guard, speaker auto-promote, leaderboard staff + exclusion. Still to add: an E2E smoke test. ## Open questions diff --git a/supabase/tests/rpc_tests.sql b/supabase/tests/rpc_tests.sql new file mode 100644 index 0000000..8213c55 --- /dev/null +++ b/supabase/tests/rpc_tests.sql @@ -0,0 +1,363 @@ +-- ============================================================================= +-- Convivo — RPC test suite +-- +-- A self-contained, idempotent test script for the transactional points RPCs, +-- role guards, and the speaker auto-promote trigger. +-- +-- HOW IT WORKS +-- * Everything runs inside a single transaction that ROLLS BACK at the end, +-- so the seed data is never mutated. Safe to run repeatedly. +-- * The "current user" is set the same way PostgREST does it: +-- set_config('request.jwt.claims', '{"email":"..."}', false) +-- which is what public.current_email() / public.is_admin() read. +-- * Each test is a DO block that catches its own exceptions and records a +-- pass/fail row into a temp table, so ALL tests always run and a summary +-- is always printed (the summary is printed BEFORE the rollback, since the +-- temp table is dropped by it). The runner (npm run test:rpc) fails the +-- process if any test failed. +-- +-- RUN IT +-- npm run test:rpc (from the repo root) +-- or manually: +-- docker exec -i supabase_db_Convivo psql -U postgres \ +-- < supabase/tests/rpc_tests.sql +-- ============================================================================= + +begin; + +-- Scratch table for the pass/fail summary (transaction-scoped). +create temporary table test_results ( + name text, + passed boolean, + message text +); + +-- Set the "current user" for the following RPC calls (PostgREST-style JWT claim). +create or replace function set_user(p_email text) +returns void +language plpgsql as $$ +begin + perform set_config('request.jwt.claims', json_build_object('email', p_email)::text, false); +end; +$$; + +-- Fixtures (from the seed): +-- active event id +-- staff/admin: amelia@appe.at (is_admin = true) +-- attendee: lena.huber@gmail.com (QR CVV-ATT-1000, 0 points) +-- attendee: felix.berger@outlook.com (QR CVV-ATT-1001, 0 points) +-- a normal session (slot 2) and a service session (slot 4). + +-- ============================================================================= +-- 1. checkin_attendee: awards +10, marks checked_in +-- ============================================================================= +do $$ +declare + v_session uuid; + v_res_points integer; + v_points integer; + v_ok boolean; + v_msg text; +begin + select id into v_session from public.sessions where slot_id = 2 limit 1; + perform set_user('amelia@appe.at'); + select points into v_res_points from public.checkin_attendee(v_session, 'CVV-ATT-1000'); + select points into v_points from public.registrations + where contact_email = 'lena.huber@gmail.com' + and event_id = (select id from public.events where is_active limit 1); + v_ok := (v_res_points = 10 and v_points = 10); + v_msg := 'expected 10 points, got ' || coalesce(v_res_points::text, 'null'); + insert into test_results values ('checkin awards +10', v_ok, case when v_ok then null else v_msg end); + + v_ok := exists (select 1 from public.registrations + where contact_email = 'lena.huber@gmail.com' and checked_in); + v_msg := 'registration not marked checked_in'; + insert into test_results values ('checkin marks checked_in', v_ok, case when v_ok then null else v_msg end); +exception when others then + insert into test_results values ('checkin (1)', false, 'error: ' || sqlerrm); +end; +$$; + +-- ============================================================================= +-- 2. checkin_attendee: idempotent (re-check-in does not double-award) +-- ============================================================================= +do $$ +declare + v_session uuid; + v_res_already boolean; + v_points integer; + v_ok boolean; + v_msg text; +begin + select id into v_session from public.sessions where slot_id = 2 limit 1; + perform set_user('amelia@appe.at'); + select already into v_res_already from public.checkin_attendee(v_session, 'CVV-ATT-1000'); + select points into v_points from public.registrations + where contact_email = 'lena.huber@gmail.com' + and event_id = (select id from public.events where is_active limit 1); + v_ok := v_res_already; + v_msg := 'expected already=true on second check-in'; + insert into test_results values ('re-check-in flagged already', v_ok, case when v_ok then null else v_msg end); + + v_ok := (v_points = 10); + v_msg := 'expected still 10 points, got ' || v_points; + insert into test_results values ('re-check-in no double-award', v_ok, case when v_ok then null else v_msg end); +exception when others then + insert into test_results values ('checkin (2)', false, 'error: ' || sqlerrm); +end; +$$; + +-- ============================================================================= +-- 3. checkin_attendee: service sessions cannot be checked in +-- ============================================================================= +do $$ +declare + v_session uuid; + v_err text; +begin + select id into v_session from public.sessions + where slot_id in (select id from public.slots where type = 'service_session') + limit 1; + perform set_user('amelia@appe.at'); + begin + perform public.checkin_attendee(v_session, 'CVV-ATT-1001'); + insert into test_results values ('service session check-in rejected', false, + 'expected an exception for a service session'); + exception + when others then + get stacked diagnostics v_err = message_text; + insert into test_results values ('service session check-in rejected', + v_err like '%service sessions cannot be checked in%', + case when v_err like '%service sessions cannot be checked in%' + then null else 'unexpected error: ' || v_err end); + end; +exception when others then + insert into test_results values ('checkin (3)', false, 'error: ' || sqlerrm); +end; +$$; + +-- ============================================================================= +-- 4. checkin_attendee: role guard (non-admin rejected) +-- ============================================================================= +do $$ +declare + v_session uuid; + v_err text; +begin + select id into v_session from public.sessions where slot_id = 2 limit 1; + perform set_user('lena.huber@gmail.com'); -- an attendee, not an admin + begin + perform public.checkin_attendee(v_session, 'CVV-ATT-1001'); + insert into test_results values ('check-in role guard (non-admin)', false, + 'expected "staff or admin only"'); + exception + when others then + get stacked diagnostics v_err = message_text; + insert into test_results values ('check-in role guard (non-admin)', + v_err = 'staff or admin only', + case when v_err = 'staff or admin only' + then null else 'unexpected error: ' || v_err end); + end; +exception when others then + insert into test_results values ('checkin (4)', false, 'error: ' || sqlerrm); +end; +$$; + +-- ============================================================================= +-- 5. submit_feedback: +5 rating only, idempotent on re-submit +-- ============================================================================= +do $$ +declare + v_session uuid; + v_res_earned integer; + v_points integer; + v_ok boolean; + v_msg text; +begin + select id into v_session from public.sessions where slot_id = 2 limit 1; + perform set_user('amelia@appe.at'); + perform public.checkin_attendee(v_session, 'CVV-ATT-1001'); + + -- Rating only -> +5. (felix already has +10 from the check-in above, so 15.) + perform set_user('felix.berger@outlook.com'); + select earned into v_res_earned from public.submit_feedback(v_session, 4, null); + select points into v_points from public.registrations + where contact_email = 'felix.berger@outlook.com' + and event_id = (select id from public.events where is_active limit 1); + v_ok := (v_res_earned = 5 and v_points = 15); + v_msg := 'expected earned=5/points=15, got earned=' || v_res_earned || ' points=' || v_points; + insert into test_results values ('feedback rating-only earns +5', v_ok, case when v_ok then null else v_msg end); + + -- Re-submit (idempotent) -> no extra points (stays at 15). + select earned into v_res_earned from public.submit_feedback(v_session, 5, null); + select points into v_points from public.registrations + where contact_email = 'felix.berger@outlook.com' + and event_id = (select id from public.events where is_active limit 1); + v_ok := (v_res_earned = 0 and v_points = 15); + v_msg := 'expected earned=0/points=15, got earned=' || v_res_earned || ' points=' || v_points; + insert into test_results values ('feedback re-submit idempotent', v_ok, case when v_ok then null else v_msg end); +exception when others then + insert into test_results values ('feedback (5)', false, 'error: ' || sqlerrm); +end; +$$; + +-- ============================================================================= +-- 6. submit_feedback: requires check-in +-- ============================================================================= +do $$ +declare + v_session uuid; + v_err text; +begin + select id into v_session from public.sessions where slot_id = 3 limit 1; + perform set_user('felix.berger@outlook.com'); -- not checked into slot 3 + begin + perform public.submit_feedback(v_session, 4, null); + insert into test_results values ('feedback requires check-in', false, + 'expected "you must be checked in"'); + exception + when others then + get stacked diagnostics v_err = message_text; + insert into test_results values ('feedback requires check-in', + v_err like '%must be checked in%', + case when v_err like '%must be checked in%' + then null else 'unexpected error: ' || v_err end); + end; +exception when others then + insert into test_results values ('feedback (6)', false, 'error: ' || sqlerrm); +end; +$$; + +-- ============================================================================= +-- 7. accept_connection: +5 to both parties +-- ============================================================================= +do $$ +declare + v_conn uuid; + v_from integer; + v_to integer; + v_ok boolean; + v_msg text; +begin + -- lena -> felix (both fresh attendees). + perform set_user('lena.huber@gmail.com'); + select id into v_conn from public.create_connection_request('CVV-ATT-1001'); + + -- felix accepts. + perform set_user('felix.berger@outlook.com'); + perform public.accept_connection(v_conn); + + select points into v_from from public.registrations + where contact_email = 'lena.huber@gmail.com' + and event_id = (select id from public.events where is_active limit 1); + select points into v_to from public.registrations + where contact_email = 'felix.berger@outlook.com' + and event_id = (select id from public.events where is_active limit 1); + -- lena had 10 from the check-in test; +5 connection = 15. + -- felix had 15 (check-in + feedback); +5 connection = 20. + v_ok := (v_from = 15 and v_to = 20); + v_msg := 'expected lena=15/felix=20, got lena=' || v_from || ' felix=' || v_to; + insert into test_results values ('connection accepted +5 each', v_ok, case when v_ok then null else v_msg end); +exception when others then + insert into test_results values ('connection (7)', false, 'error: ' || sqlerrm); +end; +$$; + +-- ============================================================================= +-- 8. adjust_points: admin only +-- ============================================================================= +do $$ +declare + v_err text; +begin + perform set_user('lena.huber@gmail.com'); -- not an admin + begin + perform public.adjust_points('lena.huber@gmail.com', 5, 'test'); + insert into test_results values ('adjust_points role guard (non-admin)', false, + 'expected "admin only"'); + exception + when others then + get stacked diagnostics v_err = message_text; + insert into test_results values ('adjust_points role guard (non-admin)', + v_err = 'admin only', + case when v_err = 'admin only' + then null else 'unexpected error: ' || v_err end); + end; +exception when others then + insert into test_results values ('adjust_points (8)', false, 'error: ' || sqlerrm); +end; +$$; + +-- ============================================================================= +-- 9. Speaker auto-promote trigger (attendee -> speaker, never overrides staff) +-- ============================================================================= +do $$ +declare + v_session uuid; + v_type public.registration_type; + v_ok boolean; + v_msg text; +begin + select id into v_session from public.sessions where slot_id = 2 limit 1; + -- lena is an attendee; adding her as a speaker should promote her. + insert into public.session_speakers (session_id, contact_email) + values (v_session, 'lena.huber@gmail.com'); + select "type" into v_type from public.registrations + where contact_email = 'lena.huber@gmail.com' + and event_id = (select id from public.events where is_active limit 1); + v_ok := (v_type = 'speaker'); + v_msg := 'expected type=speaker, got ' || coalesce(v_type::text, 'null'); + insert into test_results values ('speaker auto-promote (attendee->speaker)', v_ok, case when v_ok then null else v_msg end); + + -- A staff registration must NOT be overridden by the promote trigger. + insert into public.session_speakers (session_id, contact_email) + values (v_session, 'amelia@appe.at'); + select "type" into v_type from public.registrations + where contact_email = 'amelia@appe.at' + and event_id = (select id from public.events where is_active limit 1); + v_ok := (v_type = 'staff'); + v_msg := 'expected type=staff, got ' || coalesce(v_type::text, 'null'); + insert into test_results values ('speaker auto-promote never overrides staff', v_ok, case when v_ok then null else v_msg end); +exception when others then + insert into test_results values ('speaker promote (9)', false, 'error: ' || sqlerrm); +end; +$$; + +-- ============================================================================= +-- 10. Leaderboard excludes staff +-- ============================================================================= +do $$ +declare + v_count integer; + v_ok boolean; + v_msg text; +begin + -- Give amelia (staff) some points, then confirm she is not on the board. + perform set_user('amelia@appe.at'); + perform public.adjust_points('amelia@appe.at', 50, 'test'); + select count(*) into v_count from public.leaderboard + where contact_email = 'amelia@appe.at' + and event_id = (select id from public.events where is_active limit 1); + v_ok := (v_count = 0); + v_msg := 'expected 0 staff rows on leaderboard, got ' || v_count; + insert into test_results values ('leaderboard excludes staff', v_ok, case when v_ok then null else v_msg end); +exception when others then + insert into test_results values ('leaderboard (10)', false, 'error: ' || sqlerrm); +end; +$$; + +-- ============================================================================= +-- Summary (printed BEFORE the rollback, since the temp table is dropped by it) +-- ============================================================================= +select name, passed, message +from test_results +order by name; + +select + count(*) as total, + count(*) filter (where passed) as passed, + count(*) filter (where not passed) as failed +from test_results; + +-- Roll back so the seed is never mutated. +rollback; diff --git a/supabase/tests/run-rpc-tests.js b/supabase/tests/run-rpc-tests.js new file mode 100644 index 0000000..5f4aeaa --- /dev/null +++ b/supabase/tests/run-rpc-tests.js @@ -0,0 +1,48 @@ +#!/usr/bin/env node +// Convivo — RPC test runner. +// +// Runs supabase/tests/rpc_tests.sql against the local Supabase Postgres +// container and exits non-zero if any test failed. +// +// npm run test:rpc +// +// Requires the Supabase core to be running (`npm run db:start`). + +const { execFileSync } = require('node:child_process'); +const fs = require('node:fs'); +const path = require('node:path'); + +const SQL_FILE = path.join(__dirname, 'rpc_tests.sql'); +const DB_CONTAINER = process.env.SUPABASE_DB_CONTAINER || 'supabase_db_Convivo'; + +const sql = fs.readFileSync(SQL_FILE, 'utf8'); + +let output; +try { + output = execFileSync('docker', ['exec', '-i', DB_CONTAINER, 'psql', '-U', 'postgres'], { + input: sql, + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], + }); +} catch (e) { + // psql exits non-zero on a hard error (e.g. container not running). + process.stderr.write(e.stdout || ''); + process.stderr.write(e.stderr || ''); + process.stderr.write('\nFailed to run RPC tests (is the Supabase core running? `npm run db:start`).\n'); + process.exit(1); +} + +process.stdout.write(output); + +// Parse the summary row: " 14 | 14 | 0" (three pipe-separated +// numbers, no trailing pipe). Match the last such row in the output. +const summaryRows = [...output.matchAll(/(\d+)\s*\|\s*(\d+)\s*\|\s*(\d+)\s*$/gm)]; +const summaryMatch = summaryRows.length ? summaryRows[summaryRows.length - 1] : null; +if (!summaryMatch) { + process.stderr.write('\nCould not parse the test summary from psql output.\n'); + process.exit(1); +} + +const [, total, passed, failed] = summaryMatch.map((n) => parseInt(n, 10)); +process.stdout.write(`\nRPC tests: ${passed}/${total} passed, ${failed} failed.\n`); +process.exit(failed > 0 ? 1 : 0);