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
+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}` })),