SPB Git

Repository Public

Panels.tsx 10.1 KB 155 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : ORIX App Universe8 * File             : src/components/admin/Panels.tsx9 * Module           : components10 * Repository       : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website  : https://www.orixlab.dev12 * Created          : 2026-11-2113 * Last Modified    : 2026-11-2114 *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: support@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 */4243"use client";44import { useRouter } from "next/navigation";45import { useState, type ReactNode } from "react";46import { api, errorText } from "./client";4748/** Runs an admin action, shows the outcome inline and refreshes the server-rendered data. */49function useAction() {50  const router = useRouter();51  const [busy, setBusy] = useState(""), [note, setNote] = useState<{ ok: boolean; text: string } | null>(null);52  const run = async (key: string, fn: () => Promise<string | void>) => {53    setBusy(key); setNote(null);54    try { const text = await fn(); setNote({ ok: true, text: text || "Done." }); }55    catch (e) { setNote({ ok: false, text: errorText(e) }); }56    finally { setBusy(""); router.refresh(); } // a refused action may still have changed a state (e.g. a release marked invalid)57  };58  const Note = () => (note ? <p role="status" className={`text-sm ${note.ok ? "text-[var(--ok)]" : "text-[var(--bad)]"}`} data-testid="action-note">{note.text}</p> : null);59  return { busy, run, Note };60}6162export function LogoutButton() {63  return <button type="button" className="chip" onClick={async () => { await api("/api/auth/logout", { body: {} }).catch(() => {}); location.assign("/admin/login"); }}>Sign out</button>;64}6566export function SyncButton() {67  const { busy, run, Note } = useAction();68  return (69    <div className="flex flex-wrap items-center gap-4">70      <button type="button" className="btn btn-primary btn-sm" disabled={!!busy} data-testid="sync-now"71        onClick={() => run("sync", async () => { const r = await api<{ ok: boolean; summary: { repos: number; newReleases: number; errors: unknown[] } }>("/api/admin/sync", { body: {} }); return `${r.summary.repos} repositories read, ${r.summary.newReleases} new release record(s), ${r.summary.errors.length} error(s).`; })}>72        {busy ? "Synchronizing…" : "Synchronize now"}</button>73      <Note />74    </div>75  );76}7778export function PolicyToggle({ value }: { value: boolean }) {79  const { busy, run, Note } = useAction();80  return (81    <div className="flex flex-wrap items-center gap-4">82      <label className="flex items-center gap-3 text-[0.95rem]"><input type="checkbox" className="h-5 w-5" checked={value} disabled={!!busy} onChange={(e) => run("p", async () => { await api("/api/admin/settings", { method: "PUT", body: { requireNotarization: e.target.checked } }); })} />83        Hold any image whose notarization cannot be verified</label><Note />84    </div>85  );86}8788export function NewAppForm() {89  const { busy, run, Note } = useAction();90  const router = useRouter();91  return (92    <form className="flex flex-wrap items-end gap-3" onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); run("new", async () => { const r = await api<{ slug: string }>("/api/admin/apps", { body: { slug: f.get("slug"), name: f.get("name") } }); router.push(`/admin/apps/${r.slug}`); }); }}>93      <label><span className="label">Slug</span><input name="slug" className="field" placeholder="notes" pattern="[a-z][a-z0-9-]{1,30}" required /></label>94      <label><span className="label">Name</span><input name="name" className="field" placeholder="ORIX Notes" required /></label>95      <button className="btn btn-ghost btn-sm" disabled={!!busy}>Create draft</button><Note />96    </form>97  );98}99100export function ReleaseActions({ id, state, notes }: { id: number; state: string; notes: { en: string; fr: string } }) {101  const { busy, run, Note } = useAction();102  const [n, setN] = useState(notes), [open, setOpen] = useState(false);103  const act = (a: string, confirmText?: string) => { if (confirmText && !confirm(confirmText)) return; run(a, async () => { await api(`/api/admin/releases/${id}/${a}`, { body: {} }); }); };104  return (105    <div className="grid gap-2">106      <div className="flex flex-wrap gap-2">107        {(state === "validated" || state === "held") && <button className="btn btn-primary btn-sm" disabled={!!busy} onClick={() => act("approve", "Mirror this image, verify its checksum and notarization, and publish it if it passes?")} data-testid={`approve-${id}`}>{busy === "approve" ? "Verifying…" : state === "held" ? "Re-verify" : "Approve & publish"}</button>}108        {(state === "published" || state === "held" || state === "validated") && <button className="btn btn-ghost btn-sm" disabled={!!busy} onClick={() => act("withdraw", "Withdraw this release? The download stops immediately.")} data-testid={`withdraw-${id}`}>Withdraw</button>}109        {state === "withdrawn" && <button className="btn btn-ghost btn-sm" disabled={!!busy} onClick={() => act("requeue")}>Re-queue</button>}110        <button className="chip" onClick={() => setOpen((o) => !o)}>Notes</button>111      </div>112      {open && (113        <div className="grid gap-2">114          <textarea className="field" rows={3} placeholder="Release notes (English), one item per line" value={n.en} onChange={(e) => setN({ ...n, en: e.target.value })} />115          <textarea className="field" rows={3} placeholder="Notes de version (français), une par ligne" value={n.fr} onChange={(e) => setN({ ...n, fr: e.target.value })} />116          <button className="btn btn-ghost btn-sm justify-self-start" disabled={!!busy} onClick={() => run("notes", async () => { await api(`/api/admin/releases/${id}/notes`, { body: n }); })}>Save notes</button>117        </div>118      )}119      <Note />120    </div>121  );122}123124type Ann = { id?: number; kind: string; app_slug: string | null; date: string; publish: string; title_en: string; title_fr: string; body_en: string; body_fr: string };125export function AnnouncementForm({ value, apps }: { value?: Ann; apps: { slug: string; name: string }[] }) {126  const { busy, run, Note } = useAction();127  const [a, setA] = useState<Ann>(value ?? { kind: "announcement", app_slug: null, date: new Date().toISOString().slice(0, 10), publish: "draft", title_en: "", title_fr: "", body_en: "", body_fr: "" });128  const f = (k: keyof Ann) => ({ value: (a[k] ?? "") as string, onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => setA({ ...a, [k]: e.target.value || (k === "app_slug" ? null : "") }) });129  return (130    <form className="card grid gap-4 p-6" data-testid="announcement-form" onSubmit={(e) => { e.preventDefault(); run("save", async () => { await api(`/api/admin/announcements${a.id ? `/${a.id}` : ""}`, { method: a.id ? "PUT" : "POST", body: a }); if (!a.id) setA({ ...a, title_en: "", title_fr: "", body_en: "", body_fr: "" }); return "Saved."; }); }}>131      <div className="grid gap-4 sm:grid-cols-4">132        <label><span className="label">Kind</span><select className="field" {...f("kind")}>{["announcement", "new-app", "update", "beta", "release"].map((k) => <option key={k}>{k}</option>)}</select></label>133        <label><span className="label">Application</span><select className="field" {...f("app_slug")}><option value="">— none —</option>{apps.map((x) => <option key={x.slug} value={x.slug}>{x.name}</option>)}</select></label>134        <label><span className="label">Date</span><input type="date" className="field" {...f("date")} /></label>135        <label><span className="label">State</span><select className="field" {...f("publish")}>{["draft", "published", "archived"].map((k) => <option key={k}>{k}</option>)}</select></label>136      </div>137      <div className="grid gap-4 sm:grid-cols-2">138        <label><span className="label">Title (English)</span><input className="field" {...f("title_en")} /></label>139        <label><span className="label">Titre (français)</span><input className="field" {...f("title_fr")} /></label>140        <label><span className="label">Text (English)</span><textarea rows={4} className="field" {...f("body_en")} /></label>141        <label><span className="label">Texte (français)</span><textarea rows={4} className="field" {...f("body_fr")} /></label>142      </div>143      <div className="flex flex-wrap items-center gap-3">144        <button className="btn btn-primary btn-sm" disabled={!!busy}>{a.id ? "Save" : "Create"}</button>145        {a.id && <button type="button" className="btn btn-ghost btn-sm" disabled={!!busy} onClick={() => { if (confirm("Delete this announcement?")) run("del", async () => { await api(`/api/admin/announcements/${a.id}`, { method: "DELETE" }); }); }}>Delete</button>}146        <Note />147      </div>148    </form>149  );150}151152export function Section({ title, children, aside }: { title: string; children: ReactNode; aside?: ReactNode }) {153  return <section className="card p-6"><div className="mb-5 flex flex-wrap items-center justify-between gap-3"><h2 className="h3">{title}</h2>{aside}</div>{children}</section>;154}155
Files main
Menu

Theme