diff --git a/apps/events/backend/src/controllers/registrationController.js b/apps/events/backend/src/controllers/registrationController.js index 86b1999..e981adc 100644 --- a/apps/events/backend/src/controllers/registrationController.js +++ b/apps/events/backend/src/controllers/registrationController.js @@ -1,26 +1,8 @@ -const prisma = require('../config/db'); -const { v4: uuidv4 } = require('uuid'); -const { generateTicketsForRegistration } = require('../utils/ticketUtils'); -const { emailTickets } = require('./ticketController'); -const { hashPassword } = require('../config/auth'); -const { computeRegistrationTotalDue, refreshPricingForRegistration, attachComputedTotals, attachComputedTotalsToList } = require('../utils/pricing'); -const { assertEventOpen } = require('../utils/cashupUtils'); -const { logAdminAction } = require('../utils/adminAudit'); -const { getClientIp } = require('../utils/requestUtils'); -const { previewCoupon, applyCouponToRegistration, recalculateRegistrationDiscount, releaseRegistrationCoupons, describeCoupon } = require('../utils/coupons'); -const { validateAttendees, createAttendees, namedPlacesByKey } = require('../utils/attendees'); -const { findAccountByContact } = require('../utils/accountMatch'); -const { queueWaitlist } = require('../utils/waitlist'); -const { reservedOptionIds } = require('../utils/volunteers'); - -// Shared with POST /api/v2/registrations: the registration service (TypeScript, 1.51.1). +// Registrations (v1). The work is in src/services: registrations.ts (making and cancelling +// one) and registrationAdmin.ts (everything after) — shared with /api/v2. +const { v1StatusOf } = require('../services/errors'); const registrationService = require('../services/registrations'); -const { - queueConsentRequests, ATTENDEES_INCLUDE, TICKET_DELIVERY, placesAfter, ACTIVE_COUPONS_INCLUDE, - pendingCouponLines, priceRequestedOption, checkOptionStock, checkVariantStock, isStaffRole, -} = registrationService; -const { BUNDLE_APPS_INCLUDE } = require('../utils/bundles'); -const { expandPickLines, assertSessionCapacity, isPickOption, mergeSessionIds } = require('../utils/sessions'); +const admin = require('../services/registrationAdmin'); // @desc Create a new registration // @route POST /api/registrations @@ -35,295 +17,9 @@ const createRegistration = async (req, res) => { } }; -// @desc Get all registrations -// @route GET /api/registrations -// @access Private/Admin -const getRegistrations = async (req, res) => { - try { - const include = { - couponRedemptions: ACTIVE_COUPONS_INCLUDE, - - bundleApplications: BUNDLE_APPS_INCLUDE, - attendees: ATTENDEES_INCLUDE, - payments: { include: { recordedBy: { select: { id: true, name: true, email: true } } } }, - registrationOptions: { - include: { - eventOption: { include: { earlyBirdTiers: true } }, - variant: { select: { id: true, name: true, price: true } }, - tranches: true, - } - }, - event: true, - user: { - select: { - id: true, - name: true, - email: true, - phoneNumber: true - } - } - }; - - // Pagination is opt-in via ?page/?limit to keep existing callers (which expect a plain - // array of every registration) working unchanged; callers that pass either param get back - // the { data, total, page, limit, pages } shape used by /api/payments and /api/users. - // Campus-scoped staff: registrations for events they can see. - const scopeWhere = await require('../utils/campusScope').listWhere(req, 'event'); - // Narrowing filters, so callers needn't download every registration ever made: - // ?unpaid=1 — still owing (not paid or cancelled); ?userId= — one person's. - const filters = []; - if (['1', 'true'].includes(String(req.query.unpaid || ''))) filters.push({ status: { in: ['pending', 'confirmed', 'partial_paid'] } }); - if (req.query.userId) filters.push({ userId: String(req.query.userId) }); - const where = filters.length ? { AND: [scopeWhere, ...filters] } : scopeWhere; - if (typeof req.query.page === 'undefined' && typeof req.query.limit === 'undefined') { - const registrations = await prisma.registration.findMany({ where, include }); - return res.json(attachComputedTotalsToList(registrations)); - } - - const page = Math.max(1, parseInt(req.query.page) || 1); - const limit = Math.min(200, Math.max(1, parseInt(req.query.limit) || 100)); - const skip = (page - 1) * limit; - - const [registrations, total] = await prisma.$transaction([ - prisma.registration.findMany({ where, include, orderBy: { createdAt: 'desc' }, skip, take: limit }), - prisma.registration.count({ where }) - ]); - - res.json({ data: attachComputedTotalsToList(registrations), total, page, limit, pages: Math.ceil(total / limit) }); - } catch (error) { - res.status(400).json({ message: error.message }); - } -}; - -// @desc Get user registrations -// @route GET /api/registrations/myregistrations -// @access Private -const getUserRegistrations = async (req, res) => { - try { - const showPast = String(req.query.showPast || '').toLowerCase() === '1' || String(req.query.showPast || '').toLowerCase() === 'true'; - const now = new Date(); - const whereClause = showPast ? { userId: req.user.id } : { - userId: req.user.id, - status: { not: 'cancelled' }, - event: { endDate: { gte: now }, cashupStatus: { not: 'closed' } } - }; - - // Keep pending/partial-paid registrations' prices current before serving them — an - // early-bird tier can expire while items sit unpaid in someone's registration, and - // without this the dashboard would keep showing a price that was never actually locked - // in by a payment, indefinitely, until the user happens to attempt a payment. - const staleCandidates = await prisma.registration.findMany({ - where: { ...whereClause, status: { in: ['pending', 'partial_paid'] } }, - select: { id: true } - }); - if (staleCandidates.length > 0 && !req.readOnly) { - await Promise.all(staleCandidates.map(r => refreshPricingForRegistration(r.id).catch(() => {}))); - } - - const registrations = await prisma.registration.findMany({ - where: whereClause, - include: { - registrationOptions: { - include: { - eventOption: { include: { earlyBirdTiers: true } }, - variant: { select: { id: true, name: true, price: true } }, - tranches: true, - } - }, - couponRedemptions: ACTIVE_COUPONS_INCLUDE, - - bundleApplications: BUNDLE_APPS_INCLUDE, - attendees: ATTENDEES_INCLUDE, - formResponses: { select: { id: true, attendeeId: true } }, - // Nest the event's form so the frontend can tell whether attendee forms are - // required without a separate GET /api/events/:id per registration. - event: { include: { form: { include: { fields: true } } } }, - user: { - select: { - id: true, - name: true, - email: true, - phoneNumber: true - } - }, - payments: true, - }, - orderBy: { createdAt: 'desc' } - }); - - res.json(attachComputedTotalsToList(registrations)); - } catch (error) { - res.status(400).json({ message: error.message }); - } -}; - -// @desc Get registration by ID -// @route GET /api/registrations/:id -// @access Private -const getRegistrationById = async (req, res) => { - try { - const include = { - registrationOptions: { - include: { - eventOption: { include: { earlyBirdTiers: true } }, - variant: { select: { id: true, name: true, price: true } }, - tickets: true, - tranches: true - } - }, - event: true, - user: { - select: { - id: true, - name: true, - email: true, - phoneNumber: true - } - }, - payments: { include: { recordedBy: { select: { id: true, name: true, email: true } } } }, - formResponses: { include: { answers: true } }, - couponRedemptions: ACTIVE_COUPONS_INCLUDE, - - bundleApplications: BUNDLE_APPS_INCLUDE, - attendees: ATTENDEES_INCLUDE, - }; - - let registration = await prisma.registration.findUnique({ where: { id: req.params.id }, include }); - - if (!registration) { - res.status(404); - throw new Error('Registration not found'); - } - - // See getUserRegistrations — keep an unpaid/partially-paid registration's price current - // whenever it's viewed, not just at payment time. - if ((registration.status === 'pending' || registration.status === 'partial_paid') && !req.readOnly) { - await refreshPricingForRegistration(registration.id).catch(() => {}); - registration = await prisma.registration.findUnique({ where: { id: req.params.id }, include }); - } - - // Guests (no auth) can view by knowing the registrationId (UUID = unguessable) - // Authenticated users must be the owner, staff+, or a named attendee on it - const isOwnerOrStaffViewer = req.user && (registration.userId === req.user.id || ['admin', 'supervisor', 'staff'].includes(req.user.role)); - const isAttendeeViewer = req.user && (registration.attendees || []).some(a => a.userId === req.user.id); - if (req.user && !isOwnerOrStaffViewer && !isAttendeeViewer) { - res.status(403); - throw new Error('Not authorized to view this registration'); - } - // Only the payer and staff see attendees' contact details. - if (!isOwnerOrStaffViewer) { - registration.attendees = (registration.attendees || []).map(a => ({ ...a, email: null, phone: null })); - } - - res.json(attachComputedTotals(registration)); - } catch (error) { - res.status(400).json({ message: error.message }); - } -}; - -// @desc Update registration status -// @route PUT /api/registrations/:id -// @access Private/Admin -const updateRegistrationStatus = async (req, res) => { - try { - const { status } = req.body; - - const registration = await prisma.registration.findUnique({ - where: { id: req.params.id } - }); - - if (!registration) { - res.status(404); - throw new Error('Registration not found'); - } - - await assertEventOpen(registration.eventId, res); - - // If downgrading from paid to not-paid, ensure no tickets were used and delete unused tickets - if (registration.status === 'paid' && status !== 'paid') { - const tickets = await prisma.ticket.findMany({ - where: { registrationOption: { registrationId: req.params.id } }, - include: { usages: true } - }); - const hasUsed = tickets.some(t => t.isUsed || (t.usages && t.usages.length > 0)); - if (hasUsed) { - res.status(400); - throw new Error('Cannot change registration from paid because one or more tickets have been used'); - } - // Delete all unused tickets - await prisma.ticket.deleteMany({ - where: { - registrationOption: { registrationId: req.params.id }, - isUsed: false - } - }); - } - - const updatedRegistration = await prisma.registration.update({ - where: { id: req.params.id }, - data: { - status, - updatedAt: new Date() - }, - include: { - registrationOptions: { - include: { - eventOption: true - } - }, - event: true, - user: { - select: { - id: true, - name: true, - email: true, - phoneNumber: true - } - } - } - }); - - // This is the staff-only status-change endpoint (separate from the owner-facing - // DELETE /:id cancel route), so any transition into 'cancelled' here is always a - // staff-initiated cancellation — log it the same way DELETE /:id does, so both - // paths land under the one 'registration_cancelled' filter in the audit log. - if (status === 'cancelled' && registration.status !== 'cancelled') { - await releaseRegistrationCoupons(req.params.id); - queueWaitlist(registration.eventId); - logAdminAction({ - actorId: req.user.id, - actorRole: req.user.role, - action: 'registration_cancelled', - targetType: 'Registration', - targetId: req.params.id, - metadata: { registrationOwnerId: registration.userId, previousStatus: registration.status }, - ip: getClientIp(req), - }); - } - - // Generate tickets and email them when status is manually set to 'paid' by staff - if (status === 'paid') { - (async () => { - try { - await generateTicketsForRegistration(req.params.id); - const mockReq = { user: { id: updatedRegistration.userId }, body: { registrationId: req.params.id } }; - const mockRes = { status: () => mockRes, json: () => {} }; - await emailTickets(mockReq, mockRes); - } catch (e) { - console.error('[updateRegistrationStatus] Failed to generate/email tickets:', e?.message || e); - } - })(); - } - - res.json(updatedRegistration); - } catch (error) { - res.status(400).json({ message: error.message }); - } -}; - -// @desc Cancel registration +// @desc Cancel a registration // @route DELETE /api/registrations/:id -// @access Private +// @access Private (owner, or an admin) const cancelRegistration = async (req, res) => { try { const updatedRegistration = await registrationService.cancelRegistration(req.params.id, req.user, getClientIp(req)); @@ -333,1486 +29,35 @@ const cancelRegistration = async (req, res) => { } }; -// @desc Get registrations by event -// @route GET /api/registrations/event/:eventId -// @access Private/Admin -const getRegistrationsByEvent = async (req, res) => { +/** A service function as a v1 handler: its answer as JSON, its error as `{ message }`. */ +const handler = (fn, status = () => 200) => async (req, res) => { try { - const { search } = req.query; - - // See getUserRegistrations — keep pending/partial-paid registrations' prices current - // before serving them, rather than only at payment time. - const staleCandidates = await prisma.registration.findMany({ - where: { eventId: req.params.eventId, status: { in: ['pending', 'partial_paid'] } }, - select: { id: true } - }); - if (staleCandidates.length > 0 && !req.readOnly) { - await Promise.all(staleCandidates.map(r => refreshPricingForRegistration(r.id).catch(() => {}))); - } - - let registrations = await prisma.registration.findMany({ - where: { eventId: req.params.eventId }, - include: { - registrationOptions: { - include: { - eventOption: { include: { earlyBirdTiers: true } }, - variant: { select: { id: true, name: true, price: true } }, - tickets: true, - tranches: true, - } - }, - payments: { include: { recordedBy: { select: { id: true, name: true, email: true } } } }, - user: { select: { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true, isActive: true } }, - couponRedemptions: ACTIVE_COUPONS_INCLUDE, - - bundleApplications: BUNDLE_APPS_INCLUDE, - attendees: ATTENDEES_INCLUDE, - }, - orderBy: { createdAt: 'asc' } - }); - - if (search) { - const q = String(search).toLowerCase(); - registrations = registrations.filter(r => - String(r.user?.name || '').toLowerCase().includes(q) || - String(r.user?.email || '').toLowerCase().includes(q) || - String(r.user?.phoneNumber || '').toLowerCase().includes(q) - ); - } - - res.json(attachComputedTotalsToList(registrations)); + const out = await fn(admin.callOf(req)); + res.status(status(out)).json(out); } catch (error) { - res.status(400).json({ message: error.message }); - } -}; - -// @desc Create a new registration for non existing user -// @route POST /api/registrations/manual -// @access Private/Supervisor -const createManualRegistration = async (req, res) => { - let userRecord; - try { - const { eventId, options, user, notificationPreference: prefFromBody, skipActivationNotice, couponCode, attendees, ticketDelivery } = req.body; - - if (!eventId || !options || !user || !user.name || (!user.email && !user.phoneNumber)) { - res.status(400); - throw new Error('Missing required fields: eventId, options, user.name, and at least user.email or user.phoneNumber'); - } - - //Check event - const event = await prisma.event.findUnique({ - where: {id: eventId}, - include: { eventOptions: { include: { earlyBirdTiers: true, variants: true } }, sessions: true }, - }); - - if (!event) { - res.status(404); - throw new Error('Event not found'); - } - - if (!event.isActive) { - res.status(400); - throw new Error('Event is not active'); - } - - await assertEventOpen(eventId, res); - - // Validate options - if (!Array.isArray(options) || options.length === 0) { - res.status(400); - throw new Error('At least one option must be selected'); - } - - // Picked sessions become one line each; staff can still book a session until it ends. - const lines = expandPickLines(event, options, { staff: true }); - await assertSessionCapacity(event, lines); - - // Validate each option up front, before any account is created or changed — - // including stock, which staff registrations previously skipped. - for (const option of lines) { - const eventOption = event.eventOptions.find(eo => eo.id === option.eventOptionId); - if (!eventOption) { - res.status(400); - throw new Error(`Option with ID ${option.eventOptionId} not found for this event`); - } - if (!option.quantity || option.quantity < 1) { - res.status(400); - throw new Error('Quantity must be at least 1'); - } - const variant = option.variantId ? (eventOption.variants || []).find(v => v.id === option.variantId) : null; - const oStock = await checkOptionStock(eventOption, option.quantity, null, option.sessionId); - const vStock = variant ? await checkVariantStock(variant, option.quantity, null, option.sessionId) : { available: true }; - if (!oStock.available || !vStock.available) { - res.status(400); - const left = Math.max(0, Math.min(oStock.remaining ?? Infinity, vStock.remaining ?? Infinity)); - throw new Error(`"${eventOption.name}${variant ? ` (${variant.name})` : ''}" is sold out or does not have enough stock (${left} remaining). Raise the stock limit to add more.`); - } - } - - // Pricing (appliedTierId + priceSnapshot) depends on who the attendee is — Staff and - // above get the staff price — so it runs once the account is resolved below. - const priceManualOptions = (attendee) => Promise.all(lines.map(async (option) => { - const eventOption = event.eventOptions.find(eo => eo.id === option.eventOptionId); - const variantId = option.variantId || null; - const priced = await priceRequestedOption(eventOption, variantId, option.quantity, attendee); - return { ...option, variantId, ...priced }; - })); - - // Resolve or create a user - let userId; - - const { normalizeZAPhone } = require('../utils/whatsapp'); - const phone = normalizeZAPhone(user.phoneNumber) || (user.phoneNumber || '').replace(/\D/g, ''); - const hasValidEmail = !!(user.email && typeof user.email === 'string' && user.email.includes('@')); - - // Derive notification preference: explicit choice wins; otherwise infer from available contact info - const validPrefs = ['email', 'whatsapp', 'both']; - const derivedPref = (prefFromBody && validPrefs.includes(prefFromBody)) - ? prefFromBody - : (hasValidEmail && phone ? 'both' : phone ? 'whatsapp' : 'email'); - - // Always search by email AND/OR phone. - // Resolve each channel independently (rather than a single findFirst with an OR - // across both) so that an email belonging to one account and a phone number - // belonging to a *different* account can never be silently collapsed into - // whichever record happens to match first — that would let a registration - // hijack or corrupt someone else's account. Also try the alternate phone - // format (27xxx ↔ 0xxx) so both representations match. - const phoneAlt = phone && phone.startsWith('27') ? '0' + phone.slice(2) : (phone && phone.length === 9 ? '27' + phone : null); - const emailUser = hasValidEmail - ? await prisma.user.findUnique({ where: { email: user.email } }) - : null; - const phoneUser = phone - ? await prisma.user.findFirst({ where: { OR: [{ phoneNumber: phone }, ...(phoneAlt ? [{ phoneNumber: phoneAlt }] : [])] } }) - : null; - - if (emailUser && phoneUser && emailUser.id !== phoneUser.id) { - res.status(409); - throw new Error( - `This email and phone number belong to two different existing accounts (${emailUser.name} vs ${phoneUser.name}). Please verify the visitor's details before registering.` - ); - } - - const existingUser = emailUser || phoneUser || null; - - if (existingUser) { - userId = existingUser.id; - const updateData = {}; - // The kiosk shows the operator a diff of name/email/phone against the matched - // account and requires explicit confirmation before submitting, so any - // difference reaching this point is an already-confirmed correction — apply - // it as a full overwrite rather than only filling in blanks. - if (user.name && user.name.trim() && user.name.trim() !== existingUser.name) { - updateData.name = user.name.trim(); - } - if (phone && phone !== existingUser.phoneNumber) { - updateData.phoneNumber = phone; - } - if (hasValidEmail && existingUser.email !== user.email) { - updateData.email = user.email; - } - - // Update preference only when the caller explicitly specified one, but validate it - // against the contact info that will actually be on the account after this update — - // a stale "whatsapp"/"both" preference must not survive a phone number being - // removed, nor "email" survive an email being cleared in favor of a real phone. - if (prefFromBody && validPrefs.includes(prefFromBody)) { - const { isValidZAPhone } = require('../utils/whatsapp'); - const finalPhone = updateData.phoneNumber !== undefined ? updateData.phoneNumber : existingUser.phoneNumber; - const finalEmail = updateData.email !== undefined ? updateData.email : existingUser.email; - const finalEmailValid = !!(finalEmail && !finalEmail.endsWith('@guest.local')); - let candidatePref = prefFromBody; - if ((candidatePref === 'whatsapp' || candidatePref === 'both') && !isValidZAPhone(finalPhone)) { - candidatePref = finalEmailValid ? 'email' : candidatePref; - } - if (candidatePref === 'email' && !finalEmailValid && isValidZAPhone(finalPhone)) { - candidatePref = 'whatsapp'; - } - updateData.notificationPreference = candidatePref; - } - - if (Object.keys(updateData).length > 0) { - await prisma.user.update({ where: { id: userId }, data: updateData }).catch(() => {}); - } - } else { - const suppliedPassword = typeof user.password === 'string' && user.password.trim().length >= 6 - ? user.password.trim() - : null; - - if (hasValidEmail && suppliedPassword) { - // Caller supplied their own password (the self-service kiosk, where the - // visitor sets it themselves on the spot) — activate immediately, since - // there's nothing left for them to do via an activation link. - const hashed = await hashPassword(suppliedPassword); - const created = await prisma.user.create({ - data: { - id: uuidv4(), - name: user.name, - email: user.email, - password: hashed, - phoneNumber: phone || null, - isActive: true, - notificationPreference: derivedPref, - updatedAt: new Date(), - } - }); - userId = created.id; - } else { - // New account: uses the real email if a valid one was given, otherwise a - // guest.local placeholder (phone-only registration). Always created inactive - // with a random password — the visitor activates it themselves via the link - // sent immediately below (email or WhatsApp), unless the caller explicitly - // opted out of that nudge (e.g. a self-service visitor who declined to - // create an account at all). - const placeholderEmail = hasValidEmail - ? user.email - : `guest+${uuidv4().slice(0, 8)}@guest.local`; - const hashed = await hashPassword(uuidv4()); - const created = await prisma.user.create({ - data: { - id: uuidv4(), - name: user.name, - email: placeholderEmail, - password: hashed, - phoneNumber: phone || null, - isActive: false, - notificationPreference: derivedPref, - updatedAt: new Date(), - } - }); - userId = created.id; - if (!skipActivationNotice) { - const { sendActivationLink } = require('./userController'); - sendActivationLink(created); - } - } - } - - let couponError = null; - const attendee = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, role: true, email: true } }); - const resolvedManualOptions = await priceManualOptions(attendee); - - // Check the coupon against this attendee before saving anything. - if (couponCode) { - await previewCoupon({ code: couponCode, eventId, user: attendee, lines: pendingCouponLines(event, resolvedManualOptions) }); - } - - // Merge into existing non-cancelled registration if one exists, otherwise create new - const existingReg = await prisma.registration.findFirst({ - where: { userId, eventId, status: { not: 'cancelled' } }, - include: { registrationOptions: true } - }); - - const cleanAttendees = validateAttendees( - event, - placesAfter(existingReg?.registrationOptions, resolvedManualOptions), - attendees, - existingReg ? await namedPlacesByKey(existingReg.id) : {} - ); - if (ticketDelivery !== undefined && !TICKET_DELIVERY.includes(ticketDelivery)) { - res.status(400); - throw new Error("ticketDelivery must be 'payer' or 'each'"); - } - - let registration; - let isNewRegistration = false; - - if (existingReg) { - // Add a new price tranche per requested option into the existing registration (all in - // parallel) — never overwrite an existing row's priceSnapshot/quantity in place, or - // tickets bought at different early-bird prices would blend into a single wrong price. - await Promise.all(resolvedManualOptions.map(opt => { - const existing = existingReg.registrationOptions.find( - ro => ro.eventOptionId === opt.eventOptionId && (ro.variantId || null) === (opt.variantId || null) && (ro.sessionId || null) === (opt.sessionId || null) - ); - if (existing) { - return 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, - // More of an all-sessions ticket: it covers the sessions of both bookings. - ...(existing.sessionId ? {} : { sessionIds: mergeSessionIds(existing.sessionIds, opt.sessionIds) }), - } - }) - ]); - } - return 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, - }] - } - } - }); - })); - // Re-work any coupon over the merged items, and apply a new one, before the status - // is worked out from the totals. - await recalculateRegistrationDiscount(existingReg.id); - if (couponCode) { - try { - await applyCouponToRegistration({ registrationId: existingReg.id, code: couponCode, appliedById: req.user.id }); - } catch (e) { - if (!e.isCouponError) throw e; - couponError = e.message; - } - } - - // Recompute status based on totals across ALL current options and payments - const freshForStatus = await prisma.registration.findUnique({ - where: { id: existingReg.id }, - include: { - registrationOptions: { include: { eventOption: { include: { earlyBirdTiers: true } }, tranches: true } }, - payments: true, - } - }); - const freshTotalDue = computeRegistrationTotalDue(freshForStatus, new Date()); - const freshTotalPaid = (freshForStatus?.payments || []).reduce((sum, p) => sum + (p.amount || 0), 0); - let newExistingStatus; - if (freshTotalDue === 0 || freshTotalPaid >= freshTotalDue) newExistingStatus = 'paid'; - else if (freshTotalPaid > 0) newExistingStatus = 'partial_paid'; - else newExistingStatus = existingReg.status === 'cancelled' ? 'pending' : (existingReg.status || 'pending'); - await prisma.registration.update({ where: { id: existingReg.id }, data: { status: newExistingStatus, updatedAt: new Date() } }); - - registration = await prisma.registration.findUnique({ - where: { id: existingReg.id }, - include: { - registrationOptions: { include: { eventOption: true, tranches: true } }, - event: true, - user: { select: { id: true, name: true, email: true, phoneNumber: true } }, - couponRedemptions: ACTIVE_COUPONS_INCLUDE, - - bundleApplications: BUNDLE_APPS_INCLUDE, - }, - }); - registration.status = newExistingStatus; - } else { - isNewRegistration = true; - const registrationId = uuidv4(); - registration = await prisma.registration.create({ - data: { - id: registrationId, - userId, - eventId, - updatedAt: new Date(), - registrationOptions: { - create: resolvedManualOptions.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, - }] - } - })), - }, - }, - include: { - registrationOptions: { include: { eventOption: true, tranches: true } }, - event: true, - user: { select: { id: true, name: true, email: true, phoneNumber: true } }, - }, - }); - const hasDiscount = (await recalculateRegistrationDiscount(registration.id)) > 0; - if (couponCode) { - try { - await applyCouponToRegistration({ registrationId: registration.id, code: couponCode, appliedById: req.user.id }); - } catch (e) { - if (!e.isCouponError) throw e; - couponError = e.message; - } - } - if (couponCode || hasDiscount) { - registration = await prisma.registration.findUnique({ - where: { id: registration.id }, - include: { - registrationOptions: { include: { eventOption: true, tranches: true } }, - event: true, - user: { select: { id: true, name: true, email: true, phoneNumber: true } }, - couponRedemptions: ACTIVE_COUPONS_INCLUDE, - - bundleApplications: BUNDLE_APPS_INCLUDE, - }, - }); - } - } - - const registrationId = registration.id; - - if (cleanAttendees.length > 0) { - await createAttendees(registrationId, cleanAttendees); - queueConsentRequests(registrationId); - } - if (ticketDelivery) await prisma.registration.update({ where: { id: registrationId }, data: { ticketDelivery } }); - - if (couponCode && !couponError) { - logAdminAction({ - actorId: req.user.id, - actorRole: req.user.role, - action: 'coupon_applied_manual', - targetType: 'Registration', - targetId: registrationId, - metadata: { code: String(couponCode).trim().toUpperCase(), discount: registration.discountTotal, forUserId: userId }, - ip: getClientIp(req), - }); - } - - // Auto mark paid and generate tickets if free and no required form (new registrations only) - let hasRequiredForm = false; - try { - const form = await prisma.eventForm.findUnique({ where: { eventId: registration.eventId } }); - hasRequiredForm = !!(form && form.isRequired); - } catch {} - - // Auto-mark paid and generate tickets for free registrations (new OR existing that became free) - if (registration.status !== 'paid') try { - const totalDue = computeRegistrationTotalDue(registration, new Date()); - if (totalDue === 0) { - await prisma.registration.update({ where: { id: registration.id }, data: { status: 'paid', updatedAt: new Date() } }); - registration.status = 'paid'; - } - } catch {} - - // Generate/sync tickets for all paid registrations that have no required form - if (registration.status === 'paid' && !hasRequiredForm) try { - await generateTicketsForRegistration(registration.id); - } catch {} - - // For paid registrations, generate a checkout link to include in the email - let yocoPaymentUrl = null; - if (registration.status !== 'paid') { - try { - const { createRegistrationCheckout } = require('../payments/checkouts'); - const baseUrl = process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001'; - const checkout = await createRegistrationCheckout(registrationId, userId, { - successUrl: `${baseUrl}/payment/success`, - cancelUrl: `${baseUrl}/payment/cancel`, - failureUrl: `${baseUrl}/payment/failure`, - }); - yocoPaymentUrl = checkout.redirectUrl || null; - } catch (e) { - console.warn('Could not create a checkout for the self-service email:', e?.message || e); - } - } - - // Fire-and-forget: registration email first, then tickets (guarantees order) - const { sendSelfServiceRegistrationEmails, sendRegistrationUpdatedEmails } = require('../utils/notifications'); - const _ssRegId = registrationId; - const _ssUserId = userId; - const _ssPaymentUrl = yocoPaymentUrl; - const _ssFormRequired = hasRequiredForm; - const _ssIsNew = isNewRegistration; - const _ssNotifPref = derivedPref; - const _ssShouldEmailTickets = registration.status === 'paid' && !hasRequiredForm; - (async () => { - try { - if (_ssIsNew) { - await sendSelfServiceRegistrationEmails(_ssRegId, { paymentUrl: _ssPaymentUrl, formRequired: _ssFormRequired }); - } else { - await sendRegistrationUpdatedEmails(_ssRegId); - } - } catch (e) { console.error('Failed to send registration email:', e); } - if (_ssShouldEmailTickets) { - const mockReq = { user: { id: _ssUserId }, body: { registrationId: _ssRegId, channel: _ssNotifPref } }; - const mockRes = { status: () => mockRes, json: () => {} }; - try { await emailTickets(mockReq, mockRes); } catch (e) { console.error('Failed to email tickets after free self-service registration:', e); } - } - })(); - - logAdminAction({ - actorId: req.user.id, - actorRole: req.user.role, - action: 'registration_created_manual', - targetType: 'Registration', - targetId: registrationId, - metadata: { eventId: registration.eventId, forUserId: userId }, - ip: getClientIp(req), - }); - - return res.status(201).json({ ...attachComputedTotals(registration), ...(couponError ? { couponError } : {}) }); - } catch (error) { - console.error(error); - return res.status(400).json({message: error.message}); - } -}; - -// @desc Update registration options (add/remove items) with constraints -// @route PUT /api/registrations/:id/options -// @access Private (owner or staff/admin) -const updateRegistrationOptions = async (req, res) => { - try { - const registrationId = req.params.id; - const userId = req.user.id; - const { options } = req.body; // [{ eventOptionId, quantity }] - - if (!Array.isArray(options)) { - res.status(400); - throw new Error('Options must be an array'); - } - - // Load registration with relations - const registration = await prisma.registration.findUnique({ - where: { id: registrationId }, - include: { - registrationOptions: { - include: { - tickets: true, - tranches: true, - eventOption: { include: { earlyBirdTiers: true, variants: true } } - } - }, - event: { include: { eventOptions: { include: { earlyBirdTiers: true, variants: true } } } }, - payments: true, - user: { select: { id: true, role: true, email: true } }, - } - }); - - if (!registration) { - res.status(404); - throw new Error('Registration not found'); - } - - // Authorization: owner or admin/supervisor/staff - if ( - registration.userId !== userId && - req.user.role !== 'admin' && - req.user.role !== 'supervisor' && - req.user.role !== 'staff' - ) { - res.status(403); - throw new Error('Not authorized to edit this registration'); - } - - // If event is in the past, block edit - if (registration.event?.endDate && new Date(registration.event.endDate).getTime() < Date.now()) { - res.status(400); - throw new Error('This event has already ended; registration cannot be edited'); - } - - // registration.event is already loaded above, so check cashupStatus directly here - // rather than re-fetching via assertEventOpen. - if (registration.event?.cashupStatus === 'closed') { - res.status(400); - throw new Error('This event is closed. Reopen it (admin only) before making changes.'); - } - - // Validate provided options: must belong to same event and quantities >=1 - if (options.length === 0) { - res.status(400); - throw new Error('At least one option must be provided'); - } - - const validOptionIds = new Set((registration.event?.eventOptions || []).map(eo => eo.id)); - const pickOptionIds = new Set((registration.event?.eventOptions || []).filter(eo => isPickOption(registration.event, eo)).map(eo => eo.id)); - for (const opt of options) { - if (!opt || !opt.eventOptionId || !Number.isInteger(opt.quantity) || opt.quantity < 1) { - res.status(400); - throw new Error('Each option must include a valid eventOptionId and quantity >= 1'); - } - if (!validOptionIds.has(opt.eventOptionId)) { - res.status(400); - throw new Error('One or more options do not belong to this event'); - } - if (pickOptionIds.has(opt.eventOptionId)) { - res.status(400); - throw new Error("Sessions are booked by registering for them — they can't be changed here."); - } - } - // The kids check-in and volunteer tickets are handed out by staff: the owner can keep (or - // lower) the places they were given, not add more. - if (!isStaffRole(req.user.role)) { - for (const id of reservedOptionIds(registration.event)) { - const had = registration.registrationOptions.filter(ro => ro.eventOptionId === id).reduce((n, ro) => n + (ro.quantity || 0), 0); - const asked = options.filter(o => o.eventOptionId === id).reduce((n, o) => n + o.quantity, 0); - if (asked > had) { - res.status(400); - throw new Error('One or more options do not belong to this event'); - } - } - } - - // Picked-session lines aren't edited here: leave them exactly as they are (they still - // count towards the total due). - const pickedLines = registration.registrationOptions.filter(ro => ro.sessionId); - registration.registrationOptions = registration.registrationOptions.filter(ro => !ro.sessionId); - - // Compute totalPaid - const totalPaid = (registration.payments || []).reduce((sum, p) => sum + (p.amount || 0), 0); - - // Merge duplicate entries for the same eventOptionId+variantId (defensive; normal - // callers send one entry per option/variant combo). - const mergedOptionsMap = new Map(); - for (const opt of options) { - const key = `${opt.eventOptionId}::${opt.variantId || ''}`; - if (mergedOptionsMap.has(key)) { - mergedOptionsMap.get(key).quantity += opt.quantity; - } else { - mergedOptionsMap.set(key, { ...opt }); - } - } - const mergedOptions = Array.from(mergedOptionsMap.values()); - - // Group existing registrationOptions by eventOptionId::variantId so tickets that - // have already been issued are never deleted, only ever updated in place. Computed - // before pricing resolution because pricing now depends on whether a quantity is - // increasing (and by how much) — an unchanged or reduced quantity must never - // re-price tickets already locked in at an earlier price (see tranche design). - const oldByKey = new Map(); - for (const ro of registration.registrationOptions) { - const key = `${ro.eventOptionId}::${ro.variantId || ''}`; - if (!oldByKey.has(key)) oldByKey.set(key, []); - oldByKey.get(key).push(ro); - } - - // A legacy row (created before the tranche migration) has no tranches — fall back to - // its own priceSnapshot/quantity as a single implicit tranche for totals purposes. - const trancheSum = (tranches) => (tranches || []).reduce((s, t) => s + Number(t.quantity || 0) * Number(t.priceSnapshot || 0), 0); - const rowsTotal = (rows) => rows.reduce((sum, ro) => { - const tranches = ro.tranches || []; - if (tranches.length > 0) return sum + trancheSum(tranches); - return sum + Number(ro.quantity || 0) * Number(ro.priceSnapshot ?? ro.eventOption?.price ?? 0); - }, 0); - // Remove `qtyToRemove` units from a set of tranches, newest-first (LIFO) — mirrors the - // ticket-floor invariant below: issued tickets always map to the oldest tranches, so the - // newest (least-committed) tranches are the ones trimmed first on a quantity decrease. - const planLIFORemoval = (tranches, qtyToRemove) => { - const sorted = [...tranches].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)); - let remaining = qtyToRemove; - const ops = []; - const kept = []; - for (const t of sorted) { - if (remaining <= 0) { kept.push(t); continue; } - if (t.quantity <= remaining) { - remaining -= t.quantity; - ops.push({ type: 'delete', trancheId: t.id }); - } else { - const newQuantity = t.quantity - remaining; - remaining = 0; - ops.push({ type: 'update', trancheId: t.id, newQuantity }); - kept.push({ ...t, quantity: newQuantity }); - } - } - return { kept, ops }; - }; - - // Resolve pricing for each incoming option (variant-aware, with stock check) — but only - // for the delta being newly added. Unchanged or decreasing quantities never re-resolve. - const eventOptionsMap = new Map((registration.event?.eventOptions || []).map(eo => [eo.id, eo])); - const resolvedUpdateOptions = []; - let newTotalDue = 0; - for (const opt of mergedOptions) { - const key = `${opt.eventOptionId}::${opt.variantId || ''}`; - const existingRows = oldByKey.get(key) || []; - const existingQty = existingRows.reduce((sum, ro) => sum + (ro.quantity || 0), 0); - const delta = (opt.quantity || 0) - existingQty; - const existingTotal = rowsTotal(existingRows); - - const eventOption = eventOptionsMap.get(opt.eventOptionId); - const variantId = opt.variantId || null; - let priceSnapshot = null; - let appliedTierId = null; - let removalPlan = null; - - if (delta > 0) { - // Adding places needs stock, like a new registration does. - const oStock = await checkOptionStock(eventOption, delta); - const variant = variantId ? (eventOption.variants || []).find(v => v.id === variantId) : null; - const vStock = variant ? await checkVariantStock(variant, delta) : { available: true }; - if (!oStock.available || !vStock.available) { - res.status(400); - const left = Math.max(0, Math.min(oStock.remaining ?? Infinity, vStock.remaining ?? Infinity)); - throw new Error(`Only ${left} more "${eventOption.name}${variant ? ` (${variant.name})` : ''}" available.`); - } - ({ priceSnapshot, appliedTierId } = await priceRequestedOption(eventOption, variantId, delta, registration.user)); - newTotalDue += existingTotal + delta * (priceSnapshot || 0); - } else if (delta < 0) { - const existingTranches = existingRows.flatMap(ro => ro.tranches || []); - removalPlan = planLIFORemoval(existingTranches, -delta); - newTotalDue += trancheSum(removalPlan.kept); - } else { - newTotalDue += existingTotal; - } - - resolvedUpdateOptions.push({ ...opt, variantId, priceSnapshot, appliedTierId, existingRows, existingQty, delta, removalPlan }); - } - - newTotalDue += rowsTotal(pickedLines); - if (newTotalDue < totalPaid) { - res.status(400); - throw new Error('Cannot reduce items below the amount already paid'); - } - - // Per-item floor: a ticket is only ever created once a registration is paid, and it is - // never deleted or shrunk — only grown. So an option can never be reduced (or removed) - // below the quantity of any ticket already issued for it. - const newKeys = new Set(resolvedUpdateOptions.map(opt => `${opt.eventOptionId}::${opt.variantId || ''}`)); - const newQtyByKey = new Map(resolvedUpdateOptions.map(opt => [`${opt.eventOptionId}::${opt.variantId || ''}`, opt.quantity || 0])); - for (const [key, rows] of oldByKey) { - const ticketQty = rows.reduce((sum, ro) => sum + (ro.tickets || []).reduce((s, t) => s + (t.quantity || 0), 0), 0); - if (ticketQty <= 0) continue; - const newQty = newQtyByKey.get(key) || 0; - if (newQty < ticketQty) { - res.status(400); - throw new Error(`Cannot reduce "${rows[0].eventOption?.name || 'item'}" below the ${ticketQty} ticket(s) already issued`); - } - } - - // Differential update: update matching options in place, create genuinely new ones, - // and only delete options that were removed entirely. The floor check above guarantees - // a removed key never has tickets — the guard below turns that into a hard invariant - // instead of an assumption: tickets are never deleted. - await prisma.$transaction(async (tx) => { - for (const [key, rows] of oldByKey) { - if (newKeys.has(key)) continue; - const ticketedRows = rows.filter(ro => (ro.tickets || []).length > 0); - if (ticketedRows.length > 0) { - throw new Error(`Cannot remove "${rows[0].eventOption?.name || 'item'}" — tickets have already been issued for it`); - } - await tx.registrationOption.deleteMany({ where: { id: { in: rows.map(r => r.id) } } }); - } - - for (const opt of resolvedUpdateOptions) { - const key = `${opt.eventOptionId}::${opt.variantId || ''}`; - const existingRows = oldByKey.get(key); - if (existingRows && existingRows.length > 0) { - const [primary, ...dupes] = existingRows; - - // Consolidate dupes into primary first: move their tranches and tickets rather - // than discarding them, so price history (and money) survives duplicate cleanup. - for (const dup of dupes) { - if ((dup.tranches || []).length > 0) { - await tx.registrationOptionTranche.updateMany({ where: { registrationOptionId: dup.id }, data: { registrationOptionId: primary.id } }); - } - if ((dup.tickets || []).length > 0) { - await tx.ticket.updateMany({ where: { registrationOptionId: dup.id }, data: { registrationOptionId: primary.id } }); - } - await tx.registrationOption.delete({ where: { id: dup.id } }); - } - - if (opt.delta > 0) { - // Increase: a new tranche for the delta at the freshly-resolved price — never - // overwrite the existing tranches' locked-in prices. - await tx.registrationOptionTranche.create({ - data: { - id: uuidv4(), - registrationOptionId: primary.id, - quantity: opt.delta, - priceSnapshot: opt.priceSnapshot, - appliedTierId: opt.appliedTierId || null, - } - }); - await tx.registrationOption.update({ - where: { id: primary.id }, - data: { quantity: opt.quantity, appliedTierId: opt.appliedTierId || null, priceSnapshot: opt.priceSnapshot } - }); - } else if (opt.delta < 0 && opt.removalPlan) { - // Decrease: trim tranches newest-first (LIFO); issued tickets always map to the - // oldest tranches, and the floor check above already guarantees this never dips - // below issued-ticket quantity. - for (const op of opt.removalPlan.ops) { - if (op.type === 'delete') { - await tx.registrationOptionTranche.delete({ where: { id: op.trancheId } }); - } else { - await tx.registrationOptionTranche.update({ where: { id: op.trancheId }, data: { quantity: op.newQuantity } }); - } - } - const newest = [...opt.removalPlan.kept].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))[0]; - await tx.registrationOption.update({ - where: { id: primary.id }, - data: { - quantity: opt.quantity, - appliedTierId: newest ? (newest.appliedTierId || null) : null, - priceSnapshot: newest ? newest.priceSnapshot : null, - } - }); - } else { - // Unchanged quantity: only reflect dupe-consolidation in the aggregate; leave - // the locked-in price/tier untouched. - await tx.registrationOption.update({ - where: { id: primary.id }, - data: { quantity: opt.quantity } - }); - } - } else { - await tx.registrationOption.create({ - data: { - id: uuidv4(), - registrationId, - eventOptionId: opt.eventOptionId, - quantity: opt.quantity, - variantId: opt.variantId || null, - appliedTierId: opt.appliedTierId || null, - priceSnapshot: opt.priceSnapshot, - tranches: { - create: [{ - id: uuidv4(), - quantity: opt.quantity, - priceSnapshot: opt.priceSnapshot, - appliedTierId: opt.appliedTierId || null, - }] - } - } - }); - } - } - - // Names on places that no longer exist go too (newest first). Tickets for them - // are tidied up by generateTicketsForRegistration; the floor check above already - // stops anything going below tickets issued. - await tx.attendee.deleteMany({ where: { registrationId, registrationOptionId: null } }); - const lines = await tx.registrationOption.findMany({ where: { registrationId }, include: { attendees: { orderBy: { order: 'desc' } } } }); - for (const line of lines) { - const extra = (line.attendees || []).length - (line.quantity || 0); - if (extra > 0) { - await tx.attendee.deleteMany({ where: { id: { in: line.attendees.slice(0, extra).map(a => a.id) } } }); - } - } - - // Coupon: percentage/comp codes follow the new items, fixed codes keep their amount. - const discount = await recalculateRegistrationDiscount(registrationId, tx); - const dueAfterDiscount = Math.max(0, newTotalDue - discount); - if (dueAfterDiscount < totalPaid - 0.001) { - throw new Error('Cannot reduce items below the amount already paid'); - } - - // Update updatedAt and potentially status based on payments vs due - let newStatus = registration.status; - if (totalPaid >= dueAfterDiscount) newStatus = 'paid'; - else if (totalPaid > 0) newStatus = 'partial_paid'; - else newStatus = 'pending'; - - await tx.registration.update({ - where: { id: registrationId }, - data: { updatedAt: new Date(), status: newStatus } - }); - }); - - // Return updated registration - const updated = await prisma.registration.findUnique({ - where: { id: registrationId }, - include: { - registrationOptions: { include: { eventOption: true, tranches: true } }, - event: true, - user: { select: { id: true, name: true, email: true, phoneNumber: true } }, - payments: true, - couponRedemptions: ACTIVE_COUPONS_INCLUDE, - - bundleApplications: BUNDLE_APPS_INCLUDE, - attendees: ATTENDEES_INCLUDE, - } - }); - - const { sendRegistrationUpdatedEmails } = require('../utils/notifications'); - sendRegistrationUpdatedEmails(registrationId).catch(e => console.error('Failed to send registration updated emails:', e)); - if (resolvedUpdateOptions.some(o => o.delta < 0) || oldByKey.size > newKeys.size) queueWaitlist(registration.eventId); - - // If registration is now paid, regenerate tickets and send them - if (updated.status === 'paid') { - (async () => { - try { - await generateTicketsForRegistration(registrationId); - const mockReq = { user: { id: updated.userId }, body: { registrationId } }; - const mockRes = { status: () => mockRes, json: () => {} }; - await emailTickets(mockReq, mockRes); - } catch (e) { - console.error('[updateRegistrationOptions] Failed to generate/send tickets:', e?.message || e); - } - })(); - } - - return res.json(attachComputedTotals(updated)); - } catch (error) { - return res.status(400).json({ message: error.message }); - } -}; - -// @desc Submit form responses for a registration -// @route POST /api/registrations/:id/forms/responses -// @access Private -const submitFormResponses = async (req, res) => { - try { - const registrationId = req.params.id; - const userId = req.user?.id || null; - const { responses } = req.body; // [{ answers: { fieldId: value } }] - - // load registration with options and event form - const registration = await prisma.registration.findUnique({ - where: { id: registrationId }, - include: { - registrationOptions: { include: { eventOption: true, tranches: true } }, - event: true, - } - }); - if (!registration) { res.status(404); throw new Error('Registration not found'); } - // Guests (no auth) may submit by knowing the registrationId; authenticated users must be - // owner, staff+, or submitting their own form as a named attendee - const ownAttendeeOnly = Array.isArray(responses) && responses.length > 0 && req.user - && (await prisma.attendee.count({ where: { registrationId, userId, id: { in: responses.map(r => r?.attendeeId).filter(Boolean) } } })) === responses.length; - if (req.user && registration.userId !== userId && !['admin','supervisor','staff'].includes(req.user.role) && !ownAttendeeOnly) { - res.status(403); throw new Error('Not authorized'); - } - - // fetch form - let form = null; - try { - form = await prisma.eventForm.findUnique({ where: { eventId: registration.eventId }, include: { fields: true } }); - } catch (e) {} - if (!form) { - return res.json({ message: 'No form for this event. Nothing to submit.' }); - } - - const fields = (form.fields || []).sort((a,b) => (a.order||0)-(b.order||0)); - const answerableFields = fields.filter(f => f.type !== 'statement' && f.type !== 'paragraph'); - - const mainTickets = registration.registrationOptions.filter(ro => ro.eventOption?.isMainTicket).reduce((s, ro) => s + (ro.quantity || 0), 0); - const toSubmit = Array.isArray(responses) ? responses : []; - - if (toSubmit.length === 0) { res.status(400); throw new Error('No responses provided'); } - if (toSubmit.length > mainTickets) { res.status(400); throw new Error(`Too many forms submitted. Expected at most ${mainTickets}`); } - - // A response can be for a named attendee (group tickets); each attendee answers once. - const attendeeIds = toSubmit.map(r => r?.attendeeId).filter(Boolean); - if (attendeeIds.length > 0) { - const known = await prisma.attendee.findMany({ where: { id: { in: attendeeIds }, registrationId }, include: { formResponses: { select: { id: true } } } }); - if (known.length !== new Set(attendeeIds).size) { res.status(400); throw new Error('Unknown attendee for this registration'); } - const answered = known.find(a => a.formResponses.length > 0); - if (answered) { res.status(400); throw new Error(`${answered.name}'s form has already been submitted`); } - } - - // Create responses and answers - const created = []; - for (const resp of toSubmit) { - const respId = uuidv4(); - const fr = await prisma.formResponse.create({ data: { id: respId, registrationId, attendeeId: resp?.attendeeId || null } }); - const ansMap = resp?.answers || {}; - for (const f of answerableFields) { - const raw = ansMap[f.id]; - // If field required at field-level, enforce non-empty - if (f.isRequired && (raw === undefined || raw === null || String(raw).trim() === '')) { - res.status(400); - throw new Error(`Missing answer for: ${f.label}`); - } - if (raw !== undefined && raw !== null && String(raw).length > 0) { - await prisma.formAnswer.create({ data: { id: uuidv4(), responseId: respId, fieldId: f.id, value: String(raw) } }); - } - } - created.push(fr); - } - - // After submitting responses, if registration is already paid, generate and email tickets now. - let generatedTickets = []; - try { - const regAfter = await prisma.registration.findUnique({ where: { id: registrationId } }); - if (regAfter && regAfter.status === 'paid') { - generatedTickets = await generateTicketsForRegistration(registrationId); - if (generatedTickets && generatedTickets.length > 0) { - try { - const mockReq = { user: { id: regAfter.userId }, body: { registrationId } }; - const mockRes = { status: () => mockRes, json: () => {} }; - await emailTickets(mockReq, mockRes); - } catch (emailErr) { - console.error('Post-form ticket email failed:', emailErr?.message || emailErr); - } - } - } - } catch (e) { - console.error('Post-form ticket generation attempt failed:', e?.message || e); - } - - res.status(201).json({ message: 'Responses submitted', count: created.length, generatedTickets: (generatedTickets && generatedTickets.length) ? generatedTickets : undefined }); - } catch (error) { - res.status(400).json({ message: error.message }); - } -}; - -// @desc Replace (edit) form responses for a registration (staff/admin/supervisor) -// @route PUT /api/registrations/:id/forms/responses -// @access Private/Staff -const replaceFormResponses = async (req, res) => { - try { - const registrationId = req.params.id; - const { responses } = req.body; // [{ answers: { fieldId: value } }] - - // Authorization: staff or above only for replacing existing responses - if (!['admin','supervisor','staff'].includes(req.user.role)) { - res.status(403); - throw new Error('Not authorized'); - } - - // Load registration and form - const registration = await prisma.registration.findUnique({ - where: { id: registrationId }, - include: { - registrationOptions: { include: { eventOption: true, tranches: true } }, - event: true, - } - }); - if (!registration) { res.status(404); throw new Error('Registration not found'); } - - let form = null; - try { - form = await prisma.eventForm.findUnique({ where: { eventId: registration.eventId }, include: { fields: true } }); - } catch {} - if (!form) { return res.json({ message: 'No form for this event. Nothing to save.' }); } - - const fields = (form.fields || []).sort((a,b) => (a.order||0)-(b.order||0)); - const answerableFields = fields.filter(f => f.type !== 'statement' && f.type !== 'paragraph'); - const mainTickets = registration.registrationOptions.filter(ro => ro.eventOption?.isMainTicket).reduce((s, ro) => s + (ro.quantity || 0), 0); - const toSubmit = Array.isArray(responses) ? responses : []; - - if (toSubmit.length === 0) { res.status(400); throw new Error('No responses provided'); } - if (toSubmit.length > mainTickets) { res.status(400); throw new Error(`Too many forms submitted. Expected at most ${mainTickets}`); } - - // Replace transactionally - await prisma.$transaction(async (tx) => { - // Delete existing answers and responses for this registration - const existing = await tx.formResponse.findMany({ where: { registrationId }, select: { id: true } }); - const ids = existing.map(e => e.id); - if (ids.length > 0) { - await tx.formAnswer.deleteMany({ where: { responseId: { in: ids } } }); - await tx.formResponse.deleteMany({ where: { id: { in: ids } } }); - } - // Create new set - for (const resp of toSubmit) { - const respId = uuidv4(); - await tx.formResponse.create({ data: { id: respId, registrationId } }); - const ansMap = resp?.answers || {}; - for (const f of answerableFields) { - const raw = ansMap[f.id]; - if (f.isRequired && (raw === undefined || raw === null || String(raw).trim() === '')) { - res.status(400); - throw new Error(`Missing answer for: ${f.label}`); - } - if (raw !== undefined && raw !== null && String(raw).length > 0) { - await tx.formAnswer.create({ data: { id: uuidv4(), responseId: respId, fieldId: f.id, value: String(raw) } }); - } - } - } - // Touch registration updatedAt - await tx.registration.update({ where: { id: registrationId }, data: { updatedAt: new Date() } }); - }); - - // Attempt ticket generation and email if already paid - try { - const regAfter = await prisma.registration.findUnique({ where: { id: registrationId }, include: { user: { select: { id: true } } } }); - if (regAfter && regAfter.status === 'paid') { - const newTickets = await generateTicketsForRegistration(registrationId); - if (newTickets && newTickets.length > 0) { - try { - const mockReq = { user: { id: regAfter.userId }, body: { registrationId } }; - const mockRes = { status: () => mockRes, json: () => {} }; - await emailTickets(mockReq, mockRes); - } catch (emailErr) { - console.error('Error emailing tickets after form replacement:', emailErr); - } - } - } - } catch {} - - return res.json({ message: 'Responses saved' }); - } catch (error) { - return res.status(400).json({ message: error.message }); - } -}; - -// @desc Get saved draft for attendee forms for a registration (owner or staff) -// @route GET /api/registrations/:id/forms/draft -// @access Private -const getFormDraft = async (req, res) => { - try { - const registrationId = req.params.id; - const userId = req.user?.id || null; - - // Ensure Prisma Client has the FormDraft model (migration + generate applied) - const hasFormDraftRead = !!(prisma && prisma.formDraft && typeof prisma.formDraft.findUnique === 'function'); - if (!hasFormDraftRead) { - return res.status(400).json({ - message: 'Draft storage is not available on the server.', - hint: 'Apply Prisma migrations and regenerate the Prisma Client, then restart the server.', - next: [ - 'cd backend', - 'npx prisma migrate dev -n add-form-draft', - 'npx prisma generate', - 'restart the backend server' - ] - }); - } - - // Load registration to verify access - const registration = await prisma.registration.findUnique({ where: { id: registrationId } }); - if (!registration) { res.status(404); throw new Error('Registration not found'); } - if (req.user && registration.userId !== userId && !['admin','supervisor','staff'].includes(req.user.role)) { - res.status(403); throw new Error('Not authorized'); - } - - // Find draft. If staff/admin, we still scope the draft to the registration owner (so they can resume later). - const ownerUserId = registration.userId; - const draft = await prisma.formDraft.findUnique({ where: { registrationId_userId: { registrationId, userId: ownerUserId } } }); - if (!draft) return res.json({ data: {}, updatedAt: null }); - return res.json({ data: draft.data || {}, updatedAt: draft.updatedAt }); - } catch (error) { - return res.status(400).json({ message: error.message }); - } -}; - -// @desc Save draft for attendee forms for a registration (owner or staff). Does not mark as completed. -// @route PUT /api/registrations/:id/forms/draft -// @access Private -const saveFormDraft = async (req, res) => { - try { - const registrationId = req.params.id; - const userId = req.user?.id || null; - const { data } = req.body; // JSON object mapping attendeeIndex -> { fieldId: value } - - if (typeof data !== 'object' || data == null) { - res.status(400); throw new Error('Invalid draft payload'); - } - - // Ensure Prisma Client has the FormDraft model (migration + generate applied) - const hasFormDraftWrite = !!(prisma && prisma.formDraft && typeof prisma.formDraft.upsert === 'function'); - if (!hasFormDraftWrite) { - return res.status(400).json({ - message: 'Draft storage is not available on the server.', - hint: 'Apply Prisma migrations and regenerate the Prisma Client, then restart the server.', - next: [ - 'cd backend', - 'npx prisma migrate dev -n add-form-draft', - 'npx prisma generate', - 'restart the backend server' - ] - }); - } - - // Load registration to verify access - const registration = await prisma.registration.findUnique({ where: { id: registrationId } }); - if (!registration) { res.status(404); throw new Error('Registration not found'); } - if (req.user && registration.userId !== userId && !['admin','supervisor','staff'].includes(req.user.role)) { - res.status(403); throw new Error('Not authorized'); - } - - const ownerUserId = registration.userId; - - // Upsert by (registrationId, userId) unique composite - const saved = await prisma.formDraft.upsert({ - where: { registrationId_userId: { registrationId, userId: ownerUserId } }, - update: { data, updatedAt: new Date() }, - create: { registrationId, userId: ownerUserId, data }, - }); - - return res.json({ message: 'Draft saved', updatedAt: saved.updatedAt }); - } catch (error) { - return res.status(400).json({ message: error.message }); - } -}; - -// @desc Re-send the current invoice PDF for one of the caller's own registrations -// @route POST /api/registrations/:id/send-invoice -// @access Private -const sendInvoice = async (req, res) => { - try { - const { channel } = req.body || {}; - const { sendInvoiceToUser } = require('../utils/notifications'); - await sendInvoiceToUser(req.params.id, req.user.id, channel); - res.json({ message: channel === 'whatsapp' ? 'Invoice sent to WhatsApp.' : 'Invoice emailed.' }); - } catch (error) { - res.status(error.statusCode || 400).json({ message: error.message }); - } -}; - -/** - * After a discount changes, bring the status in line with the new total. A registration - * that a coupon has made fully paid gets its tickets, as any paid registration does. - */ -async function syncStatusAfterDiscount(registrationId) { - const reg = await prisma.registration.findUnique({ - where: { id: registrationId }, - include: { registrationOptions: { include: { eventOption: true, tranches: true } }, payments: true }, - }); - const due = computeRegistrationTotalDue(reg, new Date()); - const paid = (reg.payments || []).reduce((s, p) => s + (p.amount || 0), 0); - const status = paid >= due - 0.001 ? 'paid' : paid > 0 ? 'partial_paid' : 'pending'; - if (status !== reg.status) { - await prisma.registration.update({ where: { id: registrationId }, data: { status, updatedAt: new Date() } }); - } - if (status === 'paid' && reg.status !== 'paid') { - (async () => { - try { - let hasRequiredForm = false; - try { - const form = await prisma.eventForm.findUnique({ where: { eventId: reg.eventId } }); - hasRequiredForm = !!(form && form.isRequired); - } catch {} - if (hasRequiredForm) return; - await generateTicketsForRegistration(registrationId); - const mockReq = { user: { id: reg.userId }, body: { registrationId } }; - const mockRes = { status: () => mockRes, json: () => {} }; - await emailTickets(mockReq, mockRes); - } catch (e) { - console.error('[coupon] Failed to issue tickets after discount:', e?.message || e); - } - })(); - } - return status; -} - - -// @desc Apply a coupon code to an existing registration -// @route POST /api/registrations/:id/coupon -// @access Private (owner, or staff applying it on someone's behalf) -const applyCoupon = async (req, res) => { - try { - const { code } = req.body || {}; - const registration = await prisma.registration.findUnique({ - where: { id: req.params.id }, - include: { event: { select: { endDate: true, cashupStatus: true } } }, - }); - if (!registration) { res.status(404); throw new Error('Registration not found'); } - const byStaff = registration.userId !== req.user.id; - if (byStaff && !isStaffRole(req.user.role)) { res.status(403); throw new Error('Not authorized to change this registration'); } - if (registration.status === 'cancelled') { res.status(400); throw new Error('This registration is cancelled.'); } - if (registration.event?.cashupStatus === 'closed') { res.status(400); throw new Error('This event is closed.'); } - if (registration.event?.endDate && new Date(registration.event.endDate) < new Date()) { - res.status(400); throw new Error('This event has already ended.'); - } - - const { coupon, discount } = await applyCouponToRegistration({ - registrationId: registration.id, - code, - appliedById: byStaff ? req.user.id : null, - }); - await syncStatusAfterDiscount(registration.id); - - if (byStaff) { - logAdminAction({ - actorId: req.user.id, - actorRole: req.user.role, - action: 'coupon_applied_manual', - targetType: 'Registration', - targetId: registration.id, - metadata: { code: coupon.code, discount, forUserId: registration.userId }, - ip: getClientIp(req), - }); - } - - const { sendRegistrationUpdatedEmails } = require('../utils/notifications'); - sendRegistrationUpdatedEmails(registration.id).catch(e => console.error('Failed to send registration updated emails:', e)); - - const updated = await prisma.registration.findUnique({ - where: { id: registration.id }, - include: { - registrationOptions: { include: { eventOption: true, variant: { select: { id: true, name: true, price: true } }, tranches: true } }, - payments: true, - couponRedemptions: ACTIVE_COUPONS_INCLUDE, - - bundleApplications: BUNDLE_APPS_INCLUDE, - }, - }); - res.json({ ...attachComputedTotals(updated), message: `Code ${coupon.code} applied — ${describeCoupon(coupon)}.` }); - } catch (error) { - res.status(error.statusCode || (res.statusCode === 200 ? 400 : res.statusCode)).json({ message: error.message }); - } -}; - -// @desc Remove the coupon from a registration (the use is freed) -// @route DELETE /api/registrations/:id/coupon -// @access Private/Staff -const removeCoupon = async (req, res) => { - try { - const registration = await prisma.registration.findUnique({ where: { id: req.params.id } }); - if (!registration) { res.status(404); throw new Error('Registration not found'); } - await assertEventOpen(registration.eventId, res); - - // Removing a discount raises the total, which can take a paid registration back to - // unpaid. Same rule as a staff status change: refuse once a ticket has been scanned, - // otherwise withdraw the unused tickets until it's paid again. - const tickets = await prisma.ticket.findMany({ - where: { registrationOption: { registrationId: registration.id } }, - include: { usages: true }, - }); - if (registration.status === 'paid' && tickets.some(t => t.isUsed || t.usages.length > 0)) { - res.status(400); - throw new Error('A ticket on this registration has already been scanned, so its code can\'t be removed.'); - } - - const released = await releaseRegistrationCoupons(registration.id); - if (!released) { res.status(400); throw new Error('No code is applied to this registration.'); } - const status = await syncStatusAfterDiscount(registration.id); - if (registration.status === 'paid' && status !== 'paid') { - await prisma.ticket.deleteMany({ where: { registrationOption: { registrationId: registration.id }, isUsed: false } }); - } - - logAdminAction({ - actorId: req.user.id, - actorRole: req.user.role, - action: 'coupon_applied_manual', - targetType: 'Registration', - targetId: registration.id, - metadata: { removed: true, forUserId: registration.userId }, - ip: getClientIp(req), - }); - res.json({ message: 'Code removed.' }); - } catch (error) { - res.status(error.statusCode || (res.statusCode === 200 ? 400 : res.statusCode)).json({ message: error.message }); - } -}; - -const isOwnerOrStaff = (registration, user) => - registration.userId === user.id || ['admin', 'supervisor', 'staff'].includes(user.role); - -// @desc Replace the named attendees on a registration (and who gets the tickets) -// @route PUT /api/registrations/:id/attendees -// @access Private (owner or staff) -// Body: { attendees: [{ id?, eventOptionId, variantId?, name, email?, phone? }], ticketDelivery? } -// Attendees left out are removed — refused if their ticket has been scanned. -const updateAttendees = async (req, res) => { - try { - const { attendees = [], ticketDelivery } = req.body || {}; - const registration = await prisma.registration.findUnique({ - where: { id: req.params.id }, - include: { - registrationOptions: true, - attendees: { include: { ticket: { include: { usages: true } } } }, - event: { include: { eventOptions: true } }, - }, - }); - if (!registration) { res.status(404); throw new Error('Registration not found'); } - if (!isOwnerOrStaff(registration, req.user)) { res.status(403); throw new Error('Not authorized to edit this registration'); } - if (registration.status === 'cancelled') { res.status(400); throw new Error('This registration is cancelled.'); } - if (registration.event?.cashupStatus === 'closed') { res.status(400); throw new Error('This event is closed.'); } - if (registration.event?.endDate && new Date(registration.event.endDate) < new Date()) { - res.status(400); throw new Error('This event has already ended.'); - } - if (ticketDelivery !== undefined && !TICKET_DELIVERY.includes(ticketDelivery)) { - res.status(400); throw new Error("ticketDelivery must be 'payer' or 'each'"); - } - - const clean = validateAttendees(registration.event, placesAfter(registration.registrationOptions, []), attendees); - const keepIds = new Set(attendees.map(a => a?.id).filter(Boolean)); - const existingById = new Map(registration.attendees.map(a => [a.id, a])); - for (const id of keepIds) if (!existingById.has(id)) { res.status(400); throw new Error('Unknown attendee for this registration'); } - const removed = registration.attendees.filter(a => !keepIds.has(a.id)); - const usedRemoved = removed.find(a => a.ticket && (a.ticket.isUsed || a.ticket.usages.length > 0)); - if (usedRemoved) { res.status(400); throw new Error(`${usedRemoved.name}'s ticket has already been scanned, so they can't be removed.`); } - - const toCreate = []; - await prisma.$transaction(async (tx) => { - if (removed.length) await tx.attendee.deleteMany({ where: { id: { in: removed.map(a => a.id) } } }); - for (let i = 0; i < attendees.length; i++) { - const a = attendees[i]; - const c = clean[i]; - if (a.id) { - const prev = existingById.get(a.id); - const contactChanged = prev.email !== c.email || prev.phone !== c.phone; - const match = contactChanged && (c.email || c.phone) ? await findAccountByContact({ email: c.email, phone: c.phone }, tx) : null; - await tx.attendee.update({ - where: { id: a.id }, - data: { - name: c.name, email: c.email, phone: c.phone, - dateOfBirth: c.dateOfBirth, gender: c.gender, parentName: c.parentName, parentEmail: c.parentEmail, parentPhone: c.parentPhone, - ...(contactChanged ? { userId: match?.user?.id || null } : {}), - }, - }); - } else { - toCreate.push(c); - } - } - if (toCreate.length) await createAttendees(registration.id, toCreate, tx); - if (ticketDelivery) await tx.registration.update({ where: { id: registration.id }, data: { ticketDelivery } }); - }); - - queueConsentRequests(registration.id); - - // Paid registrations: re-sync tickets and send any new ones. - if (registration.status === 'paid') { - const created = await generateTicketsForRegistration(registration.id); - if (created.length > 0) { - const mockReq = { user: { id: registration.userId }, body: { ticketIds: created.map(t => t.id) } }; - const mockRes = { status: () => mockRes, json: () => {} }; - emailTickets(mockReq, mockRes).catch(e => console.error('[attendees] Failed to send new tickets:', e?.message || e)); - } - } - - const updated = await prisma.registration.findUnique({ - where: { id: registration.id }, - select: { id: true, ticketDelivery: true, attendees: ATTENDEES_INCLUDE }, - }); - res.json({ ...updated, attendees: updated.attendees.map(({ userId, ...a }) => a) }); - } catch (error) { - res.status(error.statusCode || (res.statusCode === 200 ? 400 : res.statusCode)).json({ message: error.message }); - } -}; - -// @desc Send an attendee a link to fill in their own attendee form -// @route POST /api/registrations/:id/attendees/:attendeeId/send-form-link -// @access Private (owner or staff) -const sendAttendeeFormLink = async (req, res) => { - try { - const attendee = await prisma.attendee.findFirst({ - where: { id: req.params.attendeeId, registrationId: req.params.id }, - include: { registration: { include: { event: true, user: { select: { id: true, name: true } } } } }, - }); - if (!attendee) { res.status(404); throw new Error('Attendee not found'); } - if (!isOwnerOrStaff(attendee.registration, req.user)) { res.status(403); throw new Error('Not authorized'); } - if (!attendee.email && !attendee.phone) { res.status(400); throw new Error(`Add an email or phone number for ${attendee.name} first.`); } - - const { sendAttendeeFormLinkMessage } = require('../utils/notifications'); - const sent = await sendAttendeeFormLinkMessage(attendee); - res.json({ message: sent.length ? `Form link sent to ${attendee.name} by ${sent.join(' and ')}.` : 'The form link could not be sent.' }); - } catch (error) { - res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: error.message }); + if (!error.statusCode) console.error(error); + res.status(v1StatusOf(error, 400)).json({ message: error.message }); } }; module.exports = { - updateAttendees, - sendAttendeeFormLink, - applyCoupon, - removeCoupon, createRegistration, - getRegistrations, - getUserRegistrations, - getRegistrationById, - updateRegistrationStatus, cancelRegistration, - getRegistrationsByEvent, - createManualRegistration, - updateRegistrationOptions, - submitFormResponses, - replaceFormResponses, - getFormDraft, - saveFormDraft, - sendInvoice, -}; \ No newline at end of file + getRegistrations: handler(admin.getRegistrations), + getUserRegistrations: handler(admin.getUserRegistrations), + getRegistrationById: handler(admin.getRegistrationById), + updateRegistrationStatus: handler(admin.updateRegistrationStatus), + getRegistrationsByEvent: handler(admin.getRegistrationsByEvent), + createManualRegistration: handler(admin.createManualRegistration, () => 201), + updateRegistrationOptions: handler(admin.updateRegistrationOptions), + // "No form for this event" was a 200; responses saved are a 201. + submitFormResponses: handler(admin.submitFormResponses, out => (out && out.count !== undefined ? 201 : 200)), + replaceFormResponses: handler(admin.replaceFormResponses), + getFormDraft: handler(admin.getFormDraft), + saveFormDraft: handler(admin.saveFormDraft), + sendInvoice: handler(admin.sendInvoice), + applyCoupon: handler(admin.applyCoupon), + removeCoupon: handler(admin.removeCoupon), + updateAttendees: handler(admin.updateAttendees), + sendAttendeeFormLink: handler(admin.sendAttendeeFormLink), +}; diff --git a/apps/events/backend/src/services/registrationAdmin.ts b/apps/events/backend/src/services/registrationAdmin.ts new file mode 100644 index 0000000..117f6d7 --- /dev/null +++ b/apps/events/backend/src/services/registrationAdmin.ts @@ -0,0 +1,1716 @@ +/** + * Registrations as staff and owners manage them after they're made (1.51.10): the staff lists, + * status changes, registering someone at the door, changing items, coupons, named attendees and + * attendee forms. Moved from registrationController.js so v1 and /api/v2 run the same code. + * + * Each function takes a `Call` (who is asking, the path parameters, body and query) and returns + * what v1 answered. Errors are ServiceErrors with their HTTP status; anything else a helper + * throws (it was a 400 on v1) becomes a 400 too, except programming errors. + */ +import { v4 as uuidv4 } from 'uuid'; +import { prisma as typedPrisma } from '../v2/legacy'; +import { fail, ServiceError } from './errors'; +import { + queueConsentRequests, ATTENDEES_INCLUDE, TICKET_DELIVERY, placesAfter, ACTIVE_COUPONS_INCLUDE, + pendingCouponLines, priceRequestedOption, checkOptionStock, checkVariantStock, isStaffRole, +} from './registrations'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- moved from JavaScript; the records are Prisma's with includes */ +// The queries below build their includes and data step by step, as the JavaScript did. +const prisma = typedPrisma as any; +const { generateTicketsForRegistration } = require('../utils/ticketUtils') as { generateTicketsForRegistration(id: string): Promise }; +const { emailTickets } = require('../controllers/ticketController') as { emailTickets(req: any, res: any): Promise }; +const { hashPassword } = require('../config/auth') as { hashPassword(p: string): Promise }; +const { computeRegistrationTotalDue, refreshPricingForRegistration, attachComputedTotals, attachComputedTotalsToList } = require('../utils/pricing') as { + computeRegistrationTotalDue(registration: any, at: Date): number; + refreshPricingForRegistration(id: string): Promise; + attachComputedTotals(registration: any): any; + attachComputedTotalsToList(registrations: any[]): any[]; +}; +const { assertEventOpen } = require('../utils/cashupUtils') as { assertEventOpen(eventId: string): Promise }; +const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise }; +const { previewCoupon, applyCouponToRegistration, recalculateRegistrationDiscount, releaseRegistrationCoupons, describeCoupon } = require('../utils/coupons') as { + previewCoupon(args: object): Promise; + applyCouponToRegistration(args: object): Promise; + recalculateRegistrationDiscount(registrationId: string, tx?: unknown): Promise; + releaseRegistrationCoupons(registrationId: string): Promise; + describeCoupon(coupon: any): string; +}; +const { validateAttendees, createAttendees, namedPlacesByKey } = require('../utils/attendees') as { + validateAttendees(event: any, places: Record, attendees: unknown, existing?: Record): any[]; + createAttendees(registrationId: string, attendees: any[], tx?: unknown): Promise; + namedPlacesByKey(registrationId: string): Promise>; +}; +const { findAccountByContact } = require('../utils/accountMatch') as { findAccountByContact(c: { email?: string; phone?: string }, tx?: unknown): Promise }; +const { queueWaitlist } = require('../utils/waitlist') as { 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 { expandPickLines, assertSessionCapacity, isPickOption, mergeSessionIds } = require('../utils/sessions') as { + expandPickLines(event: any, options: any[], opts: object): any[]; + assertSessionCapacity(event: any, lines: any[]): Promise; + isPickOption(event: any, option: any): boolean; + mergeSessionIds(a: string[] | null | undefined, b: string[] | null | undefined): string[]; +}; + +export type Call = { + /** Who is asking (null for a guest on the routes that allow one). */ + actor: any; + params: Record; + body: any; + query: Record; + /** The campus filter for staff lists (utils/campusScope listWhere(req, 'event')). */ + listWhere?: () => Promise; + /** Read-only sessions (impersonation, a lapsed licence) don't refresh prices on reads. */ + readOnly?: boolean; + ip?: string; +}; + +/** A v1 request as a Call. */ +export const callOf = (req: any): Call => { + const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: unknown): string }; + const { listWhere } = require('../utils/campusScope') as { listWhere(req: unknown, path: string): Promise }; + return { actor: req.user || null, params: req.params || {}, body: req.body || {}, query: req.query || {}, readOnly: !!req.readOnly, ip: getClientIp(req), listWhere: () => listWhere(req, 'event') }; +}; + +const as400 = (fn: (...args: A) => Promise) => async (...args: A): Promise => { + try { + return await fn(...args); + } catch (e: any) { + if (e instanceof ServiceError || e?.statusCode || (typeof e?.code === 'string' && /^P\d{4}$/.test(e.code))) throw e; + if (e instanceof TypeError || e instanceof ReferenceError) throw e; + throw new ServiceError(400, e?.message || 'Request failed.'); + } +}; + +// Never unscoped by accident: a caller that can list must say how. +const campusWhere = (call: Call): Promise => (call.listWhere ? call.listWhere() : Promise.reject(new ServiceError(500, 'No campus scope for this list.'))); + +async function eventOpen(eventId: string) { + try { + await assertEventOpen(eventId); + } catch (e: any) { + throw new ServiceError(e.message === 'Event not found' ? 404 : 400, e.message); + } +} + +/** + * After a discount changes, bring the status in line with the new total. A registration + * that a coupon has made fully paid gets its tickets, as any paid registration does. + */ +async function syncStatusAfterDiscount(registrationId: string) { + const reg = await prisma.registration.findUnique({ + where: { id: registrationId }, + include: { registrationOptions: { include: { eventOption: true, tranches: true } }, payments: true }, + }); + const due = computeRegistrationTotalDue(reg, new Date()); + const paid = (reg.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0); + const status = paid >= due - 0.001 ? 'paid' : paid > 0 ? 'partial_paid' : 'pending'; + if (status !== reg.status) { + await prisma.registration.update({ where: { id: registrationId }, data: { status, updatedAt: new Date() } }); + } + if (status === 'paid' && reg.status !== 'paid') { + (async () => { + try { + let hasRequiredForm = false; + try { + const form = await prisma.eventForm.findUnique({ where: { eventId: reg.eventId } }); + hasRequiredForm = !!(form && form.isRequired); + } catch {} + if (hasRequiredForm) return; + await generateTicketsForRegistration(registrationId); + const mockReq = { user: { id: reg.userId }, body: { registrationId } }; + const mockRes = { status: () => mockRes, json: () => {} }; + await emailTickets(mockReq, mockRes); + } catch (e: any) { + console.error('[coupon] Failed to issue tickets after discount:', e?.message || e); + } + })(); + } + return status; +} + +const isOwnerOrStaff = (registration: any, user: any) => + registration.userId === user.id || ['admin', 'supervisor', 'staff'].includes(user.role); + +// @desc Get all registrations +// @route GET /api/registrations +// @access Private/Admin +export const getRegistrations = as400(async (call: Call): Promise => { + const include = { + couponRedemptions: ACTIVE_COUPONS_INCLUDE, + + bundleApplications: BUNDLE_APPS_INCLUDE, + attendees: ATTENDEES_INCLUDE, + payments: { include: { recordedBy: { select: { id: true, name: true, email: true } } } }, + registrationOptions: { + include: { + eventOption: { include: { earlyBirdTiers: true } }, + variant: { select: { id: true, name: true, price: true } }, + tranches: true, + } + }, + event: true, + user: { + select: { + id: true, + name: true, + email: true, + phoneNumber: true + } + } + }; + + // Pagination is opt-in via ?page/?limit to keep existing callers (which expect a plain + // array of every registration) working unchanged; callers that pass either param get back + // the { data, total, page, limit, pages } shape used by /api/payments and /api/users. + // Campus-scoped staff: registrations for events they can see. + const scopeWhere = await campusWhere(call); + // Narrowing filters, so callers needn't download every registration ever made: + // ?unpaid=1 — still owing (not paid or cancelled); ?userId= — one person's. + const filters: any[] = []; + if (['1', 'true'].includes(String(call.query.unpaid || ''))) filters.push({ status: { in: ['pending', 'confirmed', 'partial_paid'] } }); + if (call.query.userId) filters.push({ userId: String(call.query.userId) }); + const where = filters.length ? { AND: [scopeWhere, ...filters] } : scopeWhere; + if (typeof call.query.page === 'undefined' && typeof call.query.limit === 'undefined') { + const registrations = await prisma.registration.findMany({ where, include }); + return attachComputedTotalsToList(registrations); + } + + const page = Math.max(1, parseInt(call.query.page) || 1); + const limit = Math.min(200, Math.max(1, parseInt(call.query.limit) || 100)); + const skip = (page - 1) * limit; + + const [registrations, total] = await prisma.$transaction([ + prisma.registration.findMany({ where, include, orderBy: { createdAt: 'desc' }, skip, take: limit }), + prisma.registration.count({ where }) + ]); + + return { data: attachComputedTotalsToList(registrations), total, page, limit, pages: Math.ceil(total / limit) }; +}); + +// @desc Get user registrations +// @route GET /api/registrations/myregistrations +// @access Private +export const getUserRegistrations = as400(async (call: Call): Promise => { + const showPast = String(call.query.showPast || '').toLowerCase() === '1' || String(call.query.showPast || '').toLowerCase() === 'true'; + const now = new Date(); + const whereClause = showPast ? { userId: call.actor.id } : { + userId: call.actor.id, + status: { not: 'cancelled' }, + event: { endDate: { gte: now }, cashupStatus: { not: 'closed' } } + }; + + // Keep pending/partial-paid registrations' prices current before serving them — an + // early-bird tier can expire while items sit unpaid in someone's registration, and + // without this the dashboard would keep showing a price that was never actually locked + // in by a payment, indefinitely, until the user happens to attempt a payment. + const staleCandidates = await prisma.registration.findMany({ + where: { ...whereClause, status: { in: ['pending', 'partial_paid'] } }, + select: { id: true } + }); + if (staleCandidates.length > 0 && !call.readOnly) { + await Promise.all(staleCandidates.map((r: any) => refreshPricingForRegistration(r.id).catch(() => {}))); + } + + const registrations = await prisma.registration.findMany({ + where: whereClause, + include: { + registrationOptions: { + include: { + eventOption: { include: { earlyBirdTiers: true } }, + variant: { select: { id: true, name: true, price: true } }, + tranches: true, + } + }, + couponRedemptions: ACTIVE_COUPONS_INCLUDE, + + bundleApplications: BUNDLE_APPS_INCLUDE, + attendees: ATTENDEES_INCLUDE, + formResponses: { select: { id: true, attendeeId: true } }, + // Nest the event's form so the frontend can tell whether attendee forms are + // required without a separate GET /api/events/:id per registration. + event: { include: { form: { include: { fields: true } } } }, + user: { + select: { + id: true, + name: true, + email: true, + phoneNumber: true + } + }, + payments: true, + }, + orderBy: { createdAt: 'desc' } + }); + + return attachComputedTotalsToList(registrations); +}); + +// @desc Get registration by ID +// @route GET /api/registrations/:id +// @access Private +export const getRegistrationById = as400(async (call: Call): Promise => { + const include = { + registrationOptions: { + include: { + eventOption: { include: { earlyBirdTiers: true } }, + variant: { select: { id: true, name: true, price: true } }, + tickets: true, + tranches: true + } + }, + event: true, + user: { + select: { + id: true, + name: true, + email: true, + phoneNumber: true + } + }, + payments: { include: { recordedBy: { select: { id: true, name: true, email: true } } } }, + formResponses: { include: { answers: true } }, + couponRedemptions: ACTIVE_COUPONS_INCLUDE, + + bundleApplications: BUNDLE_APPS_INCLUDE, + attendees: ATTENDEES_INCLUDE, + }; + + let registration = await prisma.registration.findUnique({ where: { id: call.params.id }, include }); + + if (!registration) { + return fail(404, 'Registration not found'); + } + + // See getUserRegistrations — keep an unpaid/partially-paid registration's price current + // whenever it's viewed, not just at payment time. + if ((registration.status === 'pending' || registration.status === 'partial_paid') && !call.readOnly) { + await refreshPricingForRegistration(registration.id).catch(() => {}); + registration = await prisma.registration.findUnique({ where: { id: call.params.id }, include }); + } + + // Guests (no auth) can view by knowing the registrationId (UUID = unguessable) + // Authenticated users must be the owner, staff+, or a named attendee on it + const isOwnerOrStaffViewer = call.actor && (registration.userId === call.actor.id || ['admin', 'supervisor', 'staff'].includes(call.actor.role)); + const isAttendeeViewer = call.actor && (registration.attendees || []).some((a: any) => a.userId === call.actor.id); + if (call.actor && !isOwnerOrStaffViewer && !isAttendeeViewer) { + return fail(403, 'Not authorized to view this registration'); + } + // Only the payer and staff see attendees' contact details. + if (!isOwnerOrStaffViewer) { + registration.attendees = (registration.attendees || []).map((a: any) => ({ ...a, email: null, phone: null })); + } + + return attachComputedTotals(registration); +}); + +// @desc Update registration status +// @route PUT /api/registrations/:id +// @access Private/Admin +export const updateRegistrationStatus = as400(async (call: Call): Promise => { + const { status } = call.body; + + const registration = await prisma.registration.findUnique({ + where: { id: call.params.id } + }); + + if (!registration) { + return fail(404, 'Registration not found'); + } + + await eventOpen(registration.eventId); + + // If downgrading from paid to not-paid, ensure no tickets were used and delete unused tickets + if (registration.status === 'paid' && status !== 'paid') { + const tickets = await prisma.ticket.findMany({ + where: { registrationOption: { registrationId: call.params.id } }, + include: { usages: true } + }); + const hasUsed = tickets.some((t: any) => t.isUsed || (t.usages && t.usages.length > 0)); + if (hasUsed) { + return fail(400, 'Cannot change registration from paid because one or more tickets have been used'); + } + // Delete all unused tickets + await prisma.ticket.deleteMany({ + where: { + registrationOption: { registrationId: call.params.id }, + isUsed: false + } + }); + } + + const updatedRegistration = await prisma.registration.update({ + where: { id: call.params.id }, + data: { + status, + updatedAt: new Date() + }, + include: { + registrationOptions: { + include: { + eventOption: true + } + }, + event: true, + user: { + select: { + id: true, + name: true, + email: true, + phoneNumber: true + } + } + } + }); + + // This is the staff-only status-change endpoint (separate from the owner-facing + // DELETE /:id cancel route), so any transition into 'cancelled' here is always a + // staff-initiated cancellation — log it the same way DELETE /:id does, so both + // paths land under the one 'registration_cancelled' filter in the audit log. + if (status === 'cancelled' && registration.status !== 'cancelled') { + await releaseRegistrationCoupons(call.params.id); + queueWaitlist(registration.eventId); + logAdminAction({ + actorId: call.actor.id, + actorRole: call.actor.role, + action: 'registration_cancelled', + targetType: 'Registration', + targetId: call.params.id, + metadata: { registrationOwnerId: registration.userId, previousStatus: registration.status }, + ip: call.ip, + }); + } + + // Generate tickets and email them when status is manually set to 'paid' by staff + if (status === 'paid') { + (async () => { + try { + await generateTicketsForRegistration(call.params.id); + const mockReq = { user: { id: updatedRegistration.userId }, body: { registrationId: call.params.id } }; + const mockRes = { status: () => mockRes, json: () => {} }; + await emailTickets(mockReq, mockRes); + } catch (e: any) { + console.error('[updateRegistrationStatus] Failed to generate/email tickets:', e?.message || e); + } + })(); + } + + return updatedRegistration; +}); + +// @desc Get registrations by event +// @route GET /api/registrations/event/:eventId +// @access Private/Admin +export const getRegistrationsByEvent = as400(async (call: Call): Promise => { + const { search } = call.query; + + // See getUserRegistrations — keep pending/partial-paid registrations' prices current + // before serving them, rather than only at payment time. + const staleCandidates = await prisma.registration.findMany({ + where: { eventId: call.params.eventId, status: { in: ['pending', 'partial_paid'] } }, + select: { id: true } + }); + if (staleCandidates.length > 0 && !call.readOnly) { + await Promise.all(staleCandidates.map((r: any) => refreshPricingForRegistration(r.id).catch(() => {}))); + } + + let registrations = await prisma.registration.findMany({ + where: { eventId: call.params.eventId }, + include: { + registrationOptions: { + include: { + eventOption: { include: { earlyBirdTiers: true } }, + variant: { select: { id: true, name: true, price: true } }, + tickets: true, + tranches: true, + } + }, + payments: { include: { recordedBy: { select: { id: true, name: true, email: true } } } }, + user: { select: { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true, isActive: true } }, + couponRedemptions: ACTIVE_COUPONS_INCLUDE, + + bundleApplications: BUNDLE_APPS_INCLUDE, + attendees: ATTENDEES_INCLUDE, + }, + orderBy: { createdAt: 'asc' } + }); + + if (search) { + const q = String(search).toLowerCase(); + registrations = registrations.filter((r: any) => + String(r.user?.name || '').toLowerCase().includes(q) || + String(r.user?.email || '').toLowerCase().includes(q) || + String(r.user?.phoneNumber || '').toLowerCase().includes(q) + ); + } + + return attachComputedTotalsToList(registrations); +}); + +// @desc Create a new registration for non existing user +// @route POST /api/registrations/manual +// @access Private/Supervisor +export const createManualRegistration = as400(async (call: Call): Promise => { + const { eventId, options, user, notificationPreference: prefFromBody, skipActivationNotice, couponCode, attendees, ticketDelivery } = call.body; + + if (!eventId || !options || !user || !user.name || (!user.email && !user.phoneNumber)) { + return fail(400, 'Missing required fields: eventId, options, user.name, and at least user.email or user.phoneNumber'); + } + + //Check event + 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'); + } + + await eventOpen(eventId); + + // Validate options + if (!Array.isArray(options) || options.length === 0) { + return fail(400, 'At least one option must be selected'); + } + + // Picked sessions become one line each; staff can still book a session until it ends. + const lines = expandPickLines(event, options, { staff: true }); + await assertSessionCapacity(event, lines); + + // Validate each option up front, before any account is created or changed — + // including stock, which staff registrations previously skipped. + for (const option of lines) { + const eventOption = event.eventOptions.find((eo: any) => eo.id === option.eventOptionId); + if (!eventOption) { + return fail(400, `Option with ID ${option.eventOptionId} not found for this event`); + } + if (!option.quantity || option.quantity < 1) { + return fail(400, 'Quantity must be at least 1'); + } + const variant = option.variantId ? (eventOption.variants || []).find((v: any) => v.id === option.variantId) : null; + const oStock = await checkOptionStock(eventOption, option.quantity, null, option.sessionId); + const vStock = variant ? await checkVariantStock(variant, option.quantity, null, option.sessionId) : { available: true, remaining: null }; + if (!oStock.available || !vStock.available) { + const left = Math.max(0, Math.min(oStock.remaining ?? Infinity, vStock.remaining ?? Infinity)); + fail(400, `"${eventOption.name}${variant ? ` (${variant.name})` : ''}" is sold out or does not have enough stock (${left} remaining). Raise the stock limit to add more.`); + } + } + + // Pricing (appliedTierId + priceSnapshot) depends on who the attendee is — Staff and + // above get the staff price — so it runs once the account is resolved below. + const priceManualOptions = (attendee: any) => Promise.all(lines.map(async (option: any) => { + const eventOption = event.eventOptions.find((eo: any) => eo.id === option.eventOptionId); + const variantId = option.variantId || null; + const priced = await priceRequestedOption(eventOption, variantId, option.quantity, attendee); + return { ...option, variantId, ...priced }; + })); + + // Resolve or create a user + let userId: any; + + const { normalizeZAPhone } = require('../utils/whatsapp'); + const phone = normalizeZAPhone(user.phoneNumber) || (user.phoneNumber || '').replace(/\D/g, ''); + const hasValidEmail = !!(user.email && typeof user.email === 'string' && user.email.includes('@')); + + // Derive notification preference: explicit choice wins; otherwise infer from available contact info + const validPrefs = ['email', 'whatsapp', 'both']; + const derivedPref = (prefFromBody && validPrefs.includes(prefFromBody)) + ? prefFromBody + : (hasValidEmail && phone ? 'both' : phone ? 'whatsapp' : 'email'); + + // Always search by email AND/OR phone. + // Resolve each channel independently (rather than a single findFirst with an OR + // across both) so that an email belonging to one account and a phone number + // belonging to a *different* account can never be silently collapsed into + // whichever record happens to match first — that would let a registration + // hijack or corrupt someone else's account. Also try the alternate phone + // format (27xxx ↔ 0xxx) so both representations match. + const phoneAlt = phone && phone.startsWith('27') ? '0' + phone.slice(2) : (phone && phone.length === 9 ? '27' + phone : null); + const emailUser = hasValidEmail + ? await prisma.user.findUnique({ where: { email: user.email } }) + : null; + const phoneUser = phone + ? await prisma.user.findFirst({ where: { OR: [{ phoneNumber: phone }, ...(phoneAlt ? [{ phoneNumber: phoneAlt }] : [])] } }) + : null; + + if (emailUser && phoneUser && emailUser.id !== phoneUser.id) { + return fail(409, + `This email and phone number belong to two different existing accounts (${emailUser.name} vs ${phoneUser.name}). Please verify the visitor's details before registering.` + ); + } + + const existingUser = emailUser || phoneUser || null; + + if (existingUser) { + userId = existingUser.id; + const updateData: any = {}; + // The kiosk shows the operator a diff of name/email/phone against the matched + // account and requires explicit confirmation before submitting, so any + // difference reaching this point is an already-confirmed correction — apply + // it as a full overwrite rather than only filling in blanks. + if (user.name && user.name.trim() && user.name.trim() !== existingUser.name) { + updateData.name = user.name.trim(); + } + if (phone && phone !== existingUser.phoneNumber) { + updateData.phoneNumber = phone; + } + if (hasValidEmail && existingUser.email !== user.email) { + updateData.email = user.email; + } + + // Update preference only when the caller explicitly specified one, but validate it + // against the contact info that will actually be on the account after this update — + // a stale "whatsapp"/"both" preference must not survive a phone number being + // removed, nor "email" survive an email being cleared in favor of a real phone. + if (prefFromBody && validPrefs.includes(prefFromBody)) { + const { isValidZAPhone } = require('../utils/whatsapp'); + const finalPhone = updateData.phoneNumber !== undefined ? updateData.phoneNumber : existingUser.phoneNumber; + const finalEmail = updateData.email !== undefined ? updateData.email : existingUser.email; + const finalEmailValid = !!(finalEmail && !finalEmail.endsWith('@guest.local')); + let candidatePref = prefFromBody; + if ((candidatePref === 'whatsapp' || candidatePref === 'both') && !isValidZAPhone(finalPhone)) { + candidatePref = finalEmailValid ? 'email' : candidatePref; + } + if (candidatePref === 'email' && !finalEmailValid && isValidZAPhone(finalPhone)) { + candidatePref = 'whatsapp'; + } + updateData.notificationPreference = candidatePref; + } + + if (Object.keys(updateData).length > 0) { + await prisma.user.update({ where: { id: userId }, data: updateData }).catch(() => {}); + } + } else { + const suppliedPassword = typeof user.password === 'string' && user.password.trim().length >= 6 + ? user.password.trim() + : null; + + if (hasValidEmail && suppliedPassword) { + // Caller supplied their own password (the self-service kiosk, where the + // visitor sets it themselves on the spot) — activate immediately, since + // there's nothing left for them to do via an activation link. + const hashed = await hashPassword(suppliedPassword); + const created = await prisma.user.create({ + data: { + id: uuidv4(), + name: user.name, + email: user.email, + password: hashed, + phoneNumber: phone || null, + isActive: true, + notificationPreference: derivedPref, + updatedAt: new Date(), + } + }); + userId = created.id; + } else { + // New account: uses the real email if a valid one was given, otherwise a + // guest.local placeholder (phone-only registration). Always created inactive + // with a random password — the visitor activates it themselves via the link + // sent immediately below (email or WhatsApp), unless the caller explicitly + // opted out of that nudge (e.g. a self-service visitor who declined to + // create an account at all). + const placeholderEmail = hasValidEmail + ? user.email + : `guest+${uuidv4().slice(0, 8)}@guest.local`; + const hashed = await hashPassword(uuidv4()); + const created = await prisma.user.create({ + data: { + id: uuidv4(), + name: user.name, + email: placeholderEmail, + password: hashed, + phoneNumber: phone || null, + isActive: false, + notificationPreference: derivedPref, + updatedAt: new Date(), + } + }); + userId = created.id; + if (!skipActivationNotice) { + const { sendActivationLink } = require('./userController'); + sendActivationLink(created); + } + } + } + + let couponError: any = null; + const attendee = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, role: true, email: true } }); + const resolvedManualOptions = await priceManualOptions(attendee); + + // Check the coupon against this attendee before saving anything. + if (couponCode) { + await previewCoupon({ code: couponCode, eventId, user: attendee, lines: pendingCouponLines(event, resolvedManualOptions) }); + } + + // Merge into existing non-cancelled registration if one exists, otherwise create new + const existingReg = await prisma.registration.findFirst({ + where: { userId, eventId, status: { not: 'cancelled' } }, + include: { registrationOptions: true } + }); + + const cleanAttendees = validateAttendees( + event, + placesAfter(existingReg?.registrationOptions, resolvedManualOptions), + attendees, + existingReg ? await namedPlacesByKey(existingReg.id) : {} + ); + if (ticketDelivery !== undefined && !TICKET_DELIVERY.includes(ticketDelivery)) { + return fail(400, "ticketDelivery must be 'payer' or 'each'"); + } + + let registration: any; + let isNewRegistration = false; + + if (existingReg) { + // Add a new price tranche per requested option into the existing registration (all in + // parallel) — never overwrite an existing row's priceSnapshot/quantity in place, or + // tickets bought at different early-bird prices would blend into a single wrong price. + await Promise.all(resolvedManualOptions.map((opt: any) => { + const existing = existingReg.registrationOptions.find( + (ro: any) => ro.eventOptionId === opt.eventOptionId && (ro.variantId || null) === (opt.variantId || null) && (ro.sessionId || null) === (opt.sessionId || null) + ); + if (existing) { + return 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, + // More of an all-sessions ticket: it covers the sessions of both bookings. + ...(existing.sessionId ? {} : { sessionIds: mergeSessionIds(existing.sessionIds, opt.sessionIds) }), + } + }) + ]); + } + return 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, + }] + } + } + }); + })); + // Re-work any coupon over the merged items, and apply a new one, before the status + // is worked out from the totals. + await recalculateRegistrationDiscount(existingReg.id); + if (couponCode) { + try { + await applyCouponToRegistration({ registrationId: existingReg.id, code: couponCode, appliedById: call.actor.id }); + } catch (e: any) { + if (!e.isCouponError) throw e; + couponError = e.message; + } + } + + // Recompute status based on totals across ALL current options and payments + const freshForStatus = await prisma.registration.findUnique({ + where: { id: existingReg.id }, + include: { + registrationOptions: { include: { eventOption: { include: { earlyBirdTiers: true } }, tranches: true } }, + payments: true, + } + }); + const freshTotalDue = computeRegistrationTotalDue(freshForStatus, new Date()); + const freshTotalPaid = (freshForStatus?.payments || []).reduce((sum: any, p: any) => sum + (p.amount || 0), 0); + let newExistingStatus: any; + if (freshTotalDue === 0 || freshTotalPaid >= freshTotalDue) newExistingStatus = 'paid'; + else if (freshTotalPaid > 0) newExistingStatus = 'partial_paid'; + else newExistingStatus = existingReg.status === 'cancelled' ? 'pending' : (existingReg.status || 'pending'); + await prisma.registration.update({ where: { id: existingReg.id }, data: { status: newExistingStatus, updatedAt: new Date() } }); + + registration = await prisma.registration.findUnique({ + where: { id: existingReg.id }, + include: { + registrationOptions: { include: { eventOption: true, tranches: true } }, + event: true, + user: { select: { id: true, name: true, email: true, phoneNumber: true } }, + couponRedemptions: ACTIVE_COUPONS_INCLUDE, + + bundleApplications: BUNDLE_APPS_INCLUDE, + }, + }); + registration.status = newExistingStatus; + } else { + isNewRegistration = true; + const registrationId = uuidv4(); + registration = await prisma.registration.create({ + data: { + id: registrationId, + userId, + eventId, + updatedAt: new Date(), + registrationOptions: { + create: resolvedManualOptions.map((option: any) => ({ + 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, + }] + } + })), + }, + }, + include: { + registrationOptions: { include: { eventOption: true, tranches: true } }, + event: true, + user: { select: { id: true, name: true, email: true, phoneNumber: true } }, + }, + }); + const hasDiscount = (await recalculateRegistrationDiscount(registration.id)) > 0; + if (couponCode) { + try { + await applyCouponToRegistration({ registrationId: registration.id, code: couponCode, appliedById: call.actor.id }); + } catch (e: any) { + if (!e.isCouponError) throw e; + couponError = e.message; + } + } + if (couponCode || hasDiscount) { + registration = await prisma.registration.findUnique({ + where: { id: registration.id }, + include: { + registrationOptions: { include: { eventOption: true, tranches: true } }, + event: true, + user: { select: { id: true, name: true, email: true, phoneNumber: true } }, + couponRedemptions: ACTIVE_COUPONS_INCLUDE, + + bundleApplications: BUNDLE_APPS_INCLUDE, + }, + }); + } + } + + const registrationId = registration.id; + + if (cleanAttendees.length > 0) { + await createAttendees(registrationId, cleanAttendees); + queueConsentRequests(registrationId); + } + if (ticketDelivery) await prisma.registration.update({ where: { id: registrationId }, data: { ticketDelivery } }); + + if (couponCode && !couponError) { + logAdminAction({ + actorId: call.actor.id, + actorRole: call.actor.role, + action: 'coupon_applied_manual', + targetType: 'Registration', + targetId: registrationId, + metadata: { code: String(couponCode).trim().toUpperCase(), discount: registration.discountTotal, forUserId: userId }, + ip: call.ip, + }); + } + + // Auto mark paid and generate tickets if free and no required form (new registrations only) + let hasRequiredForm = false; + try { + const form = await prisma.eventForm.findUnique({ where: { eventId: registration.eventId } }); + hasRequiredForm = !!(form && form.isRequired); + } catch {} + + // Auto-mark paid and generate tickets for free registrations (new OR existing that became free) + if (registration.status !== 'paid') try { + const totalDue = computeRegistrationTotalDue(registration, new Date()); + if (totalDue === 0) { + await prisma.registration.update({ where: { id: registration.id }, data: { status: 'paid', updatedAt: new Date() } }); + registration.status = 'paid'; + } + } catch {} + + // Generate/sync tickets for all paid registrations that have no required form + if (registration.status === 'paid' && !hasRequiredForm) try { + await generateTicketsForRegistration(registration.id); + } catch {} + + // For paid registrations, generate a checkout link to include in the email + let yocoPaymentUrl: any = null; + if (registration.status !== 'paid') { + try { + const { createRegistrationCheckout } = require('../payments/checkouts'); + const baseUrl = process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001'; + const checkout = await createRegistrationCheckout(registrationId, userId, { + successUrl: `${baseUrl}/payment/success`, + cancelUrl: `${baseUrl}/payment/cancel`, + failureUrl: `${baseUrl}/payment/failure`, + }); + yocoPaymentUrl = checkout.redirectUrl || null; + } catch (e: any) { + console.warn('Could not create a checkout for the self-service email:', e?.message || e); + } + } + + // Fire-and-forget: registration email first, then tickets (guarantees order) + const { sendSelfServiceRegistrationEmails, sendRegistrationUpdatedEmails } = require('../utils/notifications'); + const _ssRegId = registrationId; + const _ssUserId = userId; + const _ssPaymentUrl = yocoPaymentUrl; + const _ssFormRequired = hasRequiredForm; + const _ssIsNew = isNewRegistration; + const _ssNotifPref = derivedPref; + const _ssShouldEmailTickets = registration.status === 'paid' && !hasRequiredForm; + (async () => { + try { + if (_ssIsNew) { + await sendSelfServiceRegistrationEmails(_ssRegId, { paymentUrl: _ssPaymentUrl, formRequired: _ssFormRequired }); + } else { + await sendRegistrationUpdatedEmails(_ssRegId); + } + } catch (e: any) { console.error('Failed to send registration email:', e); } + if (_ssShouldEmailTickets) { + const mockReq = { user: { id: _ssUserId }, body: { registrationId: _ssRegId, channel: _ssNotifPref } }; + const mockRes = { status: () => mockRes, json: () => {} }; + try { await emailTickets(mockReq, mockRes); } catch (e: any) { console.error('Failed to email tickets after free self-service registration:', e); } + } + })(); + + logAdminAction({ + actorId: call.actor.id, + actorRole: call.actor.role, + action: 'registration_created_manual', + targetType: 'Registration', + targetId: registrationId, + metadata: { eventId: registration.eventId, forUserId: userId }, + ip: call.ip, + }); + + return { ...attachComputedTotals(registration), ...(couponError ? { couponError } : {}) }; +}); + +// @desc Update registration options (add/remove items) with constraints +// @route PUT /api/registrations/:id/options +// @access Private (owner or staff/admin) +export const updateRegistrationOptions = as400(async (call: Call): Promise => { + const registrationId = call.params.id; + const userId = call.actor.id; + const { options } = call.body; // [{ eventOptionId, quantity }] + + if (!Array.isArray(options)) { + return fail(400, 'Options must be an array'); + } + + // Load registration with relations + const registration = await prisma.registration.findUnique({ + where: { id: registrationId }, + include: { + registrationOptions: { + include: { + tickets: true, + tranches: true, + eventOption: { include: { earlyBirdTiers: true, variants: true } } + } + }, + event: { include: { eventOptions: { include: { earlyBirdTiers: true, variants: true } } } }, + payments: true, + user: { select: { id: true, role: true, email: true } }, + } + }); + + if (!registration) { + return fail(404, 'Registration not found'); + } + + // Authorization: owner or admin/supervisor/staff + if ( + registration.userId !== userId && + call.actor.role !== 'admin' && + call.actor.role !== 'supervisor' && + call.actor.role !== 'staff' + ) { + return fail(403, 'Not authorized to edit this registration'); + } + + // If event is in the past, block edit + if (registration.event?.endDate && new Date(registration.event.endDate).getTime() < Date.now()) { + return fail(400, 'This event has already ended; registration cannot be edited'); + } + + // registration.event is already loaded above, so check cashupStatus directly here + // rather than re-fetching via assertEventOpen. + if (registration.event?.cashupStatus === 'closed') { + return fail(400, 'This event is closed. Reopen it (admin only) before making changes.'); + } + + // Validate provided options: must belong to same event and quantities >=1 + if (options.length === 0) { + return fail(400, 'At least one option must be provided'); + } + + const validOptionIds = new Set((registration.event?.eventOptions || []).map((eo: any) => eo.id)); + const pickOptionIds = new Set((registration.event?.eventOptions || []).filter((eo: any) => isPickOption(registration.event, eo)).map((eo: any) => eo.id)); + for (const opt of options) { + if (!opt || !opt.eventOptionId || !Number.isInteger(opt.quantity) || opt.quantity < 1) { + return fail(400, 'Each option must include a valid eventOptionId and quantity >= 1'); + } + if (!validOptionIds.has(opt.eventOptionId)) { + return fail(400, 'One or more options do not belong to this event'); + } + if (pickOptionIds.has(opt.eventOptionId)) { + return fail(400, "Sessions are booked by registering for them — they can't be changed here."); + } + } + // The kids check-in and volunteer tickets are handed out by staff: the owner can keep (or + // lower) the places they were given, not add more. + if (!isStaffRole(call.actor.role)) { + for (const id of reservedOptionIds(registration.event)) { + const had = registration.registrationOptions.filter((ro: any) => ro.eventOptionId === id).reduce((n: any, ro: any) => n + (ro.quantity || 0), 0); + const asked = options.filter((o: any) => o.eventOptionId === id).reduce((n: any, o: any) => n + o.quantity, 0); + if (asked > had) { + return fail(400, 'One or more options do not belong to this event'); + } + } + } + + // Picked-session lines aren't edited here: leave them exactly as they are (they still + // count towards the total due). + const pickedLines = registration.registrationOptions.filter((ro: any) => ro.sessionId); + registration.registrationOptions = registration.registrationOptions.filter((ro: any) => !ro.sessionId); + + // Compute totalPaid + const totalPaid = (registration.payments || []).reduce((sum: any, p: any) => sum + (p.amount || 0), 0); + + // Merge duplicate entries for the same eventOptionId+variantId (defensive; normal + // callers send one entry per option/variant combo). + const mergedOptionsMap = new Map(); + for (const opt of options) { + const key = `${opt.eventOptionId}::${opt.variantId || ''}`; + if (mergedOptionsMap.has(key)) { + mergedOptionsMap.get(key).quantity += opt.quantity; + } else { + mergedOptionsMap.set(key, { ...opt }); + } + } + const mergedOptions = Array.from(mergedOptionsMap.values()); + + // Group existing registrationOptions by eventOptionId::variantId so tickets that + // have already been issued are never deleted, only ever updated in place. Computed + // before pricing resolution because pricing now depends on whether a quantity is + // increasing (and by how much) — an unchanged or reduced quantity must never + // re-price tickets already locked in at an earlier price (see tranche design). + const oldByKey = new Map(); + for (const ro of registration.registrationOptions) { + const key = `${ro.eventOptionId}::${ro.variantId || ''}`; + if (!oldByKey.has(key)) oldByKey.set(key, []); + oldByKey.get(key).push(ro); + } + + // A legacy row (created before the tranche migration) has no tranches — fall back to + // its own priceSnapshot/quantity as a single implicit tranche for totals purposes. + const trancheSum = (tranches: any) => (tranches || []).reduce((s: any, t: any) => s + Number(t.quantity || 0) * Number(t.priceSnapshot || 0), 0); + const rowsTotal = (rows: any) => rows.reduce((sum: any, ro: any) => { + const tranches = ro.tranches || []; + if (tranches.length > 0) return sum + trancheSum(tranches); + return sum + Number(ro.quantity || 0) * Number(ro.priceSnapshot ?? ro.eventOption?.price ?? 0); + }, 0); + // Remove `qtyToRemove` units from a set of tranches, newest-first (LIFO) — mirrors the + // ticket-floor invariant below: issued tickets always map to the oldest tranches, so the + // newest (least-committed) tranches are the ones trimmed first on a quantity decrease. + const planLIFORemoval = (tranches: any, qtyToRemove: any) => { + const sorted = [...tranches].sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()); + let remaining = qtyToRemove; + const ops: any[] = []; + const kept: any[] = []; + for (const t of sorted) { + if (remaining <= 0) { kept.push(t); continue; } + if (t.quantity <= remaining) { + remaining -= t.quantity; + ops.push({ type: 'delete', trancheId: t.id }); + } else { + const newQuantity = t.quantity - remaining; + remaining = 0; + ops.push({ type: 'update', trancheId: t.id, newQuantity }); + kept.push({ ...t, quantity: newQuantity }); + } + } + return { kept, ops }; + }; + + // Resolve pricing for each incoming option (variant-aware, with stock check) — but only + // for the delta being newly added. Unchanged or decreasing quantities never re-resolve. + const eventOptionsMap = new Map((registration.event?.eventOptions || []).map((eo: any) => [eo.id, eo])); + const resolvedUpdateOptions: any[] = []; + let newTotalDue = 0; + for (const opt of mergedOptions) { + const key = `${opt.eventOptionId}::${opt.variantId || ''}`; + const existingRows = oldByKey.get(key) || []; + const existingQty = existingRows.reduce((sum: any, ro: any) => sum + (ro.quantity || 0), 0); + const delta = (opt.quantity || 0) - existingQty; + const existingTotal = rowsTotal(existingRows); + + const eventOption = eventOptionsMap.get(opt.eventOptionId); + const variantId = opt.variantId || null; + let priceSnapshot: any = null; + let appliedTierId: any = null; + let removalPlan: any = null; + + if (delta > 0) { + // Adding places needs stock, like a new registration does. + const oStock = await checkOptionStock(eventOption, delta); + const variant = variantId ? (eventOption.variants || []).find((v: any) => v.id === variantId) : null; + const vStock = variant ? await checkVariantStock(variant, delta) : { available: true, remaining: null }; + if (!oStock.available || !vStock.available) { + const left = Math.max(0, Math.min(oStock.remaining ?? Infinity, vStock.remaining ?? Infinity)); + fail(400, `Only ${left} more "${eventOption.name}${variant ? ` (${variant.name})` : ''}" available.`); + } + ({ priceSnapshot, appliedTierId } = await priceRequestedOption(eventOption, variantId, delta, registration.user)); + newTotalDue += existingTotal + delta * (priceSnapshot || 0); + } else if (delta < 0) { + const existingTranches = existingRows.flatMap((ro: any) => ro.tranches || []); + removalPlan = planLIFORemoval(existingTranches, -delta); + newTotalDue += trancheSum(removalPlan.kept); + } else { + newTotalDue += existingTotal; + } + + resolvedUpdateOptions.push({ ...opt, variantId, priceSnapshot, appliedTierId, existingRows, existingQty, delta, removalPlan }); + } + + newTotalDue += rowsTotal(pickedLines); + if (newTotalDue < totalPaid) { + return fail(400, 'Cannot reduce items below the amount already paid'); + } + + // Per-item floor: a ticket is only ever created once a registration is paid, and it is + // never deleted or shrunk — only grown. So an option can never be reduced (or removed) + // below the quantity of any ticket already issued for it. + const newKeys = new Set(resolvedUpdateOptions.map((opt: any) => `${opt.eventOptionId}::${opt.variantId || ''}`)); + const newQtyByKey = new Map(resolvedUpdateOptions.map((opt: any) => [`${opt.eventOptionId}::${opt.variantId || ''}`, opt.quantity || 0])); + for (const [key, rows] of oldByKey) { + const ticketQty = rows.reduce((sum: any, ro: any) => sum + (ro.tickets || []).reduce((s: any, t: any) => s + (t.quantity || 0), 0), 0); + if (ticketQty <= 0) continue; + const newQty = newQtyByKey.get(key) || 0; + if (newQty < ticketQty) { + return fail(400, `Cannot reduce "${rows[0].eventOption?.name || 'item'}" below the ${ticketQty} ticket(s) already issued`); + } + } + + // Differential update: update matching options in place, create genuinely new ones, + // and only delete options that were removed entirely. The floor check above guarantees + // a removed key never has tickets — the guard below turns that into a hard invariant + // instead of an assumption: tickets are never deleted. + await prisma.$transaction(async (tx: any) => { + for (const [key, rows] of oldByKey) { + if (newKeys.has(key)) continue; + const ticketedRows = rows.filter((ro: any) => (ro.tickets || []).length > 0); + if (ticketedRows.length > 0) { + fail(400, `Cannot remove "${rows[0].eventOption?.name || 'item'}" — tickets have already been issued for it`); + } + await tx.registrationOption.deleteMany({ where: { id: { in: rows.map((r: any) => r.id) } } }); + } + + for (const opt of resolvedUpdateOptions) { + const key = `${opt.eventOptionId}::${opt.variantId || ''}`; + const existingRows = oldByKey.get(key); + if (existingRows && existingRows.length > 0) { + const [primary, ...dupes] = existingRows; + + // Consolidate dupes into primary first: move their tranches and tickets rather + // than discarding them, so price history (and money) survives duplicate cleanup. + for (const dup of dupes) { + if ((dup.tranches || []).length > 0) { + await tx.registrationOptionTranche.updateMany({ where: { registrationOptionId: dup.id }, data: { registrationOptionId: primary.id } }); + } + if ((dup.tickets || []).length > 0) { + await tx.ticket.updateMany({ where: { registrationOptionId: dup.id }, data: { registrationOptionId: primary.id } }); + } + await tx.registrationOption.delete({ where: { id: dup.id } }); + } + + if (opt.delta > 0) { + // Increase: a new tranche for the delta at the freshly-resolved price — never + // overwrite the existing tranches' locked-in prices. + await tx.registrationOptionTranche.create({ + data: { + id: uuidv4(), + registrationOptionId: primary.id, + quantity: opt.delta, + priceSnapshot: opt.priceSnapshot, + appliedTierId: opt.appliedTierId || null, + } + }); + await tx.registrationOption.update({ + where: { id: primary.id }, + data: { quantity: opt.quantity, appliedTierId: opt.appliedTierId || null, priceSnapshot: opt.priceSnapshot } + }); + } else if (opt.delta < 0 && opt.removalPlan) { + // Decrease: trim tranches newest-first (LIFO); issued tickets always map to the + // oldest tranches, and the floor check above already guarantees this never dips + // below issued-ticket quantity. + for (const op of opt.removalPlan.ops) { + if (op.type === 'delete') { + await tx.registrationOptionTranche.delete({ where: { id: op.trancheId } }); + } else { + await tx.registrationOptionTranche.update({ where: { id: op.trancheId }, data: { quantity: op.newQuantity } }); + } + } + const newest = [...opt.removalPlan.kept].sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0]; + await tx.registrationOption.update({ + where: { id: primary.id }, + data: { + quantity: opt.quantity, + appliedTierId: newest ? (newest.appliedTierId || null) : null, + priceSnapshot: newest ? newest.priceSnapshot : null, + } + }); + } else { + // Unchanged quantity: only reflect dupe-consolidation in the aggregate; leave + // the locked-in price/tier untouched. + await tx.registrationOption.update({ + where: { id: primary.id }, + data: { quantity: opt.quantity } + }); + } + } else { + await tx.registrationOption.create({ + data: { + id: uuidv4(), + registrationId, + eventOptionId: opt.eventOptionId, + quantity: opt.quantity, + variantId: opt.variantId || null, + appliedTierId: opt.appliedTierId || null, + priceSnapshot: opt.priceSnapshot, + tranches: { + create: [{ + id: uuidv4(), + quantity: opt.quantity, + priceSnapshot: opt.priceSnapshot, + appliedTierId: opt.appliedTierId || null, + }] + } + } + }); + } + } + + // Names on places that no longer exist go too (newest first). Tickets for them + // are tidied up by generateTicketsForRegistration; the floor check above already + // stops anything going below tickets issued. + await tx.attendee.deleteMany({ where: { registrationId, registrationOptionId: null } }); + const lines = await tx.registrationOption.findMany({ where: { registrationId }, include: { attendees: { orderBy: { order: 'desc' } } } }); + for (const line of lines) { + const extra = (line.attendees || []).length - (line.quantity || 0); + if (extra > 0) { + await tx.attendee.deleteMany({ where: { id: { in: line.attendees.slice(0, extra).map((a: any) => a.id) } } }); + } + } + + // Coupon: percentage/comp codes follow the new items, fixed codes keep their amount. + const discount = await recalculateRegistrationDiscount(registrationId, tx); + const dueAfterDiscount = Math.max(0, newTotalDue - discount); + if (dueAfterDiscount < totalPaid - 0.001) { + fail(400, 'Cannot reduce items below the amount already paid'); + } + + // Update updatedAt and potentially status based on payments vs due + let newStatus = registration.status; + if (totalPaid >= dueAfterDiscount) newStatus = 'paid'; + else if (totalPaid > 0) newStatus = 'partial_paid'; + else newStatus = 'pending'; + + await tx.registration.update({ + where: { id: registrationId }, + data: { updatedAt: new Date(), status: newStatus } + }); + }); + + // Return updated registration + const updated = await prisma.registration.findUnique({ + where: { id: registrationId }, + include: { + registrationOptions: { include: { eventOption: true, tranches: true } }, + event: true, + user: { select: { id: true, name: true, email: true, phoneNumber: true } }, + payments: true, + couponRedemptions: ACTIVE_COUPONS_INCLUDE, + + bundleApplications: BUNDLE_APPS_INCLUDE, + attendees: ATTENDEES_INCLUDE, + } + }); + + const { sendRegistrationUpdatedEmails } = require('../utils/notifications'); + sendRegistrationUpdatedEmails(registrationId).catch((e: any) => console.error('Failed to send registration updated emails:', e)); + if (resolvedUpdateOptions.some((o: any) => o.delta < 0) || oldByKey.size > newKeys.size) queueWaitlist(registration.eventId); + + // If registration is now paid, regenerate tickets and send them + if (updated.status === 'paid') { + (async () => { + try { + await generateTicketsForRegistration(registrationId); + const mockReq = { user: { id: updated.userId }, body: { registrationId } }; + const mockRes = { status: () => mockRes, json: () => {} }; + await emailTickets(mockReq, mockRes); + } catch (e: any) { + console.error('[updateRegistrationOptions] Failed to generate/send tickets:', e?.message || e); + } + })(); + } + + return attachComputedTotals(updated); +}); + +// @desc Submit form responses for a registration +// @route POST /api/registrations/:id/forms/responses +// @access Private +export const submitFormResponses = as400(async (call: Call): Promise => { + const registrationId = call.params.id; + const userId = call.actor?.id || null; + const { responses } = call.body; // [{ answers: { fieldId: value } }] + + // load registration with options and event form + const registration = await prisma.registration.findUnique({ + where: { id: registrationId }, + include: { + registrationOptions: { include: { eventOption: true, tranches: true } }, + event: true, + } + }); + if (!registration) { return fail(404, 'Registration not found'); } + // Guests (no auth) may submit by knowing the registrationId; authenticated users must be + // owner, staff+, or submitting their own form as a named attendee + const ownAttendeeOnly = Array.isArray(responses) && responses.length > 0 && call.actor + && (await prisma.attendee.count({ where: { registrationId, userId, id: { in: responses.map((r: any) => r?.attendeeId).filter(Boolean) } } })) === responses.length; + if (call.actor && registration.userId !== userId && !['admin','supervisor','staff'].includes(call.actor.role) && !ownAttendeeOnly) { + return fail(403, 'Not authorized'); + } + + // fetch form + let form: any = null; + try { + form = await prisma.eventForm.findUnique({ where: { eventId: registration.eventId }, include: { fields: true } }); + } catch (e: any) {} + if (!form) { + return { message: 'No form for this event. Nothing to submit.' }; + } + + const fields = (form.fields || []).sort((a: any, b: any) => (a.order||0)-(b.order||0)); + const answerableFields = fields.filter((f: any) => f.type !== 'statement' && f.type !== 'paragraph'); + + const mainTickets = registration.registrationOptions.filter((ro: any) => ro.eventOption?.isMainTicket).reduce((s: any, ro: any) => s + (ro.quantity || 0), 0); + const toSubmit = Array.isArray(responses) ? responses : []; + + if (toSubmit.length === 0) { return fail(400, 'No responses provided'); } + if (toSubmit.length > mainTickets) { return fail(400, `Too many forms submitted. Expected at most ${mainTickets}`); } + + // A response can be for a named attendee (group tickets); each attendee answers once. + const attendeeIds = toSubmit.map((r: any) => r?.attendeeId).filter(Boolean); + if (attendeeIds.length > 0) { + const known = await prisma.attendee.findMany({ where: { id: { in: attendeeIds }, registrationId }, include: { formResponses: { select: { id: true } } } }); + if (known.length !== new Set(attendeeIds).size) { return fail(400, 'Unknown attendee for this registration'); } + const answered = known.find((a: any) => a.formResponses.length > 0); + if (answered) { return fail(400, `${answered.name}'s form has already been submitted`); } + } + + // Create responses and answers + const created: any[] = []; + for (const resp of toSubmit) { + const respId = uuidv4(); + const fr = await prisma.formResponse.create({ data: { id: respId, registrationId, attendeeId: resp?.attendeeId || null } }); + const ansMap = resp?.answers || {}; + for (const f of answerableFields) { + const raw = ansMap[f.id]; + // If field required at field-level, enforce non-empty + if (f.isRequired && (raw === undefined || raw === null || String(raw).trim() === '')) { + return fail(400, `Missing answer for: ${f.label}`); + } + if (raw !== undefined && raw !== null && String(raw).length > 0) { + await prisma.formAnswer.create({ data: { id: uuidv4(), responseId: respId, fieldId: f.id, value: String(raw) } }); + } + } + created.push(fr); + } + + // After submitting responses, if registration is already paid, generate and email tickets now. + let generatedTickets = []; + try { + const regAfter = await prisma.registration.findUnique({ where: { id: registrationId } }); + if (regAfter && regAfter.status === 'paid') { + generatedTickets = await generateTicketsForRegistration(registrationId); + if (generatedTickets && generatedTickets.length > 0) { + try { + const mockReq = { user: { id: regAfter.userId }, body: { registrationId } }; + const mockRes = { status: () => mockRes, json: () => {} }; + await emailTickets(mockReq, mockRes); + } catch (emailErr: any) { + console.error('Post-form ticket email failed:', emailErr?.message || emailErr); + } + } + } + } catch (e: any) { + console.error('Post-form ticket generation attempt failed:', e?.message || e); + } + + return { message: 'Responses submitted', count: created.length, generatedTickets: (generatedTickets && generatedTickets.length) ? generatedTickets : undefined }; +}); + +// @desc Replace (edit) form responses for a registration (staff/admin/supervisor) +// @route PUT /api/registrations/:id/forms/responses +// @access Private/Staff +export const replaceFormResponses = as400(async (call: Call): Promise => { + const registrationId = call.params.id; + const { responses } = call.body; // [{ answers: { fieldId: value } }] + + // Authorization: staff or above only for replacing existing responses + if (!['admin','supervisor','staff'].includes(call.actor.role)) { + return fail(403, 'Not authorized'); + } + + // Load registration and form + const registration = await prisma.registration.findUnique({ + where: { id: registrationId }, + include: { + registrationOptions: { include: { eventOption: true, tranches: true } }, + event: true, + } + }); + if (!registration) { return fail(404, 'Registration not found'); } + + let form: any = null; + try { + form = await prisma.eventForm.findUnique({ where: { eventId: registration.eventId }, include: { fields: true } }); + } catch {} + if (!form) { return { message: 'No form for this event. Nothing to save.' }; } + + const fields = (form.fields || []).sort((a: any, b: any) => (a.order||0)-(b.order||0)); + const answerableFields = fields.filter((f: any) => f.type !== 'statement' && f.type !== 'paragraph'); + const mainTickets = registration.registrationOptions.filter((ro: any) => ro.eventOption?.isMainTicket).reduce((s: any, ro: any) => s + (ro.quantity || 0), 0); + const toSubmit = Array.isArray(responses) ? responses : []; + + if (toSubmit.length === 0) { return fail(400, 'No responses provided'); } + if (toSubmit.length > mainTickets) { return fail(400, `Too many forms submitted. Expected at most ${mainTickets}`); } + + // Replace transactionally + await prisma.$transaction(async (tx: any) => { + // Delete existing answers and responses for this registration + const existing = await tx.formResponse.findMany({ where: { registrationId }, select: { id: true } }); + const ids = existing.map((e: any) => e.id); + if (ids.length > 0) { + await tx.formAnswer.deleteMany({ where: { responseId: { in: ids } } }); + await tx.formResponse.deleteMany({ where: { id: { in: ids } } }); + } + // Create new set + for (const resp of toSubmit) { + const respId = uuidv4(); + await tx.formResponse.create({ data: { id: respId, registrationId } }); + const ansMap = resp?.answers || {}; + for (const f of answerableFields) { + const raw = ansMap[f.id]; + if (f.isRequired && (raw === undefined || raw === null || String(raw).trim() === '')) { + return fail(400, `Missing answer for: ${f.label}`); + } + if (raw !== undefined && raw !== null && String(raw).length > 0) { + await tx.formAnswer.create({ data: { id: uuidv4(), responseId: respId, fieldId: f.id, value: String(raw) } }); + } + } + } + // Touch registration updatedAt + await tx.registration.update({ where: { id: registrationId }, data: { updatedAt: new Date() } }); + }); + + // Attempt ticket generation and email if already paid + try { + const regAfter = await prisma.registration.findUnique({ where: { id: registrationId }, include: { user: { select: { id: true } } } }); + if (regAfter && regAfter.status === 'paid') { + const newTickets = await generateTicketsForRegistration(registrationId); + if (newTickets && newTickets.length > 0) { + try { + const mockReq = { user: { id: regAfter.userId }, body: { registrationId } }; + const mockRes = { status: () => mockRes, json: () => {} }; + await emailTickets(mockReq, mockRes); + } catch (emailErr: any) { + console.error('Error emailing tickets after form replacement:', emailErr); + } + } + } + } catch {} + + return { message: 'Responses saved' }; +}); + +// @desc Get saved draft for attendee forms for a registration (owner or staff) +// @route GET /api/registrations/:id/forms/draft +// @access Private +export const getFormDraft = as400(async (call: Call): Promise => { + const registrationId = call.params.id; + const userId = call.actor?.id || null; + + // Load registration to verify access + const registration = await prisma.registration.findUnique({ where: { id: registrationId } }); + if (!registration) { return fail(404, 'Registration not found'); } + if (call.actor && registration.userId !== userId && !['admin','supervisor','staff'].includes(call.actor.role)) { + return fail(403, 'Not authorized'); + } + + // Find draft. If staff/admin, we still scope the draft to the registration owner (so they can resume later). + const ownerUserId = registration.userId; + const draft = await prisma.formDraft.findUnique({ where: { registrationId_userId: { registrationId, userId: ownerUserId } } }); + if (!draft) return { data: {}, updatedAt: null }; + return { data: draft.data || {}, updatedAt: draft.updatedAt }; +}); + +// @desc Save draft for attendee forms for a registration (owner or staff). Does not mark as completed. +// @route PUT /api/registrations/:id/forms/draft +// @access Private +export const saveFormDraft = as400(async (call: Call): Promise => { + const registrationId = call.params.id; + const userId = call.actor?.id || null; + const { data } = call.body; // JSON object mapping attendeeIndex -> { fieldId: value } + + if (typeof data !== 'object' || data == null) { + return fail(400, 'Invalid draft payload'); + } + + // Load registration to verify access + const registration = await prisma.registration.findUnique({ where: { id: registrationId } }); + if (!registration) { return fail(404, 'Registration not found'); } + if (call.actor && registration.userId !== userId && !['admin','supervisor','staff'].includes(call.actor.role)) { + return fail(403, 'Not authorized'); + } + + const ownerUserId = registration.userId; + + // Upsert by (registrationId, userId) unique composite + const saved = await prisma.formDraft.upsert({ + where: { registrationId_userId: { registrationId, userId: ownerUserId } }, + update: { data, updatedAt: new Date() }, + create: { registrationId, userId: ownerUserId, data }, + }); + + return { message: 'Draft saved', updatedAt: saved.updatedAt }; +}); + +// @desc Re-send the current invoice PDF for one of the caller's own registrations +// @route POST /api/registrations/:id/send-invoice +// @access Private +export const sendInvoice = as400(async (call: Call): Promise => { + const { channel } = call.body || {}; + const { sendInvoiceToUser } = require('../utils/notifications'); + await sendInvoiceToUser(call.params.id, call.actor.id, channel); + return { message: channel === 'whatsapp' ? 'Invoice sent to WhatsApp.' : 'Invoice emailed.' }; +}); + +// @desc Apply a coupon code to an existing registration +// @route POST /api/registrations/:id/coupon +// @access Private (owner, or staff applying it on someone's behalf) +export const applyCoupon = as400(async (call: Call): Promise => { + const { code } = call.body || {}; + const registration = await prisma.registration.findUnique({ + where: { id: call.params.id }, + include: { event: { select: { endDate: true, cashupStatus: true } } }, + }); + if (!registration) { return fail(404, 'Registration not found'); } + const byStaff = registration.userId !== call.actor.id; + if (byStaff && !isStaffRole(call.actor.role)) { return fail(403, 'Not authorized to change this registration'); } + if (registration.status === 'cancelled') { return fail(400, 'This registration is cancelled.'); } + if (registration.event?.cashupStatus === 'closed') { return fail(400, 'This event is closed.'); } + if (registration.event?.endDate && new Date(registration.event.endDate) < new Date()) { + return fail(400, 'This event has already ended.'); + } + + const { coupon, discount } = await applyCouponToRegistration({ + registrationId: registration.id, + code, + appliedById: byStaff ? call.actor.id : null, + }); + await syncStatusAfterDiscount(registration.id); + + if (byStaff) { + logAdminAction({ + actorId: call.actor.id, + actorRole: call.actor.role, + action: 'coupon_applied_manual', + targetType: 'Registration', + targetId: registration.id, + metadata: { code: coupon.code, discount, forUserId: registration.userId }, + ip: call.ip, + }); + } + + const { sendRegistrationUpdatedEmails } = require('../utils/notifications'); + sendRegistrationUpdatedEmails(registration.id).catch((e: any) => console.error('Failed to send registration updated emails:', e)); + + const updated = await prisma.registration.findUnique({ + where: { id: registration.id }, + include: { + registrationOptions: { include: { eventOption: true, variant: { select: { id: true, name: true, price: true } }, tranches: true } }, + payments: true, + couponRedemptions: ACTIVE_COUPONS_INCLUDE, + + bundleApplications: BUNDLE_APPS_INCLUDE, + }, + }); + return { ...attachComputedTotals(updated), message: `Code ${coupon.code} applied — ${describeCoupon(coupon)}.` }; +}); + +// @desc Remove the coupon from a registration (the use is freed) +// @route DELETE /api/registrations/:id/coupon +// @access Private/Staff +export const removeCoupon = as400(async (call: Call): Promise => { + const registration = await prisma.registration.findUnique({ where: { id: call.params.id } }); + if (!registration) { return fail(404, 'Registration not found'); } + await eventOpen(registration.eventId); + + // Removing a discount raises the total, which can take a paid registration back to + // unpaid. Same rule as a staff status change: refuse once a ticket has been scanned, + // otherwise withdraw the unused tickets until it's paid again. + const tickets = await prisma.ticket.findMany({ + where: { registrationOption: { registrationId: registration.id } }, + include: { usages: true }, + }); + if (registration.status === 'paid' && tickets.some((t: any) => t.isUsed || t.usages.length > 0)) { + return fail(400, 'A ticket on this registration has already been scanned, so its code can\'t be removed.'); + } + + const released = await releaseRegistrationCoupons(registration.id); + if (!released) { return fail(400, 'No code is applied to this registration.'); } + const status = await syncStatusAfterDiscount(registration.id); + if (registration.status === 'paid' && status !== 'paid') { + await prisma.ticket.deleteMany({ where: { registrationOption: { registrationId: registration.id }, isUsed: false } }); + } + + logAdminAction({ + actorId: call.actor.id, + actorRole: call.actor.role, + action: 'coupon_applied_manual', + targetType: 'Registration', + targetId: registration.id, + metadata: { removed: true, forUserId: registration.userId }, + ip: call.ip, + }); + return { message: 'Code removed.' }; +}); + +// @desc Replace the named attendees on a registration (and who gets the tickets) +// @route PUT /api/registrations/:id/attendees +// @access Private (owner or staff) +// Body: { attendees: [{ id?, eventOptionId, variantId?, name, email?, phone? }], ticketDelivery? } +// Attendees left out are removed — refused if their ticket has been scanned. +export const updateAttendees = as400(async (call: Call): Promise => { + const { attendees = [], ticketDelivery } = call.body || {}; + const registration = await prisma.registration.findUnique({ + where: { id: call.params.id }, + include: { + registrationOptions: true, + attendees: { include: { ticket: { include: { usages: true } } } }, + event: { include: { eventOptions: true } }, + }, + }); + if (!registration) { return fail(404, 'Registration not found'); } + if (!isOwnerOrStaff(registration, call.actor)) { return fail(403, 'Not authorized to edit this registration'); } + if (registration.status === 'cancelled') { return fail(400, 'This registration is cancelled.'); } + if (registration.event?.cashupStatus === 'closed') { return fail(400, 'This event is closed.'); } + if (registration.event?.endDate && new Date(registration.event.endDate) < new Date()) { + return fail(400, 'This event has already ended.'); + } + if (ticketDelivery !== undefined && !TICKET_DELIVERY.includes(ticketDelivery)) { + return fail(400, "ticketDelivery must be 'payer' or 'each'"); + } + + const clean = validateAttendees(registration.event, placesAfter(registration.registrationOptions, []), attendees); + const keepIds = new Set(attendees.map((a: any) => a?.id).filter(Boolean)); + const existingById = new Map(registration.attendees.map((a: any) => [a.id, a])); + for (const id of keepIds) if (!existingById.has(id)) { return fail(400, 'Unknown attendee for this registration'); } + const removed = registration.attendees.filter((a: any) => !keepIds.has(a.id)); + const usedRemoved = removed.find((a: any) => a.ticket && (a.ticket.isUsed || a.ticket.usages.length > 0)); + if (usedRemoved) { return fail(400, `${usedRemoved.name}'s ticket has already been scanned, so they can't be removed.`); } + + const toCreate: any[] = []; + await prisma.$transaction(async (tx: any) => { + if (removed.length) await tx.attendee.deleteMany({ where: { id: { in: removed.map((a: any) => a.id) } } }); + for (let i = 0; i < attendees.length; i++) { + const a = attendees[i]; + const c = clean[i]; + if (a.id) { + const prev = existingById.get(a.id); + const contactChanged = prev.email !== c.email || prev.phone !== c.phone; + const match = contactChanged && (c.email || c.phone) ? await findAccountByContact({ email: c.email, phone: c.phone }, tx) : null; + await tx.attendee.update({ + where: { id: a.id }, + data: { + name: c.name, email: c.email, phone: c.phone, + dateOfBirth: c.dateOfBirth, gender: c.gender, parentName: c.parentName, parentEmail: c.parentEmail, parentPhone: c.parentPhone, + ...(contactChanged ? { userId: match?.user?.id || null } : {}), + }, + }); + } else { + toCreate.push(c); + } + } + if (toCreate.length) await createAttendees(registration.id, toCreate, tx); + if (ticketDelivery) await tx.registration.update({ where: { id: registration.id }, data: { ticketDelivery } }); + }); + + queueConsentRequests(registration.id); + + // Paid registrations: re-sync tickets and send any new ones. + if (registration.status === 'paid') { + const created = await generateTicketsForRegistration(registration.id); + if (created.length > 0) { + const mockReq = { user: { id: registration.userId }, body: { ticketIds: created.map((t: any) => t.id) } }; + const mockRes = { status: () => mockRes, json: () => {} }; + emailTickets(mockReq, mockRes).catch((e: any) => console.error('[attendees] Failed to send new tickets:', e?.message || e)); + } + } + + const updated = await prisma.registration.findUnique({ + where: { id: registration.id }, + select: { id: true, ticketDelivery: true, attendees: ATTENDEES_INCLUDE }, + }); + return { ...updated, attendees: updated.attendees.map(({ userId: _userId, ...a }: any) => a) }; +}); + +// @desc Send an attendee a link to fill in their own attendee form +// @route POST /api/registrations/:id/attendees/:attendeeId/send-form-link +// @access Private (owner or staff) +export const sendAttendeeFormLink = as400(async (call: Call): Promise => { + const attendee = await prisma.attendee.findFirst({ + where: { id: call.params.attendeeId, registrationId: call.params.id }, + include: { registration: { include: { event: true, user: { select: { id: true, name: true } } } } }, + }); + if (!attendee) { return fail(404, 'Attendee not found'); } + if (!isOwnerOrStaff(attendee.registration, call.actor)) { return fail(403, 'Not authorized'); } + if (!attendee.email && !attendee.phone) { return fail(400, `Add an email or phone number for ${attendee.name} first.`); } + + const { sendAttendeeFormLinkMessage } = require('../utils/notifications'); + const sent = await sendAttendeeFormLinkMessage(attendee); + return { message: sent.length ? `Form link sent to ${attendee.name} by ${sent.join(' and ')}.` : 'The form link could not be sent.' }; +});