import { z } from 'zod'; import type { Request } from 'express'; import { defineRoute, type ApiUser } from '../route'; import { pageOf, single } from '../paging'; import { id, idParams } from '../schemas'; import * as admin from '../../services/registrationAdmin'; /* eslint-disable @typescript-eslint/no-explicit-any -- registrations are passed through with their includes */ const campusScope = require('../../utils/campusScope') as { listWhere(req: unknown, path?: string): Promise; scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown; ownerOk?: boolean }): any; scopeBody(targets: [string, string][], opts?: { need?: 'view' | 'manage'; orphan?: 'pass' | 'deny' }): any; }; const { notOnSeasonPass } = require('../../utils/seasonPass') as { notOnSeasonPass: any }; const plain = (v: T): any => JSON.parse(JSON.stringify(v)); /** The v2 request as the registration service's Call. */ function callFrom(req: Request, user: ApiUser | null, parts: { params?: object; body?: object; query?: object }): admin.Call { const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; return { actor: user ? { id: user.id, role: user.role, email: user.email } : null, params: (parts.params ?? {}) as Record, body: parts.body ?? {}, query: parts.query ?? {}, readOnly: !!(req as any).readOnly, ip: getClientIp(req), listWhere: () => campusScope.listWhere(req, 'event'), }; } const OWNER_OR_STAFF = 'scopeEvent(registration, owner-ok)'; const ownerOrStaff = campusScope.scopeEvent({ resolve: 'registration', ownerOk: true }); const STATUSES = ['pending', 'confirmed', 'partial_paid', 'paid', 'cancelled'] as const; /** A registration with everything the dashboards show: items and their prices, payments, attendees, coupons, `totalDueComputed`. */ const fullRegistration = z.looseObject({ id, status: z.enum(STATUSES), eventId: id, userId: id, totalDueComputed: z.number().optional() }); const message = single(z.looseObject({ message: z.string() })); const lineBody = z.object({ eventOptionId: id, variantId: id.nullish(), quantity: z.number().int().min(1).max(1000), sessionIds: z.array(id).max(200).optional() }); const attendeeBody = z.looseObject({ id: id.optional().describe('An attendee already on it (left out = removed)'), eventOptionId: id, variantId: id.nullish(), name: z.string().max(200) }); const responsesBody = z.object({ responses: z.array(z.object({ attendeeId: id.nullish().describe('The named attendee this form is for'), answers: z.record(z.string(), z.unknown()).describe('Field id → answer (stored as text)'), })).max(500), }); // ─── Owner (or staff) ──────────────────────────────────────────────────────── export const fullOne = defineRoute({ method: 'get', path: '/registrations/:id/full', tag: 'Registrations', summary: 'A registration with everything on it', description: [ 'Items and prices, payments, coupons and bundles, named attendees, form answers and the total due.', 'The owner, a named attendee or staff — or anyone with the link when not signed in (registration ids can\'t be guessed). Attendees\' contact details are only shown to the payer and staff.', ].join('\n\n'), access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, response: single(fullRegistration), async handler({ params, user, req }) { return { data: plain(await admin.getRegistrationById(callFrom(req, user, { params }))) }; }, }); export const myFull = defineRoute({ method: 'get', path: '/me/registrations/full', tag: 'Me', summary: 'My registrations with everything on them', description: 'What the dashboard shows: as `/registrations/{id}/full`, newest first, with the event and its form. Only upcoming ones unless `past=true`.', access: 'user', query: z.object({ past: z.enum(['true', 'false']).default('false') }), response: z.object({ data: z.array(fullRegistration) }), async handler({ query, user, req }) { return { data: plain(await admin.getUserRegistrations(callFrom(req, user, { query: { showPast: query.past } }))) }; }, }); export const changeItems = defineRoute({ method: 'put', path: '/registrations/:id/items', tag: 'Registrations', summary: 'Change the tickets on a registration', description: [ 'The whole list of items it should have. Added places need stock and are priced now; places already paid for keep their price, and nothing goes below tickets already issued or the amount paid.', 'Not for registrations made with a season pass, nor once the event has ended or is closed. Staff can add kids and volunteer places; owners can only keep or lower them.', ].join('\n\n'), access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff, notOnSeasonPass], params: idParams, body: z.object({ options: z.array(lineBody.omit({ sessionIds: true })).min(1).max(100) }), response: single(fullRegistration), async handler({ params, body, user, req }) { return { data: plain(await admin.updateRegistrationOptions(callFrom(req, user, { params, body }))) }; }, }); export const sendInvoice = defineRoute({ method: 'post', path: '/registrations/:id/invoice', tag: 'Registrations', summary: 'Send me the invoice again', access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, body: z.object({ channel: z.enum(['email', 'whatsapp']).default('email') }), response: message, async handler({ params, body, user, req }) { return { data: await admin.sendInvoice(callFrom(req, user, { params, body })) }; }, }); export const applyCoupon = defineRoute({ method: 'post', path: '/registrations/:id/coupon', tag: 'Registrations', summary: 'Apply a coupon code', description: 'By the owner, or by staff on their behalf (logged). Not on season pass registrations.', access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff, notOnSeasonPass], params: idParams, body: z.object({ code: z.string().trim().min(1).max(40) }), response: single(fullRegistration.extend({ message: z.string() })), async handler({ params, body, user, req }) { return { data: plain(await admin.applyCoupon(callFrom(req, user, { params, body }))) }; }, }); export const removeCoupon = defineRoute({ method: 'delete', path: '/registrations/:id/coupon', tag: 'Registrations', summary: 'Take a coupon code off', description: 'Staff. Its use is freed. Not once a ticket on it has been scanned; unused tickets are withdrawn if it\'s no longer paid.', access: 'staff', campusScope: 'scopeEvent(registration)', middleware: [campusScope.scopeEvent({ resolve: 'registration' })], params: idParams, response: message, async handler({ params, user, req }) { return { data: await admin.removeCoupon(callFrom(req, user, { params })) }; }, }); export const setAttendees = defineRoute({ method: 'put', path: '/registrations/:id/attendees', tag: 'Registrations', summary: 'Name the people on a registration', description: 'The whole list: attendees left out are removed (not once their ticket has been scanned). `ticketDelivery` says who gets the tickets.', access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, body: z.object({ attendees: z.array(attendeeBody).max(1000), ticketDelivery: z.enum(['payer', 'each']).optional() }), response: single(z.looseObject({ id, ticketDelivery: z.string().nullable(), attendees: z.array(z.looseObject({ id, name: z.string() })) })), async handler({ params, body, user, req }) { return { data: plain(await admin.updateAttendees(callFrom(req, user, { params, body }))) }; }, }); export const sendFormLink = defineRoute({ method: 'post', path: '/registrations/:id/attendees/:attendeeId/form-link', tag: 'Registrations', summary: 'Send an attendee their form', description: 'A link to fill in their own attendee form, by email and/or WhatsApp.', access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: z.object({ id, attendeeId: id }), response: message, async handler({ params, user, req }) { return { data: await admin.sendAttendeeFormLink(callFrom(req, user, { params })) }; }, }); export const getDraft = defineRoute({ method: 'get', path: '/registrations/:id/form-draft', tag: 'Registrations', summary: 'Attendee forms saved part-way', access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, response: single(z.object({ data: z.record(z.string(), z.unknown()), updatedAt: z.string().nullable() })), async handler({ params, user, req }) { return { data: plain(await admin.getFormDraft(callFrom(req, user, { params }))) }; }, }); export const saveDraft = defineRoute({ method: 'put', path: '/registrations/:id/form-draft', tag: 'Registrations', summary: 'Save attendee forms part-way', description: 'Kept for the registration\'s owner (also when staff save it), until the forms are submitted.', access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, body: z.object({ data: z.record(z.string(), z.unknown()) }), response: single(z.object({ message: z.string(), updatedAt: z.string() })), async handler({ params, body, user, req }) { return { data: plain(await admin.saveFormDraft(callFrom(req, user, { params, body }))) }; }, }); export const submitForms = defineRoute({ method: 'post', path: '/registrations/:id/form-responses', tag: 'Registrations', summary: 'Submit attendee forms', description: 'One response per main ticket at most; each named attendee answers once. Tickets are issued once it\'s paid and the forms are in.', access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, body: responsesBody, response: single(z.looseObject({ message: z.string(), count: z.number().int().optional() })), async handler({ params, body, user, req }) { return { data: plain(await admin.submitFormResponses(callFrom(req, user, { params, body }))) }; }, }); export const replaceForms = defineRoute({ method: 'put', path: '/registrations/:id/form-responses', tag: 'Registrations', summary: 'Replace the attendee forms', description: 'Supervisors: every response on the registration is replaced by these.', access: 'supervisor', campusScope: 'scopeEvent(registration)', middleware: [campusScope.scopeEvent({ resolve: 'registration' })], params: idParams, body: responsesBody, response: message, async handler({ params, body, user, req }) { return { data: await admin.replaceFormResponses(callFrom(req, user, { params, body })) }; }, }); // ─── Staff ─────────────────────────────────────────────────────────────────── export const list = defineRoute({ method: 'get', path: '/registrations', tag: 'Registrations', summary: 'Every registration (staff)', description: 'Newest first, for the events you may see. `unpaid=true` for ones still owing; `userId` for one person\'s.', access: 'staff', campusScope: 'scopeList (listWhere)', query: z.object({ page: z.coerce.number().int().min(1).default(1), limit: z.coerce.number().int().min(1).max(200).default(100).describe('At most 200'), unpaid: z.enum(['true', 'false']).default('false'), userId: id.optional(), }), response: z.object({ data: z.array(fullRegistration), meta: z.object({ page: z.number().int(), limit: z.number().int(), total: z.number().int(), pages: z.number().int() }) }), async handler({ query, user, req }) { const out = await admin.getRegistrations(callFrom(req, user, { query: { page: String(query.page), limit: String(query.limit), unpaid: query.unpaid === 'true' ? '1' : '', userId: query.userId } })); return pageOf(plain(out.data), out.total, { page: out.page, limit: out.limit }); }, }); export const forEvent = defineRoute({ method: 'get', path: '/events/:id/registrations', tag: 'Registrations', summary: 'An event\'s registrations', description: 'Oldest first, with tickets, payments and attendees. `search` matches the name, email or phone.', access: 'staff', campusScope: 'scopeEvent(view)', middleware: [campusScope.scopeEvent()], params: idParams, query: z.object({ search: z.string().max(200).optional() }), response: z.object({ data: z.array(fullRegistration) }), async handler({ params, query, user, req }) { return { data: plain(await admin.getRegistrationsByEvent(callFrom(req, user, { params: { eventId: params.id }, query }))) }; }, }); export const setStatus = defineRoute({ method: 'patch', path: '/registrations/:id/status', tag: 'Registrations', summary: 'Set a registration\'s status', description: 'Staff. `paid` issues and sends the tickets; leaving `paid` withdraws unused tickets (refused once one has been scanned); `cancelled` frees its places for the waitlist.', access: 'staff', campusScope: 'scopeEvent(registration)', middleware: [campusScope.scopeEvent({ resolve: 'registration' })], params: idParams, body: z.object({ status: z.enum(STATUSES) }), response: single(fullRegistration), async handler({ params, body, user, req }) { return { data: plain(await admin.updateRegistrationStatus(callFrom(req, user, { params, body }))) }; }, }); export const manual = defineRoute({ method: 'post', path: '/registrations/manual', tag: 'Registrations', summary: 'Register someone (at the door, by phone)', description: [ 'Supervisors. Finds the person by email or phone (refused when those are two different accounts) or makes an account and sends them an activation link (`skipActivationNotice` to not).', 'Added to their existing registration for the event if they have one. Free ones are marked paid and get their tickets; otherwise they\'re sent a link to pay.', ].join('\n\n'), access: 'supervisor', campusScope: 'scopeEvent(body.eventId)', middleware: [campusScope.scopeEvent({ from: req => req.body?.eventId })], status: 201, body: z.looseObject({ eventId: id, options: z.array(lineBody).min(1).max(100), user: z.looseObject({ name: z.string().trim().min(1).max(200), email: z.string().max(200).nullish(), phoneNumber: z.string().max(40).nullish(), password: z.string().max(200).optional().describe('Self-service kiosk: the visitor sets it, and the account is active at once') }), notificationPreference: z.enum(['email', 'whatsapp', 'both']).optional(), skipActivationNotice: z.boolean().optional(), couponCode: z.string().max(40).optional(), attendees: z.array(attendeeBody).max(1000).optional(), ticketDelivery: z.enum(['payer', 'each']).optional(), }), response: single(fullRegistration.extend({ couponError: z.string().optional() })), async handler({ body, user, req }) { return { data: plain(await admin.createManualRegistration(callFrom(req, user, { body }))) }; }, }); export const bulk = defineRoute({ method: 'post', path: '/registrations/bulk', tag: 'Registrations', summary: 'Do one thing to many registrations', description: '`markPaid`, `cancel`, `moveOption`, `allocate` or `message`, for up to 500 you may manage. Each is done on its own: the answer lists what worked and what didn\'t.', access: 'supervisor', campusScope: 'scopeBody(registrationIds, deny orphans)', middleware: [campusScope.scopeBody([['registrationIds', 'registration']], { orphan: 'deny' })], body: z.looseObject({ action: z.enum(['markPaid', 'cancel', 'moveOption', 'allocate', 'message']), registrationIds: z.array(id).min(1).max(500) }), response: single(z.looseObject({})), async handler({ body, req }) { const { runBulk } = require('../../utils/bulkRegistrations') as { runBulk(req: unknown, body: object): Promise }; return { data: plain(await runBulk(req, body)) }; }, });