feat: add admin raffle with confetti and top-3/staff exclusion

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
This commit is contained in:
committed 2026-10-15 21:39:57 +02:00
1 parent 4cf09cd739
commit 4ec03410ff
14 files changed
+680 -2

No files matched your search

+206
View File
@@ -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>
);
}