Summarise this report on every report (2.0.1)
The eight reports that list people get the AI summary too, sent as anonymised totals built on the screen (aiReportData.ts): no names, contact details, notes or comments; consent and medical only as counts. The server refuses personal columns on those reports and logs each summary in the access log (ai_report; sensitive for consent and medical). Roadmap §18: 2.0.1, then crosscode.co.za, then 2.1.0 (AI helpers on the Consent log and Access log). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "event-management-backend",
|
||||
"version": "2.0.0",
|
||||
"version": "2.0.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "event-management-backend",
|
||||
"version": "2.0.0",
|
||||
"version": "2.0.1",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "event-management-backend",
|
||||
"version": "2.0.0",
|
||||
"version": "2.0.1",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -164,10 +164,26 @@ export async function draftEvent(userId: string, notes: string, now = new Date()
|
||||
|
||||
// ─── 2. Summarise a report ────────────────────────────────────────────────────
|
||||
|
||||
/** Reports with no people in them: only these can be summarised (keys from ReportCatalog). */
|
||||
/** Reports with no people in them: sent as they are on screen (keys from ReportCatalog). */
|
||||
export const REPORTS_WITHOUT_PEOPLE = ['seriesComparison', 'regTypes', 'usage', 'revenue', 'regStatus', 'donations', 'funnel', 'discounts', 'cashup', 'financeReport', 'profitReport'] as const;
|
||||
/**
|
||||
* Reports that list people: the screen sends these as anonymised totals instead (no names, contact
|
||||
* details, notes or comments; medical and consent only as counts). The server checks the columns too.
|
||||
*/
|
||||
export const REPORTS_WITH_PEOPLE = ['payments', 'attendees', 'revenueDetailed', 'masterOrders', 'cashupAudit', 'consentStatus', 'feedbackSummary', 'medicalList'] as const;
|
||||
export const REPORT_KEYS = [...REPORTS_WITHOUT_PEOPLE, ...REPORTS_WITH_PEOPLE] as const;
|
||||
/** Children's or special information: an AI summary of one is a sensitive access-log entry. */
|
||||
export const SENSITIVE_REPORTS: readonly string[] = ['consentStatus', 'medicalList'];
|
||||
/** Column headings that would carry a person: refused on a report with people in it. */
|
||||
const PERSONAL_COLUMN = /^(user|name|e-?mail|phone|cell|attendee|donor)$|^(parent|guardian|emergency|performed by|recorded by|registration ?id|date of birth|dob|medical$|notes?$|comments?$|signed)/i;
|
||||
const MAX_ROWS = 400;
|
||||
|
||||
/** The columns of a people report that would carry a person (none means it's safe to send). */
|
||||
export function personalColumns(r: { reportKey: string; columns: string[] }): string[] {
|
||||
if (!(REPORTS_WITH_PEOPLE as readonly string[]).includes(r.reportKey)) return [];
|
||||
return r.columns.filter(c => PERSONAL_COLUMN.test(c.trim()));
|
||||
}
|
||||
|
||||
export type ReportInput = {
|
||||
reportKey: string;
|
||||
title: string;
|
||||
@@ -187,6 +203,7 @@ const REPORT_SYSTEM = (now: Date) => [
|
||||
'- 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.',
|
||||
'- Reports about people come as anonymised totals: names, contact details and notes are left out on purpose, so don\'t ask for them or guess who is who.',
|
||||
'- Plain, friendly South African English. Amounts in rand like R18 900.',
|
||||
].join('\n');
|
||||
|
||||
@@ -202,8 +219,10 @@ export function reportText(r: ReportInput): string {
|
||||
}
|
||||
|
||||
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' });
|
||||
if (!(REPORT_KEYS as readonly string[]).includes(report.reportKey)) throw new ApiError('VALIDATION_FAILED', `There is no report called ${report.reportKey}.`);
|
||||
const personal = personalColumns(report);
|
||||
if (personal.length) {
|
||||
throw Object.assign(new ApiError('FORBIDDEN', `This report still has people in it (${personal.join(', ')}), so it can't be sent to the AI. Only anonymised totals are summarised.`), { 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' });
|
||||
|
||||
@@ -19,6 +19,7 @@ const ACCESS_ACTIONS = {
|
||||
kids_offline: 'Kids check-in list downloaded for offline use',
|
||||
volunteer_roster: 'Volunteer roster opened',
|
||||
ai_feedback: 'Feedback comments summarised by the AI helper',
|
||||
ai_report: 'Report summarised by the AI helper (anonymised totals)',
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,12 +5,14 @@ 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';
|
||||
import { draftEvent, summariseReport, draftMessage, summariseFeedback, improveText, REPORTS_WITHOUT_PEOPLE, REPORTS_WITH_PEOPLE, REPORT_KEYS, SENSITIVE_REPORTS, type FeedbackQuestion } from '../../ai/helpers';
|
||||
|
||||
const ACCESS_AI_REPORT = 'Report summarised by the AI helper (anonymised totals)';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */
|
||||
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 { logDataAccess } = require('../../utils/accessLog') as { logDataAccess(req: unknown, entry: { action: string; what?: string; eventId?: string; records?: number; sensitive?: boolean }): 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>);
|
||||
@@ -115,18 +117,21 @@ export const aiDraftEvent = defineRoute({
|
||||
|
||||
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}`,
|
||||
description: `A few plain-language insights on a report. Reports without people in them (${REPORTS_WITHOUT_PEOPLE.join(', ')}) are sent as they are on screen; reports that list people (${REPORTS_WITH_PEOPLE.join(', ')}) only as anonymised totals: a column that would carry a person (name, email, notes, …) is refused with \`AI_REPORT_HAS_PEOPLE\`, and each one is recorded in the access log. ${AI_DESCRIPTION}`,
|
||||
...helperAccess,
|
||||
body: z.object({
|
||||
reportKey: z.enum(REPORTS_WITHOUT_PEOPLE),
|
||||
reportKey: z.enum(REPORT_KEYS),
|
||||
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 }) {
|
||||
async handler({ body, user, req }) {
|
||||
const { summary, status: s } = await summariseReport(user!.id, body);
|
||||
if ((REPORTS_WITH_PEOPLE as readonly string[]).includes(body.reportKey)) {
|
||||
await logDataAccess(req, { action: 'ai_report', what: `${ACCESS_AI_REPORT}: ${body.title}`, records: body.rows.length, sensitive: SENSITIVE_REPORTS.includes(body.reportKey) });
|
||||
}
|
||||
return { data: { output: summary, status: s } };
|
||||
},
|
||||
});
|
||||
|
||||
@@ -79,10 +79,18 @@ describe('what the helpers send', () => {
|
||||
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' });
|
||||
test('summarise a report: people reports only as anonymised totals', async () => {
|
||||
for (const columns of [['Event', 'User', 'Amount'], ['Event', 'Email'], ['Event', 'Performed by', 'Notes'], ['Event', 'Attendee', 'Medical'], ['Parent / guardian']]) {
|
||||
await expect(summariseReport('u1', { reportKey: 'payments', title: 'Payments', columns, rows: [['Jane']] })).rejects.toMatchObject({ reason: 'AI_REPORT_HAS_PEOPLE' });
|
||||
}
|
||||
await expect(summariseReport('u1', { reportKey: 'nope', title: 'X', columns: ['A'], rows: [[1]] })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' });
|
||||
expect(mockRun).not.toHaveBeenCalled();
|
||||
mockRun.mockResolvedValue({ output: { headline: 'h', insights: [], watchOut: [] }, status });
|
||||
await summariseReport('u1', { reportKey: 'medicalList', title: 'Medical', columns: ['Event', 'Attendees', 'With allergies', 'With medical aid'], rows: [['Camp', 40, 6, 30]] }, now);
|
||||
await summariseReport('u1', { reportKey: 'feedbackSummary', title: 'Feedback', columns: ['Event', 'Question', 'Answered', 'Result'], rows: [['Camp', 'Overall', 12, '4.5 / 5']] }, now);
|
||||
expect(mockRun).toHaveBeenCalledTimes(2);
|
||||
mockRun.mockReset();
|
||||
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');
|
||||
});
|
||||
|
||||
@@ -700,13 +700,26 @@ describe('AI helpers (2.0)', () => {
|
||||
expect(mockRunHelper.mock.calls[0][0]).toBe('improve_text');
|
||||
});
|
||||
|
||||
test('summarise a report: reports with people in them are refused by validation', async () => {
|
||||
test('summarise a report: unknown reports fail validation, people columns are refused', async () => {
|
||||
signedIn = { id: 's1', role: 'supervisor' };
|
||||
expect((await request(app).post('/api/v2/ai/summarise-report').send({ reportKey: 'nope', title: 'X', columns: ['A'], rows: [[1]] })).status).toBe(400);
|
||||
const res = await request(app).post('/api/v2/ai/summarise-report').send({ reportKey: 'payments', title: 'Payments', columns: ['User'], rows: [['Jane']] });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error.reason).toBe('AI_REPORT_HAS_PEOPLE');
|
||||
expect(mockRunHelper).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('summarise a report: a people report as totals, with an access-log entry (sensitive for medical)', async () => {
|
||||
signedIn = { id: 's1', role: 'supervisor' };
|
||||
mockRunHelper.mockResolvedValue({ output: { headline: 'h', insights: [], watchOut: [] }, status: st });
|
||||
const res = await request(app).post('/api/v2/ai/summarise-report').send({ reportKey: 'medicalList', title: 'Medical & emergency list', columns: ['Event', 'Attendees', 'With allergies'], rows: [['Camp', 40, 6]] });
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockAccessLog).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ action: 'ai_report', records: 1, sensitive: true }));
|
||||
mockAccessLog.mockClear();
|
||||
await request(app).post('/api/v2/ai/summarise-report').send({ reportKey: 'revenue', title: 'Revenue', columns: ['Event', 'Amount'], rows: [['Camp', 100]] });
|
||||
expect(mockAccessLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('draft an event: the draft with warnings worked out in code', async () => {
|
||||
signedIn = { id: 's1', role: 'supervisor' };
|
||||
const draft = {
|
||||
|
||||
Reference in New Issue
Block a user