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/Analytics.tsx9 * 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 */4243import { useEffect, useMemo, useState } from "react";44import type { Difficulty } from "@jeux/engine";45import { Link } from "wouter";46import { formatInt, formatMoney, formatPercent } from "@jeux/engine/format";47import { IconCheck, IconDown, IconFlag, IconUp } from "../components/Icons";48import {49 COMPETITION_STATUS,50 DIFFICULTY_LABEL,51 DIFFICULTY_ORDER,52 adminApi,53 biasWord,54 categoryLabel,55 formatDateTime,56 formatRate,57 formatSeconds,58 formatSignedPercent,59 nb,60 phaseLabel,61 useLoad,62 type AnalyticsData,63 type AnalyticsItem,64 type CompetitionListItem,65 type GroupRow,66 type PlayerFlag,67} from "./lib";68import { ActionDialog, Empty, ExportLinks, Figures, LoadState, Note, PageHead, RefreshButton, Section, TableScroll, type Ask } from "./ui";6970const RANK_NAMES = ["le moins cher", "le 2ᵉ prix", "le 3ᵉ prix", "le plus cher"];7172/** Répartition des réponses du moins cher au plus cher ; le bon rang porte une coche. */73function Distribution({ item }: { item: AnalyticsItem }) {74 const d = item.analysis.distribution;75 const max = Math.max(1, ...d);76 return (77 <span78 className="adm-dist"79 role="img"80 aria-label={`Réponses du moins cher au plus cher : ${d.join(", ")}. Bonne réponse : ${RANK_NAMES[item.correctRank] ?? "inconnue"}.`}81 >82 {d.map((n, rank) => (83 <span key={rank} className={rank === item.correctRank ? "is-correct" : undefined} aria-hidden="true">84 <span className="adm-dist-bar"><span style={{ height: `${(100 * n) / max}%` }} /></span>85 <span className="adm-dist-n tabular">{n}</span>86 <span className="adm-dist-mark">{rank === item.correctRank ? <IconCheck size={12} /> : null}</span>87 </span>88 ))}89 </span>90 );91}9293function Discrimination({ value }: { value: number | null }) {94 if (value === null) {95 return <abbr className="adm-nd" title="Échantillon insuffisant (moins de 20 réponses)" tabIndex={0}>n. d.<span className="sr-only"> : échantillon insuffisant (moins de 20 réponses)</span></abbr>;96 }97 return <span className="tabular">{value < 0 ? "−" : value > 0 ? "+" : ""}{Math.abs(value).toLocaleString("fr-CA", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>;98}99100function RateBar({ rate }: { rate: number }) {101 return (102 <span className="adm-rate">103 <span className="adm-rate-track" aria-hidden="true"><span style={{ width: `${Math.round(rate * 100)}%` }} /></span>104 <span className="tabular">{formatRate(rate)}</span>105 </span>106 );107}108109function ShortList({ title, items, empty }: { title: string; items: AnalyticsItem[]; empty: string }) {110 return (111 <div>112 <h3 className="adm-h3">{title}</h3>113 {items.length === 0 ? (114 <p className="adm-quiet">{empty}</p>115 ) : (116 <TableScroll label={title}>117 <table className="table adm-table">118 <caption className="sr-only">{title}</caption>119 <thead>120 <tr><th scope="col" className="right">N°</th><th scope="col">Propriété</th><th scope="col" className="right">Rép.</th><th scope="col">Réussite</th><th scope="col" className="right">Erreur moy.</th></tr>121 </thead>122 <tbody>123 {items.map((i) => (124 <tr key={i.questionId}>125 <td className="right">{i.number}</td>126 <th scope="row" className="adm-cell-main"><span>{i.label}</span><span className="small muted">{formatMoney(i.correctPrice)} · {DIFFICULTY_LABEL[i.difficulty]}</span></th>127 <td className="right">{formatInt(i.analysis.n)}</td>128 <td><RateBar rate={i.analysis.successRate} /></td>129 <td className="right">{formatPercent(i.analysis.meanRelError, 1)}</td>130 </tr>131 ))}132 </tbody>133 </table>134 </TableScroll>135 )}136 </div>137 );138}139140function GroupTable({ title, rows, labelOf = (l) => l, head }: { title: string; rows: GroupRow[]; labelOf?: (label: string) => string; head: string }) {141 return (142 <div>143 <h3 className="adm-h3">{title}</h3>144 {rows.length === 0 ? (145 <p className="adm-quiet">Aucune réponse.</p>146 ) : (147 <TableScroll label={title}>148 <table className="table adm-table">149 <caption className="sr-only">{title} : réponses, taux de réussite, erreur relative moyenne et biais moyen</caption>150 <thead>151 <tr><th scope="col">{head}</th><th scope="col" className="right">Réponses</th><th scope="col">Réussite</th><th scope="col" className="right">Erreur moy.</th><th scope="col" className="right">Biais</th></tr>152 </thead>153 <tbody>154 {rows.map((r) => (155 <tr key={r.label}>156 <th scope="row">{labelOf(r.label)}</th>157 <td className="right">{formatInt(r.n)}</td>158 <td><RateBar rate={r.rate} /></td>159 <td className="right">{formatPercent(r.mape, 1)}</td>160 <td className="right">{formatSignedPercent(r.bias)}<span className="sr-only"> ({biasWord(r.bias)})</span></td>161 </tr>162 ))}163 </tbody>164 </table>165 </TableScroll>166 )}167 </div>168 );169}170171function Progression({ rows }: { rows: AnalyticsData["progression"] }) {172 const deciles = Array.from({ length: 10 }, (_, i) => rows.find((r) => r.decile === i) ?? null);173 const top = deciles.some((d) => d !== null && d.rate > 0.5) ? 1 : 0.5;174 return (175 <figure className="adm-histo adm-histo-rate" style={{ "--chance": 0.25 / top } as React.CSSProperties}>176 <div className="adm-histo-plot" role="img" aria-label={`Taux de réussite par dixième de la partie : ${deciles.map((d, i) => `${i + 1}ᵉ dixième ${d ? formatRate(d.rate) : "sans réponse"}`).join(", ")}`}>177 {deciles.map((d, i) => (178 <div className="adm-histo-col" key={i} aria-hidden="true">179 <span className="adm-histo-stack">180 <span className="adm-histo-n tabular">{d ? `${Math.round(d.rate * 100)} %` : ""}</span>181 <span className="adm-histo-bar" style={{ height: `calc(${d ? d.rate / top : 0} * (100% - 1.6em))` }} data-empty={!d || d.rate === 0 || undefined} />182 </span>183 <span className="adm-histo-x tabular">{i + 1}</span>184 </div>185 ))}186 </div>187 <figcaption className="small muted">Taux de réussite par dixième de la partie, du début (1) à la fin (10) ; échelle de 0 à {top === 1 ? "100" : "50"} %. Le trait pointillé marque le hasard (25 %). Effectifs : {deciles.map((d) => formatInt(d?.n ?? 0)).join(" · ")} réponses.</figcaption>188 </figure>189 );190}191192type SortKey = "number" | "n" | "rate" | "mean" | "median" | "disc" | "time";193const SORT_VALUE: Record<SortKey, (i: AnalyticsItem) => number | null> = {194 number: (i) => i.number,195 n: (i) => i.analysis.n,196 rate: (i) => (i.analysis.n ? i.analysis.successRate : null),197 mean: (i) => (i.analysis.n ? i.analysis.meanRelError : null),198 median: (i) => (i.analysis.n ? i.analysis.medianRelError : null),199 disc: (i) => i.analysis.discrimination,200 time: (i) => i.analysis.medianResponseMs,201};202203function ItemsTable({ items }: { items: AnalyticsItem[] }) {204 const [sort, setSort] = useState<{ key: SortKey; dir: 1 | -1 }>({ key: "number", dir: 1 });205 const sorted = useMemo(() => {206 const value = SORT_VALUE[sort.key];207 return [...items].sort((a, b) => {208 const va = value(a);209 const vb = value(b);210 if (va === null && vb === null) return a.number - b.number;211 if (va === null) return 1; // les valeurs absentes restent en fin de tableau212 if (vb === null) return -1;213 return (va - vb) * sort.dir || a.number - b.number;214 });215 }, [items, sort]);216217 const th = (k: SortKey, children: string, right?: boolean, title?: string) => {218 const active = sort.key === k;219 return (220 <th key={k} scope="col" className={right ? "right" : undefined} aria-sort={active ? (sort.dir === 1 ? "ascending" : "descending") : "none"}>221 <button type="button" className="adm-sort" title={title} onClick={() => setSort({ key: k, dir: active ? (sort.dir === 1 ? -1 : 1) : k === "number" ? 1 : -1 })}>222 {children}223 <span className="adm-sort-icon" aria-hidden="true">{active ? (sort.dir === 1 ? <IconUp size={13} /> : <IconDown size={13} />) : null}</span>224 </button>225 </th>226 );227 };228229 return (230 <TableScroll label="Toutes les questions">231 <table className="table adm-table adm-items">232 <caption className="sr-only">Analyse de chaque question ; les en-têtes à bouton trient le tableau</caption>233 <thead>234 <tr>235 {th("number", "N°", true)}236 <th scope="col">Propriété</th>237 {th("n", "Rép.", true)}238 {th("rate", "Réussite")}239 <th scope="col">Répartition<span className="adm-th-note"> − cher → + cher</span></th>240 {th("mean", "Erreur moy.", true)}241 {th("median", "Erreur méd.", true)}242 {th("disc", "Discrim.", true, "Écart de réussite entre les 27 % meilleurs et les 27 % moins bons participants")}243 {th("time", "Temps méd.", true, "Temps médian de réponse, à titre descriptif")}244 </tr>245 </thead>246 <tbody>247 {sorted.map((i) => {248 const none = i.analysis.n === 0;249 return (250 <tr key={i.questionId}>251 <td className="right">{i.number}</td>252 <th scope="row" className="adm-cell-main">253 <span>{i.label}</span>254 <span className="small muted">{formatMoney(i.correctPrice)} · {phaseLabel(i.phase)} · {DIFFICULTY_LABEL[i.difficulty]}</span>255 {(i.flagged || i.playerFlags > 0 || i.analysis.warnings.length > 0) && (256 <span className="adm-state is-warn small"><IconFlag size={14} />257 {[i.flagged ? "signalée" : null, i.playerFlags > 0 ? `${i.playerFlags} signalement${i.playerFlags > 1 ? "s" : ""} de joueurs` : null, i.analysis.warnings.length > 0 ? `${i.analysis.warnings.length} alerte${i.analysis.warnings.length > 1 ? "s" : ""}` : null].filter(Boolean).join(" · ")}258 </span>259 )}260 </th>261 <td className="right">{formatInt(i.analysis.n)}</td>262 <td>{none ? <span className="muted">—</span> : <RateBar rate={i.analysis.successRate} />}</td>263 <td>{none ? <span className="muted">Aucune réponse</span> : <Distribution item={i} />}</td>264 <td className="right">{none ? "—" : formatPercent(i.analysis.meanRelError, 1)}</td>265 <td className="right">{none ? "—" : formatPercent(i.analysis.medianRelError, 1)}</td>266 <td className="right"><Discrimination value={i.analysis.discrimination} /></td>267 <td className="right">{formatSeconds(i.analysis.medianResponseMs)}</td>268 </tr>269 );270 })}271 </tbody>272 </table>273 </TableScroll>274 );275}276277function PlayerFlags() {278 const flags = useLoad<PlayerFlag[]>("/flags");279 const [ask, setAsk] = useState<Ask | null>(null);280 return (281 <div>282 <h3 className="adm-h3">Signalements des joueurs, toutes compétitions</h3>283 <LoadState state={flags} label="Chargement des signalements…">284 {(rows) => {285 const open = rows.filter((f) => !f.resolved);286 const done = rows.length - open.length;287 return (288 <>289 {open.length === 0 ? (290 <p className="adm-quiet">Aucun signalement en attente.{done > 0 ? ` ${done} signalement${done > 1 ? "s" : ""} déjà traité${done > 1 ? "s" : ""}.` : ""}</p>291 ) : (292 <ul role="list" className="adm-list">293 {open.map((f) => (294 <li key={f.id}>295 <div>296 <p><strong>Propriété {f.number}</strong> · {categoryLabel(f.category)}{f.municipality ? `, ${f.municipality}` : ""}</p>297 <p>« {f.reason} »</p>298 <p className="small muted">{f.competition_name} · {formatDateTime(f.created_at)}</p>299 </div>300 <button301 type="button"302 className="btn btn-ghost"303 onClick={() =>304 setAsk({305 title: "Marquer ce signalement comme traité ?",306 body: <p>Le signalement d'un joueur sur la propriété {f.number} (« {f.reason} ») sera classé. La question n'est pas modifiée.</p>,307 confirmLabel: "Marquer comme traité",308 run: async () => {309 await adminApi(`/flags/${f.id}/resolve`, { method: "POST", body: {} });310 return "Signalement marqué comme traité.";311 },312 })313 }314 >315 Marquer comme traité<span className="sr-only"> : propriété {f.number}</span>316 </button>317 </li>318 ))}319 </ul>320 )}321 {open.length > 0 && done > 0 && <p className="small muted">{done} signalement{done > 1 ? "s" : ""} déjà traité{done > 1 ? "s" : ""}.</p>}322 </>323 );324 }}325 </LoadState>326 {ask && <ActionDialog ask={ask} onClose={() => setAsk(null)} onDone={() => void flags.reload()} />}327 </div>328 );329}330331export default function Analytics() {332 const competitions = useLoad<CompetitionListItem[]>("/competitions");333 const [selected, setSelected] = useState<string>(() => new URLSearchParams(window.location.search).get("competition") ?? "");334 const list = competitions.data;335 useEffect(() => {336 if (!list || list.length === 0) return;337 if (selected && list.some((c) => c.id === selected)) return;338 const preferred = list.find((c) => c.status !== "draft" && c.sessions > 0) ?? list.find((c) => c.status !== "draft") ?? list[0];339 if (preferred) setSelected(preferred.id);340 }, [list, selected]);341 const valid = list?.some((c) => c.id === selected) ?? false;342 const state = useLoad<AnalyticsData>(valid ? `/analytics?competitionId=${selected}` : null);343 const current = list?.find((c) => c.id === selected) ?? null;344345 return (346 <div className="adm-page">347 <PageHead348 title="Analyses pédagogiques"349 lede="Lecture collective des réponses : ce que le groupe réussit, où il se trompe et dans quel sens, question par question."350 actions={valid ? <RefreshButton state={state} /> : undefined}351 />352 <LoadState state={competitions} label="Chargement des compétitions…">353 {(rows) =>354 rows.length === 0 ? (355 <Empty title="Aucune compétition à analyser"><p>Les analyses apparaîtront dès qu'une compétition aura reçu des réponses.</p></Empty>356 ) : (357 <>358 <div className="adm-pickbar">359 <div className="field">360 <label htmlFor="adm-a-comp">Compétition analysée</label>361 <select id="adm-a-comp" className="input" value={selected} onChange={(e) => setSelected(e.target.value)}>362 {rows.map((c) => <option key={c.id} value={c.id}>{c.name} — {COMPETITION_STATUS[c.status].toLowerCase()}, {c.sessions} partie{c.sessions > 1 ? "s" : ""}</option>)}363 </select>364 </div>365 {current && <Link className="adm-more" href={`/admin/competitions/${current.id}`}>Ouvrir la compétition</Link>}366 </div>367368 <LoadState state={state} label="Calcul des analyses…">369 {(a) => (370 <>371 {a.answers === 0 ? (372 <Empty title="Aucune réponse enregistrée pour cette compétition"><p>Les indicateurs se rempliront avec les premières parties.</p></Empty>373 ) : (374 <>375 <Figures376 label="Indicateurs collectifs"377 items={[378 { label: "Taux de réussite", value: formatRate(a.collective.rate, 1), note: `${formatInt(a.answers)} réponses · hasard : 25 %` },379 { label: "Erreur relative moyenne", value: formatPercent(a.collective.mape, 1), note: "écart absolu au prix affiché" },380 { label: "Biais collectif", value: formatSignedPercent(a.collective.bias), note: `tendance : ${biasWord(a.collective.bias)}` },381 { label: "Sur / sous-estimations", value: `${formatInt(a.collective.over)} / ${formatInt(a.collective.under)}`, note: `${formatInt(a.answers - a.collective.over - a.collective.under)} réponses exactes` },382 ]}383 />384385 <Section title="Questions les plus difficiles et les plus faciles" note="Dix questions à chaque extrémité, parmi celles qui ont reçu au moins une réponse.">386 <div className="adm-cols">387 <ShortList title="Les plus difficiles" items={a.hardest} empty="Aucune question n'a encore reçu de réponse." />388 <ShortList title="Les plus faciles" items={a.easiest} empty="Aucune question n'a encore reçu de réponse." />389 </div>390 </Section>391 </>392 )}393394 <Section title="Questions potentiellement problématiques">395 <Note tone="info" title="À lire avec prudence.">396 Une question difficile n'est pas nécessairement une bonne question : un taux de réussite sous le hasard, une mauvaise réponse qui attire la majorité ou une discrimination négative peuvent trahir des choix trompeurs plutôt qu'une vraie difficulté d'évaluation.397 </Note>398 {a.problematic.length === 0 ? (399 <p className="adm-quiet">Aucune alerte automatique ni question signalée dans cette compétition. Les alertes exigent au moins 12 réponses par question.</p>400 ) : (401 <ul role="list" className="adm-list">402 {a.problematic.map((i) => (403 <li key={i.questionId}>404 <div>405 <p><strong>Propriété {i.number}</strong> · {i.label} · {formatMoney(i.correctPrice)}</p>406 <ul className="adm-problems">407 {i.analysis.warnings.map((w) => <li key={w}>{w}</li>)}408 {i.playerFlags > 0 && <li>{i.playerFlags} signalement{i.playerFlags > 1 ? "s" : ""} de joueurs en attente.</li>}409 {i.flagged && <li>Signalée par l'administration{i.flagNote ? ` : ${i.flagNote}` : "."}</li>}410 </ul>411 <p className="small muted">{formatInt(i.analysis.n)} réponses · réussite {i.analysis.n ? formatRate(i.analysis.successRate) : "—"}</p>412 </div>413 {i.analysis.n > 0 && <Distribution item={i} />}414 </li>415 ))}416 </ul>417 )}418 <PlayerFlags />419 </Section>420421 <Section422 title="Toutes les questions"423 note="Cliquez sur un en-tête pour trier. La discrimination compare les 27 % meilleurs et les 27 % moins bons participants ; le temps médian est donné à titre descriptif seulement."424 >425 <ItemsTable items={a.items} />426 </Section>427428 {a.answers > 0 && (429 <>430 <Section title="Comparaison des groupes" note="IMM1003, IMM1033 et participants hors cours. Un biais positif indique une surestimation des prix.">431 <GroupTable title="Par groupe" head="Groupe" rows={a.byCourse} labelOf={(l) => (l === "Externe" ? "Hors cours" : l)} />432 </Section>433434 <Section title="Performance par caractéristique">435 <div className="adm-cols">436 <GroupTable title="Par type de propriété" head="Type" rows={a.byCategory} />437 <GroupTable title="Par tranche de prix" head="Tranche" rows={a.byPriceBand} labelOf={nb} />438 <GroupTable title="Par phase" head="Phase" rows={[...a.byPhase].sort((x, y) => Number(x.label) - Number(y.label))} labelOf={phaseLabel} />439 <GroupTable title="Par difficulté" head="Difficulté" rows={[...a.byDifficulty].sort((x, y) => DIFFICULTY_ORDER.indexOf(x.label as Difficulty) - DIFFICULTY_ORDER.indexOf(y.label as Difficulty))} labelOf={(l) => (DIFFICULTY_LABEL as Record<string, string>)[l] ?? l} />440 </div>441 <div className="adm-gap-top"><GroupTable title="Par région" head="Région" rows={a.byRegion} /></div>442 </Section>443444 <Section title="Progression pendant la partie">445 <Progression rows={a.progression} />446 </Section>447 </>448 )}449450 {current && current.status !== "draft" && (451 <Section title="Exports">452 <ExportLinks competitionId={current.id} />453 </Section>454 )}455 </>456 )}457 </LoadState>458 </>459 )460 }461 </LoadState>462 </div>463 );464}465