Archived
WIP 1.51.8: event detail, options, variants, attachments, calendar and alias on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
This commit is contained in:
@@ -7,6 +7,7 @@ import auth from '../middleware/authMiddleware';
|
||||
// Resources: importing one registers its routes.
|
||||
// eventsManage first: /events/manage must match before /events/:id.
|
||||
import './resources/eventsManage';
|
||||
import './resources/eventDetails';
|
||||
import './resources/events';
|
||||
import './resources/me';
|
||||
import './resources/registrations';
|
||||
|
||||
@@ -71,9 +71,13 @@ export function buildOpenApi(opts: { version: string; serverUrl?: string; list?:
|
||||
operationId: `${def.method}${path.replace(/[{}]/g, '').split('/').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('')}`,
|
||||
...(secured ? { security: [{ bearerAuth: [] }] } : def.access === 'optional' ? { security: [{}, { bearerAuth: [] }] } : {}),
|
||||
parameters: parameters(def),
|
||||
...(def.body ? { requestBody: { required: true, content: { 'application/json': { schema: toSchema(def.body, 'input') } } } } : {}),
|
||||
...(def.upload
|
||||
? { requestBody: { required: true, content: { 'multipart/form-data': { schema: { type: 'object', required: [def.upload.field], properties: { [def.upload.field]: { type: 'string', format: 'binary', description: def.upload.description } } } } } } }
|
||||
: def.body ? { requestBody: { required: true, content: { 'application/json': { schema: toSchema(def.body, 'input') } } } } : {}),
|
||||
responses: {
|
||||
[String(def.status ?? 200)]: { description: 'OK', content: { 'application/json': { schema: toSchema(def.response, 'output') } } },
|
||||
[String(def.status ?? 200)]: def.file
|
||||
? { description: 'The file', content: { [def.file.contentType]: { schema: { type: 'string' } } } }
|
||||
: { description: 'OK', content: { 'application/json': { schema: toSchema(def.response, 'output') } } },
|
||||
...(def.params || def.query || def.body ? { 400: errorResponse('Validation failed (VALIDATION_FAILED)') } : {}),
|
||||
...(secured ? { 401: errorResponse('Not signed in (UNAUTHENTICATED)') } : {}),
|
||||
...(secured && def.access !== 'user' ? { 403: errorResponse('Not allowed for this role (FORBIDDEN)') } : {}),
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
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<object | null>;
|
||||
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 = <T>(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)) };
|
||||
},
|
||||
});
|
||||
@@ -50,6 +50,13 @@ export type RouteDef<P extends Schema | undefined, Q extends Schema | undefined,
|
||||
status?: number;
|
||||
/** Runs after the access check, e.g. a rate limiter. */
|
||||
middleware?: RequestHandler[];
|
||||
/** A multipart upload (the file in `field`, saved by a multer step in `middleware`). */
|
||||
upload?: { field: string; description: string };
|
||||
/**
|
||||
* The answer is a file, not JSON: the handler returns `{ data: { contentType, filename, body } }`
|
||||
* and `response` is `fileResponse`. `contentType` here is what the docs show.
|
||||
*/
|
||||
file?: { contentType: string };
|
||||
handler: (ctx: Ctx<Infer<P>, Infer<Q>, Infer<B>>) => Promise<z.input<R>> | z.input<R>;
|
||||
};
|
||||
|
||||
@@ -97,6 +104,13 @@ export function mount(router: Router, list: AnyRoute[] = routes): void {
|
||||
console.error(`[api/v2] ${def.method.toUpperCase()} ${def.path}: response doesn't match its schema`, checked.error.issues);
|
||||
throw new ApiError('INTERNAL', 'Something went wrong on the server.');
|
||||
}
|
||||
if (def.file) {
|
||||
const f = (checked.data as { data: { contentType: string; filename: string; body: string } }).data;
|
||||
res.setHeader('Content-Type', f.contentType);
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${f.filename.replace(/"/g, '')}"`);
|
||||
res.status(def.status ?? 200).send(f.body);
|
||||
return;
|
||||
}
|
||||
res.status(def.status ?? 200).json(checked.data);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -105,3 +119,6 @@ export function mount(router: Router, list: AnyRoute[] = routes): void {
|
||||
router[def.method](def.path, ...ACCESS[def.access], ...(def.middleware ?? []), run);
|
||||
}
|
||||
}
|
||||
|
||||
/** The `response` of a `file` route: what the handler hands back to be sent as a download. */
|
||||
export const fileResponse = z.object({ data: z.object({ contentType: z.string(), filename: z.string(), body: z.string() }) });
|
||||
|
||||
Reference in New Issue
Block a user