Merge branch 'main' into release/2.0 (1.52.0, 1.52.1)
# Conflicts: # CHANGELOG.md # docs/HANDOVER.md
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* 1.52.0: tickets no longer go missing at the door. A required attendee form only holds tickets
|
||||
* back until it's filled in or left for later, picked-session bookings need one form per person
|
||||
* (not per session), a form with no questions holds nothing back, and admins can issue tickets
|
||||
* unpaid, make a balance free and check people in after the event (services/corrections.ts).
|
||||
*/
|
||||
const mockDb: any = {
|
||||
registration: { findUnique: jest.fn(), findMany: jest.fn(), update: jest.fn() },
|
||||
registrationOption: { findMany: jest.fn(), findUnique: jest.fn(), update: jest.fn(), delete: jest.fn() },
|
||||
eventForm: { findUnique: jest.fn() },
|
||||
formResponse: { count: jest.fn() },
|
||||
ticket: { create: jest.fn(), update: jest.fn(), deleteMany: jest.fn(), findMany: jest.fn(), findUnique: jest.fn() },
|
||||
ticketUsage: { create: jest.fn(), deleteMany: jest.fn(), findMany: jest.fn() },
|
||||
eventSession: { findUnique: jest.fn() },
|
||||
event: { findUnique: jest.fn() },
|
||||
};
|
||||
jest.mock('../src/config/db', () => mockDb);
|
||||
const mockAudit = jest.fn();
|
||||
jest.mock('../src/utils/adminAudit', () => ({ logAdminAction: (...a: unknown[]) => mockAudit(...a) }));
|
||||
const mockReminder = jest.fn(async () => ['email']);
|
||||
jest.mock('../src/utils/notifications', () => ({ sendFormReminderMessage: (...a: unknown[]) => (mockReminder as jest.Mock)(...a) }));
|
||||
const mockEmailTickets = jest.fn(async () => undefined);
|
||||
jest.mock('../src/controllers/ticketController', () => ({ emailTickets: (...a: unknown[]) => (mockEmailTickets as jest.Mock)(...a) }));
|
||||
jest.mock('../src/utils/cashupUtils', () => ({ assertEventOpen: jest.fn(async () => undefined) }));
|
||||
const mockRecalc = jest.fn(async () => 0);
|
||||
jest.mock('../src/utils/coupons', () => ({ recalculateRegistrationDiscount: (...a: unknown[]) => (mockRecalc as jest.Mock)(...a) }));
|
||||
const mockDue = jest.fn(() => 300);
|
||||
jest.mock('../src/utils/pricing', () => ({ computeRegistrationTotalDue: (...a: unknown[]) => (mockDue as jest.Mock)(...a) }));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const tickets = require('../src/utils/ticketUtils');
|
||||
import * as corrections from '../src/services/corrections';
|
||||
|
||||
const admin = { actor: { id: 'adm', role: 'admin' }, ip: '1.2.3.4' };
|
||||
const main = { isMainTicket: true };
|
||||
const QUESTION_FORM = { isRequired: true, fields: [{ type: 'statement' }, { type: 'text' }] };
|
||||
|
||||
/** A registration as generateTicketsForRegistration loads it: one line of `qty` main tickets. */
|
||||
const reg = (extra: object = {}, qty = 2) => ({
|
||||
id: 'r1', userId: 'u1', eventId: 'ev1', status: 'paid', formWaivedAt: null, ticketsReleasedAt: null,
|
||||
registrationOptions: [{ id: 'ro1', eventOptionId: 'adult', variantId: null, sessionId: null, quantity: qty, eventOption: main, tickets: [] }],
|
||||
...extra,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockDb.eventForm.findUnique.mockResolvedValue(null);
|
||||
mockDb.formResponse.count.mockResolvedValue(0);
|
||||
mockDb.registrationOption.findMany.mockResolvedValue([{ id: 'ro1', quantity: 2, tickets: [], attendees: [] }]);
|
||||
mockDb.ticket.create.mockImplementation(async ({ data }: any) => data);
|
||||
});
|
||||
|
||||
describe('which forms hold tickets back', () => {
|
||||
test('a picked-session booking counts its people once, not once per session', () => {
|
||||
const lines = [
|
||||
{ eventOptionId: 'day', variantId: null, sessionId: 's1', quantity: 2, eventOption: main },
|
||||
{ eventOptionId: 'day', variantId: null, sessionId: 's2', quantity: 2, eventOption: main },
|
||||
{ eventOptionId: 'day', variantId: null, sessionId: 's3', quantity: 1, eventOption: main },
|
||||
{ eventOptionId: 'adult', variantId: null, sessionId: null, quantity: 3, eventOption: main },
|
||||
{ eventOptionId: 'tshirt', variantId: null, sessionId: null, quantity: 4, eventOption: { isMainTicket: false } },
|
||||
];
|
||||
expect(tickets.formPlaces(lines)).toBe(5);
|
||||
});
|
||||
|
||||
test('only a required form with a question to answer counts', () => {
|
||||
expect(tickets.formNeedsAnswers(QUESTION_FORM)).toBe(true);
|
||||
expect(tickets.formNeedsAnswers({ isRequired: true, fields: [{ type: 'statement' }, { type: 'paragraph' }] })).toBe(false);
|
||||
expect(tickets.formNeedsAnswers({ isRequired: false, fields: [{ type: 'text' }] })).toBe(false);
|
||||
expect(tickets.formNeedsAnswers(null)).toBe(false);
|
||||
});
|
||||
|
||||
test('forms still needed: places less the forms in; none once left for later', async () => {
|
||||
mockDb.eventForm.findUnique.mockResolvedValue(QUESTION_FORM);
|
||||
mockDb.formResponse.count.mockResolvedValue(1);
|
||||
expect(await tickets.formsOutstanding(reg({}, 3))).toBe(2);
|
||||
expect(await tickets.formsOutstanding(reg({ formWaivedAt: new Date() }, 3))).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generating tickets', () => {
|
||||
test('a required form not filled in holds them back', async () => {
|
||||
mockDb.registration.findUnique.mockResolvedValue(reg());
|
||||
mockDb.eventForm.findUnique.mockResolvedValue(QUESTION_FORM);
|
||||
expect(await tickets.generateTicketsForRegistration('r1')).toEqual([]);
|
||||
expect(mockDb.ticket.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('…until the form is left for later', async () => {
|
||||
mockDb.registration.findUnique.mockResolvedValue(reg({ formWaivedAt: new Date() }));
|
||||
mockDb.eventForm.findUnique.mockResolvedValue(QUESTION_FORM);
|
||||
expect(await tickets.generateTicketsForRegistration('r1')).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('a form with only statements and headings holds nothing back', async () => {
|
||||
mockDb.registration.findUnique.mockResolvedValue(reg());
|
||||
mockDb.eventForm.findUnique.mockResolvedValue({ isRequired: true, fields: [{ type: 'statement' }] });
|
||||
expect(await tickets.generateTicketsForRegistration('r1')).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('unpaid: none, unless an admin released them (and never when cancelled)', async () => {
|
||||
mockDb.registration.findUnique.mockResolvedValueOnce(reg({ status: 'pending' }));
|
||||
expect(await tickets.generateTicketsForRegistration('r1')).toEqual([]);
|
||||
mockDb.registration.findUnique.mockResolvedValueOnce(reg({ status: 'partial_paid', ticketsReleasedAt: new Date() }));
|
||||
expect(await tickets.generateTicketsForRegistration('r1')).toHaveLength(1);
|
||||
mockDb.registration.findUnique.mockResolvedValueOnce(reg({ status: 'cancelled', ticketsReleasedAt: new Date() }));
|
||||
expect(await tickets.generateTicketsForRegistration('r1')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Fill in later', () => {
|
||||
test('stops the tickets waiting, issues and sends them, and sends the form link', async () => {
|
||||
let waived: Date | null = null;
|
||||
mockDb.registration.findUnique.mockImplementation(async () => reg({ formWaivedAt: waived }));
|
||||
mockDb.registration.update.mockImplementation(async ({ data }: any) => { waived = data.formWaivedAt; });
|
||||
mockDb.eventForm.findUnique.mockResolvedValue(QUESTION_FORM);
|
||||
const out = await corrections.leaveFormForLater('r1', { actor: { id: 'st', role: 'staff' } });
|
||||
expect(waived).toBeInstanceOf(Date);
|
||||
expect(out).toEqual({ ticketsIssued: 1, sentTo: ['email'] });
|
||||
expect(mockEmailTickets).toHaveBeenCalledTimes(1);
|
||||
expect(mockReminder).toHaveBeenCalledWith('r1');
|
||||
expect(mockAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'attendee_form_waived', targetId: 'r1' }));
|
||||
});
|
||||
});
|
||||
|
||||
describe('issuing tickets as an admin', () => {
|
||||
test('unpaid needs "pay later"', async () => {
|
||||
mockDb.registration.findUnique.mockResolvedValue(reg({ status: 'pending' }));
|
||||
await expect(corrections.issueTickets('r1', admin, {})).rejects.toThrow('isn\'t paid yet');
|
||||
});
|
||||
|
||||
test('a form still outstanding is refused unless it\'s left for later — and nothing is changed', async () => {
|
||||
mockDb.registration.findUnique.mockResolvedValue(reg({ status: 'pending' }));
|
||||
mockDb.eventForm.findUnique.mockResolvedValue(QUESTION_FORM);
|
||||
await expect(corrections.issueTickets('r1', admin, { payLater: true })).rejects.toThrow('2 attendee forms are still to fill in');
|
||||
expect(mockDb.registration.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('pay later releases them with the balance still owed', async () => {
|
||||
mockDb.registration.findUnique.mockResolvedValue(reg({ status: 'pending' }));
|
||||
mockDb.event.findUnique.mockResolvedValue({ id: 'ev1', scheduleType: 'single', sessions: [], form: null });
|
||||
await corrections.issueTickets('r1', admin, { payLater: true, reason: 'Pays on Friday' }).catch(() => undefined);
|
||||
expect(mockDb.registration.update).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ ticketsReleasedAt: expect.any(Date), ticketsReleasedById: 'adm' }) }));
|
||||
expect(mockDb.registration.update.mock.calls[0][0].data.status).toBeUndefined();
|
||||
expect(mockAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'tickets_issued_override', metadata: expect.objectContaining({ payLater: true, reason: 'Pays on Friday' }) }));
|
||||
});
|
||||
|
||||
test('make it free writes the balance off as a discount and marks it paid', async () => {
|
||||
mockDb.registration.findUnique.mockImplementation(async (q: any) => (q.include?.payments
|
||||
? { ...reg({ status: 'partial_paid' }), complimentaryDiscount: 0, payments: [{ amount: 100 }] }
|
||||
: reg({ status: 'partial_paid' })));
|
||||
mockDb.event.findUnique.mockResolvedValue({ id: 'ev1', scheduleType: 'single', sessions: [], form: null });
|
||||
const out = await corrections.makeComplimentary('r1', admin, { reason: 'Speaker' }).catch((e: Error) => e);
|
||||
expect(mockDb.registration.update).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ complimentaryDiscount: 200 }) }));
|
||||
expect(mockRecalc).toHaveBeenCalledWith('r1');
|
||||
expect(mockDb.registration.update).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ status: 'paid' }) }));
|
||||
expect(mockAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'registration_complimentary', metadata: expect.objectContaining({ amount: 200 }) }));
|
||||
expect(out).toMatchObject({ amount: 200 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('check-in after the event', () => {
|
||||
const ticket = (extra: object = {}) => ({
|
||||
id: 't1', eventId: 'ev1', quantity: 2, usages: [], event: { id: 'ev1', scheduleType: 'single' },
|
||||
registrationOption: { sessionId: null, sessionIds: [], registration: { status: 'paid' } }, ...extra,
|
||||
});
|
||||
|
||||
test('checks everyone left in as a manual check-in, with no window or closed-event check', async () => {
|
||||
mockDb.ticket.findUnique.mockResolvedValue(ticket({ usages: [{ id: 'u0', quantityRedeemed: 1, sessionId: null }] }));
|
||||
mockDb.ticketUsage.findMany.mockResolvedValue([{ quantityRedeemed: 1, sessionId: null }, { quantityRedeemed: 1, sessionId: null }]);
|
||||
const out = await corrections.correctCheckIn('t1', admin, {});
|
||||
expect(mockDb.ticketUsage.create).toHaveBeenCalledWith({ data: { ticketId: 't1', scannedById: 'adm', quantityRedeemed: 1, sessionId: null, manual: true } });
|
||||
expect(mockDb.ticket.update).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ isUsed: true }) }));
|
||||
expect(out).toEqual({ checkedIn: 2, quantity: 2 });
|
||||
expect(mockAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'checkin_corrected' }));
|
||||
});
|
||||
|
||||
test('undo removes the check-ins; a full ticket can\'t be checked in again', async () => {
|
||||
mockDb.ticket.findUnique.mockResolvedValue(ticket({ usages: [{ id: 'u0', quantityRedeemed: 2, sessionId: null }] }));
|
||||
await expect(corrections.correctCheckIn('t1', admin, {})).rejects.toThrow('already checked in');
|
||||
mockDb.ticketUsage.findMany.mockResolvedValue([]);
|
||||
await corrections.correctCheckIn('t1', admin, { present: false });
|
||||
expect(mockDb.ticketUsage.deleteMany).toHaveBeenCalledWith({ where: { id: { in: ['u0'] } } });
|
||||
});
|
||||
|
||||
test('multi-day: the session must be the event\'s and on the ticket', async () => {
|
||||
mockDb.ticket.findUnique.mockResolvedValue(ticket({ event: { id: 'ev1', scheduleType: 'sessions' }, registrationOption: { sessionId: 's1', sessionIds: [], registration: { status: 'paid' } } }));
|
||||
await expect(corrections.correctCheckIn('t1', admin, {})).rejects.toThrow('Choose one of this event');
|
||||
mockDb.eventSession.findUnique.mockResolvedValue({ id: 's2', eventId: 'ev1', cancelledAt: null });
|
||||
await expect(corrections.correctCheckIn('t1', admin, { sessionId: 's2' })).rejects.toThrow('isn\'t booked for this session');
|
||||
mockDb.eventSession.findUnique.mockResolvedValue({ id: 's1', eventId: 'ev1', cancelledAt: null });
|
||||
mockDb.ticketUsage.findMany.mockResolvedValue([{ quantityRedeemed: 2, sessionId: 's1' }]);
|
||||
await corrections.correctCheckIn('t1', admin, { sessionId: 's1' });
|
||||
expect(mockDb.ticketUsage.create).toHaveBeenCalledWith({ data: expect.objectContaining({ sessionId: 's1', manual: true, quantityRedeemed: 2 }) });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
import { z } from 'zod';
|
||||
|
||||
// 1.52.1: the API document describes every route. Routes answered by a v1 handler carry
|
||||
// `documented` shapes — in the document, never enforced, and logged outside production when the
|
||||
// real body or answer doesn't fit them.
|
||||
|
||||
jest.mock('../src/middleware/authMiddleware', () => ({
|
||||
protect: (_req: unknown, _res: unknown, next: () => void) => next(),
|
||||
optionalAuth: (_req: unknown, _res: unknown, next: () => void) => next(),
|
||||
admin: (_req: unknown, _res: unknown, next: () => void) => next(),
|
||||
staff: (_req: unknown, _res: unknown, next: () => void) => next(),
|
||||
supervisor: (_req: unknown, _res: unknown, next: () => void) => next(),
|
||||
loginLimiter: (_req: unknown, _res: unknown, next: () => void) => next(),
|
||||
}));
|
||||
|
||||
import { defineRoute, mount } from '../src/v2/route';
|
||||
import { buildOpenApi } from '../src/v2/openapi';
|
||||
import { errorHandler } from '../src/v2/errors';
|
||||
|
||||
const documented = defineRoute({
|
||||
method: 'post', path: '/docs-test/things', tag: 'Test', summary: 'Make a thing', access: 'public',
|
||||
body: z.looseObject({}),
|
||||
response: z.object({ data: z.unknown() }),
|
||||
documented: { body: z.object({ name: z.string() }), response: z.object({ id: z.string(), name: z.string() }) },
|
||||
handler: ({ req }) => ({ data: (req.body as { name?: unknown }).name === 'odd' ? { id: 1 } : { id: 't1', name: String((req.body as { name?: unknown }).name) } }),
|
||||
});
|
||||
const action = defineRoute({
|
||||
method: 'post', path: '/docs-test/things/:id/poke', tag: 'Test', summary: 'Poke a thing', access: 'public',
|
||||
params: z.object({ id: z.string() }), query: z.looseObject({ from: z.string().optional() }), body: z.looseObject({}), response: z.object({ data: z.unknown() }),
|
||||
handler: () => ({ data: null }),
|
||||
});
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
const router = express.Router();
|
||||
mount(router, [documented, action]);
|
||||
router.use(errorHandler);
|
||||
app.use('/api/v2', router);
|
||||
|
||||
describe('documented shapes', () => {
|
||||
const doc = buildOpenApi({ version: 'test', list: [documented, action] }) as any;
|
||||
const op = doc.paths['/docs-test/things'].post;
|
||||
|
||||
test('are what the document shows, in place of the generic body and answer', () => {
|
||||
expect(op.requestBody.required).toBe(true);
|
||||
expect(op.requestBody.content['application/json'].schema.properties.name).toEqual({ type: 'string' });
|
||||
expect(op.responses['200'].content['application/json'].schema.properties.data.properties).toEqual({ id: { type: 'string' }, name: { type: 'string' } });
|
||||
});
|
||||
|
||||
test('an action with no input says it needs no body; parameters get their common description', () => {
|
||||
const poke = doc.paths['/docs-test/things/{id}/poke'].post;
|
||||
expect(poke.requestBody).toMatchObject({ required: true, description: expect.stringContaining('No body needed') });
|
||||
expect(poke.parameters).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ name: 'id', in: 'path', description: 'The id' }),
|
||||
expect.objectContaining({ name: 'from', in: 'query', description: expect.stringContaining('On or after') }),
|
||||
]));
|
||||
});
|
||||
|
||||
test('are never enforced: a body or answer that doesn\'t fit still goes through, and is logged', async () => {
|
||||
const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
const fits = await request(app).post('/api/v2/docs-test/things').send({ name: 'Bob' });
|
||||
expect(fits.status).toBe(200);
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
|
||||
const odd = await request(app).post('/api/v2/docs-test/things').send({ name: 'odd' });
|
||||
expect(odd.status).toBe(200);
|
||||
expect(odd.body).toEqual({ data: { id: 1 } });
|
||||
const noName = await request(app).post('/api/v2/docs-test/things').send({});
|
||||
expect(noName.status).toBe(200);
|
||||
expect(warn.mock.calls.map(c => c[0])).toEqual([
|
||||
expect.stringContaining('answer doesn\'t match its documented schema'),
|
||||
expect.stringContaining('request body doesn\'t match its documented schema'),
|
||||
]);
|
||||
warn.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the whole API document', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
require('../src/v2');
|
||||
const doc = buildOpenApi({ version: 'test' }) as any;
|
||||
// (Leaving out this file's own test routes.)
|
||||
const ops = Object.entries<any>(doc.paths).filter(([path]) => !path.startsWith('/docs-test')).flatMap(([path, methods]) => Object.entries<any>(methods).map(([method, op]) => ({ path, method, op })));
|
||||
const isBlank = (s: any) => !s || Object.keys(s).length === 0 || (s.type === 'object' && !s.properties && !s.additionalProperties && !s.description);
|
||||
|
||||
test('every JSON answer says what\'s in it', () => {
|
||||
const blank = ops.filter(({ op }) => {
|
||||
const json = Object.entries<any>(op.responses).find(([code]) => code.startsWith('2'))?.[1]?.content?.['application/json'];
|
||||
if (!json) return false;
|
||||
const data = json.schema?.properties?.data;
|
||||
return isBlank(data) || (data?.type === 'array' && isBlank(data.items));
|
||||
}).map(({ method, path }) => `${method.toUpperCase()} ${path}`);
|
||||
// A JSON file download (my data) is the one answer that's a file, not a shape.
|
||||
expect(blank).toEqual(['GET /me/privacy/export']);
|
||||
});
|
||||
|
||||
test('every body that takes something says what, and every parameter is described', () => {
|
||||
const undescribed = ops.flatMap(({ method, path, op }) => op.parameters.filter((p: any) => !p.description).map((p: any) => `${method} ${path} ${p.in}:${p.name}`));
|
||||
expect(undescribed).toEqual([]);
|
||||
const bodies = ops.filter(({ op }) => op.requestBody?.content?.['application/json']);
|
||||
for (const { op } of bodies) {
|
||||
const schema = op.requestBody.content['application/json'].schema;
|
||||
const takesSomething = (!!schema.properties && Object.keys(schema.properties).length > 0) || !!schema.additionalProperties?.type || !!schema.description;
|
||||
if (!takesSomething) expect(op.requestBody.description).toMatch(/No body needed/);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user