Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : tests/integration/prix.test.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website : https://jeux.uqo-eval.app12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Prix remis aux meilleurs rangs (config.prizes) : calculés entre étudiants des cours, les deux groupes45 * confondus ; les participants hors cours n'en reçoivent jamais ; modifiables après publication.46 */47import { afterAll, beforeAll, describe, expect, it } from "vitest";48import { generateBank, publishCompetition } from "../../apps/api/src/bank.ts";49import { ADMIN, Player, closeDatabase, markImagesOk, openServer, resetGameData, sql, type App, type QuestionJson } from "../helpers/api.ts";5051let app: App;52let competitionId = "";53const positionOf = new Map<string, number>();54const players: Record<string, Player> = {};5556interface Row { sessionId: string; displayName: string; course: string | null; rank: number; tied: boolean; correct: number; prize: number | null; prizeTied: boolean; horsConcours: boolean }5758/** Réponses décidées par la position de la propriété dans la banque : deux joueurs au même plan ont exactement les mêmes résultats. */59const plan = (wrongPositions: number[]) => (_i: number, q: QuestionJson) => ({ right: !wrongPositions.includes(positionOf.get(q.id)!), wrongIndex: 0 });6061async function board(query = "", headers: Record<string, string> = {}): Promise<{ competition: { prizes: unknown }; rows: Row[]; me: Row | null; podium: Row[] }> {62 const res = await app.inject({ method: "GET", url: `/api/v1/leaderboard/${competitionId}${query}`, headers });63 expect(res.statusCode).toBe(200);64 return res.json();65}6667const rosterIdOf = new Map<string, string>();6869async function fromRoster(name: string): Promise<Player> {70 const player = new Player(app);71 const res = await player.rawStart({ displayName: "", rosterId: rosterIdOf.get(name)!, competitionId });72 if (res.statusCode !== 200) throw new Error(`Partie de liste refusée (${res.statusCode}) : ${res.body}`);73 return player;74}7576const byName = (rows: Row[]): Record<string, Row> => Object.fromEntries(rows.map((r) => [r.displayName, r]));7778beforeAll(async () => {79 await resetGameData();80 app = await openServer();81 const created = await app.inject({82 method: "POST", url: "/api/v1/admin/competitions", headers: ADMIN,83 payload: { name: "Défi avec prix", size: 4, config: { prizes: { amounts: [100, 50, 25], label: "Bourse du département" } } },84 });85 expect(created.statusCode).toBe(200);86 competitionId = created.json().id;87 await generateBank(competitionId);88 await markImagesOk(competitionId);89 await publishCompetition(competitionId);90 for (const q of await sql<{ id: string; position: number }[]>`select id, position from questions where competition_id = ${competitionId}`) positionOf.set(q.id, q.position);9192 // Listes de classe : seuls les participants qui choisissent leur nom dans la liste sont admissibles aux prix.93 for (const [course, names] of [["IMM1003", ["Sophie Première", "Nadia Deuxième", "Paule Cinquième", "En Cours"]], ["IMM1033", ["Marc Deuxième", "Olivier Quatrième"]]] as const) {94 const res = await app.inject({ method: "PUT", url: "/api/v1/admin/roster", headers: ADMIN, payload: { course, names } });95 expect(res.statusCode).toBe(200);96 }97 // L'enseignant figure dans la liste IMM1003, hors concours (comme le fait `cli roster:add --hors-concours`).98 await sql`insert into roster_entries (course, display_name, name_key, prize_eligible) values ('IMM1003', 'Professeur Démo', 'professeur demo', false)`;99 for (const r of await sql<{ id: string; display_name: string }[]>`select id, display_name from roster_entries`) rosterIdOf.set(r.display_name, r.id);100101 const cast: [string, "liste" | "IMM1003" | null, number[]][] = [102 ["Externe Brillante", null, []], // 4/4, hors cours103 ["Déclarée Sans Liste", "IMM1003", []], // 4/4, déclare un cours sans passer par la liste104 ["Sophie Première", "liste", []], // 4/4105 ["Marc Deuxième", "liste", [2]], // 3/4106 ["Nadia Deuxième", "liste", [2]], // 3/4, mêmes réponses que Marc107 ["Olivier Quatrième", "liste", [1, 2]], // 2/4108 ["Paule Cinquième", "liste", [0, 1, 2]], // 1/4109 ];110 for (const [name, kind, wrong] of cast) {111 const player = kind === "liste" ? await fromRoster(name) : await Player.start(app, { displayName: name, course: kind, competitionId });112 await player.playToEnd(plan(wrong));113 players[name] = player;114 }115 players["En Cours"] = await fromRoster("En Cours");116});117118afterAll(async () => {119 await app.close();120 await closeDatabase();121});122123describe("Prix au classement", () => {124 it("annonce les prix de la compétition", async () => {125 expect((await board()).competition.prizes).toEqual({ amounts: [100, 50, 25], label: "Bourse du département" });126 });127128 it("attribue les montants dans l'ordre des rangs entre étudiants : 1er → 100 $, 2e → 50 $", async () => {129 const rows = byName((await board()).rows);130 expect(rows["Sophie Première"]).toMatchObject({ correct: 4, prize: 100, prizeTied: false });131 expect(rows["Marc Deuxième"]).toMatchObject({ correct: 3, prize: 50 });132 expect(rows["Nadia Deuxième"]).toMatchObject({ correct: 3, prize: 50 });133 });134135 it("un participant hors cours n'a jamais de prix, même premier du classement général", async () => {136 const rows = byName((await board()).rows);137 expect(rows["Externe Brillante"]).toMatchObject({ rank: 1, correct: 4, course: null, prize: null, prizeTied: false });138 // et sa présence ne décale pas les rangs primés : Sophie, 1re ex æquo au général, est seule 1re des étudiants inscrits139 expect(rows["Sophie Première"]).toMatchObject({ rank: 1, tied: true, prize: 100, prizeTied: false });140 });141142 it("déclarer un cours sans choisir son nom dans la liste ne rend pas admissible aux prix", async () => {143 const rows = byName((await board()).rows);144 expect(rows["Déclarée Sans Liste"]).toMatchObject({ rank: 1, correct: 4, course: "IMM1003", prize: null, prizeTied: false });145 const [row] = await sql<{ on_roster: boolean }[]>`select on_roster from leaderboard_entries where session_id = ${players["Déclarée Sans Liste"]!.sessionId}`;146 expect(row!.on_roster).toBe(false);147 const [listed] = await sql<{ on_roster: boolean }[]>`select on_roster from leaderboard_entries where session_id = ${players["Sophie Première"]!.sessionId}`;148 expect(listed!.on_roster).toBe(true);149 // la ligne du classement n'expose pas l'appartenance à la liste150 expect(JSON.stringify(rows["Sophie Première"])).not.toMatch(/on_?roster|roster/i);151 });152153 it("des ex æquo partagent le rang primé et sont signalés (prizeTied) ; le rang suivant saute", async () => {154 const rows = byName((await board()).rows);155 expect(rows["Marc Deuxième"]).toMatchObject({ prize: 50, prizeTied: true });156 expect(rows["Nadia Deuxième"]).toMatchObject({ prize: 50, prizeTied: true });157 // rangs entre étudiants : 1, 2, 2, 4, 5 → le 4e n'a pas de prix (trois montants seulement) ; le 3e prix n'est attribué à personne158 expect(rows["Olivier Quatrième"]).toMatchObject({ correct: 2, prize: null, prizeTied: false });159 expect(rows["Paule Cinquième"]).toMatchObject({ correct: 1, prize: null, prizeTied: false });160 const awarded = Object.values(rows).filter((r) => r.prize !== null).map((r) => r.prize).sort();161 expect(awarded).toEqual([100, 50, 50]);162 });163164 it("calcule les rangs primés les deux groupes confondus (un étudiant IMM1033 peut devancer un IMM1003)", async () => {165 const rows = byName((await board()).rows);166 expect(rows["Marc Deuxième"]!.course).toBe("IMM1033");167 expect(rows["Nadia Deuxième"]!.course).toBe("IMM1003");168 expect(rows["Marc Deuxième"]!.prize).toBe(rows["Nadia Deuxième"]!.prize);169 });170171 it("avec ?cours=, les rangs sont ceux du cours mais les prix restent ceux des deux cours confondus", async () => {172 const imm1003 = byName((await board("?cours=IMM1003")).rows);173 expect(Object.keys(imm1003).sort()).toEqual(["Déclarée Sans Liste", "Nadia Deuxième", "Paule Cinquième", "Sophie Première"]);174 expect(imm1003["Sophie Première"]).toMatchObject({ rank: 1, tied: true, prize: 100, prizeTied: false });175 expect(imm1003["Déclarée Sans Liste"]).toMatchObject({ rank: 1, tied: true, prize: null });176 expect(imm1003["Nadia Deuxième"]).toMatchObject({ rank: 3, tied: false, prize: 50, prizeTied: true });177 // 4e de son cours, 5e des étudiants inscrits : pas de prix178 expect(imm1003["Paule Cinquième"]).toMatchObject({ rank: 4, prize: null });179 const imm1033 = byName((await board("?cours=IMM1033")).rows);180 // 1er de son cours, 2e ex æquo des étudiants : 50 $ et non 100 $181 expect(imm1033["Marc Deuxième"]).toMatchObject({ rank: 1, prize: 50, prizeTied: true });182 expect(imm1033["Olivier Quatrième"]).toMatchObject({ rank: 2, prize: null });183 });184185 it("la recherche par nom et la ligne « moi » portent le même prix que le classement complet", async () => {186 const search = await board("?q=nadia", { "x-game": players["Nadia Deuxième"]!.sessionId });187 expect(search.rows).toHaveLength(1);188 expect(search.rows[0]).toMatchObject({ prize: 50, prizeTied: true });189 expect(search.me).toMatchObject({ displayName: "Nadia Deuxième", prize: 50, prizeTied: true });190 const asExternal = await board("", { "x-game": players["Externe Brillante"]!.sessionId });191 expect(asExternal.me).toMatchObject({ prize: null });192 });193194 it("une partie en cours ne reçoit aucun prix ; terminée, elle entre dans le calcul et déplace les suivants", async () => {195 const before = await board();196 expect(before.rows.some((r) => r.displayName === "En Cours")).toBe(false);197 await players["En Cours"]!.playToEnd(plan([]));198 const rows = byName((await board()).rows);199 // deux étudiantes à 4/4 : elles partagent le 1er prix ; Marc et Nadia passent au 3e rang ex æquo → 25 $200 expect(rows["En Cours"]).toMatchObject({ prize: 100, prizeTied: true });201 expect(rows["Sophie Première"]).toMatchObject({ prize: 100, prizeTied: true });202 expect(rows["Marc Deuxième"]).toMatchObject({ prize: 25, prizeTied: true });203 expect(rows["Nadia Deuxième"]).toMatchObject({ prize: 25, prizeTied: true });204 expect(rows["Olivier Quatrième"]!.prize).toBeNull();205 });206207 it("une partie exclue par l'administration perd son prix et les rangs primés se recalculent", async () => {208 const res = await app.inject({ method: "POST", url: `/api/v1/admin/sessions/${players["En Cours"]!.sessionId}/exclude`, headers: ADMIN, payload: { reason: "Partie jouée par un tiers" } });209 expect(res.statusCode).toBe(200);210 const rows = byName((await board()).rows);211 expect(rows["En Cours"]).toBeUndefined();212 expect(rows["Sophie Première"]).toMatchObject({ prize: 100, prizeTied: false });213 expect(rows["Marc Deuxième"]).toMatchObject({ prize: 50, prizeTied: true });214 });215});216217describe("Participant hors concours (l'enseignant)", () => {218 let before: Row[] = [];219 let prof: Player;220221 it("la liste de classe le signale « hors concours »", async () => {222 const res = await app.inject({ method: "GET", url: `/api/v1/competitions/${competitionId}/roster` });223 const students = (res.json().groups as { course: string; students: { name: string; horsConcours: boolean }[] }[]).find((g) => g.course === "IMM1003")!.students;224 expect(students.find((s) => s.name === "Professeur Démo")!.horsConcours).toBe(true);225 expect(students.filter((s) => s.horsConcours)).toHaveLength(1);226 });227228 it("figure au classement à la place que lui vaut son score, sans rang (rank 0), sans prix, hors podium", async () => {229 before = (await board()).rows;230 prof = await fromRoster("Professeur Démo");231 await prof.playToEnd(plan([])); // 4 sur 4232 const now = await board("", { "x-game": prof.sessionId });233 const row = now.rows.find((r) => r.displayName === "Professeur Démo")!;234 expect(row).toMatchObject({ rank: 0, tied: false, horsConcours: true, correct: 4, prize: null, prizeTied: false, course: "IMM1003" });235 // placé parmi les 4 sur 4, juste après les participants classés de même score, avant les 3 sur 4236 const index = now.rows.indexOf(row);237 expect(now.rows.slice(0, index).every((r) => r.correct === 4 && !r.horsConcours)).toBe(true);238 expect(now.rows.slice(index + 1).every((r) => r.correct < 4)).toBe(true);239 expect(now.podium.some((r) => r.displayName === "Professeur Démo")).toBe(false);240 expect(now.podium.every((r) => r.rank >= 1 && r.rank <= 3 && !r.horsConcours)).toBe(true);241 expect(now.me).toMatchObject({ displayName: "Professeur Démo", rank: 0, horsConcours: true, prize: null });242 });243244 it("ne décale le rang, l'égalité ni le prix de personne", async () => {245 const now = (await board()).rows.filter((r) => r.displayName !== "Professeur Démo");246 expect(now.map((r) => [r.displayName, r.rank, r.tied, r.prize, r.prizeTied, r.horsConcours])).toEqual(before.map((r) => [r.displayName, r.rank, r.tied, r.prize, r.prizeTied, false]));247 // Sophie, seule première des étudiants admissibles, ne partage pas son prix avec lui248 expect(byName(now)["Sophie Première"]).toMatchObject({ prize: 100, prizeTied: false });249 });250251 it("reste sans rang dans l'onglet de son cours, et ses résultats personnels l'annoncent hors concours", async () => {252 const course = byName((await board("?cours=IMM1003")).rows);253 expect(course["Professeur Démo"]).toMatchObject({ rank: 0, horsConcours: true, prize: null });254 expect(course["Sophie Première"]).toMatchObject({ rank: 1, prize: 100 });255 const results = (await prof.get("/api/v1/results/me")).json();256 expect(results.rank).toBeNull();257 expect(results.horsConcours).toBe(true);258 expect(results.summary.correct).toBe(4);259 const sophie = (await players["Sophie Première"]!.get("/api/v1/results/me")).json();260 expect(sophie.horsConcours).toBe(false);261 expect(sophie.rank.rank).toBe(1);262 // « of » : le nombre de participants classés ne devrait pas compter le hors-concours263 const [ranked] = await sql<{ n: number }[]>`select count(*)::int as n from leaderboard_entries where competition_id = ${competitionId} and not hors_concours`;264 expect(sophie.rank.of).toBe(ranked!.n);265 });266267 it("l'export le note « hors concours » à la place du rang", async () => {268 const res = await app.inject({ method: "GET", url: `/api/v1/admin/exports?competitionId=${competitionId}&format=json`, headers: { "x-admin-key": ADMIN["x-admin-key"] } });269 const rows = res.json().rows as { rang: number | string; nom: string }[];270 expect(rows.find((r) => r.nom === "Professeur Démo")!.rang).toBe("hors concours");271 expect(rows.filter((r) => r.rang === "hors concours")).toHaveLength(1);272 expect(rows.filter((r) => r.nom !== "Professeur Démo").every((r) => typeof r.rang === "number" && r.rang >= 1)).toBe(true);273 });274275 it("la vue du classement expose le drapeau, et un inscrit hors concours n'est jamais « admissible aux prix »", async () => {276 const [row] = await sql<{ on_roster: boolean; hors_concours: boolean }[]>`select on_roster, hors_concours from leaderboard_entries where session_id = ${prof.sessionId}`;277 expect(row).toEqual({ on_roster: false, hors_concours: true });278 });279});280281describe("Modification des prix après publication", () => {282 const patch = (payload: Record<string, unknown>) => app.inject({ method: "PATCH", url: `/api/v1/admin/competitions/${competitionId}`, headers: ADMIN, payload });283 const bankState = async (): Promise<string> => {284 const [row] = await sql<{ state: string }[]>`285 select c.bank_version || '|' || c.size || '|' || (select string_agg(q.id::text || ':' || q.correct_price, ',' order by q.position) from questions q where q.competition_id = c.id) as state286 from competitions c where c.id = ${competitionId}`;287 return row!.state;288 };289290 it("accepte de nouveaux montants sur une compétition publiée, sans toucher à la banque, et le classement suit", async () => {291 const before = await bankState();292 const res = await patch({ config: { prizes: { amounts: [300, 200], label: "Bourse bonifiée" } } });293 expect(res.statusCode).toBe(200);294 expect(res.json().config.prizes).toEqual({ amounts: [300, 200], label: "Bourse bonifiée" });295 expect(res.json().status).toBe("published");296 expect(await bankState()).toBe(before);297 const now = await board();298 expect(now.competition.prizes).toEqual({ amounts: [300, 200], label: "Bourse bonifiée" });299 const rows = byName(now.rows);300 expect(rows["Sophie Première"]!.prize).toBe(300);301 expect(rows["Marc Deuxième"]!.prize).toBe(200);302 expect(rows["Olivier Quatrième"]!.prize).toBeNull();303 });304305 it("refuse toujours de changer la taille ou les filtres, même accompagnés de prix (409 bank_immutable)", async () => {306 const before = await bankState();307 const filters = await patch({ config: { categories: ["condo"], prizes: { amounts: [10], label: "Détournement" } } });308 expect(filters.statusCode).toBe(409);309 expect(filters.json().error.code).toBe("bank_immutable");310 const size = await patch({ size: 8, config: { prizes: { amounts: [10], label: "Détournement" } } });311 expect(size.statusCode).toBe(409);312 for (const config of [{ priceMin: 100_000 }, { regionCodes: ["07"] }, { strataExponent: 0.5 }]) {313 expect((await patch({ config })).statusCode, JSON.stringify(config)).toBe(409);314 }315 expect(await bankState()).toBe(before);316 expect((await board()).competition.prizes).toEqual({ amounts: [300, 200], label: "Bourse bonifiée" });317 });318319 it("refuse des prix mal formés (400) sans modifier les prix en vigueur", async () => {320 for (const prizes of [{ amounts: [], label: "Vide" }, { amounts: [0], label: "Nul" }, { amounts: [-5], label: "Négatif" }, { amounts: [10.5], label: "Décimal" }, { amounts: [20_000], label: "Démesuré" }, { amounts: Array.from({ length: 11 }, () => 10), label: "Trop de rangs" }, { amounts: [10], label: "x" }, { amounts: [10] }]) {321 expect((await patch({ config: { prizes } })).statusCode, JSON.stringify(prizes)).toBe(400);322 }323 expect((await board()).competition.prizes).toEqual({ amounts: [300, 200], label: "Bourse bonifiée" });324 });325326 it("exige l'administration : un joueur ne peut pas s'attribuer un prix", async () => {327 const res = await app.inject({ method: "PATCH", url: `/api/v1/admin/competitions/${competitionId}`, headers: { ...players["Paule Cinquième"]!.headers, "x-requested-with": "gdi" }, payload: { config: { prizes: { amounts: [9_999], label: "Auto-attribution" } } } });328 expect(res.statusCode).toBe(401);329 const answer = await players["Paule Cinquième"]!.get("/api/v1/results/me");330 expect(answer.body).not.toContain("9999");331 });332333 it("retire les prix quand la configuration n'en contient plus : plus aucune ligne primée", async () => {334 const res = await patch({ config: {} });335 expect(res.statusCode).toBe(200);336 const now = await board();337 expect(now.competition.prizes).toBeNull();338 expect(now.rows.every((r) => r.prize === null && r.prizeTied === false)).toBe(true);339 });340341 it("journalise chaque modification", async () => {342 const [row] = await sql<{ n: number }[]>`select count(*)::int as n from audit_logs where action = 'competition.update' and target = ${competitionId}`;343 expect(row!.n).toBe(2);344 });345346 it("sur une compétition filtrée, les prix se modifient en renvoyant les mêmes filtres ; les filtres seuls restent figés", async () => {347 const created = await app.inject({ method: "POST", url: "/api/v1/admin/competitions", headers: ADMIN, payload: { name: "Maisons avec prix", size: 4, config: { categories: ["unifamiliale"], regionCodes: ["07", "15"] } } });348 const id = created.json().id as string;349 await generateBank(id);350 await markImagesOk(id);351 await publishCompetition(id);352 const same = await app.inject({ method: "PATCH", url: `/api/v1/admin/competitions/${id}`, headers: ADMIN, payload: { config: { categories: ["unifamiliale"], regionCodes: ["07", "15"], prizes: { amounts: [75], label: "Prix unique" } } } });353 expect(same.statusCode).toBe(200);354 expect(same.json().config).toMatchObject({ categories: ["unifamiliale"], regionCodes: ["07", "15"], prizes: { amounts: [75], label: "Prix unique" } });355 const widened = await app.inject({ method: "PATCH", url: `/api/v1/admin/competitions/${id}`, headers: ADMIN, payload: { config: { categories: ["unifamiliale", "condo"], regionCodes: ["07", "15"], prizes: { amounts: [75], label: "Prix unique" } } } });356 expect(widened.statusCode).toBe(409);357 });358});359