diff --git a/apps/frontend/src/screens/Dashboard.test.tsx b/apps/frontend/src/screens/Dashboard.test.tsx
index 6bfb3e1..72fd005 100644
--- a/apps/frontend/src/screens/Dashboard.test.tsx
+++ b/apps/frontend/src/screens/Dashboard.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from '@testing-library/react';
+import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -38,6 +38,41 @@ beforeEach(() => {
});
describe('Dashboard load and action errors', () => {
+ it('shows the latest completed session podium and omits it when unavailable', async () => {
+ vi.mocked(api.get).mockResolvedValueOnce({
+ data: {
+ organizedQuizes: [
+ {
+ id: 'quiz-with-podium',
+ title: 'Completed quiz',
+ status: 'COMPLETED',
+ createdAt: '2026-01-01',
+ _count: { questions: 3, quizSessions: 2 },
+ podium: [{ id: 'p-1', username: 'Ada', score: 30 }],
+ },
+ {
+ id: 'quiz-without-podium',
+ title: 'No completed session',
+ status: 'COMPLETED',
+ createdAt: '2026-01-01',
+ _count: { questions: 3, quizSessions: 0 },
+ podium: [],
+ },
+ ],
+ participated: [],
+ },
+ });
+
+ renderDashboard();
+
+ expect(await screen.findByText('Ada')).toBeInTheDocument();
+ expect(screen.getByText('30 pts')).toBeInTheDocument();
+ expect(screen.getByText('Top players')).toBeInTheDocument();
+ expect(screen.getByText('2 Sessions')).toBeInTheDocument();
+ const withoutPodium = screen.getByRole('link', { name: /No completed session/ });
+ expect(within(withoutPodium).queryByText('Top players')).not.toBeInTheDocument();
+ });
+
it('shows an error with a retry instead of the empty state when loading fails', async () => {
vi.mocked(api.get).mockRejectedValueOnce(new Error('network down'));
diff --git a/apps/frontend/src/screens/Dashboard.tsx b/apps/frontend/src/screens/Dashboard.tsx
index 65a0e48..6fa19a0 100644
--- a/apps/frontend/src/screens/Dashboard.tsx
+++ b/apps/frontend/src/screens/Dashboard.tsx
@@ -196,10 +196,34 @@ function Dashboard() {
{q._count?.questions || 0} Qs
- {q._count?.sessions || 0}{" "}
+ {q._count?.quizSessions || 0}{" "}
Sessions
+
+ {q.podium?.length > 0 && (
+
+
+ Top players
+
+
+ {q.podium.map((player: any, index: number) => (
+ -
+
+ #{index + 1}
+ {player.username}
+
+
+ {player.score} pts
+
+
+ ))}
+
+
+ )}
))}
diff --git a/apps/http-server/src/controllers/getAllQuizes.test.ts b/apps/http-server/src/controllers/getAllQuizes.test.ts
new file mode 100644
index 0000000..3279c65
--- /dev/null
+++ b/apps/http-server/src/controllers/getAllQuizes.test.ts
@@ -0,0 +1,92 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { Request, Response } from "express";
+
+const { quizFindMany, sessionFindMany, queryRaw, getRankedParticipants } = vi.hoisted(() => ({
+ quizFindMany: vi.fn(),
+ sessionFindMany: vi.fn(),
+ queryRaw: vi.fn(),
+ getRankedParticipants: vi.fn(),
+}));
+
+vi.mock("@repo/db", () => ({
+ prisma: {
+ quiz: { findMany: quizFindMany },
+ quizSession: { findMany: sessionFindMany },
+ $queryRaw: queryRaw,
+ },
+ getRankedParticipants,
+}));
+
+import { getAllQuizesController } from "./quizController";
+
+const run = async () => {
+ const req = { userId: "user-1" } as unknown as Request;
+ const res = { status: vi.fn().mockReturnThis(), json: vi.fn() } as unknown as Response;
+ await getAllQuizesController(req, res);
+ return res;
+};
+
+describe("getAllQuizesController podium", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ quizFindMany.mockResolvedValue([
+ { id: "quiz-1", status: "COMPLETED" },
+ { id: "quiz-2", status: "COMPLETED" },
+ { id: "quiz-3", status: "ACTIVE" },
+ ]);
+ sessionFindMany.mockImplementation((args) =>
+ args.where.quizId
+ ? [
+ { id: "session-latest", quizId: "quiz-1" },
+ { id: "session-older", quizId: "quiz-1" },
+ { id: "session-quiz-2", quizId: "quiz-2" },
+ ]
+ : []
+ );
+ getRankedParticipants.mockResolvedValue([
+ { id: "p1", sessionId: "session-latest", username: "Ada", score: 30, totalTimeMs: 200 },
+ { id: "p2", sessionId: "session-latest", username: "Lin", score: 30, totalTimeMs: 300 },
+ { id: "p3", sessionId: "session-latest", username: "Grace", score: 20, totalTimeMs: 100 },
+ { id: "p4", sessionId: "session-latest", username: "Edsger", score: 10, totalTimeMs: 100 },
+ { id: "p5", sessionId: "session-quiz-2", username: "Turing", score: 25, totalTimeMs: 400 },
+ ]);
+ });
+
+ it("loads rankings for only the latest completed sessions in one batch", async () => {
+ const res = await run();
+ const response = vi.mocked(res.json).mock.calls[0][0];
+
+ expect(sessionFindMany).toHaveBeenCalledWith(expect.objectContaining({
+ where: { quizId: { in: ["quiz-1", "quiz-2"] }, status: "COMPLETED" },
+ orderBy: [
+ { endedAt: { sort: "desc", nulls: "last" } },
+ { createdAt: "desc" },
+ { id: "desc" },
+ ],
+ }));
+ expect(quizFindMany).toHaveBeenCalledOnce();
+ expect(sessionFindMany).toHaveBeenCalledTimes(2);
+ expect(getRankedParticipants).toHaveBeenCalledOnce();
+ expect(getRankedParticipants).toHaveBeenCalledWith(["session-latest", "session-quiz-2"]);
+ expect(queryRaw).not.toHaveBeenCalled();
+ expect(response.organizedQuizes[0].podium).toEqual([
+ expect.objectContaining({ username: "Ada", score: 30 }),
+ expect.objectContaining({ username: "Lin", score: 30 }),
+ expect.objectContaining({ username: "Grace", score: 20 }),
+ ]);
+ expect(response.organizedQuizes[1].podium).toEqual([
+ expect.objectContaining({ username: "Turing", score: 25 }),
+ ]);
+ expect(response.organizedQuizes[2].podium).toEqual([]);
+ });
+
+ it("does not fetch rankings when no completed quiz has a completed session", async () => {
+ sessionFindMany.mockResolvedValue([]);
+
+ const res = await run();
+ const response = vi.mocked(res.json).mock.calls[0][0];
+
+ expect(getRankedParticipants).not.toHaveBeenCalled();
+ expect(response.organizedQuizes[0].podium).toEqual([]);
+ });
+});
diff --git a/apps/http-server/src/controllers/quizController.ts b/apps/http-server/src/controllers/quizController.ts
index 89d0766..16e8ea1 100644
--- a/apps/http-server/src/controllers/quizController.ts
+++ b/apps/http-server/src/controllers/quizController.ts
@@ -1,6 +1,6 @@
import { Request, Response } from 'express';
import { errorResponse } from '../utils/error';
-import { prisma } from '@repo/db';
+import { getRankedParticipants, prisma } from '@repo/db';
import { generateCode } from '../utils/code';
import { parseCreateQuestion } from '../utils/questionInput';
import { parseCreateQuiz } from '../utils/quizInput';
@@ -57,6 +57,48 @@ export const getAllQuizesController = async (req: Request, res: Response) => {
orderBy: { createdAt: 'desc' }
});
+ const completedQuizIds = organizedQuizes
+ .filter((quiz) => quiz.status === 'COMPLETED')
+ .map((quiz) => quiz.id);
+
+ const completedSessions = completedQuizIds.length > 0
+ ? await prisma.quizSession.findMany({
+ where: {
+ quizId: { in: completedQuizIds },
+ status: 'COMPLETED'
+ },
+ select: { id: true, quizId: true },
+ orderBy: [
+ { endedAt: { sort: 'desc', nulls: 'last' } },
+ { createdAt: 'desc' },
+ { id: 'desc' }
+ ]
+ })
+ : [];
+
+ const latestSessionByQuiz = new Map();
+ for (const session of completedSessions) {
+ if (!latestSessionByQuiz.has(session.quizId)) {
+ latestSessionByQuiz.set(session.quizId, session.id);
+ }
+ }
+
+ const rankedParticipants = latestSessionByQuiz.size > 0
+ ? await getRankedParticipants([...latestSessionByQuiz.values()])
+ : [];
+ const podiumBySession = new Map();
+ for (const participant of rankedParticipants) {
+ const podium = podiumBySession.get(participant.sessionId) ?? [];
+ if (podium.length < 3) {
+ podium.push(participant);
+ podiumBySession.set(participant.sessionId, podium);
+ }
+ }
+
+ const organizedQuizesWithPodium = organizedQuizes.map((quiz) => ({
+ ...quiz,
+ podium: podiumBySession.get(latestSessionByQuiz.get(quiz.id) ?? '') ?? []
+ }));
const participatedQuizes = await prisma.quizSession.findMany({
where: {
@@ -112,7 +154,7 @@ export const getAllQuizesController = async (req: Request, res: Response) => {
return res.status(200).json({
- organizedQuizes,
+ organizedQuizes: organizedQuizesWithPodium,
participated: participatedWithRank
})
diff --git a/apps/ws-server/src/utils/cache.ts b/apps/ws-server/src/utils/cache.ts
index 9809116..b3f5b88 100644
--- a/apps/ws-server/src/utils/cache.ts
+++ b/apps/ws-server/src/utils/cache.ts
@@ -1,5 +1,5 @@
import { cache } from "../redis.js";
-import { prisma } from "@repo/db";
+import { getRankedParticipants, prisma } from "@repo/db";
const TTL = {
@@ -158,17 +158,7 @@ export async function getCachedLeaderboard(sessionId: string) {
return readThrough(
Keys.leaderboard(sessionId),
TTL.LEADERBOARD,
- () => prisma.$queryRaw`
- SELECT p.id,
- p.username,
- p.score,
- COALESCE(SUM(pa."timeMs"), 0)::int AS "totalTimeMs"
- FROM "Participant" p
- LEFT JOIN "ParticipantAnswer" pa ON pa."participantId" = p.id
- WHERE p."sessionId" = ${sessionId}
- GROUP BY p.id, p.username, p.score
- ORDER BY p.score DESC, "totalTimeMs" ASC, p.username ASC
- `,
+ () => getRankedParticipants([sessionId]),
);
}
diff --git a/docker-compose.yml b/docker-compose.yml
index 8782a38..47d50e2 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -8,6 +8,9 @@ services:
- "5173:5173"
volumes:
- .:/app
+ - rexial_node_modules:/app/node_modules
+ - rexial_frontend_modules:/app/apps/frontend/node_modules
+ - rexial_db_modules:/app/packages/db/node_modules
depends_on:
- backend
- genai
@@ -21,13 +24,16 @@ services:
- "8080:8080"
volumes:
- .:/app
+ - rexial_node_modules:/app/node_modules
+ - rexial_ws_modules:/app/apps/ws-server/node_modules
+ - rexial_db_modules:/app/packages/db/node_modules
# Share the HTTP server's signing secret so organizer tokens verify here.
env_file:
- path: apps/http-server/.env
required: false
environment:
- DATABASE_URL=postgresql://postgres:postgres@db:5432/Qtrive
- - REDIS_HOST=redis
+ - REDIS_HOST=redis
- REDIS_PORT=6379
- REDIS_PASSWORD=thisistheredisPassword
command: sh -c "pnpm --filter @repo/db run db:generate && pnpm run dev"
@@ -46,6 +52,9 @@ services:
- "4000:4000"
volumes:
- .:/app
+ - rexial_node_modules:/app/node_modules
+ - rexial_http_modules:/app/apps/http-server/node_modules
+ - rexial_db_modules:/app/packages/db/node_modules
environment:
- DATABASE_URL=postgresql://postgres:postgres@db:5432/Qtrive
command: sh -c " pnpm --filter @repo/db run db:generate && npx wait-on
@@ -71,7 +80,13 @@ services:
- UPLOAD_DIR=/app/apps/genAI/uploads
- ALLOWED_ORIGINS=*
healthcheck:
- test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=4)"]
+ test:
+ [
+ "CMD",
+ "python",
+ "-c",
+ "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=4)",
+ ]
interval: 15s
timeout: 5s
retries: 5
@@ -88,9 +103,9 @@ services:
volumes:
- ./apps/streaming/livekit/livekit.dev.yaml:/etc/livekit.yaml:ro
ports:
- - "7880:7880" # signaling
- - "7881:7881" # media over TCP (fallback)
- - "7882:7882/udp" # media over UDP
+ - "7880:7880" # signaling
+ - "7881:7881" # media over TCP (fallback)
+ - "7882:7882/udp" # media over UDP
streaming:
build:
@@ -125,7 +140,7 @@ services:
volumes:
- Qtrive_data:/var/lib/postgresql/data
healthcheck:
- test: [ "CMD-SHELL", "pg_isready -U postgres -d Qtrive" ]
+ test: ["CMD-SHELL", "pg_isready -U postgres -d Qtrive"]
interval: 10s
timeout: 5s
retries: 10
@@ -153,3 +168,9 @@ volumes:
Qtrive_redis_data:
Qtrive_genai_uploads:
Qtrive_genai_models:
+
+ rexial_node_modules:
+ rexial_frontend_modules:
+ rexial_http_modules:
+ rexial_ws_modules:
+ rexial_db_modules:
diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts
index 1bf98e6..5709e16 100644
--- a/packages/db/src/index.ts
+++ b/packages/db/src/index.ts
@@ -1,2 +1,4 @@
export { prisma } from "./client.js"; // exports instance of prisma
-export * from "./generated/prisma/client.js"; // exports generated types from prisma
\ No newline at end of file
+export * from "./generated/prisma/client.js"; // exports generated types from prisma
+export { getRankedParticipants } from "./leaderboard.js";
+export type { RankedParticipant } from "./leaderboard.js";
\ No newline at end of file
diff --git a/packages/db/src/leaderboard.ts b/packages/db/src/leaderboard.ts
new file mode 100644
index 0000000..f05b5c8
--- /dev/null
+++ b/packages/db/src/leaderboard.ts
@@ -0,0 +1,26 @@
+import { prisma } from "./client.js";
+
+export type RankedParticipant = {
+ id: string;
+ sessionId: string;
+ username: string;
+ score: number;
+ totalTimeMs: number;
+};
+
+export async function getRankedParticipants(sessionIds: string[]) {
+ if (sessionIds.length === 0) return [];
+
+ return prisma.$queryRaw`
+ SELECT p.id,
+ p."sessionId",
+ p.username,
+ p.score,
+ COALESCE(SUM(pa."timeMs"), 0)::int AS "totalTimeMs"
+ FROM "Participant" p
+ LEFT JOIN "ParticipantAnswer" pa ON pa."participantId" = p.id
+ WHERE p."sessionId" = ANY(${sessionIds})
+ GROUP BY p.id, p."sessionId", p.username, p.score
+ ORDER BY p."sessionId" ASC, p.score DESC, "totalTimeMs" ASC, p.username ASC
+ `;
+}