"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"; type Settings = Record; 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(null); useEffect(() => { api(`/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 (

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.

{!settings.ai_api_key_set &&

No Claude API key saved, so AI is off for every site.

}
setKey({ ...key, value: e.target.value })} /> {settings.ai_api_key_set && ( )}

Stored encrypted; never sent to the browser or to sites.

{other ? ( setForm({ ...form, ai_model: e.target.value })} /> ) : known &&

{known.note}

}
setForm({ ...form, ai_input_usd_per_mtok: e.target.value })} />
setForm({ ...form, ai_output_usd_per_mtok: e.target.value })} />

{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}). }

{AI_FIELDS.map(f => (
setForm({ ...form, [f.key]: e.target.value })} />

{f.hint}

))}

Use by site

setMonth(e.target.value)} /> {usage && {usage.totals.calls} uses · real {randFine(usage.totals.realCents)} · charged {randFine(usage.totals.chargedCents)} · profit {randFine(usage.totals.profitCents)}}
{!usage ? : usage.installs.length === 0 ?

No AI use in {usage.month}.

: (
{usage.installs.map(i => ( ))}
SiteCapUsesReal costChargedProfit
{i.name} {i.capCents ? rand(i.capCents) : "off"} {i.calls} {randFine(i.realCents)} {randFine(i.chargedCents)} {randFine(i.profitCents)}
)}
); } export default function SettingsPage() { const [tab, setTab] = useState("alerts"); const [settings, setSettings] = useState(null); const [publicKey, setPublicKey] = useState(""); const [smtp, setSmtp] = useState(false); const [aiModels, setAiModels] = useState([]); const [audit, setAudit] = useState([]); const [auditQuery, setAuditQuery] = useState(""); const [pw, setPw] = useState({ currentPassword: "", newPassword: "" }); const [msg, setMsg] = useState(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("/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 ? : ; 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 ( <> {msg &&
}
{tab === "alerts" && (

Each product's latest version is its newest one on the Releases page{settings.latest_version ? ` (Cross Events: ${settings.latest_version})` : ""}; an install on an older one shows as behind.

{FIELDS.map(f => (
setSettings({ ...settings, [f.key]: e.target.value })} />

{f.hint}

))}
)} {tab === "email" && (

The mail server alert emails are sent through. The password is stored encrypted.

{!smtp &&

Email isn't set up, so alerts are only logged.

}
setSettings({ ...settings, smtp_host: e.target.value })} />
setSettings({ ...settings, smtp_port: e.target.value })} />

587 uses STARTTLS; 465 uses TLS from the start.

setSettings({ ...settings, smtp_user: e.target.value })} />
setSmtpPass({ ...smtpPass, value: e.target.value })} /> {settings.smtp_pass_set && ( )}
setSettings({ ...settings, smtp_from: e.target.value })} />

Blank uses the username.

setTestTo(e.target.value)} />

Tries what's in the form, saved or not. Blank sends to the alert email.

)} {tab === "billing" && } {tab === "ai" && } {tab === "security" && (

Your login

setPw({ ...pw, currentPassword: e.target.value })} required />
setPw({ ...pw, newPassword: e.target.value })} required />

Licence signing key

Installs check licences with this public key (built into Cross Events: backend/src/hub/publicKey.js). The private key stays on this server only — keep a backup.

{publicKey}
)} {tab === "audit" && ( <>
{audit.length === 0 ?

Nothing yet.

: auditShown.length === 0 ?

Nothing matches.

: (
    {auditPaged.rows.map(a => (
  • {fmtDate(a.createdAt)} {a.actor?.name || "—"} {a.action.replace(/_/g, " ")} {a.metadata ? {JSON.stringify(a.metadata)} : null}
  • ))}
)}
)}
); }