SPB Git

Repository Public

Participants.tsx 23.3 KB 458 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/admin/Participants.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, useState } from "react";44import { formatInt, formatMoney, formatPercent } from "@jeux/engine/format";45import { IconCheck, IconChevronLeft, IconChevronRight, IconCross, IconSearch } from "../components/Icons";46import {47  ANOMALY_LABEL,48  SESSION_STATUS,49  adminApi,50  categoryLabel,51  formatAgo,52  formatDateTime,53  formatSeconds,54  useLoad,55  type CompetitionListItem,56  type GameMode,57  type ParticipantRow,58  type ParticipantsPage,59  type SessionDetail,60  type SessionStatus,61} from "./lib";62import { ActionDialog, Empty, LoadState, Modal, Note, PageHead, RefreshButton, TableScroll, type Ask } from "./ui";6364const MODES: { key: GameMode; label: string }[] = [65  { key: "official", label: "Officiel" },66  { key: "training", label: "Entraînement" },67  { key: "daily", label: "Défi du jour" },68];6970export function SessionTag({ status }: { status: SessionStatus }) {71  return <span className={`adm-status is-s-${status}`}><span className="adm-status-mark" aria-hidden="true" />{SESSION_STATUS[status]}</span>;72}7374function courseText(course: string | null): string {75  return course ?? "Hors cours";76}7778type Target = Pick<ParticipantRow, "id" | "participant_id" | "display_name" | "status" | "competition_name">;7980function buildAsk(kind: "reset" | "exclude" | "restore" | "delete", t: Target, after?: () => void): Ask {81  const who = <strong>{t.display_name}</strong>;82  const post = async (path: string, reason: string): Promise<void> => {83    await adminApi(`/sessions/${t.id}/${path}`, { method: "POST", body: { reason } });84    after?.();85  };86  switch (kind) {87    case "reset":88      return {89        title: "Réinitialiser cette partie ?",90        body: <p>La partie de {who} dans « {t.competition_name} » sera retirée du classement et marquée « réinitialisée ». Le participant pourra recommencer une nouvelle partie du début. <strong>Cette action ne peut pas être annulée.</strong></p>,91        confirmLabel: "Réinitialiser la partie",92        danger: true,93        reason: true,94        run: async (reason) => {95          await post("reset", reason);96          return `Partie de ${t.display_name} réinitialisée.`;97        },98      };99    case "exclude":100      return {101        title: "Exclure cette partie du classement ?",102        body: (103          <>104            <p>La partie de {who} dans « {t.competition_name} » sera retirée du classement. Elle pourra être rétablie plus tard.</p>105            <p>Rappel : une anomalie statistique n'est jamais une preuve. L'exclusion est une décision humaine, à justifier.</p>106          </>107        ),108        confirmLabel: "Exclure la partie",109        danger: true,110        reason: true,111        run: async (reason) => {112          await post("exclude", reason);113          return `Partie de ${t.display_name} exclue du classement.`;114        },115      };116    case "restore":117      return {118        title: "Rétablir cette partie ?",119        body: <p>La partie de {who} retrouvera son état d'origine (en cours ou terminée) et reviendra au classement.</p>,120        confirmLabel: "Rétablir la partie",121        reason: true,122        run: async (reason) => {123          await post("restore", reason);124          return `Partie de ${t.display_name} rétablie.`;125        },126      };127    case "delete":128      return {129        title: "Supprimer les renseignements personnels ?",130        body: (131          <p>132            Le participant {who} sera <strong>supprimé définitivement</strong>, avec son nom, son groupe et <strong>toutes ses parties</strong>, dans toutes les compétitions. À utiliser pour répondre à une demande de retrait. Cette action ne peut pas être annulée.133          </p>134        ),135        confirmLabel: "Supprimer définitivement",136        danger: true,137        reason: true,138        check: "Je confirme la suppression définitive de ce participant et de toutes ses parties.",139        run: async (reason) => {140          await adminApi(`/participants/${t.participant_id}`, { method: "DELETE", body: { reason } });141          after?.();142          return `Renseignements personnels de ${t.display_name} supprimés.`;143        },144      };145  }146}147148function SessionPanel({ id, onClose, onChanged }: { id: string; onClose: () => void; onChanged: () => void }) {149  const state = useLoad<SessionDetail>(`/sessions/${id}`);150  const [ask, setAsk] = useState<Ask | null>(null);151  const refresh = (): void => {152    void state.reload();153    onChanged();154  };155  const title = state.data ? `Partie de ${state.data.session.display_name}` : "Détail de la partie";156  return (157    <Modal title={title} size="xl" onClose={onClose}>158      <LoadState state={state} label="Chargement de la partie…">159        {({ session: s, answers, anomalies }) => {160          const target: Target = { id: s.id, participant_id: s.participant_id, display_name: s.display_name, status: s.status, competition_name: s.competition_name };161          const live = s.status === "in_progress" || s.status === "completed";162          const mape = s.answered > 0 ? (100 * s.sum_rel_error) / s.answered : null;163          return (164            <div className="stack">165              <dl className="adm-dl adm-dl-2">166                <div><dt>Compétition</dt><dd>{s.competition_name}</dd></div>167                <div><dt>Groupe</dt><dd>{courseText(s.course)}</dd></div>168                <div><dt>État</dt><dd><SessionTag status={s.status} />{s.status === "in_progress" && s.answered < s.total ? " · partie incomplète" : ""}</dd></div>169                <div><dt>Progression</dt><dd className="tabular">{s.answered} / {s.total} réponses</dd></div>170                <div><dt>Bonnes réponses</dt><dd className="tabular">{s.correct}{s.answered > 0 ? ` (${formatPercent((100 * s.correct) / s.answered, 0)} des réponses données)` : ""}</dd></div>171                <div><dt>Erreur relative moyenne</dt><dd className="tabular">{mape === null ? "—" : formatPercent(mape, 1)}</dd></div>172                <div><dt>Plus longue série</dt><dd className="tabular">{s.best_streak}</dd></div>173                <div><dt>Début</dt><dd>{formatDateTime(s.started_at)}</dd></div>174                <div><dt>Dernière activité</dt><dd>{formatDateTime(s.last_activity_at)}</dd></div>175                <div><dt>Fin</dt><dd>{s.completed_at ? formatDateTime(s.completed_at) : "Non terminée"}</dd></div>176                {s.admin_note && <div><dt>Justification consignée</dt><dd>{s.admin_note}</dd></div>}177              </dl>178179              <div className="adm-actions">180                {live && <button type="button" className="btn btn-ghost" onClick={() => setAsk(buildAsk("reset", target, refresh))}>Réinitialiser</button>}181                {live && <button type="button" className="btn btn-ghost" onClick={() => setAsk(buildAsk("exclude", target, refresh))}>Exclure du classement</button>}182                {s.status === "excluded" && <button type="button" className="btn btn-ghost" onClick={() => setAsk(buildAsk("restore", target, refresh))}>Rétablir</button>}183                <button type="button" className="btn btn-danger" onClick={() => setAsk(buildAsk("delete", target, () => { onChanged(); onClose(); }))}>Supprimer les renseignements personnels</button>184              </div>185186              <section aria-labelledby="adm-anomalies">187                <h3 className="adm-h3" id="adm-anomalies">Anomalies statistiques ({anomalies.length})</h3>188                <Note tone="info">Une anomalie statistique n'est jamais une preuve de tricherie et n'entraîne aucune exclusion automatique : elle invite seulement à examiner la partie.</Note>189                {anomalies.length === 0 ? (190                  <p className="adm-quiet">Aucune anomalie relevée pour cette partie.</p>191                ) : (192                  <ul role="list" className="adm-list">193                    {anomalies.map((a) => (194                      <li key={a.id}>195                        <div>196                          <p><strong>{ANOMALY_LABEL[a.kind] ?? a.kind}</strong> · <span className="small muted">{formatDateTime(a.created_at)}</span></p>197                          <p className="small">{a.detail}</p>198                        </div>199                        {a.reviewed ? (200                          <span className="adm-state is-ok"><IconCheck size={16} />Examinée</span>201                        ) : (202                          <button203                            type="button"204                            className="btn btn-ghost"205                            onClick={() =>206                              setAsk({207                                title: "Marquer l'anomalie comme examinée ?",208                                body: <p>L'anomalie « {ANOMALY_LABEL[a.kind] ?? a.kind} » ne comptera plus parmi les anomalies en attente. La partie n'est pas modifiée.</p>,209                                confirmLabel: "Marquer comme examinée",210                                run: async () => {211                                  await adminApi(`/anomalies/${a.id}/review`, { method: "POST", body: {} });212                                  refresh();213                                  return "Anomalie marquée comme examinée.";214                                },215                              })216                            }217                          >218                            Marquer comme examinée219                          </button>220                        )}221                      </li>222                    ))}223                  </ul>224                )}225              </section>226227              <section aria-labelledby="adm-reponses">228                <h3 className="adm-h3" id="adm-reponses">Réponses ({answers.length})</h3>229                {answers.length === 0 ? (230                  <p className="adm-quiet">Aucune réponse enregistrée.</p>231                ) : (232                  <TableScroll label="Réponses de la partie">233                    <table className="table adm-table">234                      <caption className="sr-only">Réponses dans l'ordre où elles ont été données</caption>235                      <thead>236                        <tr>237                          <th scope="col" className="right">N°</th>238                          <th scope="col">Propriété</th>239                          <th scope="col" className="right">Prix choisi</th>240                          <th scope="col" className="right">Prix réel</th>241                          <th scope="col">Résultat</th>242                          <th scope="col" className="right">Erreur</th>243                          <th scope="col" className="right">Temps</th>244                        </tr>245                      </thead>246                      <tbody>247                        {answers.map((a) => (248                          <tr key={a.idx}>249                            <td className="right">{a.idx + 1}</td>250                            <th scope="row" className="adm-cell-main"><span>{a.municipality ?? "Municipalité inconnue"}</span><span className="small muted">{categoryLabel(a.category)}</span></th>251                            <td className="right">{formatMoney(a.chosen_price)}</td>252                            <td className="right">{formatMoney(a.correct_price)}</td>253                            <td>254                              {a.is_correct ? (255                                <span className="adm-state is-ok"><IconCheck size={16} />Exacte</span>256                              ) : (257                                <span className="adm-state is-bad"><IconCross size={16} />{a.chosen_price > a.correct_price ? "Surestimée" : "Sous-estimée"}</span>258                              )}259                            </td>260                            <td className="right">{formatPercent(100 * a.rel_error, 1)}</td>261                            <td className="right">{formatSeconds(a.response_ms)}</td>262                          </tr>263                        ))}264                      </tbody>265                    </table>266                  </TableScroll>267                )}268              </section>269            </div>270          );271        }}272      </LoadState>273      {ask && <ActionDialog ask={ask} onClose={() => setAsk(null)} />}274    </Modal>275  );276}277278export default function Participants() {279  const competitions = useLoad<CompetitionListItem[]>("/competitions");280  const [search, setSearch] = useState("");281  const [q, setQ] = useState("");282  const [competitionId, setCompetitionId] = useState("");283  const [course, setCourse] = useState("");284  const [status, setStatus] = useState<"" | SessionStatus>("");285  const [mode, setMode] = useState<GameMode>("official");286  const [page, setPage] = useState(1);287  const [openId, setOpenId] = useState<string | null>(null);288  const [ask, setAsk] = useState<Ask | null>(null);289290  useEffect(() => {291    const timer = window.setTimeout(() => {292      setQ(search.trim());293      setPage(1);294    }, 300);295    return () => window.clearTimeout(timer);296  }, [search]);297298  const params = new URLSearchParams({ mode, page: String(page) });299  if (q) params.set("q", q);300  if (competitionId && mode === "official") params.set("competitionId", competitionId);301  if (course) params.set("course", course);302  if (status) params.set("status", status);303  const state = useLoad<ParticipantsPage>(`/participants?${params.toString()}`);304  const data = state.data;305  const pages = data ? Math.max(1, Math.ceil(data.matches / data.pageSize)) : 1;306  const filtered = q !== "" || competitionId !== "" || course !== "" || status !== "";307  const change = <T,>(setter: (v: T) => void) => (value: T): void => {308    setter(value);309    setPage(1);310  };311  const reset = (): void => {312    setSearch("");313    setQ("");314    setCompetitionId("");315    setCourse("");316    setStatus("");317    setPage(1);318  };319320  return (321    <div className="adm-page">322      <PageHead323        title="Participants"324        lede="Chaque ligne est une partie. Toute intervention exige une justification écrite et une confirmation, puis s'inscrit au journal."325        actions={<RefreshButton state={state} />}326      />327      <Note tone="info" title="Anomalies statistiques.">328        Une anomalie (réponses très rapides, cadence uniforme) n'est jamais une preuve et n'entraîne aucune exclusion automatique. Elle signale seulement une partie à examiner.329      </Note>330331      <form className="adm-filterbar" role="search" aria-label="Filtrer les parties" onSubmit={(e) => e.preventDefault()}>332        <div className="field adm-filter-search">333          <label htmlFor="adm-p-q">Recherche par nom</label>334          <div className="adm-search">335            <IconSearch size={18} />336            <input id="adm-p-q" className="input" type="search" value={search} onChange={(e) => setSearch(e.target.value)} maxLength={60} placeholder="Nom du participant" autoComplete="off" />337          </div>338        </div>339        <div className="field">340          <label htmlFor="adm-p-mode">Mode</label>341          <select id="adm-p-mode" className="input" value={mode} onChange={(e) => change(setMode)(e.target.value as GameMode)}>342            {MODES.map((m) => <option key={m.key} value={m.key}>{m.label}</option>)}343          </select>344        </div>345        <div className="field">346          <label htmlFor="adm-p-comp">Compétition</label>347          <select id="adm-p-comp" className="input" value={mode === "official" ? competitionId : ""} onChange={(e) => change(setCompetitionId)(e.target.value)} disabled={mode !== "official"}>348            <option value="">Toutes</option>349            {(competitions.data ?? []).map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}350          </select>351        </div>352        <div className="field">353          <label htmlFor="adm-p-groupe">Groupe</label>354          <select id="adm-p-groupe" className="input" value={course} onChange={(e) => change(setCourse)(e.target.value)}>355            <option value="">Tous</option>356            <option value="IMM1003">IMM1003</option>357            <option value="IMM1033">IMM1033</option>358            <option value="Externe">Hors cours</option>359          </select>360        </div>361        <div className="field">362          <label htmlFor="adm-p-etat">État</label>363          <select id="adm-p-etat" className="input" value={status} onChange={(e) => change(setStatus)(e.target.value as "" | SessionStatus)}>364            <option value="">Tous</option>365            <option value="in_progress">En cours (incomplètes)</option>366            <option value="completed">Terminées</option>367            <option value="reset">Réinitialisées</option>368            <option value="excluded">Exclues</option>369          </select>370        </div>371        <div className="adm-filter-actions">372          <button type="button" className="chip" aria-pressed={status === "in_progress"} onClick={() => change(setStatus)(status === "in_progress" ? "" : "in_progress")}>Parties incomplètes</button>373          {filtered && <button type="button" className="adm-textbtn" onClick={reset}>Effacer les filtres</button>}374        </div>375      </form>376377      <LoadState state={state} label="Chargement des parties…">378        {(d) => (379          <>380            <p className="small muted" role="status" aria-live="polite">381              {d.matches === 0 ? "Aucune partie." : `${formatInt(d.matches)} partie${d.matches > 1 ? "s" : ""} · page ${d.page} de ${pages}`}382              {state.refreshing ? " · actualisation…" : ""}383            </p>384            {d.rows.length === 0 ? (385              <Empty title={filtered ? "Aucune partie ne correspond à ces filtres" : "Aucune partie dans ce mode"}>386                {filtered && <p><button type="button" className="adm-textbtn" onClick={reset}>Effacer les filtres</button></p>}387              </Empty>388            ) : (389              <TableScroll label="Liste des parties">390                <table className="table adm-table">391                  <caption className="sr-only">Parties, de la plus récente à la plus ancienne</caption>392                  <thead>393                    <tr>394                      <th scope="col">Participant</th>395                      <th scope="col">Compétition</th>396                      <th scope="col">État</th>397                      <th scope="col">Progression</th>398                      <th scope="col" className="right"><abbr title="Bonnes réponses">Bonnes</abbr></th>399                      <th scope="col" className="right"><abbr title="Erreur relative moyenne">Erreur</abbr></th>400                      <th scope="col">Dernière activité</th>401                      <th scope="col">Anomalies</th>402                      <th scope="col">Actions</th>403                    </tr>404                  </thead>405                  <tbody>406                    {d.rows.map((r) => {407                      const incomplete = r.status === "in_progress" && r.answered < r.total;408                      const live = r.status === "in_progress" || r.status === "completed";409                      return (410                        <tr key={r.id}>411                          <th scope="row" className="adm-cell-main">412                            <span>{r.display_name}</span>413                            <span className="small muted">{courseText(r.course)}</span>414                          </th>415                          <td className="small adm-cell-mid">{r.competition_name}</td>416                          <td>417                            <SessionTag status={r.status} />418                            {incomplete && <span className="small adm-warn-text"><br />Incomplète</span>}419                          </td>420                          <td>421                            <span className="tabular">{r.answered} / {r.total}</span>422                            <span className="adm-meter" aria-hidden="true"><span style={{ width: `${r.total ? (100 * r.answered) / r.total : 0}%` }} /></span>423                          </td>424                          <td className="right">{r.correct}</td>425                          <td className="right">{r.mape === null ? "—" : formatPercent(r.mape, 1)}</td>426                          <td className="small adm-nowrap">{formatDateTime(r.last_activity_at)}<span className="muted"><br />{formatAgo(r.last_activity_at)}</span></td>427                          <td className="adm-nowrap">{r.anomalies > 0 ? <span className="adm-state is-warn">{r.anomalies} à réviser</span> : <span className="muted">Aucune</span>}</td>428                          <td>429                            <div className="adm-row-actions">430                              <button type="button" className="adm-textbtn" onClick={() => setOpenId(r.id)}>Détail<span className="sr-only"> de la partie de {r.display_name}</span></button>431                              {live && <button type="button" className="adm-textbtn" onClick={() => setAsk(buildAsk("exclude", r))}>Exclure<span className="sr-only"> la partie de {r.display_name}</span></button>}432                              {r.status === "excluded" && <button type="button" className="adm-textbtn" onClick={() => setAsk(buildAsk("restore", r))}>Rétablir<span className="sr-only"> la partie de {r.display_name}</span></button>}433                            </div>434                          </td>435                        </tr>436                      );437                    })}438                  </tbody>439                </table>440              </TableScroll>441            )}442            {pages > 1 && (443              <nav className="adm-pager" aria-label="Pagination des parties">444                <button type="button" className="btn btn-ghost" onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page <= 1}><IconChevronLeft size={18} />Précédente</button>445                <span className="tabular">Page {d.page} de {pages}</span>446                <button type="button" className="btn btn-ghost" onClick={() => setPage((p) => Math.min(pages, p + 1))} disabled={page >= pages}>Suivante<IconChevronRight size={18} /></button>447              </nav>448            )}449          </>450        )}451      </LoadState>452453      {openId && <SessionPanel id={openId} onClose={() => setOpenId(null)} onChanged={() => void state.reload()} />}454      {ask && <ActionDialog ask={ask} onClose={() => setAsk(null)} onDone={() => void state.reload()} />}455    </div>456  );457}458
Files main
Menu

Theme