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
37 changes: 36 additions & 1 deletion apps/frontend/src/screens/Dashboard.test.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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'));

Expand Down
26 changes: 25 additions & 1 deletion apps/frontend/src/screens/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@

function Dashboard() {
const [quizzes, setQuizzes] = useState<{
organizedQuizes: any[];

Check failure on line 12 in apps/frontend/src/screens/Dashboard.tsx

View workflow job for this annotation

GitHub Actions / Lint & type-check

Unexpected any. Specify a different type
participated: any[];

Check failure on line 13 in apps/frontend/src/screens/Dashboard.tsx

View workflow job for this annotation

GitHub Actions / Lint & type-check

Unexpected any. Specify a different type
}>({ organizedQuizes: [], participated: [] });

const [showCreate, setShowCreate] = useState<boolean>(false);
Expand Down Expand Up @@ -168,7 +168,7 @@
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 bg-black/60 gap-6 py-8 px-5 border border-white/10 rounded-2xl">
{quizzes.organizedQuizes.map((q: any) => (

Check failure on line 171 in apps/frontend/src/screens/Dashboard.tsx

View workflow job for this annotation

GitHub Actions / Lint & type-check

Unexpected any. Specify a different type
<Link to={`/quiz/${q.id}/edit`} key={q.id}>
<div className="bg-zinc-700/20 hover:bg-zinc-700/30 border-dashed border border-gray-400/30 backdrop-blur-2xl rounded-xl p-6 h-full flex flex-col justify-between group hover:border-primary/50 transition-colors cursor-pointer">
<div>
Expand Down Expand Up @@ -196,10 +196,34 @@
{q._count?.questions || 0} Qs
</div>
<div className="flex items-center gap-1 text-green-600 font-semibold tracking-wide">
<BiPlay className="w-5 h-5" /> {q._count?.sessions || 0}{" "}
<BiPlay className="w-5 h-5" /> {q._count?.quizSessions || 0}{" "}
Sessions
</div>
</div>

{q.podium?.length > 0 && (
<div className="mt-5 border-t border-white/10 pt-4">
<h4 className="mb-2 text-xs font-semibold uppercase tracking-wider text-pink-500">
Top players
</h4>
<ol className="space-y-1">
{q.podium.map((player: any, index: number) => (

Check failure on line 210 in apps/frontend/src/screens/Dashboard.tsx

View workflow job for this annotation

GitHub Actions / Lint & type-check

Unexpected any. Specify a different type
<li
key={player.id}
className="flex items-center justify-between gap-3 text-sm text-zinc-300"
>
<span className="truncate">
<span className="mr-2 text-zinc-500">#{index + 1}</span>
{player.username}
</span>
<span className="shrink-0 font-semibold text-pink-400">
{player.score} pts
</span>
</li>
))}
</ol>
</div>
)}
</div>
</Link>
))}
Expand Down Expand Up @@ -235,7 +259,7 @@
</tr>
</thead>
<tbody>
{quizzes.participated.map((session: any) => {

Check failure on line 262 in apps/frontend/src/screens/Dashboard.tsx

View workflow job for this annotation

GitHub Actions / Lint & type-check

Unexpected any. Specify a different type
const myData = session.participants[0];
return (
<tr
Expand Down
92 changes: 92 additions & 0 deletions apps/http-server/src/controllers/getAllQuizes.test.ts
Original file line number Diff line number Diff line change
@@ -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([]);
});
});
46 changes: 44 additions & 2 deletions apps/http-server/src/controllers/quizController.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<string, string>();
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<string, typeof rankedParticipants>();
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: {
Expand Down Expand Up @@ -112,7 +154,7 @@ export const getAllQuizesController = async (req: Request, res: Response) => {


return res.status(200).json({
organizedQuizes,
organizedQuizes: organizedQuizesWithPodium,
participated: participatedWithRank
})

Expand Down
14 changes: 2 additions & 12 deletions apps/ws-server/src/utils/cache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { cache } from "../redis.js";
import { prisma } from "@repo/db";
import { getRankedParticipants, prisma } from "@repo/db";


const TTL = {
Expand Down Expand Up @@ -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]),
);
}

Expand Down
33 changes: 27 additions & 6 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
4 changes: 3 additions & 1 deletion packages/db/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export { prisma } from "./client.js"; // exports instance of prisma
export * from "./generated/prisma/client.js"; // exports generated types from prisma
export * from "./generated/prisma/client.js"; // exports generated types from prisma
export { getRankedParticipants } from "./leaderboard.js";
export type { RankedParticipant } from "./leaderboard.js";
26 changes: 26 additions & 0 deletions packages/db/src/leaderboard.ts
Original file line number Diff line number Diff line change
@@ -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<RankedParticipant[]>`
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
`;
}
Loading