SPB Git

Repository Public

settings.tsx 37.1 KB 450 lines tsx

1"use client";2import { useEffect, useState, type FormEvent, type ReactNode } from "react";3import { TONES } from "@/schema";4import { useLocale } from "@/i18n/client";5import { dict, fill, formatDateTime } from "@/i18n/dict";6import { api } from "@/lib/client-api";7import { Dialog, Notice, PageHeader, Spinner, useApi } from "@/components/admin/ui";8import { deviceName, enrol, withReauth } from "@/components/admin/passkey";9import type { listPasskeys, listSessions } from "@/lib/auth";10import type { Settings } from "@/server/settings";11import { apiMessage, authMessage, Confirm, CopyButton, Loading, validationDetails } from "./common";1213type Passkey = Awaited<ReturnType<typeof listPasskeys>>[number];14type Session = Awaited<ReturnType<typeof listSessions>>[number];15interface PasskeyData { passkeys: Passkey[]; recoveryCodesLeft: number; sessions: Session[] }16interface Model { id: string; name: string; maxOutputTokens: number | null; contextTokens: number | null; priceKnown: boolean; price: { input: number; output: number; cacheRead?: number } }17interface SettingsData {18  settings: Settings; models: Model[]; modelsError: string | null;19  environment: { anthropicKeySet: boolean; defaultModel: string; rpId: string; appUrl: string; storageDriver: string; clamdConfigured: boolean; backupDirSet: boolean; maxUploadMb: number };20}21/** As the API returns it: the columns of the table (the PATCH route takes camelCase). */22interface Topic { id: string; slug: string; name_fr: string; name_en: string; description_fr: string; description_en: string; tone: string; position: number; sheets: number }23type Flash = { tone: "ok" | "bad"; text: string } | null;2425const T = dict({26  title: ["Réglages", "Settings"], lead: ["Accès au studio, génération par Claude, site et thèmes.", "Studio access, Claude generation, site and topics."],27  loading: ["Chargement…", "Loading…"], retry: ["Réessayer", "Retry"], save: ["Enregistrer", "Save"], cancel: ["Annuler", "Cancel"], saved: ["Réglages enregistrés.", "Settings saved."], nothing: ["Aucune modification à enregistrer.", "No change to save."],28  yes: ["Oui", "Yes"], no: ["Non", "No"], close: ["Fermer", "Close"],29  // Passkeys30  pkTitle: ["Clés d’accès", "Passkeys"], pkLead: ["Le studio s’ouvre uniquement avec une clé d’accès (Face ID, Touch ID, clé de sécurité). Les opérations sensibles redemandent une vérification.", "The studio opens only with a passkey (Face ID, Touch ID, security key). Sensitive operations ask for a fresh verification."],31  synced: ["Synchronisée (trousseau)", "Synced (keychain)"], bound: ["Liée à l’appareil", "Device-bound"], multiNotSynced: ["Synchronisable, non sauvegardée", "Syncable, not backed up"],32  created: ["Créée le {d}", "Created {d}"], lastUsed: ["Dernière utilisation : {d}", "Last used: {d}"], never: ["jamais", "never"],33  rename: ["Renommer", "Rename"], remove: ["Retirer", "Remove"], pkName: ["Nom de la clé", "Passkey name"],34  addTitle: ["Ajouter cet appareil", "Add this device"], addName: ["Nom de cet appareil", "Name of this device"], add: ["Créer une clé d’accès", "Create a passkey"], added: ["Clé d’accès ajoutée.", "Passkey added."],35  renamed: ["Clé renommée.", "Passkey renamed."], removed: ["Clé d’accès retirée.", "Passkey removed."],36  removeTitle: ["Retirer cette clé d’accès ?", "Remove this passkey?"], removeBody: ["« {n} » ne pourra plus ouvrir le studio. Une vérification par clé d’accès vous sera demandée. La dernière clé ne peut pas être retirée.", "“{n}” will no longer open the studio. You will be asked to verify with a passkey. The last passkey cannot be removed."],37  rcTitle: ["Codes de récupération", "Recovery codes"], rcLeft: ["{n} code(s) inutilisé(s) sur 10.", "{n} unused code(s) out of 10."], rcNone: ["Aucun code de récupération utilisable : sans clé d’accès, l’accès ne se rétablit que depuis le serveur.", "No usable recovery code: without a passkey, access can only be restored from the server."],38  rcRegen: ["Régénérer", "Regenerate"], rcConfirmTitle: ["Régénérer les codes ?", "Regenerate the codes?"], rcConfirm: ["Les codes actuels cesseront immédiatement de fonctionner et dix nouveaux codes seront créés. Une vérification par clé d’accès vous sera demandée.", "The current codes stop working immediately and ten new codes are created. You will be asked to verify with a passkey."],39  rcNewTitle: ["Nouveaux codes de récupération", "New recovery codes"], rcWarn: ["Notez-les maintenant et rangez-les hors ligne : ils ne seront plus jamais affichés. Chaque code ne sert qu’une fois ; les anciens codes ne fonctionnent plus.", "Write them down now and keep them offline: they will never be shown again. Each code works once; the old codes no longer work."],40  copy: ["Copier les codes", "Copy the codes"], copied: ["Copié", "Copied"], rcDone: ["Je les ai notés", "I saved them"],41  sessTitle: ["Sessions actives", "Active sessions"], current: ["Cette session", "This session"], revoke: ["Révoquer", "Revoke"], revoked: ["Session révoquée.", "Session revoked."], sessSeen: ["Vue le {d}", "Seen {d}"], sessOpened: ["Ouverte le {d}", "Opened {d}"],42  sessMethod: ["Méthode : {m}", "Method: {m}"], revokeTitle: ["Révoquer cette session ?", "Revoke this session?"], revokeBody: ["L’appareil concerné sera déconnecté immédiatement.", "That device is signed out immediately."], unknownDevice: ["Appareil inconnu", "Unknown device"],43  // Claude44  aiTitle: ["Claude", "Claude"], keySet: ["La clé API Anthropic est configurée sur le serveur.", "The Anthropic API key is configured on the server."],45  keyMissing: ["Aucune clé API Anthropic sur le serveur : la génération et les modifications par IA sont indisponibles.", "No Anthropic API key on the server: AI generation and edits are unavailable."],46  keyWhere: ["La clé est une variable d’environnement (ANTHROPIC_API_KEY) du fichier .env du serveur. Elle n’est jamais affichée ni saisie ici ; après l’avoir modifiée, redémarrez l’application et le worker.", "The key is an environment variable (ANTHROPIC_API_KEY) in the server’s .env file. It is never shown or typed here; after changing it, restart the app and the worker."],47  model: ["Modèle", "Model"], modelDefault: ["Par défaut du serveur ({m})", "Server default ({m})"], modelsError: ["La liste des modèles n’a pas pu être lue : {e}", "The model list could not be read: {e}"], modelGone: ["{m} (absent de la liste actuelle)", "{m} (not in the current list)"],48  price: ["{i} $ US en entrée, {o} $ US en sortie, par million de jetons.", "US$ {i} input, US$ {o} output, per million tokens."], priceUnknown: ["Prix inconnu pour ce modèle : les coûts sont comptés au tarif connu le plus élevé.", "Unknown price for this model: costs are counted at the highest known rate."],49  modelLimits: ["Contexte : {c} jetons ; sortie maximale : {o} jetons.", "Context: {c} tokens; maximum output: {o} tokens."], priceTag: ["{i} / {o} $ par MTok", "${i} / ${o} per MTok"], priceTagUnknown: ["prix inconnu", "price unknown"],50  effortGen: ["Effort, génération", "Effort, generation"], effortEdit: ["Effort, modifications", "Effort, edits"], low: ["Faible", "Low"], medium: ["Moyen", "Medium"], high: ["Élevé", "High"], xhigh: ["Très élevé", "Very high"], max: ["Maximal", "Maximum"],51  maxTokens: ["Jetons de sortie max. par appel", "Max output tokens per call"], maxTokensHelp: ["De 4 000 à 128 000.", "4,000 to 128,000."],52  budgets: ["Budgets (en dollars US ; 0 = aucune limite)", "Budgets (US dollars; 0 = no limit)"], perJob: ["Par tâche", "Per job"], daily: ["Par jour", "Per day"], monthly: ["Par mois", "Per month"],53  jobsHour: ["Tâches par heure", "Jobs per hour"], timeout: ["Durée max. d’une tâche (minutes)", "Job timeout (minutes)"], badNumber: ["« {f} » : nombre invalide.", "“{f}”: invalid number."],54  // Site55  siteTitle: ["Site", "Site"], analytics: ["Mesure d’audience", "Analytics"], analyticsHelp: ["Compte les vues par fiche et par jour. Aucune donnée sur les visiteurs n’est conservée.", "Counts views per sheet and per day. No visitor data is kept."],56  analyticsOn: ["Mesure d’audience activée.", "Analytics turned on."], analyticsOff: ["Mesure d’audience désactivée.", "Analytics turned off."],57  env: ["Environnement (lecture seule, défini dans le .env du serveur)", "Environment (read-only, set in the server’s .env)"], rpId: ["Domaine des clés d’accès (RP ID)", "Passkey domain (RP ID)"], origin: ["Origine du site", "Site origin"], storage: ["Stockage des fichiers", "File storage"],58  av: ["Antivirus (clamd)", "Antivirus (clamd)"], avOn: ["Configuré : les téléversements sont analysés.", "Configured: uploads are scanned."], avOff: ["Non configuré : les téléversements sont conservés sans analyse.", "Not configured: uploads are stored unscanned."],59  backups: ["Dossier de sauvegardes", "Backups directory"], backupsOn: ["Défini.", "Set."], backupsOff: ["Non défini : aucune sauvegarde automatique n’est écrite.", "Not set: no automatic backup is written."], uploadLimit: ["Taille max. d’un téléversement", "Upload size limit"], mb: ["{n} Mo", "{n} MB"],60  // Topics61  tpTitle: ["Thèmes", "Topics"], tpLead: ["Les thèmes classent les fiches sur le site public. Ils se créent depuis l’éditeur d’une fiche.", "Topics classify the sheets on the public site. They are created from a sheet’s editor."], tpEmpty: ["Aucun thème pour l’instant.", "No topic yet."],62  nameFr: ["Nom (français)", "Name (French)"], nameEn: ["Nom (anglais)", "Name (English)"], descFr: ["Description (français)", "Description (French)"], descEn: ["Description (anglais)", "Description (English)"],63  tone: ["Couleur", "Colour"], position: ["Position", "Position"], sheetsN: ["{n} fiche(s)", "{n} sheet(s)"], tpSaved: ["Thème enregistré.", "Topic saved."], tpDelete: ["Supprimer", "Delete"], tpInUse: ["Utilisé par des fiches : ne peut pas être supprimé.", "Used by sheets: cannot be deleted."],64  tpDelTitle: ["Supprimer ce thème ?", "Delete this topic?"], tpDelBody: ["Le thème « {n} » sera supprimé définitivement.", "The topic “{n}” will be deleted for good."], tpDeleted: ["Thème supprimé.", "Topic deleted."],65  neutral: ["Neutre", "Neutral"], blue: ["Bleu", "Blue"], teal: ["Sarcelle", "Teal"], green: ["Vert", "Green"], amber: ["Ambre", "Amber"], red: ["Rouge", "Red"], violet: ["Violet", "Violet"], pink: ["Rose", "Pink"],66});67type Tr = ReturnType<typeof T>;6869const Section = ({ id, title, lead, children }: { id: string; title: string; lead?: string; children: ReactNode }) => (70  <section aria-labelledby={id} className="mt-10 scroll-mt-20">71    <h2 id={id} className="scroll-mt-20 font-display text-2xl font-semibold">{title}</h2>72    {lead && <p className="mt-1 max-w-[70ch] text-muted">{lead}</p>}73    <div className="mt-4 grid gap-4">{children}</div>74  </section>75);76const FlashLine = ({ flash }: { flash: Flash }) => <div aria-live="polite">{flash && <Notice tone={flash.tone}>{flash.text}</Notice>}</div>;77const Retry = ({ error, reload, label }: { error: string; reload: () => Promise<void>; label: string }) => <Notice tone="bad">{error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void reload(); }}>{label}</button></Notice>;7879// ── Passkeys, recovery codes, sessions ──────────────────────────────────────────────────────────────8081function PasskeySection({ t }: { t: Tr }) {82  const locale = useLocale(), fr = locale === "fr";83  const { data, error, loading, reload } = useApi<PasskeyData>("/api/auth/passkeys");84  const [flash, setFlash] = useState<Flash>(null), [busy, setBusy] = useState<string | null>(null);85  const [newName, setNewName] = useState("Passkey");86  const [renaming, setRenaming] = useState<{ id: string; name: string } | null>(null);87  const [confirm, setConfirm] = useState<{ kind: "passkey"; item: Passkey } | { kind: "session"; item: Session } | { kind: "codes" } | null>(null), [confirmError, setConfirmError] = useState<string | null>(null);88  const [codes, setCodes] = useState<string[] | null>(null);89  useEffect(() => { setNewName(deviceName()); }, []);9091  const run = async (key: string, action: () => Promise<void>, done: string) => {92    setBusy(key); setFlash(null);93    try { await action(); setFlash({ tone: "ok", text: done }); await reload(); } catch (e) { setFlash({ tone: "bad", text: authMessage(e, fr) }); }94    setBusy(null);95  };96  const add = (ev: FormEvent) => {97    ev.preventDefault();98    void run("add", async () => { const r = await withReauth(() => enrol({ name: newName.trim() || deviceName() })); if (r.recoveryCodes) setCodes(r.recoveryCodes); }, t.added);99  };100  const rename = (ev: FormEvent) => {101    ev.preventDefault();102    if (!renaming) return;103    const { id, name } = renaming;104    void run(`rename:${id}`, async () => { await api(`/api/auth/passkeys/${id}`, { method: "PATCH", body: { name: name.trim() } }); setRenaming(null); }, t.renamed);105  };106  const confirmed = async () => {107    if (!confirm) return;108    setBusy("confirm"); setConfirmError(null);109    try {110      if (confirm.kind === "passkey") { await withReauth(() => api(`/api/auth/passkeys/${confirm.item.id}`, { method: "DELETE" })); setFlash({ tone: "ok", text: t.removed }); }111      else if (confirm.kind === "session") { await api(`/api/auth/sessions/${confirm.item.id}`, { method: "DELETE" }); setFlash({ tone: "ok", text: t.revoked }); }112      else { const r = await withReauth(() => api<{ recoveryCodes: string[] }>("/api/auth/recovery-codes", { method: "POST", body: {} })); setCodes(r.recoveryCodes); setFlash(null); }113      setConfirm(null); await reload();114    } catch (e) { setConfirmError(authMessage(e, fr)); }115    setBusy(null);116  };117  const kindOf = (p: Passkey) => (p.backedUp ? t.synced : p.deviceType === "multiDevice" ? t.multiNotSynced : t.bound);118  const device = (ua: string) => {119    const os = /iPhone/.test(ua) ? "iPhone" : /iPad/.test(ua) ? "iPad" : /Android/.test(ua) ? "Android" : /Macintosh/.test(ua) ? "Mac" : /Windows/.test(ua) ? "Windows" : /Linux/.test(ua) ? "Linux" : "";120    const browser = /Edg\//.test(ua) ? "Edge" : /Firefox\//.test(ua) ? "Firefox" : /Chrome\//.test(ua) ? "Chrome" : /Safari\//.test(ua) ? "Safari" : "";121    return [browser, os].filter(Boolean).join(" · ") || ua.slice(0, 60) || t.unknownDevice;122  };123124  return (125    <Section id="set-pk" title={t.pkTitle} lead={t.pkLead}>126      <FlashLine flash={flash} />127      {loading && !data && <Loading label={t.loading} />}128      {error && <Retry error={error} reload={reload} label={t.retry} />}129      {data && (130        <>131          <ul className="grid gap-3">132            {data.passkeys.map((p) => (133              <li key={p.id} className="card p-4">134                {renaming?.id === p.id ? (135                  <form onSubmit={rename} className="grid gap-3 sm:grid-cols-[1fr_auto_auto] sm:items-end">136                    <label className="grid gap-1 text-sm font-medium" htmlFor={`pk-${p.id}`}>{t.pkName}137                      <input id={`pk-${p.id}`} className="field" value={renaming.name} maxLength={60} required autoComplete="off" autoFocus onChange={(e) => setRenaming({ id: p.id, name: e.target.value })} /></label>138                    <button className="btn btn-primary" disabled={busy !== null || !renaming.name.trim()}>{busy === `rename:${p.id}` && <Spinner />}{t.save}</button>139                    <button type="button" className="btn" onClick={() => setRenaming(null)} disabled={busy !== null}>{t.cancel}</button>140                  </form>141                ) : (142                  <div className="flex flex-wrap items-start justify-between gap-3">143                    <div className="min-w-0">144                      <h3 className="break-words font-semibold">{p.name}</h3>145                      <p className="mt-0.5 text-sm text-muted">{kindOf(p)}</p>146                      <p className="mt-0.5 text-sm text-faint">{fill(t.created, { d: formatDateTime(p.createdAt, locale) })} · {fill(t.lastUsed, { d: p.lastUsedAt ? formatDateTime(p.lastUsedAt, locale) : t.never })}</p>147                    </div>148                    <div className="flex flex-wrap gap-2">149                      <button type="button" className="btn" onClick={() => setRenaming({ id: p.id, name: p.name })} disabled={busy !== null}>{t.rename}</button>150                      <button type="button" className="btn btn-danger" onClick={() => { setConfirmError(null); setConfirm({ kind: "passkey", item: p }); }} disabled={busy !== null}>{t.remove}</button>151                    </div>152                  </div>153                )}154              </li>155            ))}156          </ul>157158          <form onSubmit={add} className="card grid gap-3 p-4 sm:grid-cols-[1fr_auto] sm:items-end">159            <h3 className="font-semibold sm:col-span-2">{t.addTitle}</h3>160            <label className="grid gap-1 text-sm font-medium" htmlFor="pk-new">{t.addName}161              <input id="pk-new" className="field" value={newName} maxLength={60} required autoComplete="off" onChange={(e) => setNewName(e.target.value)} /></label>162            <button className="btn btn-primary" disabled={busy !== null}>{busy === "add" && <Spinner />}{t.add}</button>163          </form>164165          <div className="card p-4">166            <div className="flex flex-wrap items-center justify-between gap-3">167              <div className="min-w-0">168                <h3 className="font-semibold">{t.rcTitle}</h3>169                <p className={`mt-0.5 text-sm ${data.recoveryCodesLeft === 0 ? "text-bad" : data.recoveryCodesLeft <= 3 ? "text-warn" : "text-muted"}`}>{data.recoveryCodesLeft === 0 ? t.rcNone : fill(t.rcLeft, { n: data.recoveryCodesLeft })}</p>170              </div>171              <button type="button" className="btn" onClick={() => { setConfirmError(null); setConfirm({ kind: "codes" }); }} disabled={busy !== null}>{t.rcRegen}</button>172            </div>173          </div>174175          <div className="card p-4">176            <h3 className="font-semibold">{t.sessTitle}</h3>177            <ul className="mt-1 divide-y divide-line">178              {data.sessions.map((s) => (179                <li key={s.id} className="flex flex-wrap items-center justify-between gap-3 py-3">180                  <div className="min-w-0">181                    <p className="font-medium">{device(s.userAgent)} {s.current && <span className="ml-1 rounded-full border border-ok/40 px-2 py-0.5 text-xs font-semibold text-ok">{t.current}</span>}</p>182                    <p className="mt-0.5 break-words text-sm text-faint">{s.ip ?? "—"} · {fill(t.sessMethod, { m: s.method })} · {fill(t.sessOpened, { d: formatDateTime(s.createdAt, locale) })} · {fill(t.sessSeen, { d: formatDateTime(s.lastSeenAt, locale) })}</p>183                  </div>184                  {!s.current && <button type="button" className="btn btn-danger" onClick={() => { setConfirmError(null); setConfirm({ kind: "session", item: s }); }} disabled={busy !== null}>{t.revoke}</button>}185                </li>186              ))}187            </ul>188          </div>189        </>190      )}191192      <Confirm open={!!confirm} busy={busy === "confirm"} error={confirmError} cancelLabel={t.cancel} onConfirm={() => { void confirmed(); }} onClose={() => { if (busy !== "confirm") setConfirm(null); }}193        title={confirm?.kind === "passkey" ? t.removeTitle : confirm?.kind === "session" ? t.revokeTitle : t.rcConfirmTitle}194        confirmLabel={confirm?.kind === "passkey" ? t.remove : confirm?.kind === "session" ? t.revoke : t.rcRegen}>195        {confirm?.kind === "passkey" ? fill(t.removeBody, { n: confirm.item.name }) : confirm?.kind === "session" ? `${device(confirm.item.userAgent)} — ${t.revokeBody}` : t.rcConfirm}196      </Confirm>197      <Dialog open={!!codes} onClose={() => setCodes(null)} title={t.rcNewTitle}>198        {codes && (199          <>200            <Notice tone="warn">{t.rcWarn}</Notice>201            <ol className="mt-4 grid grid-cols-1 gap-2 rounded-xl border border-line bg-raised p-4 font-mono text-[0.9375rem] xs:grid-cols-2">{codes.map((c) => <li key={c} className="break-all">{c}</li>)}</ol>202            <div className="mt-4 flex flex-wrap justify-end gap-2">203              <CopyButton text={codes.join("\n")} label={t.copy} copiedLabel={t.copied} />204              <button type="button" className="btn btn-primary" onClick={() => setCodes(null)}>{t.rcDone}</button>205            </div>206          </>207        )}208      </Dialog>209    </Section>210  );211}212213// ── Claude and site ─────────────────────────────────────────────────────────────────────────────────214215const EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const satisfies readonly Settings["aiEffortGenerate"][];216const NUMBERS = ["aiMaxOutputTokens", "aiBudgetPerJobUsd", "aiBudgetDailyUsd", "aiBudgetMonthlyUsd", "aiJobsPerHour", "aiJobTimeoutMinutes"] as const;217type NumKey = (typeof NUMBERS)[number];218interface AiForm { aiModel: string; aiEffortGenerate: Settings["aiEffortGenerate"]; aiEffortEdit: Settings["aiEffortEdit"]; nums: Record<NumKey, string> }219const toForm = (s: Settings): AiForm => ({ aiModel: s.aiModel, aiEffortGenerate: s.aiEffortGenerate, aiEffortEdit: s.aiEffortEdit, nums: Object.fromEntries(NUMBERS.map((k) => [k, String(s[k])])) as Record<NumKey, string> });220221function ClaudeSection({ t, data, onSaved }: { t: Tr; data: SettingsData; onSaved: (s: Settings) => void }) {222  const locale = useLocale(), fr = locale === "fr";223  const { settings, models, environment } = data;224  const [form, setForm] = useState<AiForm>(() => toForm(settings));225  const [busy, setBusy] = useState(false), [flash, setFlash] = useState<Flash>(null), [issues, setIssues] = useState<string[]>([]);226  const labels: Record<NumKey, string> = { aiMaxOutputTokens: t.maxTokens, aiBudgetPerJobUsd: t.perJob, aiBudgetDailyUsd: t.daily, aiBudgetMonthlyUsd: t.monthly, aiJobsPerHour: t.jobsHour, aiJobTimeoutMinutes: t.timeout };227  const allLabels: Record<string, string> = { ...labels, aiModel: t.model, aiEffortGenerate: t.effortGen, aiEffortEdit: t.effortEdit };228  const effortLabel = { low: t.low, medium: t.medium, high: t.high, xhigh: t.xhigh, max: t.max };229  const nf = (n: number) => new Intl.NumberFormat(fr ? "fr-CA" : "en-CA", { maximumFractionDigits: 2 }).format(n);230231  const effective = form.aiModel || environment.defaultModel;232  const selected = models.find((m) => m.id === effective);233  const known = form.aiModel === "" || models.some((m) => m.id === form.aiModel);234235  const submit = async (ev: FormEvent) => {236    ev.preventDefault(); setFlash(null); setIssues([]);237    const patch: Partial<Settings> = {};238    if (form.aiModel !== settings.aiModel) patch.aiModel = form.aiModel;239    if (form.aiEffortGenerate !== settings.aiEffortGenerate) patch.aiEffortGenerate = form.aiEffortGenerate;240    if (form.aiEffortEdit !== settings.aiEffortEdit) patch.aiEffortEdit = form.aiEffortEdit;241    const bad: string[] = [];242    for (const k of NUMBERS) {243      const raw = form.nums[k].trim().replace(",", "."), n = Number(raw);244      if (raw === "" || !Number.isFinite(n)) { bad.push(fill(t.badNumber, { f: labels[k] })); continue; }245      if (n !== settings[k]) patch[k] = n;246    }247    if (bad.length) { setIssues(bad); return; }248    if (Object.keys(patch).length === 0) { setFlash({ tone: "ok", text: t.nothing }); return; }249    setBusy(true);250    try {251      const r = await api<{ settings: Settings }>("/api/admin/settings", { method: "PATCH", body: patch });252      onSaved(r.settings); setForm(toForm(r.settings)); setFlash({ tone: "ok", text: t.saved });253    } catch (e) {254      const details = validationDetails(e);255      if (details.length) { setIssues(details.map((d) => `${allLabels[d.path] ?? d.path} : ${d.message}`)); setFlash({ tone: "bad", text: fr ? "Saisie invalide." : "Invalid input." }); }256      else setFlash({ tone: "bad", text: apiMessage(e, fr) });257    }258    setBusy(false);259  };260  const num = (k: NumKey, opts: { min: number; max: number; step: number; help?: string }) => (261    <label className="grid gap-1 text-sm font-medium" htmlFor={`ai-${k}`}>{labels[k]}262      <input id={`ai-${k}`} className="field tabular-nums" type="number" inputMode={opts.step < 1 ? "decimal" : "numeric"} min={opts.min} max={opts.max} step={opts.step} required autoComplete="off"263        value={form.nums[k]} onChange={(e) => setForm({ ...form, nums: { ...form.nums, [k]: e.target.value } })} />264      {opts.help && <span className="font-normal text-faint">{opts.help}</span>}265    </label>266  );267  const effort = (k: "aiEffortGenerate" | "aiEffortEdit", label: string) => (268    <label className="grid gap-1 text-sm font-medium" htmlFor={`ai-${k}`}>{label}269      <select id={`ai-${k}`} className="field" value={form[k]} onChange={(e) => { const v = EFFORTS.find((x) => x === e.target.value); if (v) setForm({ ...form, [k]: v }); }}>270        {EFFORTS.map((x) => <option key={x} value={x}>{effortLabel[x]}</option>)}271      </select>272    </label>273  );274  const tag = (m: Model) => (m.priceKnown ? fill(t.priceTag, { i: nf(m.price.input), o: nf(m.price.output) }) : t.priceTagUnknown);275276  return (277    <Section id="set-ai" title={t.aiTitle}>278      <Notice tone={environment.anthropicKeySet ? "ok" : "warn"}><strong className="font-semibold">{environment.anthropicKeySet ? t.keySet : t.keyMissing}</strong> {t.keyWhere}</Notice>279      {data.modelsError && <Notice tone="warn">{fill(t.modelsError, { e: data.modelsError })}</Notice>}280      <form onSubmit={submit} className="card grid gap-4 p-4" noValidate>281        <label className="grid gap-1 text-sm font-medium" htmlFor="ai-model">{t.model}282          <select id="ai-model" className="field" value={form.aiModel} onChange={(e) => setForm({ ...form, aiModel: e.target.value })}>283            <option value="">{fill(t.modelDefault, { m: environment.defaultModel })}</option>284            {!known && <option value={form.aiModel}>{fill(t.modelGone, { m: form.aiModel })}</option>}285            {models.map((m) => <option key={m.id} value={m.id}>{m.name} — {m.id} ({tag(m)})</option>)}286          </select>287          <span className="font-normal leading-relaxed text-muted" aria-live="polite">288            <code className="font-mono text-[0.8125rem] text-ink">{effective}</code>289            {selected && <> · {selected.priceKnown ? fill(t.price, { i: nf(selected.price.input), o: nf(selected.price.output) }) : <span className="font-semibold text-warn">{t.priceUnknown}</span>}290              {selected.contextTokens && selected.maxOutputTokens ? ` ${fill(t.modelLimits, { c: nf(selected.contextTokens), o: nf(selected.maxOutputTokens) })}` : ""}</>}291          </span>292        </label>293        <div className="grid gap-4 sm:grid-cols-2">{effort("aiEffortGenerate", t.effortGen)}{effort("aiEffortEdit", t.effortEdit)}</div>294        {num("aiMaxOutputTokens", { min: 4000, max: 128000, step: 1000, help: t.maxTokensHelp })}295        <fieldset className="grid gap-3">296          <legend className="text-sm font-semibold">{t.budgets}</legend>297          <div className="mt-2 grid gap-4 sm:grid-cols-3">{num("aiBudgetPerJobUsd", { min: 0, max: 1000, step: 0.01 })}{num("aiBudgetDailyUsd", { min: 0, max: 10000, step: 0.01 })}{num("aiBudgetMonthlyUsd", { min: 0, max: 100000, step: 0.01 })}</div>298        </fieldset>299        <div className="grid gap-4 sm:grid-cols-2">{num("aiJobsPerHour", { min: 1, max: 500, step: 1 })}{num("aiJobTimeoutMinutes", { min: 1, max: 60, step: 1 })}</div>300        <div aria-live="polite" className="grid gap-2">301          {flash && <Notice tone={flash.tone}>{flash.text}</Notice>}302          {issues.length > 0 && <Notice tone="bad"><ul className="list-disc pl-5">{issues.map((x) => <li key={x}>{x}</li>)}</ul></Notice>}303        </div>304        <div><button className="btn btn-primary" disabled={busy}>{busy && <Spinner />}{t.save}</button></div>305      </form>306    </Section>307  );308}309310function SiteSection({ t, data, onSaved }: { t: Tr; data: SettingsData; onSaved: (s: Settings) => void }) {311  const locale = useLocale(), fr = locale === "fr";312  const [busy, setBusy] = useState(false), [flash, setFlash] = useState<Flash>(null);313  const env = data.environment, on = data.settings.analyticsEnabled;314  const toggle = async (next: boolean) => {315    setBusy(true); setFlash(null);316    try { const r = await api<{ settings: Settings }>("/api/admin/settings", { method: "PATCH", body: { analyticsEnabled: next } }); onSaved(r.settings); setFlash({ tone: "ok", text: r.settings.analyticsEnabled ? t.analyticsOn : t.analyticsOff }); }317    catch (e) { setFlash({ tone: "bad", text: apiMessage(e, fr) }); }318    setBusy(false);319  };320  const facts: [string, ReactNode][] = [321    [t.rpId, <code key="v" className="font-mono text-sm">{env.rpId}</code>], [t.origin, <code key="v" className="font-mono text-sm">{env.appUrl}</code>], [t.storage, <code key="v" className="font-mono text-sm">{env.storageDriver}</code>],322    [t.av, <span key="v" className={env.clamdConfigured ? "text-ok" : "text-warn"}>{env.clamdConfigured ? t.avOn : t.avOff}</span>],323    [t.backups, <span key="v" className={env.backupDirSet ? "text-ok" : "text-warn"}>{env.backupDirSet ? t.backupsOn : t.backupsOff}</span>],324    [t.uploadLimit, fill(t.mb, { n: env.maxUploadMb })],325  ];326  return (327    <Section id="set-site" title={t.siteTitle}>328      <div className="card p-4">329        <label className="flex min-h-11 cursor-pointer items-start gap-3" htmlFor="set-analytics">330          <input id="set-analytics" type="checkbox" role="switch" className="mt-1 h-5 w-5 shrink-0 accent-[var(--ui-accent)]" checked={on} disabled={busy} onChange={(e) => { void toggle(e.target.checked); }} />331          <span><span className="font-semibold">{t.analytics}</span> {busy && <Spinner />}<span className="block text-sm text-muted">{t.analyticsHelp}</span></span>332        </label>333        <div className="mt-2"><FlashLine flash={flash} /></div>334      </div>335      <div className="card p-4">336        <h3 className="eyebrow">{t.env}</h3>337        <dl className="mt-2 divide-y divide-line">338          {facts.map(([k, v]) => <div key={k} className="grid gap-0.5 py-2.5 sm:grid-cols-[minmax(0,16rem)_1fr] sm:gap-4"><dt className="text-sm text-muted">{k}</dt><dd className="break-all text-[0.9375rem]">{v}</dd></div>)}339        </dl>340      </div>341    </Section>342  );343}344345// ── Topics ──────────────────────────────────────────────────────────────────────────────────────────346347function TopicCard({ t, topic, onChanged, onDelete }: { t: Tr; topic: Topic; onChanged: () => Promise<void>; onDelete: () => void }) {348  const locale = useLocale(), fr = locale === "fr";349  const initial = { nameFr: topic.name_fr, nameEn: topic.name_en, descriptionFr: topic.description_fr, descriptionEn: topic.description_en, tone: topic.tone, position: String(topic.position) };350  const [f, setF] = useState(initial), [busy, setBusy] = useState(false), [flash, setFlash] = useState<Flash>(null);351  const toneLabel: Record<string, string> = { neutral: t.neutral, blue: t.blue, teal: t.teal, green: t.green, amber: t.amber, red: t.red, violet: t.violet, pink: t.pink };352  const submit = async (ev: FormEvent) => {353    ev.preventDefault(); setFlash(null);354    const patch: Record<string, string | number> = {};355    for (const k of ["nameFr", "nameEn", "descriptionFr", "descriptionEn", "tone"] as const) if (f[k] !== initial[k]) patch[k] = k.startsWith("name") ? f[k].trim() : f[k];356    const pos = Number(f.position);357    if (f.position.trim() === "" || !Number.isInteger(pos)) { setFlash({ tone: "bad", text: fill(t.badNumber, { f: t.position }) }); return; }358    if (pos !== topic.position) patch.position = pos;359    if (Object.keys(patch).length === 0) { setFlash({ tone: "ok", text: t.nothing }); return; }360    setBusy(true);361    try { await api(`/api/admin/topics/${topic.id}`, { method: "PATCH", body: patch }); await onChanged(); setFlash({ tone: "ok", text: t.tpSaved }); }362    catch (e) { setFlash({ tone: "bad", text: apiMessage(e, fr) }); }363    setBusy(false);364  };365  const id = (k: string) => `tp-${topic.id}-${k}`;366  const text = (k: "nameFr" | "nameEn", label: string, lang: string) => (367    <label className="grid gap-1 text-sm font-medium" htmlFor={id(k)}>{label}368      <input id={id(k)} className="field" lang={lang} value={f[k]} maxLength={60} required autoComplete="off" onChange={(e) => setF({ ...f, [k]: e.target.value })} /></label>369  );370  const area = (k: "descriptionFr" | "descriptionEn", label: string, lang: string) => (371    <label className="grid gap-1 text-sm font-medium" htmlFor={id(k)}>{label}372      <textarea id={id(k)} className="field" lang={lang} rows={2} value={f[k]} maxLength={300} onChange={(e) => setF({ ...f, [k]: e.target.value })} /></label>373  );374  return (375    <li className="card p-4">376      <form onSubmit={submit} className="grid gap-3" noValidate>377        <div className="flex flex-wrap items-baseline justify-between gap-2">378          <h3 className="break-words font-semibold">{fr ? topic.name_fr : topic.name_en}</h3>379          <p className="text-sm text-faint"><span className="font-mono">{topic.slug}</span> · {fill(t.sheetsN, { n: topic.sheets })}</p>380        </div>381        <div className="grid gap-3 sm:grid-cols-2">{text("nameFr", t.nameFr, "fr")}{text("nameEn", t.nameEn, "en")}{area("descriptionFr", t.descFr, "fr")}{area("descriptionEn", t.descEn, "en")}</div>382        <div className="grid grid-cols-2 gap-3">383          <label className="grid gap-1 text-sm font-medium" htmlFor={id("tone")}>{t.tone}384            <select id={id("tone")} className="field" value={f.tone} onChange={(e) => setF({ ...f, tone: e.target.value })}>385              {!TONES.some((x) => x === f.tone) && <option value={f.tone}>{f.tone}</option>}386              {TONES.map((x) => <option key={x} value={x}>{toneLabel[x] ?? x}</option>)}387            </select></label>388          <label className="grid gap-1 text-sm font-medium" htmlFor={id("pos")}>{t.position}389            <input id={id("pos")} className="field tabular-nums" type="number" inputMode="numeric" min={0} max={999} step={1} required value={f.position} onChange={(e) => setF({ ...f, position: e.target.value })} /></label>390        </div>391        <FlashLine flash={flash} />392        <div className="flex flex-wrap items-center gap-2">393          <button className="btn btn-primary" disabled={busy}>{busy && <Spinner />}{t.save}</button>394          {topic.sheets === 0 ? <button type="button" className="btn btn-danger" onClick={onDelete} disabled={busy}>{t.tpDelete}</button> : <p className="text-sm text-faint">{t.tpInUse}</p>}395        </div>396      </form>397    </li>398  );399}400401function TopicsSection({ t }: { t: Tr }) {402  const locale = useLocale(), fr = locale === "fr";403  const { data, error, loading, reload } = useApi<{ topics: Topic[] }>("/api/admin/topics");404  const [deleting, setDeleting] = useState<Topic | null>(null), [busy, setBusy] = useState(false), [delError, setDelError] = useState<string | null>(null), [flash, setFlash] = useState<Flash>(null);405  const remove = async () => {406    if (!deleting) return;407    setBusy(true); setDelError(null);408    try { await api(`/api/admin/topics/${deleting.id}`, { method: "DELETE" }); setDeleting(null); setFlash({ tone: "ok", text: t.tpDeleted }); await reload(); }409    catch (e) { setDelError(apiMessage(e, fr)); }410    setBusy(false);411  };412  return (413    <Section id="set-topics" title={t.tpTitle} lead={t.tpLead}>414      <FlashLine flash={flash} />415      {loading && !data && <Loading label={t.loading} />}416      {error && <Retry error={error} reload={reload} label={t.retry} />}417      {data && data.topics.length === 0 && <p className="text-muted">{t.tpEmpty}</p>}418      {data && data.topics.length > 0 && (419        <ul className="grid gap-3">420          {data.topics.map((topic) => <TopicCard key={`${topic.id}:${topic.name_fr}:${topic.name_en}:${topic.description_fr}:${topic.description_en}:${topic.tone}:${topic.position}`} t={t} topic={topic} onChanged={reload} onDelete={() => { setDelError(null); setDeleting(topic); }} />)}421        </ul>422      )}423      <Confirm open={!!deleting} title={t.tpDelTitle} confirmLabel={t.tpDelete} cancelLabel={t.cancel} busy={busy} error={delError} onConfirm={() => { void remove(); }} onClose={() => { if (!busy) setDeleting(null); }}>424        {fill(t.tpDelBody, { n: deleting ? (fr ? deleting.name_fr : deleting.name_en) : "" })}425      </Confirm>426    </Section>427  );428}429430export function SettingsPage() {431  const locale = useLocale(), t = T(locale);432  const settings = useApi<SettingsData>("/api/admin/settings");433  const d = settings.data;434  const onSaved = (s: Settings) => { if (d) settings.setData({ ...d, settings: s }); };435  const links = [["#set-pk", t.pkTitle], ["#set-ai", t.aiTitle], ["#set-site", t.siteTitle], ["#set-topics", t.tpTitle]] as const;436  return (437    <>438      <PageHeader title={t.title} lead={t.lead} />439      <nav aria-label={t.title} className="-mx-1 mb-6 flex gap-2 overflow-x-auto px-1 py-1">440        {links.map(([href, label]) => <a key={href} href={href} className="inline-flex min-h-11 shrink-0 items-center rounded-full border border-line bg-surface px-4 text-sm font-semibold text-muted">{label}</a>)}441      </nav>442      <PasskeySection t={t} />443      {settings.loading && !d && <div className="mt-10"><Loading label={t.loading} /></div>}444      {settings.error && <div className="mt-10"><Retry error={settings.error} reload={settings.reload} label={t.retry} /></div>}445      {d && <><ClaudeSection t={t} data={d} onSaved={onSaved} /><SiteSection t={t} data={d} onSaved={onSaved} /></>}446      <TopicsSection t={t} />447    </>448  );449}450
Files main
Menu

Theme