WIP 2.0.0: AI helper plumbing (status, usage, Site settings -> AI)
The site calls AI through the Hub (protocol 3b, Hub 1.6.0): src/ai works out whether the AI buttons show (licence token first, then the Hub, cached a minute), runs a helper call with per-helper switches and a per-person daily limit, logs AiCall rows, and emails admins at 80%. v2 /ai/status, /ai/usage, /ai/settings; useAiStatus, AiButton, AiTab. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Sparkles } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiV2, type V2Result } from "@/lib/apiV2";
|
||||
import { loadAiStatus, renewsText } from "@/lib/ai";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Usage = V2Result<"/ai/usage", "get">["data"];
|
||||
type Helper = keyof Usage["settings"]["helpers"];
|
||||
|
||||
const HELPERS: { key: Helper; label: string; where: string }[] = [
|
||||
{ key: "draft_event", label: "Draft an event", where: "New event: describe it and the form is filled in" },
|
||||
{ key: "summarise_report", label: "Summarise this report", where: "Reports: a few plain-language insights" },
|
||||
{ key: "draft_message", label: "Draft a message", where: "Emails and WhatsApp messages to attendees, broadcasts" },
|
||||
{ key: "summarise_feedback", label: "Summarise feedback", where: "Post-event feedback results" },
|
||||
{ key: "improve_text", label: "Improve this text", where: "Event descriptions, the banner, message boxes" },
|
||||
];
|
||||
|
||||
// Fractions of a cent add up: show R0.0123 below a rand.
|
||||
const money = (cents: number) => (cents > 0 && cents < 100 ? `R${(cents / 100).toFixed(4)}` : `R${(cents / 100).toFixed(2)}`);
|
||||
|
||||
/** Site settings → AI: the monthly allowance, who used it for what, and a switch per helper. */
|
||||
export function AiTab({ active }: { active: boolean }) {
|
||||
const { token } = useAuth();
|
||||
const [usage, setUsage] = useState<Usage | null>(null);
|
||||
const [limit, setLimit] = useState("0");
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || !token) return;
|
||||
let alive = true;
|
||||
apiV2("get", "/ai/usage", { authToken: token })
|
||||
.then(({ data }) => { if (alive) { setUsage(data); setLimit(String(data.settings.dailyLimitPerPerson)); } })
|
||||
.catch(e => { if (alive) setMsg({ ok: false, text: errorMessage(e) || "Could not load AI use." }); });
|
||||
return () => { alive = false; };
|
||||
}, [active, token]);
|
||||
|
||||
const save = async (helpers: Partial<Record<Helper, boolean>>, dailyLimitPerPerson?: number) => {
|
||||
if (!token) return;
|
||||
setBusy(true);
|
||||
setMsg(null);
|
||||
try {
|
||||
const { data } = await apiV2("put", "/ai/settings", { authToken: token, body: { helpers, ...(dailyLimitPerPerson != null ? { dailyLimitPerPerson } : {}) } });
|
||||
setUsage(u => (u ? { ...u, settings: data, status: { ...u.status, helpers: data.helpers } } : u));
|
||||
setMsg({ ok: true, text: "Saved." });
|
||||
loadAiStatus(token, { fresh: true }).catch(() => {});
|
||||
} catch (e) { setMsg({ ok: false, text: errorMessage(e) || "Could not save." }); }
|
||||
setBusy(false);
|
||||
};
|
||||
|
||||
if (!usage) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
|
||||
const s = usage.status;
|
||||
const maxDay = Math.max(0.0001, ...usage.days.map(d => d.chargedCents));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="flex items-center gap-2 text-lg font-semibold"><Sparkles className="h-5 w-5 text-violet-600" aria-hidden /> AI helpers</h2>
|
||||
<p className="mt-1 text-sm text-gray-600">
|
||||
One-click helpers for supervisors and admins: drafting events and messages, improving text, summarising reports and feedback. A person always checks the suggestion before anything is saved or sent.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{!s.enabled ? (
|
||||
<div className="rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">
|
||||
AI helpers aren't part of this site's licence, so their buttons are hidden. To add them, ask your provider for a monthly AI allowance.
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border p-4">
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<span className="text-sm font-medium">This month</span>
|
||||
<span className="text-sm text-gray-600">{money(s.usedCents)} of {money(s.capCents)} · renews on {renewsText(s.renewsOn)}</span>
|
||||
</div>
|
||||
<div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-gray-100" role="progressbar" aria-label="AI allowance used" aria-valuenow={s.usedPercent} aria-valuemin={0} aria-valuemax={100}>
|
||||
<div className={`h-full ${s.usedPercent >= 80 ? "bg-amber-500" : "bg-violet-500"}`} style={{ width: `${s.usedPercent}%` }} />
|
||||
</div>
|
||||
{s.capReached && <p className="mt-2 text-sm text-amber-800">The allowance is used up: the AI buttons are disabled until {renewsText(s.renewsOn)}, or until your provider raises it.</p>}
|
||||
{!s.available && <p className="mt-2 text-sm text-amber-800">The provider's Hub can't be reached right now, so AI is unavailable. Everything else works as usual.</p>}
|
||||
<p className="mt-2 text-xs text-gray-500">Admins get an email when 80% is used.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<h3 className="mb-2 font-medium">Helpers</h3>
|
||||
<ul className="divide-y rounded-lg border">
|
||||
{HELPERS.map(h => (
|
||||
<li key={h.key} className="flex items-center justify-between gap-3 p-3">
|
||||
<div>
|
||||
<label htmlFor={`ai-${h.key}`} className="text-sm font-medium">{h.label}</label>
|
||||
<p className="text-xs text-gray-500">{h.where}</p>
|
||||
</div>
|
||||
<input id={`ai-${h.key}`} type="checkbox" className="h-4 w-4" disabled={busy} checked={usage.settings.helpers[h.key]} onChange={e => save({ [h.key]: e.target.checked })} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<form className="flex flex-wrap items-end gap-3" onSubmit={e => { e.preventDefault(); save({}, Math.max(0, parseInt(limit, 10) || 0)); }}>
|
||||
<div>
|
||||
<label htmlFor="ai-daily-limit" className="block text-sm font-medium">Most uses per person per day</label>
|
||||
<input id="ai-daily-limit" type="number" min={0} max={1000} className="mt-1 w-28 rounded-lg border px-3 py-2 text-sm" value={limit} onChange={e => setLimit(e.target.value)} />
|
||||
<p className="mt-1 text-xs text-gray-500">0 = no limit. Guards against one person using up the month.</p>
|
||||
</div>
|
||||
<button className="rounded-lg bg-brand-600 px-3 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-60" disabled={busy}>Save limit</button>
|
||||
</form>
|
||||
{msg && <p className={`text-sm ${msg.ok ? "text-green-700" : "text-red-700"}`} role="status">{msg.text}</p>}
|
||||
|
||||
{s.enabled && (
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<div>
|
||||
<h3 className="mb-2 font-medium">By person this month</h3>
|
||||
{usage.people.length === 0 ? <p className="text-sm text-gray-500">Nobody has used AI yet this month.</p> : (
|
||||
<table className="w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Person</th><th>Uses</th><th className="text-right">Cost</th></tr></thead>
|
||||
<tbody>{usage.people.map(p => <tr key={p.userId || "removed"} className="border-t"><td className="py-1">{p.name}</td><td>{p.uses}</td><td className="text-right">{money(p.chargedCents)}</td></tr>)}</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="mb-2 font-medium">By helper this month</h3>
|
||||
{usage.helpers.length === 0 ? <p className="text-sm text-gray-500">—</p> : (
|
||||
<table className="w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Helper</th><th>Uses</th><th className="text-right">Cost</th></tr></thead>
|
||||
<tbody>{usage.helpers.map(h => <tr key={h.helper} className="border-t"><td className="py-1">{HELPERS.find(x => x.key === h.helper)?.label || h.helper}</td><td>{h.uses}</td><td className="text-right">{money(h.chargedCents)}</td></tr>)}</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
{usage.days.length > 0 && (
|
||||
<div className="md:col-span-2">
|
||||
<h3 className="mb-2 font-medium">Per day</h3>
|
||||
<div className="flex h-20 items-end gap-1" aria-label="AI cost per day this month">
|
||||
{usage.days.map(d => <div key={d.day} title={`${d.day}: ${d.uses} uses, ${money(d.chargedCents)}`} className="flex-1 rounded-t bg-violet-300" style={{ height: `${Math.max(4, (d.chargedCents / maxDay) * 100)}%` }} />)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-gray-500">
|
||||
Requests go through your provider's Hub to Anthropic (Claude) in the United States. Only what a helper needs is sent — never names, contact details, medical or children's information — and nothing is kept by the provider. Add Anthropic to your operator register (Admin → Privacy) when you start using AI.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user