From b3efa2728777983d27e4a38a1509f6dcfbd519e5 Mon Sep 17 00:00:00 2001 From: AyoubBenziza Date: Thu, 11 Jun 2026 17:12:07 +0200 Subject: [PATCH] feat: game history + question lang/active management MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DB: - quiz_question gains `lang` ('fr' default) and `active` (true default); migration 0002 - only active questions are served to games (pool filter) History: - engine writes a game_history row at game end (modes + ranked results), fire-and-forget - public GET /api/history/:code lists a room's recent games - lobby shows a "Parties précédentes" collapsible (date, modes, winner/scores) Back-office: - create form has a FR/EN language select; lang stored - per-question active toggle (PATCH /questions/:id) — disable without deleting; inactive rows dimmed and labelled - seeds set lang (opentdb=en, manual/pokemon=fr) Verified e2e: migration applied; game played → /api/history returns it. Co-Authored-By: Claude Opus 4.8 (1M context) --- apps/server/drizzle/0002_lowly_tenebrous.sql | 2 + apps/server/drizzle/meta/0002_snapshot.json | 302 +++++++++++++++++++ apps/server/drizzle/meta/_journal.json | 7 + apps/server/src/admin/routes.ts | 31 +- apps/server/src/db/history-repo.ts | 55 ++++ apps/server/src/db/quiz-repo.ts | 1 + apps/server/src/db/schema.ts | 7 +- apps/server/src/db/seed-images.ts | 1 + apps/server/src/db/seed.ts | 3 + apps/server/src/game/engine.ts | 13 + apps/server/src/index.ts | 6 + apps/web/src/components/lobby-view.tsx | 38 +++ apps/web/src/lib/admin-api.ts | 8 + apps/web/src/lib/history.ts | 22 ++ apps/web/src/pages/admin.tsx | 40 ++- 15 files changed, 530 insertions(+), 6 deletions(-) create mode 100644 apps/server/drizzle/0002_lowly_tenebrous.sql create mode 100644 apps/server/drizzle/meta/0002_snapshot.json create mode 100644 apps/server/src/db/history-repo.ts create mode 100644 apps/web/src/lib/history.ts diff --git a/apps/server/drizzle/0002_lowly_tenebrous.sql b/apps/server/drizzle/0002_lowly_tenebrous.sql new file mode 100644 index 0000000..0a04f99 --- /dev/null +++ b/apps/server/drizzle/0002_lowly_tenebrous.sql @@ -0,0 +1,2 @@ +ALTER TABLE "quiz_question" ADD COLUMN "lang" text DEFAULT 'fr' NOT NULL;--> statement-breakpoint +ALTER TABLE "quiz_question" ADD COLUMN "active" boolean DEFAULT true NOT NULL; \ No newline at end of file diff --git a/apps/server/drizzle/meta/0002_snapshot.json b/apps/server/drizzle/meta/0002_snapshot.json new file mode 100644 index 0000000..01d2ac0 --- /dev/null +++ b/apps/server/drizzle/meta/0002_snapshot.json @@ -0,0 +1,302 @@ +{ + "id": "7df3d3d1-dbf0-445e-a5c1-5ef4872a80de", + "prevId": "6de8c2ee-3634-455b-ba4b-372368fc2e66", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.game_history": { + "name": "game_history", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "room_code": { + "name": "room_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "played_at": { + "name": "played_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "modes": { + "name": "modes", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "results": { + "name": "results", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.quiz_category": { + "name": "quiz_category", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "quiz_category_name_unique": { + "name": "quiz_category_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.quiz_played": { + "name": "quiz_played", + "schema": "", + "columns": { + "question_id": { + "name": "question_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "room_code": { + "name": "room_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "played_at": { + "name": "played_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "quiz_played_question_id_quiz_question_id_fk": { + "name": "quiz_played_question_id_quiz_question_id_fk", + "tableFrom": "quiz_played", + "tableTo": "quiz_question", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "quiz_played_question_id_room_code_pk": { + "name": "quiz_played_question_id_room_code_pk", + "columns": [ + "question_id", + "room_code" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.quiz_question": { + "name": "quiz_question", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "category_id": { + "name": "category_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "format": { + "name": "format", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "difficulty": { + "name": "difficulty", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "lang": { + "name": "lang", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'fr'" + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "choices": { + "name": "choices", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "correct_index": { + "name": "correct_index", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "accepted_answers": { + "name": "accepted_answers", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "image_url": { + "name": "image_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "quiz_question_prompt_unique": { + "name": "quiz_question_prompt_unique", + "columns": [ + { + "expression": "prompt", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"quiz_question\".\"format\" <> 'image_reveal'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "quiz_question_image_unique": { + "name": "quiz_question_image_unique", + "columns": [ + { + "expression": "image_url", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"quiz_question\".\"image_url\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "quiz_question_category_id_quiz_category_id_fk": { + "name": "quiz_question_category_id_quiz_category_id_fk", + "tableFrom": "quiz_question", + "tableTo": "quiz_category", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/apps/server/drizzle/meta/_journal.json b/apps/server/drizzle/meta/_journal.json index 985351f..7f8f078 100644 --- a/apps/server/drizzle/meta/_journal.json +++ b/apps/server/drizzle/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1781129455626, "tag": "0001_fancy_captain_stacy", "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1781185531830, + "tag": "0002_lowly_tenebrous", + "breakpoints": true } ] } \ No newline at end of file diff --git a/apps/server/src/admin/routes.ts b/apps/server/src/admin/routes.ts index acc961f..8b69f33 100644 --- a/apps/server/src/admin/routes.ts +++ b/apps/server/src/admin/routes.ts @@ -19,6 +19,7 @@ interface CreateBody { prompt?: string category?: string difficulty?: number + lang?: string choices?: string[] correctIndex?: number acceptedAnswers?: string[] @@ -46,7 +47,14 @@ function validate( return { error: "Difficulté invalide (1 à 3)." } } - const base = { categoryId, format, prompt, difficulty, source: "manual" } + const base = { + categoryId, + format, + prompt, + difficulty, + source: "manual", + lang: body.lang === "en" ? "en" : "fr", + } if (format === "free" || format === "image_reveal") { const answers = (body.acceptedAnswers ?? []) @@ -138,6 +146,8 @@ export async function adminRoutes(app: FastifyInstance) { correctIndex: quizQuestion.correctIndex, acceptedAnswers: quizQuestion.acceptedAnswers, imageUrl: quizQuestion.imageUrl, + lang: quizQuestion.lang, + active: quizQuestion.active, category: quizCategory.name, }) .from(quizQuestion) @@ -174,6 +184,25 @@ export async function adminRoutes(app: FastifyInstance) { return reply.code(201).send({ id: inserted[0].id }) }) + app.patch<{ Params: { id: string }; Body: { active?: boolean } }>( + "/questions/:id", + async (req, reply) => { + const active = req.body?.active + if (typeof active !== "boolean") { + return reply.code(400).send({ error: "Champ 'active' requis." }) + } + const updated = await db! + .update(quizQuestion) + .set({ active }) + .where(eq(quizQuestion.id, req.params.id)) + .returning({ id: quizQuestion.id }) + if (updated.length === 0) { + return reply.code(404).send({ error: "Question introuvable." }) + } + return { ok: true } + } + ) + app.delete<{ Params: { id: string } }>("/questions/:id", async (req, reply) => { const deleted = await db! .delete(quizQuestion) diff --git a/apps/server/src/db/history-repo.ts b/apps/server/src/db/history-repo.ts new file mode 100644 index 0000000..5495e42 --- /dev/null +++ b/apps/server/src/db/history-repo.ts @@ -0,0 +1,55 @@ +// Historique de parties (table game_history). No-op si pas de DB. + +import { desc, eq } from "drizzle-orm" +import { db } from "./index" +import { gameHistory } from "./schema" + +export interface GameResultEntry { + name: string + score: number +} + +export async function saveGameHistory( + roomCode: string, + modes: string[], + results: GameResultEntry[] +): Promise { + if (!db) { + return + } + await db.insert(gameHistory).values({ roomCode, modes, results }) +} + +export interface GameHistoryRow { + id: string + playedAt: string + modes: string[] + results: GameResultEntry[] +} + +export async function listGameHistory( + roomCode: string, + limit = 10 +): Promise { + if (!db) { + return [] + } + const rows = await db + .select({ + id: gameHistory.id, + playedAt: gameHistory.playedAt, + modes: gameHistory.modes, + results: gameHistory.results, + }) + .from(gameHistory) + .where(eq(gameHistory.roomCode, roomCode)) + .orderBy(desc(gameHistory.playedAt)) + .limit(limit) + return rows.map((r) => ({ + id: r.id, + playedAt: + r.playedAt instanceof Date ? r.playedAt.toISOString() : String(r.playedAt), + modes: (r.modes as string[]) ?? [], + results: (r.results as GameResultEntry[]) ?? [], + })) +} diff --git a/apps/server/src/db/quiz-repo.ts b/apps/server/src/db/quiz-repo.ts index 1c39a17..38fc639 100644 --- a/apps/server/src/db/quiz-repo.ts +++ b/apps/server/src/db/quiz-repo.ts @@ -51,6 +51,7 @@ export async function loadQuizPool( .leftJoin(quizCategory, eq(quizQuestion.categoryId, quizCategory.id)) .where( and( + eq(quizQuestion.active, true), inArray(quizQuestion.format, formats), categories.length > 0 ? inArray(quizCategory.name, categories) diff --git a/apps/server/src/db/schema.ts b/apps/server/src/db/schema.ts index 778bc75..12d07ca 100644 --- a/apps/server/src/db/schema.ts +++ b/apps/server/src/db/schema.ts @@ -3,6 +3,7 @@ import { sql } from "drizzle-orm" import { + boolean, integer, jsonb, pgTable, @@ -31,8 +32,12 @@ export const quizQuestion = pgTable( prompt: text("prompt").notNull(), /** 1 (facile) .. 3 (difficile). */ difficulty: integer("difficulty").notNull().default(1), - /** 'opentdb' | 'manual' */ + /** 'opentdb' | 'manual' | 'pokeapi' */ source: text("source").notNull(), + /** Langue de la question ('fr' | 'en'). */ + lang: text("lang").notNull().default("fr"), + /** Désactivée (back-office) : exclue des parties sans être supprimée. */ + active: boolean("active").notNull().default(true), // Champs selon le format (NULL si non applicable) : choices: jsonb("choices").$type(), correctIndex: integer("correct_index"), diff --git a/apps/server/src/db/seed-images.ts b/apps/server/src/db/seed-images.ts index 8cfcb7c..7c642b4 100644 --- a/apps/server/src/db/seed-images.ts +++ b/apps/server/src/db/seed-images.ts @@ -64,6 +64,7 @@ async function fetchPokemon(id: number): Promise { prompt: PROMPT, difficulty: 2, source: "pokeapi", + lang: "fr", acceptedAnswers: answers, imageUrl: art, } diff --git a/apps/server/src/db/seed.ts b/apps/server/src/db/seed.ts index e1f9579..6af9d3c 100644 --- a/apps/server/src/db/seed.ts +++ b/apps/server/src/db/seed.ts @@ -113,6 +113,7 @@ function toQuestion( prompt, difficulty, source: "opentdb", + lang: "en", choices: ["True", "False"], correctIndex: correct === "True" ? 0 : 1, } @@ -128,6 +129,7 @@ function toQuestion( prompt, difficulty, source: "opentdb", + lang: "en", choices, correctIndex: choices.indexOf(correct), } @@ -177,6 +179,7 @@ async function seedManual(): Promise { prompt: q.prompt, difficulty: q.difficulty, source: "manual", + lang: "fr", choices: q.choices, correctIndex: q.correctIndex, acceptedAnswers: q.acceptedAnswers, diff --git a/apps/server/src/game/engine.ts b/apps/server/src/game/engine.ts index 899685d..c0097b0 100644 --- a/apps/server/src/game/engine.ts +++ b/apps/server/src/game/engine.ts @@ -11,6 +11,7 @@ import type { } from "@nerdware/shared" import type { IoServer } from "../socket" import type { RoomManager, ServerRoom } from "../rooms" +import { saveGameHistory } from "../db/history-repo" import { createRound as defaultCreateRound, type RoundFactory } from "./registry" import type { GameRound, RoomGameController, RoundContext } from "./round" @@ -87,6 +88,18 @@ export class GameEngine implements RoomGameController { tracks: tracks.length > 0 ? tracks : undefined, recap: this.history.length > 0 ? this.history : undefined, }) + + // Historique (fire-and-forget, DB optionnelle). + const modes = [...new Set(this.room.settings.rounds.map((r) => r.type))] + const results = this.scoreboard() + .map((s) => ({ + name: this.room.players.get(s.playerId)?.name ?? "?", + score: s.score, + })) + .sort((a, b) => b.score - a.score) + void saveGameHistory(this.room.code, modes, results).catch((err) => + console.error("[history] save failed", err) + ) } /** Vote d'un joueur pendant une manche. Délègue à l'épreuve, puis check fin anticipée. */ diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index f0f9390..f2a03ca 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -8,6 +8,7 @@ import { env, isDev } from "./env" import { createSocketServer } from "./socket" import { adminRoutes } from "./admin/routes" import { listCategories } from "./db/quiz-repo" +import { listGameHistory } from "./db/history-repo" import "./game/modes" // enregistre les épreuves (registerRound) const app = Fastify({ @@ -29,6 +30,11 @@ app.get("/health", async () => ({ status: "ok", uptime: process.uptime() })) // Catégories de quiz disponibles (public, pour le filtre du lobby). app.get("/api/categories", async () => listCategories()) +// Historique des parties d'une room (public). +app.get<{ Params: { code: string } }>("/api/history/:code", async (req) => + listGameHistory(req.params.code.toUpperCase()) +) + await app.register(adminRoutes, { prefix: "/api/admin" }) // Socket.IO se greffe sur le serveur HTTP sous-jacent de Fastify. diff --git a/apps/web/src/components/lobby-view.tsx b/apps/web/src/components/lobby-view.tsx index c25f227..ac9fd09 100644 --- a/apps/web/src/components/lobby-view.tsx +++ b/apps/web/src/components/lobby-view.tsx @@ -16,6 +16,7 @@ import { } from "lucide-react" import { SiYoutube } from "@icons-pack/react-simple-icons" import { fetchCategories } from "@/lib/categories" +import { fetchHistory } from "@/lib/history" import type { BlindtestMode, GameType, @@ -140,6 +141,11 @@ export function LobbyView({ snapshot }: { snapshot: RoomSnapshot }) { snapshot.settings const allCategories = useQuery({ queryKey: ["categories"], queryFn: fetchCategories }).data ?? [] + const history = + useQuery({ + queryKey: ["history", snapshot.code], + queryFn: () => fetchHistory(snapshot.code), + }).data ?? [] const [quizCount, setQuizCount] = useState(5) const [imageCount, setImageCount] = useState(5) @@ -433,6 +439,38 @@ export function LobbyView({ snapshot }: { snapshot: RoomSnapshot }) { )} {error &&

