- 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
498 lines
26 KiB
TypeScript
498 lines
26 KiB
TypeScript
/**
|
|
* Making and cancelling registrations (1.51.1). Moved here from registrationController.js so
|
|
* POST /api/registrations (v1) and POST /api/v2/registrations run the same code. Errors are
|
|
* ServiceErrors carrying their HTTP status.
|
|
*/
|
|
import { v4 as uuidv4 } from 'uuid';
|
|
import { prisma } from '../v2/legacy';
|
|
import { fail, ServiceError } from './errors';
|
|
|
|
/* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */
|
|
const { generateTicketsForRegistration } = require('../utils/ticketUtils') as { generateTicketsForRegistration(id: string): Promise<unknown> };
|
|
const pricing = require('../utils/pricing') as {
|
|
resolveOptionPrice(option: any, qty: number, buyer: any): Promise<{ price: number; tierId: string | null }>;
|
|
resolveVariantTierPrice(option: any, variantId: string, qty: number, buyer: any): Promise<{ price: number; tierId: string | null }>;
|
|
computeRegistrationTotalDue(registration: any, at: Date): number;
|
|
attachComputedTotals<T>(registration: T): T & { totalDueComputed: number };
|
|
};
|
|
const coupons = require('../utils/coupons') as {
|
|
buildCouponLines(registration: any): any[];
|
|
previewCoupon(args: { code: string; eventId: string; user: any; lines: any[] }): Promise<unknown>;
|
|
applyCouponToRegistration(args: { registrationId: string; code: string }): Promise<unknown>;
|
|
recalculateRegistrationDiscount(registrationId: string): Promise<number>;
|
|
releaseRegistrationCoupons(registrationId: string): Promise<unknown>;
|
|
};
|
|
const attendeesUtil = require('../utils/attendees') as {
|
|
lineKey(eventOptionId: string, variantId?: string | null): string;
|
|
validateAttendees(event: any, places: Record<string, number>, attendees: unknown, existing: Record<string, number>): any[];
|
|
createAttendees(registrationId: string, attendees: any[]): Promise<unknown>;
|
|
namedPlacesByKey(registrationId: string): Promise<Record<string, number>>;
|
|
};
|
|
const { findAccountByContact } = require('../utils/accountMatch') as { findAccountByContact(c: { email?: string; phone?: string }): Promise<{ user: { id: string } | null; conflict?: boolean }> };
|
|
const { ensureConsentRequests } = require('../utils/consent') as { ensureConsentRequests(registrationId: string): Promise<unknown> };
|
|
const { takenCount } = require('../utils/stock') as { takenCount(where: object, opts?: { excludeEntryId?: string | null }): Promise<number> };
|
|
const waitlist = require('../utils/waitlist') as { findOfferByToken(token: string): Promise<any>; queueWaitlist(eventId: string): void };
|
|
const { reservedOptionIds } = require('../utils/volunteers') as { reservedOptionIds(event: any): string[] };
|
|
const { BUNDLE_APPS_INCLUDE } = require('../utils/bundles') as { BUNDLE_APPS_INCLUDE: any };
|
|
const sessions = require('../utils/sessions') as {
|
|
registrationClosesAt(event: any, sessions: any[]): Date;
|
|
wholeCourseClosesAt(event: any, sessions: any[]): Date;
|
|
expandPickLines(event: any, options: any[], opts: { now: Date }): any[];
|
|
assertSessionCapacity(event: any, lines: any[], registrationId?: string, opts?: { excludeEntryId?: string }): Promise<void>;
|
|
mergeSessionIds(a: string[] | null | undefined, b: string[] | null | undefined): string[];
|
|
};
|
|
const { assertEventOpen } = require('../utils/cashupUtils') as { assertEventOpen(eventId: string, res?: unknown): Promise<unknown> };
|
|
const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
|
|
|
|
export type Role = 'admin' | 'supervisor' | 'staff' | 'user';
|
|
export type Actor = { id: string; role: Role; email?: string } | null;
|
|
|
|
export const TICKET_DELIVERY = ['payer', 'each'] as const;
|
|
export const isStaffRole = (role: string | undefined | null): boolean => ['admin', 'supervisor', 'staff'].includes(String(role));
|
|
|
|
// Named attendees for API responses, with whether their ticket has been issued/used.
|
|
export const ATTENDEES_INCLUDE = {
|
|
orderBy: { order: 'asc' as const },
|
|
include: {
|
|
ticket: { select: { id: true, isUsed: true } },
|
|
// Latest consent request (youth events) — it decides check-in.
|
|
consentRequests: { orderBy: { createdAt: 'desc' as const }, take: 1, select: { id: true, status: true, respondedAt: true, lastSentAt: true, textVersion: true } },
|
|
},
|
|
};
|
|
|
|
// Active coupon on a registration, for API responses (the discount itself is
|
|
// Registration.discountTotal).
|
|
export const ACTIVE_COUPONS_INCLUDE = {
|
|
where: { releasedAt: null },
|
|
select: { id: true, discountAmount: true, createdAt: true, coupon: { select: { id: true, code: true, type: true, value: true, description: true } } },
|
|
};
|
|
|
|
// Youth events: send parental consent requests for any new under-18 attendees. Runs in
|
|
// the background so a slow mail/WhatsApp send never holds up the registration.
|
|
export function queueConsentRequests(registrationId: string): void {
|
|
ensureConsentRequests(registrationId).catch((e: any) => console.error('[consent] Failed to send requests:', e?.message || e));
|
|
}
|
|
|
|
type Line = { eventOptionId: string; variantId?: string | null; sessionId?: string | null; quantity: number | string };
|
|
|
|
/**
|
|
* Places each line will have once `requested` is added to `existingLines` — used to
|
|
* check attendee names against what's actually being bought.
|
|
*/
|
|
export function placesAfter(existingLines: Line[] | undefined, requested: Line[] | undefined): Record<string, number> {
|
|
const out: Record<string, number> = {};
|
|
// Picked-session lines take no attendee names.
|
|
for (const l of [...(existingLines || []), ...(requested || [])].filter(x => !x.sessionId)) {
|
|
const k = attendeesUtil.lineKey(l.eventOptionId, l.variantId);
|
|
out[k] = (out[k] || 0) + Number(l.quantity || 0);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Coupon lines for options that haven't been saved yet, so a code can be checked
|
|
* before anything is created. Mirrors buildCouponLines for one tranche per option.
|
|
*/
|
|
export function pendingCouponLines(event: { eventOptions: { id: string }[] }, resolvedOptions: any[]): any[] {
|
|
return coupons.buildCouponLines({
|
|
registrationOptions: resolvedOptions.map(o => ({
|
|
eventOptionId: o.eventOptionId,
|
|
variantId: o.variantId || null,
|
|
quantity: o.quantity,
|
|
eventOption: event.eventOptions.find(eo => eo.id === o.eventOptionId),
|
|
tranches: [{ quantity: o.quantity, priceSnapshot: o.priceSnapshot, appliedTierId: o.appliedTierId }],
|
|
})),
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Price one requested option for this buyer: early-bird tiers, then variant/option price,
|
|
* then the staff price for Staff and above. Returns { priceSnapshot, appliedTierId }.
|
|
*/
|
|
export async function priceRequestedOption(eventOption: any, variantId: string | null, qty: number, buyer: any): Promise<{ priceSnapshot: number; appliedTierId: string | null }> {
|
|
try {
|
|
const resolved = variantId
|
|
? await pricing.resolveVariantTierPrice(eventOption, variantId, qty, buyer)
|
|
: await pricing.resolveOptionPrice(eventOption, qty, buyer);
|
|
return { priceSnapshot: resolved.price, appliedTierId: resolved.tierId };
|
|
} catch {
|
|
const variant = variantId ? (eventOption.variants || []).find((v: any) => v.id === variantId) : null;
|
|
const price = variant && variant.price !== null && variant.price !== undefined ? variant.price : eventOption.price;
|
|
return { priceSnapshot: Number(price || 0), appliedTierId: null };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check overall stock availability for an EventOption. Places held for live waitlist
|
|
* offers count as taken, except the offer being claimed (`excludeEntryId`).
|
|
*/
|
|
export async function checkOptionStock(option: { id: string; stockLimit: number }, requestedQty: number, excludeEntryId: string | null = null, sessionId: string | null = null) {
|
|
if (!option.stockLimit || option.stockLimit === 0) return { available: true, remaining: null as number | null };
|
|
const remaining = option.stockLimit - await takenCount({ eventOptionId: option.id, sessionId }, { excludeEntryId });
|
|
return { available: remaining >= requestedQty, remaining };
|
|
}
|
|
|
|
/** Check stock availability for a specific variant (same rules as checkOptionStock). */
|
|
export async function checkVariantStock(variant: { id: string; eventOptionId: string; stockLimit: number | null }, requestedQty: number, excludeEntryId: string | null = null, sessionId: string | null = null) {
|
|
if (!variant.stockLimit || variant.stockLimit === 0) return { available: true, remaining: null as number | null };
|
|
const remaining = variant.stockLimit - await takenCount({ eventOptionId: variant.eventOptionId, variantId: variant.id, sessionId }, { excludeEntryId });
|
|
return { available: remaining >= requestedQty, remaining };
|
|
}
|
|
|
|
export type RequestedOption = { eventOptionId: string; quantity: number; variantId?: string | null; sessionIds?: string[] };
|
|
export type CreateRegistrationInput = {
|
|
eventId: string;
|
|
options: RequestedOption[];
|
|
guestName?: string;
|
|
guestEmail?: string;
|
|
guestPhone?: string;
|
|
couponCode?: string;
|
|
attendees?: unknown[];
|
|
ticketDelivery?: string;
|
|
waitlistToken?: string;
|
|
analyticsSessionId?: string;
|
|
};
|
|
|
|
const FULL_INCLUDE = {
|
|
registrationOptions: { include: { eventOption: true, tranches: true } },
|
|
event: true,
|
|
user: { select: { id: true, name: true, email: true, phoneNumber: true } },
|
|
} as const;
|
|
|
|
/**
|
|
* Registers someone for an event (online, a guest for a free event, or with a waitlist link):
|
|
* checks the event is open, prices each line (early-bird, variant, staff price), checks stock
|
|
* and session places, adds to an existing registration for the same person and event, applies
|
|
* bundle deals and a coupon, and issues tickets straight away when nothing is owed.
|
|
*/
|
|
export async function createRegistration(input: CreateRegistrationInput, actor: Actor) {
|
|
try {
|
|
return await create(input, actor);
|
|
} catch (e: any) {
|
|
// The helpers (coupons, attendee names, session places…) throw plain Errors written for
|
|
// people; like v1, those are the caller's problem (400) unless they carry a status.
|
|
if (e instanceof ServiceError || /^P\d{4}$/.test(String(e?.code || ''))) throw e;
|
|
throw new ServiceError(e?.statusCode || 400, e?.message || 'Registration failed');
|
|
}
|
|
}
|
|
|
|
async function create(input: CreateRegistrationInput, actor: Actor) {
|
|
const { eventId, options, guestName, guestEmail, guestPhone, couponCode, attendees, ticketDelivery, waitlistToken, analyticsSessionId } = input;
|
|
|
|
const event = await prisma.event.findUnique({
|
|
where: { id: eventId },
|
|
include: { eventOptions: { include: { earlyBirdTiers: true, variants: true } }, sessions: true },
|
|
});
|
|
if (!event) return fail(404, 'Event not found');
|
|
if (!event.isActive) return fail(400, 'Event is not active');
|
|
if (event.cashupStatus === 'closed') return fail(400, 'This event is closed and no longer accepting registrations.');
|
|
|
|
// A waitlist claim link: its token identifies the person and releases the places
|
|
// held for them. It works without logging in, the same way a consent link does.
|
|
let waitlistOffer: any = null;
|
|
if (waitlistToken) {
|
|
waitlistOffer = await waitlist.findOfferByToken(waitlistToken);
|
|
if (!waitlistOffer || waitlistOffer.eventId !== eventId) fail(400, 'This waitlist link is not valid.');
|
|
if (waitlistOffer.status !== 'offered') fail(400, `This waitlist offer has ${waitlistOffer.status === 'claimed' ? 'already been used' : 'expired'}.`);
|
|
if (new Date(waitlistOffer.offerExpiresAt) < new Date()) fail(400, 'This waitlist offer has expired.');
|
|
if (actor && actor.id !== waitlistOffer.userId) fail(403, 'This waitlist offer belongs to someone else.');
|
|
}
|
|
|
|
// Enforce auth unless event explicitly opts out
|
|
if (event.requiresAuth !== false && !actor && !waitlistOffer) fail(401, 'Authentication required for this event');
|
|
|
|
// Unauthenticated guest registration is only permitted for free events
|
|
if (!actor && !waitlistOffer) {
|
|
const requestedTotal = (options || []).reduce((sum, opt) => {
|
|
const eo = event.eventOptions.find(o => o.id === opt.eventOptionId);
|
|
return sum + ((eo?.price || 0) * (opt.quantity || 1));
|
|
}, 0);
|
|
if (requestedTotal > 0) fail(400, 'Guest registration is only available for free events. Please create an account to pay for tickets.');
|
|
}
|
|
|
|
// Resolve userId — authenticated or guest
|
|
let userId: string;
|
|
if (actor) {
|
|
userId = actor.id;
|
|
} else if (waitlistOffer) {
|
|
userId = waitlistOffer.userId;
|
|
} else {
|
|
// Guest registration: find existing user by email or create inactive placeholder
|
|
if (!guestEmail || !guestName) return fail(400, 'Name and email are required for unauthenticated registration');
|
|
const match = await findAccountByContact({ email: guestEmail, phone: guestPhone });
|
|
if (match.conflict) fail(409, 'This email and phone number belong to two different accounts. Please log in, or check your details.');
|
|
if (match.user) {
|
|
userId = match.user.id;
|
|
} else {
|
|
const newGuest = await prisma.user.create({
|
|
data: { id: uuidv4(), name: guestName, email: guestEmail, password: '', phoneNumber: guestPhone || null, isActive: false, updatedAt: new Date() },
|
|
});
|
|
userId = newGuest.id;
|
|
}
|
|
}
|
|
|
|
// Enforce registration cutoff for public registrations (multi-day events close when
|
|
// the first session starts, or later with late joining — see utils/sessions.js).
|
|
const now = new Date();
|
|
if (now >= sessions.registrationClosesAt(event, event.sessions)) fail(400, 'Registration is closed for this event');
|
|
|
|
if (!options || !Array.isArray(options) || options.length === 0) fail(400, 'At least one option must be selected');
|
|
|
|
// "Pick sessions" options become one line per chosen session; whole-course tickets
|
|
// on such an event still close when the whole course does.
|
|
const lines = sessions.expandPickLines(event, options, { now });
|
|
// (An all-sessions ticket with sessions ticked is checked per session instead.)
|
|
if (event.attendanceMode === 'pick' && lines.some(l => !l.sessionId && !l.sessionIds?.length) && now >= sessions.wholeCourseClosesAt(event, event.sessions)) {
|
|
fail(400, 'Whole-course tickets are no longer on sale — choose the sessions you want instead.');
|
|
}
|
|
await sessions.assertSessionCapacity(event, lines, undefined, { excludeEntryId: waitlistOffer?.id });
|
|
|
|
// Validate each option and resolve prices / check stock. Options are independent of each
|
|
// other, so resolve them concurrently. The kids check-in and volunteer tickets are handed
|
|
// out by staff, never sold.
|
|
const reserved = new Set(isStaffRole(actor?.role) ? [] : reservedOptionIds(event));
|
|
const buyerFor = async () => actor || (waitlistOffer ? await prisma.user.findUnique({ where: { id: waitlistOffer.userId }, select: { id: true, role: true } }) : null);
|
|
const resolvedOptions = await Promise.all(lines.map(async (option: any) => {
|
|
const eventOption = event.eventOptions.find(eo => eo.id === option.eventOptionId);
|
|
if (!eventOption || reserved.has(eventOption.id)) fail(400, `Option with ID ${option.eventOptionId} not found for this event`);
|
|
if (!option.quantity || option.quantity < 1) fail(400, 'Quantity must be at least 1');
|
|
const qty = option.quantity;
|
|
|
|
// (A failing count doesn't block the sale — only a real shortage does.)
|
|
const stockCheck = await checkOptionStock(eventOption!, qty, waitlistOffer?.id, option.sessionId).catch(() => ({ available: true, remaining: null }));
|
|
if (!stockCheck.available) fail(400, `"${eventOption!.name}" is sold out or does not have enough stock (${stockCheck.remaining ?? 0} remaining).`);
|
|
|
|
const variantId: string | null = option.variantId || null;
|
|
if (variantId) {
|
|
const variant = (eventOption!.variants || []).find(v => v.id === variantId);
|
|
if (!variant) return fail(400, `Variant not found for option "${eventOption!.name}"`);
|
|
const vStock = await checkVariantStock(variant, qty, waitlistOffer?.id, option.sessionId).catch(() => ({ available: true, remaining: null }));
|
|
if (!vStock.available) fail(400, `Variant "${variant.name}" is sold out (${vStock.remaining ?? 0} remaining).`);
|
|
}
|
|
|
|
// Variant-level tiers take priority, then option-level tiers, then base prices, then
|
|
// the staff price for Staff and above.
|
|
const { priceSnapshot, appliedTierId } = await priceRequestedOption(eventOption, variantId, qty, await buyerFor());
|
|
return { ...option, variantId, appliedTierId, priceSnapshot: priceSnapshot ?? eventOption!.price };
|
|
}));
|
|
|
|
// Check a coupon code before anything is saved, so a bad code doesn't leave a
|
|
// half-made registration behind. It's applied (and re-checked under a lock) below.
|
|
if (couponCode) {
|
|
const buyer = actor ? { id: actor.id, role: actor.role, email: actor.email } : null;
|
|
await coupons.previewCoupon({ code: couponCode, eventId, user: buyer, lines: pendingCouponLines(event, resolvedOptions) });
|
|
}
|
|
|
|
// Check for existing non-cancelled registration for this user+event → merge instead
|
|
const existingReg = await prisma.registration.findFirst({
|
|
where: { userId, eventId, status: { not: 'cancelled' } },
|
|
include: { registrationOptions: true },
|
|
});
|
|
|
|
// Attendee names are checked against the places the registration will have after
|
|
// this purchase, counting names already given on an existing registration.
|
|
const cleanAttendees = attendeesUtil.validateAttendees(
|
|
event,
|
|
placesAfter(existingReg?.registrationOptions, resolvedOptions),
|
|
attendees,
|
|
existingReg ? await attendeesUtil.namedPlacesByKey(existingReg.id) : {},
|
|
);
|
|
if (ticketDelivery !== undefined && !(TICKET_DELIVERY as readonly string[]).includes(ticketDelivery)) fail(400, "ticketDelivery must be 'payer' or 'each'");
|
|
|
|
let registrationId: string;
|
|
let isNewRegistration = false;
|
|
if (existingReg) {
|
|
// Merge: add a new price tranche per requested option into the existing registration.
|
|
// Never overwrite an existing row's priceSnapshot/quantity in place — that would blend
|
|
// tickets bought at different early-bird prices into a single (wrong) price. Each
|
|
// purchase gets its own tranche; the RegistrationOption row stays a maintained aggregate.
|
|
for (const opt of resolvedOptions) {
|
|
// Match on eventOptionId + variantId (+ session, for picked sessions) for correct row
|
|
const existing = existingReg.registrationOptions.find(
|
|
ro => ro.eventOptionId === opt.eventOptionId && (ro.variantId || null) === (opt.variantId || null) && (ro.sessionId || null) === (opt.sessionId || null),
|
|
);
|
|
if (existing) {
|
|
await prisma.$transaction([
|
|
prisma.registrationOptionTranche.create({
|
|
data: { id: uuidv4(), registrationOptionId: existing.id, quantity: opt.quantity, priceSnapshot: opt.priceSnapshot, appliedTierId: opt.appliedTierId || null },
|
|
}),
|
|
prisma.registrationOption.update({
|
|
where: { id: existing.id },
|
|
data: { quantity: existing.quantity + opt.quantity, priceSnapshot: opt.priceSnapshot, appliedTierId: opt.appliedTierId || null, ...(existing.sessionId ? {} : { sessionIds: sessions.mergeSessionIds(existing.sessionIds, opt.sessionIds) }) },
|
|
}),
|
|
]);
|
|
} else {
|
|
await prisma.registrationOption.create({
|
|
data: {
|
|
id: uuidv4(),
|
|
registrationId: existingReg.id,
|
|
eventOptionId: opt.eventOptionId,
|
|
quantity: opt.quantity,
|
|
variantId: opt.variantId || null,
|
|
sessionId: opt.sessionId || null,
|
|
sessionIds: opt.sessionIds || [],
|
|
appliedTierId: opt.appliedTierId || null,
|
|
priceSnapshot: opt.priceSnapshot,
|
|
tranches: { create: [{ id: uuidv4(), quantity: opt.quantity, priceSnapshot: opt.priceSnapshot, appliedTierId: opt.appliedTierId || null }] },
|
|
},
|
|
});
|
|
}
|
|
}
|
|
// Only downgrade from paid if the newly added items actually cost something
|
|
const newItemsCost = resolvedOptions.reduce((sum, opt) => sum + ((opt.priceSnapshot || 0) * (opt.quantity || 0)), 0);
|
|
await prisma.registration.update({
|
|
where: { id: existingReg.id },
|
|
data: existingReg.status === 'paid' && newItemsCost > 0 ? { status: 'partial_paid', updatedAt: new Date() } : { updatedAt: new Date() },
|
|
});
|
|
registrationId = existingReg.id;
|
|
} else {
|
|
isNewRegistration = true;
|
|
registrationId = uuidv4();
|
|
await prisma.registration.create({
|
|
data: {
|
|
id: registrationId,
|
|
userId,
|
|
eventId,
|
|
updatedAt: new Date(),
|
|
registrationOptions: {
|
|
create: resolvedOptions.map(option => ({
|
|
id: uuidv4(),
|
|
eventOptionId: option.eventOptionId,
|
|
quantity: option.quantity,
|
|
variantId: option.variantId || null,
|
|
sessionId: option.sessionId || null,
|
|
sessionIds: option.sessionIds || [],
|
|
appliedTierId: option.appliedTierId || null,
|
|
priceSnapshot: option.priceSnapshot,
|
|
tranches: { create: [{ id: uuidv4(), quantity: option.quantity, priceSnapshot: option.priceSnapshot, appliedTierId: option.appliedTierId || null }] },
|
|
})),
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
if (cleanAttendees.length > 0) {
|
|
await attendeesUtil.createAttendees(registrationId, cleanAttendees);
|
|
queueConsentRequests(registrationId);
|
|
}
|
|
if (waitlistOffer) {
|
|
await prisma.waitlistEntry.update({
|
|
where: { id: waitlistOffer.id },
|
|
data: { status: 'claimed', claimedAt: new Date(), registrationId, offerTokenHash: null },
|
|
});
|
|
}
|
|
if (ticketDelivery) {
|
|
await prisma.registration.update({ where: { id: registrationId }, data: { ticketDelivery: ticketDelivery as 'payer' | 'each' } });
|
|
}
|
|
|
|
// Bundle deals, then the coupon (or re-work an existing one over the merged items).
|
|
let couponError: string | null = null;
|
|
await coupons.recalculateRegistrationDiscount(registrationId);
|
|
if (couponCode) {
|
|
try {
|
|
await coupons.applyCouponToRegistration({ registrationId, code: couponCode });
|
|
} catch (e: any) {
|
|
// Lost a race for the last use since the check above — keep the registration.
|
|
if (!e.isCouponError) throw e;
|
|
couponError = e.message;
|
|
}
|
|
}
|
|
const load = () => prisma.registration.findUniqueOrThrow({
|
|
where: { id: registrationId },
|
|
include: { ...FULL_INCLUDE, couponRedemptions: ACTIVE_COUPONS_INCLUDE, bundleApplications: BUNDLE_APPS_INCLUDE, attendees: ATTENDEES_INCLUDE },
|
|
});
|
|
let registration = await load();
|
|
|
|
// Nothing owed: mark paid and issue tickets (unless a required form comes first).
|
|
let emailTicketsAfter = false;
|
|
try {
|
|
if (pricing.computeRegistrationTotalDue(registration, new Date()) === 0) {
|
|
if (registration.status !== 'paid') {
|
|
await prisma.registration.update({ where: { id: registrationId }, data: { status: 'paid', updatedAt: new Date() } });
|
|
}
|
|
const form = await prisma.eventForm.findUnique({ where: { eventId: registration.eventId } }).catch(() => null);
|
|
if (!(form && form.isRequired)) {
|
|
// Same generator as paid registrations: a ticket per named attendee, and one
|
|
// shared quantity ticket for the rest of each line.
|
|
await generateTicketsForRegistration(registrationId);
|
|
emailTicketsAfter = true;
|
|
}
|
|
registration = { ...registration, status: 'paid' };
|
|
}
|
|
} catch {
|
|
// ignore errors in auto-generation path; manual generation remains available
|
|
}
|
|
|
|
// Fire-and-forget: registration email first, then tickets (guarantees order)
|
|
const notifications = require('../utils/notifications') as { sendRegistrationEmails(id: string): Promise<unknown>; sendRegistrationUpdatedEmails(id: string): Promise<unknown> };
|
|
const ownerId = registration.userId;
|
|
void (async () => {
|
|
try {
|
|
if (isNewRegistration) await notifications.sendRegistrationEmails(registrationId);
|
|
else await notifications.sendRegistrationUpdatedEmails(registrationId);
|
|
} catch (e) { console.error('Failed to send registration emails:', e); }
|
|
if (emailTicketsAfter) {
|
|
try {
|
|
const { emailTickets } = require('../controllers/ticketController') as { emailTickets(req: unknown, res: unknown): Promise<unknown> };
|
|
const res: { status(): unknown; json(): void } = { status: () => res, json: () => {} };
|
|
await emailTickets({ user: { id: ownerId }, body: { registrationId } }, res);
|
|
} catch (e) { console.error('Error emailing tickets for free registration:', e); }
|
|
}
|
|
})();
|
|
|
|
// Funnel: this registration came from a tracked (cookie-consented) visit.
|
|
if (analyticsSessionId) {
|
|
const { recordSubmit } = require('../utils/analytics') as { recordSubmit(reg: unknown, sessionId: string): Promise<unknown> };
|
|
recordSubmit(registration, analyticsSessionId).catch((e: any) => console.warn('[analytics] submit not recorded:', e?.message || e));
|
|
}
|
|
|
|
return { registration: pricing.attachComputedTotals(registration), isNew: isNewRegistration, couponError };
|
|
}
|
|
|
|
/**
|
|
* Cancels a registration: the owner (not after the event, not once anything is paid) or an
|
|
* admin. Releases its coupon and offers its places to the waitlist.
|
|
*/
|
|
export async function cancelRegistration(registrationId: string, actor: { id: string; role: Role }, ip?: string) {
|
|
const registration = await prisma.registration.findUnique({
|
|
where: { id: registrationId },
|
|
include: { event: { select: { endDate: true } } },
|
|
});
|
|
if (!registration) return fail(404, 'Registration not found');
|
|
|
|
if (registration.userId !== actor.id && actor.role !== 'admin') fail(403, 'Not authorized to cancel this registration');
|
|
|
|
// If event is in the past, block self-cancellation (mirrors the edit block)
|
|
if (actor.role !== 'admin' && registration.event?.endDate && new Date(registration.event.endDate).getTime() < Date.now()) {
|
|
fail(400, 'This event has already ended; registration can no longer be cancelled');
|
|
}
|
|
|
|
try {
|
|
await assertEventOpen(registration.eventId);
|
|
} catch (e: any) {
|
|
throw new ServiceError(e.message === 'Event not found' ? 404 : 400, e.message);
|
|
}
|
|
|
|
if (registration.status === 'cancelled') fail(400, 'Registration is already cancelled');
|
|
|
|
// Non-admins cannot cancel a registration that has payments against it
|
|
if (actor.role !== 'admin') {
|
|
const paymentCount = await prisma.payment.count({ where: { registrationId: registration.id, amount: { gt: 0 } } });
|
|
if (paymentCount > 0) fail(403, 'This registration has payments recorded against it and cannot be self-cancelled. Please contact the organisation for assistance.');
|
|
}
|
|
|
|
const updated = await prisma.registration.update({ where: { id: registrationId }, data: { status: 'cancelled', updatedAt: new Date() } });
|
|
await coupons.releaseRegistrationCoupons(registrationId);
|
|
waitlist.queueWaitlist(registration.eventId);
|
|
|
|
// Only log when staff cancels on someone else's behalf — a routine self-service
|
|
// cancellation isn't an admin action worth cluttering the audit trail with.
|
|
if (registration.userId !== actor.id) {
|
|
logAdminAction({
|
|
actorId: actor.id, actorRole: actor.role, action: 'registration_cancelled', targetType: 'Registration', targetId: registrationId,
|
|
metadata: { registrationOwnerId: registration.userId }, ip,
|
|
});
|
|
}
|
|
return updated;
|
|
}
|