feat: add admin raffle with confetti and top-3/staff exclusion
This commit is contained in:
1 parent
5117a25372
commit
3e2f8ff0ed
14 files changed
+680
-2
No files matched your search
Generated
+19
@@ -9,12 +9,14 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@supabase/supabase-js": "^2.45.4",
|
"@supabase/supabase-js": "^2.45.4",
|
||||||
|
"canvas-confetti": "1.9.3",
|
||||||
"lucide-react": "0.468.0",
|
"lucide-react": "0.468.0",
|
||||||
"qrcode.react": "^4.0.1",
|
"qrcode.react": "^4.0.1",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1"
|
"react-dom": "^18.3.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/canvas-confetti": "1.6.4",
|
||||||
"@types/react": "^18.3.5",
|
"@types/react": "^18.3.5",
|
||||||
"@types/react-dom": "^18.3.0",
|
"@types/react-dom": "^18.3.0",
|
||||||
"@vitejs/plugin-react": "^4.3.1",
|
"@vitejs/plugin-react": "^4.3.1",
|
||||||
@@ -1298,6 +1300,13 @@
|
|||||||
"@babel/types": "^7.28.2"
|
"@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": {
|
"node_modules/@types/estree": {
|
||||||
"version": "1.0.9",
|
"version": "1.0.9",
|
||||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
|
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
|
||||||
@@ -1422,6 +1431,16 @@
|
|||||||
],
|
],
|
||||||
"license": "CC-BY-4.0"
|
"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": {
|
"node_modules/convert-source-map": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
|
||||||
|
|||||||
@@ -10,12 +10,14 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@supabase/supabase-js": "^2.45.4",
|
"@supabase/supabase-js": "^2.45.4",
|
||||||
|
"canvas-confetti": "1.9.3",
|
||||||
"lucide-react": "0.468.0",
|
"lucide-react": "0.468.0",
|
||||||
"qrcode.react": "^4.0.1",
|
"qrcode.react": "^4.0.1",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1"
|
"react-dom": "^18.3.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/canvas-confetti": "1.6.4",
|
||||||
"@types/react": "^18.3.5",
|
"@types/react": "^18.3.5",
|
||||||
"@types/react-dom": "^18.3.0",
|
"@types/react-dom": "^18.3.0",
|
||||||
"@vitejs/plugin-react": "^4.3.1",
|
"@vitejs/plugin-react": "^4.3.1",
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { Registrations } from './views/Registrations';
|
|||||||
import { Sponsors } from './views/Sponsors';
|
import { Sponsors } from './views/Sponsors';
|
||||||
import { Schedule } from './views/Schedule';
|
import { Schedule } from './views/Schedule';
|
||||||
import { Activity } from './views/Activity';
|
import { Activity } from './views/Activity';
|
||||||
|
import { Raffle } from './views/Raffle';
|
||||||
import { Events } from './views/Events';
|
import { Events } from './views/Events';
|
||||||
import { Interfaces } from './views/Interfaces';
|
import { Interfaces } from './views/Interfaces';
|
||||||
import { Reports } from './views/Reports';
|
import { Reports } from './views/Reports';
|
||||||
@@ -22,6 +23,7 @@ export type View =
|
|||||||
| 'sponsors'
|
| 'sponsors'
|
||||||
| 'schedule'
|
| 'schedule'
|
||||||
| 'activity'
|
| 'activity'
|
||||||
|
| 'raffle'
|
||||||
| 'events'
|
| 'events'
|
||||||
| 'interfaces'
|
| 'interfaces'
|
||||||
| 'reports'
|
| 'reports'
|
||||||
@@ -34,6 +36,7 @@ const NAV: { id: View; label: string; ico: string }[] = [
|
|||||||
{ id: 'sponsors', label: 'Sponsors', ico: '🤝' },
|
{ id: 'sponsors', label: 'Sponsors', ico: '🤝' },
|
||||||
{ id: 'schedule', label: 'Schedule', ico: '🗓️' },
|
{ id: 'schedule', label: 'Schedule', ico: '🗓️' },
|
||||||
{ id: 'activity', label: 'Activity', ico: '⚡' },
|
{ id: 'activity', label: 'Activity', ico: '⚡' },
|
||||||
|
{ id: 'raffle', label: 'Raffle', ico: '🎯' },
|
||||||
{ id: 'events', label: 'Events', ico: '📅' },
|
{ id: 'events', label: 'Events', ico: '📅' },
|
||||||
{ id: 'interfaces', label: 'Interfaces', ico: '🔌' },
|
{ id: 'interfaces', label: 'Interfaces', ico: '🔌' },
|
||||||
{ id: 'reports', label: 'Reports', ico: '📤' },
|
{ id: 'reports', label: 'Reports', ico: '📤' },
|
||||||
@@ -104,6 +107,7 @@ function Shell() {
|
|||||||
{view === 'sponsors' && <Sponsors />}
|
{view === 'sponsors' && <Sponsors />}
|
||||||
{view === 'schedule' && <Schedule />}
|
{view === 'schedule' && <Schedule />}
|
||||||
{view === 'activity' && <Activity />}
|
{view === 'activity' && <Activity />}
|
||||||
|
{view === 'raffle' && <Raffle />}
|
||||||
{view === 'events' && <Events />}
|
{view === 'events' && <Events />}
|
||||||
{view === 'interfaces' && <Interfaces />}
|
{view === 'interfaces' && <Interfaces />}
|
||||||
{view === 'reports' && <Reports />}
|
{view === 'reports' && <Reports />}
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ import type {
|
|||||||
PointsLogRow,
|
PointsLogRow,
|
||||||
PretixOptions,
|
PretixOptions,
|
||||||
PretixSyncResult,
|
PretixSyncResult,
|
||||||
|
RafflePoolEntry,
|
||||||
|
RaffleWinner,
|
||||||
Registration,
|
Registration,
|
||||||
ResetQrResult,
|
ResetQrResult,
|
||||||
Session,
|
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 });
|
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<RafflePoolEntry[]> {
|
||||||
|
return rpc<RafflePoolEntry[]>('get_raffle_pool', {});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Winners already drawn in the current run (oldest first). */
|
||||||
|
export async function getRaffleWinners(): Promise<RaffleWinner[]> {
|
||||||
|
return all<RaffleWinner>('raffle_draws', { col: 'draw_number' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Draw one random eligible attendee and record them as the next winner. */
|
||||||
|
export async function drawRaffleWinner(): Promise<RaffleWinner> {
|
||||||
|
const rows = await rpc<Omit<RaffleWinner, 'drawn_at'>[]>('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<void> {
|
||||||
|
await rpc('reset_raffle', {});
|
||||||
|
}
|
||||||
|
|
||||||
// ---- Sessions: speakers, material, AI feedback -------------------------------
|
// ---- Sessions: speakers, material, AI feedback -------------------------------
|
||||||
|
|
||||||
export async function setSessionSpeakers(sessionId: string, emails: string[]): Promise<void> {
|
export async function setSessionSpeakers(sessionId: string, emails: string[]): Promise<void> {
|
||||||
|
|||||||
@@ -330,3 +330,16 @@ export interface ResetQrResult {
|
|||||||
email: string;
|
email: string;
|
||||||
qr_token: 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;
|
||||||
|
}
|
||||||
@@ -12,6 +12,20 @@
|
|||||||
@media (max-width: 760px) {
|
@media (max-width: 760px) {
|
||||||
.seg.activity-tabs { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
.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; }
|
* { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||||
:root {
|
:root {
|
||||||
--bg: #f0f2f6; --surface: #ffffff; --surface-2: #f4f5f9;
|
--bg: #f0f2f6; --surface: #ffffff; --surface-2: #f4f5f9;
|
||||||
|
|||||||
@@ -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<Event | null>(null);
|
||||||
|
const [pool, setPool] = useState<RafflePoolEntry[]>([]);
|
||||||
|
const [winners, setWinners] = useState<RaffleWinner[]>([]);
|
||||||
|
const [picks, setPicks] = useState(DEFAULT_PICKS);
|
||||||
|
const [loaded, setLoaded] = useState(false);
|
||||||
|
const [spinning, setSpinning] = useState(false);
|
||||||
|
const [currentName, setCurrentName] = useState<string | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const running = useRef(false);
|
||||||
|
const timer = useRef<ReturnType<typeof setTimeout> | 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 <Empty icon="⚠️" text={error} />;
|
||||||
|
if (!loaded) return <div className="loading-screen"><Spinner /></div>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="page-head">
|
||||||
|
<div>
|
||||||
|
<h1>Raffle</h1>
|
||||||
|
<div className="sub">
|
||||||
|
{event ? `${event.name} · ${total} eligible attendees` : 'No active event. Set an event active in the Events view first.'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!event ? (
|
||||||
|
<div className="card"><Empty icon="🎟️" text="No active event. Set an event active in the Events view first." /></div>
|
||||||
|
) : (
|
||||||
|
<div className="raffle">
|
||||||
|
<section className="raffle-stage card" aria-label="Raffle roulette">
|
||||||
|
<div className="raffle-name" role="status" aria-live="polite">
|
||||||
|
{currentName ?? 'Press Spin to draw a winner'}
|
||||||
|
</div>
|
||||||
|
<div className="raffle-controls">
|
||||||
|
<label className="field raffle-picks">
|
||||||
|
<span>Picks per run</span>
|
||||||
|
<input
|
||||||
|
className="input"
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={Math.max(1, total)}
|
||||||
|
value={picks}
|
||||||
|
disabled={spinning || winners.length > 0}
|
||||||
|
onChange={(e) => setPicks(Math.max(1, Number(e.target.value) || 1))}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button className="btn primary" onClick={draw} disabled={!canDraw}>
|
||||||
|
<RotateCw size={16} aria-hidden="true" className={spinning ? 'raffle-spin-icon' : undefined} />
|
||||||
|
{spinning ? 'Spinning...' : winners.length >= picks ? 'Run complete' : pool.length === 0 ? 'No attendees left' : 'Spin'}
|
||||||
|
</button>
|
||||||
|
<button className="btn" onClick={reset} disabled={spinning || winners.length === 0}>
|
||||||
|
<RotateCcw size={16} aria-hidden="true" />New run
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="muted small" role="status">
|
||||||
|
Winners this run: {winners.length} of {picks}
|
||||||
|
{winners.length < picks && pool.length === 0 && ' · no eligible attendees left'}
|
||||||
|
</p>
|
||||||
|
{error && <p className="feedback-error" role="alert">{error}</p>}
|
||||||
|
<p className="muted small">
|
||||||
|
Excludes staff/Admin and the leaderboard top 3. Everyone can win only once per run.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="card" aria-label="Raffle winners">
|
||||||
|
<div className="feedback-summary-head">
|
||||||
|
<h2 className="h2">Winners</h2>
|
||||||
|
<span className="muted small">{remainingForRun > 0 ? `${remainingForRun} to go` : 'Run complete'}</span>
|
||||||
|
</div>
|
||||||
|
{winners.length === 0 ? (
|
||||||
|
<Empty icon="🏆" text="No winners yet. Spin the roulette to draw the first attendee." />
|
||||||
|
) : (
|
||||||
|
<div className="table-wrap">
|
||||||
|
<table className="data">
|
||||||
|
<thead>
|
||||||
|
<tr><th>#</th><th>Attendee</th><th>Points</th><th>When</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{winners.map((w) => (
|
||||||
|
<tr key={w.contact_email}>
|
||||||
|
<td className="muted">{w.draw_number}</td>
|
||||||
|
<td style={{ fontWeight: 600 }}>{w.full_name}</td>
|
||||||
|
<td>{w.points}</td>
|
||||||
|
<td className="muted">{new Date(w.drawn_at).toLocaleTimeString()}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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):
|
with **`is_admin`** or an **`@appe.at`** email. See [frontend/admin-app.md](./frontend/admin-app.md):
|
||||||
- **Views** — Dashboard (active event + aggregates), Contacts, Registrations,
|
- **Views** — Dashboard (active event + aggregates), Contacts, Registrations,
|
||||||
Sponsors, Schedule (slots/sessions/speakers/material), Activity (manual event
|
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.
|
- **Auth guard** — email-only magic links; non-admin sessions are rejected.
|
||||||
- **Key RPCs** — `reset_registration_qr_token` (regenerate a registration's
|
- **Key RPCs** — `reset_registration_qr_token` (regenerate a registration's
|
||||||
lanyard token + sync the Auth password), `adjust_points`, `upsert_contact`,
|
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
|
(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).
|
client-callable; generation uses authenticated [sidecar routes](./backend/feedback-ai.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. |
|
| `_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
|
## Error handling
|
||||||
|
|
||||||
RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot
|
RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot
|
||||||
|
|||||||
@@ -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
|
# Leaderboard Regression
|
||||||
|
|
||||||
After applying `20261015164546_leaderboard_staff_admin_exclusion`, run:
|
After applying `20261015164546_leaderboard_staff_admin_exclusion`, run:
|
||||||
|
|||||||
@@ -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**). |
|
| **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. |
|
| **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. |
|
| **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. |
|
| **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. |
|
| **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). |
|
| **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). |
|
||||||
|
|||||||
@@ -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: '[email protected]', 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<string, unknown>[] = [];
|
||||||
|
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('[email protected]')).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 });
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
@@ -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
|
||||||
|
('[email protected]', 'Top One', false),
|
||||||
|
('[email protected]', 'Top Two', false),
|
||||||
|
('[email protected]', 'Top Three', false),
|
||||||
|
('[email protected]', 'Low One', false),
|
||||||
|
('[email protected]', 'Low Two', false),
|
||||||
|
('[email protected]', 'Staff Person', false),
|
||||||
|
('[email protected]', 'Admin Person', true),
|
||||||
|
('[email protected]', 'Domain Person', false),
|
||||||
|
('[email protected]', 'Plain Viewer', false);
|
||||||
|
|
||||||
|
insert into public.registrations (event_id, contact_email, type, points) values
|
||||||
|
('b0ff1e00-0000-0000-0000-000000000001', '[email protected]', 'attendee', 100),
|
||||||
|
('b0ff1e00-0000-0000-0000-000000000001', '[email protected]', 'attendee', 90),
|
||||||
|
('b0ff1e00-0000-0000-0000-000000000001', '[email protected]', 'attendee', 80),
|
||||||
|
('b0ff1e00-0000-0000-0000-000000000001', '[email protected]', 'attendee', 10),
|
||||||
|
('b0ff1e00-0000-0000-0000-000000000001', '[email protected]', 'attendee', 5),
|
||||||
|
('b0ff1e00-0000-0000-0000-000000000001', '[email protected]', 'staff', 999),
|
||||||
|
('b0ff1e00-0000-0000-0000-000000000001', '[email protected]', 'attendee', 500),
|
||||||
|
('b0ff1e00-0000-0000-0000-000000000001', '[email protected]', 'attendee', 500);
|
||||||
|
|
||||||
|
-- Act as the raffle admin.
|
||||||
|
select set_config('request.jwt.claims', '{"email":"[email protected]","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['[email protected]','[email protected]'] 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 ('[email protected]','[email protected]') 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 ('[email protected]','[email protected]') 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 ('[email protected]','[email protected]'))
|
||||||
|
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":"[email protected]","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;
|
||||||
Reference in new issue
Block a user