- v2: register, get, cancel and checkout a registration (owner/admin only). - Registration create/cancel moved to src/services/registrations.ts and online checkout to src/services/payments.ts; v1 controllers call the same services (ServiceError carries status). - Typed frontend calls: npm run api:types writes openapi.json and schema.d.ts; apiV2() helper. Register page, Pay now and My Events cancel use v2; apiFetch reads v2 errors. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
188 lines
8.7 KiB
TypeScript
188 lines
8.7 KiB
TypeScript
import { z } from 'zod';
|
||
import { defineRoute, type ApiUser } from '../route';
|
||
import { ApiError, notFound } from '../errors';
|
||
import { single } from '../paging';
|
||
import { eventRef, id, idParams, iso, isoDate } from '../schemas';
|
||
import { prisma, computeRegistrationTotalDue } from '../legacy';
|
||
import { createRegistration, cancelRegistration } from '../../services/registrations';
|
||
import { startRegistrationCheckout } from '../../services/payments';
|
||
|
||
const STATUSES = ['pending', 'confirmed', 'partial_paid', 'paid', 'cancelled'] as const;
|
||
|
||
/** A registration as v2 shows it to its owner. Also used by GET /me/registrations. */
|
||
export const registrationSummary = z.object({
|
||
id,
|
||
status: z.enum(STATUSES),
|
||
createdAt: isoDate,
|
||
event: eventRef,
|
||
items: z.array(z.object({
|
||
ticket: z.string(),
|
||
variant: z.string().nullable(),
|
||
quantity: z.number().int(),
|
||
unitPrice: z.number(),
|
||
})),
|
||
totalDue: z.number().describe('In rand, after discounts'),
|
||
amountPaid: z.number().describe('In rand (refunds subtracted)'),
|
||
balance: z.number().describe('totalDue − amountPaid; 0 or less = nothing owing'),
|
||
});
|
||
|
||
const r2 = (n: number) => Math.round(n * 100) / 100;
|
||
|
||
export const SUMMARY_INCLUDE = {
|
||
event: { select: { id: true, title: true, startDate: true, endDate: true } },
|
||
registrationOptions: { include: { eventOption: { include: { earlyBirdTiers: true } }, variant: { select: { name: true, price: true } }, tranches: true } },
|
||
payments: { select: { amount: true, createdAt: true } },
|
||
} as const;
|
||
|
||
type SummaryRow = {
|
||
id: string; status: (typeof STATUSES)[number]; createdAt: Date;
|
||
event: { id: string; title: string; startDate: Date; endDate: Date };
|
||
registrationOptions: { quantity: number; priceSnapshot: number | null; eventOption: { name: string; price: number } | null; variant: { name: string } | null }[];
|
||
payments: { amount: number }[];
|
||
};
|
||
|
||
export function toSummary(r: SummaryRow, now = new Date()): z.input<typeof registrationSummary> {
|
||
const totalDue = r2(computeRegistrationTotalDue(r, now));
|
||
const amountPaid = r2(r.payments.reduce((s, p) => s + p.amount, 0));
|
||
return {
|
||
id: r.id,
|
||
status: r.status,
|
||
createdAt: iso(r.createdAt),
|
||
event: { id: r.event.id, title: r.event.title, startDate: iso(r.event.startDate), endDate: iso(r.event.endDate) },
|
||
items: r.registrationOptions.map(o => ({ ticket: o.eventOption?.name ?? '', variant: o.variant?.name ?? null, quantity: o.quantity, unitPrice: o.priceSnapshot ?? o.eventOption?.price ?? 0 })),
|
||
totalDue,
|
||
amountPaid,
|
||
balance: r2(totalDue - amountPaid),
|
||
};
|
||
}
|
||
|
||
/** The owner's registration (admins may see anyone's); others get NOT_FOUND, not a hint it exists. */
|
||
async function ownRegistration(registrationId: string, user: ApiUser) {
|
||
const r = await prisma.registration.findUnique({ where: { id: registrationId }, include: SUMMARY_INCLUDE });
|
||
if (!r || (r.userId !== user.id && user.role !== 'admin')) throw notFound('That registration');
|
||
return r;
|
||
}
|
||
|
||
const attendee = z.object({
|
||
eventOptionId: id,
|
||
variantId: id.nullish(),
|
||
name: z.string().trim().min(1).max(200),
|
||
email: z.string().trim().max(200).nullish(),
|
||
phone: z.string().trim().max(40).nullish(),
|
||
dateOfBirth: z.string().max(40).nullish().describe('YYYY-MM-DD (youth events)'),
|
||
gender: z.string().max(20).nullish(),
|
||
parentName: z.string().max(200).nullish(),
|
||
parentEmail: z.string().max(200).nullish(),
|
||
parentPhone: z.string().max(40).nullish(),
|
||
});
|
||
|
||
export const register = defineRoute({
|
||
method: 'post',
|
||
path: '/registrations',
|
||
tag: 'Registrations',
|
||
summary: 'Register for an event',
|
||
description: [
|
||
'Signed in, or as a guest for a free event that allows it (`guest` then required), or with a waitlist link (`waitlistToken`).',
|
||
'Registering again for the same event adds to the existing registration. When nothing is owed it is marked paid and tickets are issued; otherwise pay with `POST /registrations/{id}/checkout`.',
|
||
'A coupon that was valid when checked but used up a moment later is reported in `couponError`; the registration is still made.',
|
||
].join('\n\n'),
|
||
access: 'optional',
|
||
status: 201,
|
||
body: z.object({
|
||
eventId: id,
|
||
options: z.array(z.object({
|
||
eventOptionId: id,
|
||
quantity: z.number().int().min(1).max(1000),
|
||
variantId: id.nullish(),
|
||
sessionIds: z.array(id).max(200).optional().describe('"Pick sessions" tickets: the sessions chosen'),
|
||
})).min(1).max(50),
|
||
guest: z.object({ name: z.string().trim().min(1).max(200), email: z.email().max(200), phone: z.string().trim().max(40).optional() }).optional(),
|
||
couponCode: z.string().trim().max(60).optional(),
|
||
attendees: z.array(attendee).max(500).optional().describe('Names for the places (events that collect them)'),
|
||
ticketDelivery: z.enum(['payer', 'each']).optional().describe('With attendees: tickets to the payer, or to each attendee'),
|
||
waitlistToken: z.string().max(200).optional(),
|
||
analyticsSessionId: z.string().max(100).optional(),
|
||
}),
|
||
response: single(registrationSummary.extend({
|
||
isNew: z.boolean().describe('false = added to an existing registration'),
|
||
couponError: z.string().nullable(),
|
||
})),
|
||
async handler({ body, user }) {
|
||
const { registration, isNew, couponError } = await createRegistration({
|
||
eventId: body.eventId,
|
||
options: body.options.map(o => ({ ...o, variantId: o.variantId ?? null })),
|
||
guestName: body.guest?.name,
|
||
guestEmail: body.guest?.email,
|
||
guestPhone: body.guest?.phone,
|
||
couponCode: body.couponCode,
|
||
attendees: body.attendees,
|
||
ticketDelivery: body.ticketDelivery,
|
||
waitlistToken: body.waitlistToken,
|
||
analyticsSessionId: body.analyticsSessionId,
|
||
}, user ? { id: user.id, role: user.role, email: user.email } : null);
|
||
const fresh = await prisma.registration.findUniqueOrThrow({ where: { id: registration.id }, include: SUMMARY_INCLUDE });
|
||
return { data: { ...toSummary(fresh), isNew, couponError } };
|
||
},
|
||
});
|
||
|
||
export const getRegistration = defineRoute({
|
||
method: 'get',
|
||
path: '/registrations/:id',
|
||
tag: 'Registrations',
|
||
summary: 'One of my registrations',
|
||
access: 'user',
|
||
params: idParams,
|
||
response: single(registrationSummary),
|
||
async handler({ params, user }) {
|
||
return { data: toSummary(await ownRegistration(params.id, user!)) };
|
||
},
|
||
});
|
||
|
||
export const cancel = defineRoute({
|
||
method: 'post',
|
||
path: '/registrations/:id/cancel',
|
||
tag: 'Registrations',
|
||
summary: 'Cancel my registration',
|
||
description: 'Not after the event has ended, and not once anything has been paid (the church can do that). Its places go to the waitlist.',
|
||
access: 'user',
|
||
params: idParams,
|
||
response: single(registrationSummary),
|
||
async handler({ params, user, req }) {
|
||
await ownRegistration(params.id, user!);
|
||
const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string };
|
||
await cancelRegistration(params.id, user!, getClientIp(req));
|
||
return { data: toSummary(await ownRegistration(params.id, user!)) };
|
||
},
|
||
});
|
||
|
||
export const checkout = defineRoute({
|
||
method: 'post',
|
||
path: '/registrations/:id/checkout',
|
||
tag: 'Registrations',
|
||
summary: 'Pay what I owe online',
|
||
description: [
|
||
'Starts a payment with the church\'s provider (Yoco or PayFast) and returns where to send the person (`redirectUrl`).',
|
||
'If an early-bird price ran out since the registration was made, nothing is started: `priceUpdated` is true with the new amount owing — show it, then call again.',
|
||
].join('\n\n'),
|
||
access: 'user',
|
||
params: idParams,
|
||
body: z.object({
|
||
donationAmount: z.number().min(0).max(100000).optional().describe('An optional donation added on top, in rand'),
|
||
provider: z.string().max(40).optional().describe('yoco or payfast (default: the first one switched on)'),
|
||
successUrl: z.url().max(2000).optional(),
|
||
cancelUrl: z.url().max(2000).optional(),
|
||
failureUrl: z.url().max(2000).optional(),
|
||
}),
|
||
response: single(z.discriminatedUnion('priceUpdated', [
|
||
z.object({ priceUpdated: z.literal(true), newBalance: z.number(), message: z.string() }),
|
||
z.object({ priceUpdated: z.literal(false), checkoutId: z.string(), redirectUrl: z.string(), provider: z.string(), amount: z.number().describe('Charged now, in rand (with any donation)') }),
|
||
])),
|
||
async handler({ params, body, user }) {
|
||
await ownRegistration(params.id, user!);
|
||
const result = await startRegistrationCheckout(params.id, user!, body);
|
||
if (result.priceUpdated) return { data: { priceUpdated: true as const, newBalance: result.newTotal, message: result.message } };
|
||
if (!result.redirectUrl) throw new ApiError('INTERNAL', 'The payment provider did not return a payment page.');
|
||
return { data: { priceUpdated: false as const, checkoutId: result.checkoutId, redirectUrl: result.redirectUrl, provider: result.provider, amount: result.amount } };
|
||
},
|
||
});
|