diff --git a/apps/frontend/src/screens/LiveQuiz.tsx b/apps/frontend/src/screens/LiveQuiz.tsx index cbdd828..5886eaa 100644 --- a/apps/frontend/src/screens/LiveQuiz.tsx +++ b/apps/frontend/src/screens/LiveQuiz.tsx @@ -8,6 +8,7 @@ import BgBoss from "../components/BgBoss"; import { FaSpinner } from "react-icons/fa6"; import { MdViewInAr } from "react-icons/md"; import { participantTokenKey, streamingEnabled } from "../services/streamApi"; +import { downloadLeaderboardCsv } from "../utils/leaderboardCsv"; // The LiveKit client is most of a megabyte; only a live video quiz loads it. const LiveStage = lazy(() => import("../components/live/LiveStage")); @@ -66,6 +67,7 @@ function LiveQuiz({ isOrganizer = false }: LiveQuizProps) { const [joinCode, setJoinCode] = useState(''); // Set by the server on join: the host opened this lobby with live video. const [liveVideo, setLiveVideo] = useState(false); + const [startError, setStartError] = useState(''); @@ -267,6 +269,7 @@ function LiveQuiz({ isOrganizer = false }: LiveQuizProps) { // The server refused a message, for example when this login is not // an organizer of the quiz. console.error('[ws]', payload?.code, payload?.message); + if (payload?.code === 'NO_QUESTIONS') setStartError(payload.message); break; case 'participants:sync': setParticipants(payload.participants); @@ -561,6 +564,9 @@ function LiveQuiz({ isOrganizer = false }: LiveQuizProps) { > Start Game + {startError && ( +
{startError}
+ )} {notSentNotice('the game was not started.', 'the game can be started once the connection is back.')} > @@ -1080,10 +1086,20 @@ function LiveQuiz({ isOrganizer = false }: LiveQuizProps) { + {isOrganizer && sortedLeaderboard.length > 0 && ( + + )} + {isOrganizer ? "Back to Dashboard" : "Join Another Quiz"} diff --git a/apps/frontend/src/utils/leaderboardCsv.test.ts b/apps/frontend/src/utils/leaderboardCsv.test.ts new file mode 100644 index 0000000..c03708a --- /dev/null +++ b/apps/frontend/src/utils/leaderboardCsv.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest'; +import { leaderboardFilename, leaderboardToCsv } from './leaderboardCsv'; + +describe('leaderboardToCsv', () => { + it('writes a ranked row with seconds for each player', () => { + const csv = leaderboardToCsv([ + { username: 'Aisha', score: 47, totalTimeMs: 38200 }, + { username: 'Marco', score: 44, totalTimeMs: 41000 }, + ]); + expect(csv).toBe('Rank,Name,Score,Time (s)\r\n1,Aisha,47,38.2\r\n2,Marco,44,41.0\r\n'); + }); + + it('quotes names with commas, quotes and line breaks', () => { + const csv = leaderboardToCsv([{ username: 'Lee, "Ace"\nJr', score: 1, totalTimeMs: 1000 }]); + expect(csv).toContain('1,"Lee, ""Ace""\nJr",1,1.0'); + }); + + it('defuses names that would run as a spreadsheet formula', () => { + const csv = leaderboardToCsv([{ username: '=SUM(A1)', score: 0 }]); + expect(csv).toContain("1,'=SUM(A1),0,"); + }); + + it('leaves the time blank when it is missing', () => { + expect(leaderboardToCsv([{ username: 'Sam', score: 3 }])).toContain('1,Sam,3,\r\n'); + }); +}); + +describe('leaderboardFilename', () => { + it('includes the session and the date', () => { + expect(leaderboardFilename('ab12-cd34-ef56', new Date('2026-11-18T10:00:00Z'))).toBe( + 'rexial-leaderboard-ab12cd34-2026-11-18.csv', + ); + }); +}); diff --git a/apps/frontend/src/utils/leaderboardCsv.ts b/apps/frontend/src/utils/leaderboardCsv.ts new file mode 100644 index 0000000..eb669b6 --- /dev/null +++ b/apps/frontend/src/utils/leaderboardCsv.ts @@ -0,0 +1,44 @@ +export interface LeaderboardRow { + username?: string; + score?: number; + totalTimeMs?: number; +} + +// Quote a value when it holds a comma, quote or line break, and keep a name +// that starts with = + - @ from being run as a formula by Excel or Sheets. +function cell(value: string): string { + let text = value; + if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`; + return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text; +} + +// Rows are expected in final order. The time column explains why equal +// scores are ranked the way they are. +export function leaderboardToCsv(rows: LeaderboardRow[]): string { + const lines = ['Rank,Name,Score,Time (s)']; + rows.forEach((row, i) => { + const seconds = + typeof row.totalTimeMs === 'number' ? (row.totalTimeMs / 1000).toFixed(1) : ''; + lines.push([String(i + 1), cell(row.username ?? ''), String(row.score ?? 0), seconds].join(',')); + }); + return lines.join('\r\n') + '\r\n'; +} + +export function leaderboardFilename(sessionId: string, date = new Date()): string { + const day = date.toISOString().slice(0, 10); + const id = sessionId.replace(/[^a-zA-Z0-9]/g, '').slice(0, 8); + return `rexial-leaderboard-${id ? id + '-' : ''}${day}.csv`; +} + +export function downloadLeaderboardCsv(rows: LeaderboardRow[], sessionId: string): void { + // The BOM makes Excel read the file as UTF-8, so non-ASCII names survive. + const blob = new Blob(['', leaderboardToCsv(rows)], { type: 'text/csv;charset=utf-8' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = leaderboardFilename(sessionId); + document.body.appendChild(link); + link.click(); + link.remove(); + URL.revokeObjectURL(url); +} diff --git a/apps/ws-server/src/utils/handleMessages.auth.test.ts b/apps/ws-server/src/utils/handleMessages.auth.test.ts index 2b99053..653b114 100644 --- a/apps/ws-server/src/utils/handleMessages.auth.test.ts +++ b/apps/ws-server/src/utils/handleMessages.auth.test.ts @@ -136,6 +136,7 @@ beforeEach(() => { } mocks.getCachedParticipants.mockResolvedValue([]); mocks.getCachedSession.mockResolvedValue({ status: "WAITING", quiz: { joinCode: "ABC123" } }); + mocks.getCachedQuestions.mockResolvedValue([{ id: "q-1", answers: [] }]); mocks.prisma.quizSession.updateMany.mockResolvedValue({ count: 1 }); }); @@ -325,6 +326,17 @@ describe("a verified organizer can run their quiz", () => { expect(errorCodes(host)).toEqual([]); }); + it("refuses to start a quiz that has no questions", async () => { + const host = await joinedHost(); + mocks.getCachedQuestions.mockResolvedValue([]); + + await handleMessage(host, { type: "quiz:start", payload: { sessionId } }); + + expect(errorCodes(host)).toEqual(["NO_QUESTIONS"]); + expect(mocks.prisma.quizSession.updateMany).not.toHaveBeenCalled(); + expect(mocks.broadcastToSession).not.toHaveBeenCalled(); + }); + it("uses the joined session when the message leaves it out", async () => { const host = await joinedHost(); diff --git a/apps/ws-server/src/utils/handleMessages.ts b/apps/ws-server/src/utils/handleMessages.ts index 2377da7..0b21b3c 100644 --- a/apps/ws-server/src/utils/handleMessages.ts +++ b/apps/ws-server/src/utils/handleMessages.ts @@ -353,6 +353,13 @@ export const handleMessage = async (client: Client, data: any) => { case 'quiz:start': { const sessionId = authorizeOrganizerAction(client, payload); if (!sessionId) break; + // Starting a quiz with nothing to ask only walks the room through + // "get ready" and then ends the session as COMPLETED. + const startQuestions = await getCachedQuestions(sessionId); + if (!startQuestions || startQuestions.length === 0) { + sendError(client, 'NO_QUESTIONS', 'Add at least one question before starting the quiz.'); + break; + } // A session the super-admin cancelled (or one that already // ended) must not be revived by a host coming back to the lobby. const { count } = await prisma.quizSession.updateMany({