SPB Git

Repository Public

Roster.tsx 10.6 KB 210 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/Roster.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, useId, useMemo, useState } from "react";44import { formatInt } from "@jeux/engine/format";45import { adminPut, useLoad, type Course } from "./lib";46import { ActionDialog, LoadState, Note, PageHead, RefreshButton, Section, type Ask } from "./ui";4748interface RosterEntry {49  id: string;50  course: string;51  display_name: string;52}53type RosterData = Record<Course, RosterEntry[]>;5455const COURSES: readonly Course[] = ["IMM1003", "IMM1033"];56const MAX_NAMES = 400;57const MAX_LENGTH = 80;5859/** Même clé de comparaison que le serveur : sans accents, sans casse, sans ponctuation. */60function nameKey(name: string): string {61  return name.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();62}6364function clean(line: string): string {65  return line.replace(/\s+/g, " ").trim();66}6768interface Diff {69  names: string[];70  added: string[];71  removed: string[];72  corrected: { from: string; to: string }[];73  ignored: string[];74  duplicates: number;75  tooLong: string[];76}7778function computeDiff(current: RosterEntry[], text: string): Diff {79  const before = new Map(current.map((e) => [nameKey(e.display_name), e.display_name]));80  const after = new Map<string, string>();81  const ignored: string[] = [];82  const tooLong: string[] = [];83  let duplicates = 0;84  for (const raw of text.split("\n")) {85    const name = clean(raw);86    if (!name) continue;87    if (name.length > MAX_LENGTH) {88      tooLong.push(name);89      continue;90    }91    const key = nameKey(name);92    if (key.length < 2) {93      ignored.push(name);94      continue;95    }96    if (after.has(key)) duplicates += 1;97    after.set(key, name);98  }99  const added = [...after].filter(([key]) => !before.has(key)).map(([, name]) => name);100  const removed = [...before].filter(([key]) => !after.has(key)).map(([, name]) => name);101  const corrected = [...after].filter(([key, name]) => before.has(key) && before.get(key) !== name).map(([key, name]) => ({ from: before.get(key) ?? "", to: name }));102  return { names: [...after.values()], added, removed, corrected, ignored, duplicates, tooLong };103}104105const sortFr = (names: string[]): string[] => [...names].sort((a, b) => a.localeCompare(b, "fr-CA"));106107function CourseRoster({ course, entries, onSaved }: { course: Course; entries: RosterEntry[]; onSaved: () => void }) {108  const uid = useId();109  const initial = useMemo(() => entries.map((e) => e.display_name).join("\n"), [entries]);110  const [text, setText] = useState(initial);111  const [ask, setAsk] = useState<Ask | null>(null);112  useEffect(() => setText(initial), [initial]);113  const diff = useMemo(() => computeDiff(entries, text), [entries, text]);114  const changed = diff.added.length + diff.removed.length + diff.corrected.length > 0;115  const blocked = diff.tooLong.length > 0 || diff.names.length > MAX_NAMES;116  const sorted = useMemo(() => sortFr(entries.map((e) => e.display_name)), [entries]);117118  const save = (): void =>119    setAsk({120      title: `Remplacer la liste de ${course} ?`,121      body: (122        <>123          <p>La liste de {course} passera de <strong>{formatInt(entries.length)}</strong> à <strong>{formatInt(diff.names.length)}</strong> nom{diff.names.length > 1 ? "s" : ""} : {diff.added.length} ajouté{diff.added.length > 1 ? "s" : ""}, {diff.removed.length} retiré{diff.removed.length > 1 ? "s" : ""}, {diff.corrected.length} corrigé{diff.corrected.length > 1 ? "s" : ""}.</p>124          {diff.removed.length > 0 && <p><strong>Les étudiants retirés ne pourront plus choisir leur nom</strong> à l'entrée d'une compétition officielle et ne seront plus admissibles aux prix. Les parties déjà jouées ne sont pas modifiées.</p>}125          {diff.names.length === 0 && <p><strong>La liste sera vide.</strong></p>}126        </>127      ),128      confirmLabel: "Remplacer la liste",129      danger: diff.removed.length > 0,130      check: diff.removed.length > 0 ? `Je confirme le retrait de ${diff.removed.length} nom${diff.removed.length > 1 ? "s" : ""} de la liste de ${course}.` : undefined,131      run: async () => {132        const res = await adminPut<{ count: number }>("/roster", { course, names: diff.names });133        return `Liste de ${course} enregistrée : ${res.count} nom${res.count > 1 ? "s" : ""}.`;134      },135    });136137  return (138    <Section title={course} aside={<span className="adm-count"><span className="num">{formatInt(entries.length)}</span> étudiant{entries.length > 1 ? "s" : ""}</span>}>139      <div className="adm-cols">140        <div>141          <h3 className="adm-h3">Liste actuelle</h3>142          {sorted.length === 0 ? (143            <p className="adm-quiet">Liste vide : aucun étudiant de {course} ne peut choisir son nom.</p>144          ) : (145            <ol className="adm-roster" aria-label={`Étudiants de ${course}, par ordre alphabétique`}>146              {sorted.map((name) => <li key={name}>{name}</li>)}147            </ol>148          )}149        </div>150        <div className="stack">151          <div className="field">152            <label htmlFor={`${uid}-noms`}>Modifier en bloc — un nom par ligne</label>153            <textarea id={`${uid}-noms`} className="input adm-textarea adm-roster-edit" rows={Math.min(22, Math.max(8, entries.length + 3))} value={text} onChange={(e) => setText(e.target.value)} spellCheck={false} autoComplete="off" aria-describedby={`${uid}-aide`} />154            <p id={`${uid}-aide`} className="small muted">Ajoutez, retirez ou corrigez des lignes. Les majuscules, les accents et la ponctuation ne distinguent pas deux noms ; les lignes vides et les doublons sont ignorés.</p>155          </div>156157          <div className="adm-diff" role="status" aria-live="polite" aria-label={`Aperçu des changements, ${course}`}>158            <h3 className="adm-h3">Aperçu des changements</h3>159            {!changed ? (160              <p className="adm-quiet">Aucun changement par rapport à la liste enregistrée.</p>161            ) : (162              <>163                <p className="small"><strong>{diff.added.length}</strong> ajouté{diff.added.length > 1 ? "s" : ""} · <strong>{diff.removed.length}</strong> retiré{diff.removed.length > 1 ? "s" : ""} · <strong>{diff.corrected.length}</strong> corrigé{diff.corrected.length > 1 ? "s" : ""} · total après enregistrement : <strong>{diff.names.length}</strong></p>164                <ul role="list" className="adm-diff-list">165                  {sortFr(diff.added).map((n) => <li key={`a-${n}`} className="is-added"><span className="adm-diff-mark">+ Ajouté</span><span>{n}</span></li>)}166                  {sortFr(diff.removed).map((n) => <li key={`r-${n}`} className="is-removed"><span className="adm-diff-mark">− Retiré</span><span>{n}</span></li>)}167                  {diff.corrected.map((c) => <li key={`c-${c.to}`} className="is-corrected"><span className="adm-diff-mark">≈ Corrigé</span><span>{c.from} → {c.to}</span></li>)}168                </ul>169              </>170            )}171            {diff.duplicates > 0 && <p className="small muted">{diff.duplicates} doublon{diff.duplicates > 1 ? "s" : ""} ignoré{diff.duplicates > 1 ? "s" : ""}.</p>}172            {diff.ignored.length > 0 && <p className="small muted">Ligne{diff.ignored.length > 1 ? "s" : ""} ignorée{diff.ignored.length > 1 ? "s" : ""} (moins de deux lettres) : {diff.ignored.join(", ")}.</p>}173            {diff.tooLong.length > 0 && <p className="error-text" role="alert">Nom de plus de {MAX_LENGTH} caractères à raccourcir : {diff.tooLong.map((n) => `${n.slice(0, 30)}…`).join(", ")}</p>}174            {diff.names.length > MAX_NAMES && <p className="error-text" role="alert">La liste ne peut dépasser {MAX_NAMES} noms.</p>}175          </div>176177          <div className="adm-actions">178            <button type="button" className="btn btn-dark" onClick={save} disabled={!changed || blocked}>Enregistrer la liste de {course}</button>179            <button type="button" className="btn btn-ghost" onClick={() => setText(initial)} disabled={text === initial}>Annuler les modifications</button>180          </div>181        </div>182      </div>183      {ask && <ActionDialog ask={ask} onClose={() => setAsk(null)} onDone={onSaved} />}184    </Section>185  );186}187188export default function Roster() {189  const state = useLoad<RosterData>("/roster");190  return (191    <div className="adm-page">192      <PageHead193        title="Listes de classe"194        lede="À l'entrée d'une compétition officielle, les étudiants choisissent leur nom dans un menu tiré de ces listes. Seuls les noms inscrits ici sont admissibles aux prix."195        actions={<RefreshButton state={state} />}196      />197      <Note tone="warn" title="Visibilité des noms.">198        Sans code d'accès sur la compétition, la liste des noms est visible par quiconque ouvre le site. Avec un code d'accès, elle n'apparaît qu'après la saisie du code.199      </Note>200      <LoadState state={state} label="Chargement des listes de classe…">201        {(data) => (202          <>203            {COURSES.map((course) => <CourseRoster key={course} course={course} entries={data[course] ?? []} onSaved={() => void state.reload()} />)}204          </>205        )}206      </LoadState>207    </div>208  );209}210
Files main
Menu

Theme