From 4ec03410ffd023590019b52d10bb5ab7d36805b8 Mon Sep 17 00:00:00 2001 From: Jose Lago Date: Thu, 15 Oct 2026 21:39:57 +0200 Subject: [PATCH] feat: add admin raffle with confetti and top-3/staff exclusion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Stephan Charles Co-authored-by: Amelia Hernandez Co-authored-by: Markus Franz Co-authored-by: Sabrina Hota Co-authored-by: NilΓΌfer Doğan --- apps/admin/package-lock.json | 19 ++ apps/admin/package.json | 2 + apps/admin/src/App.tsx | 4 + apps/admin/src/lib/api.ts | 27 +++ apps/admin/src/lib/types.ts | 13 ++ apps/admin/src/styles.css | 14 ++ apps/admin/src/views/Raffle.tsx | 206 ++++++++++++++++++ docs/architecture.md | 6 +- docs/backend/rpcs.md | 25 +++ docs/backend/tests.md | 21 ++ docs/frontend/admin-app.md | 1 + e2e/tests/raffle.spec.ts | 130 +++++++++++ supabase/migrations/20261015180640_raffle.sql | 87 ++++++++ supabase/tests/raffle_tests.sql | 127 +++++++++++ 14 files changed, 680 insertions(+), 2 deletions(-) create mode 100644 apps/admin/src/views/Raffle.tsx create mode 100644 e2e/tests/raffle.spec.ts create mode 100644 supabase/migrations/20261015180640_raffle.sql create mode 100644 supabase/tests/raffle_tests.sql diff --git a/apps/admin/package-lock.json b/apps/admin/package-lock.json index 384cee7..a058587 100644 --- a/apps/admin/package-lock.json +++ b/apps/admin/package-lock.json @@ -9,12 +9,14 @@ "version": "0.1.0", "dependencies": { "@supabase/supabase-js": "^2.45.4", + "canvas-confetti": "1.9.3", "lucide-react": "0.468.0", "qrcode.react": "^4.0.1", "react": "^18.3.1", "react-dom": "^18.3.1" }, "devDependencies": { + "@types/canvas-confetti": "1.6.4", "@types/react": "^18.3.5", "@types/react-dom": "^18.3.0", "@vitejs/plugin-react": "^4.3.1", @@ -1298,6 +1300,13 @@ "@babel/types": "^7.28.2" } }, + "node_modules/@types/canvas-confetti": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/@types/canvas-confetti/-/canvas-confetti-1.6.4.tgz", + "integrity": "sha512-fNyZ/Fdw/Y92X0vv7B+BD6ysHL4xVU5dJcgzgxLdGbn8O3PezZNIJpml44lKM0nsGur+o/6+NZbZeNTt00U1uA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", @@ -1422,6 +1431,16 @@ ], "license": "CC-BY-4.0" }, + "node_modules/canvas-confetti": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/canvas-confetti/-/canvas-confetti-1.9.3.tgz", + "integrity": "sha512-rFfTURMvmVEX1gyXFgn5QMn81bYk70qa0HLzcIOSVEyl57n6o9ItHeBtUSWdvKAPY0xlvBHno4/v3QPrT83q9g==", + "license": "ISC", + "funding": { + "type": "donate", + "url": "https://www.paypal.me/kirilvatev" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", diff --git a/apps/admin/package.json b/apps/admin/package.json index 03395be..3627bdc 100644 --- a/apps/admin/package.json +++ b/apps/admin/package.json @@ -10,12 +10,14 @@ }, "dependencies": { "@supabase/supabase-js": "^2.45.4", + "canvas-confetti": "1.9.3", "lucide-react": "0.468.0", "qrcode.react": "^4.0.1", "react": "^18.3.1", "react-dom": "^18.3.1" }, "devDependencies": { + "@types/canvas-confetti": "1.6.4", "@types/react": "^18.3.5", "@types/react-dom": "^18.3.0", "@vitejs/plugin-react": "^4.3.1", diff --git a/apps/admin/src/App.tsx b/apps/admin/src/App.tsx index 2353555..0d6ade7 100644 --- a/apps/admin/src/App.tsx +++ b/apps/admin/src/App.tsx @@ -8,6 +8,7 @@ import { Registrations } from './views/Registrations'; import { Sponsors } from './views/Sponsors'; import { Schedule } from './views/Schedule'; import { Activity } from './views/Activity'; +import { Raffle } from './views/Raffle'; import { Events } from './views/Events'; import { Interfaces } from './views/Interfaces'; import { Reports } from './views/Reports'; @@ -22,6 +23,7 @@ export type View = | 'sponsors' | 'schedule' | 'activity' + | 'raffle' | 'events' | 'interfaces' | 'reports' @@ -34,6 +36,7 @@ const NAV: { id: View; label: string; ico: string }[] = [ { id: 'sponsors', label: 'Sponsors', ico: '🀝' }, { id: 'schedule', label: 'Schedule', ico: 'πŸ—“οΈ' }, { id: 'activity', label: 'Activity', ico: '⚑' }, + { id: 'raffle', label: 'Raffle', ico: '🎯' }, { id: 'events', label: 'Events', ico: 'πŸ“…' }, { id: 'interfaces', label: 'Interfaces', ico: 'πŸ”Œ' }, { id: 'reports', label: 'Reports', ico: 'πŸ“€' }, @@ -104,6 +107,7 @@ function Shell() { {view === 'sponsors' && } {view === 'schedule' && } {view === 'activity' && } + {view === 'raffle' && } {view === 'events' && } {view === 'interfaces' && } {view === 'reports' && } diff --git a/apps/admin/src/lib/api.ts b/apps/admin/src/lib/api.ts index 75b9388..f5f7eca 100644 --- a/apps/admin/src/lib/api.ts +++ b/apps/admin/src/lib/api.ts @@ -14,6 +14,8 @@ import type { PointsLogRow, PretixOptions, PretixSyncResult, + RafflePoolEntry, + RaffleWinner, Registration, ResetQrResult, Session, @@ -349,6 +351,31 @@ export async function adjustPoints(contactEmail: string, delta: number, reason: await rpc('adjust_points', { p_contact_email: contactEmail, p_delta: delta, p_reason: reason }); } +// ---- Raffle ------------------------------------------------------------------ + +/** Eligible attendees for the active event: excludes staff/Admin, the + * leaderboard top 3, and everyone already drawn in the current run. */ +export async function getRafflePool(): Promise { + return rpc('get_raffle_pool', {}); +} + +/** Winners already drawn in the current run (oldest first). */ +export async function getRaffleWinners(): Promise { + return all('raffle_draws', { col: 'draw_number' }); +} + +/** Draw one random eligible attendee and record them as the next winner. */ +export async function drawRaffleWinner(): Promise { + const rows = await rpc[]>('draw_raffle_winner', {}); + if (!rows[0]) throw new ApiError('No eligible attendees left to draw'); + return { ...rows[0], drawn_at: new Date().toISOString() }; +} + +/** Clear the current run's winners so a new run can begin. */ +export async function resetRaffle(): Promise { + await rpc('reset_raffle', {}); +} + // ---- Sessions: speakers, material, AI feedback ------------------------------- export async function setSessionSpeakers(sessionId: string, emails: string[]): Promise { diff --git a/apps/admin/src/lib/types.ts b/apps/admin/src/lib/types.ts index a60a342..a676ad3 100644 --- a/apps/admin/src/lib/types.ts +++ b/apps/admin/src/lib/types.ts @@ -330,3 +330,16 @@ export interface ResetQrResult { email: string; qr_token: string; } + +/** An eligible attendee returned by `get_raffle_pool` (admin raffle). */ +export interface RafflePoolEntry { + contact_email: string; + full_name: string; + points: number; +} + +/** A winner recorded by `draw_raffle_winner` / read from `raffle_draws`. */ +export interface RaffleWinner extends RafflePoolEntry { + draw_number: number; + drawn_at: string; +} diff --git a/apps/admin/src/styles.css b/apps/admin/src/styles.css index c626d53..fc68536 100644 --- a/apps/admin/src/styles.css +++ b/apps/admin/src/styles.css @@ -12,6 +12,20 @@ @media (max-width: 760px) { .seg.activity-tabs { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } } +.raffle { display: grid; gap: 20px; } +.raffle-stage { display: grid; gap: 18px; justify-items: center; text-align: center; padding: 32px 20px; } +.raffle-name { + min-height: 1.4em; width: 100%; max-width: 640px; font-size: clamp(24px, 5vw, 44px); font-weight: 700; + color: var(--text); overflow-wrap: anywhere; +} +.raffle-controls { display: flex; align-items: flex-end; justify-content: center; gap: 12px; flex-wrap: wrap; } +.raffle-picks { text-align: left; } +.raffle-picks input { width: 120px; } +.raffle-spin-icon { animation: raffle-rotate 0.9s linear infinite; } +@keyframes raffle-rotate { to { transform: rotate(360deg); } } +@media (prefers-reduced-motion: reduce) { + .raffle-spin-icon { animation: none; } +} * { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; } :root { --bg: #f0f2f6; --surface: #ffffff; --surface-2: #f4f5f9; diff --git a/apps/admin/src/views/Raffle.tsx b/apps/admin/src/views/Raffle.tsx new file mode 100644 index 0000000..e3d1a7b --- /dev/null +++ b/apps/admin/src/views/Raffle.tsx @@ -0,0 +1,206 @@ +import { useEffect, useRef, useState } from 'react'; +import confetti from 'canvas-confetti'; +import { RotateCcw, RotateCw } from 'lucide-react'; +import { + drawRaffleWinner, + getActiveEvent, + getRafflePool, + getRaffleWinners, + resetRaffle, +} from '../lib/api'; +import type { Event, RafflePoolEntry, RaffleWinner } from '../lib/types'; +import { Empty, Spinner } from '../components/ui'; + +const DEFAULT_PICKS = 5; +// Roulette timing: names flash fast, then decelerate onto the server's winner. +const SPIN_STEPS = 22; +const SPIN_MIN_MS = 45; +const SPIN_MAX_MS = 520; + +// Celebrate each drawn winner with a confetti burst (skipped for reduced motion). +function celebrate() { + confetti({ particleCount: 160, spread: 80, startVelocity: 45, origin: { y: 0.6 }, disableForReducedMotion: true }); + confetti({ particleCount: 60, angle: 60, spread: 60, origin: { x: 0, y: 0.7 }, disableForReducedMotion: true }); + confetti({ particleCount: 60, angle: 120, spread: 60, origin: { x: 1, y: 0.7 }, disableForReducedMotion: true }); +} + +export function Raffle() { + const [event, setEvent] = useState(null); + const [pool, setPool] = useState([]); + const [winners, setWinners] = useState([]); + const [picks, setPicks] = useState(DEFAULT_PICKS); + const [loaded, setLoaded] = useState(false); + const [spinning, setSpinning] = useState(false); + const [currentName, setCurrentName] = useState(null); + const [error, setError] = useState(null); + const running = useRef(false); + const timer = useRef | null>(null); + + useEffect(() => { + let active = true; + (async () => { + try { + const ev = await getActiveEvent(); + if (!active) return; + setEvent(ev); + if (!ev) { setLoaded(true); return; } + const [entries, drawn] = await Promise.all([getRafflePool(), getRaffleWinners()]); + if (!active) return; + setPool(entries); + setWinners(drawn); + setLoaded(true); + } catch (cause) { + if (active) setError(cause instanceof Error ? cause.message : 'Failed to load raffle'); + } + })(); + return () => { active = false; if (timer.current) clearTimeout(timer.current); }; + }, []); + + const total = winners.length + pool.length; + const remainingForRun = Math.max(0, picks - winners.length); + const canDraw = loaded && !spinning && !!event && winners.length < picks && pool.length > 0; + + function finish(winner: RaffleWinner) { + setWinners((current) => [...current, winner]); + setPool((current) => current.filter((entry) => entry.contact_email !== winner.contact_email)); + setCurrentName(winner.full_name); + running.current = false; + setSpinning(false); + celebrate(); + } + + function animateTo(winner: RaffleWinner) { + const others = pool.filter((entry) => entry.contact_email !== winner.contact_email).map((entry) => entry.full_name); + const sequence: string[] = []; + for (let step = 0; step < SPIN_STEPS; step += 1) { + sequence.push(others.length > 0 ? others[Math.floor(Math.random() * others.length)] : winner.full_name); + } + sequence.push(winner.full_name); + let index = 0; + const tick = () => { + setCurrentName(sequence[index]); + index += 1; + if (index < sequence.length) { + const progress = index / sequence.length; + timer.current = setTimeout(tick, SPIN_MIN_MS + Math.pow(progress, 2.6) * (SPIN_MAX_MS - SPIN_MIN_MS)); + } else { + finish(winner); + } + }; + tick(); + } + + async function draw() { + if (running.current) return; + running.current = true; + setSpinning(true); + setError(null); + try { + const winner = await drawRaffleWinner(); + animateTo(winner); + } catch (cause) { + setError(cause instanceof Error ? cause.message : 'Draw failed'); + running.current = false; + setSpinning(false); + } + } + + async function reset() { + if (spinning) return; + setError(null); + try { + await resetRaffle(); + const [entries, drawn] = await Promise.all([getRafflePool(), getRaffleWinners()]); + setPool(entries); + setWinners(drawn); + setCurrentName(null); + } catch (cause) { + setError(cause instanceof Error ? cause.message : 'Reset failed'); + } + } + + if (error && !loaded) return ; + if (!loaded) return
; + + return ( +
+
+
+

Raffle

+
+ {event ? `${event.name} Β· ${total} eligible attendees` : 'No active event. Set an event active in the Events view first.'} +
+
+
+ + {!event ? ( +
+ ) : ( +
+
+
+ {currentName ?? 'Press Spin to draw a winner'} +
+
+ + + +
+

+ Winners this run: {winners.length} of {picks} + {winners.length < picks && pool.length === 0 && ' Β· no eligible attendees left'} +

+ {error &&

{error}

} +

+ Excludes staff/Admin and the leaderboard top 3. Everyone can win only once per run. +

+
+ +
+
+

Winners

+ {remainingForRun > 0 ? `${remainingForRun} to go` : 'Run complete'} +
+ {winners.length === 0 ? ( + + ) : ( +
+ + + + + + {winners.map((w) => ( + + + + + + + ))} + +
#AttendeePointsWhen
{w.draw_number}{w.full_name}{w.points}{new Date(w.drawn_at).toLocaleTimeString()}
+
+ )} +
+
+ )} +
+ ); +} diff --git a/docs/architecture.md b/docs/architecture.md index 484a9c2..022b6e1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -95,11 +95,13 @@ A separate desktop-first React app for organizers, guarded to existing contacts with **`is_admin`** or an **`@appe.at`** email. See [frontend/admin-app.md](./frontend/admin-app.md): - **Views** β€” Dashboard (active event + aggregates), Contacts, Registrations, Sponsors, Schedule (slots/sessions/speakers/material), Activity (manual event - and session AI summaries), Events, Interfaces, Reports and Settings. + and session AI summaries), Raffle (attendee prize draws), Events, Interfaces, + Reports and Settings. - **Auth guard** β€” email-only magic links; non-admin sessions are rejected. - **Key RPCs** β€” `reset_registration_qr_token` (regenerate a registration's lanyard token + sync the Auth password), `adjust_points`, `upsert_contact`, - `create_registration`, `set_registration_type`, and `set_session_material` + `create_registration`, `set_registration_type`, `set_session_material`, and the + raffle functions `get_raffle_pool` / `draw_raffle_winner` / `reset_raffle` (see [backend/rpcs.md](./backend/rpcs.md)). The deprecated AI stub is no longer client-callable; generation uses authenticated [sidecar routes](./backend/feedback-ai.md). diff --git a/docs/backend/rpcs.md b/docs/backend/rpcs.md index bf4a662..87fe9b6 100644 --- a/docs/backend/rpcs.md +++ b/docs/backend/rpcs.md @@ -394,6 +394,31 @@ All are `security definer` so they can read `contacts` / `registrations` / |---|---|---| | `_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). + ## Error handling RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot diff --git a/docs/backend/tests.md b/docs/backend/tests.md index 53dadac..d1c5884 100644 --- a/docs/backend/tests.md +++ b/docs/backend/tests.md @@ -1,3 +1,24 @@ +# Raffle Regression + +After applying `20261015180640_raffle`, run: + +```sh +docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres \ + -v ON_ERROR_STOP=1 < supabase/tests/raffle_tests.sql +CONVIVO_ADMIN_URL=http://127.0.0.1:3001 npm test --prefix e2e -- raffle.spec.ts --project=chromium +``` + +The SQL fixture is rollback-only: fifteen assertions cover the eligible pool +(excluding staff, Admin, the `@appe.at` domain and the leaderboard top 3), +sequential draw numbers, drawn attendees leaving the pool, the empty-pool +over-draw error, winner persistence, run reset, and admin/non-admin/anon +authorization. The browser suite is API-mocked and covers the default five +picks, the decelerating roulette landing on a winner, drawing until the pick +count, retry after a failed draw, starting a new run, a configurable pick +count, and the mobile layout. No real LLM, email or points change is involved. + +See [RPC rules](./rpcs.md#raffle) and the [Raffle view](../frontend/admin-app.md). + # Leaderboard Regression After applying `20261015164546_leaderboard_staff_admin_exclusion`, run: diff --git a/docs/frontend/admin-app.md b/docs/frontend/admin-app.md index 63ac31e..b9ad4ed 100644 --- a/docs/frontend/admin-app.md +++ b/docs/frontend/admin-app.md @@ -20,6 +20,7 @@ It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container | **Sponsors** | List (paid only visible to attendees; admin sees all). Add/edit (type, name, email, phone, paid, amount, **contact search-and-pick**). | | **Schedule** | Slots (with a **type optionset** β€” `Session` / `Service Session`) + sessions (with speakers 1:N via a **multi-select search dropdown**, material upload with a **submitted / not submitted** state and `average_feedback`), plus an admin-only **Delete current schedule** action for the active event. | | **Activity** | Tables of check-ins, connections, and feedback (per active event), with manual **Generate AI Summary** controls for the event and individual sessions. | +| **Raffle** | Draws eligible attendees one at a time for the active event. Configure the number of picks (default 5), then **Spin** a roulette that decelerates onto a server-chosen winner; repeat until the pick count is reached. Excludes staff/Admin and the leaderboard top 3, and no one can win twice in a run. **New run** clears the current winners. See [../backend/rpcs.md#raffle](../backend/rpcs.md#raffle). | | **Settings** | Global LLM endpoint, model and optional API key for feedback summaries. | | **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time β€” activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. | | **Interfaces** | Manages the Sessionize sync **sidecar**: status (online / running / last run), a **Run sync** control (event picker + blocking run + result modal), an **Import Excel** control (upload the Sessionize "Sessions and speakers (advanced)" `.xlsx` + a "How to get this file" tooltip), and a **Recent runs** table from `sync_runs`. See [../backend/sidecar.md](../backend/sidecar.md). | diff --git a/e2e/tests/raffle.spec.ts b/e2e/tests/raffle.spec.ts new file mode 100644 index 0000000..ba46187 --- /dev/null +++ b/e2e/tests/raffle.spec.ts @@ -0,0 +1,130 @@ +import { test, expect, type Page } from '@playwright/test'; + +const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001'; +const eventId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; +const user = { id: '99999999-9999-4999-8999-999999999999', email: 'admin@appe.at', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} }; + +interface Options { poolSize?: number; fail?: boolean; } + +async function openRaffle(page: Page, options: Options = {}) { + const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url'); + const session = { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test`, refresh_token: 'mock-refresh-token', expires_in: 3600, token_type: 'bearer' }; + const event = { id: eventId, name: 'Raffle Conference', is_active: true, start_date: '2026-10-23', end_date: '2026-10-23', num_registrations: 8, num_sessions: 0, num_speakers: 0 }; + const poolSize = options.poolSize ?? 4; + const pool = Array.from({ length: poolSize }, (_v, i) => ({ contact_email: `attendee-${i}@example.com`, full_name: `Attendee ${i + 1}`, points: 10 - i })); + const winners: Record[] = []; + const draws: string[] = []; + let resets = 0; + + await page.route('**/auth/v1/**', route => route.fulfill({ json: new URL(route.request().url()).pathname.endsWith('/user') ? user : session })); + await page.route('**/rest/v1/**', route => { + const url = new URL(route.request().url()); + if (url.pathname.endsWith('/rpc/get_raffle_pool')) { + return route.fulfill({ json: pool.filter(e => !winners.some(w => w.contact_email === e.contact_email)) }); + } + if (url.pathname.endsWith('/rpc/draw_raffle_winner')) { + draws.push('draw'); + if (options.fail) return route.fulfill({ status: 400, json: { code: 'P0001', message: 'No eligible attendees left to draw' } }); + const remaining = pool.filter(e => !winners.some(w => w.contact_email === e.contact_email)); + if (remaining.length === 0) return route.fulfill({ status: 400, json: { code: 'P0001', message: 'No eligible attendees left to draw' } }); + const winner = remaining[0]; + const row = { ...winner, draw_number: winners.length + 1, drawn_at: '2026-10-23T16:00:00Z' }; + winners.push(row); + return route.fulfill({ json: [row] }); + } + if (url.pathname.endsWith('/rpc/reset_raffle')) { resets += 1; winners.length = 0; return route.fulfill({ json: null }); } + if (url.pathname.endsWith('/raffle_draws')) return route.fulfill({ json: winners }); + if (url.pathname.endsWith('/events')) return route.fulfill({ json: url.searchParams.has('is_active') ? event : [event] }); + if (url.pathname.endsWith('/contacts')) { + const contact = { email: user.email, full_name: 'Admin', is_admin: true }; + return route.fulfill({ json: url.searchParams.has('email') ? contact : [contact] }); + } + return route.fulfill({ json: [] }); + }); + + await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`); + await expect(page.locator('.nav').getByRole('button', { name: /Dashboard/ })).toBeVisible(); + await page.locator('.nav').getByRole('button', { name: /Raffle/ }).click(); + return { draws, resetCount: () => resets, winnerCount: () => winners.length }; +} + +test('raffle defaults to five picks and excludes staff, admin and the top three', async ({ page }, testInfo) => { + await page.setViewportSize({ width: 1280, height: 900 }); + await openRaffle(page); + await expect(page.getByRole('heading', { name: 'Raffle' })).toBeVisible(); + await expect(page.getByLabel('Picks per run')).toHaveValue('5'); + await expect(page.getByText('Winners this run: 0 of 5')).toBeVisible(); + await expect(page.getByText('Excludes staff/Admin and the leaderboard top 3.')).toBeVisible(); + await expect(page.getByRole('button', { name: 'Spin', exact: true })).toBeEnabled(); + await page.screenshot({ path: testInfo.outputPath('raffle-idle.png'), fullPage: true }); +}); + +test('spinning decelerates onto a winner and removes them from the pool', async ({ page }, testInfo) => { + await page.setViewportSize({ width: 1280, height: 900 }); + const { draws } = await openRaffle(page); + const spin = page.getByRole('button', { name: 'Spin', exact: true }); + await spin.click(); + await expect(page.getByRole('button', { name: 'Spinning...' })).toBeVisible(); + await expect(page.getByRole('status').filter({ hasText: /^Attendee/ }).first()).toBeVisible(); + await expect(page.getByRole('button', { name: 'Spin', exact: true })).toBeEnabled(); + expect(draws).toHaveLength(1); + await expect(page.getByText('Winners this run: 1 of 5')).toBeVisible(); + await expect(page.getByRole('cell', { name: 'Attendee 1', exact: true })).toBeVisible(); + await expect(page.getByText('attendee-0@example.com')).toHaveCount(0); + await expect(page.locator('canvas')).toBeVisible(); + await page.screenshot({ path: testInfo.outputPath('raffle-winner.png'), fullPage: true }); +}); + +test('draws continue until the pick count is reached, then the run is complete', async ({ page }) => { + const { draws } = await openRaffle(page, { poolSize: 3 }); + for (let i = 1; i <= 3; i += 1) { + await page.getByRole('button', { name: 'Spin', exact: true }).click(); + await expect(page.getByText(`Winners this run: ${i} of 5`)).toBeVisible(); + } + expect(draws).toHaveLength(3); + await expect(page.getByRole('button', { name: 'No attendees left', exact: true })).toBeDisabled(); + await expect(page.getByText('no eligible attendees left')).toBeVisible(); +}); + +test('a failed draw keeps the previous winners and allows retry', async ({ page }) => { + const { draws, winnerCount } = await openRaffle(page, { fail: true }); + await page.getByRole('button', { name: 'Spin', exact: true }).click(); + await expect(page.getByRole('alert')).toHaveText('No eligible attendees left to draw'); + await expect(page.getByRole('button', { name: 'Spin', exact: true })).toBeEnabled(); + expect(draws).toHaveLength(1); + expect(winnerCount()).toBe(0); +}); + +test('starting a new run clears the winners and re-enables drawing', async ({ page }) => { + const { resetCount } = await openRaffle(page); + await page.getByRole('button', { name: 'Spin', exact: true }).click(); + await expect(page.getByText('Winners this run: 1 of 5')).toBeVisible(); + await page.getByRole('button', { name: 'New run', exact: true }).click(); + await expect(page.getByText('Winners this run: 0 of 5')).toBeVisible(); + await expect(page.getByRole('cell', { name: 'Attendee 1' })).toHaveCount(0); + expect(resetCount()).toBe(1); +}); + +test('the pick count is configurable before the run starts', async ({ page }) => { + await openRaffle(page); + await page.getByLabel('Picks per run').fill('2'); + await expect(page.getByText('Winners this run: 0 of 2')).toBeVisible(); + await page.getByRole('button', { name: 'Spin', exact: true }).click(); + await expect(page.getByText('Winners this run: 1 of 2')).toBeVisible(); + await page.getByRole('button', { name: 'Spin', exact: true }).click(); + await expect(page.getByRole('region', { name: 'Raffle winners' }).getByText('Run complete', { exact: true })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Run complete', exact: true })).toBeDisabled(); +}); + +test('raffle controls fit a mobile viewport', async ({ page }, testInfo) => { + await page.setViewportSize({ width: 390, height: 844 }); + await openRaffle(page); + const stage = page.getByRole('region', { name: 'Raffle roulette' }); + await expect(stage).toBeVisible(); + const bounds = await stage.boundingBox(); + expect(bounds).not.toBeNull(); + expect(bounds!.x).toBeGreaterThanOrEqual(0); + expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390); + expect(await stage.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true); + await page.screenshot({ path: testInfo.outputPath('raffle-mobile.png'), fullPage: true }); +}); diff --git a/supabase/migrations/20261015180640_raffle.sql b/supabase/migrations/20261015180640_raffle.sql new file mode 100644 index 0000000..ff14066 --- /dev/null +++ b/supabase/migrations/20261015180640_raffle.sql @@ -0,0 +1,87 @@ +-- ----------------------------------------------------------------------------- +-- Admin raffle. +-- +-- Draws eligible attendees one at a time for the active event. The pool +-- excludes staff/Admin contacts (same rule as scoring eligibility), the top 3 +-- of the leaderboard, and anyone already drawn in the current run. A run is +-- the set of winners recorded for the event; `reset_raffle` clears it so a new +-- run can begin. Winner selection is authoritative server-side (random), so +-- the client roulette animation only has to decelerate onto the returned name. +-- ----------------------------------------------------------------------------- + +create table public.raffle_draws ( + event_id uuid not null references public.events (id) on delete cascade, + contact_email text not null references public.contacts (email) on delete cascade, + full_name text not null, + draw_number integer not null check (draw_number > 0), + drawn_at timestamptz not null default now(), + primary key (event_id, contact_email) +); + +create index raffle_draws_event_id_idx on public.raffle_draws (event_id); + +alter table public.raffle_draws enable row level security; +revoke all on public.raffle_draws from public, anon, authenticated; +grant select on public.raffle_draws to authenticated; +create policy raffle_draws_admin_read on public.raffle_draws + for select to authenticated using ((select public.is_admin())); + +-- Eligible attendees for the active event: non-staff, non-Admin, not in the +-- leaderboard top 3, and not already drawn in the current run. +create or replace function public.get_raffle_pool() +returns table (contact_email text, full_name text, points integer) +language sql stable security definer set search_path = '' as $$ + select c.email, c.full_name, r.points + from public.registrations r + join public.contacts c on c.email = r.contact_email + join public.events e on e.id = r.event_id and e.is_active + where public.is_admin() + and r.type <> 'staff' and not c.is_admin and c.email not like '%@appe.at' + and c.email not in (select l.contact_email from public.get_leaderboard() l limit 3) + and c.email not in (select d.contact_email from public.raffle_draws d) + order by c.full_name, c.email; +$$; + +-- Draw one random eligible attendee and record them as the next winner. +create or replace function public.draw_raffle_winner() +returns table (contact_email text, full_name text, points integer, draw_number integer) +language plpgsql security definer set search_path = '' as $$ +declare + v_event uuid; + v_email text; + v_name text; + v_points integer; + v_num integer; +begin + if not public.is_admin() then raise exception 'admin only'; end if; + select id into v_event from public.events where is_active limit 1; + if v_event is null then raise exception 'no active event'; end if; + select p.contact_email, p.full_name, p.points into v_email, v_name, v_points + from public.get_raffle_pool() p order by random() limit 1; + if v_email is null then raise exception 'No eligible attendees left to draw'; end if; + select coalesce(max(d.draw_number), 0) + 1 into v_num + from public.raffle_draws d where d.event_id = v_event; + insert into public.raffle_draws (event_id, contact_email, full_name, draw_number) + values (v_event, v_email, v_name, v_num); + return query select v_email, v_name, v_points, v_num; +end; +$$; + +-- Clear the current run's winners so a new run can begin. +create or replace function public.reset_raffle() +returns void +language plpgsql security definer set search_path = '' as $$ +declare + v_event uuid; +begin + if not public.is_admin() then raise exception 'admin only'; end if; + select id into v_event from public.events where is_active limit 1; + if v_event is null then raise exception 'no active event'; end if; + delete from public.raffle_draws where event_id = v_event; +end; +$$; + +revoke all on function public.get_raffle_pool(), public.draw_raffle_winner(), public.reset_raffle() + from public, anon; +grant execute on function public.get_raffle_pool(), public.draw_raffle_winner(), public.reset_raffle() + to authenticated; diff --git a/supabase/tests/raffle_tests.sql b/supabase/tests/raffle_tests.sql new file mode 100644 index 0000000..c0228fa --- /dev/null +++ b/supabase/tests/raffle_tests.sql @@ -0,0 +1,127 @@ +\set ON_ERROR_STOP on +begin; + +create temporary table raffle_results (name text); +grant insert on raffle_results to authenticated, anon; +create function pg_temp.assert_raffle(p_condition boolean, p_name text) returns void +language plpgsql as $$ +begin + if p_condition is distinct from true then raise exception 'FAIL: %', p_name; end if; + insert into raffle_results values (p_name); +end; +$$; + +-- Isolate a single active event for the run. +update public.events set is_active = false where is_active; +insert into public.events (id, name, start_date, end_date, is_active) +values ('b0ff1e00-0000-0000-0000-000000000001', 'Raffle regression', current_date, current_date, true); + +insert into public.contacts (email, full_name, is_admin) values + ('rf-top1@example.test', 'Top One', false), + ('rf-top2@example.test', 'Top Two', false), + ('rf-top3@example.test', 'Top Three', false), + ('rf-low1@example.test', 'Low One', false), + ('rf-low2@example.test', 'Low Two', false), + ('rf-staff@example.test', 'Staff Person', false), + ('rf-admin@example.test', 'Admin Person', true), + ('rf-domain@appe.at', 'Domain Person', false), + ('rf-viewer@example.test', 'Plain Viewer', false); + +insert into public.registrations (event_id, contact_email, type, points) values + ('b0ff1e00-0000-0000-0000-000000000001', 'rf-top1@example.test', 'attendee', 100), + ('b0ff1e00-0000-0000-0000-000000000001', 'rf-top2@example.test', 'attendee', 90), + ('b0ff1e00-0000-0000-0000-000000000001', 'rf-top3@example.test', 'attendee', 80), + ('b0ff1e00-0000-0000-0000-000000000001', 'rf-low1@example.test', 'attendee', 10), + ('b0ff1e00-0000-0000-0000-000000000001', 'rf-low2@example.test', 'attendee', 5), + ('b0ff1e00-0000-0000-0000-000000000001', 'rf-staff@example.test', 'staff', 999), + ('b0ff1e00-0000-0000-0000-000000000001', 'rf-admin@example.test', 'attendee', 500), + ('b0ff1e00-0000-0000-0000-000000000001', 'rf-domain@appe.at', 'attendee', 500); + +-- Act as the raffle admin. +select set_config('request.jwt.claims', '{"email":"rf-admin@example.test","role":"authenticated"}', true); + +-- The pool excludes staff, Admin, the @appe.at domain and the leaderboard top 3, +-- leaving exactly the two low-point eligible attendees. +select pg_temp.assert_raffle( + (select array_agg(contact_email order by contact_email) = + array['rf-low1@example.test','rf-low2@example.test'] from public.get_raffle_pool()), + 'pool excludes staff, admin, domain and top 3'); + +-- Draw one: winner is an eligible non-top attendee, recorded with draw_number 1. +create temporary table draw1 as select * from public.draw_raffle_winner(); +select pg_temp.assert_raffle( + (select contact_email in ('rf-low1@example.test','rf-low2@example.test') from draw1), + 'first draw returns an eligible attendee'); +select pg_temp.assert_raffle((select draw_number = 1 from draw1), 'first draw number is one'); +select pg_temp.assert_raffle( + (select count(*) = 1 from public.get_raffle_pool()), 'drawn attendee leaves the pool'); + +-- Draw two: the remaining eligible attendee, draw_number 2, pool now empty. +create temporary table draw2 as select * from public.draw_raffle_winner(); +select pg_temp.assert_raffle( + (select contact_email <> (select contact_email from draw1) + and contact_email in ('rf-low1@example.test','rf-low2@example.test') from draw2), + 'second draw is a different eligible attendee'); +select pg_temp.assert_raffle((select draw_number = 2 from draw2), 'second draw number is two'); +select pg_temp.assert_raffle((select count(*) = 0 from public.get_raffle_pool()), 'pool empty after all eligible drawn'); + +-- A third draw with no eligible attendees left fails clearly. +do $$ begin + begin + perform public.draw_raffle_winner(); + raise exception 'over-draw allowed'; + exception when raise_exception then + if sqlerrm <> 'No eligible attendees left to draw' then raise; end if; + end; + perform pg_temp.assert_raffle(true, 'over-draw rejected'); +end; $$; + +-- Winners persisted, none excluded, sequential numbers. +select pg_temp.assert_raffle( + (select count(*) = 2 and bool_and(contact_email in ('rf-low1@example.test','rf-low2@example.test')) + and count(distinct draw_number) = 2 from public.raffle_draws), + 'winners persisted without excluded attendees'); + +-- Reset clears the run so the same attendees become eligible again. +select public.reset_raffle(); +select pg_temp.assert_raffle( + (select count(*) = 0 from public.raffle_draws), 'reset clears winners'); +select pg_temp.assert_raffle( + (select count(*) = 2 from public.get_raffle_pool()), 'reset restores the pool'); + +-- Non-admin authenticated users cannot see the pool or draw. +select set_config('request.jwt.claims', '{"email":"rf-viewer@example.test","role":"authenticated"}', true); +select pg_temp.assert_raffle((select count(*) = 0 from public.get_raffle_pool()), 'non-admin sees empty pool'); +select pg_temp.assert_raffle((select count(*) = 0 from public.raffle_draws), 'non-admin cannot read winners'); +do $$ begin + begin + perform public.draw_raffle_winner(); + raise exception 'non-admin draw allowed'; + exception when raise_exception then + if sqlerrm <> 'admin only' then raise; end if; + end; + begin + perform public.reset_raffle(); + raise exception 'non-admin reset allowed'; + exception when raise_exception then + if sqlerrm <> 'admin only' then raise; end if; + end; + perform pg_temp.assert_raffle(true, 'non-admin cannot draw or reset'); +end; $$; + +-- The anonymous API role has no execute grant at all. +reset role; +select set_config('request.jwt.claims', '{"role":"anon"}', true); +set local role anon; +do $$ begin + begin + perform public.draw_raffle_winner(); + raise exception 'anon draw allowed'; + exception when insufficient_privilege then null; + end; + perform pg_temp.assert_raffle(true, 'anon cannot execute raffle functions'); +end; $$; +reset role; + +select count(*) as passed_assertions from raffle_results; +rollback;