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/web/src/admin/lib.ts9 * Module : admin10 * 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/** Espace d'administration : client, types des réponses de l'API, libellés et formats. */44import { useCallback, useEffect, useRef, useState } from "react";45import type { Category, Difficulty, DifficultyBand, ItemAnalysis, MarketContext, PublicCard } from "@jeux/engine";46import { formatInt, formatPercent } from "@jeux/engine/format";47import { ApiError, api, type RequestOptions } from "../lib/api";4849/* ---------- Client ---------- */5051let unauthorizedHandler: (() => void) | null = null;5253export function setUnauthorizedHandler(handler: (() => void) | null): void {54 unauthorizedHandler = handler;55}5657/** Appel à l'API d'administration ; toute réponse 401 ramène à l'écran d'accès. */58export async function adminApi<T>(path: string, options: RequestOptions = {}): Promise<T> {59 try {60 return await api<T>(`/api/v1/admin${path}`, options);61 } catch (error) {62 if (error instanceof ApiError && error.status === 401) unauthorizedHandler?.();63 throw error;64 }65}6667/**68 * Requête PUT d'administration. Le client partagé (`lib/api.ts`) ne déclare pas cette méthode :69 * même en-têtes, même forme d'erreur, même retour à l'écran d'accès sur un 401.70 */71export async function adminPut<T>(path: string, body: unknown): Promise<T> {72 let response: Response;73 try {74 response = await fetch(`/api/v1/admin${path}`, {75 method: "PUT",76 headers: { accept: "application/json", "content-type": "application/json", "x-requested-with": "gdi" },77 body: JSON.stringify(body),78 credentials: "same-origin",79 });80 } catch {81 throw new ApiError(0, "offline", "Connexion interrompue.");82 }83 if (response.ok) return (await response.json()) as T;84 let code = "error";85 let message = "Une erreur est survenue.";86 try {87 const data = (await response.json()) as { error?: { code?: string; message?: string } };88 code = data.error?.code ?? code;89 message = data.error?.message ?? message;90 } catch {91 /* réponse non JSON */92 }93 if (response.status === 401) unauthorizedHandler?.();94 throw new ApiError(response.status, code, message);95}9697export function errorMessage(error: unknown): string {98 if (error instanceof ApiError) {99 return error.status === 0 ? "Connexion interrompue. Vérifiez le réseau, puis réessayez." : error.message;100 }101 return "Une erreur inattendue est survenue.";102}103104export interface Loaded<T> {105 data: T | null;106 error: string | null;107 /** Premier chargement (aucune donnée à afficher encore). */108 loading: boolean;109 /** Rechargement en cours alors que des données sont déjà affichées. */110 refreshing: boolean;111 loadedAt: number | null;112 reload: () => Promise<void>;113}114115/** Charge une ressource d'administration ; `intervalMs` active un rafraîchissement périodique (onglet visible seulement). */116export function useLoad<T>(path: string | null, intervalMs?: number): Loaded<T> {117 const [data, setData] = useState<T | null>(null);118 const [error, setError] = useState<string | null>(null);119 const [pending, setPending] = useState(path !== null);120 const [loadedAt, setLoadedAt] = useState<number | null>(null);121 const [loadedPath, setLoadedPath] = useState<string | null>(null);122 const ticket = useRef(0);123124 const reload = useCallback(async (): Promise<void> => {125 if (path === null) return;126 const mine = ++ticket.current;127 setPending(true);128 try {129 const result = await adminApi<T>(path);130 if (mine !== ticket.current) return;131 setData(result);132 setLoadedPath(path);133 setError(null);134 setLoadedAt(Date.now());135 } catch (e) {136 if (mine !== ticket.current) return;137 setError(errorMessage(e));138 } finally {139 if (mine === ticket.current) setPending(false);140 }141 }, [path]);142143 useEffect(() => {144 if (path === null) {145 ticket.current += 1;146 setData(null);147 setError(null);148 setPending(false);149 return;150 }151 void reload();152 return () => {153 ticket.current += 1;154 };155 }, [path, reload]);156157 useEffect(() => {158 if (!intervalMs || path === null) return;159 const timer = window.setInterval(() => {160 if (document.visibilityState === "visible") void reload();161 }, intervalMs);162 return () => window.clearInterval(timer);163 }, [intervalMs, path, reload]);164165 const has = data !== null;166 return { data, error, loading: pending && !has, refreshing: pending && has, loadedAt: loadedPath === null ? null : loadedAt, reload };167}168169/* ---------- Types des réponses ---------- */170171export type CompetitionStatus = "draft" | "published" | "closed" | "archived";172export type Course = "IMM1003" | "IMM1033";173174export interface Prizes {175 amounts: number[];176 label: string;177}178179export interface CompetitionConfig {180 categories?: Category[];181 regionCodes?: string[];182 priceMin?: number;183 priceMax?: number;184 bands?: Record<Difficulty, DifficultyBand>;185 strataExponent?: number;186 prizes?: Prizes;187 distractorNonce?: number;188}189190export interface Competition {191 id: string;192 slug: string;193 name: string;194 mode: "official" | "training" | "daily";195 status: CompetitionStatus;196 courses: string[];197 allowExternal: boolean;198 startsAt: string | null;199 endsAt: string | null;200 accessCode: string | null;201 size: number;202 config: CompetitionConfig;203 bankVersion: number;204 notes: string | null;205 createdAt: string;206 publishedAt: string | null;207 closedAt: string | null;208}209210export interface CompetitionListItem extends Competition {211 questions: number;212 sessions: number;213 completed: number;214}215216export interface Tally {217 label: string;218 n: number;219}220221export interface CompetitionDetail extends Competition {222 problems: string[];223 images: { total: number; ok: number; failed: number };224 mix: { categories: Tally[]; regions: Tally[]; priceBands: Tally[] };225}226227export interface AdminOptions {228 categories: { key: Category; label: string }[];229 regions: { code: string; name: string }[];230 priceBands: { key: string; label: string }[];231 defaultBands: Record<Difficulty, DifficultyBand>;232}233234export interface AdminQuestion {235 id: string;236 number: number;237 phase: number;238 difficulty: Difficulty;239 atypicality: number;240 correctPrice: number;241 card: PublicCard;242 context: MarketContext | null;243 flagged: boolean;244 flagNote: string | null;245 choices: { price: number; isCorrect: boolean }[];246 images: string[];247 failedImages: number;248}249250export interface SyncStats {251 scanned?: number;252 normalized?: number;253 deduplicated?: number;254 eligible?: number;255 deactivated?: number;256 durationMs?: number;257 byCategory?: Record<string, number>;258 rejections?: Record<string, number>;259}260261export interface SyncJob {262 id: string;263 started_at: string;264 finished_at: string | null;265 status: "running" | "success" | "failed";266 stats: SyncStats | null;267 error: string | null;268}269270export interface DashboardData {271 totals: { sessions: number; completed: number; in_progress: number; active: number; participants: number; completionRate: number; training: number; daily: number };272 scores: { mean_score: number | null; median_score: number | null; mean_mape: number | null };273 distribution: Tally[];274 byCourse: { course: string; n: number; meanScore: number; meanMape: number }[];275 pool: { total: number; eligible: number; byCategory: Tally[] };276 sync: { running: boolean; last: SyncJob | null; sourceAvailable: boolean };277 pending: { flags: number; anomalies: number };278 services: { database: boolean; liveListeners: number; imageCache: { files: number; bytes: number }; uptimeSeconds: number; memoryMb: number; version: string };279}280281export type SessionStatus = "in_progress" | "completed" | "reset" | "excluded";282export type GameMode = "official" | "training" | "daily";283284export interface ParticipantRow {285 id: string;286 status: SessionStatus;287 answered: number;288 total: number;289 correct: number;290 best_streak: number;291 started_at: string;292 last_activity_at: string;293 completed_at: string | null;294 admin_note: string | null;295 mape: number | null;296 participant_id: string;297 display_name: string;298 course: string | null;299 competition_name: string;300 competition_id: string;301 anomalies: number;302}303304export interface ParticipantsPage {305 rows: ParticipantRow[];306 matches: number;307 page: number;308 pageSize: number;309}310311export interface SessionDetail {312 session: {313 id: string;314 participant_id: string;315 competition_id: string;316 status: SessionStatus;317 total: number;318 answered: number;319 correct: number;320 best_streak: number;321 sum_rel_error: number;322 started_at: string;323 last_activity_at: string;324 completed_at: string | null;325 admin_note: string | null;326 display_name: string;327 course: string | null;328 competition_name: string;329 };330 answers: { idx: number; chosen_price: number; correct_price: number; is_correct: boolean; rel_error: number; response_ms: number | null; created_at: string; municipality: string | null; category: string | null }[];331 anomalies: { id: string; kind: string; detail: string; reviewed: boolean; created_at: string }[];332}333334export interface PlayerFlag {335 id: string;336 reason: string;337 created_at: string;338 resolved: boolean;339 question_id: string;340 number: number;341 competition_name: string;342 municipality: string | null;343 category: string | null;344}345346export interface AnalyticsItem {347 questionId: string;348 number: number;349 phase: number;350 difficulty: Difficulty;351 label: string;352 region: string | null;353 correctPrice: number;354 prices: number[];355 correctRank: number;356 flagged: boolean;357 flagNote: string | null;358 playerFlags: number;359 analysis: ItemAnalysis;360}361362export interface GroupRow {363 label: string;364 n: number;365 rate: number;366 mape: number;367 bias: number;368}369370export interface AnalyticsData {371 answers: number;372 collective: { rate: number; mape: number; bias: number; over: number; under: number };373 hardest: AnalyticsItem[];374 easiest: AnalyticsItem[];375 problematic: AnalyticsItem[];376 items: AnalyticsItem[];377 byCategory: GroupRow[];378 byRegion: GroupRow[];379 byCourse: GroupRow[];380 byPhase: GroupRow[];381 byDifficulty: GroupRow[];382 byPriceBand: GroupRow[];383 progression: { decile: number; rate: number; n: number }[];384}385386export interface AuditEntry {387 id: string;388 at: string;389 actor: string;390 action: string;391 target: string | null;392 detail: Record<string, unknown> | null;393}394395/* ---------- Libellés ---------- */396397export const COMPETITION_STATUS: Record<CompetitionStatus, string> = {398 draft: "Brouillon",399 published: "Publiée",400 closed: "Fermée",401 archived: "Archivée",402};403404export const SESSION_STATUS: Record<SessionStatus, string> = {405 in_progress: "En cours",406 completed: "Terminée",407 reset: "Réinitialisée",408 excluded: "Exclue",409};410411export const DIFFICULTY_ORDER: readonly Difficulty[] = ["initiation", "intermediaire", "avance", "expert"];412413export const DIFFICULTY_LABEL: Record<Difficulty, string> = {414 initiation: "Initiation",415 intermediaire: "Intermédiaire",416 avance: "Avancé",417 expert: "Expert",418};419420export const PHASE_NAME: Record<number, string> = { 1: "Découverte", 2: "Analyse", 3: "Expertise", 4: "Maîtrise" };421422export function phaseLabel(phase: number | string): string {423 const name = PHASE_NAME[Number(phase)];424 return name ? `${phase} · ${name}` : `Phase ${phase}`;425}426427const CATEGORY_LABEL: Record<Category, string> = {428 unifamiliale: "Maison unifamiliale",429 jumele: "Maison jumelée",430 rangee: "Maison en rangée",431 condo: "Copropriété",432 plex: "Plex",433 chalet: "Chalet",434 mobile: "Maison mobile",435 fermette: "Fermette",436};437438export function categoryLabel(key: string | null | undefined): string {439 if (!key) return "Type non précisé";440 return (CATEGORY_LABEL as Record<string, string>)[key] ?? key;441}442443export const REJECTION_LABEL: Record<string, string> = {444 inactive: "Inscription inactive",445 duplicate_flag: "Doublon déjà signalé à la source",446 excluded_source: "Provenance exclue",447 unknown_type: "Type de propriété non reconnu",448 not_for_sale: "Propriété qui n'est pas à vendre",449 price_missing: "Prix absent",450 price_out_of_range: "Prix hors des bornes admises",451 price_incoherent: "Prix incohérent avec la fiche",452 no_municipality: "Municipalité non reconnue",453 low_quality: "Fiche trop incomplète",454 implausible_data: "Données invraisemblables",455};456457export const ANOMALY_LABEL: Record<string, string> = {458 rapid_answers: "Réponses très rapides",459 uniform_timing: "Cadence de réponse uniforme",460};461462export const SYNC_STATUS: Record<SyncJob["status"], string> = {463 running: "En cours",464 success: "Réussie",465 failed: "Échouée",466};467468/* ---------- Formats ---------- */469470const dateTimeFormat = new Intl.DateTimeFormat("fr-CA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit", timeZone: "America/Toronto" });471const timeFormat = new Intl.DateTimeFormat("fr-CA", { hour: "2-digit", minute: "2-digit", second: "2-digit", timeZone: "America/Toronto" });472473export function formatDateTime(iso: string | null | undefined): string {474 if (!iso) return "—";475 const date = new Date(iso);476 return Number.isNaN(date.getTime()) ? "—" : dateTimeFormat.format(date);477}478479export function formatClock(ms: number): string {480 return timeFormat.format(new Date(ms));481}482483export function formatRate(rate: number, digits = 0): string {484 return formatPercent(rate * 100, digits);485}486487export function formatSignedPercent(value: number, digits = 1): string {488 const text = formatPercent(Math.abs(value), digits);489 if (Math.abs(value) < 0.05) return formatPercent(0, digits);490 return `${value > 0 ? "+" : "−"}${text}`;491}492493export function biasWord(value: number): string {494 if (Math.abs(value) < 0.05) return "aucun biais";495 return value > 0 ? "surestimation" : "sous-estimation";496}497498export function formatDuration(totalSeconds: number): string {499 const s = Math.max(0, Math.round(totalSeconds));500 if (s < 60) return `${s} s`;501 const minutes = Math.floor(s / 60);502 if (minutes < 60) return `${minutes} min ${s % 60} s`;503 const hours = Math.floor(minutes / 60);504 if (hours < 24) return `${hours} h ${minutes % 60} min`;505 return `${Math.floor(hours / 24)} j ${hours % 24} h`;506}507508export function formatAgo(iso: string, now = Date.now()): string {509 const seconds = Math.max(0, (now - new Date(iso).getTime()) / 1000);510 if (seconds < 60) return "à l'instant";511 if (seconds < 3600) return `il y a ${Math.floor(seconds / 60)} min`;512 if (seconds < 86_400) return `il y a ${Math.floor(seconds / 3600)} h`;513 return `il y a ${Math.floor(seconds / 86_400)} j`;514}515516export function formatBytes(bytes: number): string {517 if (bytes >= 1_073_741_824) return `${(bytes / 1_073_741_824).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} Go`;518 if (bytes >= 1_048_576) return `${formatInt(bytes / 1_048_576)} Mo`;519 return `${formatInt(bytes / 1024)} ko`;520}521522/** Insécables dans les montants (« 300 000 $ ») pour éviter les coupures de ligne. */523export function nb(label: string): string {524 return label.replace(/(\d) (?=\d{3})/g, "$1\u00a0").replace(/ \$/g, "\u00a0$");525}526527export function formatSeconds(ms: number | null): string {528 if (ms === null) return "—";529 return `${(ms / 1000).toLocaleString("fr-CA", { minimumFractionDigits: 1, maximumFractionDigits: 1 })} s`;530}531532/** ISO → valeur d'un champ `datetime-local` (heure locale du navigateur). */533export function isoToLocalInput(iso: string | null): string {534 if (!iso) return "";535 const d = new Date(iso);536 if (Number.isNaN(d.getTime())) return "";537 const pad = (n: number): string => String(n).padStart(2, "0");538 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;539}540541export function localInputToIso(value: string): string | null {542 if (!value) return null;543 const d = new Date(value);544 return Number.isNaN(d.getTime()) ? null : d.toISOString();545}546547export function exportUrl(competitionId: string, scope: "results" | "questions", format: "csv" | "xlsx" | "json" | "pdf"): string {548 return `/api/v1/admin/exports?competitionId=${encodeURIComponent(competitionId)}&format=${format}&scope=${scope}`;549}550