SPB Git

Repository Public

Data.tsx 12.2 KB 234 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/Data.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, useRef, useState } from "react";44import { formatInt } from "@jeux/engine/format";45import { IconCheck, IconCross } from "../components/Icons";46import { REJECTION_LABEL, SYNC_STATUS, adminApi, categoryLabel, formatAgo, formatDateTime, formatDuration, useLoad, type DashboardData, type SyncJob } from "./lib";47import { ActionDialog, Empty, Figures, LoadState, Note, PageHead, RefreshButton, Section, TableScroll, TallyBars, useNotify, type Ask } from "./ui";4849interface SyncData {50  running: boolean;51  jobs: SyncJob[];52}5354function JobStatus({ job }: { job: SyncJob }) {55  if (job.status === "running") return <span className="adm-state is-run"><span className="adm-dot" aria-hidden="true" />{SYNC_STATUS.running}</span>;56  if (job.status === "success") return <span className="adm-state is-ok"><IconCheck size={16} />{SYNC_STATUS.success}</span>;57  return <span className="adm-state is-bad"><IconCross size={16} />{SYNC_STATUS.failed}</span>;58}5960function jobDuration(job: SyncJob): string {61  if (job.stats?.durationMs !== undefined) return formatDuration(job.stats.durationMs / 1000);62  if (job.finished_at) return formatDuration((new Date(job.finished_at).getTime() - new Date(job.started_at).getTime()) / 1000);63  return "—";64}6566export default function DataPage() {67  const notify = useNotify();68  const [watch, setWatch] = useState(false);69  const state = useLoad<SyncData>("/sync", watch ? 3000 : undefined);70  const dashboard = useLoad<DashboardData>("/dashboard");71  const [ask, setAsk] = useState<Ask | null>(null);72  const running = state.data?.running ?? false;73  const wasRunning = useRef(false);74  const reloadDashboard = dashboard.reload;7576  useEffect(() => {77    setWatch(running);78    if (wasRunning.current && !running) {79      notify("Synchronisation terminée.");80      void reloadDashboard();81    }82    wasRunning.current = running;83  }, [running, notify, reloadDashboard]);8485  const launch = (): void =>86    setAsk({87      title: "Lancer une synchronisation ?",88      body: (89        <>90          <p>La base d'inscriptions immobilières sera relue en entier (lecture seule), puis les propriétés seront normalisées, dédoublonnées et filtrées. L'opération dure de quelques secondes à quelques minutes.</p>91          <p>Le bassin de propriétés admissibles sera mis à jour. <strong>Les compétitions déjà générées ne changent pas</strong> : leurs questions sont figées dans leur banque.</p>92        </>93      ),94      confirmLabel: "Lancer la synchronisation",95      run: async () => {96        await adminApi("/sync", { method: "POST", body: {} });97        setWatch(true);98        return "Synchronisation lancée. Le suivi s'actualise toutes les 3 secondes.";99      },100    });101102  const source = dashboard.data?.sync.sourceAvailable;103  const pool = dashboard.data?.pool;104105  return (106    <div className="adm-page">107      <PageHead108        title="Données"109        lede="Synchronisation du bassin de propriétés à partir de la base d'inscriptions immobilières. La source n'est jamais modifiée."110        actions={<RefreshButton state={state} />}111      />112      <LoadState state={state} label="Chargement de l'état des données…">113        {(d) => {114          const last = d.jobs[0] ?? null;115          const lastOk = d.jobs.find((j) => j.status === "success") ?? null;116          const stats = lastOk?.stats ?? null;117          const rejections = Object.entries(stats?.rejections ?? {}).map(([reason, n]) => ({ label: REJECTION_LABEL[reason] ?? reason, n })).sort((a, b) => b.n - a.n);118          const categories = Object.entries(stats?.byCategory ?? {}).map(([key, n]) => ({ label: categoryLabel(key), n })).sort((a, b) => b.n - a.n);119          return (120            <>121              <Section title="État de la source">122                <div className="adm-cols adm-cols-wide-left">123                  <dl className="adm-dl">124                    <div>125                      <dt>Source de données</dt>126                      <dd>127                        {source === undefined ? (128                          <span className="muted">Vérification…</span>129                        ) : source ? (130                          <span className="adm-state is-ok"><IconCheck size={16} />Accessible</span>131                        ) : (132                          <span className="adm-state is-bad"><IconCross size={16} />Inaccessible : la synchronisation échouera</span>133                        )}134                      </dd>135                    </div>136                    <div>137                      <dt>Synchronisation</dt>138                      <dd role="status" aria-live="polite">139                        {d.running ? <span className="adm-state is-run"><span className="adm-dot" aria-hidden="true" />En cours{last?.status === "running" ? ` depuis ${formatDuration((Date.now() - new Date(last.started_at).getTime()) / 1000)}` : ""}</span> : "Au repos"}140                      </dd>141                    </div>142                    <div><dt>Dernière tâche</dt><dd>{last ? <><JobStatus job={last} /> <span className="muted">· {formatDateTime(last.started_at)} ({formatAgo(last.started_at)})</span></> : "Aucune"}</dd></div>143                    {pool && <div><dt>Bassin actuel</dt><dd>{formatInt(pool.total)} propriétés disponibles, dont {formatInt(pool.eligible)} admissibles</dd></div>}144                  </dl>145                  <div className="adm-launch">146                    <button type="button" className="btn btn-dark" onClick={launch} disabled={d.running || source === false}>147                      {d.running ? "Synchronisation en cours…" : "Lancer une synchronisation"}148                    </button>149                    <p className="small muted">Une seule synchronisation à la fois. Chaque lancement est consigné au journal.</p>150                  </div>151                </div>152                {last?.status === "failed" && <Note tone="error" title="La dernière synchronisation a échoué.">{last.error ?? "Aucun détail fourni."} Le bassin précédent reste en place.</Note>}153              </Section>154155              {stats && lastOk && (156                <Section title="Dernière synchronisation réussie" note={`${formatDateTime(lastOk.started_at)} · durée ${jobDuration(lastOk)}`}>157                  <Figures158                    label="Bilan de la dernière synchronisation réussie"159                    items={[160                      { label: "Inscriptions lues", value: formatInt(stats.scanned ?? 0), note: "dans la source" },161                      { label: "Normalisées", value: formatInt(stats.normalized ?? 0), note: "fiches exploitables" },162                      { label: "Doublons écartés", value: formatInt(stats.deduplicated ?? 0), note: "même propriété, plusieurs fiches" },163                      { label: "Admissibles", value: formatInt(stats.eligible ?? 0), note: `${formatInt(stats.deactivated ?? 0)} retirées du bassin` },164                    ]}165                  />166                  <div className="adm-cols">167                    <div>168                      <h3 className="adm-h3">Rejets par motif</h3>169                      <TallyBars rows={rejections} label="Rejets par motif" />170                    </div>171                    <div>172                      <h3 className="adm-h3">Propriétés admissibles par catégorie</h3>173                      <TallyBars rows={categories} label="Propriétés admissibles par catégorie" />174                    </div>175                  </div>176                </Section>177              )}178179              <Section title="Historique des tâches" note="Les quinze dernières synchronisations.">180                {d.jobs.length === 0 ? (181                  <Empty title="Aucune synchronisation enregistrée"><p>Lancez une première synchronisation pour constituer le bassin de propriétés.</p></Empty>182                ) : (183                  <TableScroll label="Historique des synchronisations">184                    <table className="table adm-table">185                      <caption className="sr-only">Synchronisations, de la plus récente à la plus ancienne</caption>186                      <thead>187                        <tr>188                          <th scope="col" className="right">N°</th>189                          <th scope="col">Début</th>190                          <th scope="col">État</th>191                          <th scope="col" className="right">Durée</th>192                          <th scope="col" className="right">Lues</th>193                          <th scope="col" className="right">Normalisées</th>194                          <th scope="col" className="right">Doublons</th>195                          <th scope="col" className="right">Admissibles</th>196                          <th scope="col" className="right">Rejets</th>197                          <th scope="col">Principal motif de rejet</th>198                        </tr>199                      </thead>200                      <tbody>201                        {d.jobs.map((job) => {202                          const s = job.stats;203                          const rej = Object.entries(s?.rejections ?? {}).sort((a, b) => b[1] - a[1]);204                          const totalRej = rej.reduce((acc, [, n]) => acc + n, 0);205                          const num = (v: number | undefined): string => (v === undefined ? "—" : formatInt(v));206                          return (207                            <tr key={job.id}>208                              <td className="right">{job.id}</td>209                              <th scope="row">{formatDateTime(job.started_at)}</th>210                              <td><JobStatus job={job} />{job.error && <span className="small error-text"><br />{job.error}</span>}</td>211                              <td className="right">{job.status === "running" ? "…" : jobDuration(job)}</td>212                              <td className="right">{num(s?.scanned)}</td>213                              <td className="right">{num(s?.normalized)}</td>214                              <td className="right">{num(s?.deduplicated)}</td>215                              <td className="right">{num(s?.eligible)}</td>216                              <td className="right">{s ? formatInt(totalRej) : "—"}</td>217                              <td className="small">{rej[0] ? `${REJECTION_LABEL[rej[0][0]] ?? rej[0][0]} (${formatInt(rej[0][1])})` : "—"}</td>218                            </tr>219                          );220                        })}221                      </tbody>222                    </table>223                  </TableScroll>224                )}225              </Section>226            </>227          );228        }}229      </LoadState>230      {ask && <ActionDialog ask={ask} onClose={() => setAsk(null)} onDone={() => void state.reload()} />}231    </div>232  );233}234
Files main
Menu

Theme