Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/components/admin/AppEditor.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 } from "react";46import { CATEGORIES, PLATFORMS, STATUSES } from "@/models/constants";47import type { AppDoc, Distribution, Screenshot } from "@/models/app";48import { api, errorText } from "./client";49import { Section } from "./Panels";5051const url = (slug: string, file: string) => (file.startsWith("u/") ? `/media/${slug}/${file.slice(2)}` : `/apps/${slug}/${file}`);52/** The structured parts of the document are edited as JSON; the schema is enforced by the server on save. */53const ADVANCED = ["features", "deepDives", "specs", "privacy", "faq", "verification", "releases", "minOS", "architectures", "downloadSize", "seo"] as const;5455export function AppEditor({ initial, publish, hasDraft }: { initial: AppDoc; publish: string; hasDraft: boolean }) {56 const router = useRouter();57 const [a, setA] = useState<AppDoc>(initial);58 const [adv, setAdv] = useState(() => JSON.stringify(Object.fromEntries(ADVANCED.map((k) => [k, initial[k] ?? null])), null, 2));59 const [busy, setBusy] = useState(""), [note, setNote] = useState<{ ok: boolean; text: string } | null>(null), [dirty, setDirty] = useState(false);60 const set = (patch: Partial<AppDoc>) => { setA((cur) => ({ ...cur, ...patch })); setDirty(true); };61 const L2 = (k: "tagline" | "summary" | "description", rows = 1) => (["en", "fr"] as const).map((l) => (62 <label key={l}><span className="label">{k} ({l})</span>{rows > 163 ? <textarea rows={rows} className="field" value={a[k][l]} onChange={(e) => set({ [k]: { ...a[k], [l]: e.target.value } } as Partial<AppDoc>)} />64 : <input className="field" value={a[k][l]} onChange={(e) => set({ [k]: { ...a[k], [l]: e.target.value } } as Partial<AppDoc>)} />}</label>65 ));66 const dist = (channel: Distribution["channel"]) => a.distribution.find((d) => d.channel === channel);67 const setDist = (channel: Distribution["channel"], patch: Partial<Distribution>) => {68 const cur = dist(channel) ?? { channel, state: "none" as const, url: null };69 const next = { ...cur, ...patch }; if (patch.url !== undefined && patch.url !== cur.url) delete next.check; // a changed link must be verified again70 set({ distribution: [...a.distribution.filter((d) => d.channel !== channel), next] });71 };72 const shots = (next: Screenshot[]) => set({ screenshots: next });7374 const compose = (): AppDoc => {75 let extra: Record<string, unknown>;76 try { extra = JSON.parse(adv); } catch { throw new Error("The structured content is not valid JSON."); }77 const doc = { ...a, ...Object.fromEntries(ADVANCED.filter((k) => k in extra).map((k) => [k, extra[k]])) } as Record<string, unknown>;78 for (const k of ["downloadSize"]) if (doc[k] === undefined) doc[k] = null;79 if (doc.seo === null) delete doc.seo;80 return doc as AppDoc;81 };82 const act = async (key: string, fn: () => Promise<string>) => {83 setBusy(key); setNote(null);84 try { setNote({ ok: true, text: await fn() }); router.refresh(); } catch (e) { setNote({ ok: false, text: errorText(e) }); } finally { setBusy(""); }85 };86 const save = async () => { await api(`/api/admin/apps/${a.slug}`, { method: "PUT", body: compose() }); setDirty(false); };87 const upload = (kind: "icon" | "screenshot") => async (e: React.ChangeEvent<HTMLInputElement>) => {88 const files = [...(e.target.files ?? [])]; e.target.value = "";89 await act("upload", async () => {90 let next = a.screenshots, icon = a.icon;91 for (const file of files) {92 const form = new FormData(); form.set("file", file); form.set("kind", kind);93 const r = await api<{ file: string; width: number; height: number }>(`/api/admin/apps/${a.slug}/media`, { form });94 if (kind === "icon") icon = r.file;95 else next = [...next, { file: r.file, device: a.platforms.includes("macos") ? "mac" : r.width > r.height * 0.6 ? "ipad" : "iphone", appearance: "light", caption: { en: "", fr: "" } }];96 }97 set({ screenshots: next, icon });98 return `${files.length} image(s) uploaded — save the draft to keep them.`;99 });100 };101102 return (103 <div className="grid gap-6" data-testid="app-editor">104 <div className="sticky top-14 z-30 -mx-2 flex flex-wrap items-center gap-3 rounded-2xl border border-line bg-[color-mix(in_oklab,var(--bg)_88%,transparent)] px-4 py-3 backdrop-blur-xl">105 <span className="tag">{publish}</span>{(hasDraft || dirty) && <span className="tag !text-[var(--warn)]">{dirty ? "unsaved changes" : "draft pending"}</span>}106 <span className="flex-1" />107 <button className="btn btn-ghost btn-sm" disabled={!!busy} onClick={() => act("save", async () => { await save(); return "Draft saved. Nothing public changed."; })} data-testid="save-draft">Save draft</button>108 <a className="btn btn-ghost btn-sm" href={`/apps/${a.slug}?preview=1`} target="_blank" rel="noopener">Preview</a>109 <button className="btn btn-primary btn-sm" disabled={!!busy} onClick={() => act("publish", async () => { await save(); await api(`/api/admin/apps/${a.slug}/publish`, { body: {} }); return "Published."; })} data-testid="publish">Save & publish</button>110 {hasDraft && <button className="chip" disabled={!!busy} onClick={() => { if (confirm("Discard the pending draft?")) act("discard", async () => { await api(`/api/admin/apps/${a.slug}/discard`, { body: {} }); location.reload(); return "Draft discarded."; }); }}>Discard draft</button>}111 {publish === "published" && <button className="chip" disabled={!!busy} onClick={() => { if (confirm("Unpublish? The page disappears from the public site.")) act("unpublish", async () => { await api(`/api/admin/apps/${a.slug}/unpublish`, { body: {} }); return "Unpublished."; }); }}>Unpublish</button>}112 {publish !== "archived" && <button className="chip" disabled={!!busy} onClick={() => { if (confirm("Archive this application?")) act("archive", async () => { await api(`/api/admin/apps/${a.slug}/archive`, { body: {} }); return "Archived."; }); }}>Archive</button>}113 {note && <p role="status" className={`w-full text-sm ${note.ok ? "text-[var(--ok)]" : "text-[var(--bad)]"}`} data-testid="editor-note">{note.text}</p>}114 </div>115116 <Section title="Identity">117 <div className="grid gap-4 sm:grid-cols-4">118 <label className="sm:col-span-2"><span className="label">Name</span><input className="field" value={a.name} onChange={(e) => set({ name: e.target.value })} data-testid="field-name" /></label>119 <label><span className="label">Status</span><select className="field" value={a.status} onChange={(e) => set({ status: e.target.value as AppDoc["status"] })} data-testid="field-status">{STATUSES.map((s) => <option key={s}>{s}</option>)}</select></label>120 <label><span className="label">Category</span><select className="field" value={a.category} onChange={(e) => set({ category: e.target.value as AppDoc["category"] })}>{CATEGORIES.map((s) => <option key={s}>{s}</option>)}</select></label>121 <fieldset><legend className="label">Platforms</legend><div className="flex gap-3 pt-2 text-sm">{PLATFORMS.map((p) => <label key={p} className="flex items-center gap-1.5"><input type="checkbox" checked={a.platforms.includes(p)} onChange={(e) => set({ platforms: e.target.checked ? [...a.platforms, p] : a.platforms.filter((x) => x !== p) })} />{p}</label>)}</div></fieldset>122 <label><span className="label">Version</span><input className="field" value={a.version ?? ""} onChange={(e) => set({ version: e.target.value || null })} /></label>123 <label><span className="label">Build</span><input className="field" value={a.build ?? ""} onChange={(e) => set({ build: e.target.value || null })} /></label>124 <label><span className="label">Order</span><input type="number" className="field" value={a.order} onChange={(e) => set({ order: Number(e.target.value) || 0 })} /></label>125 <label><span className="label">Accent (#rrggbb)</span><input className="field" value={a.accent ?? ""} onChange={(e) => set({ accent: e.target.value || null })} /></label>126 <label><span className="label">Repository (SPB Git)</span><input className="field" value={a.repo.name ?? ""} onChange={(e) => set({ repo: { ...a.repo, name: e.target.value || null } })} /></label>127 <label><span className="label">Repository visibility</span><select className="field" value={a.repo.visibility} onChange={(e) => set({ repo: { ...a.repo, visibility: e.target.value as AppDoc["repo"]["visibility"] } })}>{["public", "private", "none"].map((s) => <option key={s}>{s}</option>)}</select></label>128 <label className="flex items-center gap-2 self-end pb-2 text-sm"><input type="checkbox" checked={!!a.featured} onChange={(e) => set({ featured: e.target.checked })} />Featured</label>129 </div>130 <div className="mt-5 flex items-center gap-4">131 {a.icon ? <img src={url(a.slug, a.icon)} alt="" width={64} height={64} className="rounded-[22%]" /> : <span className="tag">no icon</span>}132 <label className="btn btn-ghost btn-sm cursor-pointer">Upload icon<input type="file" accept="image/png,image/jpeg,image/webp" className="sr-only" onChange={upload("icon")} /></label>133 </div>134 </Section>135136 <Section title="Copy"><div className="grid gap-4 sm:grid-cols-2">{L2("tagline")}{L2("summary", 2)}{L2("description", 8)}</div></Section>137138 <Section title="Distribution">139 <div className="grid gap-4 sm:grid-cols-[1fr_10rem_auto] sm:items-end">140 <label><span className="label">TestFlight public invitation URL</span><input className="field" placeholder="https://testflight.apple.com/join/…" value={dist("testflight")?.url ?? ""} onChange={(e) => setDist("testflight", { url: e.target.value.trim() || null })} data-testid="field-testflight" /></label>141 <label><span className="label">State</span><select className="field" value={dist("testflight")?.state ?? "none"} onChange={(e) => setDist("testflight", { state: e.target.value as Distribution["state"] })} data-testid="field-testflight-state">{["none", "internal", "public"].map((s) => <option key={s}>{s}</option>)}</select></label>142 <button className="btn btn-ghost btn-sm" disabled={!!busy} onClick={() => act("tf", async () => { await save(); const r = await api<{ check: { result: string; detail?: string } }>(`/api/admin/apps/${a.slug}/testflight`, { body: {} }); setDist("testflight", { check: { at: new Date().toISOString(), result: r.check.result as "open", detail: r.check.detail } }); setDirty(false); return `Apple answered: ${r.check.result}${r.check.detail ? ` (${r.check.detail})` : ""}. Recorded in the draft.`; })} data-testid="verify-testflight">Save & verify link</button>143 </div>144 <p className="mt-2 text-[0.85rem] text-ink3">“Join TestFlight” appears publicly only when the state is <b>public</b>, the URL is a public invitation and the last verification answered <b>open</b>. Last check: {dist("testflight")?.check ? `${dist("testflight")!.check!.result} — ${dist("testflight")!.check!.at.slice(0, 16).replace("T", " ")}` : "never"}.</p>145 <div className="mt-5 grid gap-4 sm:grid-cols-2">146 {(["appstore-ios", "appstore-mac"] as const).map((c) => <label key={c}><span className="label">{c} URL (https://apps.apple.com/…)</span><input className="field" value={dist(c)?.url ?? ""} onChange={(e) => setDist(c, { url: e.target.value.trim() || null, state: e.target.value.trim() ? "public" : "none" })} /></label>)}147 </div>148 <p className="mt-3 text-[0.85rem] text-ink3">macOS images are never linked by hand: they come from approved SPB Git releases (Releases tab).</p>149 </Section>150151 <Section title="Screenshots" aside={<label className="btn btn-ghost btn-sm cursor-pointer">Upload<input type="file" multiple accept="image/png,image/jpeg,image/webp" className="sr-only" onChange={upload("screenshot")} data-testid="upload-screenshot" /></label>}>152 {a.screenshots.length === 0 && <p className="text-ink3">No screenshot. Upload real captures of the application only.</p>}153 <ul className="grid gap-4">154 {a.screenshots.map((s, i) => {155 const patch = (p: Partial<Screenshot>) => shots(a.screenshots.map((x, j) => (j === i ? { ...x, ...p } : p.hero ? { ...x, hero: false } : x)));156 const move = (d: number) => { const n = [...a.screenshots]; const [x] = n.splice(i, 1); n.splice(i + d, 0, x); shots(n); };157 return (158 <li key={s.file} className="grid gap-4 rounded-2xl border border-line p-4 sm:grid-cols-[6rem_1fr_auto]" data-testid="shot-row">159 <img src={url(a.slug, s.file)} alt="" loading="lazy" className="max-h-40 w-24 rounded-lg object-contain" />160 <div className="grid gap-3 sm:grid-cols-2">161 <label><span className="label">Caption (en)</span><input className="field" value={s.caption.en} onChange={(e) => patch({ caption: { ...s.caption, en: e.target.value } })} /></label>162 <label><span className="label">Légende (fr)</span><input className="field" value={s.caption.fr} onChange={(e) => patch({ caption: { ...s.caption, fr: e.target.value } })} /></label>163 <label><span className="label">Device</span><select className="field" value={s.device} onChange={(e) => patch({ device: e.target.value as Screenshot["device"] })}>{["iphone", "ipad", "mac"].map((d) => <option key={d}>{d}</option>)}</select></label>164 <label><span className="label">Appearance</span><select className="field" value={s.appearance} onChange={(e) => patch({ appearance: e.target.value as Screenshot["appearance"] })}>{["light", "dark"].map((d) => <option key={d}>{d}</option>)}</select></label>165 </div>166 <div className="flex flex-wrap content-start gap-2 sm:w-36">167 <label className="flex w-full items-center gap-2 text-sm"><input type="radio" name="hero" checked={!!s.hero} onChange={() => patch({ hero: true })} />Hero</label>168 <button className="chip" disabled={i === 0} onClick={() => move(-1)} aria-label="Move up">↑</button>169 <button className="chip" disabled={i === a.screenshots.length - 1} onClick={() => move(1)} aria-label="Move down">↓</button>170 <button className="chip" onClick={() => shots(a.screenshots.filter((_, j) => j !== i))}>Remove</button>171 </div>172 </li>173 );174 })}175 </ul>176 </Section>177178 <Section title="Structured content (JSON)">179 <p className="mb-3 text-[0.85rem] text-ink3">Features, deep dives, specifications, privacy, FAQ, verification, release notes, minimum OS, architectures, SEO. Every text is {"{ \"en\": …, \"fr\": … }"}; the schema is checked on save.</p>180 <textarea className="field mono !text-[0.8rem]" rows={28} spellCheck={false} value={adv} onChange={(e) => { setAdv(e.target.value); setDirty(true); }} data-testid="field-advanced" />181 </Section>182 </div>183 );184}185