Phase 0: scaffold Next.js, Tailwind tokens, Supabase clients, env validation

Next.js 16 App Router with strict TypeScript, Tailwind 4 theme tokens from
docs/UI.md, Vitest, and the three Supabase clients. Env vars are validated
with zod in next.config.ts so dev and build fail fast with a readable error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-03 12:27:11 +02:00
co-authored by Claude Opus 5.5
commit c89a82295b
29 changed files with 9107 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
# Architecture
## Stack
Next.js (App Router) on Vercel · Supabase (Postgres + Auth + Realtime Broadcast) · Tailwind · zod · Vitest.
## Routes
| Route | Who | Notes |
|---|---|---|
| `/login` | admin | Supabase magic link |
| `/admin` | admin | Events list |
| `/admin/events/[eventId]` | admin | Setup: teams, games, criteria, judges, share links |
| `/admin/events/[eventId]/live` | admin | Control room |
| `/s/[scoreboardToken]` | public | Scoreboard |
| `/j/[judgeToken]` | judge | Personal judge page |
| `/jo/[openToken]` | judge | Open link → name form |
| `GET /api/public/scoreboard/[token]` | public | Sanitised scoreboard payload |
| `GET /api/judge/[token]` | judge | Game, criteria, teams, this judge's scores |
| `PUT /api/judge/[token]/scores` | judge | Upsert one score `{teamId, criterionId, value}` |
| `POST /api/judge-open/[openToken]` | judge | `{name}` → `{judgeToken}` |
Admin mutations = server actions. Middleware protects `/admin/*`: must be logged in AND email in `ADMIN_EMAILS`.
## Supabase clients (`src/lib/supabase/`)
- `browser.ts` — anon key, used for Realtime subscribe + admin auth session.
- `server.ts` — cookie-based, for admin server actions (RLS applies as the admin user).
- `admin.ts` — service role, **server-only** (`import 'server-only'`). Used by public/judge route handlers after token validation.
## Security model
- RLS ON for every table. Policies only for the authenticated event owner. Anon role has no policies → no direct table access.
- Public/judge access = token in URL → route handler validates with zod → service-role query scoped by that token.
- Judge write checks: judge not revoked, game not locked/done, criterion belongs to judge's game, team belongs to the game's event, value within min/max and on step. (DB trigger also enforces range.)
- Scoreboard API checks `scoreboard_visibility` and strips scores when `hidden`; returns `frozen_snapshot` when `frozen`.
- Light rate limiting on judge PUT (e.g. 20 req/s per token, in-memory is fine for v1).
## Realtime (Broadcast "ping then refetch")
Channels (names use tokens/ids; payload is always just `{ type: "refresh", scope }`):
- `sb:{scoreboardToken}` — scoreboard listens
- `game:{gameId}` — all judges of that game listen
- `admin:{eventId}` — admin control room listens (judge submissions land here)
`src/lib/realtime.ts` exposes `notify({ eventId, gameId? })` which looks up the scoreboard token and sends to the right channels from the server.
Use Supabase's server-side broadcast (REST endpoint / `httpSend` — check current docs).
Debounce refetches client-side (~150ms) so a burst of taps causes one fetch.
Clients also poll every 10s as a safety net, and refetch on reconnect / tab focus.
## Scoring engine (`src/lib/scoring/`)
Pure TS, no DB access. Input = plain data (teams, games, criteria, scores, adjustments). Output = per-game results + standings. See SCORING.md. Fully unit tested.
## Scoreboard payload shape
```ts
type ScoreboardPayload = {
eventName: string;
visibility: 'visible' | 'frozen' | 'hidden';
currentGame: { id: string; title: string; index: number; total: number } | null;
reveal: { active: boolean; revealedCount: number } | null;
teams: Array<{
id: string; name: string; color: string;
// omitted entirely when hidden:
rank?: number; total?: number;
perGame?: Array<{ gameId: string; points: number }>;
}>;
updatedAt: string;
};
```
During reveal mode, teams not yet revealed are sent without rank/total.
## Folder layout
```
src/
app/ (routes above)
components/ (ui/, scoreboard/, judge/, admin/)
lib/
scoring/ (index.ts, *.test.ts)
supabase/ (browser.ts, server.ts, admin.ts)
realtime.ts
tokens.ts (zod schemas)
queries/ (data loaders shared by admin + API)
supabase/migrations/
```
+63
View File
@@ -0,0 +1,63 @@
# Build plan
Work one phase at a time. At the end of each phase: run lint + tests, commit, and give the
human a short "how to test this manually" checklist. Don't start the next phase until told.
## Phase 0 — Scaffold
- Next.js + TS strict + Tailwind + ESLint + Vitest. `src/` layout per ARCHITECTURE.md.
- Fonts: Big Shoulders Display + Atkinson Hyperlegible via `next/font/google`. Tokens from UI.md as CSS variables + Tailwind theme.
- Supabase clients (`browser`, `server`, `admin` with `server-only`).
- `.env.local` loading; fail fast with a clear error if vars are missing.
**Done when:** `npm run dev` shows a placeholder home; `npm run test` runs a dummy test.
## Phase 1 — Database + types
- Apply `supabase/migrations/0001_init.sql`. Generate TS types into `src/lib/database.types.ts`.
- `src/lib/tokens.ts` zod schemas (32-char hex).
**Done when:** tables visible in Supabase; anon key cannot `select` from any table (write a quick script/test proving it).
## Phase 2 — Scoring engine (TDD)
- Implement SCORING.md in `src/lib/scoring/` as pure functions.
- All listed test cases + edge cases.
**Done when:** tests green, 100% branch coverage on the scoring module.
## Phase 3 — Admin auth + setup screens
- `/login` magic link; middleware guards `/admin/*` with `ADMIN_EMAILS`.
- Events list + create/duplicate/delete.
- Event setup: teams CRUD (colour picker, reorder), games builder with criteria + presets, notes.
**Done when:** I can build a "Worship Game Night" with 4 teams and a Karaoke game with 5 criteria (1–5) and a Guess the Lyric game with 1 number criterion.
## Phase 4 — Scoreboard + realtime
- `src/lib/realtime.ts` `notify()` (server broadcast) + `useRefreshChannel(channel, refetch)` hook (debounce, reconnect, 10s poll, refetch on focus).
- `GET /api/public/scoreboard/[token]` building the payload via the scoring engine.
- `/s/[token]` page per UI.md: FLIP rank animation, count-up totals, reduced motion, fullscreen, cursor hide, connection dot.
**Done when:** changing anything in the DB via admin (or SQL + a manual notify) updates an open scoreboard tab in < 1s.
## Phase 5 — Control room (direct scoring)
- `/admin/events/[id]/live`: game list, prev/next, set current (→ live), mark done.
- Scoring grid with block + number inputs, autosave, optimistic UI.
- Bonus/penalty panel with quick buttons, custom, reason, undo.
- Keyboard shortcuts.
**Done when:** I run a full direct-scored game and the scoreboard tracks every change.
## Phase 6 — Visibility + reveal
- Visible / Frozen / Hidden toggle. Freeze stores snapshot server-side. Hidden strips scores in the API.
- Reveal mode: start, reveal next (bottom-up), finish → visible.
**Done when:** in Hidden mode, the network tab on the scoreboard contains NO totals. Reveal works end-to-end.
## Phase 7 — Judges
- Nominate judges, copy link, QR codes (use a small QR lib), revoke.
- Open link toggle + `/jo/[token]` name flow + localStorage.
- `/j/[token]` mobile page: team cards, spotlight pinned, block rows, autosave status, read-only states.
- `PUT /api/judge/[token]/scores` with all checks from ARCHITECTURE.md + rate limit. Clearing = DELETE or `value: null`.
- Control room in judged mode: averages, judge progress matrix, per-judge breakdown, override cells, spotlight select, lock toggle.
**Done when:** 2 phones judging Karaoke at once, admin sees progress live, scoreboard updates with averages, override works, lock makes judges read-only.
## Phase 8 — Polish + deploy
- Share panel (all links + QR in one place, "copy all judge links for this game" as text for WhatsApp).
- Empty states + error copy per UI.md.
- Accessibility pass (focus, contrast, tap targets).
- Deploy to Vercel; set env vars; set Supabase auth redirect URLs to the Vercel domain.
**Done when:** full dry run on the deployed URL: laptop admin + projector scoreboard + 2 phone judges.
## Stretch (only if asked)
Participants within teams · co-host admins · countdown timer on scoreboard · sound effects on reveal · CSV export of results.
+19
View File
@@ -0,0 +1,19 @@
# Data model
Full SQL in `supabase/migrations/0001_init.sql`.
| Table | Purpose | Key columns |
|---|---|---|
| `events` | A game night | `owner_id`, `scoreboard_token`, `scoreboard_visibility`, `frozen_snapshot`, `current_game_id`, `reveal_active`, `reveal_count` |
| `teams` | Teams in an event | `name`, `color` (#RRGGBB), `sort_order` |
| `games` | Activities | `scoring_mode`, `points_mode`, `multiplier`, `placement_points int[]`, `status`, `admin_notes`, `judge_notes`, `open_token`, `open_link_enabled`, `judging_locked`, `spotlight_team_id` |
| `criteria` | Scoring blocks per game | `label`, `description`, `input_type`, `min_value`, `max_value`, `step`, `weight` |
| `judges` | Judges per game | `name`, `token`, `revoked`, `source` (nominated/open_link) |
| `scores` | One value per (team, criterion, judge) | `judge_id` NULL = admin score (direct mode or override) |
| `adjustments` | Bonus/penalty | `points` (+/-), `reason`, optional `game_id` |
## Notes
- `scores` unique on `(team_id, criterion_id, judge_id)` with `NULLS NOT DISTINCT`, so there's exactly one admin row per team+criterion → clean upserts.
- In **judged** games, an admin row (`judge_id IS NULL`) is an **override** for that cell.
- Deleting a criterion/team/judge cascades its scores.
- `frozen_snapshot` holds the `ScoreboardPayload` captured at freeze time.
+18
View File
@@ -0,0 +1,18 @@
Paste everything below the line into Claude Code.
---
We're building "Game Night Live", a live scoring app for my church youth group's game nights.
Before writing any code:
1. Read CLAUDE.md and every file in docs/ plus supabase/migrations/0001_init.sql.
2. Give me a short summary of what you understood, list any gaps/contradictions you found,
and ask me any questions you need answered (max 5).
3. Confirm the current versions/APIs you'll use for Next.js, @supabase/ssr and Supabase Realtime
server-side broadcast by checking the official docs.
Then start Phase 0 from docs/BUILD_PLAN.md. Stop at the end of each phase, show me
what to test manually, and wait for me to say "next phase".
My .env.local is already filled in. I'm using WebStorm and npm.
Explain the *why* behind key decisions as you go — keep it brief.
+101
View File
@@ -0,0 +1,101 @@
# PRD — Game Night Live
## 1. Goal
Run a youth game night (e.g. "Worship Game Night") from one admin tab while a projector tab shows a
live scoreboard, and judges score from their phones via links. Versatile enough for any game format.
## 2. Roles
| Role | Access | How they get in |
|---|---|---|
| **Admin** | Everything | Logs in (magic link). Email must be in `ADMIN_EMAILS`. |
| **Scoreboard viewer** | Read-only scoreboard for ONE event | Public link `/s/{scoreboardToken}` |
| **Judge** | Score ONE game | Personal link `/j/{judgeToken}` OR open game link `/jo/{openToken}` (enters name first) |
## 3. Core concepts
- **Event** — one game night. Has teams, games, one scoreboard link, visibility state.
- **Team** — name + colour. Belongs to an event.
- **Game** — one activity. Ordered. Has a scoring mode:
- `judged` — judges submit scores via links; admin can see progress & override.
- `direct` — admin enters scores directly.
- **Criterion ("block")** — one thing being scored in a game. A game has 1..N criteria.
- e.g. Karaoke: Pitch, Energy, Lyrics accuracy, Stage presence, Crowd reaction (each 1–5).
- e.g. Guess the Lyric: one criterion "Correct answers" (number input, 0–20).
- Input type: `blocks` (tap a number in a row of buttons) or `number` (free numeric input / +/- stepper).
- Has min, max, step, weight, and a description (shown to whoever scores it).
- **Points mode** per game (how a game's result becomes leaderboard points):
- `raw` — game points = criteria total × multiplier.
- `placement` — teams ranked by criteria total, then awarded placement points (default 10/7/5/3).
- **Adjustment** — bonus or penalty points with a reason, optionally tied to a game.
- **Notes** — `admin_notes` (only admin sees) and `judge_notes` (judges see) per game.
## 4. Features
### 4.1 Admin — Setup (`/admin/events/[id]`)
- Create/edit/delete events; duplicate an event (copies teams, games, criteria — not scores).
- Teams: add, rename, recolour, reorder, delete.
- Games builder: add, reorder (drag or up/down), duplicate, delete.
- Title, description, scoring mode, points mode, multiplier, placement points.
- Criteria list: add/remove/reorder; label, description, input type, min/max/step, weight.
- Quick presets: "Karaoke (5 × 1–5)", "Single score (0–10)", "Points (number)", "Win/Lose (0–1)".
- Admin notes + judge notes (multiline).
- Judges (judged games only):
- Nominate judges by name → each gets a personal link (copy button + QR code).
- Toggle the open link on/off; anyone opening it types their name and becomes a judge.
- Revoke a judge (link stops working, their scores excluded).
- Share panel: scoreboard link + QR, all judge links per game.
### 4.2 Admin — Control room (`/admin/events/[id]/live`)
This is the screen used during the night. Must be fast and hard to mess up.
- Game switcher: Prev / Next buttons + list of all games with status (upcoming / live / done).
Setting a game as current marks it `live` and shows it on the scoreboard.
- Current game panel:
- Scoring grid: rows = teams, columns = criteria, using the same block/number inputs.
- Direct mode: admin types/taps here. Autosaves.
- Judged mode: shows per-team average per criterion, a judge-progress matrix
(✓ per judge per team), and per-judge breakdown on expand. Admin can override a cell
(override wins over judge average; clearly marked; can be cleared).
- Spotlight: pick "now performing" team — judges see it highlighted.
- Lock judging toggle (judges become read-only).
- Mark game done.
- Admin notes visible.
- Bonus/penalty: per team quick buttons (+1, +5, +10, −5) and custom amount + reason.
Recent adjustments list with undo.
- Scoreboard visibility: **Visible / Frozen / Hidden** (see 4.3). Big obvious toggle.
- "Open scoreboard" button (new tab) + "Reveal mode" button (see 4.3).
- Keyboard shortcuts: `N` next game, `P` prev game, `H` cycle visibility, `?` help.
### 4.3 Scoreboard (`/s/[token]`)
- Projector-first, 16:9, readable from the back of a hall.
- Shows: event name, current game title, team standings (rank, name, colour, total points),
optionally per-game points columns for completed games.
- Updates live (< 1s) when admin changes anything. Rank changes animate.
- **Visible** — live totals.
- **Frozen** — shows totals as they were the moment it was frozen, with a subtle "scores frozen" note.
Server stores the snapshot; live scores are not sent.
- **Hidden** — no scores sent at all. Shows team names (no order implied — alphabetical) and the current game, with a "scores are hidden" state.
- **Reveal mode** (admin-triggered): scoreboard reveals final standings last place → first,
one team per admin click ("Reveal next"), then sets visibility to Visible.
- Auto-reconnects; also polls every 10s as a fallback. Shows a small offline dot if disconnected.
- Fullscreen button; hides cursor after inactivity.
### 4.4 Judge (`/j/[token]`)
- Mobile-first. Shows game title, judge notes, and their own name.
- One card per team (spotlighted team pinned on top + highlighted).
- Each card: one block row per criterion (e.g. 1 2 3 4 5 big tap targets) with the criterion
label + description; number criteria get a stepper.
- Autosaves on every tap; shows saved ✓ / saving / error per card.
- Judges see only their own scores — never other judges' or totals.
- If judging locked or game done: read-only with a message. If revoked: "This link is no longer active."
- Open link (`/jo/[token]`): enter name → creates judge → redirects to personal link and stores it
in localStorage so a refresh keeps them in.
## 5. Non-functional
- Live latency target < 1s on normal Wi-Fi.
- Works with ~10 teams, ~20 games, ~10 judges per game without lag.
- No data loss on refresh; all state server-side.
- Accessible: visible focus, sufficient contrast, tap targets ≥ 44px.
## 6. Out of scope (v1)
- Individual contestants within teams (stretch: `participants` per team).
- Multiple admins / co-hosts (stretch).
- Timers/buzzers (stretch).
+42
View File
@@ -0,0 +1,42 @@
# Scoring rules
All implemented in `src/lib/scoring/` as pure functions. Tests must cover every rule below.
## 1. Cell value (team × criterion)
- **Direct game:** the admin score row. Missing → not scored.
- **Judged game:**
- If an admin override row exists → use it.
- Else average of non-revoked judges' values for that cell. Missing judges are ignored (not zero).
- No judge values → not scored.
## 2. Team raw score for a game
`raw = Σ (cellValue × criterion.weight)` over scored criteria.
A team with zero scored cells is **unscored** for that game (not 0).
## 3. Game points
- **raw mode:** `points = round2(raw × multiplier)`.
- **placement mode:** rank scored teams by raw desc. Award `placement_points[rank-1] ?? 0`.
- Ties: tied teams share the **average** of the places they span, rounded to 2dp.
e.g. two teams tied for 1st with [10,7,5] → each gets 8.5; next team gets 5.
- Then × multiplier.
- Unscored teams get 0 and are not ranked.
- Only games with status `live` or `done` count toward totals. `upcoming` games contribute nothing
(prevents half-set-up games leaking).
## 4. Event total
`total = Σ game points + Σ adjustments.points`
## 5. Standings
Sort by total desc. Ties share rank (standard competition: 1,1,3). Tie display order: team `sort_order`.
## Test cases to include (minimum)
1. Karaoke: 5 criteria × 1–5, 3 judges, one judge missing a team → average uses 2 judges.
2. Override beats judge average.
3. Revoked judge excluded.
4. Weights applied.
5. Placement with a 2-way tie at 1st and 3 teams.
6. Placement with more teams than placement_points → extra teams get 0.
7. Multiplier on both modes.
8. Upcoming game ignored.
9. Adjustments (+ and −) added; adjustment tied to an upcoming game still counts (it's explicit).
10. Standings tie → shared rank.
+79
View File
@@ -0,0 +1,79 @@
# UI & design direction
## Concept: "Sports-hall scoreboard at a worship night"
Chunky, legible-from-the-back numbers; team colours do the shouting; everything else stays calm.
Spend the boldness in ONE place: the scoreboard's rank-change moment. Admin + judge UIs are quiet and functional.
## Tokens
| Name | Hex | Use |
|---|---|---|
| Stage | `#1B1640` | Scoreboard background (deep indigo, not black) |
| Floodlight | `#FFD23F` | Leader highlight, focus rings on scoreboard |
| Chalk | `#F5F7FA` | Admin/judge background |
| Ink | `#14213D` | Primary text on light |
| Signal | `#2EC4B6` | Saved/connected state |
| Alert | `#E63946` | Errors, penalties, hidden state |
Team colours are user-chosen; pick text colour per team by contrast (white or Ink).
Type:
- **Big Shoulders Display** (Google Fonts) — scoreboard numbers, team names, game titles. Tabular numbers.
- **Atkinson Hyperlegible** — all body/UI text (readable on phones + projector).
Sentence case everywhere. No all-caps labels.
## Screens
### Scoreboard (16:9)
```
┌──────────────────────────────────────────────────────────────┐
│ Worship Game Night Game 3 of 8: Karaoke │
│ │
│ 1 ████ Lions 142 │
│ 2 ████ Eagles 128 │
│ 3 ████ Sharks 120 │
│ 4 ████ Wolves 97 │
│ │
│ ● live ⛶ │
└──────────────────────────────────────────────────────────────┘
```
- Each row: rank, colour bar (full-height block in team colour), name, total. Row height scales with team count to fill the screen.
- Leader row gets a Floodlight outline.
- On update: rows slide to new positions (FLIP animation, ~600ms), changed totals count up. Respect `prefers-reduced-motion` (instant swap).
- Hidden: team colour blocks in alphabetical order, totals replaced by a single centred message "Scores are hidden — final reveal soon".
- Reveal mode: rows appear bottom-up, one per admin click, with a short drum-roll pause effect (visual only).
### Admin control room (desktop/laptop)
```
┌ Games ─────────┐┌ Karaoke · live ───────────────────────┐┌ Scoreboard ─────┐
│ ✓ Name that... ││ [Prev] [Next] Spotlight: [Lions ▾] ││ (●Visible)Frozen│
│ ✓ Guess lyric ││ ││ Hidden │
│ ▶ Karaoke ││ Team Pitch Energy Lyrics Stage Crowd││ [Open] [Reveal] │
│ ○ Charades ││ Lions 4.3 5.0 3.7 4.0 4.7 ││ │
│ ○ Bible quiz ││ Eagles … │├ Bonus ──────────┤
│ ││ Judges: Eben ✓✓✓✓ Melissa ✓✓✗✗ ││ Lions +1 +5 +10 │
│ ││ Notes (only you): … ││ … │
└────────────────┘└───────────────────────────────────────┘└─────────────────┘
```
Collapses to stacked panels on tablet.
### Judge (phone)
```
┌─────────────────────────┐
│ Karaoke │
│ Judging as Melissa │
│ ▸ Judge notes │
├─────────────────────────┤
│ ★ Now: Lions │
│ Pitch │
│ [1][2][3][4][5] │
│ Energy │
│ [1][2][3][4][5] │
│ … Saved ✓ │
├─────────────────────────┤
│ Eagles … │
└─────────────────────────┘
```
Selected block filled in team colour. Tap the selected block again to clear.
## Copy
Plain verbs: "Next game", "Hide scores", "Freeze scores", "Show scores", "Add bonus", "Copy judge link".
Errors say what happened + what to do: "This link has been turned off. Ask the host for a new one."