Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion apps/frontend/src/screens/LiveQuiz.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
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"));
Expand Down Expand Up @@ -57,15 +58,16 @@
const [sendFailed, setSendFailed] = useState(false);
const isConnected = connectionState === 'connected';
const [gameState, setGameState] = useState<GameState>('WAITING');
const [participants, setParticipants] = useState<any[]>([]);

Check failure on line 61 in apps/frontend/src/screens/LiveQuiz.tsx

View workflow job for this annotation

GitHub Actions / Lint & type-check

Unexpected any. Specify a different type
const [currentQuestion, setCurrentQuestion] = useState<any>(null);

Check failure on line 62 in apps/frontend/src/screens/LiveQuiz.tsx

View workflow job for this annotation

GitHub Actions / Lint & type-check

Unexpected any. Specify a different type
const [timeLeft, setTimeLeft] = useState(0);
const [correctAnswers, setCorrectAnswers] = useState<string[]>([]);
const [leaderboard, setLeaderboard] = useState<any[]>([]);

Check failure on line 65 in apps/frontend/src/screens/LiveQuiz.tsx

View workflow job for this annotation

GitHub Actions / Lint & type-check

Unexpected any. Specify a different type

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('');



Expand Down Expand Up @@ -267,6 +269,7 @@
// 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);
Expand Down Expand Up @@ -422,7 +425,7 @@
}
};

}, [sessionId, isOrganizer]);

Check warning on line 428 in apps/frontend/src/screens/LiveQuiz.tsx

View workflow job for this annotation

GitHub Actions / Lint & type-check

React Hook useEffect has missing dependencies: 'navigate', 'participantId', 'token', and 'user?.id'. Either include them or remove the dependency array


// `ws?.send` on a closed socket does nothing and throws nothing, so every
Expand Down Expand Up @@ -561,6 +564,9 @@
>
Start Game
</button>
{startError && (
<p role="alert" className="mt-3 text-sm text-red-400">{startError}</p>
)}
{notSentNotice('the game was not started.',
'the game can be started once the connection is back.')}
</>
Expand Down Expand Up @@ -1080,10 +1086,20 @@

</div>

{isOrganizer && sortedLeaderboard.length > 0 && (
<button
type="button"
onClick={() => downloadLeaderboardCsv(sortedLeaderboard, sessionId ?? '')}
className="mt-10 px-6 py-2 text-pink-300 font-secondary tracking-wide rounded-full border border-pink-500/50 hover:bg-pink-500/10 transition duration-200 cursor-pointer"
>
Download CSV
</button>
)}

<Link
to={isOrganizer ? "/dashboard" : "/join"}
state={isOrganizer ? undefined : { username }}
className="mt-16 px-8 py-3 text-black font-bold font-secondary tracking-wide rounded-full bg-linear-to-b from-pink-500 to-pink-800/40 hover:to-pink-800/30 transition duration-200 shadow-sm active:shadow-none active:scale-95 shadow-pink-700"
className="mt-6 px-8 py-3 text-black font-bold font-secondary tracking-wide rounded-full bg-linear-to-b from-pink-500 to-pink-800/40 hover:to-pink-800/30 transition duration-200 shadow-sm active:shadow-none active:scale-95 shadow-pink-700"
>
{isOrganizer ? "Back to Dashboard" : "Join Another Quiz"}
</Link>
Expand Down
34 changes: 34 additions & 0 deletions apps/frontend/src/utils/leaderboardCsv.test.ts
Original file line number Diff line number Diff line change
@@ -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',
);
});
});
44 changes: 44 additions & 0 deletions apps/frontend/src/utils/leaderboardCsv.ts
Original file line number Diff line number Diff line change
@@ -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);
}
12 changes: 12 additions & 0 deletions apps/ws-server/src/utils/handleMessages.auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
});

Expand Down Expand Up @@ -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();

Expand Down
7 changes: 7 additions & 0 deletions apps/ws-server/src/utils/handleMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
Loading