WIP Hub 1.6.0: AI proxy for Cross Events 2.0

Signed /installs/ai/status and /installs/ai/complete (protocol 3b):
the Hub holds the Claude key, holds each call's worst case against the
licence's monthly cap in a locked transaction, calls Claude Haiku 5.5
and meters real cost and charged amount (markup) in rand. Settings ->
AI, licence markup override, AI use on the install page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 09:16:04 +02:00
co-authored by Claude Opus 5.5
parent 0f4d1c360a
commit 49f62aeb75
20 changed files with 1041 additions and 27 deletions
+104 -2
View File
@@ -3,8 +3,9 @@
import React, { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { api, errorText, setToken } from "@/lib/api";
import { fmtDate } from "@/lib/format";
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";
type Settings = Record<string, string>;
@@ -20,14 +21,113 @@ const FIELDS: { key: string; label: string; hint: string; type?: string }[] = [
{ key: "licence_expiry_warning_days", label: "Warn about licence expiry (days before)", hint: "Default 14.", type: "number" },
];
type Tab = "alerts" | "email" | "security" | "audit";
type Tab = "alerts" | "email" | "ai" | "security" | "audit";
const TABS: { key: Tab; label: string }[] = [
{ key: "alerts", label: "Alerts" },
{ key: "email", label: "Email" },
{ 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 } };
const AI_FIELDS: { key: string; label: string; hint: string; type?: string }[] = [
{ key: "ai_model", label: "Model", hint: "claude-haiku-5-5 — the cheapest current model." },
{ key: "ai_input_usd_per_mtok", label: "Input price (US$ per million tokens)", hint: "Haiku 5.5: 0.10 (prompts under 100K tokens).", type: "number" },
{ key: "ai_output_usd_per_mtok", label: "Output price (US$ per million tokens)", hint: "Haiku 5.5: 0.50.", type: "number" },
{ 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 and prices, and what each install used this month. */
function AiTab({ settings, onSaved, setMsg }: { settings: Settings; onSaved: (s: Settings) => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState(() => Object.fromEntries(AI_FIELDS.map(f => [f.key, settings[f.key] ?? ""])));
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>
{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>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.name}</Link></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);
@@ -164,6 +264,8 @@ export default function SettingsPage() {
</form>
)}
{tab === "ai" && <AiTab settings={settings} onSaved={setSettings} setMsg={setMsg} />}
{tab === "security" && (
<div className="max-w-2xl space-y-6">
<form onSubmit={changePassword} className="card space-y-3">