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:
2026-10-30 09:25:36 +02:00
co-authored by Claude Opus 5.5
parent 838a6b3c3d
commit dbec47aae3
19 changed files with 1760 additions and 19 deletions
@@ -8,7 +8,7 @@ import { ApiError, resolveToApiOrigin } from "@/lib/api";
import { apiV2Raw, apiV2Data } from "@/lib/apiV2";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook } from "lucide-react";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles } from "lucide-react";
import { ColorPickerField } from "@/components/admin/ColorPickerField";
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
import { BackupsTab } from "@/components/admin/BackupsTab";
@@ -16,6 +16,7 @@ import { JobsTab } from "@/components/admin/JobsTab";
import { PaymentsTab } from "@/components/admin/PaymentsTab";
import { LicenceTab } from "@/components/admin/LicenceTab";
import { WebhooksTab } from "@/components/admin/WebhooksTab";
import { AiTab } from "@/components/admin/AiTab";
import { CampusesTab } from "@/components/admin/CampusesTab";
import { extractDominantColors } from "@/lib/extractColors";
import { mapsSearchUrl } from "@/lib/maps";
@@ -23,7 +24,7 @@ import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { uploadImage } from "@/lib/eventSetup";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence" | "ai";
const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "organisation", label: "Organisation", icon: Building2 },
@@ -38,6 +39,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "backups", label: "Backups", icon: DatabaseBackup },
{ id: "jobs", label: "Background jobs", icon: Timer },
{ id: "licence", label: "Licence", icon: KeyRound },
{ id: "ai", label: "AI", icon: Sparkles },
];
const inputCls =
@@ -717,6 +719,7 @@ function SiteSettingsPageInner() {
{activeTab === "webhooks" && <WebhooksTab active={activeTab === "webhooks"} />}
{activeTab === "jobs" && <JobsTab active={activeTab === "jobs"} />}
{activeTab === "licence" && <LicenceTab active={activeTab === "licence"} />}
{activeTab === "ai" && <AiTab active={activeTab === "ai"} />}
{activeTab === "campuses" && <CampusesTab active={activeTab === "campuses"} />}
</div>
@@ -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&apos;t part of this site&apos;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&apos;s Hub can&apos;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&apos;s Hub to Anthropic (Claude) in the United States. Only what a helper needs is sent — never names, contact details, medical or children&apos;s information — and nothing is kept by the provider. Add Anthropic to your operator register (Admin → Privacy) when you start using AI.
</p>
</div>
);
}
@@ -0,0 +1,51 @@
"use client";
import React, { useId } from "react";
import { Loader2, Sparkles } from "lucide-react";
import { useAiStatus } from "@/hooks/useAiStatus";
import { disabledReason, type AiHelper } from "@/lib/ai";
/**
* A button for one AI helper. Not shown at all when the site has no AI (or for anyone but
* supervisors and admins); shown but disabled, with the reason, when this month's allowance is
* used up, the Hub can't be reached, or the helper is switched off in Site settings → AI.
*/
export function AiButton({ helper, onClick, busy = false, children, className = "", size = "md" }: {
helper: AiHelper;
onClick: () => void;
busy?: boolean;
children: React.ReactNode;
className?: string;
size?: "sm" | "md";
}) {
const status = useAiStatus();
const reasonId = useId();
if (!status?.enabled) return null;
const reason = disabledReason(status, helper);
const pad = size === "sm" ? "px-2 py-1 text-xs" : "px-3 py-1.5 text-sm";
return (
<span className="inline-flex flex-col">
<button
type="button"
onClick={onClick}
disabled={busy || !!reason}
title={reason || undefined}
aria-describedby={reason ? reasonId : undefined}
className={`inline-flex items-center gap-1.5 rounded-lg border border-violet-200 bg-violet-50 font-medium text-violet-800 hover:bg-violet-100 disabled:cursor-not-allowed disabled:opacity-60 ${pad} ${className}`}
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : <Sparkles className="h-4 w-4" aria-hidden />}
{children}
</button>
{reason && <span id={reasonId} className="sr-only">{reason}</span>}
</span>
);
}
/** Under every AI result: a person checks it before anything is saved or sent. */
export function AiNotice({ className = "" }: { className?: string }) {
return (
<p className={`flex items-center gap-1.5 text-xs text-violet-800 ${className}`}>
<Sparkles className="h-3.5 w-3.5" aria-hidden /> AI suggestion — check it before saving.
</p>
);
}
@@ -0,0 +1,24 @@
"use client";
import { useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { currentAiStatus, loadAiStatus, subscribeAiStatus, type AiStatus } from "@/lib/ai";
/**
* Whether to show the AI buttons, shared across the page (one request per page load). Null while
* loading, and for anyone who isn't a supervisor or admin — AI helpers are theirs only.
*/
export function useAiStatus(): AiStatus | null {
const { user, token } = useAuth();
const allowed = !!token && (user?.role === "admin" || user?.role === "supervisor");
const [status, setStatus] = useState<AiStatus | null>(() => (allowed ? currentAiStatus() : null));
useEffect(() => {
if (!allowed || !token) return;
const off = subscribeAiStatus(setStatus);
loadAiStatus(token).then(setStatus).catch(() => {});
return off;
}, [allowed, token]);
return allowed ? status : null;
}
+76
View File
@@ -0,0 +1,76 @@
import { apiV2Data, apiV2Raw } from "@/lib/apiV2";
import type { V2Result } from "@/lib/apiV2";
/**
* AI helpers (2.0). The site calls AI through the Cross Events Hub, which keeps a monthly
* allowance in rand per licence. One status per page load is shared by every AI button
* (`useAiStatus`), and every helper call refreshes it — so the buttons disable straight after the
* call that used up the allowance.
*/
export type AiStatus = V2Result<"/ai/status", "get">["data"];
export type AiHelper = keyof AiStatus["helpers"];
const OFF: AiStatus = {
enabled: false, capReached: false, available: true, capCents: 0, usedCents: 0, usedPercent: 0, renewsOn: null,
helpers: { draft_event: false, summarise_report: false, draft_message: false, summarise_feedback: false, improve_text: false },
};
let current: AiStatus | null = null;
let loading: Promise<AiStatus> | null = null;
const listeners = new Set<(s: AiStatus) => void>();
function publish(s: AiStatus) {
current = s;
listeners.forEach(l => l(s));
}
/** The status, fetched once per page load (staff never see AI, so they never ask). */
export function loadAiStatus(authToken: string, { fresh = false } = {}): Promise<AiStatus> {
if (current && !fresh) return Promise.resolve(current);
if (!loading || fresh) {
loading = (apiV2Data("get", "/ai/status", { authToken }) as Promise<AiStatus>)
.then(s => { publish(s); return s; })
.catch(() => { publish(OFF); return OFF; })
.finally(() => { loading = null; });
}
return loading;
}
export function subscribeAiStatus(fn: (s: AiStatus) => void): () => void {
listeners.add(fn);
return () => { listeners.delete(fn); };
}
export function currentAiStatus(): AiStatus | null {
return current;
}
/** "1 December" from "2026-12-01". */
export function renewsText(renewsOn: string | null): string {
if (!renewsOn) return "next month";
return new Date(`${renewsOn}T12:00:00Z`).toLocaleDateString("en-ZA", { day: "numeric", month: "long" });
}
/** What the button's tooltip says when it can't be used. */
export function disabledReason(s: AiStatus, helper: AiHelper): string | null {
if (s.capReached) return `This month's AI allowance is used up — it renews on ${renewsText(s.renewsOn)}.`;
if (!s.available) return "AI is unavailable right now. Try again in a few minutes.";
if (!s.helpers[helper]) return "This AI helper is switched off in Site settings → AI.";
return null;
}
/**
* Run a helper (`POST /api/v2/ai/<helper>`). Resolves to its answer; throws the API error (with
* a message written for people). Either way the shared status is refreshed.
*/
export async function runAi<T>(helper: AiHelper, body: object, authToken: string): Promise<T> {
try {
const res = await apiV2Raw<{ output: T; status: AiStatus }>("post", `/ai/${helper.replace(/_/g, "-")}`, { authToken, body });
publish(res.status);
return res.output;
} catch (e) {
loadAiStatus(authToken, { fresh: true }).catch(() => {});
throw e;
}
}
@@ -97,6 +97,9 @@
},
{
"name": "Webhooks"
},
{
"name": "AI"
}
],
"paths": {
@@ -39939,6 +39942,548 @@
}
}
}
},
"/ai/status": {
"get": {
"tags": [
"AI"
],
"summary": "Whether to show the AI buttons",
"description": "Hidden when `enabled` is false; shown but disabled when `capReached` (until `renewsOn`, or until the allowance is raised). Cached for a minute; every AI call refreshes it.\n\n**Who:** Supervisors and admins.",
"operationId": "getAiStatus",
"security": [
{
"bearerAuth": []
}
],
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean",
"description": "false: hide the AI buttons (the licence has no AI, or the site isn't connected to the Hub)"
},
"capReached": {
"type": "boolean",
"description": "true: show the buttons disabled until `renewsOn`"
},
"available": {
"type": "boolean",
"description": "false: the Hub couldn't be reached just now"
},
"capCents": {
"type": "number",
"description": "The monthly allowance, in cents"
},
"usedCents": {
"type": "number",
"description": "Used this month, in cents (fractions of a cent)"
},
"usedPercent": {
"type": "number"
},
"renewsOn": {
"description": "YYYY-MM-DD",
"type": [
"string",
"null"
]
},
"helpers": {
"type": "object",
"properties": {
"draft_event": {
"type": "boolean"
},
"summarise_report": {
"type": "boolean"
},
"draft_message": {
"type": "boolean"
},
"summarise_feedback": {
"type": "boolean"
},
"improve_text": {
"type": "boolean"
}
},
"required": [
"draft_event",
"summarise_report",
"draft_message",
"summarise_feedback",
"improve_text"
],
"additionalProperties": false,
"description": "Each helper switched on or off in Site settings → AI"
}
},
"required": [
"enabled",
"capReached",
"available",
"capCents",
"usedCents",
"usedPercent",
"renewsOn",
"helpers"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/ai/usage": {
"get": {
"tags": [
"AI"
],
"summary": "AI use this month",
"description": "For Site settings → AI: the allowance, this site's switches, and this month's use per person, per helper and per day.\n\n**Who:** Admins only.",
"operationId": "getAiUsage",
"security": [
{
"bearerAuth": []
}
],
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"status": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean",
"description": "false: hide the AI buttons (the licence has no AI, or the site isn't connected to the Hub)"
},
"capReached": {
"type": "boolean",
"description": "true: show the buttons disabled until `renewsOn`"
},
"available": {
"type": "boolean",
"description": "false: the Hub couldn't be reached just now"
},
"capCents": {
"type": "number",
"description": "The monthly allowance, in cents"
},
"usedCents": {
"type": "number",
"description": "Used this month, in cents (fractions of a cent)"
},
"usedPercent": {
"type": "number"
},
"renewsOn": {
"description": "YYYY-MM-DD",
"type": [
"string",
"null"
]
},
"helpers": {
"type": "object",
"properties": {
"draft_event": {
"type": "boolean"
},
"summarise_report": {
"type": "boolean"
},
"draft_message": {
"type": "boolean"
},
"summarise_feedback": {
"type": "boolean"
},
"improve_text": {
"type": "boolean"
}
},
"required": [
"draft_event",
"summarise_report",
"draft_message",
"summarise_feedback",
"improve_text"
],
"additionalProperties": false,
"description": "Each helper switched on or off in Site settings → AI"
}
},
"required": [
"enabled",
"capReached",
"available",
"capCents",
"usedCents",
"usedPercent",
"renewsOn",
"helpers"
],
"additionalProperties": false
},
"settings": {
"type": "object",
"properties": {
"helpers": {
"type": "object",
"properties": {
"draft_event": {
"type": "boolean"
},
"summarise_report": {
"type": "boolean"
},
"draft_message": {
"type": "boolean"
},
"summarise_feedback": {
"type": "boolean"
},
"improve_text": {
"type": "boolean"
}
},
"required": [
"draft_event",
"summarise_report",
"draft_message",
"summarise_feedback",
"improve_text"
],
"additionalProperties": false
},
"dailyLimitPerPerson": {
"type": "integer",
"minimum": 0,
"maximum": 1000,
"description": "0 = no limit"
}
},
"required": [
"helpers",
"dailyLimitPerPerson"
],
"additionalProperties": false
},
"people": {
"type": "array",
"items": {
"type": "object",
"properties": {
"uses": {
"type": "integer",
"minimum": -9007199254740991,
"maximum": 9007199254740991
},
"chargedCents": {
"type": "number"
},
"userId": {
"type": [
"string",
"null"
]
},
"name": {
"type": "string"
}
},
"required": [
"uses",
"chargedCents",
"userId",
"name"
],
"additionalProperties": false
}
},
"helpers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"uses": {
"type": "integer",
"minimum": -9007199254740991,
"maximum": 9007199254740991
},
"chargedCents": {
"type": "number"
},
"helper": {
"type": "string"
}
},
"required": [
"uses",
"chargedCents",
"helper"
],
"additionalProperties": false
}
},
"days": {
"type": "array",
"items": {
"type": "object",
"properties": {
"uses": {
"type": "integer",
"minimum": -9007199254740991,
"maximum": 9007199254740991
},
"chargedCents": {
"type": "number"
},
"day": {
"type": "string"
}
},
"required": [
"uses",
"chargedCents",
"day"
],
"additionalProperties": false
}
}
},
"required": [
"status",
"settings",
"people",
"helpers",
"days"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/ai/settings": {
"put": {
"tags": [
"AI"
],
"summary": "Switch helpers on or off, and set a daily limit",
"description": "**Who:** Admins only.",
"operationId": "putAiSettings",
"security": [
{
"bearerAuth": []
}
],
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"helpers": {
"type": "object",
"properties": {
"draft_event": {
"type": "boolean"
},
"summarise_report": {
"type": "boolean"
},
"draft_message": {
"type": "boolean"
},
"summarise_feedback": {
"type": "boolean"
},
"improve_text": {
"type": "boolean"
}
}
},
"dailyLimitPerPerson": {
"type": "integer",
"minimum": 0,
"maximum": 1000
}
}
}
}
}
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"helpers": {
"type": "object",
"properties": {
"draft_event": {
"type": "boolean"
},
"summarise_report": {
"type": "boolean"
},
"draft_message": {
"type": "boolean"
},
"summarise_feedback": {
"type": "boolean"
},
"improve_text": {
"type": "boolean"
}
},
"required": [
"draft_event",
"summarise_report",
"draft_message",
"summarise_feedback",
"improve_text"
],
"additionalProperties": false
},
"dailyLimitPerPerson": {
"type": "integer",
"minimum": 0,
"maximum": 1000,
"description": "0 = no limit"
}
},
"required": [
"helpers",
"dailyLimitPerPerson"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"400": {
"description": "Validation failed (VALIDATION_FAILED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
}
},
"components": {
@@ -39973,6 +40518,7 @@
"CONFLICT",
"RATE_LIMITED",
"READ_ONLY",
"UNAVAILABLE",
"INTERNAL"
]
},
+290 -1
View File
@@ -6930,6 +6930,70 @@ export interface paths {
patch?: never;
trace?: never;
};
"/ai/status": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Whether to show the AI buttons
* @description Hidden when `enabled` is false; shown but disabled when `capReached` (until `renewsOn`, or until the allowance is raised). Cached for a minute; every AI call refreshes it.
*
* **Who:** Supervisors and admins.
*/
get: operations["getAiStatus"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/ai/usage": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* AI use this month
* @description For Site settings → AI: the allowance, this site's switches, and this month's use per person, per helper and per day.
*
* **Who:** Admins only.
*/
get: operations["getAiUsage"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/ai/settings": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
/**
* Switch helpers on or off, and set a daily limit
* @description **Who:** Admins only.
*/
put: operations["putAiSettings"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
@@ -6937,7 +7001,7 @@ export interface components {
Error: {
error: {
/** @enum {string} */
code: "VALIDATION_FAILED" | "UNAUTHENTICATED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "RATE_LIMITED" | "READ_ONLY" | "INTERNAL";
code: "VALIDATION_FAILED" | "UNAUTHENTICATED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "RATE_LIMITED" | "READ_ONLY" | "UNAVAILABLE" | "INTERNAL";
message: string;
/** @description Per-field problems (VALIDATION_FAILED only) */
fields?: {
@@ -29721,4 +29785,229 @@ export interface operations {
};
};
};
getAiStatus: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @description false: hide the AI buttons (the licence has no AI, or the site isn't connected to the Hub) */
enabled: boolean;
/** @description true: show the buttons disabled until `renewsOn` */
capReached: boolean;
/** @description false: the Hub couldn't be reached just now */
available: boolean;
/** @description The monthly allowance, in cents */
capCents: number;
/** @description Used this month, in cents (fractions of a cent) */
usedCents: number;
usedPercent: number;
/** @description YYYY-MM-DD */
renewsOn: string | null;
/** @description Each helper switched on or off in Site settings → AI */
helpers: {
draft_event: boolean;
summarise_report: boolean;
draft_message: boolean;
summarise_feedback: boolean;
improve_text: boolean;
};
};
};
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
getAiUsage: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
status: {
/** @description false: hide the AI buttons (the licence has no AI, or the site isn't connected to the Hub) */
enabled: boolean;
/** @description true: show the buttons disabled until `renewsOn` */
capReached: boolean;
/** @description false: the Hub couldn't be reached just now */
available: boolean;
/** @description The monthly allowance, in cents */
capCents: number;
/** @description Used this month, in cents (fractions of a cent) */
usedCents: number;
usedPercent: number;
/** @description YYYY-MM-DD */
renewsOn: string | null;
/** @description Each helper switched on or off in Site settings → AI */
helpers: {
draft_event: boolean;
summarise_report: boolean;
draft_message: boolean;
summarise_feedback: boolean;
improve_text: boolean;
};
};
settings: {
helpers: {
draft_event: boolean;
summarise_report: boolean;
draft_message: boolean;
summarise_feedback: boolean;
improve_text: boolean;
};
/** @description 0 = no limit */
dailyLimitPerPerson: number;
};
people: {
uses: number;
chargedCents: number;
userId: string | null;
name: string;
}[];
helpers: {
uses: number;
chargedCents: number;
helper: string;
}[];
days: {
uses: number;
chargedCents: number;
day: string;
}[];
};
};
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
putAiSettings: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
helpers?: {
draft_event?: boolean;
summarise_report?: boolean;
draft_message?: boolean;
summarise_feedback?: boolean;
improve_text?: boolean;
};
dailyLimitPerPerson?: number;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
helpers: {
draft_event: boolean;
summarise_report: boolean;
draft_message: boolean;
summarise_feedback: boolean;
improve_text: boolean;
};
/** @description 0 = no limit */
dailyLimitPerPerson: number;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
}
+1 -1
View File
@@ -61,7 +61,7 @@ export const COMMAND_PAGES: CommandPage[] = [
...([
["organisation", "Organisation"], ["campuses", "Campuses"], ["branding", "Branding"], ["notifications", "Notifications"],
["email", "Email"], ["legal", "Legal"], ["whatsapp", "WhatsApp"], ["payments", "Payments"], ["webhooks", "Webhooks"],
["backups", "Backups"], ["jobs", "Background jobs"], ["licence", "Licence & updates"],
["backups", "Backups"], ["jobs", "Background jobs"], ["licence", "Licence & updates"], ["ai", "AI helpers"],
] as const).map(([tab, label]): CommandPage => ({ group: "Settings", label: `Settings: ${label}`, href: `/dashboard/admin/settings?tab=${tab}`, roles: ADM, keywords: "site settings" })),
// Reports — every report in the catalogue
...REPORTS.map((r): CommandPage => ({ group: "Reports", label: `Report: ${r.label}`, href: `/dashboard/supervisor/reports?report=${r.key}`, roles: SUP, keywords: `report ${r.category} ${r.description}` })),