SPB Git

Repository Public

dashboard.tsx 19.1 KB 254 lines tsx

1"use client";2import Link from "next/link";3import { useRouter } from "next/navigation";4import { useRef, useState, type ReactNode } from "react";5import { useLocale } from "@/i18n/client";6import { dict, fill, formatDateTime } from "@/i18n/dict";7import { api } from "@/lib/client-api";8import { Dialog, money, Notice, PageHeader, Spinner, StatusPill, useApi } from "@/components/admin/ui";9import type { dashboard } from "@/server/misc";10import type { listSheets } from "@/server/sheets";11import { apiMessage, formatNumber, Loading, Pager, Segments, useDebounced } from "./common";1213type Dash = Awaited<ReturnType<typeof dashboard>>;14type SheetList = Awaited<ReturnType<typeof listSheets>>;15type StatusFilter = "all" | "draft" | "in_review" | "published" | "archived";16interface ImportInfo { ok: boolean; title: string; blocks: number; locale: string }1718const T = dict({19  title: ["Tableau de bord", "Dashboard"], lead: ["L’état du site, du studio et de vos fiches.", "The state of the site, the studio and your sheets."],20  newSheet: ["Nouvelle fiche", "New sheet"], importJson: ["Importer un JSON", "Import a JSON"], loading: ["Chargement…", "Loading…"], retry: ["Réessayer", "Retry"],21  counts: ["Contenu", "Content"], drafts: ["Brouillons", "Drafts"], inReview: ["En révision", "In review"], published: ["Publiées", "Published"], archived: ["Archivées", "Archived"],22  revisions: ["Révisions", "Revisions"], topics: ["Thèmes", "Topics"], media: ["Médias", "Media"], views7: ["Vues, 7 jours", "Views, 7 days"], views30: ["Vues, 30 jours", "Views, 30 days"],23  analyticsOff: ["La mesure d’audience est désactivée : aucune vue n’est comptée. Elle s’active dans les réglages.", "Analytics is off: no view is counted. Turn it on in the settings."],24  topViewed: ["Les plus consultées, 30 jours", "Most viewed, 30 days"], noViews: ["Aucune vue enregistrée sur 30 jours.", "No view recorded in 30 days."], viewsN: ["{n} vues", "{n} views"],25  health: ["État des services", "Service health"], database: ["Base de données", "Database"], claude: ["API Claude", "Claude API"], queue: ["File de tâches", "Job queue"], storage: ["Stockage", "Storage"], antivirus: ["Antivirus", "Antivirus"],26  ok: ["Opérationnel", "Operational"], down: ["En panne", "Failing"], notConfigured: ["Non configuré", "Not configured"], model: ["Modèle : {m}", "Model: {m}"],27  queueLine: ["{q} en file, {r} en cours, {f} échec(s) en 24 h, {e} export(s) en attente.", "{q} queued, {r} running, {f} failed in 24 h, {e} export(s) pending."],28  workerAlive: ["Worker actif, vu il y a {s} s.", "Worker alive, seen {s} s ago."], workerDead: ["Worker arrêté : dernier signe de vie il y a {s} s. Les tâches ne sont pas traitées.", "Worker stopped: last seen {s} s ago. Jobs are not being processed."],29  workerNever: ["Le worker n’a jamais démarré : les tâches ne sont pas traitées.", "The worker has never started: jobs are not being processed."], oldest: ["Plus ancienne tâche en file : {d}.", "Oldest queued job: {d}."],30  spend: ["Dépenses IA", "AI spend"], today: ["Aujourd’hui", "Today"], month: ["Ce mois-ci", "This month"], of: ["sur {b}", "of {b}"], noLimit: ["aucune limite", "no limit"], budgetReached: ["Budget atteint : les nouvelles tâches IA sont refusées.", "Budget reached: new AI jobs are refused."],31  sheets: ["Fiches", "Sheets"], search: ["Rechercher une fiche", "Search sheets"], searchPh: ["Titre ou adresse…", "Title or slug…"], filter: ["Filtrer par statut", "Filter by status"], all: ["Toutes", "All"],32  draft: ["Brouillons", "Drafts"], unpublished: ["Modifications non publiées", "Unpublished changes"], updated: ["Modifiée le {d}", "Updated {d}"], edit: ["Modifier", "Edit"], view: ["Voir la page publique", "View public page"],33  empty: ["Aucune fiche pour l’instant.", "No sheet yet."], emptyLead: ["Créez votre première fiche, partez d’un modèle ou importez un fichier JSON exporté.", "Create your first sheet, start from a template or import an exported JSON file."],34  noMatch: ["Aucune fiche ne correspond à cette recherche.", "No sheet matches this search."], templates: ["Parcourir les modèles", "Browse templates"], revN: ["{n} révision(s)", "{n} revision(s)"], featured: ["À la une", "Featured"],35  importTitle: ["Importer une fiche", "Import a sheet"], importReading: ["Vérification du fichier…", "Checking the file…"], importBadJson: ["Ce fichier n’est pas un JSON valide.", "This file is not valid JSON."],36  importTooBig: ["Fichier trop volumineux (2 Mo au maximum).", "File too large (2 MB at most)."], importValid: ["Document valide.", "Valid document."], importFile: ["Fichier", "File"], importSheetTitle: ["Titre", "Title"],37  importBlocks: ["Blocs", "Blocks"], importLang: ["Langue", "Language"], importNote: ["La fiche est créée comme brouillon. Les images ne voyagent pas avec le fichier : les blocs image sont retirés à l’import.", "The sheet is created as a draft. Images do not travel with the file: image blocks are removed on import."],38  importGo: ["Créer la fiche", "Create the sheet"], cancel: ["Annuler", "Cancel"], close: ["Fermer", "Close"],39});4041function Stat({ label, value }: { label: string; value: string }) {42  return <div className="card px-4 py-3"><dt className="eyebrow">{label}</dt><dd className="mt-1 font-display text-3xl font-semibold tabular-nums">{value}</dd></div>;43}4445function Health({ name, state, labels, children }: { name: string; state: "ok" | "bad" | "off"; labels: { ok: string; down: string; notConfigured: string }; children: ReactNode }) {46  const tone = state === "ok" ? "text-ok border-ok/40" : state === "bad" ? "text-bad border-bad/40" : "text-warn border-warn/40";47  return (48    <li className="card p-4">49      <div className="flex flex-wrap items-center justify-between gap-2">50        <h3 className="font-semibold">{name}</h3>51        <span className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold ${tone}`}>{state === "ok" ? labels.ok : state === "bad" ? labels.down : labels.notConfigured}</span>52      </div>53      <div className="mt-2 space-y-1 break-words text-sm leading-relaxed text-muted">{children}</div>54    </li>55  );56}5758function Budget({ label, spent, budget, t }: { label: string; spent: number; budget: number; t: { of: string; noLimit: string; budgetReached: string } }) {59  const pct = budget > 0 ? Math.min(100, (spent / budget) * 100) : 0, reached = budget > 0 && spent >= budget;60  return (61    <div className="card p-4">62      <h3 className="eyebrow">{label}</h3>63      <p className="mt-1"><span className="font-display text-3xl font-semibold tabular-nums">{money(spent)}</span> <span className="text-sm text-muted">{budget > 0 ? fill(t.of, { b: money(budget) }) : `(${t.noLimit})`}</span></p>64      {budget > 0 && <div className="mt-3 h-2 overflow-hidden rounded-full bg-raised" role="progressbar" aria-label={label} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(pct)}><div className={`h-full rounded-full ${reached ? "bg-bad" : pct > 80 ? "bg-warn" : "bg-accent"}`} style={{ width: `${pct}%` }} /></div>}65      {reached && <p className="mt-2 text-sm text-bad">{t.budgetReached}</p>}66    </div>67  );68}6970const PAGE = 20;7172export function DashboardPage() {73  const locale = useLocale(), fr = locale === "fr", t = T(locale), router = useRouter();74  const dash = useApi<Dash>("/api/admin/dashboard");75  const [q, setQ] = useState(""), [status, setStatus] = useState<StatusFilter>("all"), [offset, setOffset] = useState(0);76  const dq = useDebounced(q.trim());77  const listPath = `/api/admin/sheets?limit=${PAGE}&offset=${offset}${status !== "all" ? `&status=${status}` : ""}${dq ? `&q=${encodeURIComponent(dq)}` : ""}`;78  const list = useApi<SheetList>(listPath);7980  const fileRef = useRef<HTMLInputElement>(null);81  const [imp, setImp] = useState<{ name: string; doc: unknown; info: ImportInfo | null } | null>(null);82  const [impOpen, setImpOpen] = useState(false), [impBusy, setImpBusy] = useState(false), [impError, setImpError] = useState<string | null>(null);8384  const pickFile = async (file: File | undefined) => {85    if (fileRef.current) fileRef.current.value = "";86    if (!file) return;87    setImp({ name: file.name, doc: null, info: null }); setImpError(null); setImpOpen(true); setImpBusy(true);88    try {89      if (file.size > 2_000_000) { setImpError(t.importTooBig); return; }90      let doc: unknown;91      try { doc = JSON.parse(await file.text()); } catch { setImpError(t.importBadJson); return; }92      const info = await api<ImportInfo>("/api/admin/validate", { body: { doc } });93      setImp({ name: file.name, doc, info });94    } catch (e) { setImpError(apiMessage(e, fr)); } finally { setImpBusy(false); }95  };96  const doImport = async () => {97    if (!imp?.info) return;98    setImpBusy(true); setImpError(null);99    try { const r = await api<{ id: string }>("/api/admin/sheets", { body: { doc: imp.doc } }); router.push(`/admin/sheets/${r.id}/edit`); }100    catch (e) { setImpError(apiMessage(e, fr)); setImpBusy(false); }101  };102103  const d = dash.data, h = d?.health;104  const filtering = status !== "all" || dq !== "";105  const statuses = [["all", t.all], ["draft", t.draft], ["in_review", t.inReview], ["published", t.published], ["archived", t.archived]] as const;106107  return (108    <>109      <PageHeader title={t.title} lead={t.lead} actions={<>110        <Link href="/admin/sheets/new" className="btn btn-primary">{t.newSheet}</Link>111        <button type="button" className="btn" onClick={() => fileRef.current?.click()}>{t.importJson}</button>112        <input ref={fileRef} type="file" accept="application/json,.json" className="sr-only" tabIndex={-1} aria-label={t.importJson} onChange={(e) => { void pickFile(e.target.files?.[0]); }} />113      </>} />114115      <div aria-live="polite">116        {dash.loading && !d && <Loading label={t.loading} />}117        {dash.error && <Notice tone="bad">{dash.error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void dash.reload(); }}>{t.retry}</button></Notice>}118      </div>119120      {d && h && (121        <>122          <section aria-labelledby="dash-counts">123            <h2 id="dash-counts" className="sr-only">{t.counts}</h2>124            <dl className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">125              <Stat label={t.drafts} value={formatNumber(d.counts.drafts, fr)} />126              <Stat label={t.inReview} value={formatNumber(d.counts.inReview, fr)} />127              <Stat label={t.published} value={formatNumber(d.counts.published, fr)} />128              <Stat label={t.archived} value={formatNumber(d.counts.archived, fr)} />129              <Stat label={t.revisions} value={formatNumber(d.counts.revisions, fr)} />130              <Stat label={t.topics} value={formatNumber(d.counts.topics, fr)} />131              <Stat label={t.media} value={formatNumber(d.counts.assets, fr)} />132              {d.views && <><Stat label={t.views7} value={formatNumber(d.views.last7Days, fr)} /><Stat label={t.views30} value={formatNumber(d.views.last30Days, fr)} /></>}133            </dl>134            {!d.views && <div className="mt-3"><Notice>{t.analyticsOff} <Link href="/admin/settings" className="font-semibold text-accent underline">{fr ? "Réglages" : "Settings"}</Link></Notice></div>}135            {d.views && (136              <div className="card mt-3 p-4">137                <h3 className="eyebrow">{t.topViewed}</h3>138                {d.views.top.length === 0 ? <p className="mt-2 text-sm text-muted">{t.noViews}</p> : (139                  <ol className="mt-2 divide-y divide-line">140                    {d.views.top.map((s) => (141                      <li key={s.id} className="flex min-h-11 items-center justify-between gap-3">142                        <Link href={`/admin/sheets/${s.id}/edit`} className="min-w-0 truncate py-2 font-medium">{s.title}</Link>143                        <span className="shrink-0 text-sm tabular-nums text-muted">{fill(t.viewsN, { n: formatNumber(s.views, fr) })}</span>144                      </li>145                    ))}146                  </ol>147                )}148              </div>149            )}150          </section>151152          <section aria-labelledby="dash-health" className="mt-8">153            <h2 id="dash-health" className="font-display text-2xl font-semibold">{t.health}</h2>154            <ul className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">155              <Health name={t.database} state={h.database.ok ? "ok" : "bad"} labels={t}><p>{h.database.detail}</p></Health>156              <Health name={t.claude} state={!h.ai.configured ? "off" : h.ai.ok ? "ok" : "bad"} labels={t}>157                {h.ai.model && <p>{fill(t.model, { m: "" })}<code className="font-mono text-[0.8125rem] text-ink">{h.ai.model}</code></p>}158                {(!h.ai.ok || !h.ai.model) && <p>{h.ai.detail}</p>}159              </Health>160              <Health name={t.queue} state={h.queue.workerAlive ? "ok" : "bad"} labels={t}>161                <p>{fill(t.queueLine, { q: h.queue.queued, r: h.queue.running, f: h.queue.failed24h, e: h.queue.exportsPending })}</p>162                <p className={h.queue.workerAlive ? undefined : "text-bad"}>{h.queue.workerSeenSecondsAgo === null ? t.workerNever : fill(h.queue.workerAlive ? t.workerAlive : t.workerDead, { s: formatNumber(h.queue.workerSeenSecondsAgo, fr) })}</p>163                {h.queue.oldestQueuedAt && <p>{fill(t.oldest, { d: formatDateTime(h.queue.oldestQueuedAt, locale) })}</p>}164              </Health>165              <Health name={t.storage} state={h.storage.ok ? "ok" : "bad"} labels={t}><p>{h.storage.detail}</p></Health>166              <Health name={t.antivirus} state={!h.scanner.configured ? "off" : h.scanner.ok ? "ok" : "bad"} labels={t}><p>{h.scanner.detail}</p></Health>167            </ul>168          </section>169170          <section aria-labelledby="dash-spend" className="mt-8">171            <h2 id="dash-spend" className="font-display text-2xl font-semibold">{t.spend}</h2>172            <div className="mt-3 grid gap-3 sm:grid-cols-2">173              <Budget label={t.today} spent={d.spend.todayUsd} budget={d.spend.dailyBudgetUsd} t={t} />174              <Budget label={t.month} spent={d.spend.monthUsd} budget={d.spend.monthlyBudgetUsd} t={t} />175            </div>176          </section>177        </>178      )}179180      <section aria-labelledby="dash-sheets" className="mt-10">181        <h2 id="dash-sheets" className="font-display text-2xl font-semibold">{t.sheets}</h2>182        <div className="mt-3 grid gap-2">183          <label className="grid gap-1 text-sm font-medium" htmlFor="sheet-q">{t.search}184            <input id="sheet-q" type="search" inputMode="search" autoComplete="off" enterKeyHint="search" className="field" placeholder={t.searchPh} value={q} maxLength={120} onChange={(e) => { setQ(e.target.value); setOffset(0); }} />185          </label>186          <Segments label={t.filter} options={statuses} value={status} onChange={(v) => { setStatus(v); setOffset(0); }} />187        </div>188        <div aria-live="polite" aria-busy={list.loading} className="mt-3">189          {list.error && <Notice tone="bad">{list.error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void list.reload(); }}>{t.retry}</button></Notice>}190          {list.loading && !list.data && <Loading label={t.loading} />}191          {list.data && list.data.items.length === 0 && (filtering ? <p className="py-6 text-muted">{t.noMatch}</p> : (192            <div className="card grid justify-items-start gap-3 p-6">193              <p className="font-display text-xl font-semibold">{t.empty}</p>194              <p className="text-muted">{t.emptyLead}</p>195              <div className="flex flex-wrap gap-2">196                <Link href="/admin/sheets/new" className="btn btn-primary">{t.newSheet}</Link>197                <Link href="/admin/templates" className="btn">{t.templates}</Link>198                <button type="button" className="btn" onClick={() => fileRef.current?.click()}>{t.importJson}</button>199              </div>200            </div>201          ))}202          {list.data && list.data.items.length > 0 && (203            <ul className={`grid gap-3 ${list.loading ? "opacity-60" : ""}`}>204              {list.data.items.map((s) => (205                <li key={s.id} className="card p-4">206                  <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2">207                    <h3 className="min-w-0 break-words font-display text-lg font-semibold leading-snug"><Link href={`/admin/sheets/${s.id}/edit`}>{s.title}</Link></h3>208                    <div className="flex flex-wrap items-center gap-2">209                      <StatusPill status={s.status} fr={fr} />210                      <span className="rounded-full border border-line px-2.5 py-0.5 font-mono text-xs font-semibold uppercase text-muted" lang={s.locale}>{s.locale}</span>211                      {s.featured && <span className="rounded-full border border-line px-2.5 py-0.5 text-xs font-semibold text-muted">{t.featured}</span>}212                    </div>213                  </div>214                  {s.hasUnpublishedChanges && <p className="mt-2 text-sm font-semibold text-warn">● {t.unpublished}</p>}215                  <p className="mt-2 text-sm text-muted">{fill(t.updated, { d: formatDateTime(s.updatedAt, locale) })} · {fill(t.revN, { n: s.revisions })}</p>216                  <p className="mt-0.5 break-all font-mono text-xs text-faint">/s/{s.slug}</p>217                  <div className="mt-3 flex flex-wrap gap-2">218                    <Link href={`/admin/sheets/${s.id}/edit`} className="btn">{t.edit}</Link>219                    {s.status === "published" && <a href={`/s/${s.slug}`} className="btn btn-ghost" target="_blank" rel="noopener">{t.view} ↗</a>}220                  </div>221                </li>222              ))}223            </ul>224          )}225          {list.data && <Pager total={list.data.total} limit={PAGE} offset={offset} onChange={setOffset} fr={fr} />}226        </div>227      </section>228229      <Dialog open={impOpen} onClose={() => { if (!impBusy) setImpOpen(false); }} title={t.importTitle}>230        <div aria-live="polite">231          {imp && <p className="break-all text-sm text-muted">{t.importFile} : <span className="font-mono text-ink">{imp.name}</span></p>}232          {impBusy && !imp?.info && <Loading label={t.importReading} />}233          {imp?.info && (234            <>235              <div className="mt-3"><Notice tone="ok">{t.importValid}</Notice></div>236              <dl className="mt-3 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[0.9375rem]">237                <dt className="text-muted">{t.importSheetTitle}</dt><dd className="break-words font-semibold">{imp.info.title}</dd>238                <dt className="text-muted">{t.importBlocks}</dt><dd className="tabular-nums">{imp.info.blocks}</dd>239                <dt className="text-muted">{t.importLang}</dt><dd className="uppercase">{imp.info.locale}</dd>240              </dl>241              <p className="mt-3 text-sm text-muted">{t.importNote}</p>242            </>243          )}244          {impError && <div className="mt-3"><Notice tone="bad">{impError}</Notice></div>}245        </div>246        <div className="mt-5 flex flex-wrap justify-end gap-2">247          <button type="button" className="btn" onClick={() => setImpOpen(false)} disabled={impBusy}>{imp?.info ? t.cancel : t.close}</button>248          {imp?.info && <button type="button" className="btn btn-primary" onClick={() => { void doImport(); }} disabled={impBusy}>{impBusy && <Spinner />}{t.importGo}</button>}249        </div>250      </Dialog>251    </>252  );253}254
Files main
Menu

Theme