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/bank.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 * Compétitions et banques de questions.45 *46 * Une banque est générée de façon déterministe à partir de la graine de la47 * compétition ; elle devient immuable dès la publication.48 */49import crypto from "node:crypto";50import {51 buildMarketContext,52 createRng,53 generateChoices,54 selectProperties,55 toSnapshot,56 type Category,57 type ComparableLookup,58 type Difficulty,59 type DifficultyBand,60 type NormalizedProperty,61} from "@jeux/engine";62import { sql, type Tx } from "./db.ts";63import { HttpError, slugify } from "./util.ts";6465export interface CompetitionConfig {66 categories?: Category[];67 regionCodes?: string[];68 priceMin?: number;69 priceMax?: number;70 bands?: Record<Difficulty, DifficultyBand>;71 fixedDifficulty?: Difficulty;72 strataExponent?: number;73 /** Prix remis aux meilleurs rangs parmi les étudiants des cours (montants en dollars, du 1er au dernier rang primé). */74 prizes?: { amounts: number[]; label: string };75 /** Temps accordé par propriété, en secondes (défaut 60 ; 0 = aucun chrono). Ne touche pas à la banque. */76 timeLimitSeconds?: number;77 /** Compteur de régénération des choix (fait varier la graine). */78 distractorNonce?: number;79}8081export interface CompetitionRow {82 id: string;83 slug: string;84 name: string;85 mode: "official" | "training" | "daily";86 status: "draft" | "published" | "closed" | "archived";87 courses: string[];88 allow_external: boolean;89 starts_at: Date | null;90 ends_at: Date | null;91 access_code: string | null;92 size: number;93 config: CompetitionConfig;94 seed: string;95 bank_version: number;96 daily_date: string | null;97 notes: string | null;98 created_at: Date;99 published_at: Date | null;100 closed_at: Date | null;101}102103export const MAX_IMAGES_PER_QUESTION = 14;104105export async function getCompetition(id: string, tx: Tx | typeof sql = sql): Promise<CompetitionRow> {106 const [row] = await tx<CompetitionRow[]>`select * from competitions where id = ${id}`;107 if (!row) throw new HttpError(404, "competition_not_found", "Compétition introuvable.");108 return row;109}110111export interface NewCompetition {112 name: string;113 mode: CompetitionRow["mode"];114 size: number;115 courses?: string[];116 allowExternal?: boolean;117 startsAt?: Date | null;118 endsAt?: Date | null;119 accessCode?: string | null;120 config?: CompetitionConfig;121 seed?: string;122 dailyDate?: string | null;123 notes?: string | null;124}125126export async function createCompetition(input: NewCompetition, tx: Tx | typeof sql = sql): Promise<CompetitionRow> {127 const base = slugify(input.name) || "competition";128 const slug = `${base}-${crypto.randomBytes(3).toString("hex")}`;129 const [row] = await tx<CompetitionRow[]>`130 insert into competitions (slug, name, mode, size, courses, allow_external, starts_at, ends_at, access_code, config, seed, daily_date, notes)131 values (${slug}, ${input.name}, ${input.mode}, ${input.size}, ${input.courses ?? ["IMM1003", "IMM1033"]},132 ${input.allowExternal ?? true}, ${input.startsAt ?? null}, ${input.endsAt ?? null}, ${input.accessCode || null},133 ${tx.json((input.config ?? {}) as never)}, ${input.seed ?? crypto.randomBytes(8).toString("hex")},134 ${input.dailyDate ?? null}, ${input.notes ?? null})135 returning *`;136 return row!;137}138139interface PoolRow {140 id: string;141 data: NormalizedProperty;142}143144async function loadPool(tx: Tx | typeof sql, cfg: CompetitionConfig, sample?: { limit: number; salt: string }): Promise<PoolRow[]> {145 const categories = cfg.categories?.length ? cfg.categories : null;146 const regions = cfg.regionCodes?.length ? cfg.regionCodes : null;147 return tx<PoolRow[]>`148 select id, data from properties149 where eligible and active150 and (${categories}::text[] is null or category = any(${categories}))151 and (${regions}::text[] is null or region_code = any(${regions}))152 and (${cfg.priceMin ?? null}::int is null or price >= ${cfg.priceMin ?? null})153 and (${cfg.priceMax ?? null}::int is null or price <= ${cfg.priceMax ?? null})154 ${sample ? tx`order by md5(source_ref || ${sample.salt}) limit ${sample.limit}` : tx`order by source_ref`}`;155}156157async function marketLookup(tx: Tx | typeof sql): Promise<ComparableLookup> {158 const rows = await tx<{ scope: string; category: string; key: string; prices: number[]; per_sqft: number[] }[]>`159 select scope, category, key, prices, per_sqft from market_stats`;160 const map = new Map(rows.map((r) => [`${r.scope}|${r.category}|${r.key}`, { prices: r.prices, perSqft: r.per_sqft }]));161 return (scope, category, key) => map.get(`${scope}|${category}|${key}`) ?? null;162}163164interface PriceMarket {165 bounds: Map<string, { floor: number; ceil: number }>;166 /** Tous les prix affichés admissibles, triés, doublons conservés : réservoir des prix fictifs. */167 prices: number[];168}169170/** Marché de référence pour la génération des prix fictifs. */171async function priceMarket(tx: Tx | typeof sql): Promise<PriceMarket> {172 const rows = await tx<{ price: number }[]>`select price from properties where eligible and active order by price`;173 return { bounds: await priceBounds(tx), prices: rows.map((r) => r.price) };174}175176/** Bornes de plausibilité par catégorie (centiles 0,5 et 99,5 des prix affichés). */177async function priceBounds(tx: Tx | typeof sql): Promise<Map<string, { floor: number; ceil: number }>> {178 const rows = await tx<{ category: string; lo: number; hi: number }[]>`179 select category,180 percentile_cont(0.005) within group (order by price) as lo,181 percentile_cont(0.995) within group (order by price) as hi182 from properties where eligible and active group by category`;183 return new Map(rows.map((r) => [r.category, { floor: Math.floor(Number(r.lo) * 0.7), ceil: Math.ceil(Number(r.hi) * 1.3) }]));184}185186async function insertChoices(187 tx: Tx,188 questionId: string,189 price: number,190 difficulty: Difficulty,191 category: string,192 seed: string,193 cfg: CompetitionConfig,194 market: PriceMarket,195): Promise<void> {196 const b = market.bounds.get(category);197 const generated = generateChoices(price, difficulty, createRng(seed), {198 bands: cfg.bands,199 floorPrice: b?.floor,200 ceilPrice: b?.ceil,201 marketPrices: market.prices,202 });203 const rows = generated.prices.map((p, rank) => ({ question_id: questionId, price: p, is_correct: p === price, price_rank: rank }));204 await tx`insert into question_choices ${tx(rows)}`;205}206207/** (Re)génère la banque d'une compétition en brouillon. */208export async function generateBank(competitionId: string, sample?: { limit: number; salt: string }, outer?: Tx): Promise<number> {209 const run = async (tx: Tx): Promise<number> => {210 const [competition] = await tx<CompetitionRow[]>`select * from competitions where id = ${competitionId} for update`;211 if (!competition) throw new HttpError(404, "competition_not_found", "Compétition introuvable.");212 if (competition.status !== "draft") {213 throw new HttpError(409, "bank_immutable", "La banque d'une compétition publiée est immuable.");214 }215 const cfg = competition.config ?? {};216 const pool = await loadPool(tx, cfg, sample);217 const version = competition.bank_version + 1;218 const idBySource = new Map(pool.map((r) => [r.data.sourceUid, r.id]));219 let selected;220 try {221 selected = selectProperties(222 pool.map((r) => r.data),223 {224 size: competition.size,225 fixedDifficulty: cfg.fixedDifficulty,226 strataExponent: cfg.strataExponent,227 },228 createRng(`${competition.seed}:banque:v${version}`),229 );230 } catch (error) {231 throw new HttpError(422, "pool_too_small", (error as Error).message);232 }233 const lookup = await marketLookup(tx);234 const bounds = await priceMarket(tx);235 await tx`delete from questions where competition_id = ${competitionId}`;236 let position = 0;237 for (const item of selected) {238 const p = item.property;239 const [question] = await tx<{ id: string }[]>`240 insert into questions (competition_id, property_id, source_ref, position, phase, difficulty, atypicality, correct_price, snapshot, context, bank_version)241 values (${competitionId}, ${idBySource.get(p.sourceUid) ?? null}, ${p.sourceUid}, ${position}, ${item.phase}, ${item.difficulty},242 ${item.atypicality}, ${p.price}, ${tx.json(toSnapshot(p) as never)}, ${tx.json(buildMarketContext(p, lookup) as never)}, ${version})243 returning id`;244 await insertChoices(tx, question!.id, p.price, item.difficulty, p.category, `${competition.seed}:choix:v${version}:${p.sourceUid}:${cfg.distractorNonce ?? 0}`, cfg, bounds);245 const images = p.imageUrls.slice(0, MAX_IMAGES_PER_QUESTION).map((url, i) => ({ question_id: question!.id, position: i, source_url: url }));246 if (images.length) await tx`insert into question_images ${tx(images)}`;247 position += 1;248 }249 await tx`update competitions set bank_version = ${version} where id = ${competitionId}`;250 return selected.length;251 };252 return outer ? run(outer) : sql.begin(run);253}254255/** Régénère les trois mauvaises réponses (toutes les questions, ou une seule) avant publication. */256export async function regenerateDistractors(competitionId: string, questionId?: string): Promise<number> {257 return sql.begin(async (tx) => {258 const [competition] = await tx<CompetitionRow[]>`select * from competitions where id = ${competitionId} for update`;259 if (!competition) throw new HttpError(404, "competition_not_found", "Compétition introuvable.");260 if (competition.status !== "draft") {261 throw new HttpError(409, "bank_immutable", "Les choix d'une compétition publiée ne peuvent plus être régénérés.");262 }263 const nonce = (competition.config.distractorNonce ?? 0) + 1;264 const cfg = { ...competition.config, distractorNonce: nonce };265 await tx`update competitions set config = ${tx.json(cfg as never)} where id = ${competitionId}`;266 const questions = await tx<{ id: string; correct_price: number; difficulty: Difficulty; source_ref: string; category: string }[]>`267 select id, correct_price, difficulty, source_ref, snapshot->>'category' as category from questions268 where competition_id = ${competitionId} and (${questionId ?? null}::uuid is null or id = ${questionId ?? null})`;269 const bounds = await priceMarket(tx);270 for (const q of questions) {271 await tx`delete from question_choices where question_id = ${q.id}`;272 await insertChoices(tx, q.id, q.correct_price, q.difficulty, q.category, `${competition.seed}:choix:v${competition.bank_version}:${q.source_ref}:${nonce}`, cfg, bounds);273 }274 return questions.length;275 });276}277278/** Remplace une question d'un brouillon par une autre propriété du bassin (même phase, même difficulté). */279export async function replaceQuestion(competitionId: string, questionId: string): Promise<void> {280 await sql.begin(async (tx) => {281 const [competition] = await tx<CompetitionRow[]>`select * from competitions where id = ${competitionId} for update`;282 if (!competition) throw new HttpError(404, "competition_not_found", "Compétition introuvable.");283 if (competition.status !== "draft") throw new HttpError(409, "bank_immutable", "La banque d'une compétition publiée est immuable.");284 const [old] = await tx<{ id: string; position: number; phase: number; difficulty: Difficulty; atypicality: number; category: string; region: string | null }[]>`285 select id, position, phase, difficulty, atypicality, snapshot->>'category' as category, snapshot->>'regionCode' as region286 from questions where id = ${questionId} and competition_id = ${competitionId}`;287 if (!old) throw new HttpError(404, "question_not_found", "Question introuvable.");288 const cfg = competition.config ?? {};289 const [candidate] = await tx<PoolRow[]>`290 select id, data from properties p291 where eligible and active and category = ${old.category}292 and (${old.region}::text is null or region_code = ${old.region})293 and (${cfg.priceMin ?? null}::int is null or price >= ${cfg.priceMin ?? null})294 and (${cfg.priceMax ?? null}::int is null or price <= ${cfg.priceMax ?? null})295 and not exists (select 1 from questions q where q.competition_id = ${competitionId} and q.source_ref = p.source_ref)296 order by random() limit 1`;297 if (!candidate) throw new HttpError(422, "pool_too_small", "Aucune propriété de remplacement comparable n'est disponible.");298 const p = candidate.data;299 const lookup = await marketLookup(tx);300 const bounds = await priceMarket(tx);301 await tx`delete from questions where id = ${old.id}`;302 const [question] = await tx<{ id: string }[]>`303 insert into questions (competition_id, property_id, source_ref, position, phase, difficulty, atypicality, correct_price, snapshot, context, bank_version)304 values (${competitionId}, ${candidate.id}, ${p.sourceUid}, ${old.position}, ${old.phase}, ${old.difficulty}, ${old.atypicality},305 ${p.price}, ${tx.json(toSnapshot(p) as never)}, ${tx.json(buildMarketContext(p, lookup) as never)}, ${competition.bank_version})306 returning id`;307 await insertChoices(tx, question!.id, p.price, old.difficulty, p.category, `${competition.seed}:choix:r:${p.sourceUid}:${Date.now()}`, cfg, bounds);308 const images = p.imageUrls.slice(0, MAX_IMAGES_PER_QUESTION).map((url, i) => ({ question_id: question!.id, position: i, source_url: url }));309 if (images.length) await tx`insert into question_images ${tx(images)}`;310 });311}312313/** Vérifie l'intégrité d'une banque : taille, unicité, quatre choix dont un seul correct, photos. */314export async function validateBank(competitionId: string, tx: Tx | typeof sql = sql): Promise<string[]> {315 const competition = await getCompetition(competitionId, tx);316 const problems: string[] = [];317 const [counts] = await tx<{ n: number; distinct_refs: number }[]>`318 select count(*)::int as n, count(distinct source_ref)::int as distinct_refs from questions where competition_id = ${competitionId}`;319 if (counts!.n !== competition.size) problems.push(`La banque compte ${counts!.n} propriétés au lieu de ${competition.size}.`);320 if (counts!.distinct_refs !== counts!.n) problems.push("La banque contient une propriété en double.");321 const bad = await tx<{ position: number; choices: number; correct: number; images: number }[]>`322 select q.position,323 (select count(*)::int from question_choices c where c.question_id = q.id) as choices,324 (select count(*)::int from question_choices c where c.question_id = q.id and c.is_correct and c.price = q.correct_price) as correct,325 (select count(*)::int from question_images i where i.question_id = q.id and i.status = 'ok') as images326 from questions q where q.competition_id = ${competitionId}`;327 for (const q of bad) {328 if (q.choices !== 4) problems.push(`Propriété ${q.position + 1} : ${q.choices} choix au lieu de 4.`);329 if (q.correct !== 1) problems.push(`Propriété ${q.position + 1} : ${q.correct} bonne réponse au lieu d'une.`);330 if (q.images < 3) problems.push(`Propriété ${q.position + 1} : moins de trois photographies vérifiées (la vérification suit la génération ; patientez ou remplacez la propriété).`);331 }332 return problems;333}334335export async function publishCompetition(competitionId: string): Promise<CompetitionRow> {336 return sql.begin(async (tx) => {337 const [competition] = await tx<CompetitionRow[]>`select * from competitions where id = ${competitionId} for update`;338 if (!competition) throw new HttpError(404, "competition_not_found", "Compétition introuvable.");339 if (competition.status !== "draft") throw new HttpError(409, "not_draft", "Seul un brouillon peut être publié.");340 const problems = await validateBank(competitionId, tx);341 if (problems.length) throw new HttpError(422, "bank_invalid", problems.slice(0, 5).join(" "));342 const [row] = await tx<CompetitionRow[]>`343 update competitions set status = 'published', published_at = now() where id = ${competitionId} returning *`;344 return row!;345 });346}347348export async function setCompetitionStatus(competitionId: string, status: "closed" | "archived"): Promise<CompetitionRow> {349 const current = await getCompetition(competitionId);350 if (status === "closed" && current.status !== "published") throw new HttpError(409, "not_published", "Seule une compétition publiée peut être fermée.");351 if (status === "archived" && current.status === "published") throw new HttpError(409, "still_open", "Fermez la compétition avant de l'archiver.");352 const [row] = await sql<CompetitionRow[]>`353 update competitions set status = ${status}, closed_at = coalesce(closed_at, now()) where id = ${competitionId} returning *`;354 return row!;355}356357/** Copie les paramètres d'une compétition dans un nouveau brouillon (nouvelle graine, banque à générer). */358export async function duplicateCompetition(competitionId: string): Promise<CompetitionRow> {359 const source = await getCompetition(competitionId);360 return createCompetition({361 name: `${source.name} (copie)`,362 mode: "official",363 size: source.size,364 courses: source.courses,365 allowExternal: source.allow_external,366 accessCode: source.access_code,367 config: { ...source.config, distractorNonce: 0 },368 notes: source.notes,369 });370}371372/** Partie d'entraînement : banque indépendante, tirée pour une seule partie. */373export async function createTrainingCompetition(size: number, cfg: CompetitionConfig = {}): Promise<CompetitionRow> {374 return sql.begin(async (tx) => {375 const competition = await createCompetition({ name: `Entraînement · ${size} propriétés`, mode: "training", size, config: cfg }, tx);376 await generateBank(competition.id, { limit: Math.max(600, size * 25), salt: competition.seed }, tx);377 const [row] = await tx<CompetitionRow[]>`378 update competitions set status = 'published', published_at = now() where id = ${competition.id} returning *`;379 return row!;380 });381}382383/** Défi du jour : une propriété commune à tous, tirée de façon déterministe pour la date. */384export async function getOrCreateDaily(date: string): Promise<CompetitionRow> {385 const [existing] = await sql<CompetitionRow[]>`select * from competitions where daily_date = ${date}`;386 if (existing) return existing;387 try {388 return await sql.begin(async (tx) => {389 const competition = await createCompetition(390 { name: `Défi du jour · ${date}`, mode: "daily", size: 1, seed: `jour:${date}`, dailyDate: date, config: { fixedDifficulty: "avance" } },391 tx,392 );393 await generateBank(competition.id, { limit: 400, salt: `jour:${date}` }, tx);394 const [row] = await tx<CompetitionRow[]>`395 update competitions set status = 'published', published_at = now() where id = ${competition.id} returning *`;396 return row!;397 });398 } catch (error) {399 // Deux requêtes simultanées : l'autre a gagné, on relit.400 const [row] = await sql<CompetitionRow[]>`select * from competitions where daily_date = ${date}`;401 if (row) return row;402 throw error;403 }404}405406/** Date du jour au fuseau de Montréal (AAAA-MM-JJ). */407export function todayInMontreal(now = new Date()): string {408 return new Intl.DateTimeFormat("en-CA", { timeZone: "America/Toronto", year: "numeric", month: "2-digit", day: "2-digit" }).format(now);409}410