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:
2026-10-30 17:38:16 +02:00
co-authored by Claude Opus 5.5
parent cbdc7ad10a
commit d4f54f2cc8
7 changed files with 2423 additions and 1 deletions
+113 -1
View File
@@ -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 } };
},
});