import { z } from 'zod'; import type { Request } from 'express'; import { defineRoute, fileResponse, type ApiUser } from '../route'; import { ApiError } from '../errors'; import { single } from '../paging'; import { absoluteUrl, id, idParams, isoDate } from '../schemas'; import * as details from '../../services/eventDetails'; import { managedEvent } from './eventsManage'; /* eslint-disable @typescript-eslint/no-explicit-any -- stored records are passed through */ const campusScope = require('../../utils/campusScope') as { scopeFor(req: unknown): Promise; scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown }): any; }; // The same multer step as v1 (field "file"; PDFs, Office files, text, CSV, ZIP; 20 MB). const { receiveAttachment } = require('../../controllers/eventController') as { receiveAttachment: any }; const urlOf = (req: Request) => (u: string | null | undefined) => absoluteUrl(req, u); const plain = (v: T): any => JSON.parse(JSON.stringify(v)); const viewerOf = async (req: Request, user: ApiUser | null) => ({ staff: !!user && ['admin', 'supervisor', 'staff'].includes(user.role), scope: await campusScope.scopeFor(req) }); // ─── The event in full, calendar file, short link ────────────────────────────── export const full = defineRoute({ method: 'get', path: '/events/:id/full', tag: 'Events', summary: 'One event in full', description: [ 'What the registration page and the set-up screens need: ticket options with what\'s left (per variant, and per session for "pick sessions" tickets), early-bird tiers, sessions with bookings, the attendee form, attachments, bundle deals on sale and the next event in its series.', 'Staff (of a campus they work with) also get inactive and not-yet-live events, who created it, who gets its emails, and the kids/volunteer tickets. Everyone else gets NOT_FOUND for events that aren\'t public.', ].join('\n\n'), access: 'optional', params: idParams, response: single(managedEvent.extend({ form: z.looseObject({ id, isRequired: z.boolean(), fields: z.array(z.looseObject({ id, type: z.string(), label: z.string() })) }).nullable(), attachments: z.array(z.looseObject({ id, originalName: z.string(), url: z.string().nullable() })), })), async handler({ params, user, req }) { return { data: plain(await details.getEventDetail(params.id, await viewerOf(req, user), urlOf(req))) }; }, }); export const calendar = defineRoute({ method: 'get', path: '/events/:id/calendar.ics', tag: 'Events', summary: 'The event as a calendar file', description: 'An .ics file (each session for a multi-day event). Same visibility as the event.', access: 'optional', file: { contentType: 'text/calendar' }, params: idParams, response: fileResponse, async handler({ params, user, req }) { const { filename, ics } = await details.eventCalendar(params.id, await viewerOf(req, user)); return { data: { contentType: 'text/calendar; charset=utf-8', filename, body: ics } }; }, }); export const byAlias = defineRoute({ method: 'get', path: '/events/by-alias/:alias', tag: 'Events', summary: 'An event by its short link', description: 'The part after the site address (`/camp2026`), any letter case. Active events only.', access: 'public', params: z.object({ alias: z.string().min(1).max(100).describe('The short link, e.g. camp2026') }), response: single(z.object({ id, title: z.string(), description: z.string().nullable(), startDate: isoDate, endDate: isoDate, registrationDeadline: isoDate.nullable(), goLiveAt: isoDate.nullable(), price: z.number(), picture: z.string().nullable(), redirectUrl: z.string().nullable(), isLive: z.boolean().describe('Not over yet'), })), async handler({ params, req }) { const ev = plain(await details.eventByAlias(params.alias)); return { data: { ...ev, picture: absoluteUrl(req, ev.picture) } }; }, }); // ─── Ticket options and variants ───────────────────────────────────────────── const variant = z.looseObject({ id, name: z.string(), price: z.number().nullable(), stockLimit: z.number().int(), staffPrice: z.number().nullable(), order: z.number().int() }); const tier = z.looseObject({ id, deadline: isoDate, price: z.number(), stockLimit: z.number().int(), variantId: id.nullable() }); const ticketOption = z.looseObject({ id, eventId: id, name: z.string(), price: z.number(), isMainTicket: z.boolean(), stockLimit: z.number().int(), staffPrice: z.number().nullable(), sessionMode: z.enum(['all', 'pick']), earlyBirdTiers: z.array(tier).optional(), variants: z.array(variant).optional(), }); const money = z.union([z.number(), z.string().max(20)]); const optionBody = z.object({ name: z.string().trim().min(1).max(120), price: money, isMainTicket: z.boolean().optional(), stockLimit: z.union([z.number().int().min(0), z.string().max(10)]).optional().describe('0 = no limit'), staffPrice: money.nullable().optional().describe('What staff pay (empty = the normal price)'), sessionMode: z.enum(['all', 'pick']).optional().describe('"pick" = buyers choose sessions (multi-day events)'), }); const variantBody = z.object({ name: z.string().trim().min(1).max(120), price: money.nullable().optional().describe('Empty = the option\'s price'), stockLimit: z.union([z.number().int().min(0), z.string().max(10)]).optional(), staffPrice: money.nullable().optional(), order: z.union([z.number().int(), z.string().max(10)]).optional(), }); export const createOption = defineRoute({ method: 'post', path: '/events/:id/ticket-options', tag: 'Events (staff)', summary: 'Add a ticket option', access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [campusScope.scopeEvent({ need: 'manage' })], status: 201, params: idParams, body: optionBody, response: single(ticketOption), async handler({ params, body }) { return { data: plain(await details.createOption(params.id, body)) }; }, }); export const updateOption = defineRoute({ method: 'patch', path: '/ticket-options/:id', tag: 'Events (staff)', summary: 'Change a ticket option', description: 'Only what\'s sent changes. `earlyBirdTiers` and `variants`, when sent, are the full lists: kept by id, added without one, and ones left out removed when nothing was bought under them.', access: 'supervisor', campusScope: 'scopeEvent(eventOption, manage)', middleware: [campusScope.scopeEvent({ resolve: 'eventOption', need: 'manage' })], params: idParams, body: optionBody.partial().extend({ earlyBirdTiers: z.array(z.looseObject({ id: id.optional(), deadline: z.string().max(40), price: money, stockLimit: z.union([z.number(), z.string()]).optional(), variantId: id.nullable().optional() })).max(50).optional(), variants: z.array(variantBody.extend({ id: id.optional() })).max(100).optional(), }), response: single(ticketOption), async handler({ params, body }) { return { data: plain(await details.updateOption(params.id, body)) }; }, }); export const deleteOption = defineRoute({ method: 'delete', path: '/ticket-options/:id', tag: 'Events (staff)', summary: 'Remove a ticket option', description: 'Admins only. Not one anybody has bought, and never the event\'s only main ticket.', access: 'admin', params: idParams, response: single(z.object({ id, deleted: z.literal(true) })), async handler({ params }) { await details.deleteOption(params.id); return { data: { id: params.id, deleted: true as const } }; }, }); export const createVariant = defineRoute({ method: 'post', path: '/ticket-options/:id/variants', tag: 'Events (staff)', summary: 'Add a variant (e.g. a T-shirt size)', access: 'supervisor', campusScope: 'scopeEvent(eventOption, manage)', middleware: [campusScope.scopeEvent({ resolve: 'eventOption', need: 'manage' })], status: 201, params: idParams, body: variantBody, response: single(variant), async handler({ params, body }) { return { data: plain(await details.createVariant(params.id, body)) }; }, }); export const updateVariant = defineRoute({ method: 'patch', path: '/variants/:id', tag: 'Events (staff)', summary: 'Change a variant', access: 'supervisor', campusScope: 'scopeEvent(optionVariant, manage)', middleware: [campusScope.scopeEvent({ resolve: 'optionVariant', need: 'manage' })], params: idParams, body: variantBody.partial(), response: single(variant), async handler({ params, body }) { return { data: plain(await details.updateVariant(params.id, body)) }; }, }); export const deleteVariant = defineRoute({ method: 'delete', path: '/variants/:id', tag: 'Events (staff)', summary: 'Remove a variant', description: 'Admins only, and not one anybody has bought.', access: 'admin', params: idParams, response: single(z.object({ id, deleted: z.literal(true) })), async handler({ params }) { await details.deleteVariant(params.id); return { data: { id: params.id, deleted: true as const } }; }, }); // ─── Attachments ───────────────────────────────────────────────────────────── const attachment = z.object({ id, eventId: id, originalName: z.string(), filename: z.string(), mimeType: z.string(), size: z.number().int(), url: z.string().nullable(), createdAt: isoDate }); export const listAttachments = defineRoute({ method: 'get', path: '/events/:id/attachments', tag: 'Events', summary: 'An event\'s attachments', description: 'Files for attendees (programmes, packing lists…), newest first.', access: 'public', params: idParams, response: z.object({ data: z.array(attachment) }), async handler({ params, req }) { return { data: plain(await details.listAttachments(params.id, urlOf(req))) }; }, }); export const uploadAttachment = defineRoute({ method: 'post', path: '/events/:id/attachments', tag: 'Events (staff)', summary: 'Attach a file to an event', access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [campusScope.scopeEvent({ need: 'manage' }), receiveAttachment], upload: { field: 'file', description: 'PDF, Word, Excel, PowerPoint, text, CSV or ZIP, up to 20 MB' }, status: 201, params: idParams, response: single(attachment), async handler({ params, req }) { const r = req as Request & { multerError?: Error; file?: { originalname: string; filename: string; mimetype: string; size: number } }; if (r.multerError) throw new ApiError('VALIDATION_FAILED', r.multerError.message, { file: r.multerError.message }); if (!r.file) throw new ApiError('VALIDATION_FAILED', 'No file uploaded', { file: 'Choose a file' }); return { data: plain(await details.recordAttachment(params.id, r.file, urlOf(req))) }; }, }); export const deleteAttachment = defineRoute({ method: 'delete', path: '/events/:id/attachments/:attachmentId', tag: 'Events (staff)', summary: 'Remove an attachment', access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [campusScope.scopeEvent({ need: 'manage' })], params: z.object({ id, attachmentId: id }), response: single(z.object({ id, deleted: z.literal(true) })), async handler({ params }) { await details.deleteAttachment(params.id, params.attachmentId); return { data: { id: params.attachmentId, deleted: true as const } }; }, }); export const attachmentsStatus = defineRoute({ method: 'get', path: '/attachments/status', tag: 'Admin', summary: 'Attachments diagnostics', access: 'admin', response: single(z.looseObject({ databaseTableQueryable: z.boolean(), probeError: z.string().nullable() })), async handler() { return { data: plain(await details.attachmentsStatus()) }; }, }); export const attachmentsSync = defineRoute({ method: 'post', path: '/attachments/sync', tag: 'Admin', summary: 'Import attachments from old manifests', description: 'Attachments recorded in JSON files on disk by very old versions go into the database. `dryRun` only reports; `remove` deletes each manifest once imported.', access: 'admin', body: z.object({ dryRun: z.boolean().default(false), remove: z.boolean().default(false) }), response: single(z.looseObject({ dryRun: z.boolean(), remove: z.boolean() })), async handler({ body }) { return { data: plain(await details.syncAttachmentManifests(body)) }; }, });