{error}

} + + {history.length > 0 && ( +
+ + Parties précédentes ({history.length}) + +
    + {history.map((g) => { + const top = [...g.results].sort((a, b) => b.score - a.score) + return ( +
  • +

    + {new Date(g.playedAt).toLocaleString("fr-FR", { + dateStyle: "short", + timeStyle: "short", + })} + {" · "} + {g.modes.join(", ")} +

    +

    + 🏆 {top[0]?.name ?? "?"} + + {" "} + — {top.map((r) => `${r.name} ${r.score}`).join(" · ")} + +

    +
  • + ) + })} +
+
+ )} ) diff --git a/apps/web/src/lib/admin-api.ts b/apps/web/src/lib/admin-api.ts index 5a277a8..63e6f1d 100644 --- a/apps/web/src/lib/admin-api.ts +++ b/apps/web/src/lib/admin-api.ts @@ -25,6 +25,8 @@ export interface AdminQuestion { correctIndex: number | null acceptedAnswers: string[] | null imageUrl: string | null + lang: string + active: boolean category: string | null } @@ -33,6 +35,7 @@ export interface NewQuestionInput { prompt: string category: string difficulty: number + lang?: string choices?: string[] correctIndex?: number acceptedAnswers?: string[] @@ -83,6 +86,11 @@ export const adminApi = { method: "POST", body: JSON.stringify(input), }), + setActive: (id: string, active: boolean) => + request<{ ok: true }>(`/questions/${id}`, { + method: "PATCH", + body: JSON.stringify({ active }), + }), deleteQuestion: (id: string) => request<{ ok: true }>(`/questions/${id}`, { method: "DELETE" }), } diff --git a/apps/web/src/lib/history.ts b/apps/web/src/lib/history.ts new file mode 100644 index 0000000..64f2517 --- /dev/null +++ b/apps/web/src/lib/history.ts @@ -0,0 +1,22 @@ +// Historique public des parties d'une room. + +const SERVER_URL = import.meta.env.VITE_SERVER_URL ?? "http://localhost:3001" + +export interface GameHistoryEntry { + id: string + playedAt: string + modes: string[] + results: { name: string; score: number }[] +} + +export async function fetchHistory(code: string): Promise { + try { + const res = await fetch(`${SERVER_URL}/api/history/${code}`) + if (!res.ok) { + return [] + } + return (await res.json()) as GameHistoryEntry[] + } catch { + return [] + } +} diff --git a/apps/web/src/pages/admin.tsx b/apps/web/src/pages/admin.tsx index 4bf1d3d..6e19c64 100644 --- a/apps/web/src/pages/admin.tsx +++ b/apps/web/src/pages/admin.tsx @@ -1,7 +1,7 @@ import { useRef, useState } from "react" import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" import { Link } from "wouter" -import { Trash2, Upload } from "lucide-react" +import { Eye, EyeOff, Trash2, Upload } from "lucide-react" import type { QuizFormat } from "@nerdware/shared" import { Button } from "@workspace/ui/components/button" import { @@ -86,6 +86,12 @@ function AdminPanel({ onLogout }: { onLogout: () => void }) { onSuccess: () => qc.invalidateQueries({ queryKey: ["admin-questions"] }), }) + const toggle = useMutation({ + mutationFn: ({ id, active }: { id: string; active: boolean }) => + adminApi.setActive(id, active), + onSuccess: () => qc.invalidateQueries({ queryKey: ["admin-questions"] }), + }) + const unauthorized = questions.isError && /401|autoris/i.test(String(questions.error)) @@ -126,6 +132,7 @@ function AdminPanel({ onLogout }: { onLogout: () => void }) { key={q.id} q={q} onDelete={() => remove.mutate(q.id)} + onToggle={() => toggle.mutate({ id: q.id, active: !q.active })} deleting={remove.isPending} /> ))} @@ -140,14 +147,20 @@ function AdminPanel({ onLogout }: { onLogout: () => void }) { function QuestionRow({ q, onDelete, + onToggle, deleting, }: { q: AdminQuestion onDelete: () => void + onToggle: () => void deleting: boolean }) { return ( -
  • +
  • {q.format === "image_reveal" && q.imageUrl && (

    {q.prompt}

    - {q.format} · {q.category ?? "—"} · diff. {q.difficulty} · {q.source} + {q.format} · {q.category ?? "—"} · diff. {q.difficulty} ·{" "} + {q.lang.toUpperCase()} · {q.source} + {!q.active && " · désactivée"}

    {q.format === "free" || q.format === "image_reveal" ? (

    @@ -172,6 +187,14 @@ function QuestionRow({

    )} +