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() }, user: { findUnique: jest.fn() }, registration: { findMany: jest.fn(), count: jest.fn(), findUnique: jest.fn(), findUniqueOrThrow: jest.fn() }, }; jest.mock('../src/config/db', () => mockDb); 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: jest.fn(), 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 }; 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), })); 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({ holder: 'Lulu', remaining: 2, consentStatus: 'not_required' }); }); });