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:
@@ -19,6 +19,7 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
|
||||
expiresAt: dateInput(licence.expiresAt),
|
||||
graceDays: String(licence.graceDays),
|
||||
aiRand: String(licence.aiMonthlyCapCents / 100),
|
||||
aiMarkup: licence.aiMarkupPercent == null ? "" : String(licence.aiMarkupPercent),
|
||||
notes: licence.notes || "",
|
||||
});
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -35,6 +36,7 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
|
||||
expiresAt: form.expiresAt ? `${form.expiresAt}T23:59:59+02:00` : null,
|
||||
graceDays: form.graceDays,
|
||||
aiMonthlyCapCents: Math.round((parseFloat(form.aiRand) || 0) * 100),
|
||||
aiMarkupPercent: form.aiMarkup.trim() === "" ? null : form.aiMarkup,
|
||||
notes: form.notes,
|
||||
},
|
||||
});
|
||||
@@ -65,7 +67,7 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
|
||||
? <>Used by <Link href={`/installs/${licence.install.id}`} className="text-indigo-600 hover:underline">{licence.install.url}</Link> · last heartbeat {ago(licence.install.lastHeartbeatAt)}</>
|
||||
: "Not used yet — enter this key in the church's Cross Events setup (or Site settings → Licence)."}
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-4">
|
||||
<div className="grid gap-3 sm:grid-cols-5">
|
||||
<div>
|
||||
<label className="label">Status</label>
|
||||
<select className="input" value={form.status} onChange={e => setForm({ ...form, status: e.target.value as LicenceStatus })}>
|
||||
@@ -86,7 +88,12 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
|
||||
<div>
|
||||
<label className="label">AI cap (R / month)</label>
|
||||
<input type="number" min={0} step="1" className="input" value={form.aiRand} onChange={e => setForm({ ...form, aiRand: e.target.value })} />
|
||||
<p className="mt-1 text-xs text-slate-500">0 = off. Used from 2.0.</p>
|
||||
<p className="mt-1 text-xs text-slate-500">0 = off (no AI buttons). Counted in charged rand.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label" htmlFor={`markup-${licence.id}`}>AI markup (%)</label>
|
||||
<input id={`markup-${licence.id}`} type="number" min={0} max={500} step="1" className="input" placeholder="Default" value={form.aiMarkup} onChange={e => setForm({ ...form, aiMarkup: e.target.value })} />
|
||||
<p className="mt-1 text-xs text-slate-500">Blank uses the default (Settings → AI).</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
|
||||
@@ -5,9 +5,9 @@ import Link from "next/link";
|
||||
import { useParams } from "next/navigation";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { ago, bytes, fmtDate, rand } from "@/lib/format";
|
||||
import { ago, bytes, fmtDate, rand, randFine } from "@/lib/format";
|
||||
import { usePaged } from "@/lib/paging";
|
||||
import type { Health, InstallEvent, InstallSummary, Licence, Stats } from "@/lib/types";
|
||||
import type { AiHelperUse, AiMonth, AiStatus, Health, InstallEvent, InstallSummary, Licence, Stats } from "@/lib/types";
|
||||
import { Badge, Loading, Message, PageTitle, Pager } from "@/components/ui";
|
||||
|
||||
type Detail = {
|
||||
@@ -20,6 +20,7 @@ type Detail = {
|
||||
summary: InstallSummary;
|
||||
events: InstallEvent[];
|
||||
heartbeats: { receivedAt: string; version: string | null; stats: Stats | null }[];
|
||||
ai: { status: AiStatus; months: AiMonth[]; helpers: AiHelperUse[] };
|
||||
};
|
||||
|
||||
const NO_EVENTS: InstallEvent[] = [];
|
||||
@@ -114,7 +115,8 @@ export default function InstallPage() {
|
||||
<Row k="Status" v={<Badge value={d.licence.status} />} />
|
||||
<Row k="Expires" v={d.licence.expiresAt ? fmtDate(d.licence.expiresAt, false) : "no end date"} />
|
||||
<Row k="Grace" v={`${d.licence.graceDays} days`} />
|
||||
<Row k="AI cap (2.0)" v={d.licence.aiMonthlyCapCents ? `${rand(d.licence.aiMonthlyCapCents)} / month` : "off"} />
|
||||
<Row k="AI cap" v={d.licence.aiMonthlyCapCents ? `${rand(d.licence.aiMonthlyCapCents)} / month` : "off"} />
|
||||
<Row k="AI markup" v={d.licence.aiMarkupPercent == null ? "default" : `${d.licence.aiMarkupPercent}%`} />
|
||||
<Link href={`/customers/${d.customer.id}`} className="mt-3 inline-block text-sm text-indigo-600 hover:underline">Change the licence →</Link>
|
||||
</>
|
||||
) : <p className="text-sm text-slate-500">No licence (released).</p>}
|
||||
@@ -135,6 +137,38 @@ export default function InstallPage() {
|
||||
|
||||
{msg && <div className="mt-4"><Message msg={msg} /></div>}
|
||||
|
||||
<div className="card mt-6">
|
||||
<h2 className="mb-2 font-semibold">AI</h2>
|
||||
{!d.ai.status.enabled && d.ai.months.length === 0 ? (
|
||||
<p className="text-sm text-slate-500">Off for this site{d.licence?.aiMonthlyCapCents ? " (AI isn't set up in Settings → AI, or the licence isn't active)" : " (cap R0)"}.</p>
|
||||
) : (
|
||||
<>
|
||||
<Row k="This month (charged)" v={`${randFine(d.ai.status.usedCents)} of ${rand(d.ai.status.capCents)} (${d.ai.status.usedPercent}%)${d.ai.status.capReached ? " — used up" : ""}`} />
|
||||
<Row k="Renews" v={fmtDate(d.ai.status.renewsOn, false)} />
|
||||
{d.ai.helpers.length > 0 && <Row k="By helper this month" v={d.ai.helpers.map(h => `${h.helper.replace(/_/g, " ")}: ${h.calls} (${randFine(h.chargedCents)})`).join(" · ")} />}
|
||||
{d.ai.months.length > 0 && (
|
||||
<div className="mt-3 overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Month</th><th>Uses</th><th>Tokens in / out</th><th className="text-right">Real cost</th><th className="text-right">Charged</th><th className="text-right">Profit</th></tr></thead>
|
||||
<tbody>
|
||||
{d.ai.months.map(m => (
|
||||
<tr key={m.month} className="border-t border-slate-100">
|
||||
<td className="py-1">{m.month}</td>
|
||||
<td>{m.calls}</td>
|
||||
<td>{m.inputTokens.toLocaleString("en-ZA")} / {m.outputTokens.toLocaleString("en-ZA")}</td>
|
||||
<td className="text-right">{randFine(m.realCents)}</td>
|
||||
<td className="text-right">{randFine(m.chargedCents)}</td>
|
||||
<td className="text-right">{randFine(m.profitCents)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="card mt-6">
|
||||
<h2 className="mb-3 font-semibold">History</h2>
|
||||
{d.events.length === 0 ? <p className="text-sm text-slate-500">Nothing yet.</p> : (
|
||||
|
||||
@@ -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'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">
|
||||
|
||||
Reference in New Issue
Block a user