SPB Git

Repository Public

Finale.tsx 21.4 KB 350 lines tsx

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/pages/Finale.tsx9 * Module           : pages10 * 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 { motion } from "motion/react";44import { useEffect, useMemo, useRef, useState } from "react";45import { Link } from "wouter";46import type { GroupStat } from "@jeux/engine";47import { formatMoney, formatPercent, formatSignedMoney, ordinal } from "@jeux/engine/format";48import { BiasBar, ChartCard, ColumnChart, GroupBars, LineChart, ScatterChart } from "../components/Charts";49import { CountUp } from "../components/CountUp";50import { IconArrow, IconCheck, IconCross, IconDown, IconPrint, IconTrophy } from "../components/Icons";51import { Logo } from "../components/Logo";52import { ApiError, api, imageUrl } from "../lib/api";53import { prefersReducedMotion } from "../lib/store";54import type { Analytics, Results, ReviewItem } from "../lib/types";5556/** Pluie de confettis aux couleurs du jeu, brève, sur un canevas. Désactivée si l'on réduit les animations. */57function Confetti() {58  const ref = useRef<HTMLCanvasElement>(null);59  useEffect(() => {60    const canvas = ref.current;61    if (!canvas || prefersReducedMotion()) return;62    const ctx = canvas.getContext("2d");63    if (!ctx) return;64    const dpr = Math.min(2, window.devicePixelRatio || 1);65    canvas.width = window.innerWidth * dpr;66    canvas.height = window.innerHeight * dpr;67    ctx.scale(dpr, dpr);68    const colors = ["#2bccae", "#e9edee", "#006085", "#ea6047", "#5fe0c8"];69    const pieces = Array.from({ length: 150 }, (_, i) => ({70      x: window.innerWidth * (0.1 + 0.8 * Math.random()),71      y: -20 - Math.random() * window.innerHeight * 0.5,72      w: 5 + Math.random() * 7,73      h: 9 + Math.random() * 9,74      vx: -1.5 + Math.random() * 3,75      vy: 2.2 + Math.random() * 3.6,76      rot: Math.random() * Math.PI,77      vr: -0.14 + Math.random() * 0.28,78      color: colors[i % colors.length]!,79    }));80    let frame = 0;81    const started = performance.now();82    const tick = (now: number): void => {83      const elapsed = now - started;84      ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);85      ctx.globalAlpha = Math.max(0, 1 - Math.max(0, elapsed - 3200) / 1200);86      for (const p of pieces) {87        p.x += p.vx;88        p.y += p.vy;89        p.rot += p.vr;90        ctx.save();91        ctx.translate(p.x, p.y);92        ctx.rotate(p.rot);93        ctx.fillStyle = p.color;94        ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h * Math.abs(Math.cos(p.rot * 1.7)));95        ctx.restore();96      }97      if (elapsed < 4400) frame = requestAnimationFrame(tick);98      else ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);99    };100    frame = requestAnimationFrame(tick);101    return () => cancelAnimationFrame(frame);102  }, []);103  return <canvas ref={ref} className="confetti" aria-hidden="true" />;104}105106const REGION_TILES: Record<string, [number, number]> = {107  "10": [2, 0], "09": [5, 0], "08": [0, 1], "02": [3, 1], "11": [6, 1],108  "07": [0, 2], "15": [1, 2], "14": [2, 2], "04": [3, 2], "03": [4, 2], "01": [5, 2],109  "13": [1, 3], "06": [2, 3], "17": [3, 3], "12": [4, 3], "16": [2, 4], "05": [3, 4],110};111112/** Cartogramme schématique : une tuile par région administrative, placée approximativement selon la géographie. */113function RegionTiles({ groups }: { groups: GroupStat[] }) {114  const cell = 78;115  const gap = 6;116  return (117    <svg viewBox={`0 0 ${7 * (cell + gap)} ${5 * (cell + gap)}`} role="img" aria-label={`Performance par région : ${groups.map((g) => `${g.label} ${g.correct} sur ${g.n}`).join(", ")}`}>118      {Object.entries(REGION_TILES).map(([code, [col, row]]) => {119        const g = groups.find((x) => x.key === code);120        const x = col * (cell + gap);121        const y = row * (cell + gap);122        const fill = !g ? "var(--ivory-2)" : `color-mix(in srgb, var(--forest) ${Math.round(18 + g.rate * 82)}%, var(--ivory))`;123        const light = g ? g.rate > 0.45 : false;124        return (125          <g key={code}>126            <rect x={x} y={y} width={cell} height={cell} rx={2} fill={fill} stroke={g ? "none" : "var(--stone)"} strokeDasharray={g ? undefined : "3 3"} />127            <text x={x + 8} y={y + 18} className="chart-axis" style={{ fill: light ? "#ffffff" : "var(--graphite-2)", fontSize: 8.5 }}>{g?.label.slice(0, 15) ?? ""}</text>128            {g && (129              <>130                <text x={x + 8} y={y + 50} style={{ fill: light ? "#ffffff" : "var(--graphite)", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 22 }}>{Math.round(g.rate * 100)} %</text>131                <text x={x + 8} y={y + 66} className="chart-axis" style={{ fill: light ? "#dcebf2" : "var(--graphite-3)", fontSize: 8.5 }}>{g.correct} / {g.n}</text>132              </>133            )}134          </g>135        );136      })}137    </svg>138  );139}140141export default function Finale({ id }: { id: string }) {142  const [results, setResults] = useState<Results | null>(null);143  const [analytics, setAnalytics] = useState<Analytics | null>(null);144  const [review, setReview] = useState<ReviewItem[] | null>(null);145  const [onlyWrong, setOnlyWrong] = useState(true);146  const [shown, setShown] = useState(8);147  const [error, setError] = useState<{ code: string; message: string } | null>(null);148  const celebrate = useMemo(() => new URLSearchParams(window.location.search).get("finale") === "1", []);149150  useEffect(() => {151    void (async () => {152      try {153        const r = await api<Results>("/api/v1/results/me", { game: id });154        setResults(r);155        document.title = `${r.summary.correct} / ${r.total} — Le Grand Défi Immobilier`;156        const [a, v] = await Promise.all([api<Analytics>("/api/v1/results/me/analytics", { game: id }), api<ReviewItem[]>("/api/v1/results/me/review", { game: id })]);157        setAnalytics(a);158        setReview(v);159      } catch (e) {160        setError(e instanceof ApiError ? { code: e.code, message: e.message } : { code: "error", message: "Résultats indisponibles." });161      }162    })();163  }, [id]);164165  if (error) {166    return (167      <div className="theme-night center-screen">168        <div className="stack" style={{ maxWidth: 480 }}>169          <h1 className="title" style={{ fontSize: "var(--step-3)" }}>{error.code === "not_completed" ? "La partie n'est pas terminée" : "Résultats introuvables"}</h1>170          <p className="muted">{error.message}</p>171          <div className="row" style={{ justifyContent: "center" }}>172            {error.code === "not_completed" && <Link href={`/jouer/${id}`} className="btn btn-primary">Continuer ma partie</Link>}173            <Link href="/" className="btn btn-ghost">Accueil</Link>174          </div>175        </div>176      </div>177    );178  }179  if (!results) return <div className="theme-night center-screen" role="status"><span className="spinner" /></div>;180181  const s = results.summary;182  const step = (i: number) => (celebrate && !prefersReducedMotion() ? { initial: { opacity: 0, y: 24 }, animate: { opacity: 1, y: 0 }, transition: { delay: 0.5 + i * 0.55, duration: 0.7, ease: [0.16, 1, 0.3, 1] as [number, number, number, number] } } : {});183  const items = (review ?? []).filter((r) => !onlyWrong || !r.isCorrect);184  const ideal = analytics ? analytics.progression.map((p) => ({ x: p.n, y: p.n })) : [];185186  return (187    <div>188      <section className="theme-night finale">189        {celebrate && s.correct / results.total >= 0.6 && <Confetti />}190        <header className="topbar no-print">191          <Link href="/"><Logo /></Link>192          {results.mode !== "training" && <Link href={`/classement/${results.competitionId}`} className="btn btn-quiet"><IconTrophy size={18} /> Classement</Link>}193        </header>194        <main id="contenu" className="wrap finale-body">195          <motion.p className="kicker" {...step(-0.5)}>Défi terminé · {results.competitionName}</motion.p>196          <motion.p className="num finale-score" {...step(0)} aria-label={`${s.correct} bonnes réponses sur ${results.total}`}>197            <CountUp value={s.correct} format={(v) => String(Math.round(v))} duration={celebrate ? 2200 : 0} delay={celebrate ? 600 : 0} />198            <span className="muted"> / {results.total}</span>199          </motion.p>200          <motion.div {...step(1.6)} className="stack" style={{ "--gap": "var(--s-2)" } as React.CSSProperties}>201            <p className="title finale-title">{results.title.title}</p>202            <p className="small muted">{results.displayName} · titre ludique, sans valeur de qualification professionnelle</p>203          </motion.div>204          <motion.dl className="finale-grid" {...step(2.4)}>205            {results.rank ? (206              <div className="finale-cell">207                <dt className="eyebrow">Rang</dt>208                <dd className="num">{ordinal(results.rank.rank)}<span className="muted small"> sur {results.rank.of}</span></dd>209                {results.rank.tied && <dd className="small muted">ex æquo</dd>}210              </div>211            ) : results.horsConcours ? (212              <div className="finale-cell">213                <dt className="eyebrow">Rang</dt>214                <dd className="num">HC</dd>215                <dd className="small muted">hors concours : ni podium ni prix</dd>216              </div>217            ) : (218              <div className="finale-cell">219                <dt className="eyebrow">Sens des erreurs</dt>220                <dd className="num">{s.overestimates}<span className="muted small"> sur · </span>{s.underestimates}<span className="muted small"> sous</span></dd>221                <dd className="small muted">surestimations et sous-estimations</dd>222              </div>223            )}224            <div className="finale-cell"><dt className="eyebrow">Erreur relative moyenne</dt><dd className="num">{formatPercent(s.mape, 1)}</dd></div>225            <div className="finale-cell"><dt className="eyebrow">Plus longue série</dt><dd className="num">{s.bestStreak}</dd><dd className="small muted">bonnes réponses d'affilée</dd></div>226            <div className="finale-cell"><dt className="eyebrow">Erreur médiane</dt><dd className="num">{formatPercent(s.medianRelError, 1)}</dd></div>227            <div className="finale-cell"><dt className="eyebrow">Erreur moyenne</dt><dd className="num">{formatMoney(s.meanAbsError)}</dd></div>228            <div className="finale-cell"><dt className="eyebrow">Biais moyen</dt><dd className="num">{s.bias === 0 ? "0 %" : `${s.bias > 0 ? "+" : "−"}${formatPercent(Math.abs(s.bias), 1)}`}</dd><dd className="small muted">{s.bias > 0.5 ? "tendance à surestimer" : s.bias < -0.5 ? "tendance à sous-estimer" : "estimations équilibrées"}</dd></div>229          </motion.dl>230          {(results.best || results.worst) && (231            <motion.div className="finale-insights" {...step(3.2)}>232              {results.best && (233                <div className="finale-insight">234                  <span className="eyebrow">Votre spécialité</span>235                  <strong>{results.best.label}</strong>236                  <span className="muted small">{results.best.correct} sur {results.best.n} · erreur moyenne de {formatPercent(results.best.mape, 1)}</span>237                </div>238              )}239              {results.worst && (240                <div className="finale-insight">241                  <span className="eyebrow">Axe d'amélioration</span>242                  <strong>{results.worst.label}</strong>243                  <span className="muted small">{results.worst.correct} sur {results.worst.n} · erreur moyenne de {formatPercent(results.worst.mape, 1)}</span>244                </div>245              )}246            </motion.div>247          )}248          <motion.div className="row no-print" style={{ justifyContent: "center" }} {...step(4)}>249            <a href="#rapport" className="btn btn-primary btn-lg">Mon rapport détaillé <IconDown /></a>250            {results.mode !== "training" ? <Link href={`/classement/${results.competitionId}`} className="btn btn-ghost btn-lg">Voir le classement</Link> : <Link href="/" className="btn btn-ghost btn-lg">Rejouer</Link>}251          </motion.div>252        </main>253      </section>254255      <section className="report" id="rapport" aria-labelledby="rapport-titre">256        <div className="wrap stack" style={{ "--gap": "var(--s-6)" } as React.CSSProperties}>257          <div className="row" style={{ justifyContent: "space-between", alignItems: "end" }}>258            <div className="stack" style={{ "--gap": "var(--s-2)" } as React.CSSProperties}>259              <p className="kicker">Rapport individuel · {results.displayName}</p>260              <h2 id="rapport-titre" className="display" style={{ fontSize: "var(--step-4)" }}>Comprendre vos <em>résultats</em></h2>261            </div>262            <button type="button" className="btn btn-ghost no-print" onClick={() => window.print()}><IconPrint size={18} /> Imprimer ou enregistrer en PDF</button>263          </div>264          <p className="callout small">{results.disclaimer}</p>265266          {!analytics ? (267            <div style={{ display: "grid", placeItems: "center", padding: "var(--s-8)" }}><span className="spinner" /></div>268          ) : (269            <div className="report-grid">270              <ChartCard title="1 · Évolution du score cumulatif" note="La ligne pointillée représente un parcours sans faute.">271                <LineChart points={analytics.progression.map((p) => ({ x: p.n, y: p.score }))} yMax={results.total} yFormat={(v) => String(v)} label="Score cumulatif au fil des propriétés" reference={{ points: ideal, label: "sans faute" }} />272              </ChartCard>273              <ChartCard title="2 · Évolution de l'erreur relative moyenne" note="Moyenne des erreurs relatives depuis le début de la partie.">274                <LineChart points={analytics.progression.map((p) => ({ x: p.n, y: p.runningMape }))} yMax={Math.max(5, ...analytics.progression.map((p) => p.runningMape)) * 1.1} yFormat={(v) => `${v.toLocaleString("fr-CA")} %`} label="Erreur relative moyenne cumulative" color="var(--coral-deep)" />275              </ChartCard>276              <ChartCard title="3 · Distribution des erreurs relatives">277                <ColumnChart data={analytics.errorDistribution.map((d) => ({ label: d.label.replace(" à ", "–").replace("Plus de ", "> ").replace(/ %/g, ""), value: d.count, highlight: d.label === "Exact" }))} label="Nombre de réponses par classe d'erreur relative (en %)" />278              </ChartCard>279              <ChartCard title="4 · Biais d'estimation" note={`Biais moyen signé : ${s.bias > 0 ? "+" : s.bias < 0 ? "−" : ""}${formatPercent(Math.abs(s.bias), 2)}. Erreur maximale : ${formatSignedMoney(s.maxAbsError).replace("+", "")} (${formatPercent(s.maxRelError, 1)}).`}>280                <BiasBar over={analytics.bias.over} under={analytics.bias.under} exact={analytics.bias.exact} />281              </ChartCard>282              <ChartCard title="5 · Prix choisis et prix affichés" wide note="Échelles logarithmiques. Cercle plein : réponse exacte (sur la diagonale). Losange : erreur.">283                <ScatterChart points={analytics.scatter} />284              </ChartCard>285              <ChartCard title="6 · Performance par type de propriété"><GroupBars groups={analytics.byCategory} /></ChartCard>286              <ChartCard title="7 · Performance par tranche de prix"><GroupBars groups={analytics.byPriceBand} /></ChartCard>287              <ChartCard title="8 · Performance par niveau de difficulté"><GroupBars groups={analytics.byDifficulty} /></ChartCard>288              <ChartCard title="9 · Performance par phase du jeu"><GroupBars groups={analytics.byPhase} /></ChartCard>289              <ChartCard title="10 · Performance par région"><GroupBars groups={analytics.byRegion} /></ChartCard>290              <ChartCard title="11 · Séries de bonnes réponses" note="Nombre de séries selon leur longueur.">291                {analytics.streaks.length > 0 ? (292                  <ColumnChart data={analytics.streaks.map((x) => ({ label: String(x.length), value: x.count, highlight: x.length === s.bestStreak }))} label="Distribution des séries de bonnes réponses" color="var(--forest-mid)" />293                ) : (294                  <p className="muted small">Aucune série de bonnes réponses dans cette partie.</p>295                )}296              </ChartCard>297              <ChartCard title="12 · Carte régionale des performances" wide note="Cartogramme schématique des 17 régions administratives. Tuile pointillée : aucune propriété de cette région dans votre partie.">298                <RegionTiles groups={analytics.byRegion} />299              </ChartCard>300            </div>301          )}302303          <div className="stack" style={{ "--gap": "var(--s-4)" } as React.CSSProperties}>304            <div className="row" style={{ justifyContent: "space-between" }}>305              <h2 className="title" style={{ fontSize: "var(--step-3)" }}>Révision des propriétés</h2>306              <div className="row no-print" role="radiogroup" aria-label="Filtrer les propriétés">307                <button type="button" role="radio" aria-checked={onlyWrong} className="chip" onClick={() => { setOnlyWrong(true); setShown(8); }}>Mes erreurs ({s.wrong})</button>308                <button type="button" role="radio" aria-checked={!onlyWrong} className="chip" onClick={() => { setOnlyWrong(false); setShown(8); }}>Toutes ({s.answered})</button>309              </div>310            </div>311            {review && items.length === 0 && <p className="muted">Aucune erreur à revoir. Un parcours sans faute.</p>}312            <div className="review-list">313              {items.slice(0, shown).map((item) => (314                <article key={item.questionId} className="review-item">315                  {item.images[0] ? <img src={imageUrl(item.images[0], 480)} alt={`${item.card.categoryLabel} à ${item.card.municipality}`} loading="lazy" /> : <div />}316                  <div className="stack" style={{ "--gap": "var(--s-3)" } as React.CSSProperties}>317                    <div>318                      <p className="eyebrow">Propriété {item.number}</p>319                      <h3 className="title" style={{ fontSize: "var(--step-1)" }}>{item.card.categoryLabel} · {[item.card.sector, item.card.municipality].filter(Boolean).join(", ")}</h3>320                      <p className="small muted">{item.card.facts.map((f) => (["bedrooms", "bathrooms", "powder"].includes(f.key) ? `${f.value} ${f.label}` : `${f.label} : ${f.value}`)).join(" · ")}</p>321                    </div>322                    <div className="review-choices">323                      {item.choices.map((c) => (324                        <span key={c.id} className={`tag ${c.isCorrect ? "tag-success" : c.chosen ? "tag-error" : ""}`}>325                          {c.isCorrect ? <IconCheck size={14} /> : c.chosen ? <IconCross size={14} /> : null}326                          <span className="tabular">{formatMoney(c.price)}</span>327                          {c.isCorrect && <span className="sr-only"> (prix affiché)</span>}328                          {c.chosen && !c.isCorrect && <span className="sr-only"> (votre réponse)</span>}329                        </span>330                      ))}331                    </div>332                    {!item.isCorrect && <p className="small">{item.feedback.headline} Écart : <strong>{formatSignedMoney(item.feedback.delta)}</strong> ({formatPercent(item.feedback.relErrorPct, 1)}).</p>}333                    {item.feedback.insights.slice(0, 3).map((i) => <p key={i.key} className="small muted">{i.label} : <strong style={{ color: "var(--graphite)" }}>{i.value}</strong>{i.note ? ` — ${i.note}` : ""}</p>)}334                  </div>335                </article>336              ))}337            </div>338            {items.length > shown && <button type="button" className="btn btn-ghost no-print" onClick={() => setShown(shown + 12)}>Afficher plus ({items.length - shown} restantes)</button>}339          </div>340341          <div className="row no-print" style={{ paddingTop: "var(--s-5)", borderTop: "1px solid var(--line)" }}>342            <Link href="/" className="btn btn-dark">Rejouer en entraînement <IconArrow /></Link>343            {results.mode !== "training" && <Link href={`/classement/${results.competitionId}`} className="btn btn-ghost">Classement complet</Link>}344          </div>345        </div>346      </section>347    </div>348  );349}350
Files main
Menu

Theme