SPB Git

Repository Public

api.ts 14.9 KB 329 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : UQO Éval — Le Grand Défi Immobilier8 * File             : tests/helpers/api.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 * Outils des tests d'intégration et de sécurité : serveur Fastify en mémoire45 * (`app.inject`, aucun port ouvert, aucun accès réseau), base `uqo_jeux_test`.46 */47import type { FastifyInstance } from "fastify";48import { createCompetition, generateBank, publishCompetition, validateBank, type CompetitionConfig, type CompetitionRow } from "../../apps/api/src/bank.ts";49import { config } from "../../apps/api/src/config.ts";50import { sql } from "../../apps/api/src/db.ts";51import { buildServer } from "../../apps/api/src/server.ts";5253export { sql, config };54export type App = FastifyInstance;5556export const ADMIN_KEY = "cle-admin-de-test";57export const ADMIN_GET = { "x-admin-key": ADMIN_KEY };58export const ADMIN = { "x-admin-key": ADMIN_KEY, "x-requested-with": "gdi" };59export const XRW = { "x-requested-with": "gdi" };6061/** Garde-fou : ces tests ne s'exécutent que sur la base réservée. */62export async function assertTestDatabase(): Promise<void> {63  if (!/\/uqo_jeux_test$/.test(config.databaseUrl)) throw new Error(`Base de test attendue, reçu ${config.databaseUrl}`);64  const [row] = await sql<{ name: string }[]>`select current_database() as name`;65  if (row!.name !== "uqo_jeux_test") throw new Error(`Connexion inattendue à ${row!.name}`);66  if (config.adminKey !== ADMIN_KEY) throw new Error("ADMIN_KEY de test absente : vitest.config.ts n'a pas été appliqué");67}6869/** Efface compétitions, parties et journaux ; conserve le bassin de propriétés synchronisé. */70export async function resetGameData(): Promise<void> {71  await assertTestDatabase();72  await sql`truncate table competitions, participants, audit_logs restart identity cascade`;73  // Listes de classe (migration 002) : vidées si la table existe, pour que chaque fichier parte du même état.74  const [roster] = await sql<{ present: boolean }[]>`select to_regclass('public.roster_entries') is not null as present`;75  if (roster!.present) await sql`truncate table roster_entries cascade`;76}7778export async function openServer(): Promise<App> {79  await assertTestDatabase();80  const app = await buildServer();81  await app.ready();82  return app;83}8485export async function closeDatabase(): Promise<void> {86  await sql.end({ timeout: 5 });87}8889/**90 * Sans réseau, aucune photographie n'est téléchargée : on inscrit en base le résultat qu'aurait eu la vérification91 * (statut `ok`, dimensions plausibles). `validateBank` exige trois photos vérifiées par propriété.92 */93export async function markImagesOk(competitionId: string): Promise<void> {94  await sql`95    update question_images i set status = 'ok', width = 1600, height = 1067, checked_at = now()96    from questions q where q.id = i.question_id and q.competition_id = ${competitionId} and i.status <> 'ok'`;97}9899export interface NewCompetitionOptions {100  name?: string;101  size?: number;102  seed?: string;103  accessCode?: string | null;104  startsAt?: Date | null;105  endsAt?: Date | null;106  courses?: string[];107  allowExternal?: boolean;108  config?: CompetitionConfig;109  /** Chrono par propriété, en secondes (0 = aucun ; par défaut celui du produit, 60 s). */110  timeLimitSeconds?: number;111  publish?: boolean;112}113114/** Compétition officielle créée par les fonctions de bank.ts (aucun préchargement d'images). */115export async function makeCompetition(options: NewCompetitionOptions = {}): Promise<CompetitionRow> {116  const competition = await createCompetition({117    name: options.name ?? "Compétition de test",118    mode: "official",119    size: options.size ?? 8,120    seed: options.seed ?? `graine-${options.name ?? "test"}-${options.size ?? 8}`,121    accessCode: options.accessCode ?? null,122    startsAt: options.startsAt ?? null,123    endsAt: options.endsAt ?? null,124    courses: options.courses,125    allowExternal: options.allowExternal,126    config: options.timeLimitSeconds === undefined ? options.config : { ...(options.config ?? {}), timeLimitSeconds: options.timeLimitSeconds },127  });128  await generateBank(competition.id);129  await markImagesOk(competition.id);130  const problems = await validateBank(competition.id);131  if (problems.length) throw new Error(`Banque invalide : ${problems.join(" ")}`);132  return options.publish === false ? competition : publishCompetition(competition.id);133}134135export interface OracleChoice { id: string; price: number; is_correct: boolean; price_rank: number }136export interface Oracle { questionId: string; correctPrice: number; sourceRef: string; category: string; regionCode: string | null; choices: OracleChoice[]; correct: OracleChoice; wrong: OracleChoice[] }137138/** Vérité du serveur, lue directement en base : réservée aux tests (le joueur n'y a jamais accès). */139export async function oracle(questionId: string): Promise<Oracle> {140  const [q] = await sql<{ correct_price: number; source_ref: string; category: string; region_code: string | null }[]>`141    select correct_price, source_ref, snapshot->>'category' as category, snapshot->>'regionCode' as region_code from questions where id = ${questionId}`;142  const choices = await sql<OracleChoice[]>`select id, price, is_correct, price_rank from question_choices where question_id = ${questionId} order by price_rank`;143  return {144    questionId, correctPrice: q!.correct_price, sourceRef: q!.source_ref, category: q!.category, regionCode: q!.region_code,145    choices: [...choices], correct: choices.find((c) => c.is_correct)!, wrong: choices.filter((c) => !c.is_correct),146  };147}148149export interface StartBody {150  displayName: string;151  course?: "IMM1003" | "IMM1033" | null;152  mode?: "official" | "training" | "daily";153  competitionId?: string;154  size?: number;155  accessCode?: string;156  consent?: boolean;157  [extra: string]: unknown;158}159160/** Recule l'ouverture de la propriété courante de `seconds` secondes : fait « passer le temps » sans attendre. */161export async function rewindOpenQuestion(sessionId: string, seconds: number): Promise<void> {162  await sql`163    update game_session_questions sq set served_at = served_at - make_interval(secs => ${seconds})164    from game_sessions s where s.id = sq.session_id and s.id = ${sessionId} and sq.idx = s.answered and sq.served_at is not null`;165}166167export interface QuestionJson { id: string; number: number; total: number; phase: number; choices: { id: string; price: number }[]; [k: string]: unknown }168export interface SessionJson { id: string; status: string; total: number; answered: number; correct: number; streak: number; bestStreak: number; mape: number; competitionId: string; displayName: string; mode: string; [k: string]: unknown }169170let keyCounter = 0;171export function newKey(): string {172  keyCounter += 1;173  return `cle-idempotence-${process.pid}-${keyCounter}`;174}175176/** Un participant sur « son appareil » : identifiant de partie + témoin HttpOnly. */177export class Player {178  app: App;179  sessionId = "";180  cookie = "";181  resumeCode = "";182  startResponse: { session: SessionJson; resumeCode: string } | null = null;183  /** Réponses données, dans l'ordre : sert au recalcul indépendant des résultats. */184  played: { questionId: string; chosenPrice: number; correctPrice: number; category: string; regionCode: string | null }[] = [];185186  constructor(app: App) {187    this.app = app;188  }189190  static async start(app: App, body: StartBody): Promise<Player> {191    const player = new Player(app);192    const res = await player.rawStart(body);193    if (res.statusCode !== 200) throw new Error(`Création de partie refusée (${res.statusCode}) : ${res.body}`);194    return player;195  }196197  async rawStart(body: StartBody, headers: Record<string, string> = XRW) {198    const res = await this.app.inject({199      method: "POST", url: "/api/v1/sessions", headers,200      payload: { course: null, mode: "official", consent: true, ...body },201    });202    if (res.statusCode === 200) {203      const json = res.json() as { session: SessionJson; resumeCode: string };204      this.startResponse = json;205      this.sessionId = json.session.id;206      this.resumeCode = json.resumeCode;207      const cookie = res.cookies.find((c) => c.name === `gdi_${this.sessionId.slice(0, 8)}`);208      if (!cookie) throw new Error("Témoin de partie absent de la réponse");209      this.cookie = `${cookie.name}=${cookie.value}`;210    }211    return res;212  }213214  get headers(): Record<string, string> {215    return { "x-game": this.sessionId, cookie: this.cookie };216  }217218  get(url: string, headers: Record<string, string> = this.headers) {219    return this.app.inject({ method: "GET", url, headers });220  }221222  /** État de la partie (lecture seule : ne démarre aucun chrono). */223  current() {224    return this.get("/api/v1/game/current");225  }226227  /** Ouvre la propriété courante (POST /game/next) : c'est ce qui démarre son chrono. */228  next(headers: Record<string, string> = this.headers) {229    return this.app.inject({ method: "POST", url: "/api/v1/game/next", headers, payload: {} });230  }231232  /** Ouvre (ou rouvre) la propriété courante et la renvoie. */233  async question(): Promise<QuestionJson> {234    const res = await this.next();235    if (res.statusCode !== 200) throw new Error(`/game/next ${res.statusCode} : ${res.body}`);236    const q = (res.json() as { question: QuestionJson | null }).question;237    if (!q) throw new Error("Aucune question courante");238    return q;239  }240241  answer(questionId: string, choiceId: string | null, idempotencyKey: string = newKey(), extra: Record<string, unknown> = {}, headers: Record<string, string> = this.headers) {242    return this.app.inject({ method: "POST", url: "/api/v1/game/answer", headers, payload: { questionId, choiceId, idempotencyKey, ...extra } });243  }244245  /** Répond à la question courante : bonne réponse si `right`, sinon le mauvais choix d'indice `wrongIndex`. */246  async answerCurrent(right: boolean, wrongIndex = 0, known?: QuestionJson) {247    const q = known ?? (await this.question());248    const truth = await oracle(q.id);249    const choice = right ? truth.correct : truth.wrong[wrongIndex % truth.wrong.length]!;250    const res = await this.answer(q.id, choice.id);251    if (res.statusCode !== 200) throw new Error(`Réponse refusée (${res.statusCode}) : ${res.body}`);252    this.played.push({ questionId: q.id, chosenPrice: choice.price, correctPrice: truth.correctPrice, category: truth.category, regionCode: truth.regionCode });253    return res.json() as { isCorrect: boolean; completed: boolean; replayed: boolean; timedOut: boolean; session: SessionJson; correctChoiceId: string; chosenChoiceId: string; feedback: Record<string, unknown> };254  }255256  /** Joue jusqu'à la fin (ou `limit` réponses) ; `plan(i, question)` décide de la réponse à la i-ième propriété (0 = première). */257  async playToEnd(plan: (index: number, question: QuestionJson) => { right: boolean; wrongIndex?: number }, limit = Number.POSITIVE_INFINITY): Promise<void> {258    let given = 0;259    while (given < limit) {260      const state = await this.next();261      if (state.statusCode !== 200) throw new Error(`/game/next ${state.statusCode} : ${state.body}`);262      const q = (state.json() as { question: QuestionJson | null }).question;263      if (!q) break;264      given += 1;265      const step = plan(this.played.length, q);266      const result = await this.answerCurrent(step.right, step.wrongIndex ?? 0, q);267      if (result.completed) break;268    }269  }270}271272/** Toutes les clés (à toute profondeur) d'une valeur JSON. */273export function allKeys(value: unknown, out = new Set<string>()): Set<string> {274  if (Array.isArray(value)) for (const item of value) allKeys(item, out);275  else if (value && typeof value === "object") {276    for (const [key, inner] of Object.entries(value)) {277      out.add(key);278      allKeys(inner, out);279    }280  }281  return out;282}283284/** Recalcul indépendant d'un sommaire de partie (ne passe par aucune fonction du moteur). */285export function recompute(played: { chosenPrice: number; correctPrice: number }[]) {286  const rel = played.map((p) => Math.abs(p.chosenPrice - p.correctPrice) / p.correctPrice);287  const signed = played.map((p) => (p.chosenPrice - p.correctPrice) / p.correctPrice);288  const sorted = [...rel].sort((a, b) => a - b);289  const n = played.length;290  const median = n === 0 ? 0 : n % 2 ? sorted[(n - 1) / 2]! : (sorted[n / 2 - 1]! + sorted[n / 2]!) / 2;291  const streaks: number[] = [];292  let run = 0;293  for (const p of played) {294    if (p.chosenPrice === p.correctPrice) run += 1;295    else {296      if (run) streaks.push(run);297      run = 0;298    }299  }300  if (run) streaks.push(run);301  const sum = (values: number[]): number => values.reduce((a, b) => a + b, 0);302  return {303    answered: n,304    correct: played.filter((p) => p.chosenPrice === p.correctPrice).length,305    mape: n ? (100 * sum(rel)) / n : 0,306    medianRelError: 100 * median,307    bias: n ? (100 * sum(signed)) / n : 0,308    meanAbsError: n ? sum(played.map((p) => Math.abs(p.chosenPrice - p.correctPrice))) / n : 0,309    maxAbsError: Math.max(0, ...played.map((p) => Math.abs(p.chosenPrice - p.correctPrice))),310    overestimates: signed.filter((s) => s > 0).length,311    underestimates: signed.filter((s) => s < 0).length,312    streaks,313    bestStreak: Math.max(0, ...streaks),314    currentStreak: run,315  };316}317318/** Titre attendu, d'après le barème de l'énoncé (indépendant du moteur). */319export function expectedTitleKey(correct: number, total: number): string {320  if (correct === total) return "legende";321  const pct = Math.min(99, Math.floor((100 * correct) / total));322  if (pct >= 95) return "maitre";323  if (pct >= 85) return "expert";324  if (pct >= 75) return "stratege";325  if (pct >= 60) return "analyste";326  if (pct >= 40) return "en-formation";327  return "explorateur";328}329
Files main
Menu

Theme