WIP 2.0.0: the five AI helpers' API
src/ai/helpers.ts: instructions, schemas and inputs for draft event, summarise report (people-free reports only), draft message, summarise feedback (no names, access-logged) and improve text. Contact details are swapped for placeholders before sending and restored after; every helper gets today's date; weekday clashes and break-even over capacity are checked in code. v2 routes /ai/draft-event and friends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -24,6 +24,15 @@ and this project follows [Semantic Versioning](https://semver.org/).
|
||||
operator register, switched off until a site uses AI. Migration `20261030120000_ai_helpers`.
|
||||
- v2 errors have a new code, `UNAVAILABLE` (503), for when the Hub or the AI service can't be
|
||||
reached.
|
||||
- **The five AI helpers' API** (supervisors and admins): `POST /api/v2/ai/draft-event` (the event
|
||||
form from a description, with ticket options, early bird, schedule and a budget from the notes),
|
||||
`/ai/summarise-report` (reports without people in them only), `/ai/draft-message` (email or
|
||||
WhatsApp, with `{{name}}` and the event placeholders), `/ai/summarise-feedback` (an event's
|
||||
feedback, sent without who answered; recorded in the access log) and `/ai/improve-text`
|
||||
(improve, shorter, or only fix mistakes). Every helper is told today's date. Email addresses,
|
||||
phone numbers and ID numbers in what's sent are swapped for placeholders and put back in the
|
||||
answer, so they never leave the site. Two checks are worked out in code as well as by the AI: a
|
||||
weekday that doesn't match its date, and costs a full event can't cover.
|
||||
|
||||
## [1.51.17] - 2026-10-30 — security release
|
||||
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* The five AI helpers (roadmap §15): each one's instructions, the shape of its answer, and what it
|
||||
* sends. Run through `runHelper` (./index.ts), which goes via the Hub.
|
||||
*
|
||||
* What leaves the site (POPIA): only what a helper needs, and never names, contact details,
|
||||
* medical or children's information.
|
||||
* - Email addresses, phone numbers and ID numbers in any free text are swapped for placeholders
|
||||
* like [[CONTACT1]] before sending, and put back in the answer (`protect` / `restore`).
|
||||
* - Reports: only those without people in them (REPORTS_WITHOUT_PEOPLE).
|
||||
* - Feedback: ratings, choice counts and comments, never who answered.
|
||||
*
|
||||
* Lessons from the October 2026 trial, built in: every helper is told today's date, and the checks
|
||||
* that matter most (a weekday that doesn't match its date, an event that loses money when full)
|
||||
* are worked out here in code as well, not left to the model.
|
||||
*/
|
||||
|
||||
import { ApiError } from '../v2/errors';
|
||||
import { runHelper, type AiStatus } from './index';
|
||||
|
||||
// ─── Dates ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const SAST_MS = 2 * 3600 * 1000;
|
||||
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
||||
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
||||
|
||||
/** "Today is Friday 30 October 2026." in South African time. */
|
||||
export function todayLine(now = new Date()): string {
|
||||
const d = new Date(now.getTime() + SAST_MS);
|
||||
return `Today is ${WEEKDAYS[d.getUTCDay()]} ${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}.`;
|
||||
}
|
||||
|
||||
// ─── Keeping contact details on the site ──────────────────────────────────────
|
||||
|
||||
const CONTACT_RE = [
|
||||
/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, // email
|
||||
/(?:\+27|\b0)(?:[\s-]?\d){9}\b/g, // South African phone numbers
|
||||
/\b\d{13}\b/g, // South African ID numbers
|
||||
];
|
||||
|
||||
export type Protected = { text: string; found: Map<string, string> };
|
||||
|
||||
/** Swap contact details for [[CONTACTn]], so they never leave the site. */
|
||||
export function protect(text: string, found: Map<string, string> = new Map()): Protected {
|
||||
let out = text;
|
||||
for (const re of CONTACT_RE) {
|
||||
out = out.replace(re, match => {
|
||||
for (const [k, v] of found) if (v === match) return k;
|
||||
const key = `[[CONTACT${found.size + 1}]]`;
|
||||
found.set(key, match);
|
||||
return key;
|
||||
});
|
||||
}
|
||||
return { text: out, found };
|
||||
}
|
||||
|
||||
/** Put the contact details back into an answer (strings anywhere inside it). */
|
||||
export function restore<T>(value: T, found: Map<string, string>): T {
|
||||
if (!found.size) return value;
|
||||
const fix = (s: string) => s.replace(/\[\[CONTACT\d+\]\]/g, k => found.get(k) ?? k);
|
||||
const walk = (v: unknown): unknown => (typeof v === 'string' ? fix(v) : Array.isArray(v) ? v.map(walk) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)])) : v);
|
||||
return walk(value) as T;
|
||||
}
|
||||
|
||||
const KEEP_PLACEHOLDERS = 'Text like [[CONTACT1]] stands for a contact detail the site keeps private: copy it exactly where it belongs and never change it.';
|
||||
|
||||
// ─── Schemas ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const str = { type: 'string' };
|
||||
const num = { type: 'number' };
|
||||
const int = { type: 'integer' };
|
||||
const bool = { type: 'boolean' };
|
||||
const list = (items: object) => ({ type: 'array', items });
|
||||
const obj = (properties: Record<string, object>, descriptions: Record<string, string> = {}) => ({
|
||||
type: 'object', additionalProperties: false, required: Object.keys(properties),
|
||||
properties: Object.fromEntries(Object.entries(properties).map(([k, v]) => [k, descriptions[k] ? { ...v, description: descriptions[k] } : v])),
|
||||
});
|
||||
|
||||
// ─── 1. Draft an event ────────────────────────────────────────────────────────
|
||||
|
||||
export type EventDraftAnswer = {
|
||||
title: string; summary: string; description: string;
|
||||
startDate: string; startTime: string; endDate: string; endTime: string;
|
||||
location: string; capacity: number; needsParentalConsent: boolean; ageGroup: string;
|
||||
ticketOptions: { name: string; priceRand: number; description: string; earlyBirdPriceRand: number; earlyBirdUntil: string }[];
|
||||
sessions: { date: string; startTime: string; endTime: string; label: string }[];
|
||||
costs: { item: string; basis: string; amountRand: number }[];
|
||||
checks: string[];
|
||||
};
|
||||
|
||||
const EVENT_SCHEMA = obj({
|
||||
title: str, summary: str, description: str,
|
||||
startDate: str, startTime: str, endDate: str, endTime: str,
|
||||
location: str, capacity: int, needsParentalConsent: bool, ageGroup: str,
|
||||
ticketOptions: list(obj({ name: str, priceRand: num, description: str, earlyBirdPriceRand: num, earlyBirdUntil: str }, { earlyBirdPriceRand: '0 when there is none', earlyBirdUntil: 'YYYY-MM-DD, or empty' })),
|
||||
sessions: list(obj({ date: str, startTime: str, endTime: str, label: str })),
|
||||
costs: list(obj({ item: str, basis: str, amountRand: num }, { basis: 'How it is worked out, e.g. "R180 × 60 people × 2 nights"', amountRand: 'Total for this line at full capacity' })),
|
||||
checks: list(str),
|
||||
}, {
|
||||
summary: 'One sentence for the event card',
|
||||
description: 'The public event page: 2–4 short paragraphs, plain text',
|
||||
startDate: 'YYYY-MM-DD', endDate: 'YYYY-MM-DD', startTime: 'HH:MM, 24-hour, or empty', endTime: 'HH:MM, 24-hour, or empty',
|
||||
capacity: 'Places in total; 0 when not given',
|
||||
sessions: 'Only for an event that meets on several separate dates people attend, like a weekly course: one row per date. Empty for a single event, even one over a weekend.',
|
||||
checks: 'Things to look at before publishing: missing details, contradictions, money that does not add up. Empty if none.',
|
||||
});
|
||||
|
||||
const EVENT_SYSTEM = (now: Date) => [
|
||||
'You help a church events team set up an event in Cross Events, an event registration system. From the organiser\'s notes, fill in the event form.',
|
||||
todayLine(now),
|
||||
'- Title: short and clear. Description: for the public event page, warm and clear, 2–4 short paragraphs, plain text (no markdown): who it is for, what happens, what is included, what to bring if known.',
|
||||
'- South African rand; 24-hour times. Dates as YYYY-MM-DD: the next time that date comes round after today, unless the notes give a year.',
|
||||
'- If a weekday in the notes does not match its date, keep the date and say so in "checks".',
|
||||
'- Ticket options: the prices the notes give, with any early-bird price and its last day. One option when only one price is given.',
|
||||
'- Leave anything the notes do not give empty (or 0) rather than guess, including times.',
|
||||
'- Costs: one line per cost the notes give, worked out at full capacity, showing how. Never invent costs.',
|
||||
'- Never invent names, phone numbers, email addresses or links.',
|
||||
KEEP_PLACEHOLDERS,
|
||||
].join('\n');
|
||||
|
||||
/** Weekdays written next to dates in the notes ("Fri 14 March") that don't match the year used. */
|
||||
export function weekdayClashes(notes: string, year: number): string[] {
|
||||
const out: string[] = [];
|
||||
const re = /\b(mon|tue|wed|thu|fri|sat|sun)[a-z]*\.?,?\s+(\d{1,2})(?:st|nd|rd|th)?\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*/gi;
|
||||
for (const m of notes.matchAll(re)) {
|
||||
const day = Number(m[2]);
|
||||
const month = MONTHS.findIndex(x => x.toLowerCase().startsWith(m[3].toLowerCase()));
|
||||
const actual = new Date(Date.UTC(year, month, day)).getUTCDay();
|
||||
const said = WEEKDAYS.findIndex(w => w.toLowerCase().startsWith(m[1].toLowerCase()));
|
||||
if (actual !== said) out.push(`The notes say ${WEEKDAYS[said]} ${day} ${MONTHS[month]}, but ${day} ${MONTHS[month]} ${year} is a ${WEEKDAYS[actual]}. Check the dates.`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** R34 800 — plain spaces between thousands, as the AI writes them (en-ZA uses a no-break space). */
|
||||
const rands = (n: number) => `R${Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ')}`;
|
||||
|
||||
/** Money and date checks worked out in code, whatever the model said. */
|
||||
export function eventWarnings(notes: string, a: EventDraftAnswer): string[] {
|
||||
const out: string[] = [];
|
||||
const year = Number(a.startDate.slice(0, 4));
|
||||
if (year > 2000) out.push(...weekdayClashes(notes, year));
|
||||
if (a.startDate && a.endDate && `${a.endDate}T${a.endTime || '23:59'}` < `${a.startDate}T${a.startTime || '00:00'}`) out.push('The end is before the start.');
|
||||
const costs = a.costs.reduce((s, c) => s + (Number(c.amountRand) || 0), 0);
|
||||
const main = a.ticketOptions[0];
|
||||
if (costs > 0 && main?.priceRand > 0) {
|
||||
const breakEven = Math.ceil(costs / main.priceRand);
|
||||
if (a.capacity > 0 && breakEven > a.capacity) {
|
||||
const full = a.capacity * main.priceRand;
|
||||
const early = main.earlyBirdPriceRand > 0 ? a.capacity * main.earlyBirdPriceRand : null;
|
||||
out.push(`The costs in the notes come to ${rands(costs)}, which needs ${breakEven} places at ${rands(main.priceRand)} — more than the ${a.capacity} available. Even full, the event takes ${rands(full)}${early ? ` (${rands(early)} if everyone books early)` : ''}, ${rands(costs - full)} short.`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function draftEvent(userId: string, notes: string, now = new Date()): Promise<{ draft: EventDraftAnswer; warnings: string[]; totalCostRand: number; breakEvenPlaces: number | null; status: AiStatus }> {
|
||||
const p = protect(notes);
|
||||
const { output, status } = await runHelper('draft_event', userId, { system: EVENT_SYSTEM(now), input: p.text, schema: EVENT_SCHEMA, maxTokens: 4000, effort: 'low' });
|
||||
const draft = restore(output as EventDraftAnswer, p.found);
|
||||
const totalCostRand = draft.costs.reduce((s, c) => s + (Number(c.amountRand) || 0), 0);
|
||||
const price = draft.ticketOptions[0]?.priceRand || 0;
|
||||
return { draft, warnings: eventWarnings(notes, draft), totalCostRand, breakEvenPlaces: totalCostRand > 0 && price > 0 ? Math.ceil(totalCostRand / price) : null, status };
|
||||
}
|
||||
|
||||
// ─── 2. Summarise a report ────────────────────────────────────────────────────
|
||||
|
||||
/** Reports with no people in them: only these can be summarised (keys from ReportCatalog). */
|
||||
export const REPORTS_WITHOUT_PEOPLE = ['seriesComparison', 'regTypes', 'usage', 'revenue', 'regStatus', 'donations', 'funnel', 'discounts', 'cashup', 'financeReport', 'profitReport'] as const;
|
||||
const MAX_ROWS = 400;
|
||||
|
||||
export type ReportInput = {
|
||||
reportKey: string;
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
stats?: { label: string; value: string | number }[];
|
||||
columns: string[];
|
||||
rows: (string | number)[][];
|
||||
};
|
||||
|
||||
export type ReportSummary = { headline: string; insights: { title: string; detail: string }[]; watchOut: string[] };
|
||||
|
||||
const REPORT_SCHEMA = obj({ headline: str, insights: list(obj({ title: str, detail: str })), watchOut: list(str) }, { watchOut: 'Things that need someone to act; empty if none' });
|
||||
|
||||
const REPORT_SYSTEM = (now: Date) => [
|
||||
'You summarise a report for the leaders of a church that uses Cross Events, an event registration system. They are busy volunteers and staff, not analysts.',
|
||||
todayLine(now),
|
||||
'- A one-sentence headline, then 3–5 insights: trends, changes against earlier periods, outliers, and anything that needs action.',
|
||||
'- Use the report\'s numbers; work out percentages and differences where they help, and get them right. Never invent figures or causes; when you suggest a cause, say it is only a possibility.',
|
||||
'- Mind the dates against today: an event that has already happened can\'t still be promoted or paid for before it starts.',
|
||||
'- Plain, friendly South African English. Amounts in rand like R18 900.',
|
||||
].join('\n');
|
||||
|
||||
/** The report as compact text: stats, then the table as pipe-separated rows. */
|
||||
export function reportText(r: ReportInput): string {
|
||||
const lines = [`Report: ${r.title}`];
|
||||
if (r.subtitle) lines.push(r.subtitle);
|
||||
for (const s of r.stats || []) lines.push(`${s.label}: ${s.value}`);
|
||||
lines.push(`Columns: ${r.columns.join(' | ')}`);
|
||||
for (const row of r.rows.slice(0, MAX_ROWS)) lines.push(row.map(c => String(c ?? '').replace(/\s+/g, ' ')).join(' | '));
|
||||
if (r.rows.length > MAX_ROWS) lines.push(`(${r.rows.length - MAX_ROWS} more rows not shown)`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export async function summariseReport(userId: string, report: ReportInput, now = new Date()): Promise<{ summary: ReportSummary; status: AiStatus }> {
|
||||
if (!(REPORTS_WITHOUT_PEOPLE as readonly string[]).includes(report.reportKey)) {
|
||||
throw Object.assign(new ApiError('FORBIDDEN', 'This report lists people, so it can\'t be sent to the AI. Summaries work on totals-only reports.'), { reason: 'AI_REPORT_HAS_PEOPLE' });
|
||||
}
|
||||
const p = protect(reportText(report));
|
||||
const { output, status } = await runHelper('summarise_report', userId, { system: REPORT_SYSTEM(now), input: p.text, schema: REPORT_SCHEMA, maxTokens: 2000, effort: 'low' });
|
||||
return { summary: restore(output as ReportSummary, p.found), status };
|
||||
}
|
||||
|
||||
// ─── 3. Draft a message ───────────────────────────────────────────────────────
|
||||
|
||||
export type MessageAnswer = { subject: string; body: string };
|
||||
|
||||
const MESSAGE_SCHEMA = obj({ subject: str, body: str }, { subject: 'Empty for WhatsApp' });
|
||||
|
||||
const MESSAGE_SYSTEM = (channel: 'email' | 'whatsapp', now: Date) => [
|
||||
'You write messages from a church events team to people registered for an event, from the organiser\'s short note.',
|
||||
todayLine(now),
|
||||
channel === 'whatsapp'
|
||||
? '- WhatsApp: plain text, at most 3 short sentences, at most one emoji. "subject" is empty.'
|
||||
: '- Email: a clear subject, then the body in short plain-text paragraphs, the most important thing first. Start with "Hi {{name}}," and end with "The events team".',
|
||||
'- Use {{name}} for the person\'s first name. {{event.title}}, {{event.start}} and {{event.link}} are filled in for each event, if useful.',
|
||||
'- Use only the facts in the note and the event details; never invent times, places, prices, links or contact details, or add advice the note doesn\'t give.',
|
||||
'- Spell carefully: this goes to everyone registered.',
|
||||
KEEP_PLACEHOLDERS,
|
||||
].join('\n');
|
||||
|
||||
export type EventFacts = { title: string; start: string; location: string | null };
|
||||
|
||||
export async function draftMessage(userId: string, input: { channel: 'email' | 'whatsapp'; note: string; event?: EventFacts | null }, now = new Date()): Promise<{ message: MessageAnswer; status: AiStatus }> {
|
||||
const p = protect(input.note);
|
||||
const facts = input.event ? `\n\nEvent: ${input.event.title}, ${input.event.start}${input.event.location ? `, at ${input.event.location}` : ''}` : '';
|
||||
const { output, status } = await runHelper('draft_message', userId, {
|
||||
system: MESSAGE_SYSTEM(input.channel, now), input: `Note: ${p.text}${facts}`, schema: MESSAGE_SCHEMA, maxTokens: input.channel === 'whatsapp' ? 600 : 1500, effort: 'low',
|
||||
});
|
||||
const message = restore(output as MessageAnswer, p.found);
|
||||
return { message: input.channel === 'whatsapp' ? { subject: '', body: message.body } : message, status };
|
||||
}
|
||||
|
||||
// ─── 4. Summarise feedback ────────────────────────────────────────────────────
|
||||
|
||||
export type FeedbackQuestion = { label: string; type: string; answered: number; average?: number | null; counts?: { label: string; value: number }[]; texts?: string[] };
|
||||
export type FeedbackSummary = { overall: string; liked: { theme: string; mentions: number }[]; improve: { theme: string; mentions: number }[]; quotes: string[]; nextTime: string[] };
|
||||
|
||||
const FEEDBACK_SCHEMA = obj({
|
||||
overall: str, liked: list(obj({ theme: str, mentions: int })), improve: list(obj({ theme: str, mentions: int })), quotes: list(str), nextTime: list(str),
|
||||
}, { liked: 'Most-mentioned first', improve: 'Most-mentioned first', quotes: 'Up to 3 short comments, copied exactly' });
|
||||
|
||||
const FEEDBACK_SYSTEM = [
|
||||
'You summarise the feedback people gave after a church event, for the team that ran it.',
|
||||
'- "overall": two sentences on how it went, using the ratings.',
|
||||
'- "liked" and "improve": the main themes, most-mentioned first, each with how many comments raised it. Count carefully: a comment counts once per theme.',
|
||||
'- "quotes": up to 3 short comments that capture the feedback well, copied exactly.',
|
||||
'- "nextTime": 2–4 concrete suggestions for next time, based only on the feedback.',
|
||||
'- The comments are anonymous; never guess who wrote one.',
|
||||
KEEP_PLACEHOLDERS,
|
||||
].join('\n');
|
||||
const MAX_COMMENTS = 400;
|
||||
const MAX_COMMENT = 600;
|
||||
|
||||
/** The feedback as text: each question with its average or counts, and the comments numbered. */
|
||||
export function feedbackText(event: { title: string }, responses: number, invited: number, questions: FeedbackQuestion[]): string {
|
||||
const lines = [`Event: ${event.title}`, `Responses: ${responses}${invited ? ` of ${invited} asked` : ''}`];
|
||||
let n = 0;
|
||||
for (const q of questions) {
|
||||
if (q.average != null) lines.push(`${q.label} — average ${q.average} (${q.answered} answers)`);
|
||||
else if (q.counts) lines.push(`${q.label} — ${q.counts.map(c => `${c.label}: ${c.value}`).join(', ')}`);
|
||||
else if (q.texts?.length) {
|
||||
lines.push(`${q.label} — comments:`);
|
||||
for (const t of q.texts) {
|
||||
if (n++ >= MAX_COMMENTS) break;
|
||||
lines.push(`${n}. ${t.replace(/\s+/g, ' ').slice(0, MAX_COMMENT)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export async function summariseFeedback(userId: string, input: { event: { title: string }; responses: number; invited: number; questions: FeedbackQuestion[] }): Promise<{ summary: FeedbackSummary; status: AiStatus }> {
|
||||
const p = protect(feedbackText(input.event, input.responses, input.invited, input.questions));
|
||||
const { output, status } = await runHelper('summarise_feedback', userId, { system: FEEDBACK_SYSTEM, input: p.text, schema: FEEDBACK_SCHEMA, maxTokens: 2000, effort: 'low' });
|
||||
return { summary: restore(output as FeedbackSummary, p.found), status };
|
||||
}
|
||||
|
||||
// ─── 5. Improve this text ─────────────────────────────────────────────────────
|
||||
|
||||
export const IMPROVE_MODES = { improve: 'Make it clear and friendly', shorter: 'Make it shorter', fix: 'Only fix spelling and grammar' } as const;
|
||||
export type ImproveMode = keyof typeof IMPROVE_MODES;
|
||||
export type ImproveAnswer = { text: string; changes: string[] };
|
||||
|
||||
const IMPROVE_SCHEMA = obj({ text: str, changes: list(str) }, { changes: 'A short list of what changed and why' });
|
||||
|
||||
const IMPROVE_SYSTEM = (mode: ImproveMode, where: string) => [
|
||||
`You improve text a church events team wrote for ${where}.`,
|
||||
mode === 'fix'
|
||||
? '- Only fix spelling, grammar and punctuation. Change nothing else.'
|
||||
: mode === 'shorter'
|
||||
? '- Make it noticeably shorter and easier to scan, fixing spelling and grammar too.'
|
||||
: '- Fix spelling, grammar and punctuation, and make it clear and friendly, about the same length or shorter.',
|
||||
'- Keep every fact (times, dates, prices, places, ages) exactly; add none.',
|
||||
'- Plain text, no markdown. Keep the writer\'s warmth, and any humour that works in public. Keep placeholders like {{name}} exactly.',
|
||||
KEEP_PLACEHOLDERS,
|
||||
].join('\n');
|
||||
|
||||
const WHERE = { description: 'an event page', banner: 'a short banner across the top of the website', message: 'a message to people registered for an event' } as const;
|
||||
export type ImproveWhere = keyof typeof WHERE;
|
||||
|
||||
export async function improveText(userId: string, input: { text: string; mode: ImproveMode; where: ImproveWhere }): Promise<{ result: ImproveAnswer; status: AiStatus }> {
|
||||
const p = protect(input.text);
|
||||
const { output, status } = await runHelper('improve_text', userId, { system: IMPROVE_SYSTEM(input.mode, WHERE[input.where]), input: p.text, schema: IMPROVE_SCHEMA, maxTokens: Math.min(8000, 600 + Math.ceil(input.text.length / 2)), effort: 'low' });
|
||||
return { result: restore(output as ImproveAnswer, p.found), status };
|
||||
}
|
||||
@@ -18,6 +18,7 @@ const ACCESS_ACTIONS = {
|
||||
kids_rooms: 'Kids check-in desk or room opened',
|
||||
kids_offline: 'Kids check-in list downloaded for offline use',
|
||||
volunteer_roster: 'Volunteer roster opened',
|
||||
ai_feedback: 'Feedback comments summarised by the AI helper',
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { z } from 'zod';
|
||||
import { defineRoute } from '../route';
|
||||
import { single } from '../paging';
|
||||
import { id } from '../schemas';
|
||||
import { notFound } from '../errors';
|
||||
import { prisma } from '../legacy';
|
||||
import { aiStatus, getAiSettings, saveAiSettings, usageThisMonth, HELPERS, clearAiStatusCache } from '../../ai';
|
||||
import { draftEvent, summariseReport, draftMessage, summariseFeedback, improveText, REPORTS_WITHOUT_PEOPLE, type FeedbackQuestion } from '../../ai/helpers';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */
|
||||
const { campusIndependent } = require('../../utils/campusScope') as { campusIndependent(reason: string): any };
|
||||
const { campusIndependent, scopeBody } = require('../../utils/campusScope') as { campusIndependent(reason: string): any; scopeBody(targets: [string, string][], opts?: object): any };
|
||||
const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string };
|
||||
const { logDataAccess } = require('../../utils/accessLog') as { logDataAccess(req: unknown, entry: { action: string; eventId?: string; records?: number }): Promise<void> };
|
||||
const feedbackUtils = require('../../utils/feedback') as { summarise(fields: unknown[], answers: { fieldId: string; value: string }[]): any[] };
|
||||
|
||||
const helperFlags = z.object(Object.fromEntries(HELPERS.map(h => [h, z.boolean()])) as Record<(typeof HELPERS)[number], z.ZodBoolean>);
|
||||
|
||||
@@ -75,3 +81,109 @@ export const updateAiSettings = defineRoute({
|
||||
return { data: await saveAiSettings(body, user!, getClientIp(req)) };
|
||||
},
|
||||
});
|
||||
|
||||
// ─── The helpers ──────────────────────────────────────────────────────────────
|
||||
// Each answer is a suggestion for a person to check: nothing is saved or sent by these routes.
|
||||
|
||||
const withStatus = <T extends z.ZodType>(output: T) => single(z.object({ output, status }));
|
||||
const HELPER_SCOPE = 'campusIndependent (an AI suggestion from what is sent; nothing is read or changed)';
|
||||
const helperAccess = { access: 'supervisor' as const, campusScope: HELPER_SCOPE, middleware: [campusIndependent('an AI suggestion from what is sent; nothing is read or changed')] };
|
||||
const AI_DESCRIPTION = 'Goes through the Cross Events Hub, which counts it against the site\'s monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.';
|
||||
|
||||
const textList = z.array(z.string());
|
||||
const eventDraft = z.object({
|
||||
title: z.string(), summary: z.string(), description: z.string(),
|
||||
startDate: z.string(), startTime: z.string(), endDate: z.string(), endTime: z.string(),
|
||||
location: z.string(), capacity: z.number(), needsParentalConsent: z.boolean(), ageGroup: z.string(),
|
||||
ticketOptions: z.array(z.object({ name: z.string(), priceRand: z.number(), description: z.string(), earlyBirdPriceRand: z.number(), earlyBirdUntil: z.string() })),
|
||||
sessions: z.array(z.object({ date: z.string(), startTime: z.string(), endTime: z.string(), label: z.string() })),
|
||||
costs: z.array(z.object({ item: z.string(), basis: z.string(), amountRand: z.number() })),
|
||||
checks: textList,
|
||||
});
|
||||
|
||||
export const aiDraftEvent = defineRoute({
|
||||
method: 'post', path: '/ai/draft-event', tag: 'AI', summary: 'Draft an event from a description',
|
||||
description: `Fills in the event form from the organiser's notes. \`warnings\` are checked in code (a weekday that doesn't match its date, costs that a full event can't cover); \`draft.checks\` are the AI's own. ${AI_DESCRIPTION}`,
|
||||
...helperAccess,
|
||||
body: z.object({ notes: z.string().trim().min(10).max(4000) }),
|
||||
response: withStatus(z.object({ draft: eventDraft, warnings: textList, totalCostRand: z.number(), breakEvenPlaces: z.number().nullable() })),
|
||||
async handler({ body, user }) {
|
||||
const { status: s, ...output } = await draftEvent(user!.id, body.notes);
|
||||
return { data: { output, status: s } };
|
||||
},
|
||||
});
|
||||
|
||||
export const aiSummariseReport = defineRoute({
|
||||
method: 'post', path: '/ai/summarise-report', tag: 'AI', summary: 'Summarise a report',
|
||||
description: `A few plain-language insights on a report as it is on screen. Only reports without people in them: ${REPORTS_WITHOUT_PEOPLE.join(', ')}. ${AI_DESCRIPTION}`,
|
||||
...helperAccess,
|
||||
body: z.object({
|
||||
reportKey: z.enum(REPORTS_WITHOUT_PEOPLE),
|
||||
title: z.string().max(300), subtitle: z.string().max(500).optional(),
|
||||
stats: z.array(z.object({ label: z.string().max(200), value: z.union([z.string().max(200), z.number()]) })).max(40).optional(),
|
||||
columns: z.array(z.string().max(200)).max(40),
|
||||
rows: z.array(z.array(z.union([z.string().max(500), z.number(), z.null()]).transform(v => v ?? ''))).max(5000),
|
||||
}),
|
||||
response: withStatus(z.object({ headline: z.string(), insights: z.array(z.object({ title: z.string(), detail: z.string() })), watchOut: textList })),
|
||||
async handler({ body, user }) {
|
||||
const { summary, status: s } = await summariseReport(user!.id, body);
|
||||
return { data: { output: summary, status: s } };
|
||||
},
|
||||
});
|
||||
|
||||
export const aiDraftMessage = defineRoute({
|
||||
method: 'post', path: '/ai/draft-message', tag: 'AI', summary: 'Draft an email or WhatsApp message',
|
||||
description: `Turns a short note into a message, using {{name}} and the event placeholders. With \`eventId\`, the event's title, start and place are given to the AI as facts. ${AI_DESCRIPTION}`,
|
||||
access: 'supervisor', campusScope: 'scopeBody(eventId)', middleware: [scopeBody([['eventId', 'event']])],
|
||||
body: z.object({ channel: z.enum(['email', 'whatsapp']), note: z.string().trim().min(3).max(3000), eventId: id.optional() }),
|
||||
response: withStatus(z.object({ subject: z.string(), body: z.string() })),
|
||||
async handler({ body, user }) {
|
||||
let event = null;
|
||||
if (body.eventId) {
|
||||
const e = await prisma.event.findUnique({ where: { id: body.eventId }, select: { title: true, startDate: true, location: true } });
|
||||
if (!e) throw notFound('The event');
|
||||
event = { title: e.title, start: e.startDate.toLocaleString('en-ZA', { timeZone: 'Africa/Johannesburg', weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' }), location: e.location };
|
||||
}
|
||||
const { message, status: s } = await draftMessage(user!.id, { channel: body.channel, note: body.note, event });
|
||||
return { data: { output: message, status: s } };
|
||||
},
|
||||
});
|
||||
|
||||
export const aiSummariseFeedback = defineRoute({
|
||||
method: 'post', path: '/ai/summarise-feedback', tag: 'AI', summary: 'Summarise an event\'s feedback',
|
||||
description: `Themes, what people liked, what to improve and suggestions, from the event's feedback. Sent without who answered; contact details in comments are kept back. Recorded in the access log. ${AI_DESCRIPTION}`,
|
||||
access: 'supervisor', campusScope: 'scopeBody(eventId)', middleware: [scopeBody([['eventId', 'event']])],
|
||||
body: z.object({ eventId: id }),
|
||||
response: withStatus(z.object({
|
||||
overall: z.string(), liked: z.array(z.object({ theme: z.string(), mentions: z.number() })), improve: z.array(z.object({ theme: z.string(), mentions: z.number() })),
|
||||
quotes: textList, nextTime: textList, responses: z.number(),
|
||||
})),
|
||||
async handler({ body, user, req }) {
|
||||
const form = await prisma.feedbackForm.findUnique({
|
||||
where: { eventId: body.eventId },
|
||||
include: { event: { select: { title: true } }, fields: { orderBy: { order: 'asc' } }, responses: { include: { answers: true } }, _count: { select: { invites: true } } },
|
||||
});
|
||||
if (!form) throw notFound('Feedback for this event');
|
||||
if (!form.responses.length) throw Object.assign(notFound('Feedback answers for this event'), { reason: 'AI_NOTHING_TO_SUMMARISE' });
|
||||
// Never who answered: only the answers.
|
||||
const answers = form.responses.flatMap(r => r.answers.map(a => ({ fieldId: a.fieldId, value: a.value })));
|
||||
const questions: FeedbackQuestion[] = feedbackUtils.summarise(form.fields, answers).map((q: any) => ({
|
||||
label: q.label, type: q.type, answered: q.answered, average: q.average, counts: q.counts, texts: q.texts?.map((t: { value: string }) => t.value),
|
||||
}));
|
||||
await logDataAccess(req, { action: 'ai_feedback', eventId: body.eventId, records: form.responses.length });
|
||||
const { summary, status: s } = await summariseFeedback(user!.id, { event: form.event, responses: form.responses.length, invited: form._count.invites, questions });
|
||||
return { data: { output: { ...summary, responses: form.responses.length }, status: s } };
|
||||
},
|
||||
});
|
||||
|
||||
export const aiImproveText = defineRoute({
|
||||
method: 'post', path: '/ai/improve-text', tag: 'AI', summary: 'Improve a piece of text',
|
||||
description: `Fixes spelling and grammar and makes it clearer (\`improve\`), shorter (\`shorter\`) or only fixes mistakes (\`fix\`), keeping every fact. ${AI_DESCRIPTION}`,
|
||||
...helperAccess,
|
||||
body: z.object({ text: z.string().trim().min(3).max(8000), mode: z.enum(['improve', 'shorter', 'fix']).default('improve'), where: z.enum(['description', 'banner', 'message']).default('description') }),
|
||||
response: withStatus(z.object({ text: z.string(), changes: textList })),
|
||||
async handler({ body, user }) {
|
||||
const { result, status: s } = await improveText(user!.id, body);
|
||||
return { data: { output: result, status: s } };
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
// The five AI helpers (2.0): what they send, what they keep back, and the checks done in code.
|
||||
|
||||
const mockRun = jest.fn();
|
||||
jest.mock('../src/ai/index', () => ({ runHelper: (...a: unknown[]) => mockRun(...a) }));
|
||||
jest.mock('../src/config/db', () => ({}));
|
||||
|
||||
import {
|
||||
todayLine, protect, restore, weekdayClashes, eventWarnings, reportText, feedbackText,
|
||||
draftEvent, summariseReport, draftMessage, improveText, type EventDraftAnswer,
|
||||
} from '../src/ai/helpers';
|
||||
|
||||
const status = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: {} };
|
||||
const now = new Date('2026-10-30T08:00:00Z');
|
||||
|
||||
beforeEach(() => mockRun.mockReset());
|
||||
|
||||
const camp: EventDraftAnswer = {
|
||||
title: 'Rooted Youth Camp', summary: '', description: '', startDate: '2027-03-14', startTime: '18:00', endDate: '2027-03-16', endTime: '14:00',
|
||||
location: 'Camp Wartburg', capacity: 60, needsParentalConsent: true, ageGroup: 'Grades 8–12',
|
||||
ticketOptions: [{ name: 'Camper', priceRand: 450, description: '', earlyBirdPriceRand: 400, earlyBirdUntil: '2027-01-31' }],
|
||||
sessions: [],
|
||||
costs: [
|
||||
{ item: 'Venue', basis: 'R180 × 60 × 2', amountRand: 21600 }, { item: 'Bus', basis: '', amountRand: 6500 },
|
||||
{ item: 'Speaker gift', basis: '', amountRand: 1000 }, { item: 'T-shirts', basis: 'R95 × 60', amountRand: 5700 },
|
||||
],
|
||||
checks: [],
|
||||
};
|
||||
|
||||
describe('today and contact details', () => {
|
||||
test('today is given in South African time', () => {
|
||||
expect(todayLine(now)).toBe('Today is Friday 30 October 2026.');
|
||||
expect(todayLine(new Date('2026-10-30T22:30:00Z'))).toBe('Today is Saturday 31 October 2026.');
|
||||
});
|
||||
|
||||
test('emails, phone numbers and ID numbers never leave the site, and come back in the answer', () => {
|
||||
const p = protect('Call Sarah on 082 555 1234 or +27 21 555 9876, email youth@church.co.za. ID 9001015009087. Bus R6 500 at 07:30.');
|
||||
// Emails are found first, then phone numbers, then ID numbers.
|
||||
expect(p.text).toBe('Call Sarah on [[CONTACT2]] or [[CONTACT3]], email [[CONTACT1]]. ID [[CONTACT4]]. Bus R6 500 at 07:30.');
|
||||
expect(restore({ body: 'Questions? [[CONTACT1]] or [[CONTACT2]].', list: ['[[CONTACT3]]'] }, p.found))
|
||||
.toEqual({ body: 'Questions? youth@church.co.za or 082 555 1234.', list: ['+27 21 555 9876'] });
|
||||
});
|
||||
|
||||
test('the same detail twice gets one placeholder', () => {
|
||||
expect(protect('a@b.co.za and again a@b.co.za').text).toBe('[[CONTACT1]] and again [[CONTACT1]]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checks done in code', () => {
|
||||
test('a weekday that does not match its date', () => {
|
||||
expect(weekdayClashes('Youth camp Fri 14 March to Sun 16 March', 2027)).toEqual([
|
||||
'The notes say Friday 14 March, but 14 March 2027 is a Sunday. Check the dates.',
|
||||
'The notes say Sunday 16 March, but 16 March 2027 is a Tuesday. Check the dates.',
|
||||
]);
|
||||
expect(weekdayClashes('Fri 14 March', 2025)).toEqual([]);
|
||||
});
|
||||
|
||||
test('an event that loses money even when full', () => {
|
||||
expect(eventWarnings('', camp)).toEqual([
|
||||
'The costs in the notes come to R34 800, which needs 78 places at R450 — more than the 60 available. Even full, the event takes R27 000 (R24 000 if everyone books early), R7 800 short.',
|
||||
]);
|
||||
expect(eventWarnings('', { ...camp, capacity: 80 })).toEqual([]);
|
||||
expect(eventWarnings('', { ...camp, endDate: '2027-03-13' })).toContain('The end is before the start.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('what the helpers send', () => {
|
||||
test('draft an event: today\'s date, a schema, contact details kept back; code warnings added', async () => {
|
||||
mockRun.mockResolvedValue({ output: { ...camp, description: 'Questions? [[CONTACT1]]' }, status });
|
||||
const r = await draftEvent('u1', 'Youth camp Fri 14 March, R450, 60 places. Questions: youth@church.co.za', now);
|
||||
const [helper, user, req] = mockRun.mock.calls[0];
|
||||
expect([helper, user]).toEqual(['draft_event', 'u1']);
|
||||
expect(req.system).toContain('Today is Friday 30 October 2026.');
|
||||
expect(req.input).not.toContain('youth@church.co.za');
|
||||
expect(req.schema.required).toContain('ticketOptions');
|
||||
expect(r.draft.description).toBe('Questions? youth@church.co.za');
|
||||
expect(r.totalCostRand).toBe(34800);
|
||||
expect(r.breakEvenPlaces).toBe(78);
|
||||
expect(r.warnings.some(w => w.includes('is a Sunday'))).toBe(true);
|
||||
expect(r.warnings.some(w => w.includes('R7 800 short'))).toBe(true);
|
||||
});
|
||||
|
||||
test('summarise a report: only reports without people', async () => {
|
||||
await expect(summariseReport('u1', { reportKey: 'payments', title: 'Payments', columns: ['User'], rows: [['Jane']] })).rejects.toMatchObject({ reason: 'AI_REPORT_HAS_PEOPLE' });
|
||||
expect(mockRun).not.toHaveBeenCalled();
|
||||
mockRun.mockResolvedValue({ output: { headline: 'h', insights: [], watchOut: [] }, status });
|
||||
await summariseReport('u1', { reportKey: 'revenue', title: 'Revenue Summary', stats: [{ label: 'Total', value: 'R66 550' }], columns: ['Event', 'Amount'], rows: [['Camp', 'R16 650']] }, now);
|
||||
expect(mockRun.mock.calls[0][2].input).toBe('Report: Revenue Summary\nTotal: R66 550\nColumns: Event | Amount\nCamp | R16 650');
|
||||
});
|
||||
|
||||
test('report text is capped at 400 rows', () => {
|
||||
const t = reportText({ reportKey: 'usage', title: 'T', columns: ['A'], rows: Array.from({ length: 450 }, (_, i) => [i]) });
|
||||
expect(t).toContain('(50 more rows not shown)');
|
||||
expect(t.split('\n')).toHaveLength(2 + 400 + 1);
|
||||
});
|
||||
|
||||
test('feedback text: averages, counts and numbered comments, no names', () => {
|
||||
expect(feedbackText({ title: 'Women\'s Conference' }, 112, 186, [
|
||||
{ label: 'Overall', type: 'rating', answered: 112, average: 4.4 },
|
||||
{ label: 'Come again?', type: 'yes_no', answered: 100, counts: [{ label: 'Yes', value: 90 }, { label: 'No', value: 10 }] },
|
||||
{ label: 'Comments', type: 'text', answered: 2, texts: ['Hall B sound please fix it.', 'Loved the worship!'] },
|
||||
])).toBe([
|
||||
'Event: Women\'s Conference', 'Responses: 112 of 186 asked', 'Overall — average 4.4 (112 answers)', 'Come again? — Yes: 90, No: 10',
|
||||
'Comments — comments:', '1. Hall B sound please fix it.', '2. Loved the worship!',
|
||||
].join('\n'));
|
||||
});
|
||||
|
||||
test('draft a message: WhatsApp has no subject; the event is given as facts', async () => {
|
||||
mockRun.mockResolvedValue({ output: { subject: 'ignored', body: 'Hi {{name}}!' }, status });
|
||||
const r = await draftMessage('u1', { channel: 'whatsapp', note: 'bring a sleeping bag', event: { title: 'Youth Camp', start: 'Friday 14 March 2027, 18:00', location: 'Camp Wartburg' } }, now);
|
||||
expect(r.message).toEqual({ subject: '', body: 'Hi {{name}}!' });
|
||||
expect(mockRun.mock.calls[0][2].input).toBe('Note: bring a sleeping bag\n\nEvent: Youth Camp, Friday 14 March 2027, 18:00, at Camp Wartburg');
|
||||
expect(mockRun.mock.calls[0][2].system).toContain('WhatsApp');
|
||||
});
|
||||
|
||||
test('improve text: the mode and where it goes shape the instructions', async () => {
|
||||
mockRun.mockResolvedValue({ output: { text: 'Fixed.', changes: [] }, status });
|
||||
await improveText('u1', { text: 'join us for are anual fun day', mode: 'fix', where: 'banner' });
|
||||
const req = mockRun.mock.calls[0][2];
|
||||
expect(req.system).toContain('a short banner across the top of the website');
|
||||
expect(req.system).toContain('Only fix spelling, grammar and punctuation');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
+594
@@ -6994,6 +6994,116 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/ai/draft-event": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Draft an event from a description
|
||||
* @description Fills in the event form from the organiser's notes. `warnings` are checked in code (a weekday that doesn't match its date, costs that a full event can't cover); `draft.checks` are the AI's own. Goes through the Cross Events Hub, which counts it against the site's monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.
|
||||
*
|
||||
* **Who:** Supervisors and admins.
|
||||
*/
|
||||
post: operations["postAiDraft-event"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/ai/summarise-report": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Summarise a report
|
||||
* @description A few plain-language insights on a report as it is on screen. Only reports without people in them: seriesComparison, regTypes, usage, revenue, regStatus, donations, funnel, discounts, cashup, financeReport, profitReport. Goes through the Cross Events Hub, which counts it against the site's monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.
|
||||
*
|
||||
* **Who:** Supervisors and admins.
|
||||
*/
|
||||
post: operations["postAiSummarise-report"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/ai/draft-message": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Draft an email or WhatsApp message
|
||||
* @description Turns a short note into a message, using {{name}} and the event placeholders. With `eventId`, the event's title, start and place are given to the AI as facts. Goes through the Cross Events Hub, which counts it against the site's monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.
|
||||
*
|
||||
* **Who:** Supervisors and admins.
|
||||
*/
|
||||
post: operations["postAiDraft-message"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/ai/summarise-feedback": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Summarise an event's feedback
|
||||
* @description Themes, what people liked, what to improve and suggestions, from the event's feedback. Sent without who answered; contact details in comments are kept back. Recorded in the access log. Goes through the Cross Events Hub, which counts it against the site's monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.
|
||||
*
|
||||
* **Who:** Supervisors and admins.
|
||||
*/
|
||||
post: operations["postAiSummarise-feedback"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/ai/improve-text": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Improve a piece of text
|
||||
* @description Fixes spelling and grammar and makes it clearer (`improve`), shorter (`shorter`) or only fixes mistakes (`fix`), keeping every fact. Goes through the Cross Events Hub, which counts it against the site's monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.
|
||||
*
|
||||
* **Who:** Supervisors and admins.
|
||||
*/
|
||||
post: operations["postAiImprove-text"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
}
|
||||
export type webhooks = Record<string, never>;
|
||||
export interface components {
|
||||
@@ -30010,4 +30120,488 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
"postAiDraft-event": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
notes: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
output: {
|
||||
draft: {
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
startDate: string;
|
||||
startTime: string;
|
||||
endDate: string;
|
||||
endTime: string;
|
||||
location: string;
|
||||
capacity: number;
|
||||
needsParentalConsent: boolean;
|
||||
ageGroup: string;
|
||||
ticketOptions: {
|
||||
name: string;
|
||||
priceRand: number;
|
||||
description: string;
|
||||
earlyBirdPriceRand: number;
|
||||
earlyBirdUntil: string;
|
||||
}[];
|
||||
sessions: {
|
||||
date: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
label: string;
|
||||
}[];
|
||||
costs: {
|
||||
item: string;
|
||||
basis: string;
|
||||
amountRand: number;
|
||||
}[];
|
||||
checks: string[];
|
||||
};
|
||||
warnings: string[];
|
||||
totalCostRand: number;
|
||||
breakEvenPlaces: number | null;
|
||||
};
|
||||
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;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
"postAiSummarise-report": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
/** @enum {string} */
|
||||
reportKey: "seriesComparison" | "regTypes" | "usage" | "revenue" | "regStatus" | "donations" | "funnel" | "discounts" | "cashup" | "financeReport" | "profitReport";
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
stats?: {
|
||||
label: string;
|
||||
value: string | number;
|
||||
}[];
|
||||
columns: string[];
|
||||
rows: (string | number | null)[][];
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
output: {
|
||||
headline: string;
|
||||
insights: {
|
||||
title: string;
|
||||
detail: string;
|
||||
}[];
|
||||
watchOut: string[];
|
||||
};
|
||||
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;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
"postAiDraft-message": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
/** @enum {string} */
|
||||
channel: "email" | "whatsapp";
|
||||
note: string;
|
||||
eventId?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
output: {
|
||||
subject: string;
|
||||
body: string;
|
||||
};
|
||||
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;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
"postAiSummarise-feedback": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
eventId: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
output: {
|
||||
overall: string;
|
||||
liked: {
|
||||
theme: string;
|
||||
mentions: number;
|
||||
}[];
|
||||
improve: {
|
||||
theme: string;
|
||||
mentions: number;
|
||||
}[];
|
||||
quotes: string[];
|
||||
nextTime: string[];
|
||||
responses: number;
|
||||
};
|
||||
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;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
"postAiImprove-text": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
text: string;
|
||||
/**
|
||||
* @default improve
|
||||
* @enum {string}
|
||||
*/
|
||||
mode?: "improve" | "shorter" | "fix";
|
||||
/**
|
||||
* @default description
|
||||
* @enum {string}
|
||||
*/
|
||||
where?: "description" | "banner" | "message";
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
output: {
|
||||
text: string;
|
||||
changes: string[];
|
||||
};
|
||||
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;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user