Phase 5: control room with direct scoring, bonuses and shortcuts

- /admin/events/[eventId]/live: game list with status, previous/next,
  mark done/reopen, scoring grid, standings, and bonus/penalty with undo.
- Scores autosave per cell with optimistic UI; the validate_score trigger
  and RLS do the checking so a save costs one DB round trip.
- BlockInput and NumberStepper are shared UI, ready for the judge page.
- buildLiveView shapes all data on the server from the scoring engine, so
  the client components contain no score math.
- N / P switch games, ? shows shortcut help.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-03 14:48:41 +02:00
co-authored by Claude Opus 5.5
parent 17eb76d036
commit f7122b193c
12 changed files with 1091 additions and 4 deletions
+188
View File
@@ -0,0 +1,188 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { saveAdminScore } from "@/app/admin/live-actions";
import { BlockInput, NumberStepper } from "@/components/ui/score-inputs";
import { formatScore } from "@/lib/criteria";
import type { LiveGame, LiveView } from "@/lib/live-view";
import { ErrorText } from "./error-text";
// An edit the server hasn't echoed back yet. Shown instead of the server's value so
// taps feel instant (optimistic UI).
type PendingEdit = { value: number | null; version: number; savedAt: number | null };
const cellKey = (teamId: string, criterionId: string) => `${teamId}|${criterionId}`;
// A saved edit normally disappears when the refreshed data matches it. If it never
// matches (someone else changed the cell), stop masking the server's value after this long.
const STALE_MS = 5000;
export function ScoringGrid({
eventId,
game,
teams,
}: {
eventId: string;
game: LiveGame;
teams: LiveView["teams"];
}) {
const router = useRouter();
const [pending, setPending] = useState<Record<string, PendingEdit>>({});
const [savingCount, setSavingCount] = useState(0);
const [error, setError] = useState<string | null>(null);
const versions = useRef(0);
// Drop optimistic edits once the server data has caught up with them.
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- reconciling local edits with fresh server props
setPending((current) => {
const now = Date.now();
const kept = Object.entries(current).filter(([key, edit]) => {
if (edit.savedAt === null) return true;
const [teamId, criterionId] = key.split("|");
const serverValue = game.cells[teamId]?.[criterionId]?.adminValue ?? null;
return serverValue !== edit.value && now - edit.savedAt < STALE_MS;
});
return kept.length === Object.keys(current).length ? current : Object.fromEntries(kept);
});
}, [game]);
const save = (teamId: string, criterionId: string, value: number | null) => {
const key = cellKey(teamId, criterionId);
const version = ++versions.current;
setPending((current) => ({ ...current, [key]: { value, version, savedAt: null } }));
setSavingCount((count) => count + 1);
setError(null);
// Only the newest edit of a cell may update or clear its pending state.
const settle = (savedAt: number | null) =>
setPending((current) => {
if (current[key]?.version !== version) return current;
if (savedAt === null) {
return Object.fromEntries(Object.entries(current).filter(([other]) => other !== key));
}
return { ...current, [key]: { ...current[key], savedAt } };
});
saveAdminScore(eventId, game.id, teamId, criterionId, value)
.then((result) => {
if (result.ok) {
settle(Date.now());
router.refresh();
} else {
settle(null);
setError(result.error);
}
})
.catch(() => {
settle(null);
setError("That score wasn't saved — couldn't reach the server. Check your connection and enter it again.");
})
.finally(() => setSavingCount((count) => count - 1));
};
if (game.criteria.length === 0) {
return <p>This game has no criteria yet. Add some on the setup page.</p>;
}
if (teams.length === 0) {
return <p>No teams yet. Add teams on the setup page.</p>;
}
const judged = game.scoringMode === "judged";
return (
<div className="flex flex-col gap-2">
<div className="overflow-x-auto">
<table className="w-full border-separate border-spacing-y-1 text-left">
<thead>
<tr className="text-sm">
<th scope="col" className="pr-3 font-bold">
Team
</th>
{game.criteria.map((criterion) => (
<th key={criterion.id} scope="col" className="px-2 align-bottom font-bold">
{criterion.label}
{criterion.description && (
<span className="block font-normal text-ink/70">{criterion.description}</span>
)}
</th>
))}
<th scope="col" className="px-2 text-right font-bold">
Total
</th>
<th scope="col" className="pl-2 text-right font-bold">
Points
</th>
</tr>
</thead>
<tbody>
{teams.map((team) => {
const result = game.results[team.id];
return (
<tr key={team.id} className="bg-chalk">
<th scope="row" className="rounded-l-md py-2 pr-3 pl-2 font-bold whitespace-nowrap">
<span
aria-hidden
className="mr-2 inline-block size-3 rounded-full align-middle"
style={{ backgroundColor: team.color }}
/>
{team.name}
</th>
{game.criteria.map((criterion) => {
const cell = game.cells[team.id]?.[criterion.id];
const edit = pending[cellKey(team.id, criterion.id)];
const value = edit ? edit.value : (cell?.adminValue ?? null);
const inputProps = {
range: criterion,
value,
label: `${criterion.label} for ${team.name}`,
onChange: (next: number | null) => save(team.id, criterion.id, next),
};
return (
<td key={criterion.id} className="px-2 py-2 align-top">
{criterion.inputType === "blocks" ? (
<BlockInput compact color={team.color} {...inputProps} />
) : (
<NumberStepper {...inputProps} />
)}
{judged && (
<span className="mt-1 block text-sm text-ink/70">
{cell?.judgeAverage == null
? "No judge scores"
: `Judges: ${formatScore(cell.judgeAverage)} (${cell.judgeCount})`}
{value !== null && " · overridden"}
</span>
)}
</td>
);
})}
<td className="px-2 py-2 text-right font-bold tabular-nums">
{result?.raw == null ? "–" : formatScore(result.raw)}
</td>
<td className="rounded-r-md py-2 pr-2 pl-2 text-right font-bold tabular-nums">
{result?.raw == null ? "–" : formatScore(result.points)}
{game.pointsMode === "placement" && result?.placement != null && (
<span className="block text-sm font-normal text-ink/70">place {result.placement}</span>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<p role="status" className="text-sm font-bold">
{savingCount > 0 ? "Saving…" : error ? "" : "All scores saved ✓"}
</p>
<ErrorText>{error}</ErrorText>
{judged && (
<p className="text-sm text-ink/70">
This is a judged game. A value you enter here overrides the judges&apos; average for that
cell; clear it to use the judges again.
</p>
)}
</div>
);
}