Files
events-hub/frontend/src/app/(hub)/settings/page.tsx
T
joshuaandClaude Opus 5.5 59e6b9f03c Hub 2.0 step 6: AI cap and markup per church
The cap and markup move from the licence to the customer (migrated), use
is counted over all the church's installs under one lock per church, and
the licence token carries the church's cap. Settings → AI shows product.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:55:43 +02:00

354 lines
22 KiB
TypeScript

"use client";
import React, { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { api, errorText, setToken } from "@/lib/api";
import { fmtDate, rand, randFine } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import type { AiInstallUse } from "@/lib/types";
import { Loading, Message, PageTitle, Pager, SearchInput, Tabs } from "@/components/ui";
import { BillingSettings } from "@/components/billing/BillingSettings";
import { PRODUCT_NAMES } from "@/lib/products";
type Settings = Record<string, string>;
type AuditRow = { id: string; action: string; target: string | null; metadata: unknown; createdAt: string; actor: { name: string } | null };
type Msg = { type: "ok" | "err"; text: string } | null;
const FIELDS: { key: string; label: string; hint: string; type?: string }[] = [
{ key: "alert_email", label: "Alert email", hint: "Where new alerts are sent.", type: "email" },
{ key: "offline_minutes", label: "Offline after (minutes without a heartbeat)", hint: "Default 60.", type: "number" },
{ key: "backup_max_age_hours", label: "Backup too old after (hours)", hint: "Default 48.", type: "number" },
{ key: "disk_min_free_percent", label: "Disk low below (% free)", hint: "Default 10.", type: "number" },
{ key: "errors_per_day", label: "Errors spiking above (per 24 h)", hint: "Default 50.", type: "number" },
{ key: "licence_expiry_warning_days", label: "Warn about licence expiry (days before)", hint: "Default 14.", type: "number" },
];
type Tab = "alerts" | "email" | "billing" | "ai" | "security" | "audit";
const TABS: { key: Tab; label: string }[] = [
{ key: "alerts", label: "Alerts" },
{ key: "email", label: "Email" },
{ key: "billing", label: "Billing" },
{ key: "ai", label: "AI" },
{ key: "security", label: "Login and security" },
{ key: "audit", label: "Audit log" },
];
type AiUsage = { month: string; installs: AiInstallUse[]; totals: { calls: number; realCents: number; chargedCents: number; profitCents: number } };
type AiModel = { id: string; label: string; inputUsd: number; outputUsd: number; cacheReadUsd: number; note: string };
const AI_KEYS = ["ai_model", "ai_input_usd_per_mtok", "ai_output_usd_per_mtok", "ai_usd_zar", "ai_markup_percent"];
const OTHER = "__other";
const AI_FIELDS: { key: string; label: string; hint: string; type?: string }[] = [
{ key: "ai_usd_zar", label: "Exchange rate (rand per US$)", hint: "AI stays off until this is set. Each call is charged at the rate in force when it ran.", type: "number" },
{ key: "ai_markup_percent", label: "Default markup (%)", hint: "Added to the real cost; covers small overruns and is the profit. A licence can override it.", type: "number" },
];
/** Settings → AI: the Claude key, model and prices, and what each install used this month. */
function AiTab({ settings, models, onSaved, setMsg }: { settings: Settings; models: AiModel[]; onSaved: (s: Settings) => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState(() => Object.fromEntries(AI_KEYS.map(k => [k, settings[k] ?? ""])));
const known = models.find(m => m.id === form.ai_model);
const [other, setOther] = useState(() => !!form.ai_model && !known);
// Choosing a model fills in its list prices; they stay editable.
const chooseModel = (value: string) => {
if (value === OTHER) { setOther(true); setForm({ ...form, ai_model: "" }); return; }
const m = models.find(x => x.id === value);
setOther(false);
setForm({ ...form, ai_model: value, ...(m ? { ai_input_usd_per_mtok: String(m.inputUsd), ai_output_usd_per_mtok: String(m.outputUsd) } : {}) });
};
const pricesDiffer = !!known && (parseFloat(form.ai_input_usd_per_mtok) !== known.inputUsd || parseFloat(form.ai_output_usd_per_mtok) !== known.outputUsd);
const [key, setKey] = useState({ value: "", clear: false });
const [testing, setTesting] = useState(false);
const [month, setMonth] = useState("");
const [usage, setUsage] = useState<AiUsage | null>(null);
useEffect(() => {
api<AiUsage>(`/api/admin/ai-usage${month ? `?month=${month}` : ""}`).then(setUsage).catch(e => setMsg({ type: "err", text: errorText(e) }));
}, [month, setMsg]);
const save = async (e: React.FormEvent) => {
e.preventDefault();
try {
const r = await api<{ settings: Settings }>("/api/admin/settings", { method: "PUT", body: { settings: { ...form, ai_api_key: key.value, ai_api_key_clear: key.clear } } });
onSaved(r.settings);
setKey({ value: "", clear: false });
setMsg({ type: "ok", text: "AI settings saved." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const test = async () => {
setTesting(true);
setMsg(null);
try {
const r = await api<{ model: string; reply: string }>("/api/admin/settings/ai-test", { method: "POST" });
setMsg({ type: "ok", text: `Claude answered (${r.model}): “${r.reply}”. Uses the saved key and model.` });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setTesting(false);
};
return (
<div className="space-y-6">
<form onSubmit={save} className="card max-w-2xl space-y-3">
<p className="text-sm text-slate-600">Sites call AI through the Hub, which adds this key, checks each licence&apos;s monthly cap and meters every call. Churches only ever see the charged amount in rand.</p>
{!settings.ai_api_key_set && <p className="rounded-lg bg-amber-50 p-3 text-sm text-amber-900">No Claude API key saved, so AI is off for every site.</p>}
<div>
<label className="label" htmlFor="ai_api_key">Claude API key</label>
<input id="ai_api_key" className="input" type="password" autoComplete="off" disabled={key.clear} placeholder={settings.ai_api_key_set ? "Saved — leave blank to keep it" : "sk-ant-…"} value={key.value} onChange={e => setKey({ ...key, value: e.target.value })} />
{settings.ai_api_key_set && (
<label className="mt-1 flex items-center gap-2 text-xs text-slate-600"><input type="checkbox" checked={key.clear} onChange={e => setKey({ value: "", clear: e.target.checked })} /> Remove the saved key (turns AI off everywhere)</label>
)}
<p className="mt-1 text-xs text-slate-500">Stored encrypted; never sent to the browser or to sites.</p>
</div>
<div>
<label className="label" htmlFor="ai_model">Model</label>
<select id="ai_model" className="input" value={other ? OTHER : form.ai_model} onChange={e => chooseModel(e.target.value)}>
{models.map(m => <option key={m.id} value={m.id}>{m.label} — ${m.inputUsd} / ${m.outputUsd} per million tokens</option>)}
<option value={OTHER}>Another model (type its ID)</option>
</select>
{other ? (
<input id="ai_model_other" aria-label="Model ID" className="input mt-2" placeholder="claude-…" value={form.ai_model} onChange={e => setForm({ ...form, ai_model: e.target.value })} />
) : known && <p className="mt-1 text-xs text-slate-500">{known.note}</p>}
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="ai_input_usd_per_mtok">Input price (US$ per million tokens)</label>
<input id="ai_input_usd_per_mtok" className="input" type="number" step="any" min={0} value={form.ai_input_usd_per_mtok} onChange={e => setForm({ ...form, ai_input_usd_per_mtok: e.target.value })} />
</div>
<div>
<label className="label" htmlFor="ai_output_usd_per_mtok">Output price (US$ per million tokens)</label>
<input id="ai_output_usd_per_mtok" className="input" type="number" step="any" min={0} value={form.ai_output_usd_per_mtok} onChange={e => setForm({ ...form, ai_output_usd_per_mtok: e.target.value })} />
</div>
</div>
<p className="-mt-1 text-xs text-slate-500">
{other ? "Enter the model's prices from Anthropic's pricing page." : "Filled in from Anthropic's list prices when you choose a model. Change them only if Anthropic's prices change."}
{pricesDiffer && <> These differ from the list price (${known!.inputUsd} / ${known!.outputUsd}). <button type="button" className="text-indigo-700 hover:underline" onClick={() => chooseModel(known!.id)}>Use the list price</button></>}
</p>
{AI_FIELDS.map(f => (
<div key={f.key}>
<label className="label" htmlFor={f.key}>{f.label}</label>
<input id={f.key} className="input" type={f.type || "text"} step="any" value={form[f.key]} onChange={e => setForm({ ...form, [f.key]: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">{f.hint}</p>
</div>
))}
<div className="flex flex-wrap gap-2">
<button className="btn-primary">Save AI settings</button>
<button type="button" className="btn-secondary" disabled={testing || !settings.ai_api_key_set} onClick={test}>{testing ? "Testing…" : "Test the saved key"}</button>
</div>
</form>
<div className="card p-0">
<div className="flex flex-wrap items-center gap-3 p-5 pb-3">
<h2 className="font-semibold">Use by site</h2>
<input type="month" className="input w-auto" aria-label="Month" value={month || usage?.month || ""} onChange={e => setMonth(e.target.value)} />
{usage && <span className="ml-auto text-sm text-slate-600">{usage.totals.calls} uses · real {randFine(usage.totals.realCents)} · charged {randFine(usage.totals.chargedCents)} · profit {randFine(usage.totals.profitCents)}</span>}
</div>
{!usage ? <Loading /> : usage.installs.length === 0 ? <p className="px-5 pb-5 text-sm text-slate-500">No AI use in {usage.month}.</p> : (
<div className="overflow-x-auto px-5 pb-5">
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Site</th><th>Church cap</th><th>Uses</th><th className="text-right">Real cost</th><th className="text-right">Charged</th><th className="text-right">Profit</th></tr></thead>
<tbody>
{usage.installs.map(i => (
<tr key={i.installId} className="border-t border-slate-100">
<td className="py-1"><Link href={`/installs/${i.installId}`} className="text-indigo-700 hover:underline">{i.customer?.name || i.name}</Link> <span className="text-xs text-slate-500">{PRODUCT_NAMES[i.product]}</span></td>
<td>{i.capCents ? rand(i.capCents) : "off"}</td>
<td>{i.calls}</td>
<td className="text-right">{randFine(i.realCents)}</td>
<td className="text-right">{randFine(i.chargedCents)}</td>
<td className="text-right">{randFine(i.profitCents)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
);
}
export default function SettingsPage() {
const [tab, setTab] = useState<Tab>("alerts");
const [settings, setSettings] = useState<Settings | null>(null);
const [publicKey, setPublicKey] = useState("");
const [smtp, setSmtp] = useState(false);
const [aiModels, setAiModels] = useState<AiModel[]>([]);
const [audit, setAudit] = useState<AuditRow[]>([]);
const [auditQuery, setAuditQuery] = useState("");
const [pw, setPw] = useState({ currentPassword: "", newPassword: "" });
const [msg, setMsg] = useState<Msg>(null);
const [smtpPass, setSmtpPass] = useState({ value: "", clear: false });
const [testTo, setTestTo] = useState("");
const [testing, setTesting] = useState(false);
useEffect(() => {
api<{ settings: Settings; publicKey: string; smtp: boolean; aiModels: AiModel[] }>("/api/admin/settings").then(r => { setSettings(r.settings); setPublicKey(r.publicKey); setSmtp(r.smtp); setAiModels(r.aiModels || []); }).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<AuditRow[]>("/api/admin/audit").then(setAudit).catch(() => {});
// Open the tab named in the address (#email), so a reload or a link lands in the same place.
const fromHash = window.location.hash.slice(1);
if (TABS.some(t => t.key === fromHash)) setTab(fromHash as Tab);
}, []);
const auditShown = useMemo(() => audit.filter(a => matches(auditQuery, a.action.replace(/_/g, " "), a.actor?.name, a.target, a.metadata ? JSON.stringify(a.metadata) : "")), [audit, auditQuery]);
const auditPaged = usePaged(auditShown, auditQuery, 30);
if (!settings) return msg ? <Message msg={msg} /> : <Loading />;
const openTab = (t: Tab) => {
setTab(t);
setMsg(null);
window.history.replaceState(null, "", `#${t}`);
};
const save = async (e: React.FormEvent) => {
e.preventDefault();
try {
const r = await api<{ settings: Settings; smtp: boolean }>("/api/admin/settings", { method: "PUT", body: { settings } });
setSettings(r.settings);
setSmtp(r.smtp);
setMsg({ type: "ok", text: "Settings saved." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const smtpValues = () => ({
smtp_host: settings.smtp_host, smtp_port: settings.smtp_port, smtp_user: settings.smtp_user, smtp_from: settings.smtp_from,
smtp_pass: smtpPass.value, smtp_pass_clear: smtpPass.clear,
});
const saveSmtp = async (e: React.FormEvent) => {
e.preventDefault();
try {
const r = await api<{ settings: Settings; smtp: boolean }>("/api/admin/settings", { method: "PUT", body: { settings: smtpValues() } });
setSettings(r.settings);
setSmtp(r.smtp);
setSmtpPass({ value: "", clear: false });
setMsg({ type: "ok", text: "Email settings saved." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const testSmtp = async () => {
setTesting(true);
setMsg(null);
try {
const r = await api<{ to: string }>("/api/admin/settings/smtp-test", { method: "POST", body: { settings: smtpValues(), to: testTo } });
setMsg({ type: "ok", text: `Logged in to the mail server and sent a test email to ${r.to}. Check it arrived (and the spam folder).` });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setTesting(false);
};
const changePassword = async (e: React.FormEvent) => {
e.preventDefault();
try {
const r = await api<{ token: string }>("/api/auth/password", { method: "POST", body: pw });
setToken(r.token);
setPw({ currentPassword: "", newPassword: "" });
setMsg({ type: "ok", text: "Password changed. Other devices are signed out." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const signOutEverywhere = async () => {
if (!confirm("Sign out on every device, including this one?")) return;
await api("/api/auth/logout-everywhere", { method: "POST" }).catch(() => {});
setToken(null);
window.location.href = "/login";
};
return (
<>
<PageTitle title="Settings" />
<Tabs tabs={TABS} active={tab} onChange={openTab} />
{msg && <div className="mb-4"><Message msg={msg} /></div>}
<div role="tabpanel" id={`panel-${tab}`} aria-labelledby={`tab-${tab}`}>
{tab === "alerts" && (
<form onSubmit={save} className="card max-w-2xl space-y-4">
<p className="text-sm text-slate-600">Each product&apos;s latest version is its newest one on the <Link href="/releases" className="text-indigo-700 hover:underline">Releases</Link> page{settings.latest_version ? ` (Cross Events: ${settings.latest_version})` : ""}; an install on an older one shows as behind.</p>
{FIELDS.map(f => (
<div key={f.key}>
<label className="label" htmlFor={f.key}>{f.label}</label>
<input id={f.key} className="input" type={f.type || "text"} value={settings[f.key] ?? ""} onChange={e => setSettings({ ...settings, [f.key]: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">{f.hint}</p>
</div>
))}
<button className="btn-primary">Save settings</button>
</form>
)}
{tab === "email" && (
<form onSubmit={saveSmtp} className="card max-w-2xl space-y-3">
<p className="text-sm text-slate-600">The mail server alert emails are sent through. The password is stored encrypted.</p>
{!smtp && <p className="rounded-lg bg-amber-50 p-3 text-sm text-amber-900">Email isn&apos;t set up, so alerts are only logged.</p>}
<div className="grid gap-3 sm:grid-cols-3">
<div className="sm:col-span-2"><label className="label" htmlFor="smtp_host">Server</label><input id="smtp_host" className="input" placeholder="mail.example.com" value={settings.smtp_host ?? ""} onChange={e => setSettings({ ...settings, smtp_host: e.target.value })} /></div>
<div><label className="label" htmlFor="smtp_port">Port</label><input id="smtp_port" className="input" type="number" value={settings.smtp_port ?? ""} onChange={e => setSettings({ ...settings, smtp_port: e.target.value })} /></div>
</div>
<p className="-mt-1 text-xs text-slate-500">587 uses STARTTLS; 465 uses TLS from the start.</p>
<div><label className="label" htmlFor="smtp_user">Username</label><input id="smtp_user" className="input" autoComplete="off" value={settings.smtp_user ?? ""} onChange={e => setSettings({ ...settings, smtp_user: e.target.value })} /></div>
<div>
<label className="label" htmlFor="smtp_pass">Password</label>
<input id="smtp_pass" className="input" type="password" autoComplete="new-password" disabled={smtpPass.clear} placeholder={settings.smtp_pass_set ? "Saved — leave blank to keep it" : ""} value={smtpPass.value} onChange={e => setSmtpPass({ ...smtpPass, value: e.target.value })} />
{settings.smtp_pass_set && (
<label className="mt-1 flex items-center gap-2 text-xs text-slate-600"><input type="checkbox" checked={smtpPass.clear} onChange={e => setSmtpPass({ value: "", clear: e.target.checked })} /> Remove the saved password</label>
)}
</div>
<div><label className="label" htmlFor="smtp_from">From address</label><input id="smtp_from" className="input" placeholder="Cross Code Hub <hub@crosscode.co.za>" value={settings.smtp_from ?? ""} onChange={e => setSettings({ ...settings, smtp_from: e.target.value })} /><p className="mt-1 text-xs text-slate-500">Blank uses the username.</p></div>
<button className="btn-primary">Save email settings</button>
<div className="border-t border-slate-100 pt-3">
<label className="label" htmlFor="smtp_test_to">Send a test email to</label>
<div className="flex flex-wrap gap-2">
<input id="smtp_test_to" className="input flex-1" type="email" placeholder={settings.alert_email || "you@example.com"} value={testTo} onChange={e => setTestTo(e.target.value)} />
<button type="button" className="btn-secondary" disabled={testing} onClick={testSmtp}>{testing ? "Testing…" : "Send test"}</button>
</div>
<p className="mt-1 text-xs text-slate-500">Tries what&apos;s in the form, saved or not. Blank sends to the alert email.</p>
</div>
</form>
)}
{tab === "billing" && <BillingSettings settings={settings} onSaved={setSettings} setMsg={setMsg} />}
{tab === "ai" && <AiTab settings={settings} models={aiModels} onSaved={setSettings} setMsg={setMsg} />}
{tab === "security" && (
<div className="max-w-2xl space-y-6">
<form onSubmit={changePassword} className="card space-y-3">
<h2 className="font-semibold">Your login</h2>
<div><label className="label" htmlFor="current_password">Current password</label><input id="current_password" type="password" className="input" autoComplete="current-password" value={pw.currentPassword} onChange={e => setPw({ ...pw, currentPassword: e.target.value })} required /></div>
<div><label className="label" htmlFor="new_password">New password (12+ characters)</label><input id="new_password" type="password" className="input" autoComplete="new-password" minLength={12} value={pw.newPassword} onChange={e => setPw({ ...pw, newPassword: e.target.value })} required /></div>
<div className="flex flex-wrap gap-2">
<button className="btn-secondary">Change password</button>
<button type="button" className="btn-danger" onClick={signOutEverywhere}>Sign out everywhere</button>
</div>
</form>
<div className="card space-y-2">
<h2 className="font-semibold">Licence signing key</h2>
<p className="text-sm text-slate-600">Installs check licences with this public key (built into Cross Events: <code>backend/src/hub/publicKey.js</code>). The private key stays on this server only — keep a backup.</p>
<pre className="overflow-x-auto rounded-lg bg-slate-50 p-3 text-xs">{publicKey}</pre>
</div>
</div>
)}
{tab === "audit" && (
<>
<SearchInput className="mb-3 w-full sm:w-72" value={auditQuery} onChange={setAuditQuery} placeholder="Search who or what" />
<div className="card p-0">
{audit.length === 0 ? <p className="p-5 text-sm text-slate-500">Nothing yet.</p> : auditShown.length === 0 ? <p className="p-5 text-sm text-slate-500">Nothing matches.</p> : (
<ul className="space-y-1 p-5 text-sm">
{auditPaged.rows.map(a => (
<li key={a.id} className="flex flex-wrap gap-2">
<span className="w-40 shrink-0 text-xs text-slate-500">{fmtDate(a.createdAt)}</span>
<span className="font-medium">{a.actor?.name || "—"}</span>
<span>{a.action.replace(/_/g, " ")}</span>
{a.metadata ? <span className="text-xs text-slate-400 break-all">{JSON.stringify(a.metadata)}</span> : null}
</li>
))}
</ul>
)}
<Pager {...auditPaged} />
</div>
</>
)}
</div>
</>
);
}