Files
crosscode-platform/apps/events/backend/src/v2/docs.ts
T
joshuaandClaude Opus 5.5 ee65ff358c Events 2.3.0 (phase 1c): two-factor with an authenticator app, recovery codes
- TOTP (RFC 6238) next to email and WhatsApp: QR code and key to set up,
  the app's first code confirms it, a code can't be used twice, nothing
  is sent. The secret is stored encrypted.
- 10 single-use recovery codes whenever two-factor is turned on, shown
  once; accepted at sign-in in place of any code; a new set on request.
- Admins see each account's method; Reset 2FA clears the app and codes.
- Profile & Security, sign-in and Users pages; API types; 10 new tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:55:22 +02:00

213 lines
7.7 KiB
TypeScript

/**
* Shapes for the API documentation (1.52.1): the records v1 handlers answer with, and the bodies
* they take, described once so every route shows the same thing the same way. Used as
* `documented: { body, response }` on v1Route (see RouteDef.documented) — shown in the OpenAPI
* document, not enforced; outside production anything that doesn't fit is logged.
*
* Everything is a loose object (extra fields pass, as v1 answers carry their Prisma includes),
* dates are ISO strings (as they arrive in JSON), and fields a handler may leave out are optional.
*/
import { z } from 'zod';
export const obj = <T extends z.ZodRawShape>(shape: T) => z.looseObject(shape);
export const str = z.string();
export const optStr = z.string().nullish();
export const num = z.number();
export const optNum = z.number().nullish();
export const bool = z.boolean();
export const optBool = z.boolean().nullish();
export const date = z.string().describe('Date and time (ISO 8601)');
export const optDate = date.nullish();
export const rand = z.number().describe('Rand');
export const optRand = rand.nullish();
export const anyObj = z.looseObject({});
/** A number sent as a number or as text (forms send text). */
export const numeric = z.union([z.number(), z.string()]);
export const ids = z.array(z.string()).describe('Ids');
export const channel = z.enum(['email', 'whatsapp', 'both']).describe('How to send it');
/** `{ message }`: what was done, in words for the person. */
export const message = obj({ message: str });
/** `{ ok: true }` */
export const ok = obj({ ok: z.literal(true) });
/** v1's paged lists: `{ data, total, page, limit, pages }`. */
export const v1Page = <T extends z.ZodType>(item: T) => obj({ data: z.array(item), total: num, page: num, limit: num, pages: num });
/** A `{ redirectUrl }` answer from a checkout: where to send the person to pay. */
export const checkout = obj({
checkoutId: optStr,
redirectUrl: optStr.describe('Where to send the person to pay (null when the provider takes a form)'),
provider: optStr,
form: obj({ action: str, fields: z.record(z.string(), z.string()) }).nullish().describe('A form to post (PayFast)'),
});
export const userSummary = obj({ id: str.optional(), name: str, email: optStr, phoneNumber: optStr });
export const userRef = obj({ id: str.optional(), name: str, email: optStr });
export const user = obj({
id: str,
name: str,
email: str,
phoneNumber: optStr,
role: z.enum(['admin', 'supervisor', 'staff', 'user']),
isActive: optBool,
notificationPreference: z.enum(['email', 'whatsapp', 'both']).nullish(),
twoFactorEnabled: optBool,
twoFactorMethod: z.enum(['email', 'whatsapp', 'authenticator']).nullish().describe('How their sign-in codes come (2.3.0: authenticator = an app)'),
homeCampusId: optStr,
createdAt: optDate,
});
export const eventRef = obj({ id: str, title: str, startDate: optDate, endDate: optDate });
export const event = obj({
id: str,
title: str,
description: optStr,
startDate: date,
endDate: date,
location: optStr,
price: optRand,
isActive: optBool,
isHidden: optBool,
imageUrl: optStr,
campusId: optStr,
scheduleType: z.enum(['single', 'sessions']).nullish(),
cashupStatus: z.enum(['open', 'closed']).nullish(),
});
export const session = obj({ id: str, label: optStr, startsAt: date, endsAt: date, cancelledAt: optDate, capacity: optNum });
export const eventOption = obj({
id: str,
eventId: str.optional(),
name: str,
description: optStr,
price: rand,
isMainTicket: bool,
stockLimit: optNum,
});
export const payment = obj({
id: str,
amount: rand.describe('Rand; a refund is negative'),
method: str.describe('cash, card, eft, other — or the wallet type for an online payment'),
provider: optStr.describe('yoco or payfast for an online payment'),
userId: str,
recordedById: optStr,
registrationId: optStr,
eventId: optStr,
isDonation: bool,
isSponsorship: optBool,
originalPaymentId: optStr.describe('A refund: the payment it refunds; a donation leg: the donation'),
externalId: optStr,
createdAt: date,
user: userSummary.nullish(),
recordedBy: userRef.nullish(),
event: eventRef.nullish(),
});
export const registrationStatus = z.enum(['pending', 'confirmed', 'partial_paid', 'paid', 'cancelled']);
export const registration = obj({
id: str,
userId: str,
eventId: str,
status: registrationStatus,
discountTotal: optRand,
totalDueComputed: optRand.describe('What it costs now, after discounts'),
createdAt: date,
user: userSummary.nullish(),
event: eventRef.nullish(),
});
export const ticket = obj({
id: str,
qrCode: str.describe('What the QR code holds'),
quantity: num.describe('People on the ticket'),
isUsed: bool,
eventId: str,
userId: str.describe('The payer'),
registrationOptionId: str,
attendeeId: optStr.describe('A named ticket: the person it\'s for'),
holderUserId: optStr,
createdAt: date,
});
export const auditEntry = obj({
id: str,
action: str,
actorRole: optStr,
targetType: optStr,
targetId: optStr,
metadata: anyObj.nullish(),
ip: optStr,
createdAt: date,
actor: userRef.nullish(),
});
/**
* What the common query parameters mean, for routes that declare them by name only (`filters(…)`
* in the resource files). The OpenAPI document uses these when a parameter has no description.
*/
export const QUERY_HELP: Record<string, string> = {
page: 'Page number, from 1',
limit: 'How many per page',
eventId: 'Only this event',
eventIds: 'These events (comma-separated ids)',
registrationId: 'Only this registration',
userId: 'Only this person',
actorId: 'Only things this person did',
sessionId: 'Multi-day events: the session (default: today\'s)',
deviceId: 'This device\'s id (offline scanning)',
from: 'On or after (ISO date or date-time)',
to: 'On or before (ISO date or date-time)',
startDate: 'On or after (ISO date)',
endDate: 'On or before (ISO date)',
before: 'Older than (ISO date-time), for the next page',
cursor: 'Where the last page ended (its `nextCursor`)',
search: 'Text to search for',
q: 'Text to search for',
status: 'Only this status',
role: 'admin, supervisor, staff or user',
isActive: '`true` or `false`',
campus: 'Campus id or slug (`all` for every campus)',
series: 'Event series slug',
format: 'File type, e.g. `pdf` or `xlsx`',
log: '`1` also writes it to the access log (a list with personal details)',
all: '`true`/`1`: include everything, not just the current ones',
medical: '`true`: include medical notes (supervisors; logged)',
type: 'Which kind',
action: 'Only this action',
sensitive: '`true`: only access to sensitive information',
version: 'A version number (default: the current one)',
provider: 'yoco or payfast',
method: 'Payment method: cash, card, eft, other',
kind: 'payment or refund',
donations: '`1`: only donations and the parts put towards registrations',
channel: 'email or whatsapp',
email: 'An email address',
phone: 'A phone number',
phoneNumber: 'A phone number',
past: '`true`: include ones that are over too',
unpaid: '`true`: only ones with money still owed',
unreviewed: '`true`: only the ones not reviewed yet',
seriesId: 'Only this event series',
registrants: '`true`: also people registered for its events in the last 12 months',
};
/** What path parameters are, when the route doesn't say. */
export const PATH_HELP: Record<string, string> = {
id: 'The id',
userId: 'The person\'s id',
attendeeId: 'The named attendee\'s id',
attachmentId: 'The attachment\'s id',
familyId: 'The family\'s id',
childId: 'The child\'s id',
slug: 'The short name in the address',
token: 'The token from the link (it is the credential)',
qrCode: 'What the ticket\'s QR code holds',
code: 'The code',
name: 'The name',
filename: 'The file name',
};