Files
joshuaandClaude Opus 5.5 40fa8b2dba 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>
2026-11-02 18:42:27 +02:00

140 lines
8.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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: 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');
});
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');
expect(mockRun.mock.calls[0][2].system).toContain('{{event.title}}');
});
test('draft a message without an event: no event placeholders offered', async () => {
mockRun.mockResolvedValue({ output: { subject: 'S', body: 'Hi {{name}}' }, status });
await draftMessage('u1', { channel: 'email', note: 'the breakfast moves to the hotel' }, now);
const system = mockRun.mock.calls[0][2].system;
expect(system).toContain('Use no other {{…}} placeholders');
expect(system).not.toContain('{{event.title}}');
});
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');
});
});