import { z } from 'zod'; import type { Request, RequestHandler } from 'express'; import { defineRoute } from '../route'; import { ApiError } from '../errors'; import { single } from '../paging'; import { absoluteUrl, id, idParams, isoDate } from '../schemas'; import * as setup from '../../services/setup'; import { prisma } from '../legacy'; import auth from '../../middleware/authMiddleware'; /* eslint-disable @typescript-eslint/no-explicit-any -- multer and the scope middleware are JS */ const campusScope = require('../../utils/campusScope') as { listWhere(req: unknown, path?: string): Promise; scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown }): any; }; const uploads = require('../../controllers/uploadController') as { upload: any; uploadLogo: any; uploadFavicon: any }; const plain = (v: T): any => JSON.parse(JSON.stringify(v)); // ─── Sections ──────────────────────────────────────────────────────────────── const section = z.looseObject({ id, eventId: id, name: z.string(), allowedOptions: z.array(z.looseObject({ eventOptionId: id, eventOption: z.looseObject({ id, name: z.string() }) })), }); export const listSections = defineRoute({ method: 'get', path: '/sections', tag: 'Events (staff)', summary: 'Scanning sections', description: 'Which ticket types may come in at which door, for one event or every event you can see.', access: 'staff', campusScope: 'scopeList (listWhere)', query: z.object({ eventId: id.optional() }), response: z.object({ data: z.array(section.extend({ event: z.object({ id, title: z.string() }) })) }), async handler({ query, req }) { return { data: plain(await setup.listSections(query.eventId, await campusScope.listWhere(req, 'event'))) }; }, }); export const createSection = defineRoute({ method: 'post', path: '/sections', tag: 'Events (staff)', summary: 'Add a scanning section', access: 'supervisor', campusScope: 'scopeEvent(body.eventId, manage)', middleware: [campusScope.scopeEvent({ from: req => req.body?.eventId, need: 'manage' })], status: 201, body: z.object({ eventId: id, name: z.string().trim().min(1).max(120), allowedOptionIds: z.array(id).max(100).optional() }), response: single(section), async handler({ body }) { return { data: plain(await setup.createSection(body)) }; }, }); export const updateSection = defineRoute({ method: 'patch', path: '/sections/:id', tag: 'Events (staff)', summary: 'Change a scanning section', description: '`allowedOptionIds`, when sent, replaces its ticket types.', access: 'supervisor', campusScope: 'scopeEvent(section, manage)', middleware: [campusScope.scopeEvent({ resolve: 'section', need: 'manage' })], params: idParams, body: z.object({ name: z.string().trim().min(1).max(120).optional(), allowedOptionIds: z.array(id).max(100).optional() }), response: single(section), async handler({ params, body }) { return { data: plain(await setup.updateSection(params.id, body)) }; }, }); export const deleteSection = defineRoute({ method: 'delete', path: '/sections/:id', tag: 'Events (staff)', summary: 'Remove a scanning section', access: 'admin', params: idParams, response: single(z.object({ id, deleted: z.literal(true) })), async handler({ params }) { await setup.deleteSection(params.id); return { data: { id: params.id, deleted: true as const } }; }, }); // ─── Planned costs ─────────────────────────────────────────────────────────── const cost = z.object({ id, eventId: id, label: z.string(), costType: z.enum(['once_off', 'per_item']), amount: z.number(), eventOptionId: id.nullable(), eventOption: z.object({ id, name: z.string() }).nullable(), paidFromMethod: z.string().nullable().describe('How it was paid out of the takings (cash, card, eft, other)'), notes: z.string().nullable(), createdAt: isoDate, updatedAt: isoDate.optional(), }); const costBody = z.object({ label: z.string().trim().min(1).max(200), costType: z.enum(['once_off', 'per_item']).describe('per_item = per ticket sold of `eventOptionId`'), amount: z.union([z.number().min(0), z.string().max(20)]), eventOptionId: id.nullable().optional(), notes: z.string().max(2000).nullable().optional(), paidFromMethod: z.enum(['cash', 'card', 'eft', 'other']).nullable().optional(), }); export const listCosts = defineRoute({ method: 'get', path: '/events/:id/costs', tag: 'Events (staff)', summary: 'An event\'s planned costs', access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [campusScope.scopeEvent({ need: 'manage' })], params: idParams, response: z.object({ data: z.array(cost) }), async handler({ params }) { return { data: plain(await setup.listCosts(params.id)) }; }, }); export const createCost = defineRoute({ method: 'post', path: '/events/:id/costs', tag: 'Events (staff)', summary: 'Add a planned cost', description: 'Admins. Not on a cashed-up event.', access: 'admin', status: 201, params: idParams, body: costBody, response: single(cost), async handler({ params, body }) { return { data: plain(await setup.createCost(params.id, body)) }; }, }); export const updateCost = defineRoute({ method: 'patch', path: '/costs/:id', tag: 'Events (staff)', summary: 'Change a planned cost', access: 'admin', params: idParams, body: costBody.partial(), response: single(cost), async handler({ params, body }) { return { data: plain(await setup.updateCost(params.id, body)) }; }, }); export const deleteCost = defineRoute({ method: 'delete', path: '/costs/:id', tag: 'Events (staff)', summary: 'Remove a planned cost', access: 'admin', params: idParams, response: single(z.object({ id, deleted: z.literal(true) })), async handler({ params }) { await setup.deleteCost(params.id); return { data: { id: params.id, deleted: true as const } }; }, }); // ─── Image uploads ─────────────────────────────────────────────────────────── /** Runs a multer step for field "image", keeping any error on the request. */ const receive = (m: any): RequestHandler => (req, res, next) => m.single('image')(req, res, (e: Error | undefined) => { if (e) (req as Request & { multerError?: Error }).multerError = e; next(); }); /** Branding images: admins — or anyone during first-time setup, before any account exists. */ const brandingAccess: RequestHandler = async (req, res, next) => { try { if (await prisma.user.count() === 0) return next(); } catch { /* fall through to the admin check */ } auth.protect(req, res, (e?: unknown) => (e ? next(e) : auth.admin(req, res, next))); }; const uploaded = (folder: string) => async ({ req }: { req: Request }) => { const r = req as Request & { multerError?: Error; file?: { filename: string } }; if (r.multerError) throw new ApiError('VALIDATION_FAILED', `Upload failed: ${r.multerError.message}`, { image: r.multerError.message }); if (!r.file) throw new ApiError('VALIDATION_FAILED', 'No file uploaded', { image: 'Choose an image' }); const path = `/uploads/${folder}/${r.file.filename}`; return { data: { path, url: absoluteUrl(req, path)! } }; }; const uploadResult = single(z.object({ path: z.string().describe('What to save on the event or setting'), url: z.string().describe('The same, as a full address') })); const IMAGE = 'A JPEG, PNG, GIF or WebP image'; const LOGO = 'A JPEG, PNG, WebP or SVG image'; export const uploadEventImage = defineRoute({ method: 'post', path: '/uploads/event-image', tag: 'Uploads', summary: 'Upload an event picture', description: 'Returns the path to save as the event\'s `picture`.', access: 'supervisor', campusScope: 'campusIndependent (only stores the file; the event is checked when it is saved)', middleware: [receive(uploads.upload)], upload: { field: 'image', description: IMAGE }, response: uploadResult, handler: uploaded('events'), }); export const uploadLogo = defineRoute({ method: 'post', path: '/uploads/logo', tag: 'Uploads', summary: 'Upload the site logo', description: 'Admins — or anyone during first-time setup, before any account exists.', access: 'public', middleware: [brandingAccess, receive(uploads.uploadLogo)], upload: { field: 'image', description: LOGO }, response: uploadResult, handler: uploaded('branding'), }); export const uploadFavicon = defineRoute({ method: 'post', path: '/uploads/favicon', tag: 'Uploads', summary: 'Upload the site icon (favicon)', description: 'Admins — or anyone during first-time setup, before any account exists.', access: 'public', middleware: [brandingAccess, receive(uploads.uploadFavicon)], upload: { field: 'image', description: 'An ICO, PNG or SVG image' }, response: uploadResult, handler: uploaded('branding'), });