Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : apps/api/src/game.ts9 * Module : api10 * 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 * Competition & Game Engine — sessions, questions, réponses.45 *46 * Toute la logique officielle est ici, côté serveur : ordre des questions,47 * validité des choix, score, séries. Le navigateur ne reçoit jamais le statut48 * correct ou incorrect d'un prix avant d'avoir répondu.49 */50import {51 PHASES,52 answerMetrics,53 buildFeedback,54 createRng,55 detectAnomalies,56 participantOrder,57 phaseOfIndex,58 priceBandOf,59 summarize,60 toPublicCard,61 DIFFICULTY_LABELS,62 type AnswerRecord,63 type Course,64 type Difficulty,65 type Feedback,66 type MarketContext,67 type PropertySnapshot,68 type PublicCard,69} from "@jeux/engine";70import { createTrainingCompetition, getCompetition, getOrCreateDaily, todayInMontreal, type CompetitionConfig, type CompetitionRow } from "./bank.ts";71import { config } from "./config.ts";72import { sql, type Tx } from "./db.ts";73import { publish } from "./live.ts";74import { HttpError, cleanDisplayName, hmac, nameKey, normalizeResumeCode, randomResumeCode, randomToken } from "./util.ts";7576export interface SessionRow {77 id: string;78 participant_id: string;79 competition_id: string;80 name_key: string;81 status: "in_progress" | "completed" | "reset" | "excluded";82 order_seed: string;83 total: number;84 answered: number;85 correct: number;86 current_streak: number;87 best_streak: number;88 sum_rel_error: number;89 started_at: Date;90 last_activity_at: Date;91 completed_at: Date | null;92}9394export interface SessionView {95 id: string;96 mode: CompetitionRow["mode"];97 competitionId: string;98 competitionName: string;99 status: SessionRow["status"];100 displayName: string;101 course: string | null;102 total: number;103 answered: number;104 correct: number;105 streak: number;106 bestStreak: number;107 /** Erreur relative moyenne provisoire, en pourcentage. */108 mape: number;109 /** Heure limite de la compétition : la partie doit être TERMINÉE avant (aucune réponse acceptée ensuite). */110 endsAt: string | null;111}112113export interface QuestionView {114 id: string;115 /** Position dans la partie, à partir de 1. */116 number: number;117 total: number;118 phase: number;119 phaseName: string;120 difficultyLabel: string;121 card: PublicCard;122 images: { id: string; alt: string }[];123 choices: { id: string; price: number }[];124}125126export interface StartInput {127 displayName: string;128 /** Entrée de la liste de classe choisie dans le menu (remplace la saisie du nom). */129 rosterId?: string;130 course: string | null;131 mode: "official" | "training" | "daily";132 competitionId?: string;133 size?: number;134 accessCode?: string;135 training?: CompetitionConfig;136 consent: boolean;137 ipHash: string | null;138}139140export const TRAINING_SIZES = [10, 25, 30, 50, 100];141142async function sessionView(tx: Tx | typeof sql, session: SessionRow): Promise<SessionView> {143 const [row] = await tx<{ name: string; mode: CompetitionRow["mode"]; display_name: string; course: string | null; ends_at: Date | null }[]>`144 select c.name, c.mode, p.display_name, p.course, c.ends_at145 from competitions c, participants p where c.id = ${session.competition_id} and p.id = ${session.participant_id}`;146 return {147 id: session.id,148 mode: row!.mode,149 competitionId: session.competition_id,150 competitionName: row!.name,151 status: session.status,152 displayName: row!.display_name,153 course: row!.course,154 total: session.total,155 answered: session.answered,156 correct: session.correct,157 streak: session.current_streak,158 bestStreak: session.best_streak,159 mape: session.answered ? (100 * session.sum_rel_error) / session.answered : 0,160 endsAt: row!.mode === "official" && row!.ends_at ? row!.ends_at.toISOString() : null,161 };162}163164async function questionView(tx: Tx | typeof sql, session: SessionRow, idx: number, markServed: boolean): Promise<QuestionView | null> {165 if (idx >= session.total) return null;166 const [row] = await tx<{ question_id: string; choice_order: string[]; phase: number; difficulty: Difficulty; snapshot: PropertySnapshot }[]>`167 select sq.question_id, sq.choice_order, q.phase, q.difficulty, q.snapshot168 from game_session_questions sq join questions q on q.id = sq.question_id169 where sq.session_id = ${session.id} and sq.idx = ${idx}`;170 if (!row) return null;171 if (markServed) {172 await tx`update game_session_questions set served_at = now() where session_id = ${session.id} and idx = ${idx} and served_at is null`;173 }174 const choices = await tx<{ id: string; price: number }[]>`select id, price from question_choices where question_id = ${row.question_id}`;175 const byId = new Map(choices.map((c) => [c.id, c]));176 const images = await tx<{ id: string }[]>`177 select id from question_images where question_id = ${row.question_id} and status <> 'failed' order by position`;178 const card = toPublicCard(row.snapshot, hmac(`emplacement:${row.question_id}`));179 const phase = session.total >= 4 ? phaseOfIndex(idx, session.total) : (row.phase as 1 | 2 | 3 | 4);180 const place = [card.sector, card.municipality].filter(Boolean).join(", ");181 return {182 id: row.question_id,183 number: idx + 1,184 total: session.total,185 phase,186 phaseName: PHASES[phase - 1]!.name,187 difficultyLabel: DIFFICULTY_LABELS[row.difficulty],188 card,189 images: images.map((image, i) => ({ id: image.id, alt: `${card.categoryLabel} à ${place} — photographie ${i + 1} sur ${images.length}` })),190 // Ordre propre au participant ; aucun indicateur de bonne réponse.191 choices: row.choice_order.map((id) => ({ id, price: byId.get(id)!.price })),192 };193}194195function assertWindow(competition: CompetitionRow): void {196 if (competition.status !== "published") throw new HttpError(409, "competition_closed", "Cette compétition n'est pas ouverte.");197 const now = Date.now();198 if (competition.starts_at && now < competition.starts_at.getTime()) {199 throw new HttpError(409, "competition_not_started", "Cette compétition n'a pas encore commencé.");200 }201 if (competition.ends_at && now > competition.ends_at.getTime()) {202 throw new HttpError(409, "competition_ended", "Cette compétition est terminée.");203 }204}205206export interface StartResult {207 session: SessionView;208 token: string;209 resumeCode: string;210}211212export async function startSession(input: StartInput): Promise<StartResult> {213 if (!input.consent) throw new HttpError(400, "consent_required", "Vous devez accepter les règles du jeu pour commencer.");214 let displayName = cleanDisplayName(input.displayName);215 let course = input.course === "IMM1003" || input.course === "IMM1033" ? input.course : null;216 let rosterId: string | null = null;217 let guestLabel: string | null = null;218 if (input.rosterId) {219 const [entry] = await sql<{ id: string; course: "IMM1003" | "IMM1033" | "ENSEIGNANT"; display_name: string }[]>`220 select id, course, display_name from roster_entries where id = ${input.rosterId}`;221 if (!entry) throw new HttpError(400, "roster_not_found", "Ce nom ne figure plus dans la liste. Rechargez la page.");222 displayName = entry.display_name;223 // L'enseignant joue hors concours : il n'appartient à aucun groupe d'étudiants.224 course = entry.course === "ENSEIGNANT" ? null : entry.course;225 rosterId = entry.id;226 guestLabel = entry.course === "ENSEIGNANT" ? "Enseignant" : null;227 }228 // Essai libre : aucune identité demandée, un nom d'invité est attribué.229 if (!displayName && input.mode === "training") displayName = `Invité ${1000 + Math.floor(Math.random() * 9000)}`;230 const key = nameKey(displayName);231 if (key.length < 2) throw new HttpError(400, "name_required", "Choisissez votre nom pour commencer.");232233 let competition: CompetitionRow;234 if (input.mode === "training") {235 const size = TRAINING_SIZES.includes(input.size ?? 0) ? input.size! : 10;236 competition = await createTrainingCompetition(size, input.training ?? {});237 } else if (input.mode === "daily") {238 competition = await getOrCreateDaily(todayInMontreal());239 } else {240 if (!input.competitionId) throw new HttpError(400, "competition_required", "Choisissez une compétition.");241 competition = await getCompetition(input.competitionId);242 if (competition.mode !== "official") throw new HttpError(400, "competition_required", "Compétition invalide.");243 assertWindow(competition);244 if (competition.access_code && competition.access_code.trim().toUpperCase() !== (input.accessCode ?? "").trim().toUpperCase()) {245 throw new HttpError(403, "bad_access_code", "Le code de compétition est incorrect.");246 }247 if (course && !competition.courses.includes(course)) {248 throw new HttpError(403, "course_not_allowed", `Cette compétition n'est pas ouverte au cours ${course}.`);249 }250 if (!rosterId) {251 // Si une liste de classe existe pour cette compétition, le nom se choisit dans le menu.252 const [roster] = await sql<{ n: number }[]>`select count(*)::int as n from roster_entries where course = any(${competition.courses})`;253 if ((roster?.n ?? 0) > 0 && !competition.allow_external) {254 throw new HttpError(403, "roster_required", "Choisissez votre nom dans la liste de votre groupe.");255 }256 // Un participant hors liste ne peut pas emprunter le nom d'un étudiant inscrit.257 const [clash] = await sql`select 1 from roster_entries where name_key = ${key} and course = any(${competition.courses})`;258 if (clash) throw new HttpError(403, "roster_required", "Ce nom figure dans une liste de classe : choisissez-le dans le menu de votre groupe.");259 }260 if (!course && !competition.allow_external && !rosterId) {261 throw new HttpError(403, "course_required", "Cette compétition est réservée aux groupes IMM1003 et IMM1033 : indiquez votre cours.");262 }263 }264265 const token = randomToken();266 const resumeCode = randomResumeCode();267 const orderSeed = randomToken(12);268269 try {270 return await sql.begin(async (tx) => {271 const questions = await tx<{ id: string; phase: number; position: number }[]>`272 select id, phase, position from questions where competition_id = ${competition.id} order by position`;273 if (questions.length !== competition.size) throw new HttpError(500, "bank_incomplete", "La banque de cette compétition est incomplète.");274 const choices = await tx<{ id: string; question_id: string; price_rank: number }[]>`275 select c.id, c.question_id, c.price_rank from question_choices c join questions q on q.id = c.question_id276 where q.competition_id = ${competition.id} order by c.question_id, c.price_rank`;277 const [participant] = await tx<{ id: string }[]>`278 insert into participants (display_name, name_key, course, roster_id) values (${displayName}, ${key}, ${course ?? guestLabel}, ${rosterId}) returning id`;279 await tx`insert into consent_records (participant_id, notice_version) values (${participant!.id}, ${config.noticeVersion})`;280 const [session] = await tx<SessionRow[]>`281 insert into game_sessions (participant_id, competition_id, name_key, token_hash, resume_code_hash, order_seed, total, ip_hash)282 values (${participant!.id}, ${competition.id}, ${key}, ${hmac(token)}, ${hmac(resumeCode)}, ${orderSeed}, ${competition.size}, ${input.ipHash})283 returning *`;284 const rng = createRng(orderSeed);285 const ordered = participantOrder(questions, rng);286 const rows = ordered.map((q, idx) => ({287 session_id: session!.id,288 idx,289 question_id: q.id,290 choice_order: rng.fork(`choix:${q.id}`).shuffle(choices.filter((c) => c.question_id === q.id).map((c) => c.id)),291 }));292 await tx`insert into game_session_questions ${tx(rows)}`;293 return { session: await sessionView(tx, session!), token, resumeCode };294 });295 } catch (error) {296 if ((error as { code?: string }).code === "23505" && String((error as { constraint_name?: string }).constraint_name).includes("one_attempt")) {297 throw new HttpError(298 409,299 "name_taken",300 input.mode === "daily"301 ? "Ce nom a déjà relevé le défi du jour. Revenez demain !"302 : "Une partie existe déjà sous ce nom dans cette compétition. Si c'est la vôtre, reprenez-la avec votre code de reprise ; sinon, avisez votre enseignant.",303 );304 }305 throw error;306 }307}308309export async function findSessionByToken(sessionId: string, token: string): Promise<SessionRow | null> {310 const [row] = await sql<SessionRow[]>`select * from game_sessions where id = ${sessionId} and token_hash = ${hmac(token)}`;311 return row ?? null;312}313314/** Reprise par code : émet un nouveau jeton pour l'appareil courant. */315export async function resumeByCode(code: string): Promise<{ session: SessionView; token: string }> {316 const normalized = normalizeResumeCode(code);317 const token = randomToken();318 const [row] = await sql<SessionRow[]>`319 update game_sessions set token_hash = ${hmac(token)}, last_activity_at = now()320 where resume_code_hash = ${hmac(normalized)} and status in ('in_progress', 'completed') returning *`;321 if (!row) throw new HttpError(404, "resume_not_found", "Code de reprise introuvable. Vérifiez les 12 caractères.");322 return { session: await sessionView(sql, row), token };323}324325/** Durée accordée par propriété (secondes) lorsqu'une compétition ne précise rien. 0 = aucun chrono. */326export const DEFAULT_TIME_LIMIT_SECONDS = 60;327/** Marge accordée pour l'animation d'ouverture de la propriété, incluse dans l'échéance transmise au navigateur. */328const OPENING_ALLOWANCE_MS = 2_000;329/** Tolérance du serveur sur la latence du réseau : au-delà, la réponse compte comme hors délai. */330const NETWORK_GRACE_MS = 3_000;331332function timeLimitMs(competition: CompetitionRow): number {333 const seconds = competition.config?.timeLimitSeconds ?? DEFAULT_TIME_LIMIT_SECONDS;334 return seconds > 0 ? seconds * 1000 : 0;335}336337export interface Timing {338 /** Durée accordée par propriété, en secondes (0 = aucun chrono). */339 limitSeconds: number;340 /** Échéance de la propriété en cours (ISO), ou `null` si aucune propriété n'est ouverte. */341 deadline: string | null;342 /** Heure du serveur à l'émission de la réponse : le navigateur s'en sert pour corriger son horloge. */343 serverNow: string;344}345346export interface CurrentState {347 session: SessionView;348 /** Propriété en cours, si elle a été ouverte ; sinon `null` : le joueur doit l'ouvrir (POST /game/next). */349 question: QuestionView | null;350 timing: Timing;351 /** Vrai si cet appel vient de constater l'expiration de la propriété qui était ouverte. */352 lapsed: boolean;353}354355function timingOf(competition: CompetitionRow, servedAt: Date | null): Timing {356 const limit = timeLimitMs(competition);357 return {358 limitSeconds: limit / 1000,359 deadline: servedAt && limit > 0 ? new Date(servedAt.getTime() + limit + OPENING_ALLOWANCE_MS).toISOString() : null,360 serverNow: new Date().toISOString(),361 };362}363364export interface AnswerResult {365 correctChoiceId: string;366 chosenChoiceId: string;367 isCorrect: boolean;368 /** Vrai si le délai est écoulé : la réponse a été enregistrée d'office. */369 timedOut: boolean;370 feedback: Feedback;371 /** Part des participants ayant retenu chaque choix (en %), si l'échantillon le permet. */372 crowd: { n: number; shares: Record<string, number> } | null;373 session: SessionView;374 completed: boolean;375 replayed: boolean;376}377378interface StoredAnswer {379 choice_id: string;380 chosen_price: number;381 idempotency_key: string;382 idx: number;383 timed_out: boolean;384}385386async function crowdShares(tx: Tx | typeof sql, questionId: string): Promise<AnswerResult["crowd"]> {387 const rows = await tx<{ choice_id: string; n: number }[]>`388 select a.choice_id, count(*)::int as n from answers a join game_sessions s on s.id = a.session_id389 where a.question_id = ${questionId} and not a.timed_out and s.status in ('in_progress', 'completed') group by a.choice_id`;390 const total = rows.reduce((acc, r) => acc + r.n, 0);391 if (total < 5) return null;392 return { n: total, shares: Object.fromEntries(rows.map((r) => [r.choice_id, Math.round((100 * r.n) / total)])) };393}394395async function feedbackFor(tx: Tx | typeof sql, questionId: string, chosenPrice: number, course: string | null, timedOut: boolean): Promise<{ feedback: Feedback; correctChoiceId: string }> {396 const [q] = await tx<{ snapshot: PropertySnapshot; context: MarketContext | null; correct_id: string }[]>`397 select q.snapshot, q.context, (select id from question_choices c where c.question_id = q.id and c.is_correct) as correct_id398 from questions q where q.id = ${questionId}`;399 const feedback = buildFeedback(q!.snapshot, q!.context, chosenPrice, questionId, (course as Course | null) ?? null);400 if (timedOut) feedback.headline = "Temps écoulé : aucune réponse validée à temps. La propriété compte comme une erreur.";401 return { feedback, correctChoiceId: q!.correct_id };402}403404/** Enregistre une réponse (ou une expiration du délai) pour la propriété en cours et met la partie à jour. */405async function recordAnswer(406 tx: Tx,407 session: SessionRow,408 questionId: string,409 choiceId: string | null,410 servedAt: Date | null,411 idempotencyKey: string,412): Promise<{ session: SessionRow; choiceId: string; chosenPrice: number; isCorrect: boolean; timedOut: boolean; completed: boolean }> {413 const timedOut = choiceId === null;414 // Hors délai : on retient d'office le choix le plus éloigné du prix affiché (pire erreur possible).415 const [choice] = timedOut416 ? await tx<{ id: string; price: number; correct_price: number }[]>`417 select c.id, c.price, q.correct_price from question_choices c join questions q on q.id = c.question_id418 where c.question_id = ${questionId} order by abs(c.price - q.correct_price) desc, c.price_rank limit 1`419 : await tx<{ id: string; price: number; correct_price: number }[]>`420 select c.id, c.price, q.correct_price from question_choices c join questions q on q.id = c.question_id421 where c.id = ${choiceId} and c.question_id = ${questionId}`;422 if (!choice) throw new HttpError(400, "invalid_choice", "Choix invalide.");423 const metrics = answerMetrics(choice.price, choice.correct_price);424 // Une expiration n'a pas de temps de réponse : le moment où le serveur la constate ne mesure rien.425 const responseMs = servedAt && !timedOut ? Math.min(Date.now() - servedAt.getTime(), 86_400_000) : null;426 await tx`427 insert into answers (session_id, question_id, idx, choice_id, chosen_price, correct_price, is_correct, abs_error, rel_error, signed_rel_error, response_ms, idempotency_key, timed_out)428 values (${session.id}, ${questionId}, ${session.answered}, ${choice.id}, ${choice.price}, ${choice.correct_price},429 ${metrics.isCorrect}, ${metrics.absError}, ${metrics.relError}, ${metrics.signedRelError}, ${responseMs}, ${idempotencyKey}, ${timedOut})`;430 const streak = metrics.isCorrect ? session.current_streak + 1 : 0;431 const answered = session.answered + 1;432 const completed = answered >= session.total;433 const [updated] = await tx<SessionRow[]>`434 update game_sessions set435 answered = ${answered},436 correct = correct + ${metrics.isCorrect ? 1 : 0},437 current_streak = ${streak},438 best_streak = greatest(best_streak, ${streak}),439 sum_rel_error = sum_rel_error + ${metrics.relError},440 last_activity_at = now(),441 status = ${completed ? "completed" : "in_progress"},442 completed_at = ${completed ? tx`now()` : null}443 where id = ${session.id} returning *`;444 if (completed) await finalizeSession(tx, updated!);445 return { session: updated!, choiceId: choice.id, chosenPrice: choice.price, isCorrect: metrics.isCorrect, timedOut, completed };446}447448interface OpenQuestion {449 question_id: string;450 choice_order: string[];451 served_at: Date | null;452}453454/**455 * Si la propriété ouverte a dépassé son délai, enregistre l'expiration. Appelé avant toute lecture456 * ou écriture : fermer l'onglet ou recharger la page n'arrête pas le chrono.457 */458async function expireOpenQuestion(tx: Tx, session: SessionRow, competition: CompetitionRow): Promise<SessionRow> {459 const limit = timeLimitMs(competition);460 if (limit === 0 || session.status !== "in_progress") return session;461 const [open] = await tx<OpenQuestion[]>`462 select question_id, choice_order, served_at from game_session_questions where session_id = ${session.id} and idx = ${session.answered}`;463 if (!open?.served_at) return session;464 if (Date.now() <= open.served_at.getTime() + limit + OPENING_ALLOWANCE_MS + NETWORK_GRACE_MS) return session;465 const result = await recordAnswer(tx, session, open.question_id, null, open.served_at, `expiration:${open.question_id}`);466 return result.session;467}468469/** État de la partie. Ne démarre aucun chrono : une propriété ne s'ouvre que par `openNextQuestion`. */470export async function currentState(sessionRow: SessionRow): Promise<CurrentState> {471 if (sessionRow.status === "reset" || sessionRow.status === "excluded") {472 throw new HttpError(410, "session_closed", "Cette partie n'est plus active.");473 }474 let notify = false;475 const state = await sql.begin(async (tx): Promise<CurrentState> => {476 const [locked] = await tx<SessionRow[]>`select * from game_sessions where id = ${sessionRow.id} for update`;477 const competition = await getCompetition(locked!.competition_id, tx);478 const session = await expireOpenQuestion(tx, locked!, competition);479 notify = session.answered !== locked!.answered;480 let question: QuestionView | null = null;481 let servedAt: Date | null = null;482 if (session.status === "in_progress") {483 const [open] = await tx<OpenQuestion[]>`484 select question_id, choice_order, served_at from game_session_questions where session_id = ${session.id} and idx = ${session.answered}`;485 if (open?.served_at) {486 servedAt = open.served_at;487 question = await questionView(tx, session, session.answered, false);488 }489 }490 return { session: await sessionView(tx, session), question, timing: timingOf(competition, servedAt), lapsed: notify };491 });492 if (notify) publish(state.session.competitionId, state.session.status === "completed" ? "completed" : "progress");493 return state;494}495496/** Ouvre la propriété suivante : c'est ici, et seulement ici, que le chrono démarre. */497export async function openNextQuestion(sessionId: string): Promise<CurrentState> {498 return sql.begin(async (tx): Promise<CurrentState> => {499 const [locked] = await tx<SessionRow[]>`select * from game_sessions where id = ${sessionId} for update`;500 if (!locked) throw new HttpError(404, "session_not_found", "Partie introuvable.");501 const competition = await getCompetition(locked.competition_id, tx);502 const session = await expireOpenQuestion(tx, locked, competition);503 const lapsed = session.answered !== locked.answered;504 // Si la propriété ouverte vient d'expirer, on n'enchaîne pas : le joueur est prévenu et ouvre lui-même la suivante.505 if (session.status !== "in_progress" || lapsed) {506 return { session: await sessionView(tx, session), question: null, timing: timingOf(competition, null), lapsed };507 }508 if (competition.mode === "official") {509 if (competition.status !== "published") throw new HttpError(409, "competition_closed", "Cette compétition est fermée.");510 if (competition.ends_at && Date.now() > competition.ends_at.getTime()) {511 throw new HttpError(409, "competition_ended", "L'heure limite est passée : la partie devait être terminée avant.");512 }513 }514 const [open] = await tx<{ served_at: Date }[]>`515 update game_session_questions set served_at = coalesce(served_at, now())516 where session_id = ${session.id} and idx = ${session.answered} returning served_at`;517 return {518 session: await sessionView(tx, session),519 question: await questionView(tx, session, session.answered, false),520 timing: timingOf(competition, open?.served_at ?? null),521 lapsed: false,522 };523 });524}525526export async function submitAnswer(527 sessionId: string,528 input: { questionId: string; choiceId: string | null; idempotencyKey: string },529): Promise<AnswerResult> {530 const result = await sql.begin(async (tx): Promise<AnswerResult> => {531 // Verrou de ligne : deux soumissions simultanées sont traitées l'une après l'autre.532 const [session] = await tx<SessionRow[]>`select * from game_sessions where id = ${sessionId} for update`;533 if (!session) throw new HttpError(404, "session_not_found", "Partie introuvable.");534 const [participant] = await tx<{ course: string | null }[]>`select course from participants where id = ${session.participant_id}`;535 const course = participant?.course ?? null;536537 const replay = async (existing: StoredAnswer, current: SessionRow): Promise<AnswerResult> => {538 const { feedback, correctChoiceId } = await feedbackFor(tx, input.questionId, existing.chosen_price, course, existing.timed_out);539 return {540 correctChoiceId,541 chosenChoiceId: existing.choice_id,542 isCorrect: !existing.timed_out && existing.choice_id === correctChoiceId,543 timedOut: existing.timed_out,544 feedback,545 crowd: await crowdShares(tx, input.questionId),546 session: await sessionView(tx, current),547 completed: current.status === "completed",548 replayed: true,549 };550 };551552 const [existing] = await tx<StoredAnswer[]>`553 select choice_id, chosen_price, idempotency_key, idx, timed_out from answers where session_id = ${sessionId} and question_id = ${input.questionId}`;554 if (existing) {555 // Rejeu idempotent (double clic, nouvel essai réseau) ou réponse arrivée après l'expiration : résultat déjà enregistré.556 if (!existing.timed_out && existing.idempotency_key !== input.idempotencyKey && existing.choice_id !== input.choiceId) {557 throw new HttpError(409, "already_answered", "Vous avez déjà répondu à cette propriété : la réponse ne peut plus être modifiée.");558 }559 return replay(existing, session);560 }561562 if (session.status !== "in_progress") throw new HttpError(409, "session_not_active", "Cette partie est terminée.");563 const competition = await getCompetition(session.competition_id, tx);564 if (competition.mode === "official" && competition.status !== "published") {565 throw new HttpError(409, "competition_closed", "Cette compétition est fermée.");566 }567 if (competition.mode === "official" && competition.ends_at && Date.now() > competition.ends_at.getTime()) {568 throw new HttpError(409, "competition_ended", "L'heure limite est passée : la partie devait être terminée avant. Les réponses ne sont plus acceptées.");569 }570571 // Ordre imposé : seule la propriété en cours, une fois ouverte, peut recevoir une réponse.572 const [expected] = await tx<OpenQuestion[]>`573 select question_id, choice_order, served_at from game_session_questions where session_id = ${sessionId} and idx = ${session.answered}`;574 if (!expected || expected.question_id !== input.questionId) {575 throw new HttpError(409, "wrong_question", "Cette propriété n'est pas la propriété en cours.");576 }577 if (!expected.served_at) throw new HttpError(409, "question_not_open", "Cette propriété n'a pas encore été ouverte.");578 if (input.choiceId !== null && !expected.choice_order.includes(input.choiceId)) {579 throw new HttpError(400, "invalid_choice", "Ce choix n'appartient pas à cette propriété.");580 }581582 const limit = timeLimitMs(competition);583 const elapsed = Date.now() - expected.served_at.getTime();584 let choiceId = input.choiceId;585 if (limit > 0 && elapsed > limit + OPENING_ALLOWANCE_MS + NETWORK_GRACE_MS) {586 choiceId = null; // arrivée hors délai : le choix transmis n'est pas retenu587 } else if (choiceId === null) {588 if (limit === 0) throw new HttpError(400, "invalid_choice", "Choisissez un prix.");589 // Une expiration ne peut être déclarée qu'une fois le temps réellement écoulé.590 if (elapsed < limit - 1_500) throw new HttpError(409, "too_early", "Le temps n'est pas encore écoulé.");591 }592593 const recorded = await recordAnswer(tx, session, input.questionId, choiceId, expected.served_at, input.idempotencyKey);594 const { feedback, correctChoiceId } = await feedbackFor(tx, input.questionId, recorded.chosenPrice, course, recorded.timedOut);595 return {596 correctChoiceId,597 chosenChoiceId: recorded.choiceId,598 isCorrect: recorded.isCorrect,599 timedOut: recorded.timedOut,600 feedback,601 crowd: await crowdShares(tx, input.questionId),602 session: await sessionView(tx, recorded.session),603 completed: recorded.completed,604 replayed: false,605 };606 });607 publish(result.session.competitionId, result.completed ? "completed" : "progress");608 return result;609}610611export interface AnswerDetail extends AnswerRecord {612 questionId: string;613 isCorrect: boolean;614 absError: number;615 relError: number;616 signedRelError: number;617 responseMs: number | null;618}619620/** Réponses d'une partie, enrichies des attributs de chaque propriété. */621export async function loadAnswerDetails(tx: Tx | typeof sql, sessionId: string): Promise<AnswerDetail[]> {622 const rows = await tx<{623 question_id: string; idx: number; chosen_price: number; correct_price: number; is_correct: boolean; abs_error: number;624 rel_error: number; signed_rel_error: number; response_ms: number | null; phase: number; difficulty: Difficulty;625 category: PropertySnapshot["category"]; region_code: string | null; region_name: string | null; total: number;626 }[]>`627 select a.question_id, a.idx, a.chosen_price, a.correct_price, a.is_correct, a.abs_error, a.rel_error, a.signed_rel_error, a.response_ms,628 q.phase, q.difficulty, q.snapshot->>'category' as category, q.snapshot->>'regionCode' as region_code,629 q.snapshot->>'regionName' as region_name, s.total630 from answers a join questions q on q.id = a.question_id join game_sessions s on s.id = a.session_id631 where a.session_id = ${sessionId} order by a.idx`;632 return rows.map((r) => ({633 questionId: r.question_id,634 index: r.idx,635 chosenPrice: r.chosen_price,636 correctPrice: r.correct_price,637 category: r.category,638 regionCode: r.region_code,639 regionName: r.region_name,640 priceBand: priceBandOf(r.correct_price).key,641 difficulty: r.difficulty,642 phase: r.total >= 4 ? phaseOfIndex(r.idx, r.total) : r.phase,643 isCorrect: r.is_correct,644 absError: r.abs_error,645 relError: r.rel_error,646 signedRelError: r.signed_rel_error,647 responseMs: r.response_ms,648 }));649}650651/** Fin de partie : sommaire officiel recalculé à partir des réponses enregistrées. */652async function finalizeSession(tx: Tx, session: SessionRow): Promise<void> {653 const details = await loadAnswerDetails(tx, session.id);654 const summary = summarize(details);655 await tx`656 insert into score_summaries (session_id, correct, mape, median_rel_error, summary)657 values (${session.id}, ${summary.correct}, ${summary.mape}, ${summary.medianRelError}, ${tx.json(summary as never)})658 on conflict (session_id) do update set correct = excluded.correct, mape = excluded.mape,659 median_rel_error = excluded.median_rel_error, summary = excluded.summary, computed_at = now()`;660 for (const signal of detectAnomalies(details.map((d) => d.responseMs))) {661 await tx`insert into anomalies (session_id, kind, detail) values (${session.id}, ${signal.kind}, ${signal.detail}) on conflict do nothing`;662 }663}664665/** Signalement d'une question par un participant (après y avoir répondu). */666export async function flagQuestion(session: SessionRow, questionId: string, reason: string): Promise<void> {667 const [answered] = await sql`select 1 from answers where session_id = ${session.id} and question_id = ${questionId}`;668 if (!answered) throw new HttpError(403, "not_answered", "Vous pourrez signaler cette propriété après y avoir répondu.");669 const text = reason.replace(/\s+/g, " ").trim().slice(0, 300);670 if (!text) throw new HttpError(400, "reason_required", "Précisez le motif du signalement.");671 const [count] = await sql<{ n: number }[]>`select count(*)::int as n from question_flags where session_id = ${session.id}`;672 const n = count?.n ?? 0;673 if (n >= 20) throw new HttpError(429, "too_many_flags", "Nombre maximal de signalements atteint.");674 await sql`insert into question_flags (question_id, session_id, reason) values (${questionId}, ${session.id}, ${text})`;675}676