import express from 'express'; import request from 'supertest'; // /api/v2 (1.51.0): the route declarations validate requests, shape responses and errors the same // way everywhere, and produce the OpenAPI document. const mockDb = { event: { findMany: jest.fn(), count: jest.fn(), findFirst: jest.fn(), findUnique: jest.fn() }, user: { findUnique: jest.fn() }, registration: { findMany: jest.fn(), count: jest.fn(), findUnique: jest.fn(), findUniqueOrThrow: jest.fn() }, feedbackForm: { findUnique: jest.fn() }, }; jest.mock('../src/config/db', () => mockDb); // AI helpers: everything real except the call to the Hub. const mockRunHelper = jest.fn(); jest.mock('../src/ai/index', () => ({ ...jest.requireActual('../src/ai/index'), runHelper: (...a: unknown[]) => mockRunHelper(...a) })); const mockAccessLog = jest.fn(async () => undefined); jest.mock('../src/utils/accessLog', () => ({ logDataAccess: (...a: unknown[]) => mockAccessLog(...(a as [])) })); jest.mock('../src/utils/campuses', () => ({ campusesEnabled: jest.fn().mockResolvedValue(false), resolveCampusFilter: jest.fn(async (v: string) => v), campusWhere: jest.fn(() => ({})), })); // Signed in as whoever the test says (the real middleware checks JWTs against the database). let signedIn: { id: string; role: string } | null = null; jest.mock('../src/middleware/authMiddleware', () => { const deny = (status: number, message: string) => (_req: unknown, res: { status(n: number): void }, next: (e: Error) => void) => { res.status(status); next(new Error(message)); }; return { protect: (req: { user?: unknown }, res: { status(n: number): void }, next: (e?: Error) => void) => (signedIn ? ((req.user = signedIn), next()) : deny(401, 'Not authorized, no token')(req, res, next as (e: Error) => void)), optionalAuth: (req: { user?: unknown }, _res: unknown, next: () => void) => { if (signedIn) req.user = signedIn; next(); }, admin: (req: { user?: { role: string } }, res: { status(n: number): void }, next: (e?: Error) => void) => (req.user?.role === 'admin' ? next() : deny(403, 'Not authorized as an admin')(req, res, next as (e: Error) => void)), staff: (req: { user?: { role: string } }, res: { status(n: number): void }, next: (e?: Error) => void) => (['admin', 'supervisor', 'staff'].includes(req.user?.role || '') ? next() : deny(403, 'Not authorized as staff')(req, res, next as (e: Error) => void)), supervisor: (req: { user?: { role: string } }, res: { status(n: number): void }, next: (e?: Error) => void) => (['admin', 'supervisor'].includes(req.user?.role || '') ? next() : deny(403, 'Not authorized as a supervisor')(req, res, next as (e: Error) => void)), loginLimiter: (_req: unknown, _res: unknown, next: () => void) => next(), }; }); // The services are tested through v1 (e2e); here only how v2 calls them and maps their answers. const mockServices = { createRegistration: jest.fn(), cancelRegistration: jest.fn(), startRegistrationCheckout: jest.fn() }; jest.mock('../src/services/registrations', () => ({ createRegistration: (...a: unknown[]) => mockServices.createRegistration(...a), cancelRegistration: (...a: unknown[]) => mockServices.cancelRegistration(...a) })); jest.mock('../src/services/payments', () => ({ startRegistrationCheckout: (...a: unknown[]) => mockServices.startRegistrationCheckout(...a) })); const mockAuth = { signUp: jest.fn(), logIn: jest.fn(), verifyLoginCode: jest.fn(), updateProfile: jest.fn() }; jest.mock('../src/services/auth', () => ({ signUp: (...a: unknown[]) => mockAuth.signUp(...a), logIn: (...a: unknown[]) => mockAuth.logIn(...a), verifyLoginCode: (...a: unknown[]) => mockAuth.verifyLoginCode(...a), updateProfile: (...a: unknown[]) => mockAuth.updateProfile(...a), })); const mockCheckin = { previewScan: jest.fn(), scanTicket: jest.fn() }; jest.mock('../src/services/checkin', () => ({ previewScan: (...a: unknown[]) => mockCheckin.previewScan(...a), scanTicket: (...a: unknown[]) => mockCheckin.scanTicket(...a) })); const mockScope = { scope: null as object | null, campusId: 'north' as string | null, blockEvent: false }; jest.mock('../src/utils/campusScope', () => ({ scopeFor: async () => mockScope.scope, eventOf: async () => ({ campusId: mockScope.campusId, campusName: 'North' }), canView: (scope: { campusIds: string[] }, campusId: string | null) => !campusId || scope.campusIds.includes(campusId), // Route-level checks: refuse like v1 does (v1 shape — the v2 wrapper isn't in this test app). scopeEvent: () => (_req: unknown, res: { status(n: number): { json(b: unknown): void } }, next: () => void) => (mockScope.blockEvent ? res.status(404).json({ message: 'Not found' }) : next()), scopeBody: () => (_req: unknown, _res: unknown, next: () => void) => next(), listWhere: async () => ({}), scopeList: (_req: unknown, _res: unknown, next: () => void) => next(), scopeBroadcast: () => (_req: unknown, _res: unknown, next: () => void) => next(), unscopedOnly: (_req: unknown, _res: unknown, next: () => void) => next(), campusIndependent: () => (_req: unknown, _res: unknown, next: () => void) => next(), })); const mockEvents = { listManagedEvents: jest.fn(), createEvent: jest.fn(), updateEvent: jest.fn(), deactivateEvent: jest.fn(), getNotifyRecipients: jest.fn(), setNotifyRecipients: jest.fn(), copySetupFrom: jest.fn() }; jest.mock('../src/services/events', () => Object.fromEntries(Object.keys(mockEvents).map(k => [k, (...a: unknown[]) => (mockEvents as Record)[k](...a)]))); const mockDetails = { getEventDetail: jest.fn(), eventCalendar: jest.fn(), eventByAlias: jest.fn(), createOption: jest.fn(), updateOption: jest.fn(), deleteOption: jest.fn(), createVariant: jest.fn(), updateVariant: jest.fn(), deleteVariant: jest.fn(), listAttachments: jest.fn(), recordAttachment: jest.fn(), deleteAttachment: jest.fn(), attachmentsStatus: jest.fn(), syncAttachmentManifests: jest.fn(), }; jest.mock('../src/services/eventDetails', () => Object.fromEntries(Object.keys(mockDetails).map(k => [k, (...a: unknown[]) => (mockDetails as Record)[k](...a)]))); // The upload step: pretend multer saved the file (or refused it). const mockUpload = { file: null as object | null, error: null as Error | null }; jest.mock('../src/controllers/eventController', () => ({ receiveAttachment: (req: { file?: object; multerError?: Error }, _res: unknown, next: () => void) => { if (mockUpload.error) req.multerError = mockUpload.error; else if (mockUpload.file) req.file = mockUpload.file; next(); }, })); const mockSetup = { listSections: jest.fn(), createSection: jest.fn(), updateSection: jest.fn(), deleteSection: jest.fn(), listCosts: jest.fn(), createCost: jest.fn(), updateCost: jest.fn(), deleteCost: jest.fn() }; jest.mock('../src/services/setup', () => Object.fromEntries(Object.keys(mockSetup).map(k => [k, (...a: unknown[]) => (mockSetup as Record)[k](...a)]))); // Image uploads: a stand-in for multer that "saves" mockImage. const mockImage = { file: null as object | null }; jest.mock('../src/controllers/uploadController', () => { const m = { single: () => (req: { file?: object }, _res: unknown, cb: () => void) => { if (mockImage.file) req.file = mockImage.file; cb(); } }; return { upload: m, uploadLogo: m, uploadFavicon: m }; }); const mockSeries = { listSeries: jest.fn(), createSeries: jest.fn(), updateSeries: jest.fn(), deleteSeries: jest.fn(), seriesPage: jest.fn(), compareSeries: jest.fn(), setFollowing: jest.fn(), listPasses: jest.fn(), createPass: jest.fn(), updatePass: jest.fn(), deletePass: jest.fn(), buyPass: jest.fn(), payPassPurchase: jest.fn(), myPassPurchases: jest.fn() }; jest.mock('../src/services/series', () => Object.fromEntries(Object.keys(mockSeries).map(k => [k, (...a: unknown[]) => (mockSeries as Record)[k](...a)]))); const mockDeals = { listBundles: jest.fn(), createBundle: jest.fn(), updateBundle: jest.fn(), deleteBundle: jest.fn(), quoteBundles: jest.fn(), checkCode: jest.fn(), listCoupons: jest.fn(), getCoupon: jest.fn(), createCoupon: jest.fn(), updateCoupon: jest.fn(), listRedemptions: jest.fn(), publicBundlesForEvent: jest.fn() }; jest.mock('../src/services/deals', () => Object.fromEntries(Object.keys(mockDeals).map(k => [k, (...a: unknown[]) => (mockDeals as Record)[k](...a)]))); const mockCampuses = { publicCampuses: jest.fn(), campusBySlug: jest.fn(), adminCampuses: jest.fn(), setCampusesEnabled: jest.fn(), createCampus: jest.fn(), updateCampus: jest.fn(), reorderCampuses: jest.fn(), deleteCampus: jest.fn(), campusAudience: jest.fn() }; jest.mock('../src/services/campuses', () => Object.fromEntries(Object.keys(mockCampuses).map(k => [k, (...a: unknown[]) => (mockCampuses as Record)[k](...a)]))); const mockAdmin = { getRegistrations: jest.fn(), getUserRegistrations: jest.fn(), getRegistrationById: jest.fn(), updateRegistrationStatus: jest.fn(), getRegistrationsByEvent: jest.fn(), createManualRegistration: jest.fn(), updateRegistrationOptions: jest.fn(), submitFormResponses: jest.fn(), replaceFormResponses: jest.fn(), getFormDraft: jest.fn(), saveFormDraft: jest.fn(), sendInvoice: jest.fn(), applyCoupon: jest.fn(), removeCoupon: jest.fn(), updateAttendees: jest.fn(), sendAttendeeFormLink: jest.fn() }; jest.mock('../src/services/registrationAdmin', () => Object.fromEntries(Object.keys(mockAdmin).map(k => [k, (...a: unknown[]) => (mockAdmin as Record)[k](...a)]))); jest.mock('../src/utils/seasonPass', () => ({ notOnSeasonPass: (_req: unknown, _res: unknown, next: () => void) => next() })); jest.mock('../src/controllers/cashupController', () => { const echo = (req: { params: object; body: object }, res: { json(b: unknown): void }) => res.json({ params: req.params, body: req.body }); return { getEventCashup: echo, getCashByRecordedUser: echo, savePersonCash: echo, saveEventCashupDraft: echo, reopenEvent: echo, resolvePending: echo, getCashupAudit: echo, closeEvent: (_req: unknown, res: { status(n: number): { json(b: unknown): void } }) => res.status(400).json({ message: 'There are pending lines.', code: 'PENDING_LINES' }), }; }); import { v2Router } from '../src/v2'; import { ServiceError } from '../src/services/errors'; import { routes } from '../src/v2/route'; import { buildOpenApi } from '../src/v2/openapi'; const app = express(); app.use(express.json()); app.use('/api/v2', v2Router()); const event = (over: Record = {}) => ({ id: 'e1', title: 'Youth Camp', startDate: new Date('2026-12-04T16:00:00Z'), endDate: new Date('2026-12-06T12:00:00Z'), location: 'Camp Joy', price: 600, picture: '/uploads/events/camp.jpg', requiresRegistration: true, scheduleType: 'single', campus: null, series: { id: 's1', name: 'Camps', slug: 'camps' }, ...over, }); beforeEach(() => { signedIn = null; jest.clearAllMocks(); }); describe('GET /api/v2/events', () => { test('a page of public events, with meta and ISO dates', async () => { mockDb.event.findMany.mockResolvedValue([event()]); mockDb.event.count.mockResolvedValue(31); const res = await request(app).get('/api/v2/events?page=2&limit=10&q=camp'); expect(res.status).toBe(200); expect(res.body.meta).toEqual({ page: 2, limit: 10, total: 31, pages: 4 }); expect(res.body.data[0]).toMatchObject({ id: 'e1', startDate: '2026-12-04T16:00:00.000Z', series: { slug: 'camps' } }); expect(res.body.data[0].pictureUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/uploads\/events\/camp\.jpg$/); const args = mockDb.event.findMany.mock.calls[0][0]; expect(args).toMatchObject({ skip: 10, take: 10 }); expect(args.where.AND).toEqual(expect.arrayContaining([{ isActive: true, isHidden: false, goLiveAt: { lte: expect.any(Date) } }, { title: { contains: 'camp', mode: 'insensitive' } }])); }); test('fields the schema does not list are never sent', async () => { mockDb.event.findMany.mockResolvedValue([event({ cashupStatus: 'closed', createdById: 'u9' })]); mockDb.event.count.mockResolvedValue(1); const res = await request(app).get('/api/v2/events'); expect(Object.keys(res.body.data[0]).sort()).toEqual(['campus', 'endDate', 'id', 'location', 'pictureUrl', 'price', 'requiresRegistration', 'scheduleType', 'series', 'startDate', 'title']); }); test('a bad query is a VALIDATION_FAILED error naming the field', async () => { const res = await request(app).get('/api/v2/events?limit=500&page=0'); expect(res.status).toBe(400); expect(res.body.error.code).toBe('VALIDATION_FAILED'); expect(Object.keys(res.body.error.fields).sort()).toEqual(['limit', 'page']); expect(mockDb.event.findMany).not.toHaveBeenCalled(); }); }); describe('GET /api/v2/events/:id', () => { test('leaves out kids and volunteer tickets and shows the early-bird price now', async () => { mockDb.event.findFirst.mockResolvedValue({ ...event(), description: 'A weekend away', registrationDeadline: null, kidsOptionId: 'kids', volunteerOptionId: null, eventOptions: [ { id: 'o1', name: 'Camper', price: 600, isMainTicket: true, sessionMode: 'all', earlyBirdTiers: [{ id: 't', price: 500, deadline: new Date(Date.now() + 864e5), stockLimit: 0 }] }, { id: 'kids', name: 'Kids check-in', price: 0, isMainTicket: false, sessionMode: 'all', earlyBirdTiers: [] }, ], sessions: [], }); const res = await request(app).get('/api/v2/events/e1'); expect(res.status).toBe(200); expect(res.body.data.ticketOptions).toEqual([{ id: 'o1', name: 'Camper', price: 600, currentPrice: 500, isMainTicket: true, sessionMode: 'all' }]); }); test('an unknown or private event is NOT_FOUND', async () => { mockDb.event.findFirst.mockResolvedValue(null); const res = await request(app).get('/api/v2/events/nope'); expect(res.status).toBe(404); expect(res.body).toEqual({ error: { code: 'NOT_FOUND', message: "That event wasn't found." } }); }); }); describe('me', () => { test('signed out is UNAUTHENTICATED in the v2 shape', async () => { const res = await request(app).get('/api/v2/me'); expect(res.status).toBe(401); expect(res.body.error.code).toBe('UNAUTHENTICATED'); }); test('my registrations with totals and what is owing', async () => { signedIn = { id: 'u1', role: 'user' }; mockDb.registration.findMany.mockResolvedValue([{ id: 'r1', status: 'partial_paid', createdAt: new Date('2026-10-01T10:00:00Z'), discountTotal: 0, event: { id: 'e1', title: 'Youth Camp', startDate: new Date('2026-12-04T16:00:00Z'), endDate: new Date('2026-12-06T12:00:00Z') }, registrationOptions: [{ quantity: 2, priceSnapshot: 600, eventOption: { name: 'Camper', price: 600, earlyBirdTiers: [] }, variant: null, tranches: [] }], payments: [{ amount: 500, createdAt: new Date() }], }]); mockDb.registration.count.mockResolvedValue(1); const res = await request(app).get('/api/v2/me/registrations'); expect(res.status).toBe(200); expect(res.body.data[0]).toMatchObject({ id: 'r1', totalDue: 1200, amountPaid: 500, balance: 700, items: [{ ticket: 'Camper', variant: null, quantity: 2, unitPrice: 600 }] }); expect(mockDb.registration.findMany.mock.calls[0][0].where).toMatchObject({ userId: 'u1', status: { not: 'cancelled' } }); }); }); describe('the API description', () => { test('openapi.json is for admins', async () => { signedIn = { id: 'u1', role: 'user' }; expect((await request(app).get('/api/v2/openapi.json')).body.error.code).toBe('FORBIDDEN'); signedIn = { id: 'a1', role: 'admin' }; const res = await request(app).get('/api/v2/openapi.json'); expect(res.status).toBe(200); expect(res.body.openapi).toBe('3.1.0'); }); test('every route is described, with its parameters, auth and response', () => { const doc = buildOpenApi({ version: 'test' }); for (const r of routes) { const op = (doc.paths as Record>>)[r.path.replace(/:(\w+)/g, '{$1}')][r.method]; expect(op).toBeDefined(); expect(op.responses).toHaveProperty(String(r.status ?? 200)); } const list = doc.paths['/events'].get as { parameters: { name: string; in: string }[]; security?: unknown }; expect(list.parameters.map(p => p.name)).toEqual(['page', 'limit', 'q', 'campus', 'series']); expect(list.security).toBeUndefined(); expect((doc.paths['/me'].get as { security: unknown }).security).toEqual([{ bearerAuth: [] }]); expect((doc.paths['/events/{id}'].get as { parameters: { name: string; in: string; required: boolean }[] }).parameters[0]).toMatchObject({ name: 'id', in: 'path', required: true }); }); test('an unknown v2 path is a v2 NOT_FOUND', async () => { const res = await request(app).get('/api/v2/nothing-here'); expect(res.status).toBe(404); expect(res.body.error.code).toBe('NOT_FOUND'); }); }); describe('registrations', () => { const row = (over: Record = {}) => ({ id: 'r1', userId: 'u1', status: 'pending', createdAt: new Date('2026-10-01T10:00:00Z'), discountTotal: 0, event: { id: 'e1', title: 'Youth Camp', startDate: new Date('2026-12-04T16:00:00Z'), endDate: new Date('2026-12-06T12:00:00Z') }, registrationOptions: [{ quantity: 1, priceSnapshot: 600, eventOption: { name: 'Camper', price: 600, earlyBirdTiers: [] }, variant: null, tranches: [] }], payments: [], ...over, }); test('registering passes a guest through and answers 201 with what is owing', async () => { mockServices.createRegistration.mockResolvedValue({ registration: { id: 'r1' }, isNew: true, couponError: null }); mockDb.registration.findUniqueOrThrow.mockResolvedValue(row()); const res = await request(app).post('/api/v2/registrations').send({ eventId: 'e1', options: [{ eventOptionId: 'o1', quantity: 1 }], guest: { name: 'Thandi', email: 'thandi@example.com' }, }); expect(res.status).toBe(201); expect(res.body.data).toMatchObject({ id: 'r1', isNew: true, couponError: null, totalDue: 600, balance: 600 }); expect(mockServices.createRegistration).toHaveBeenCalledWith(expect.objectContaining({ eventId: 'e1', guestName: 'Thandi', guestEmail: 'thandi@example.com' }), null); }); test('a bad body never reaches the service', async () => { const res = await request(app).post('/api/v2/registrations').send({ eventId: 'e1', options: [{ eventOptionId: 'o1', quantity: 0 }], guest: { name: 'T', email: 'not-an-email' } }); expect(res.status).toBe(400); expect(Object.keys(res.body.error.fields).sort()).toEqual(['guest.email', 'options.0.quantity']); expect(mockServices.createRegistration).not.toHaveBeenCalled(); }); test("the service's errors keep their meaning", async () => { mockServices.createRegistration.mockRejectedValueOnce(new ServiceError(401, 'Authentication required for this event')); const res = await request(app).post('/api/v2/registrations').send({ eventId: 'e1', options: [{ eventOptionId: 'o1', quantity: 1 }] }); expect(res.status).toBe(401); expect(res.body.error).toEqual({ code: 'UNAUTHENTICATED', message: 'Authentication required for this event' }); mockServices.createRegistration.mockRejectedValueOnce(new ServiceError(400, '"Camper" is sold out or does not have enough stock (0 remaining).')); const sold = await request(app).post('/api/v2/registrations').send({ eventId: 'e1', options: [{ eventOptionId: 'o1', quantity: 1 }] }); expect(sold.body.error.code).toBe('VALIDATION_FAILED'); }); test("someone else's registration is NOT_FOUND, and can't be cancelled or paid", async () => { signedIn = { id: 'u2', role: 'user' }; mockDb.registration.findUnique.mockResolvedValue(row()); for (const [method, path] of [['get', '/api/v2/registrations/r1'], ['post', '/api/v2/registrations/r1/cancel'], ['post', '/api/v2/registrations/r1/checkout']] as const) { const res = await request(app)[method](path).send({}); expect([path, res.status]).toEqual([path, 404]); } expect(mockServices.cancelRegistration).not.toHaveBeenCalled(); expect(mockServices.startRegistrationCheckout).not.toHaveBeenCalled(); }); test('cancelling my registration', async () => { signedIn = { id: 'u1', role: 'user' }; mockDb.registration.findUnique.mockResolvedValueOnce(row()).mockResolvedValueOnce(row({ status: 'cancelled' })); mockServices.cancelRegistration.mockResolvedValue({}); const res = await request(app).post('/api/v2/registrations/r1/cancel'); expect(res.status).toBe(200); expect(res.body.data.status).toBe('cancelled'); }); test('checkout: the payment page, or the new balance when an early-bird price ran out', async () => { signedIn = { id: 'u1', role: 'user' }; mockDb.registration.findUnique.mockResolvedValue(row()); mockServices.startRegistrationCheckout.mockResolvedValueOnce({ checkoutId: 'c1', redirectUrl: 'https://pay.example/c1', provider: 'yoco', amount: 650, registration: {} }); const pay = await request(app).post('/api/v2/registrations/r1/checkout').send({ donationAmount: 50 }); expect(pay.body.data).toEqual({ priceUpdated: false, checkoutId: 'c1', redirectUrl: 'https://pay.example/c1', provider: 'yoco', amount: 650 }); expect(mockServices.startRegistrationCheckout).toHaveBeenCalledWith('r1', signedIn, { donationAmount: 50 }); mockServices.startRegistrationCheckout.mockResolvedValueOnce({ priceUpdated: true, newTotal: 700, message: 'Prices changed' }); const changed = await request(app).post('/api/v2/registrations/r1/checkout').send({}); expect(changed.body.data).toEqual({ priceUpdated: true, newBalance: 700, message: 'Prices changed' }); }); }); describe('the frontend types', () => { test('frontend/src/lib/api-v2/openapi.json is up to date (run `npm run api:types` in the repo root)', () => { // eslint-disable-next-line @typescript-eslint/no-require-imports const { OPENAPI_FILE, currentDocument } = require('../scripts/openapi'); // eslint-disable-next-line @typescript-eslint/no-require-imports const saved = require('fs').readFileSync(OPENAPI_FILE, 'utf8').replace(/\r\n/g, '\n'); expect(saved).toBe(currentDocument()); }); }); describe('accounts', () => { const sess = { id: 'u1', name: 'Thandi', email: 't@x.co', role: 'user', token: 'jwt', newsPromptPending: true, noticePromptPending: false }; test('log in: a token, or a code to finish with', async () => { mockAuth.logIn.mockResolvedValueOnce({ status: 'signed_in', session: sess }); const ok = await request(app).post('/api/v2/auth/login').send({ identifier: 't@x.co', password: 'secret' }); expect(ok.body.data).toEqual({ status: 'signed_in', token: 'jwt', user: { id: 'u1', name: 'Thandi', email: 't@x.co', role: 'user' }, newsPromptPending: true, noticePromptPending: false }); mockAuth.logIn.mockResolvedValueOnce({ status: 'code_required', challenge: { challengeId: 'c1', method: 'email', destination: 't***@x.co' }, enrolling: true }); const code = await request(app).post('/api/v2/auth/login').send({ identifier: 't@x.co', password: 'secret' }); expect(code.body.data).toEqual({ status: 'code_required', challengeId: 'c1', method: 'email', destination: 't***@x.co', enrolling: true }); // The token never comes with a code challenge. expect(code.body.data.token).toBeUndefined(); }); test('a wrong password is UNAUTHENTICATED and a locked account RATE_LIMITED', async () => { mockAuth.logIn.mockRejectedValueOnce(new ServiceError(401, 'Invalid email or password', undefined, { v1Status: 400 })); expect((await request(app).post('/api/v2/auth/login').send({ identifier: 'a', password: 'b' })).body.error.code).toBe('UNAUTHENTICATED'); mockAuth.logIn.mockRejectedValueOnce(new ServiceError(429, 'Too many attempts. Try again in 5 minute(s).')); const locked = await request(app).post('/api/v2/auth/login').send({ identifier: 'a', password: 'b' }); expect([locked.status, locked.body.error.code]).toEqual([429, 'RATE_LIMITED']); }); test('sign up needs the terms accepted and a password of 8+', async () => { const bad = await request(app).post('/api/v2/auth/signup').send({ name: 'T', email: 't@x.co', password: 'short' }); expect(Object.keys(bad.body.error.fields).sort()).toEqual(['acceptTerms', 'password']); mockAuth.signUp.mockResolvedValue({ id: 'u9', name: 'T', email: 't@x.co', role: 'user', token: 'jwt9' }); const ok = await request(app).post('/api/v2/auth/signup').send({ name: 'T', email: 't@x.co', password: 'long-enough', acceptTerms: true, newsOptIn: true }); expect(ok.status).toBe(201); expect(ok.body.data).toMatchObject({ status: 'signed_in', token: 'jwt9' }); expect(mockAuth.signUp).toHaveBeenCalledWith(expect.objectContaining({ newsOptIn: true }), expect.any(Object)); }); test('PATCH /me changes only what is sent and hands back a fresh token', async () => { signedIn = { id: 'u1', role: 'user' }; mockAuth.updateProfile.mockResolvedValue({ user: { id: 'u1', name: 'New', email: 't@x.co', phoneNumber: null, role: 'user', twoFactorEnabled: false, notificationPreference: 'email', homeCampusId: null, createdAt: new Date('2026-01-01T00:00:00Z'), tokenVersion: 0 }, token: 'jwt2' }); const res = await request(app).patch('/api/v2/me').send({ name: 'New' }); expect(res.body).toMatchObject({ data: { name: 'New', phone: null }, token: 'jwt2' }); expect(res.body.data.tokenVersion).toBeUndefined(); expect(mockAuth.updateProfile).toHaveBeenCalledWith('u1', { name: 'New', phoneNumber: undefined }, expect.any(Object)); }); }); describe('check-in', () => { const ticket = { id: 't1', quantity: 2, isUsed: false, eventId: 'e1', event: { title: 'Youth Camp' }, registrationOption: { eventOption: { id: 'o1', name: 'Camper', isMainTicket: true } }, usages: [] }; afterEach(() => { mockScope.scope = null; }); test('staff only', async () => { signedIn = { id: 'u1', role: 'user' }; expect((await request(app).post('/api/v2/checkin/QR1').send({})).body.error.code).toBe('FORBIDDEN'); }); test('every normal result is a 200 with an outcome', async () => { signedIn = { id: 's1', role: 'staff' }; mockCheckin.scanTicket.mockResolvedValueOnce({ outcome: 'checked_in', message: 'Ticket scanned successfully (1 of 2 redeemed, 1 remaining)', session: null, ticketUsage: {}, ticket, qtyRedeemed: 1, totalRedeemed: 1, remaining: 1 }); const ok = await request(app).post('/api/v2/checkin/QR1').send({ people: 1, eventId: 'e1' }); expect(ok.body.data).toEqual({ outcome: 'checked_in', message: expect.any(String), ticket: { id: 't1', eventId: 'e1', eventTitle: 'Youth Camp', ticketName: 'Camper', quantity: 2 }, checkedIn: 1, remaining: 1, session: null, consentStatus: null, canOverride: false }); expect(mockCheckin.scanTicket).toHaveBeenCalledWith('QR1', signedIn, expect.objectContaining({ qty: 1, eventId: 'e1' }), expect.anything()); mockCheckin.scanTicket.mockResolvedValueOnce({ outcome: 'consent_required', message: 'Parental consent is missing', consentStatus: 'missing', canOverride: false, ticket }); const consent = await request(app).post('/api/v2/checkin/QR1').send({}); expect(consent.status).toBe(200); expect(consent.body.data).toMatchObject({ outcome: 'consent_required', checkedIn: 0, consentStatus: 'missing' }); mockCheckin.scanTicket.mockResolvedValueOnce({ outcome: 'transferred', message: 'Given to Sipho' }); expect((await request(app).post('/api/v2/checkin/QR1').send({})).body.data).toMatchObject({ outcome: 'transferred', ticket: null }); }); test("campus-scoped staff can't check in another campus's ticket", async () => { signedIn = { id: 's1', role: 'staff' }; mockScope.scope = { campusIds: ['south'] }; const res = await request(app).post('/api/v2/checkin/QR1').send({}); expect(res.body.error).toEqual({ code: 'FORBIDDEN', message: 'This ticket is for an event at North.' }); expect(mockCheckin.scanTicket).not.toHaveBeenCalled(); }); test('the preview names the holder and what is left', async () => { signedIn = { id: 's1', role: 'staff' }; mockCheckin.previewScan.mockResolvedValue({ outcome: 'found', ticket: { ...ticket, consentStatus: 'not_required', remaining: 2, session: null, sessionError: null, registrationOption: { id: 'ro1', eventOption: { id: 'o1', name: 'Camper' }, variant: null }, event: { id: 'e1', title: 'Youth Camp' }, user: { id: 'u1', name: 'Thandi' }, attendee: { name: 'Lulu' } } }); const res = await request(app).get('/api/v2/checkin/QR1'); expect(res.body.data.ticket).toMatchObject({ attendee: 'Lulu', bookedBy: 'Thandi', ticketOptionId: 'o1', remaining: 2, consentStatus: 'not_required' }); }); }); describe('shared middleware on v2', () => { test("v1-style refusals become v2 errors, keeping the specific code as reason", async () => { // eslint-disable-next-line @typescript-eslint/no-require-imports const { legacyErrorsToV2 } = require('../src/v2/errors'); const mini = express(); mini.use('/api/v2', legacyErrorsToV2); mini.get('/api/v2/limited', (_req, res) => { res.status(429).json({ message: 'Too many requests, please try again later.' }); }); mini.post('/api/v2/locked', (_req, res) => { res.status(403).json({ code: 'LICENCE_READ_ONLY', message: 'Read only.' }); }); mini.get('/api/v2/twofa', (_req, res) => { res.status(401).json({ code: 'TWO_FACTOR_REQUIRED', message: 'Set up 2FA.' }); }); mini.get('/api/v2/fine', (_req, res) => { res.json({ data: { message: 'not an error' } }); }); expect((await request(mini).get('/api/v2/limited')).body).toEqual({ error: { code: 'RATE_LIMITED', message: 'Too many requests, please try again later.' } }); expect((await request(mini).post('/api/v2/locked')).body).toEqual({ error: { code: 'READ_ONLY', message: 'Read only.', reason: 'LICENCE_READ_ONLY' } }); expect((await request(mini).get('/api/v2/twofa')).body.error).toMatchObject({ code: 'UNAUTHENTICATED', reason: 'TWO_FACTOR_REQUIRED' }); expect((await request(mini).get('/api/v2/fine')).body).toEqual({ data: { message: 'not an error' } }); }); }); describe('events (staff)', () => { const stored = (over: Record = {}) => ({ id: 'e1', title: 'Camp', description: null, startDate: new Date('2026-12-04T16:00:00Z'), endDate: new Date('2026-12-06T12:00:00Z'), isActive: true, isHidden: true, requiresRegistration: true, scheduleType: 'single', attendanceMode: 'whole', cashupStatus: 'open', campusId: null, seriesId: null, picture: '/uploads/events/c.jpg', waitlistEnabled: true, eventOptions: [{ id: 'o1', name: 'Main Ticket', price: 600, isMainTicket: true, stockLimit: 0, earlyBirdTiers: [] }], sessions: [], ...over, }); afterEach(() => { mockScope.blockEvent = false; }); test('/events/manage lists hidden events for staff, with the rest of each record passed through', async () => { signedIn = { id: 's1', role: 'staff' }; mockEvents.listManagedEvents.mockResolvedValue([stored()]); const res = await request(app).get('/api/v2/events/manage?past=true'); expect(res.status).toBe(200); expect(res.body.data[0]).toMatchObject({ id: 'e1', isHidden: true, waitlistEnabled: true, startDate: '2026-12-04T16:00:00.000Z' }); expect(res.body.data[0].picture).toMatch(/^http:\/\/.*\/uploads\/events\/c\.jpg$/); expect(mockEvents.listManagedEvents).toHaveBeenCalledWith({ includePast: true, includeInactive: false, excludeClosed: false, campus: undefined }, expect.objectContaining({ scope: null })); }); test('members can\'t list or create', async () => { signedIn = { id: 'u1', role: 'user' }; expect((await request(app).get('/api/v2/events/manage')).body.error.code).toBe('FORBIDDEN'); signedIn = { id: 's1', role: 'staff' }; expect((await request(app).post('/api/v2/events').send({ title: 'X', startDate: '2026-12-01', endDate: '2026-12-02' })).body.error.code).toBe('FORBIDDEN'); }); test('create needs a title and dates; update passes only what was sent', async () => { signedIn = { id: 'v1', role: 'supervisor' }; const bad = await request(app).post('/api/v2/events').send({ title: '' }); expect(Object.keys(bad.body.error.fields).sort()).toEqual(['endDate', 'startDate', 'title']); mockEvents.createEvent.mockResolvedValue(stored()); const made = await request(app).post('/api/v2/events').send({ title: 'Camp', startDate: '2026-12-04T16:00', endDate: '2026-12-06T12:00', waitlistEnabled: true }); expect(made.status).toBe(201); expect(mockEvents.createEvent.mock.calls[0][0]).toMatchObject({ title: 'Camp', waitlistEnabled: true }); mockEvents.updateEvent.mockResolvedValue({ ...stored({ title: 'New' }), sessionChanges: null }); const upd = await request(app).patch('/api/v2/events/e1').send({ title: 'New' }); expect(upd.body.data).toMatchObject({ title: 'New', sessionChanges: null }); expect(mockEvents.updateEvent).toHaveBeenCalledWith('e1', { title: 'New' }, { id: 'v1', role: 'supervisor' }, expect.any(Object)); }); test("a campus-scoped supervisor can't change another campus's event", async () => { signedIn = { id: 'v1', role: 'supervisor' }; mockScope.blockEvent = true; expect((await request(app).patch('/api/v2/events/e1').send({ title: 'X' })).status).toBe(404); expect(mockEvents.updateEvent).not.toHaveBeenCalled(); }); test('deactivating is for admins', async () => { signedIn = { id: 'v1', role: 'supervisor' }; expect((await request(app).delete('/api/v2/events/e1')).status).toBe(403); signedIn = { id: 'a1', role: 'admin' }; mockEvents.deactivateEvent.mockResolvedValue({ id: 'e1', isActive: false }); expect((await request(app).delete('/api/v2/events/e1')).body.data).toEqual({ id: 'e1', isActive: false }); }); }); describe('one event in full, options, attachments', () => { const detail = { id: 'e1', title: 'Camp', description: null, startDate: '2026-12-04T16:00:00.000Z', endDate: '2026-12-06T12:00:00.000Z', isActive: true, isHidden: false, requiresRegistration: true, scheduleType: 'single', attendanceMode: 'whole', cashupStatus: 'open', campusId: null, seriesId: null, picture: null, eventOptions: [], sessions: [], form: null, attachments: [], bundles: [], }; afterEach(() => { mockUpload.file = null; mockUpload.error = null; }); test('/events/{id}/full asks for the staff view only for staff', async () => { mockDetails.getEventDetail.mockResolvedValue(detail); await request(app).get('/api/v2/events/e1/full'); expect(mockDetails.getEventDetail.mock.calls[0][1]).toEqual({ staff: false, scope: null }); signedIn = { id: 's1', role: 'staff' }; const res = await request(app).get('/api/v2/events/e1/full'); expect(res.status).toBe(200); expect(mockDetails.getEventDetail.mock.calls[1][1]).toEqual({ staff: true, scope: null }); }); test('the calendar file is a download, not JSON', async () => { mockDetails.eventCalendar.mockResolvedValue({ filename: 'Camp.ics', ics: 'BEGIN:VCALENDAR\nEND:VCALENDAR' }); const res = await request(app).get('/api/v2/events/e1/calendar.ics'); expect(res.status).toBe(200); expect(res.headers['content-type']).toContain('text/calendar'); expect(res.headers['content-disposition']).toBe('attachment; filename="Camp.ics"'); expect(res.text).toContain('BEGIN:VCALENDAR'); }); test('ticket options: supervisors add and change them, only admins remove them', async () => { signedIn = { id: 'v1', role: 'supervisor' }; mockDetails.createOption.mockResolvedValue({ id: 'o2', eventId: 'e1', name: 'Child', price: 300, isMainTicket: false, stockLimit: 0, staffPrice: null, sessionMode: 'all' }); const made = await request(app).post('/api/v2/events/e1/ticket-options').send({ name: 'Child', price: 300 }); expect(made.status).toBe(201); expect((await request(app).post('/api/v2/events/e1/ticket-options').send({ price: 300 })).body.error.fields).toHaveProperty('name'); expect((await request(app).delete('/api/v2/ticket-options/o2')).status).toBe(403); signedIn = { id: 'a1', role: 'admin' }; mockDetails.deleteOption.mockRejectedValueOnce(new ServiceError(400, 'Cannot delete event option that has registrations')); expect((await request(app).delete('/api/v2/ticket-options/o2')).body.error.message).toBe('Cannot delete event option that has registrations'); }); test('uploading an attachment: the file, or why it was refused', async () => { signedIn = { id: 'v1', role: 'supervisor' }; mockUpload.error = new Error('Unsupported file type'); const refused = await request(app).post('/api/v2/events/e1/attachments'); expect(refused.body.error).toMatchObject({ code: 'VALIDATION_FAILED', fields: { file: 'Unsupported file type' } }); mockUpload.error = null; mockUpload.file = { originalname: 'packing.pdf', filename: 'event-file-1.pdf', mimetype: 'application/pdf', size: 1200 }; mockDetails.recordAttachment.mockResolvedValue({ id: 'a1', eventId: 'e1', originalName: 'packing.pdf', filename: 'event-file-1.pdf', mimeType: 'application/pdf', size: 1200, url: 'http://x/uploads/event-files/event-file-1.pdf', createdAt: new Date('2026-10-29T10:00:00Z') }); const ok = await request(app).post('/api/v2/events/e1/attachments'); expect(ok.status).toBe(201); expect(ok.body.data).toMatchObject({ originalName: 'packing.pdf', createdAt: '2026-10-29T10:00:00.000Z' }); }); test('the upload is described as multipart and the calendar as a file', () => { const doc = buildOpenApi({ version: 'test' }) as { paths: Record }; responses: Record }> }>> }; expect(Object.keys(doc.paths['/events/{id}/attachments'].post.requestBody!.content)).toEqual(['multipart/form-data']); expect(Object.keys(doc.paths['/events/{id}/calendar.ics'].get.responses['200'].content)).toEqual(['text/calendar']); }); }); describe('sections, costs, image uploads', () => { afterEach(() => { mockImage.file = null; }); test('costs: supervisors read them, admins add them; per-item needs a ticket type', async () => { signedIn = { id: 'v1', role: 'supervisor' }; mockSetup.listCosts.mockResolvedValue([{ id: 'c1', eventId: 'e1', label: 'Hall', costType: 'once_off', amount: 1500, eventOptionId: null, eventOption: null, paidFromMethod: null, notes: null, createdAt: new Date('2026-10-01T10:00:00Z') }]); expect((await request(app).get('/api/v2/events/e1/costs')).body.data[0]).toMatchObject({ label: 'Hall', createdAt: '2026-10-01T10:00:00.000Z' }); expect((await request(app).post('/api/v2/events/e1/costs').send({ label: 'Hall', costType: 'once_off', amount: 1500 })).status).toBe(403); signedIn = { id: 'a1', role: 'admin' }; expect((await request(app).post('/api/v2/events/e1/costs').send({ label: 'Hall', costType: 'monthly', amount: 1 })).body.error.fields).toHaveProperty('costType'); mockSetup.createCost.mockRejectedValueOnce(new ServiceError(400, 'eventOptionId is required for per-item costs')); expect((await request(app).post('/api/v2/events/e1/costs').send({ label: 'Shirt', costType: 'per_item', amount: 80 })).body.error.message).toBe('eventOptionId is required for per-item costs'); }); test('sections need staff to list and a supervisor to add', async () => { signedIn = { id: 'u1', role: 'user' }; expect((await request(app).get('/api/v2/sections')).status).toBe(403); signedIn = { id: 's1', role: 'staff' }; mockSetup.listSections.mockResolvedValue([]); expect((await request(app).get('/api/v2/sections?eventId=e1')).body).toEqual({ data: [] }); expect(mockSetup.listSections).toHaveBeenCalledWith('e1', expect.anything()); }); test('an event picture comes back as a path to save and a full address', async () => { signedIn = { id: 'v1', role: 'supervisor' }; expect((await request(app).post('/api/v2/uploads/event-image')).body.error.fields).toEqual({ image: 'Choose an image' }); mockImage.file = { filename: 'event-123.jpg' }; const res = await request(app).post('/api/v2/uploads/event-image'); expect(res.body.data.path).toBe('/uploads/events/event-123.jpg'); expect(res.body.data.url).toMatch(/^http:\/\/.*\/uploads\/events\/event-123\.jpg$/); }); test('branding images are for admins once accounts exist', async () => { signedIn = { id: 'v1', role: 'supervisor' }; mockImage.file = { filename: 'logo.png' }; expect((await request(app).post('/api/v2/uploads/logo')).status).toBe(403); signedIn = { id: 'a1', role: 'admin' }; expect((await request(app).post('/api/v2/uploads/logo')).body.data.path).toBe('/uploads/branding/logo.png'); }); }); describe('series, deals and campuses', () => { test('following a series needs an account; the page works without one', async () => { expect((await request(app).put('/api/v2/series/s1/follow')).status).toBe(401); signedIn = { id: 'u1', role: 'user' }; mockSeries.setFollowing.mockResolvedValue({ following: true }); expect((await request(app).put('/api/v2/series/s1/follow')).body.data).toEqual({ following: true }); expect(mockSeries.setFollowing).toHaveBeenCalledWith('s1', 'u1', true); }); test('a coupon check is always a 200 with valid true or false', async () => { mockDeals.checkCode.mockResolvedValueOnce({ valid: false, message: 'This code has expired.' }); const res = await request(app).post('/api/v2/coupons/check').send({ code: 'OLD', eventId: 'e1', options: [{ eventOptionId: 'o1', quantity: 1 }] }); expect(res.status).toBe(200); expect(res.body.data).toEqual({ valid: false, message: 'This code has expired.' }); }); test('/coupons/redemptions is not read as a coupon id', async () => { signedIn = { id: 'v1', role: 'supervisor' }; mockDeals.listRedemptions.mockResolvedValue([]); expect((await request(app).get('/api/v2/coupons/redemptions?eventIds=e1,e2')).body).toEqual({ data: [] }); expect(mockDeals.listRedemptions.mock.calls[0][0]).toEqual({ eventIds: ['e1', 'e2'], from: null, to: null }); expect(mockDeals.getCoupon).not.toHaveBeenCalled(); }); test("a campus that can't be deleted says why, as a reason", async () => { signedIn = { id: 'a1', role: 'admin' }; mockCampuses.deleteCampus.mockRejectedValueOnce(new ServiceError(409, 'North has 3 events, so it can\'t be deleted. Archive it instead.', 'CAMPUS_HAS_EVENTS')); const res = await request(app).delete('/api/v2/campuses/c1'); expect(res.status).toBe(409); expect(res.body.error).toEqual({ code: 'CONFLICT', message: expect.stringContaining('Archive it instead'), reason: 'CAMPUS_HAS_EVENTS' }); }); test('campus admin routes are for admins; the public list is for anyone', async () => { mockCampuses.publicCampuses.mockResolvedValue({ enabled: true, campuses: [{ id: 'c1', name: 'North', slug: 'north', colour: null }] }); expect((await request(app).get('/api/v2/campuses')).body.data.campuses[0]).toMatchObject({ slug: 'north' }); signedIn = { id: 'v1', role: 'supervisor' }; expect((await request(app).get('/api/v2/campuses/admin')).status).toBe(403); expect((await request(app).put('/api/v2/campuses/enabled').send({ enabled: true })).status).toBe(403); }); }); describe('managing registrations', () => { const reg = { id: 'r1', status: 'pending', eventId: 'e1', userId: 'u1', totalDueComputed: 150, payments: [] }; test('a guest with the link can read a registration in full', async () => { mockAdmin.getRegistrationById.mockResolvedValue(reg); const res = await request(app).get('/api/v2/registrations/r1/full'); expect(res.status).toBe(200); expect(res.body.data).toMatchObject({ id: 'r1', totalDueComputed: 150, payments: [] }); expect(mockAdmin.getRegistrationById.mock.calls[0][0]).toMatchObject({ actor: null, params: { id: 'r1' } }); }); test('the staff list is paged and campus-scoped', async () => { signedIn = { id: 'u1', role: 'user' }; expect((await request(app).get('/api/v2/registrations')).status).toBe(403); signedIn = { id: 's1', role: 'staff' }; mockAdmin.getRegistrations.mockResolvedValue({ data: [reg], total: 1, page: 1, limit: 100, pages: 1 }); const res = await request(app).get('/api/v2/registrations?unpaid=true'); expect(res.body).toEqual({ data: [reg], meta: { page: 1, limit: 100, total: 1, pages: 1 } }); const call = mockAdmin.getRegistrations.mock.calls[0][0]; expect(call.query).toMatchObject({ unpaid: '1', page: '1', limit: '100' }); expect(typeof call.listWhere).toBe('function'); }); test('a status must be one of the five', async () => { signedIn = { id: 's1', role: 'staff' }; const res = await request(app).patch('/api/v2/registrations/r1/status').send({ status: 'refunded' }); expect(res.status).toBe(400); expect(res.body.error.code).toBe('VALIDATION_FAILED'); expect(mockAdmin.updateRegistrationStatus).not.toHaveBeenCalled(); }); test('registering someone at the door is for supervisors, and answers 201', async () => { const body = { eventId: 'e1', options: [{ eventOptionId: 'o1', quantity: 2 }], user: { name: 'Thandi', phoneNumber: '0821234567' } }; signedIn = { id: 's1', role: 'staff' }; expect((await request(app).post('/api/v2/registrations/manual').send(body)).status).toBe(403); signedIn = { id: 'v1', role: 'supervisor' }; mockAdmin.createManualRegistration.mockResolvedValue(reg); const res = await request(app).post('/api/v2/registrations/manual').send(body); expect(res.status).toBe(201); expect(mockAdmin.createManualRegistration.mock.calls[0][0].body).toMatchObject(body); }); test("a refusal keeps the service's status", async () => { signedIn = { id: 'u1', role: 'user' }; mockAdmin.updateRegistrationOptions.mockRejectedValueOnce(new ServiceError(400, 'Cannot reduce items below the amount already paid')); const res = await request(app).put('/api/v2/registrations/r1/items').send({ options: [{ eventOptionId: 'o1', quantity: 1 }] }); expect(res.status).toBe(400); expect(res.body.error).toMatchObject({ code: 'VALIDATION_FAILED', message: 'Cannot reduce items below the amount already paid' }); }); }); describe('money (v1 handlers behind v2 routes)', () => { test("an event's cash-up reaches v1 with the event as :eventId", async () => { signedIn = { id: 'v1', role: 'supervisor' }; const res = await request(app).get('/api/v2/events/e1/cashup'); expect(res.status).toBe(200); expect(res.body.data.params).toMatchObject({ eventId: 'e1' }); }); test('closing is for admins, and a v1 refusal keeps its code as the reason', async () => { signedIn = { id: 'v1', role: 'supervisor' }; expect((await request(app).post('/api/v2/events/e1/cashup/close').send({})).status).toBe(403); signedIn = { id: 'a1', role: 'admin' }; const res = await request(app).post('/api/v2/events/e1/cashup/close').send({}); expect(res.status).toBe(400); expect(res.body.error).toEqual({ code: 'VALIDATION_FAILED', message: 'There are pending lines.', reason: 'PENDING_LINES' }); }); test('a cash-up line is given to v1 as :lineId', async () => { signedIn = { id: 'a1', role: 'admin' }; const res = await request(app).post('/api/v2/cashup-lines/l9/pending').send({ resolution: 'paid' }); expect(res.body.data).toEqual({ params: { lineId: 'l9' }, body: { resolution: 'paid' } }); }); }); describe('AI helpers (2.0)', () => { const st = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: { draft_event: true, summarise_report: true, draft_message: true, summarise_feedback: true, improve_text: true } }; test('supervisors only', async () => { signedIn = { id: 's1', role: 'staff' }; expect((await request(app).post('/api/v2/ai/improve-text').send({ text: 'hello there' })).status).toBe(403); expect(mockRunHelper).not.toHaveBeenCalled(); }); test('improve text: the answer and the new status', async () => { signedIn = { id: 's1', role: 'supervisor' }; mockRunHelper.mockResolvedValue({ output: { text: 'Hello there.', changes: ['Capital letter'] }, status: st }); const res = await request(app).post('/api/v2/ai/improve-text').send({ text: 'hello there', mode: 'fix', where: 'banner' }); expect(res.status).toBe(200); expect(res.body.data).toEqual({ output: { text: 'Hello there.', changes: ['Capital letter'] }, status: st }); expect(mockRunHelper.mock.calls[0][0]).toBe('improve_text'); }); 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(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 = { title: 'Camp', summary: '', description: '', startDate: '2027-03-14', startTime: '18:00', endDate: '2027-03-16', endTime: '14:00', location: '', capacity: 60, needsParentalConsent: true, ageGroup: '', ticketOptions: [{ name: 'Camper', priceRand: 450, description: '', earlyBirdPriceRand: 0, earlyBirdUntil: '' }], sessions: [], costs: [{ item: 'Venue', basis: '', amountRand: 34800 }], checks: [], }; mockRunHelper.mockResolvedValue({ output: draft, status: st }); const res = await request(app).post('/api/v2/ai/draft-event').send({ notes: 'Camp Fri 14 March, R450, 60 places' }); expect(res.status).toBe(200); expect(res.body.data.output).toMatchObject({ totalCostRand: 34800, breakEvenPlaces: 78 }); expect(res.body.data.output.warnings.join(' ')).toMatch(/is a Sunday.*R7 800 short/); }); test('draft a message: the event is given as facts', async () => { signedIn = { id: 's1', role: 'supervisor' }; mockDb.event.findUnique.mockResolvedValue({ title: 'Youth Camp', startDate: new Date('2027-03-12T16:00:00Z'), location: 'Camp Wartburg' }); mockRunHelper.mockResolvedValue({ output: { subject: '', body: 'Hi {{name}}!' }, status: st }); const res = await request(app).post('/api/v2/ai/draft-message').send({ channel: 'whatsapp', note: 'bring a sleeping bag', eventId: '11111111-1111-4111-8111-111111111111' }); expect(res.status).toBe(200); expect(res.body.data.output).toEqual({ subject: '', body: 'Hi {{name}}!' }); expect(mockRunHelper.mock.calls[0][2].input).toContain('Event: Youth Camp'); }); test('summarise feedback: answers without who gave them, and an access-log entry', async () => { signedIn = { id: 's1', role: 'supervisor' }; mockDb.feedbackForm.findUnique.mockResolvedValue({ event: { title: 'Conference' }, _count: { invites: 10 }, fields: [{ id: 'f1', type: 'rating', label: 'Overall' }, { id: 'f2', type: 'textarea', label: 'Comments' }], responses: [ { userId: 'u1', user: { name: 'Jane Doe' }, answers: [{ fieldId: 'f1', value: '5' }, { fieldId: 'f2', value: 'Loved it, call me on 082 555 1234' }] }, { userId: 'u2', user: { name: 'John Roe' }, answers: [{ fieldId: 'f1', value: '3' }] }, ], }); mockRunHelper.mockResolvedValue({ output: { overall: 'Good.', liked: [], improve: [], quotes: [], nextTime: [] }, status: st }); const res = await request(app).post('/api/v2/ai/summarise-feedback').send({ eventId: '11111111-1111-4111-8111-111111111111' }); expect(res.status).toBe(200); expect(res.body.data.output.responses).toBe(2); const sent = mockRunHelper.mock.calls[0][2].input; expect(sent).toContain('Overall — average 4'); expect(sent).not.toMatch(/Jane|John|082 555 1234/); expect(mockAccessLog).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ action: 'ai_feedback', records: 2 })); }); test('Hub errors keep their reason', async () => { signedIn = { id: 's1', role: 'supervisor' }; const { ApiError } = jest.requireActual('../src/v2/errors'); mockRunHelper.mockRejectedValue(Object.assign(new ApiError('FORBIDDEN', 'Used up.'), { reason: 'AI_CAP_REACHED' })); const res = await request(app).post('/api/v2/ai/improve-text').send({ text: 'hello there' }); expect(res.status).toBe(403); expect(res.body.error).toMatchObject({ code: 'FORBIDDEN', reason: 'AI_CAP_REACHED' }); }); });