SPB Git

Repository Public

Journal.tsx 9.3 KB 167 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/Journal.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 { useMemo, useState } from "react";44import { Link } from "wouter";45import { formatDateTime, useLoad, type AuditEntry, type CompetitionListItem } from "./lib";46import { Empty, LoadState, PageHead, RefreshButton, TableScroll } from "./ui";4748const ACTIONS: Record<string, { label: string; group: string }> = {49  "competition.create": { label: "Création d'une compétition", group: "Compétitions" },50  "competition.update": { label: "Modification des paramètres", group: "Compétitions" },51  "competition.delete": { label: "Suppression d'un brouillon", group: "Compétitions" },52  "competition.generate": { label: "Génération de la banque", group: "Compétitions" },53  "competition.regenerate_choices": { label: "Régénération de choix de prix", group: "Compétitions" },54  "competition.replace_question": { label: "Remplacement d'une propriété", group: "Compétitions" },55  "competition.publish": { label: "Publication", group: "Compétitions" },56  "competition.close": { label: "Fermeture", group: "Compétitions" },57  "competition.archive": { label: "Archivage", group: "Compétitions" },58  "competition.duplicate": { label: "Duplication", group: "Compétitions" },59  "question.flag": { label: "Signalement d'une question", group: "Questions" },60  "flag.resolve": { label: "Signalement de joueur traité", group: "Questions" },61  "session.reset": { label: "Réinitialisation d'une partie", group: "Participants" },62  "session.exclude": { label: "Exclusion d'une partie", group: "Participants" },63  "session.restore": { label: "Rétablissement d'une partie", group: "Participants" },64  "participant.delete": { label: "Suppression de renseignements personnels", group: "Participants" },65  "anomaly.review": { label: "Anomalie examinée", group: "Participants" },66  export: { label: "Export de données", group: "Exports" },67  "sync.start": { label: "Lancement d'une synchronisation", group: "Données" },68  "roster.replace": { label: "Remplacement d'une liste de classe", group: "Participants" },69};7071const FIELD_LABEL: Record<string, string> = {72  name: "nom", size: "taille", courses: "cours", allowExternal: "participants hors cours", startsAt: "début", endsAt: "fin",73  accessCode: "code d'accès", notes: "notes", config: "filtres, difficulté ou prix",74};75const STATUS_LABEL: Record<string, string> = { draft: "brouillon", published: "publiée", closed: "fermée", archived: "archivée" };7677function text(value: unknown): string {78  return typeof value === "string" || typeof value === "number" ? String(value) : "";79}8081/** Traduit le détail technique d'une entrée en une phrase lisible. */82function describe(entry: AuditEntry): string {83  const d = entry.detail ?? {};84  const parts: string[] = [];85  if (typeof d.name === "string") parts.push(`« ${d.name} »`);86  if (typeof d.reason === "string") parts.push(`Justification : ${d.reason}`);87  if (Array.isArray(d.fields)) parts.push(`Champs : ${d.fields.map((f) => FIELD_LABEL[String(f)] ?? String(f)).join(", ") || "aucun"}`);88  if (typeof d.status === "string") parts.push(`état ${STATUS_LABEL[d.status] ?? d.status}`);89  if (typeof d.count === "number") parts.push(entry.action === "roster.replace" ? `${d.count} nom${d.count > 1 ? "s" : ""} dans la liste` : `${d.count} question${d.count > 1 ? "s" : ""}`);90  if (typeof d.questionId === "string" && entry.action === "competition.regenerate_choices") parts.push(d.questionId === "toutes" ? "toutes les questions" : "une seule question");91  if (typeof d.bankVersion === "number") parts.push(`banque version ${d.bankVersion}`);92  if (typeof d.format === "string") parts.push(`${d.scope === "questions" ? "Questions" : "Résultats"}, format ${d.format.toUpperCase()}`);93  if (typeof d.flagged === "boolean") parts.push(d.flagged ? "Question signalée" : "Signalement retiré");94  if (typeof d.note === "string" && d.note) parts.push(`Note : ${d.note}`);95  if (entry.action === "competition.duplicate" && d.from) parts.push("copie d'une compétition existante");96  return parts.join(" · ") || text(d.detail);97}9899function shortId(id: string): string {100  return id.length > 12 ? `${id.slice(0, 8)}…` : id;101}102103export default function Journal() {104  const state = useLoad<AuditEntry[]>("/audit");105  const competitions = useLoad<CompetitionListItem[]>("/competitions");106  const [group, setGroup] = useState("");107  const names = useMemo(() => new Map((competitions.data ?? []).map((c) => [c.id, c.name])), [competitions.data]);108  const groups = [...new Set(Object.values(ACTIONS).map((a) => a.group))];109110  return (111    <div className="adm-page">112      <PageHead113        title="Journal"114        lede="Les 200 dernières actions sensibles, de la plus récente à la plus ancienne. Le journal ne peut être ni modifié ni effacé depuis cette interface."115        actions={<RefreshButton state={state} />}116      />117      <LoadState state={state} label="Chargement du journal…">118        {(rows) => {119          const shown = rows.filter((r) => !group || (ACTIONS[r.action]?.group ?? "Autres") === group);120          return rows.length === 0 ? (121            <Empty title="Le journal est vide"><p>Les créations, publications, exclusions, exports et synchronisations s'inscriront ici.</p></Empty>122          ) : (123            <>124              <div className="adm-filters" role="group" aria-label="Filtrer le journal par domaine">125                <button type="button" className="chip" aria-pressed={group === ""} onClick={() => setGroup("")}>Tout ({rows.length})</button>126                {groups.map((g) => {127                  const n = rows.filter((r) => ACTIONS[r.action]?.group === g).length;128                  return <button key={g} type="button" className="chip" aria-pressed={group === g} onClick={() => setGroup(g)} disabled={n === 0}>{g} ({n})</button>;129                })}130              </div>131              {shown.length === 0 ? (132                <Empty title="Aucune action dans ce domaine" />133              ) : (134                <TableScroll label="Journal des actions">135                  <table className="table adm-table">136                    <caption className="sr-only">Actions sensibles horodatées (heure de Montréal)</caption>137                    <thead>138                      <tr><th scope="col">Date et heure</th><th scope="col">Action</th><th scope="col">Objet</th><th scope="col">Détail</th><th scope="col">Auteur</th></tr>139                    </thead>140                    <tbody>141                      {shown.map((r) => {142                        const action = ACTIONS[r.action];143                        const name = r.target ? names.get(r.target) : undefined;144                        return (145                          <tr key={r.id}>146                            <td className="small adm-nowrap">{formatDateTime(r.at)}</td>147                            <th scope="row" className="adm-cell-main"><span>{action?.label ?? r.action}</span><span className="small muted">{action?.group ?? "Autres"}</span></th>148                            <td className="small">149                              {r.target === null ? <span className="muted">—</span> : name ? <Link href={`/admin/competitions/${r.target}`}>{name}</Link> : r.action === "roster.replace" ? <Link href="/admin/listes">{r.target}</Link> : <span className="adm-mono" title={r.target}>{shortId(r.target)}</span>}150                            </td>151                            <td className="small adm-cell-wide">{describe(r) || <span className="muted">—</span>}</td>152                            <td className="small">{r.actor === "admin" ? "Administration" : r.actor}</td>153                          </tr>154                        );155                      })}156                    </tbody>157                  </table>158                </TableScroll>159              )}160            </>161          );162        }}163      </LoadState>164    </div>165  );166}167
Files main
Menu

Theme