diff --git a/CHANGELOG.md b/CHANGELOG.md index c6700a7..2f7e27e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,30 @@ and this project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [1.51.10] - 2026-10-29 + +### Added + +- **API v2 — managing registrations:** the staff list (`GET /registrations`, paged, `unpaid`, + `userId`), an event's registrations (`/events/{id}/registrations`), a registration in full + (`/registrations/{id}/full`, `/me/registrations/full`), `PATCH /registrations/{id}/status`, + registering someone (`POST /registrations/manual`), bulk actions (`/registrations/bulk`), changing + items (`PUT /registrations/{id}/items`), the invoice, coupon codes on a registration, named + attendees and their form links, attendee form drafts and responses + (`/registrations/{id}/form-draft`, `/registrations/{id}/form-responses`). +- **`src/services/registrationAdmin.ts`:** everything after a registration is made, moved from + `registrationController.js` (now about 60 lines of v1 wrappers). +- v2 manual registration accepts the same `notificationPreference` and `couponCode` values v1 did. +- Frontend: `fetchAllRegistrations()` reads every page of the staff list. Registrations, at the + door, manual registration, self-service, payments, forms, the attendee composers, reports and + the user dashboard all use v2. + +### Changed + +- The roadmap gives money (payments, cashup, provider transactions, waitlist, sponsorship, + consent, feedback) its own release, 1.51.11; the later areas move up one, and incoming webhooks + and links are now 1.51.16. + ## [1.51.9] - 2026-10-29 ### Added diff --git a/WHATS-NEW.md b/WHATS-NEW.md index 59e9854..d35ca44 100644 --- a/WHATS-NEW.md +++ b/WHATS-NEW.md @@ -12,6 +12,12 @@ Write for church admins, not developers: no environment variables, endpoints or developer log is CHANGELOG.md. A tagged version without a section here shows "No details given". --> +## 1.51.10 + +- **More groundwork for 2.0.** Registrations — at the door, in the dashboards, attendee forms and + bulk actions — now run on the new version of the server's connection to the app. They work + just as before. + ## 1.51.9 - **More groundwork for 2.0.** Event series, season passes, bundle deals, coupon codes and campuses diff --git a/backend/package-lock.json b/backend/package-lock.json index 4df9607..ec12609 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "event-management-backend", - "version": "1.51.9", + "version": "1.51.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "event-management-backend", - "version": "1.51.9", + "version": "1.51.10", "hasInstallScript": true, "dependencies": { "@cj-tech-master/excelts": "^10.2.0", diff --git a/backend/package.json b/backend/package.json index eac2318..0ec45a3 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "event-management-backend", - "version": "1.51.9", + "version": "1.51.10", "description": "Event Management System Backend", "main": "src/index.js", "scripts": { diff --git a/backend/src/controllers/registrationController.js b/backend/src/controllers/registrationController.js index 86b1999..6f6017d 100644 --- a/backend/src/controllers/registrationController.js +++ b/backend/src/controllers/registrationController.js @@ -1,26 +1,9 @@ -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'); +// Registrations (v1). The work is in src/services: registrations.ts (making and cancelling +// one) and registrationAdmin.ts (everything after) — shared with /api/v2. 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). +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 +18,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 +30,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/backend/src/services/registrationAdmin.ts b/backend/src/services/registrationAdmin.ts new file mode 100644 index 0000000..0d1f2f1 --- /dev/null +++ b/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 || e?.code === 'MODULE_NOT_FOUND') 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('../controllers/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.' }; +}); diff --git a/backend/src/v2/deprecation.ts b/backend/src/v2/deprecation.ts index 2ce85ca..44121d6 100644 --- a/backend/src/v2/deprecation.ts +++ b/backend/src/v2/deprecation.ts @@ -46,6 +46,24 @@ const SUCCESSORS: Successor[] = [ { method: 'POST', v1: /^\/api\/events\/([^/]+)\/copy-from$/, v2: m => `/api/v2/events/${m[1]}/copy-from` }, { method: 'GET', v1: /^\/api\/events\/([^/]+)\/notify-recipients$/, v2: m => `/api/v2/events/${m[1]}/notify-recipients` }, { method: 'PUT', v1: /^\/api\/events\/([^/]+)\/notify-recipients$/, v2: m => `/api/v2/events/${m[1]}/notify-recipients` }, + // 1.51.10: managing registrations + { method: 'GET', v1: /^\/api\/registrations\/?$/, v2: () => '/api/v2/registrations' }, + { method: 'GET', v1: /^\/api\/registrations\/myregistrations$/, v2: () => '/api/v2/me/registrations/full' }, + { method: 'GET', v1: /^\/api\/registrations\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/registrations` }, + { method: 'POST', v1: /^\/api\/registrations\/manual$/, v2: () => '/api/v2/registrations/manual' }, + { method: 'POST', v1: /^\/api\/registrations\/bulk$/, v2: () => '/api/v2/registrations/bulk' }, + { method: 'PUT', v1: /^\/api\/registrations\/([^/]+)\/options$/, v2: m => `/api/v2/registrations/${m[1]}/items` }, + { method: 'POST', v1: /^\/api\/registrations\/([^/]+)\/send-invoice$/, v2: m => `/api/v2/registrations/${m[1]}/invoice` }, + { method: 'POST', v1: /^\/api\/registrations\/([^/]+)\/coupon$/, v2: m => `/api/v2/registrations/${m[1]}/coupon` }, + { method: 'DELETE', v1: /^\/api\/registrations\/([^/]+)\/coupon$/, v2: m => `/api/v2/registrations/${m[1]}/coupon` }, + { method: 'PUT', v1: /^\/api\/registrations\/([^/]+)\/attendees$/, v2: m => `/api/v2/registrations/${m[1]}/attendees` }, + { method: 'POST', v1: /^\/api\/registrations\/([^/]+)\/attendees\/([^/]+)\/send-form-link$/, v2: m => `/api/v2/registrations/${m[1]}/attendees/${m[2]}/form-link` }, + { method: 'GET', v1: /^\/api\/registrations\/([^/]+)\/forms\/draft$/, v2: m => `/api/v2/registrations/${m[1]}/form-draft` }, + { method: 'PUT', v1: /^\/api\/registrations\/([^/]+)\/forms\/draft$/, v2: m => `/api/v2/registrations/${m[1]}/form-draft` }, + { method: 'POST', v1: /^\/api\/registrations\/([^/]+)\/forms\/responses$/, v2: m => `/api/v2/registrations/${m[1]}/form-responses` }, + { method: 'PUT', v1: /^\/api\/registrations\/([^/]+)\/forms\/responses$/, v2: m => `/api/v2/registrations/${m[1]}/form-responses` }, + { method: 'GET', v1: /^\/api\/registrations\/([^/]+)$/, v2: m => `/api/v2/registrations/${m[1]}/full` }, + { method: 'PUT', v1: /^\/api\/registrations\/([^/]+)$/, v2: m => `/api/v2/registrations/${m[1]}/status` }, // 1.51.9: series, season passes, bundles, coupons, campuses { method: 'GET', v1: /^\/api\/series\/?$/, v2: () => '/api/v2/series' }, { method: 'POST', v1: /^\/api\/series\/?$/, v2: () => '/api/v2/series' }, @@ -87,7 +105,6 @@ const SUCCESSORS: Successor[] = [ { method: 'POST', v1: /^\/api\/users\/?$/, v2: () => '/api/v2/auth/signup' }, { method: 'POST', v1: /^\/api\/users\/login$/, v2: () => '/api/v2/auth/login' }, { method: 'POST', v1: /^\/api\/users\/login\/2fa$/, v2: () => '/api/v2/auth/login/code' }, - { method: 'GET', v1: /^\/api\/registrations\/myregistrations$/, v2: () => '/api/v2/me/registrations' }, { method: 'POST', v1: /^\/api\/registrations\/?$/, v2: () => '/api/v2/registrations' }, { method: 'DELETE', v1: /^\/api\/registrations\/([^/]+)$/, v2: m => `/api/v2/registrations/${m[1]}/cancel` }, { method: 'POST', v1: /^\/api\/payments\/checkout$/, v2: () => '/api/v2/registrations/{id}/checkout' }, diff --git a/backend/src/v2/index.ts b/backend/src/v2/index.ts index d3cfe74..af8a6e2 100644 --- a/backend/src/v2/index.ts +++ b/backend/src/v2/index.ts @@ -13,6 +13,7 @@ import './resources/seriesDeals'; import './resources/events'; import './resources/me'; import './resources/registrations'; +import './resources/registrationsManage'; import './resources/checkin'; import './resources/auth'; diff --git a/backend/src/v2/resources/registrationsManage.ts b/backend/src/v2/resources/registrationsManage.ts new file mode 100644 index 0000000..cf9fd44 --- /dev/null +++ b/backend/src/v2/resources/registrationsManage.ts @@ -0,0 +1,214 @@ +import { z } from 'zod'; +import type { Request } from 'express'; +import { defineRoute, type ApiUser } from '../route'; +import { pageOf, single } from '../paging'; +import { id, idParams } from '../schemas'; +import * as admin from '../../services/registrationAdmin'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- registrations are passed through with their includes */ +const campusScope = require('../../utils/campusScope') as { + listWhere(req: unknown, path?: string): Promise; + scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown; ownerOk?: boolean }): any; + scopeBody(targets: [string, string][], opts?: { need?: 'view' | 'manage'; orphan?: 'pass' | 'deny' }): any; +}; +const { notOnSeasonPass } = require('../../utils/seasonPass') as { notOnSeasonPass: any }; +const plain = (v: T): any => JSON.parse(JSON.stringify(v)); + +/** The v2 request as the registration service's Call. */ +function callFrom(req: Request, user: ApiUser | null, parts: { params?: object; body?: object; query?: object }): admin.Call { + const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; + return { + actor: user ? { id: user.id, role: user.role, email: user.email } : null, + params: (parts.params ?? {}) as Record, + body: parts.body ?? {}, + query: parts.query ?? {}, + readOnly: !!(req as any).readOnly, + ip: getClientIp(req), + listWhere: () => campusScope.listWhere(req, 'event'), + }; +} + +const OWNER_OR_STAFF = 'scopeEvent(registration, owner-ok)'; +const ownerOrStaff = campusScope.scopeEvent({ resolve: 'registration', ownerOk: true }); +const STATUSES = ['pending', 'confirmed', 'partial_paid', 'paid', 'cancelled'] as const; + +/** A registration with everything the dashboards show: items and their prices, payments, attendees, coupons, `totalDueComputed`. */ +const fullRegistration = z.looseObject({ id, status: z.enum(STATUSES), eventId: id, userId: id, totalDueComputed: z.number().optional() }); +const message = single(z.looseObject({ message: z.string() })); +const lineBody = z.object({ eventOptionId: id, variantId: id.nullish(), quantity: z.number().int().min(1).max(1000), sessionIds: z.array(id).max(200).optional() }); +const attendeeBody = z.looseObject({ id: id.optional().describe('An attendee already on it (left out = removed)'), eventOptionId: id, variantId: id.nullish(), name: z.string().max(200) }); +const responsesBody = z.object({ + responses: z.array(z.object({ + attendeeId: id.nullish().describe('The named attendee this form is for'), + answers: z.record(z.string(), z.unknown()).describe('Field id → answer (stored as text)'), + })).max(500), +}); + +// ─── Owner (or staff) ──────────────────────────────────────────────────────── + +export const fullOne = defineRoute({ + method: 'get', path: '/registrations/:id/full', tag: 'Registrations', summary: 'A registration with everything on it', + description: [ + 'Items and prices, payments, coupons and bundles, named attendees, form answers and the total due.', + 'The owner, a named attendee or staff — or anyone with the link when not signed in (registration ids can\'t be guessed). Attendees\' contact details are only shown to the payer and staff.', + ].join('\n\n'), + access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, response: single(fullRegistration), + async handler({ params, user, req }) { return { data: plain(await admin.getRegistrationById(callFrom(req, user, { params }))) }; }, +}); + +export const myFull = defineRoute({ + method: 'get', path: '/me/registrations/full', tag: 'Me', summary: 'My registrations with everything on them', + description: 'What the dashboard shows: as `/registrations/{id}/full`, newest first, with the event and its form. Only upcoming ones unless `past=true`.', + access: 'user', + query: z.object({ past: z.enum(['true', 'false']).default('false') }), + response: z.object({ data: z.array(fullRegistration) }), + async handler({ query, user, req }) { return { data: plain(await admin.getUserRegistrations(callFrom(req, user, { query: { showPast: query.past } }))) }; }, +}); + +export const changeItems = defineRoute({ + method: 'put', path: '/registrations/:id/items', tag: 'Registrations', summary: 'Change the tickets on a registration', + description: [ + 'The whole list of items it should have. Added places need stock and are priced now; places already paid for keep their price, and nothing goes below tickets already issued or the amount paid.', + 'Not for registrations made with a season pass, nor once the event has ended or is closed. Staff can add kids and volunteer places; owners can only keep or lower them.', + ].join('\n\n'), + access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff, notOnSeasonPass], params: idParams, + body: z.object({ options: z.array(lineBody.omit({ sessionIds: true })).min(1).max(100) }), response: single(fullRegistration), + async handler({ params, body, user, req }) { return { data: plain(await admin.updateRegistrationOptions(callFrom(req, user, { params, body }))) }; }, +}); + +export const sendInvoice = defineRoute({ + method: 'post', path: '/registrations/:id/invoice', tag: 'Registrations', summary: 'Send me the invoice again', + access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, + body: z.object({ channel: z.enum(['email', 'whatsapp']).default('email') }), response: message, + async handler({ params, body, user, req }) { return { data: await admin.sendInvoice(callFrom(req, user, { params, body })) }; }, +}); + +export const applyCoupon = defineRoute({ + method: 'post', path: '/registrations/:id/coupon', tag: 'Registrations', summary: 'Apply a coupon code', + description: 'By the owner, or by staff on their behalf (logged). Not on season pass registrations.', + access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff, notOnSeasonPass], params: idParams, + body: z.object({ code: z.string().trim().min(1).max(40) }), response: single(fullRegistration.extend({ message: z.string() })), + async handler({ params, body, user, req }) { return { data: plain(await admin.applyCoupon(callFrom(req, user, { params, body }))) }; }, +}); + +export const removeCoupon = defineRoute({ + method: 'delete', path: '/registrations/:id/coupon', tag: 'Registrations', summary: 'Take a coupon code off', + description: 'Staff. Its use is freed. Not once a ticket on it has been scanned; unused tickets are withdrawn if it\'s no longer paid.', + access: 'staff', campusScope: 'scopeEvent(registration)', middleware: [campusScope.scopeEvent({ resolve: 'registration' })], params: idParams, response: message, + async handler({ params, user, req }) { return { data: await admin.removeCoupon(callFrom(req, user, { params })) }; }, +}); + +export const setAttendees = defineRoute({ + method: 'put', path: '/registrations/:id/attendees', tag: 'Registrations', summary: 'Name the people on a registration', + description: 'The whole list: attendees left out are removed (not once their ticket has been scanned). `ticketDelivery` says who gets the tickets.', + access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, + body: z.object({ attendees: z.array(attendeeBody).max(1000), ticketDelivery: z.enum(['payer', 'each']).optional() }), + response: single(z.looseObject({ id, ticketDelivery: z.string().nullable(), attendees: z.array(z.looseObject({ id, name: z.string() })) })), + async handler({ params, body, user, req }) { return { data: plain(await admin.updateAttendees(callFrom(req, user, { params, body }))) }; }, +}); + +export const sendFormLink = defineRoute({ + method: 'post', path: '/registrations/:id/attendees/:attendeeId/form-link', tag: 'Registrations', summary: 'Send an attendee their form', + description: 'A link to fill in their own attendee form, by email and/or WhatsApp.', + access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: z.object({ id, attendeeId: id }), response: message, + async handler({ params, user, req }) { return { data: await admin.sendAttendeeFormLink(callFrom(req, user, { params })) }; }, +}); + +export const getDraft = defineRoute({ + method: 'get', path: '/registrations/:id/form-draft', tag: 'Registrations', summary: 'Attendee forms saved part-way', + access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, + response: single(z.object({ data: z.record(z.string(), z.unknown()), updatedAt: z.string().nullable() })), + async handler({ params, user, req }) { return { data: plain(await admin.getFormDraft(callFrom(req, user, { params }))) }; }, +}); + +export const saveDraft = defineRoute({ + method: 'put', path: '/registrations/:id/form-draft', tag: 'Registrations', summary: 'Save attendee forms part-way', + description: 'Kept for the registration\'s owner (also when staff save it), until the forms are submitted.', + access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, + body: z.object({ data: z.record(z.string(), z.unknown()) }), response: single(z.object({ message: z.string(), updatedAt: z.string() })), + async handler({ params, body, user, req }) { return { data: plain(await admin.saveFormDraft(callFrom(req, user, { params, body }))) }; }, +}); + +export const submitForms = defineRoute({ + method: 'post', path: '/registrations/:id/form-responses', tag: 'Registrations', summary: 'Submit attendee forms', + description: 'One response per main ticket at most; each named attendee answers once. Tickets are issued once it\'s paid and the forms are in.', + access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, body: responsesBody, + response: single(z.looseObject({ message: z.string(), count: z.number().int().optional() })), + async handler({ params, body, user, req }) { return { data: plain(await admin.submitFormResponses(callFrom(req, user, { params, body }))) }; }, +}); + +export const replaceForms = defineRoute({ + method: 'put', path: '/registrations/:id/form-responses', tag: 'Registrations', summary: 'Replace the attendee forms', + description: 'Supervisors: every response on the registration is replaced by these.', + access: 'supervisor', campusScope: 'scopeEvent(registration)', middleware: [campusScope.scopeEvent({ resolve: 'registration' })], params: idParams, body: responsesBody, response: message, + async handler({ params, body, user, req }) { return { data: await admin.replaceFormResponses(callFrom(req, user, { params, body })) }; }, +}); + +// ─── Staff ─────────────────────────────────────────────────────────────────── + +export const list = defineRoute({ + method: 'get', path: '/registrations', tag: 'Registrations', summary: 'Every registration (staff)', + description: 'Newest first, for the events you may see. `unpaid=true` for ones still owing; `userId` for one person\'s.', + access: 'staff', campusScope: 'scopeList (listWhere)', + query: z.object({ + page: z.coerce.number().int().min(1).default(1), + limit: z.coerce.number().int().min(1).max(200).default(100).describe('At most 200'), + unpaid: z.enum(['true', 'false']).default('false'), + userId: id.optional(), + }), + response: z.object({ data: z.array(fullRegistration), meta: z.object({ page: z.number().int(), limit: z.number().int(), total: z.number().int(), pages: z.number().int() }) }), + async handler({ query, user, req }) { + const out = await admin.getRegistrations(callFrom(req, user, { query: { page: String(query.page), limit: String(query.limit), unpaid: query.unpaid === 'true' ? '1' : '', userId: query.userId } })); + return pageOf(plain(out.data), out.total, { page: out.page, limit: out.limit }); + }, +}); + +export const forEvent = defineRoute({ + method: 'get', path: '/events/:id/registrations', tag: 'Registrations', summary: 'An event\'s registrations', + description: 'Oldest first, with tickets, payments and attendees. `search` matches the name, email or phone.', + access: 'staff', campusScope: 'scopeEvent(view)', middleware: [campusScope.scopeEvent()], params: idParams, + query: z.object({ search: z.string().max(200).optional() }), + response: z.object({ data: z.array(fullRegistration) }), + async handler({ params, query, user, req }) { return { data: plain(await admin.getRegistrationsByEvent(callFrom(req, user, { params: { eventId: params.id }, query }))) }; }, +}); + +export const setStatus = defineRoute({ + method: 'patch', path: '/registrations/:id/status', tag: 'Registrations', summary: 'Set a registration\'s status', + description: 'Staff. `paid` issues and sends the tickets; leaving `paid` withdraws unused tickets (refused once one has been scanned); `cancelled` frees its places for the waitlist.', + access: 'staff', campusScope: 'scopeEvent(registration)', middleware: [campusScope.scopeEvent({ resolve: 'registration' })], params: idParams, + body: z.object({ status: z.enum(STATUSES) }), response: single(fullRegistration), + async handler({ params, body, user, req }) { return { data: plain(await admin.updateRegistrationStatus(callFrom(req, user, { params, body }))) }; }, +}); + +export const manual = defineRoute({ + method: 'post', path: '/registrations/manual', tag: 'Registrations', summary: 'Register someone (at the door, by phone)', + description: [ + 'Supervisors. Finds the person by email or phone (refused when those are two different accounts) or makes an account and sends them an activation link (`skipActivationNotice` to not).', + 'Added to their existing registration for the event if they have one. Free ones are marked paid and get their tickets; otherwise they\'re sent a link to pay.', + ].join('\n\n'), + access: 'supervisor', campusScope: 'scopeEvent(body.eventId)', middleware: [campusScope.scopeEvent({ from: req => req.body?.eventId })], status: 201, + body: z.looseObject({ + eventId: id, + options: z.array(lineBody).min(1).max(100), + user: z.looseObject({ name: z.string().trim().min(1).max(200), email: z.string().max(200).nullish(), phoneNumber: z.string().max(40).nullish(), password: z.string().max(200).optional().describe('Self-service kiosk: the visitor sets it, and the account is active at once') }), + notificationPreference: z.string().max(20).nullish().describe('email, whatsapp or both (anything else: worked out from the contact details given)'), + skipActivationNotice: z.boolean().optional(), + couponCode: z.string().max(40).nullish(), + attendees: z.array(attendeeBody).max(1000).optional(), + ticketDelivery: z.enum(['payer', 'each']).optional(), + }), + response: single(fullRegistration.extend({ couponError: z.string().optional() })), + async handler({ body, user, req }) { return { data: plain(await admin.createManualRegistration(callFrom(req, user, { body }))) }; }, +}); + +export const bulk = defineRoute({ + method: 'post', path: '/registrations/bulk', tag: 'Registrations', summary: 'Do one thing to many registrations', + description: '`markPaid`, `cancel`, `moveOption`, `allocate` or `message`, for up to 500 you may manage. Each is done on its own: the answer lists what worked and what didn\'t.', + access: 'supervisor', campusScope: 'scopeBody(registrationIds, deny orphans)', middleware: [campusScope.scopeBody([['registrationIds', 'registration']], { orphan: 'deny' })], + body: z.looseObject({ action: z.enum(['markPaid', 'cancel', 'moveOption', 'allocate', 'message']), registrationIds: z.array(id).min(1).max(500) }), + response: single(z.looseObject({})), + async handler({ body, req }) { + const { runBulk } = require('../../utils/bulkRegistrations') as { runBulk(req: unknown, body: object): Promise }; + return { data: plain(await runBulk(req, body)) }; + }, +}); diff --git a/backend/tests/v2.test.ts b/backend/tests/v2.test.ts index 3ed4a0e..803e978 100644 --- a/backend/tests/v2.test.ts +++ b/backend/tests/v2.test.ts @@ -82,6 +82,10 @@ jest.mock('../src/services/deals', () => Object.fromEntries(Object.keys(mockDeal const mockCampuses = { publicCampuses: jest.fn(), campusBySlug: jest.fn(), adminCampuses: jest.fn(), setCampusesEnabled: jest.fn(), createCampus: jest.fn(), updateCampus: jest.fn(), reorderCampuses: jest.fn(), deleteCampus: jest.fn(), campusAudience: jest.fn() }; jest.mock('../src/services/campuses', () => Object.fromEntries(Object.keys(mockCampuses).map(k => [k, (...a: unknown[]) => (mockCampuses as Record)[k](...a)]))); +const mockAdmin = { getRegistrations: jest.fn(), getUserRegistrations: jest.fn(), getRegistrationById: jest.fn(), updateRegistrationStatus: jest.fn(), getRegistrationsByEvent: jest.fn(), createManualRegistration: jest.fn(), updateRegistrationOptions: jest.fn(), submitFormResponses: jest.fn(), replaceFormResponses: jest.fn(), getFormDraft: jest.fn(), saveFormDraft: jest.fn(), sendInvoice: jest.fn(), applyCoupon: jest.fn(), removeCoupon: jest.fn(), updateAttendees: jest.fn(), sendAttendeeFormLink: jest.fn() }; +jest.mock('../src/services/registrationAdmin', () => Object.fromEntries(Object.keys(mockAdmin).map(k => [k, (...a: unknown[]) => (mockAdmin as Record)[k](...a)]))); +jest.mock('../src/utils/seasonPass', () => ({ notOnSeasonPass: (_req: unknown, _res: unknown, next: () => void) => next() })); + import { v2Router } from '../src/v2'; import { ServiceError } from '../src/services/errors'; import { routes } from '../src/v2/route'; @@ -602,3 +606,54 @@ describe('series, deals and campuses', () => { expect((await request(app).put('/api/v2/campuses/enabled').send({ enabled: true })).status).toBe(403); }); }); + +describe('managing registrations', () => { + const reg = { id: 'r1', status: 'pending', eventId: 'e1', userId: 'u1', totalDueComputed: 150, payments: [] }; + + test('a guest with the link can read a registration in full', async () => { + mockAdmin.getRegistrationById.mockResolvedValue(reg); + const res = await request(app).get('/api/v2/registrations/r1/full'); + expect(res.status).toBe(200); + expect(res.body.data).toMatchObject({ id: 'r1', totalDueComputed: 150, payments: [] }); + expect(mockAdmin.getRegistrationById.mock.calls[0][0]).toMatchObject({ actor: null, params: { id: 'r1' } }); + }); + + test('the staff list is paged and campus-scoped', async () => { + signedIn = { id: 'u1', role: 'user' }; + expect((await request(app).get('/api/v2/registrations')).status).toBe(403); + signedIn = { id: 's1', role: 'staff' }; + mockAdmin.getRegistrations.mockResolvedValue({ data: [reg], total: 1, page: 1, limit: 100, pages: 1 }); + const res = await request(app).get('/api/v2/registrations?unpaid=true'); + expect(res.body).toEqual({ data: [reg], meta: { page: 1, limit: 100, total: 1, pages: 1 } }); + const call = mockAdmin.getRegistrations.mock.calls[0][0]; + expect(call.query).toMatchObject({ unpaid: '1', page: '1', limit: '100' }); + expect(typeof call.listWhere).toBe('function'); + }); + + test('a status must be one of the five', async () => { + signedIn = { id: 's1', role: 'staff' }; + const res = await request(app).patch('/api/v2/registrations/r1/status').send({ status: 'refunded' }); + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('VALIDATION_FAILED'); + expect(mockAdmin.updateRegistrationStatus).not.toHaveBeenCalled(); + }); + + test('registering someone at the door is for supervisors, and answers 201', async () => { + const body = { eventId: 'e1', options: [{ eventOptionId: 'o1', quantity: 2 }], user: { name: 'Thandi', phoneNumber: '0821234567' } }; + signedIn = { id: 's1', role: 'staff' }; + expect((await request(app).post('/api/v2/registrations/manual').send(body)).status).toBe(403); + signedIn = { id: 'v1', role: 'supervisor' }; + mockAdmin.createManualRegistration.mockResolvedValue(reg); + const res = await request(app).post('/api/v2/registrations/manual').send(body); + expect(res.status).toBe(201); + expect(mockAdmin.createManualRegistration.mock.calls[0][0].body).toMatchObject(body); + }); + + test("a refusal keeps the service's status", async () => { + signedIn = { id: 'u1', role: 'user' }; + mockAdmin.updateRegistrationOptions.mockRejectedValueOnce(new ServiceError(400, 'Cannot reduce items below the amount already paid')); + const res = await request(app).put('/api/v2/registrations/r1/items').send({ options: [{ eventOptionId: 'o1', quantity: 1 }] }); + expect(res.status).toBe(400); + expect(res.body.error).toMatchObject({ code: 'VALIDATION_FAILED', message: 'Cannot reduce items below the amount already paid' }); + }); +}); diff --git a/docs/HANDOVER.md b/docs/HANDOVER.md index 8a2653d..ca0f50b 100644 --- a/docs/HANDOVER.md +++ b/docs/HANDOVER.md @@ -1,6 +1,6 @@ # Handover — where things stand and how to carry on -Last updated: 2026-10-29, after **1.51.9** (and Hub 1.5.0). The plan itself is in +Last updated: 2026-10-29, after **1.51.10** (and Hub 1.5.0). The plan itself is in [ROADMAP-v2.md](./ROADMAP-v2.md) (decisions table at the end); the previous round of features is in [FEATURES-ROUND-1.md](./FEATURES-ROUND-1.md). @@ -17,6 +17,7 @@ encrypted settings unreadable or break existing installs. | 1.51.3 | **Express 5** (qs query parser and `req.body = {}` kept); scanner and at-the-door on v2 check-in; shared middleware answers v2-shaped on `/api/v2` (`legacyErrorsToV2`, `reason`); v1 `Deprecation` + `successor-version` headers (`src/v2/deprecation.ts`) | | 1.51.2 | **v2 accounts and check-in**: signup, login (+ code step), `PATCH /me`; check-in look-up and scan with `outcome`s. `src/services/auth.ts` (from userController) and `src/services/checkin.ts` (from ticketController); login/signup/profile pages on v2 | | 1.51.1 | **v2 registrations and payments**: register, get, cancel, checkout; create/cancel moved to `src/services/registrations.ts`, online checkout to `src/services/payments.ts` (v1 uses them too); typed frontend calls (`apiV2`, `npm run api:types`); register page, Pay now and My Events cancel on v2 | +| 1.51.10 | **Managing registrations on v2** — `src/services/registrationAdmin.ts` (the rest of `registrationController.js`); frontend `fetchAllRegistrations()`; money split out to 1.51.11 | | 1.51.9 | **Series, season passes, bundles, coupons, campuses on v2** — `src/services/series.ts`, `deals.ts`, `campuses.ts`; `reason` on v2 errors from service codes; frontend `apiV2Data()` | | 1.51.8 | **Rest of event set-up on v2**: event in full, calendar, alias, ticket options and variants, attachments, sections, costs, image uploads — `src/services/eventDetails.ts`, `src/services/setup.ts`; frontend `fetchEvent()` and `lib/eventSetup.ts`; v2 `file` and `upload` routes | | 1.51.7 | **Setting events up on v2** (`/events/manage`, create, `PATCH`, deactivate, copy-from, notify-recipients) via `src/services/events.ts`; `fetchManagedEvents()` for every picker; **pg-boss 11** in schema `pgboss_v11` | @@ -69,8 +70,8 @@ encrypted settings unreadable or break existing installs. Hub 1.1.0 is deployed with update requests rolled out, and `scripts/install.sh` has been tried on a test server (both done 2026-10-28). -1. **1.51.10 – 1.51.15: every endpoint onto v2**, one area per release (roadmap build order, row - 11b): services in TS, screens on `apiV2`, v1 routes into `SUCCESSORS`. 1.51.15 gives incoming +1. **1.51.11 – 1.51.16: every endpoint onto v2**, one area per release (roadmap build order, row + 11b): services in TS, screens on `apiV2`, v1 routes into `SUCCESSORS`. 1.51.16 gives incoming webhooks and links in sent messages v2 URLs, with the v1 paths still answering (links redirect, webhooks handled by the same code). Then **2.0.0** — AI helpers and v1 removed. 2. **Servers run Node 24** (Joshua, 2026-10-29), so the backend may need Node 22+. Still to do: @@ -467,6 +468,18 @@ a test server (both done 2026-10-28). `fetchAllUsers` (Payments, Email/WhatsApp attendees, Forms, Manual) — a server-side search picker would replace them; the coupons list; `GET /api/registrations` without `page` (other callers still use the plain array). +## Managing registrations on v2 (1.51.10) + +- **`registrationAdmin.ts` takes a `Call`** — `{ actor, params, body, query, readOnly, ip, listWhere }` + — and returns what v1 answered, because these handlers were moved nearly as they were (about + 1,400 lines). v1 builds it with `callOf(req)`, v2 with `callFrom(req, user, parts)` in + `resources/registrationsManage.ts`. Lists that are campus-scoped call `call.listWhere()`, which + refuses (500) when a caller didn't give one, so nothing is listed unscoped by mistake. +- Errors a JS helper throws without a status were 400s on v1; `as400` keeps them 400 on v2 + (TypeErrors and the like stay 500s). +- The staff list is paged on v2 (up to 200 a page); screens that need everything use + `fetchAllRegistrations(token, { unpaid?, userId? })`. + ## Series, deals and campuses on v2 (1.51.9) - **`apiV2Data(method, path, opts)`** (`lib/apiV2.ts`) returns `data` untyped for screens that keep @@ -486,7 +499,7 @@ a test server (both done 2026-10-28). send a file; `upload: { field, description }` documents a multipart body (the multer step goes in `middleware`; check `req.multerError`/`req.file` in the handler). - `eventController.js` still holds the public list (`getEvents`), the admin list and the attendee - email/WhatsApp senders (messaging, 1.51.13). + email/WhatsApp senders (messaging, 1.51.14). ## Setting events up on v2 (1.51.7) diff --git a/docs/ROADMAP-v2.md b/docs/ROADMAP-v2.md index bc15fe0..ef7b0bf 100644 --- a/docs/ROADMAP-v2.md +++ b/docs/ROADMAP-v2.md @@ -42,8 +42,8 @@ pass** shipped. 1.50.1 **pagination and search on long lists** and 1.50.2 **even foundations**, 1.51.1 **v2 registrations and payments**, 1.51.2 **v2 accounts and check-in** and 1.51.3 **Express 5, scanner on v2, v1 deprecation headers** shipped. 1.51.4 **security and dependency updates**, 1.51.5 **Next.js 16** and 1.51.6 **the complete command palette and ExcelTS** , 1.51.7 **setting events up on v2, pg-boss 11** and 1.51.8 **the rest of event set-up on v2** and 1.51.9 -**series, passes, deals and campuses on v2** shipped. **Next: 1.51.10 – 1.51.15 (every endpoint onto v2), -then 2.0.0.** +**series, passes, deals and campuses on v2** and 1.51.10 **managing registrations on v2** shipped. **Next: 1.51.11 – +1.51.16 (every endpoint onto v2), then 2.0.0.** **Repositories:** @@ -1012,7 +1012,7 @@ income justify the hardware: | 9 | 1.47.0 ✅ – 1.47.3 ✅, 1.48.0 ✅ | Event series & cloning (1.47.0 clone, 1.47.1 series, 1.47.2 year-on-year reports, 1.47.3 season pass), Outbound webhooks (Wallet passes removed from scope) | Smaller, independent wins | | 10 | 1.49.0 ✅ – 1.49.2 ✅, 1.50.0 ✅, 1.50.1 ✅, 1.50.2 ✅ | Admin dashboard/Ctrl+K/bulk actions/saved filters, Accessibility pass, pagination and search on long lists, event picker and webhook guide (Afrikaans removed from scope) | Polish before the big release | | 11 | 1.51.0 ✅, 1.51.1 ✅, 1.51.2 ✅, 1.51.3 ✅ | TypeScript backend + OpenAPI + `/api/v2` alongside v1: 1.51.0 foundations (build, launcher, route declarations, errors, paging, OpenAPI at `/docs/v2`, first read endpoints); 1.51.1 registrations and payments as TS services, typed frontend calls; 1.51.2 check-in and accounts; 1.51.3 Express 5, the scanner on v2, v1 deprecation headers, v2-shaped shared middleware | The breaking-change groundwork | -| 11b | 1.51.4 ✅ – 1.51.9 ✅, 1.51.10 – 1.51.15 | **Every endpoint on v2 before 2.0** (decided 2026-10-29): 1.51.4 dependency audit and Node 24 LTS; 1.51.5 Next.js 16 and ESLint 10 (ESLint 9 is out of support); 1.51.6 the complete command palette and ExcelTS instead of exceljs; 1.51.7 setting events up (the staff list, create, change, deactivate, copy-from, notification recipients) and pg-boss 11; 1.51.8 the rest of event set-up (the event in full, ticket options and variants, attachments, sections, costs, uploads, calendar file, alias); 1.51.9 series, season passes, bundles, coupons and campuses; 1.51.10 registrations and money, staff side (manage registrations, payments, cashup, provider transactions, waitlist, sponsorship, consent, forms, feedback); 1.51.11 tickets and attendance, staff side (tickets, scan locks, attendance, allocations); 1.51.12 kids check-in and volunteer rosters; 1.51.13 people and messaging (users, WhatsApp, broadcasts, scheduled emails, automations, banner, saved filters, dashboard, stats, analytics, reports); 1.51.14 privacy and admin (privacy, admin, settings, setup, Hub, outbound webhooks, backups); 1.51.15 **incoming webhooks and links in sent messages**: Yoco, PayFast and WAWP webhooks and the links in emails and WhatsApp (unsubscribe, consent, ticket transfer, calendar feeds, waitlist offers) get v2 URLs — new messages and provider registrations use them, and the v1 paths keep answering (links by a 308 redirect to v2, provider webhooks handled by the same code, since providers may not follow a redirect on a POST). Each moves its area's logic into TS services, its screens onto `apiV2`, and its v1 routes into `SUCCESSORS` | 2.0 can then remove v1 | +| 11b | 1.51.4 ✅ – 1.51.10 ✅, 1.51.11 – 1.51.16 | **Every endpoint on v2 before 2.0** (decided 2026-10-29): 1.51.4 dependency audit and Node 24 LTS; 1.51.5 Next.js 16 and ESLint 10 (ESLint 9 is out of support); 1.51.6 the complete command palette and ExcelTS instead of exceljs; 1.51.7 setting events up (the staff list, create, change, deactivate, copy-from, notification recipients) and pg-boss 11; 1.51.8 the rest of event set-up (the event in full, ticket options and variants, attachments, sections, costs, uploads, calendar file, alias); 1.51.9 series, season passes, bundles, coupons and campuses; 1.51.10 managing registrations (the staff lists, status, at the door, bulk actions, items, coupons, attendees, attendee forms); 1.51.11 money, staff side (payments, cashup, provider transactions, waitlist, sponsorship, consent, form builder, feedback); 1.51.12 tickets and attendance, staff side (tickets, scan locks, attendance, allocations); 1.51.13 kids check-in and volunteer rosters; 1.51.14 people and messaging (users, WhatsApp, broadcasts, scheduled emails, automations, banner, saved filters, dashboard, stats, analytics, reports); 1.51.15 privacy and admin (privacy, admin, settings, setup, Hub, outbound webhooks, backups); 1.51.16 **incoming webhooks and links in sent messages**: Yoco, PayFast and WAWP webhooks and the links in emails and WhatsApp (unsubscribe, consent, ticket transfer, calendar feeds, waitlist offers) get v2 URLs — new messages and provider registrations use them, and the v1 paths keep answering (links by a 308 redirect to v2, provider webhooks handled by the same code, since providers may not follow a redirect on a POST). Each moves its area's logic into TS services, its screens onto `apiV2`, and its v1 routes into `SUCCESSORS` | 2.0 can then remove v1 | | 12 | **2.0.0** | **AI helpers** (§15 — headline feature: draft an event, summarise reports and feedback, draft messages, improve text; through the Hub with a rand cap per licence), v1 removed (all of it is on v2 by then; the old webhook URLs and links already sent in messages keep forwarding to v2), migration guide, marketing site/docs for selling | The release. AI needs the Hub (phase 6) for the key, metering and caps | Each phase should add matching help content (`frontend/src/content/help/`), @@ -1050,7 +1050,7 @@ feature. | — | AI in 2.0 | The **headline feature of 2.0**: one-button helpers only (draft an event, summarise reports and feedback, draft messages, improve text) — no chat yet (2026-10-24) | | — | AI provider and key | One provider, **Claude** (Haiku 5.5 to start, for cost). Joshua provides the key; installs call AI **through the Hub**, which holds the key and meters usage (2026-10-24) | | — | AI cost limits | A **monthly rand cap per install**, set in the Hub per licence to match what the church pays; admins see their usage in Site settings → AI (2026-10-24) | -| — | v1 in 2.0 | **Every endpoint moves to v2 before 2.0** (1.51.7 – 1.51.15, by area), then 2.0 removes v1. Changed the same day from "retire only what's replaced". Incoming webhooks (Yoco, PayFast, WAWP) and links in emails and WhatsApp (unsubscribe, consent, ticket transfer, calendar feeds) also get v2 URLs (1.51.15); their v1 paths keep working — links redirect (308) to v2, provider webhooks are handled by the same code — because old messages and provider registrations still use them (2026-10-29) | +| — | v1 in 2.0 | **Every endpoint moves to v2 before 2.0** (1.51.7 – 1.51.16, by area), then 2.0 removes v1. Changed the same day from "retire only what's replaced". Incoming webhooks (Yoco, PayFast, WAWP) and links in emails and WhatsApp (unsubscribe, consent, ticket transfer, calendar feeds) also get v2 URLs (1.51.16); their v1 paths keep working — links redirect (308) to v2, provider webhooks are handled by the same code — because old messages and provider registrations still use them (2026-10-29) | | — | AI buttons and markup | AI buttons show only when the licence's monthly cap is **above R0**. When the cap is reached they stay visible but **disabled** until next month or until the cap is raised. Usage is charged at the real cost **plus a markup %** set in the Hub (a default, plus an override per licence). The markup covers small overruns and is the profit. The cap is counted in charged rand, and each call is checked against its worst-case cost before it's sent (2026-10-29) | | — | AI later | Ask AI (read-only, tools only), help/navigation assistant, actions with confirmation, more helpers, and long-term **self-hosted** AI behind the same Hub endpoint — not tied to versions (2026-10-24) | | — | POPIA: message kinds | Bulk messages are either **Event updates** (to registrants — still sent after unsubscribing) or **News & announcements** (marketing — opt-in, one-click unsubscribe). Every bulk email links to the preferences (2026-10-23) | diff --git a/e2e/api-v2.spec.ts b/e2e/api-v2.spec.ts index 07b5994..07b4e5a 100644 --- a/e2e/api-v2.spec.ts +++ b/e2e/api-v2.spec.ts @@ -183,6 +183,39 @@ test.describe("API v2", () => { expect((await request.get(`${API}/api/v2/campuses/admin`, { headers: sup })).status()).toBe(403); }); + test("staff register someone at the door and manage the registration", async ({ request }) => { + const sup = { Authorization: `Bearer ${seed().users.supervisor.token}` }; + const admin = { Authorization: `Bearer ${seed().users.admin.token}` }; + const ev = (await (await request.get(`${API}/api/v2/events/${seed().events.conference}/full`)).json()).data; + const opt = ev.eventOptions[0]; + + const made = await request.post(`${API}/api/v2/registrations/manual`, { + headers: sup, + data: { eventId: ev.id, options: [{ eventOptionId: opt.id, quantity: 1 }], user: { name: "E2E Door Guest", email: "e2e-v2-door@example.com" }, skipActivationNotice: true }, + }); + expect(made.status()).toBe(201); + const reg = (await made.json()).data; + expect(reg).toMatchObject({ eventId: ev.id, status: expect.any(String) }); + + const list = (await (await request.get(`${API}/api/v2/events/${ev.id}/registrations?search=e2e-v2-door`, { headers: sup })).json()).data; + expect(list.map((r: { id: string }) => r.id)).toContain(reg.id); + + const full = (await (await request.get(`${API}/api/v2/registrations/${reg.id}/full`, { headers: sup })).json()).data; + expect(full.registrationOptions[0]).toMatchObject({ eventOptionId: opt.id, quantity: 1 }); + + const bad = await request.patch(`${API}/api/v2/registrations/${reg.id}/status`, { headers: sup, data: { status: "refunded" } }); + expect(bad.status()).toBe(400); + expect((await bad.json()).error.code).toBe("VALIDATION_FAILED"); + + const page = await (await request.get(`${API}/api/v2/registrations?limit=2`, { headers: sup })).json(); + expect(page.meta).toMatchObject({ page: 1, limit: 2 }); + expect(page.data.length).toBeLessThanOrEqual(2); + + // Tidy up: cancelled registrations don't count towards anything. + const cancelled = await request.post(`${API}/api/v2/registrations/${reg.id}/cancel`, { headers: admin }); + expect((await cancelled.json()).data.status).toBe("cancelled"); + }); + test("an admin can read the OpenAPI reference at /docs/v2", async ({ page, request }) => { const headers = { Authorization: `Bearer ${seed().users.user.token}` }; expect((await request.get(`${API}/api/v2/openapi.json`, { headers })).status()).toBe(403); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 0036e43..13c6479 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "hope-events-frontend", - "version": "1.51.9", + "version": "1.51.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "hope-events-frontend", - "version": "1.51.9", + "version": "1.51.10", "dependencies": { "@dnd-kit/core": "^6.3.1", "@hookform/resolvers": "^5.2.1", diff --git a/frontend/package.json b/frontend/package.json index ba13bd0..9335061 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "hope-events-frontend", - "version": "1.51.9", + "version": "1.51.10", "private": true, "scripts": { "dev": "next dev", diff --git a/frontend/src/app/dashboard/admin/registrations/page.tsx b/frontend/src/app/dashboard/admin/registrations/page.tsx index 60b9a78..87e1811 100644 --- a/frontend/src/app/dashboard/admin/registrations/page.tsx +++ b/frontend/src/app/dashboard/admin/registrations/page.tsx @@ -3,7 +3,7 @@ import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; -import { apiFetch, fetchManagedEvents } from "@/lib/api"; +import { apiFetch, fetchManagedEvents, fetchAllRegistrations } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { ClipboardList } from "lucide-react"; import { errorMessage } from "@/lib/utils"; @@ -12,6 +12,7 @@ import { BackLink } from "@/components/shared/BackLink"; import { RegistrationBulkBar } from "@/components/admin/RegistrationBulkBar"; import { SavedFilters } from "@/components/shared/SavedFilters"; import { EventPicker } from "@/components/shared/EventPicker"; +import { apiV2Data } from "@/lib/apiV2"; const STATUS_OPTIONS = ["pending", "confirmed", "partial_paid", "paid", "cancelled"] as const; @@ -80,7 +81,7 @@ export default function AdminRegistrationsPage() { if (!token) return; try { setLoadingRegs(true); - const regs = await apiFetch("/api/registrations", { authToken: token }); + const regs = await fetchAllRegistrations(token); const list = Array.isArray(regs) ? regs.sort((a, b) => { const eventCompare = (a.event?.startDate || a.eventId).localeCompare(b.event?.startDate || b.eventId); if (eventCompare !== 0) return eventCompare; @@ -140,7 +141,7 @@ export default function AdminRegistrationsPage() { setError(null); setInfo(null); if (!confirm(`Cancel registration #${String(reg.id).slice(0, 8)} for ${reg.user?.name || reg.userId}?`)) return; try { - await apiFetch(`/api/registrations/${encodeURIComponent(reg.id)}`, { method: "DELETE", authToken: token }); + await apiV2Data("post", "/registrations/{id}/cancel", { params: { id: reg.id }, authToken: token }); setInfo("Registration cancelled"); await loadRegistrations(); } catch (e) { @@ -152,7 +153,7 @@ export default function AdminRegistrationsPage() { if (!token) return; setError(null); setInfo(null); try { - await apiFetch(`/api/registrations/${encodeURIComponent(reg.id)}`, { method: "PUT", authToken: token, body: { status } }); + await apiV2Data("patch", "/registrations/{id}/status", { params: { id: reg.id }, authToken: token, body: { status: status as "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled" } }); setInfo("Status updated"); await loadRegistrations(); } catch (e) { diff --git a/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx b/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx index c87b778..95eb7d3 100644 --- a/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx +++ b/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx @@ -19,7 +19,7 @@ import { bookableSessions, choosesSessions, isPickOption, todaysSession } from " import { SessionPicker } from "@/components/events/SessionPicker"; import type { Event, EventOption, PublicBundle, Registration, Ticket as TicketRecord, UserSummary } from "@/types"; import { EventPicker } from "@/components/shared/EventPicker"; -import { apiV2 } from "@/lib/apiV2"; +import { apiV2, apiV2Data } from "@/lib/apiV2"; type NewAttendee = { name: string; email: string | null; phone: string | null; notifPref: "email" | "whatsapp" | "both" }; @@ -265,20 +265,20 @@ export default function AtTheDoorPage() { try { if (pendingEditReg) { // Edit existing registration — replace options via PUT - let res = await apiFetch(`/api/registrations/${pendingEditReg.id}/options`, { - method: "PUT", - authToken: token, - body: { options: opts } - }); + let res = await (apiV2Data("put", "/registrations/{id}/items", { + params: { id: pendingEditReg.id }, + authToken: token, + body: { options: opts }, + }) as Promise); let message = "Registration updated"; if (doorCoupon) { // Applied after the items are saved, so it's worked out on the final items. try { - res = await apiFetch(`/api/registrations/${pendingEditReg.id}/coupon`, { - method: "POST", - authToken: token, - body: { code: doorCoupon.code }, - }); + res = await (apiV2Data("post", "/registrations/{id}/coupon", { + params: { id: pendingEditReg.id }, + authToken: token, + body: { code: doorCoupon.code }, + }) as Promise); message = `Registration updated — code ${doorCoupon.code} applied`; } catch (ce) { message = `Registration updated, but the code wasn't applied: ${errorMessage(ce) || "unknown error"}`; @@ -290,10 +290,9 @@ export default function AtTheDoorPage() { handleRegistrationSelected(res); } else if (pendingUser) { // New attendee - const res = await apiFetch("/api/registrations/manual", { - method: "POST", - authToken: token, - body: { + const res = await (apiV2Data("post", "/registrations/manual", { + authToken: token, + body: { eventId, user: { name: pendingUser.name, @@ -306,8 +305,8 @@ export default function AtTheDoorPage() { ...(doorAllowsNames && (doorNaming || doorYouthStart) && attendeesPayload(nameOptions, (o, v) => quantities[v ? `${o}::${v}` : o] || 0, doorEntries).length > 0 ? { attendees: attendeesPayload(nameOptions, (o, v) => quantities[v ? `${o}::${v}` : o] || 0, doorEntries), ticketDelivery: doorDelivery } : {}), - } - }); + }, + }) as Promise); setShowOptionsModal(false); if (res?.couponError) setError(`Registered, but the code wasn't applied: ${res.couponError}`); handleRegistrationCreated(res); @@ -360,7 +359,7 @@ export default function AtTheDoorPage() { const handleEditRegistration = async (reg: Registration) => { let freshReg = reg; try { - freshReg = await apiFetch(`/api/registrations/${reg.id}`, { authToken: token }); + freshReg = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: reg.id }, authToken: token }) as Promise); } catch (e) { setError(errorMessage(e) || "Failed to load latest registration data"); return; @@ -575,7 +574,7 @@ function DoorRegistrationPanel({ token, eventId, onSelected, onEditRegistration, const load = async () => { try { setLoading(true); - const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }); + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: eventId }, authToken: token }) as Promise); if (!cancelled) setAllRegs(regs || []); } catch { if (!cancelled) setAllRegs([]); @@ -601,7 +600,7 @@ function DoorRegistrationPanel({ token, eventId, onSelected, onEditRegistration, if (!token || !eventId) return; try { setLoading(true); - const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }); + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: eventId }, authToken: token }) as Promise); setAllRegs(regs || []); } catch {} finally { setLoading(false); } }} @@ -715,9 +714,10 @@ function DoorPaymentPanel({ token, registration, onSuccess, setError }: { } }); - const updated = await apiFetch(`/api/registrations/${registration.id}`, { - authToken: token - }); + const updated = await (apiV2Data("get", "/registrations/{id}/full", { + params: { id: registration.id }, + authToken: token, + }) as Promise); const updatedBalance = Math.max(0, registrationTotal(updated) - totalPaidOn(updated)); @@ -1677,7 +1677,7 @@ function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded } }); // Re-fetch registration to get updated status & payments - const updated = await apiFetch(`/api/registrations/${registration.id}`, { authToken: token }); + const updated = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: registration.id }, authToken: token }) as Promise); onRefunded(updated); } catch (e) { setLocalError(errorMessage(e) || "Refund failed."); @@ -1778,7 +1778,7 @@ function DoorRefundPanel({ token, eventId, setInfo }: { if (!token || !eventId) return; try { setLoading(true); - const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }); + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: eventId }, authToken: token }) as Promise); setAllRegs(regs || []); } catch { setAllRegs([]); @@ -1800,7 +1800,7 @@ function DoorRefundPanel({ token, eventId, setInfo }: { setSelectedReg(updated); setInfo("Refund recorded"); // Refresh list - const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }).catch(() => null); + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: eventId }, authToken: token }) as Promise).catch(() => null); if (regs) setAllRegs(regs); }; diff --git a/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx b/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx index 66cba80..2d28727 100644 --- a/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx +++ b/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx @@ -13,6 +13,7 @@ import { BackLink } from "@/components/shared/BackLink"; import { MessageKindPicker, matchedText, type MessageKind } from "@/components/shared/MessageKindPicker"; import { CampusAudiencePicker } from "@/components/shared/CampusAudiencePicker"; import { EventPicker } from "@/components/shared/EventPicker"; +import { apiV2Data } from "@/lib/apiV2"; type Attendee = { id: string; name: string; email: string; pref: string }; type TemplateKey = 'custom'|'payment_reminder'|'event_reminder'|'tickets'; @@ -390,7 +391,7 @@ function EmailAttendeesPageInner() { setAttendees([]); setSelectedAttendeeIds([]); if (!eventId || !token) return; - const regs = await apiFetch(`/api/registrations/event/${encodeURIComponent(eventId)}`, { authToken: token }); + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: eventId }, authToken: token }) as Promise); const uniq = new Map(); (regs || []).forEach((r) => { const u: User | undefined = r?.user; diff --git a/frontend/src/app/dashboard/supervisor/forms/page.tsx b/frontend/src/app/dashboard/supervisor/forms/page.tsx index c6f0984..c3dc341 100644 --- a/frontend/src/app/dashboard/supervisor/forms/page.tsx +++ b/frontend/src/app/dashboard/supervisor/forms/page.tsx @@ -11,7 +11,7 @@ import { errorMessage } from "@/lib/utils"; import type { Event, EventForm, FormResponse, Registration, User } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; -import { apiV2 } from "@/lib/apiV2"; +import { apiV2, apiV2Data } from "@/lib/apiV2"; type FormFieldType = 'yes_no' | 'text' | 'date' | 'numeric' | 'statement' | 'paragraph' | 'rating' | 'multiple_choice'; @@ -350,7 +350,7 @@ export default function FormsBrowserPage() { if (!token || !evId) return; try { setLoadingRegs(true); - const regs = await apiFetch(`/api/registrations/event/${encodeURIComponent(evId)}`, { authToken: token }); + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: evId }, authToken: token }) as Promise); const sorted = (Array.isArray(regs) ? regs : []).sort((a, b) => (a.user?.name || '').toLowerCase().localeCompare((b.user?.name || '').toLowerCase())); setFillRegistrations(sorted); } catch { @@ -374,7 +374,7 @@ export default function FormsBrowserPage() { (async () => { if (mode !== 'fill' || !fillRegistrationId) return; try { - const reg = await apiFetch(`/api/registrations/${encodeURIComponent(fillRegistrationId)}`, { authToken: token! }); + const reg = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: fillRegistrationId }, authToken: token }) as Promise); setFillRegistration(reg); if (reg?.event?.id) { const evFull = await fetchEvent(reg.event.id); @@ -435,8 +435,10 @@ export default function FormsBrowserPage() { if (v == null || String(v).trim() === '') throw new Error(`Response #${i+1}: Missing answer for a required field`); } } - await apiFetch(`/api/registrations/${encodeURIComponent(fillRegistrationId)}/forms/responses`, { - method: 'PUT', authToken: token, body: { responses: editableResponses } + await apiV2Data("put", "/registrations/{id}/form-responses", { + params: { id: fillRegistrationId }, + authToken: token, + body: { responses: editableResponses }, }); setInfo('Responses saved'); const resList = await apiFetch<{ items?: FormResponse[] } | FormResponse[]>(`/api/forms/responses?registrationId=${encodeURIComponent(fillRegistrationId)}`, { authToken: token! }); diff --git a/frontend/src/app/dashboard/supervisor/manual-registration/page.tsx b/frontend/src/app/dashboard/supervisor/manual-registration/page.tsx index 40c6414..30b50a2 100644 --- a/frontend/src/app/dashboard/supervisor/manual-registration/page.tsx +++ b/frontend/src/app/dashboard/supervisor/manual-registration/page.tsx @@ -4,12 +4,13 @@ import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormField import React, { useEffect, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; -import { apiFetch, fetchEvent } from "@/lib/api"; +import { fetchEvent } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { UserPlus } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Registration } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; +import { apiV2Data } from "@/lib/apiV2"; type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown }; @@ -39,15 +40,14 @@ export default function ManualRegistrationPage() { setBusy(true); setError(null); try { - const res = await apiFetch("/api/registrations/manual", { - method: "POST", + const res = await (apiV2Data("post", "/registrations/manual", { authToken: token, body: { eventId, options: [{ eventOptionId: optionId, quantity }], user: { name, ...(email ? { email } : {}), ...(phoneNumber ? { phoneNumber } : {}) }, }, - }); + }) as Promise); setCreatedReg(res); // Load form definition for this event (if any) try { @@ -154,8 +154,10 @@ function AttendeeFormsSection({ registration, form, formsData, setFormsData }: { setError(null); setInfo(null); const payload: { answers: Record }[] = []; for (let i = 0; i < count; i++) payload.push({ answers: formsData[i] || {} }); - await apiFetch(`/api/registrations/${encodeURIComponent(registration.id)}/forms/responses`, { - method: 'POST', authToken: token, body: { responses: payload } + await apiV2Data("post", "/registrations/{id}/form-responses", { + params: { id: registration.id }, + authToken: token, + body: { responses: payload }, }); setInfo('Attendee forms submitted successfully.'); } catch (e) { diff --git a/frontend/src/app/dashboard/supervisor/manual/page.tsx b/frontend/src/app/dashboard/supervisor/manual/page.tsx index ea9f7d1..f43eaa2 100644 --- a/frontend/src/app/dashboard/supervisor/manual/page.tsx +++ b/frontend/src/app/dashboard/supervisor/manual/page.tsx @@ -3,7 +3,7 @@ import React, { useEffect, useMemo, useRef, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; -import { apiFetch, fetchAllUsers, fetchManagedEvents, fetchEvent } from "@/lib/api"; +import { apiFetch, fetchAllUsers, fetchManagedEvents, fetchEvent, fetchAllRegistrations } from "@/lib/api"; import { scoreUser } from "@/lib/fuzzyMatch"; import { useDismissingState } from "@/hooks/useDismissingState"; import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField"; @@ -17,6 +17,7 @@ import { SessionPicker } from "@/components/events/SessionPicker"; import type { Event, EventOption, PublicBundle, Registration, RegistrationOption, User } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; +import { apiV2Data } from "@/lib/apiV2"; // ─── Pricing helpers ───────────────────────────────────────────────────────── @@ -24,7 +25,7 @@ function fmtPrice(n: number) { return n === 0 ? "Free" : `R ${n.toFixed(2)}`; } -// Effective unit price for an existing registration option (as returned by /api/registrations). +// Effective unit price for an existing registration option (as returned by /api/v2/registrations). // Prefers priceSnapshot (authoritative price captured at registration time) and only falls // back to a live early-bird calculation for legacy rows without a snapshot. function optionUnitPrice(opt: RegistrationOption): number { @@ -103,7 +104,7 @@ export default function ManualRegistrationPage() { // balances can be computed without a per-registration fetch loop). useEffect(() => { if (!token) return; - apiFetch("/api/registrations", { authToken: token }) + fetchAllRegistrations(token) .then(regs => setAllRegistrations(Array.isArray(regs) ? regs : [])) .catch(() => {}); }, [token]); @@ -180,7 +181,7 @@ export default function ManualRegistrationPage() { setPayPaidAtLocal(""); // Refresh registrations so the displayed outstanding balance updates try { - const regs = await apiFetch("/api/registrations", { authToken: token }); + const regs = await fetchAllRegistrations(token); setAllRegistrations(Array.isArray(regs) ? regs : []); } catch {} } catch (e) { @@ -346,8 +347,7 @@ export default function ManualRegistrationPage() { const hasEmail = !!guest.email.trim(); const hasPhone = !!guest.phoneNumber.trim(); const resolvedPref = hasEmail && hasPhone ? notifPref : hasPhone ? "whatsapp" : "email"; - const res = await apiFetch("/api/registrations/manual", { - method: "POST", + const res = await (apiV2Data("post", "/registrations/manual", { authToken: token, body: { eventId: selectedEventId, @@ -358,8 +358,8 @@ export default function ManualRegistrationPage() { ...(selectedEventAllowsNames && (namingOthers || selectedIsYouth) && attendeesPayload(options, manualQtyFor, attendeeEntries).length > 0 ? { attendees: attendeesPayload(options, manualQtyFor, attendeeEntries), ticketDelivery: delivery } : {}), - } - }); + }, + }) as Promise); setMessage(res?.couponError ? `Manual registration created, but the code wasn't applied: ${res.couponError}` : coupon ? `Manual registration created with code ${coupon.code}.` : "Manual registration created successfully."); diff --git a/frontend/src/app/dashboard/supervisor/payments/page.tsx b/frontend/src/app/dashboard/supervisor/payments/page.tsx index 949db67..e2691ec 100644 --- a/frontend/src/app/dashboard/supervisor/payments/page.tsx +++ b/frontend/src/app/dashboard/supervisor/payments/page.tsx @@ -3,7 +3,7 @@ import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter, useSearchParams } from "next/navigation"; -import { apiFetch, fetchAllUsers, fetchAllPayments, fetchManagedEvents } from "@/lib/api"; +import { apiFetch, fetchAllUsers, fetchAllPayments, fetchManagedEvents, fetchAllRegistrations } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { scoreUser } from "@/lib/fuzzyMatch"; import { Wallet, RotateCcw, HandHeart, ScanLine, Link2 } from "lucide-react"; @@ -209,14 +209,14 @@ function PaymentsContent() { useEffect(() => { loadPayments(); }, [loadPayments]); - // Registrations still owing (not paid or cancelled), for the dropdowns. GET /api/registrations + // Registrations still owing (not paid or cancelled), for the dropdowns. GET /api/v2/registrations // embeds each registration's `payments`, so balances come from that in one pass. Refunds load // the chosen person's own registrations (including paid ones) when needed. const loadRegistrations = useCallback(async () => { if (!token) return; try { setLoadingRegs(true); - const regs = await apiFetch("/api/registrations?unpaid=1", { authToken: token }); + const regs = await fetchAllRegistrations(token, { unpaid: true }); const list = Array.isArray(regs) ? regs : []; setRegOutstanding(computeOutstanding(list)); // Sort by createdAt desc @@ -891,7 +891,7 @@ function RefundSection({ allUsers, onDone }: RefundSectionProps) { setLoadingUser(true); Promise.all([ fetchAllPayments(token, { userId }), - apiFetch(`/api/registrations?userId=${encodeURIComponent(userId)}`, { authToken: token }), + fetchAllRegistrations(token, { userId }), ]).then(([p, r]) => { if (cancelled) return; setPayments(p); diff --git a/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx b/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx index 267b8cd..b96198c 100644 --- a/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx +++ b/frontend/src/app/dashboard/supervisor/whatsapp-attendees/page.tsx @@ -13,6 +13,7 @@ import { BackLink } from "@/components/shared/BackLink"; import { MessageKindPicker, matchedText, type MessageKind } from "@/components/shared/MessageKindPicker"; import { CampusAudiencePicker } from "@/components/shared/CampusAudiencePicker"; import { EventPicker } from "@/components/shared/EventPicker"; +import { apiV2Data } from "@/lib/apiV2"; // Attendee with preference info type Attendee = { id: string; name: string; phone: string; pref: string }; @@ -426,7 +427,7 @@ function WhatsAppAttendeesPageInner() { try { setLoadingAttendees(true); setAttendees([]); setSelectedAttendeeIds([]); if (!eventId || !token) return; - const regs = await apiFetch(`/api/registrations/event/${encodeURIComponent(eventId)}`, { authToken: token }); + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: eventId }, authToken: token }) as Promise); const uniq = new Map(); (regs || []).forEach((r) => { const u: User | undefined = r?.user; diff --git a/frontend/src/app/dashboard/user/forms/page.tsx b/frontend/src/app/dashboard/user/forms/page.tsx index 0605e54..0d59bc7 100644 --- a/frontend/src/app/dashboard/user/forms/page.tsx +++ b/frontend/src/app/dashboard/user/forms/page.tsx @@ -3,12 +3,13 @@ import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormField import React, { Suspense, useEffect, useMemo, useState } from "react"; import { useSearchParams, useRouter } from "next/navigation"; import { useAuth } from "@/hooks/useAuth"; -import { apiFetch, fetchEvent } from "@/lib/api"; +import { fetchEvent } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { FileText } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Registration } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; +import { apiV2Data } from "@/lib/apiV2"; // Types for form fields type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown }; @@ -35,13 +36,13 @@ function FormsContent() { setError(null); setInfo(null); try { - const reg = await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token }); + const reg = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: registrationId }, authToken: token }) as Promise); setRegistration(reg); const ev = await fetchEvent<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(reg.eventId); if (ev?.form) setEventForm(ev.form); // Load any saved draft try { - const draft = await apiFetch<{ data?: Record> } | null>(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { authToken: token }); + const draft = await (apiV2Data("get", "/registrations/{id}/form-draft", { params: { id: registrationId }, authToken: token }) as Promise<{ data?: Record> } | null>); if (draft && draft.data && typeof draft.data === 'object') setFormsData(draft.data); } catch {} } catch (e) { @@ -99,14 +100,14 @@ function FormsContent() { setInfo('No remaining attendee forms to submit.'); return; } - await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/responses`, { - method: 'POST', + await apiV2Data("post", "/registrations/{id}/form-responses", { + params: { id: registrationId }, authToken: token, - body: { responses: payload } + body: { responses: payload }, }); setInfo('Attendee forms submitted successfully.'); // reload registration to reflect new responses - const reg = await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token }); + const reg = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: registrationId }, authToken: token }) as Promise); setRegistration(reg); setFormsData({}); // On success, redirect to the user dashbaord @@ -120,10 +121,10 @@ function FormsContent() { if (!token || !registrationId) return; try { setError(null); setInfo(null); - await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { - method: 'PUT', + await apiV2Data("put", "/registrations/{id}/form-draft", { + params: { id: registrationId }, authToken: token, - body: { data: formsData } + body: { data: formsData }, }); setInfo('Draft saved. You can return later to finish.'); } catch (e) { diff --git a/frontend/src/app/dashboard/user/page.tsx b/frontend/src/app/dashboard/user/page.tsx index e88ebdf..c49672c 100644 --- a/frontend/src/app/dashboard/user/page.tsx +++ b/frontend/src/app/dashboard/user/page.tsx @@ -2,7 +2,7 @@ import React, { useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { apiFetch, createFullPaymentCheckout, fetchEvent } from "@/lib/api"; -import { apiV2 } from "@/lib/apiV2"; +import { apiV2, apiV2Data } from "@/lib/apiV2"; import { useOnlinePayments } from "@/lib/onlinePayments"; import { useRouter } from "next/navigation"; import { formatDate } from "@/lib/date"; @@ -124,7 +124,7 @@ export default function UserDashboardPage() { // waterfalling — this was previously fetched only after registrations + all // their payments had already resolved. const [myRegs, myTicks] = await Promise.all([ - apiFetch(`/api/registrations/myregistrations?showPast=${showPast ? '1' : '0'}`, { authToken: token }), + (apiV2Data("get", "/me/registrations/full", { query: { past: showPast ? "true" : "false" }, authToken: token }) as Promise), apiFetch("/api/tickets/mytickets", { authToken: token }), ]); setRegistrations(myRegs); @@ -189,7 +189,7 @@ export default function UserDashboardPage() { return; } // Load registration to get number of submitted responses - const regFull = await apiFetch(`/api/registrations/${encodeURIComponent(r.id)}`, { authToken: token }); + const regFull = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: r.id }, authToken: token }) as Promise); const submittedCount = (regFull?.formResponses || []).length; // Required count equals the number of main tickets purchased const requiredCount = (r.registrationOptions || []) @@ -273,11 +273,11 @@ export default function UserDashboardPage() { loadingSubtitle: "Please wait while we prepare your invoice.", }); try { - const res = await apiFetch<{ message?: string }>(`/api/registrations/${encodeURIComponent(registrationId)}/send-invoice`, { - method: "POST", + const res = await (apiV2Data("post", "/registrations/{id}/invoice", { + params: { id: registrationId }, body: { channel }, authToken: token, - }); + }) as Promise<{ message?: string }>); setDialog({ open: true, loading: false, title: "Invoice sent", message: (res && res.message) || "Invoice sent." }); } catch (e) { setDialog({ open: false, message: "", loading: false }); @@ -332,7 +332,7 @@ export default function UserDashboardPage() { // Refresh this registration's billing so the displayed outstanding reflects the new price try { const now = new Date(); - const r = await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token }); + const r = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: registrationId }, authToken: token }) as Promise); const pays = await apiFetch(`/api/payments/registration/${encodeURIComponent(registrationId)}`, { authToken: token }); const totalPaid = pays.reduce((s, p) => s + (p.amount || 0), 0); const totalDue = (r.registrationOptions || []).reduce((sum, opt) => sum + registrationOptionUnitPrice(opt, null, now) * (opt.quantity || 0), 0); @@ -409,12 +409,12 @@ export default function UserDashboardPage() { setCodeBusy(true); setCodeError(null); try { - const res = await apiFetch<{ message?: string }>(`/api/registrations/${encodeURIComponent(activeRegId)}/coupon`, { - method: 'POST', + const res = await (apiV2Data("post", "/registrations/{id}/coupon", { + params: { id: activeRegId }, authToken: token, body: { code: codeInput.trim() }, - }); - const myRegs = await apiFetch(`/api/registrations/myregistrations?showPast=${showPast ? '1' : '0'}`, { authToken: token }); + }) as Promise<{ message?: string }>); + const myRegs = await (apiV2Data("get", "/me/registrations/full", { query: { past: showPast ? "true" : "false" }, authToken: token }) as Promise); setRegistrations(myRegs); const updated = myRegs.find(r => r.id === activeRegId); const pays = await apiFetch(`/api/payments/registration/${encodeURIComponent(activeRegId)}`, { authToken: token }); @@ -440,7 +440,7 @@ export default function UserDashboardPage() { const reloadAfterAttendees = async () => { if (!token) return; try { - const myRegs = await apiFetch(`/api/registrations/myregistrations?showPast=${showPast ? '1' : '0'}`, { authToken: token }); + const myRegs = await (apiV2Data("get", "/me/registrations/full", { query: { past: showPast ? "true" : "false" }, authToken: token }) as Promise); setRegistrations(myRegs); const myTicks = await apiFetch("/api/tickets/mytickets", { authToken: token }); setTickets(myTicks); @@ -456,7 +456,7 @@ export default function UserDashboardPage() { setCancelLoading(true); try { await apiV2("post", "/registrations/{id}/cancel", { params: { id: activeRegId }, authToken: token }); - const myRegs = await apiFetch(`/api/registrations/myregistrations?showPast=${showPast ? '1' : '0'}`, { authToken: token }); + const myRegs = await (apiV2Data("get", "/me/registrations/full", { query: { past: showPast ? "true" : "false" }, authToken: token }) as Promise); setRegistrations(myRegs); setActiveRegId(null); setShowCancelConfirm(false); @@ -593,13 +593,13 @@ export default function UserDashboardPage() { } setLoading(true); try { - await apiFetch(`/api/registrations/${encodeURIComponent(activeReg.id)}/options`, { - method: 'PUT', + await apiV2Data("put", "/registrations/{id}/items", { + params: { id: activeReg.id }, authToken: token, body: { options: payloadOptions }, }); // Reload registrations to reflect changes - const myRegs = await apiFetch(`/api/registrations/myregistrations?showPast=${showPast ? '1' : '0'}`, { authToken: token }); + const myRegs = await (apiV2Data("get", "/me/registrations/full", { query: { past: showPast ? "true" : "false" }, authToken: token }) as Promise); setRegistrations(myRegs); try { const myTicks = await apiFetch("/api/tickets/mytickets", { authToken: token }); diff --git a/frontend/src/app/forms/page.tsx b/frontend/src/app/forms/page.tsx index dd2e568..6533e48 100644 --- a/frontend/src/app/forms/page.tsx +++ b/frontend/src/app/forms/page.tsx @@ -3,12 +3,13 @@ import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormField import React, { Suspense, useEffect, useMemo, useState } from "react"; import { useSearchParams, useRouter } from "next/navigation"; import { useAuth } from "@/hooks/useAuth"; -import { apiFetch, fetchEvent } from "@/lib/api"; +import { fetchEvent } from "@/lib/api"; import { Navbar } from "@/components/layout/Navbar"; import { Footer } from "@/components/layout/Footer"; import { FileText } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Registration } from "@/types"; +import { apiV2Data } from "@/lib/apiV2"; // Types for form fields type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown }; @@ -40,13 +41,13 @@ function FormsContent() { setInfo(null); try { // authToken optional — guests access via registrationId alone - const reg = await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token || undefined }); + const reg = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: registrationId }, authToken: token }) as Promise); setRegistration(reg); const ev = await fetchEvent<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(reg.eventId); if (ev?.form) setEventForm(ev.form); // Load any saved draft to prefill fields try { - const draft = await apiFetch<{ data?: Record> } | null>(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { authToken: token || undefined }); + const draft = await (apiV2Data("get", "/registrations/{id}/form-draft", { params: { id: registrationId }, authToken: token }) as Promise<{ data?: Record> } | null>); if (draft && draft.data && typeof draft.data === 'object') setFormsData(draft.data); } catch {} } catch (e) { @@ -124,10 +125,10 @@ function FormsContent() { router.push(`/registration/success?registrationId=${encodeURIComponent(registrationId)}${totalDue>0?`&totalDue=${encodeURIComponent(totalDue.toFixed(2))}`:''}${donationParam}`); return; } - await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/responses`, { - method: 'POST', - authToken: token || undefined, - body: { responses: payload } + await apiV2Data("post", "/registrations/{id}/form-responses", { + params: { id: registrationId }, + authToken: token, + body: { responses: payload }, }); // On success, redirect to the success page const totalDue = (registration?.registrationOptions || []).reduce((s, ro) => s + ((ro.eventOption?.price || 0) * (ro.quantity || 0)), 0); @@ -141,10 +142,10 @@ function FormsContent() { if (!registrationId) return; try { setError(null); setInfo(null); - await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { - method: 'PUT', - authToken: token || undefined, - body: { data: formsData } + await apiV2Data("put", "/registrations/{id}/form-draft", { + params: { id: registrationId }, + authToken: token, + body: { data: formsData }, }); setInfo('Draft saved. You can come back and finish later.'); if (!token || !registrationId) return; diff --git a/frontend/src/app/registration/success/page.tsx b/frontend/src/app/registration/success/page.tsx index e989617..d00cf9e 100644 --- a/frontend/src/app/registration/success/page.tsx +++ b/frontend/src/app/registration/success/page.tsx @@ -8,6 +8,7 @@ import { CheckCircle2 } from "lucide-react"; import { useOnlinePayments } from "@/lib/onlinePayments"; import { errorMessage } from "@/lib/utils"; import type { Registration } from "@/types"; +import { apiV2Data } from "@/lib/apiV2"; type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown }; @@ -40,7 +41,7 @@ function RegistrationSuccessContent() { if (!registrationId) return; try { // Try to fetch registration and event form - const r = token ? await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token }) : null; + const r = token ? await (apiV2Data("get", "/registrations/{id}/full", { params: { id: registrationId }, authToken: token }) as Promise) : null; if (r) { setReg(r); const ev = await (await import('@/lib/api')).fetchEvent<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(r.eventId); @@ -95,7 +96,7 @@ function RegistrationSuccessContent() { // reload the registration so the displayed totalDue reflects it, instead of redirecting. setError(`${res.message || 'Pricing has changed.'} New total: R ${(res.newTotal ?? 0).toFixed(2)}. Please try again.`); try { - const r = await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token }); + const r = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: registrationId }, authToken: token }) as Promise); if (r) setReg(r); } catch {} return; diff --git a/frontend/src/app/self-service/page.tsx b/frontend/src/app/self-service/page.tsx index 74fe945..c8054df 100644 --- a/frontend/src/app/self-service/page.tsx +++ b/frontend/src/app/self-service/page.tsx @@ -13,6 +13,7 @@ import { choosesSessions, isPickOption } from "@/lib/sessions"; import { SessionPicker } from "@/components/events/SessionPicker"; import { ModalOverlay } from "@/components/shared/ModalOverlay"; import { EventPicker } from "@/components/shared/EventPicker"; +import { apiV2Data } from "@/lib/apiV2"; // ─── Types ──────────────────────────────────────────────────────────────────── type EarlyBirdTier = { deadline: string; price: number; order?: number; variantId?: string | null }; @@ -478,11 +479,10 @@ export default function SelfServicePage() { payload.attendees = kioskNames; payload.ticketDelivery = delivery; } - const result = await apiFetch("/api/registrations/manual", { - method: "POST", - body: payload, + const result = await (apiV2Data("post", "/registrations/manual", { + body: payload as never, authToken: supervisorToken, - }); + }) as Promise); setCurrentRegistrationId(result?.id || null); setRegistrationIsFree(result?.status === "paid" || (result?.totalDueComputed ?? total) === 0); @@ -539,8 +539,8 @@ export default function SelfServicePage() { try { const responses = collectedAnswers.map((answers) => ({ answers })); - await apiFetch(`/api/registrations/${currentRegistrationId}/forms/responses`, { - method: "POST", + await apiV2Data("post", "/registrations/{id}/form-responses", { + params: { id: currentRegistrationId }, body: { responses }, authToken: supervisorToken, }); diff --git a/frontend/src/components/admin/RegistrationBulkBar.tsx b/frontend/src/components/admin/RegistrationBulkBar.tsx index 5108b0a..28799fa 100644 --- a/frontend/src/components/admin/RegistrationBulkBar.tsx +++ b/frontend/src/components/admin/RegistrationBulkBar.tsx @@ -6,6 +6,7 @@ import { apiFetch, API_BASE } from "@/lib/api"; import { errorMessage } from "@/lib/utils"; import { downloadReportExcel } from "@/lib/export"; import type { Event, Registration } from "@/types"; +import { apiV2Data } from "@/lib/apiV2"; type Action = "" | "message" | "markPaid" | "moveOption" | "allocate" | "cancel" | "export"; type Result = { id: string; ok: boolean; skipped?: boolean; message: string }; @@ -102,7 +103,7 @@ export function RegistrationBulkBar({ selected, events, token, onClear, onDone } : {}; setBusy(true); try { - const res = await apiFetch("/api/registrations/bulk", { method: "POST", authToken: token, body: { action, registrationIds: selected.map(r => r.id), ...params } }); + const res = await (apiV2Data("post", "/registrations/bulk", { authToken: token, body: { action: action as Exclude, registrationIds: selected.map(r => r.id), ...params } }) as Promise); setResult(res); onDone(); } catch (e) { diff --git a/frontend/src/components/reports/ReportsV2.tsx b/frontend/src/components/reports/ReportsV2.tsx index afecacf..ca89941 100644 --- a/frontend/src/components/reports/ReportsV2.tsx +++ b/frontend/src/components/reports/ReportsV2.tsx @@ -332,7 +332,7 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) { const byEv: Record = {}; for (const id of eventIds) { try { - const list = await apiFetch(`/api/registrations/event/${encodeURIComponent(id)}`, { authToken: token }); + const list = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: id }, authToken: token }) as Promise); byEv[id] = Array.isArray(list) ? list : []; } catch { byEv[id] = []; diff --git a/frontend/src/components/shared/AttendeesPanel.tsx b/frontend/src/components/shared/AttendeesPanel.tsx index 334b298..4f2f5aa 100644 --- a/frontend/src/components/shared/AttendeesPanel.tsx +++ b/frontend/src/components/shared/AttendeesPanel.tsx @@ -6,6 +6,7 @@ import { apiFetch } from "@/lib/api"; import { isMinorOn } from "@/components/shared/AttendeeNamesEditor"; import { errorMessage } from "@/lib/utils"; import type { Attendee } from "@/types"; +import { apiV2Data } from "@/lib/apiV2"; const CONSENT_LABEL: Record = { pending: { text: "consent pending", cls: "text-amber-700" }, @@ -95,8 +96,8 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved, setBusy(true); setError(null); try { - await apiFetch(`/api/registrations/${encodeURIComponent(registration.id)}/attendees`, { - method: "PUT", + await apiV2Data("put", "/registrations/{id}/attendees", { + params: { id: registration.id }, authToken: token, body: { ticketDelivery: delivery, @@ -127,7 +128,7 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved, const sendLink = async (a: Attendee) => { try { - const res = await apiFetch<{ message: string }>(`/api/registrations/${encodeURIComponent(registration.id)}/attendees/${encodeURIComponent(a.id)}/send-form-link`, { method: "POST", authToken: token }); + const res = await (apiV2Data("post", "/registrations/{id}/attendees/{attendeeId}/form-link", { params: { id: registration.id, attendeeId: a.id }, authToken: token }) as Promise<{ message: string }>); onMessage(res.message); } catch (e) { setError(errorMessage(e) || "Couldn't send the form link"); diff --git a/frontend/src/lib/api-v2/openapi.json b/frontend/src/lib/api-v2/openapi.json index 4f3cea5..127c25e 100644 --- a/frontend/src/lib/api-v2/openapi.json +++ b/frontend/src/lib/api-v2/openapi.json @@ -11867,6 +11867,191 @@ } } } + }, + "get": { + "tags": [ + "Registrations" + ], + "summary": "Every registration (staff)", + "description": "Newest first, for the events you may see. `unpaid=true` for ones still owing; `userId` for one person's.\n\n**Who:** Staff, supervisors and admins.", + "operationId": "getRegistrations", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "default": 1, + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "At most 200", + "schema": { + "default": 100, + "type": "integer", + "minimum": 1, + "maximum": 200 + } + }, + { + "name": "unpaid", + "in": "query", + "required": false, + "schema": { + "default": "false", + "type": "string", + "enum": [ + "true", + "false" + ] + } + }, + { + "name": "userId", + "in": "query", + "required": false, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "confirmed", + "partial_paid", + "paid", + "cancelled" + ] + }, + "eventId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "userId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "totalDueComputed": { + "type": "number" + } + }, + "required": [ + "id", + "status", + "eventId", + "userId" + ], + "additionalProperties": {} + } + }, + "meta": { + "type": "object", + "properties": { + "page": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "limit": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "total": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "pages": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "page", + "limit", + "total", + "pages" + ], + "additionalProperties": false + } + }, + "required": [ + "data", + "meta" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } } }, "/registrations/{id}": { @@ -12958,6 +13143,2168 @@ } } }, + "/registrations/{id}/full": { + "get": { + "tags": [ + "Registrations" + ], + "summary": "A registration with everything on it", + "description": "Items and prices, payments, coupons and bundles, named attendees, form answers and the total due.\n\nThe owner, a named attendee or staff — or anyone with the link when not signed in (registration ids can't be guessed). Attendees' contact details are only shown to the payer and staff.\n\n**Who:** Anyone; signed-in staff may see more.", + "operationId": "getRegistrationsIdFull", + "security": [ + {}, + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "confirmed", + "partial_paid", + "paid", + "cancelled" + ] + }, + "eventId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "userId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "totalDueComputed": { + "type": "number" + } + }, + "required": [ + "id", + "status", + "eventId", + "userId" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/me/registrations/full": { + "get": { + "tags": [ + "Me" + ], + "summary": "My registrations with everything on them", + "description": "What the dashboard shows: as `/registrations/{id}/full`, newest first, with the event and its form. Only upcoming ones unless `past=true`.\n\n**Who:** Any signed-in person.", + "operationId": "getMeRegistrationsFull", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "past", + "in": "query", + "required": false, + "schema": { + "default": "false", + "type": "string", + "enum": [ + "true", + "false" + ] + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "confirmed", + "partial_paid", + "paid", + "cancelled" + ] + }, + "eventId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "userId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "totalDueComputed": { + "type": "number" + } + }, + "required": [ + "id", + "status", + "eventId", + "userId" + ], + "additionalProperties": {} + } + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/registrations/{id}/items": { + "put": { + "tags": [ + "Registrations" + ], + "summary": "Change the tickets on a registration", + "description": "The whole list of items it should have. Added places need stock and are priced now; places already paid for keep their price, and nothing goes below tickets already issued or the amount paid.\n\nNot for registrations made with a season pass, nor once the event has ended or is closed. Staff can add kids and volunteer places; owners can only keep or lower them.\n\n**Who:** Any signed-in person.", + "operationId": "putRegistrationsIdItems", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "options": { + "minItems": 1, + "maxItems": 100, + "type": "array", + "items": { + "type": "object", + "properties": { + "eventOptionId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "variantId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + { + "type": "null" + } + ] + }, + "quantity": { + "type": "integer", + "minimum": 1, + "maximum": 1000 + } + }, + "required": [ + "eventOptionId", + "quantity" + ] + } + } + }, + "required": [ + "options" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "confirmed", + "partial_paid", + "paid", + "cancelled" + ] + }, + "eventId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "userId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "totalDueComputed": { + "type": "number" + } + }, + "required": [ + "id", + "status", + "eventId", + "userId" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/registrations/{id}/invoice": { + "post": { + "tags": [ + "Registrations" + ], + "summary": "Send me the invoice again", + "description": "**Who:** Any signed-in person.", + "operationId": "postRegistrationsIdInvoice", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "channel": { + "default": "email", + "type": "string", + "enum": [ + "email", + "whatsapp" + ] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/registrations/{id}/coupon": { + "post": { + "tags": [ + "Registrations" + ], + "summary": "Apply a coupon code", + "description": "By the owner, or by staff on their behalf (logged). Not on season pass registrations.\n\n**Who:** Any signed-in person.", + "operationId": "postRegistrationsIdCoupon", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "code": { + "type": "string", + "minLength": 1, + "maxLength": 40 + } + }, + "required": [ + "code" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "confirmed", + "partial_paid", + "paid", + "cancelled" + ] + }, + "eventId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "userId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "totalDueComputed": { + "type": "number" + }, + "message": { + "type": "string" + } + }, + "required": [ + "id", + "status", + "eventId", + "userId", + "message" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "tags": [ + "Registrations" + ], + "summary": "Take a coupon code off", + "description": "Staff. Its use is freed. Not once a ticket on it has been scanned; unused tickets are withdrawn if it's no longer paid.\n\n**Who:** Staff, supervisors and admins.", + "operationId": "deleteRegistrationsIdCoupon", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/registrations/{id}/attendees": { + "put": { + "tags": [ + "Registrations" + ], + "summary": "Name the people on a registration", + "description": "The whole list: attendees left out are removed (not once their ticket has been scanned). `ticketDelivery` says who gets the tickets.\n\n**Who:** Any signed-in person.", + "operationId": "putRegistrationsIdAttendees", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "attendees": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "description": "An attendee already on it (left out = removed)", + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "eventOptionId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "variantId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + { + "type": "null" + } + ] + }, + "name": { + "type": "string", + "maxLength": 200 + } + }, + "required": [ + "eventOptionId", + "name" + ], + "additionalProperties": {} + } + }, + "ticketDelivery": { + "type": "string", + "enum": [ + "payer", + "each" + ] + } + }, + "required": [ + "attendees" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "ticketDelivery": { + "type": [ + "string", + "null" + ] + }, + "attendees": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "name": { + "type": "string" + } + }, + "required": [ + "id", + "name" + ], + "additionalProperties": {} + } + } + }, + "required": [ + "id", + "ticketDelivery", + "attendees" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/registrations/{id}/attendees/{attendeeId}/form-link": { + "post": { + "tags": [ + "Registrations" + ], + "summary": "Send an attendee their form", + "description": "A link to fill in their own attendee form, by email and/or WhatsApp.\n\n**Who:** Any signed-in person.", + "operationId": "postRegistrationsIdAttendeesAttendeeIdForm-link", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + }, + { + "name": "attendeeId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/registrations/{id}/form-draft": { + "get": { + "tags": [ + "Registrations" + ], + "summary": "Attendee forms saved part-way", + "description": "**Who:** Anyone; signed-in staff may see more.", + "operationId": "getRegistrationsIdForm-draft", + "security": [ + {}, + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "data": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + }, + "updatedAt": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data", + "updatedAt" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "tags": [ + "Registrations" + ], + "summary": "Save attendee forms part-way", + "description": "Kept for the registration's owner (also when staff save it), until the forms are submitted.\n\n**Who:** Anyone; signed-in staff may see more.", + "operationId": "putRegistrationsIdForm-draft", + "security": [ + {}, + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + } + }, + "required": [ + "data" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "updatedAt": { + "type": "string" + } + }, + "required": [ + "message", + "updatedAt" + ], + "additionalProperties": false + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/registrations/{id}/form-responses": { + "post": { + "tags": [ + "Registrations" + ], + "summary": "Submit attendee forms", + "description": "One response per main ticket at most; each named attendee answers once. Tickets are issued once it's paid and the forms are in.\n\n**Who:** Anyone; signed-in staff may see more.", + "operationId": "postRegistrationsIdForm-responses", + "security": [ + {}, + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "responses": { + "maxItems": 500, + "type": "array", + "items": { + "type": "object", + "properties": { + "attendeeId": { + "description": "The named attendee this form is for", + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + { + "type": "null" + } + ] + }, + "answers": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {}, + "description": "Field id → answer (stored as text)" + } + }, + "required": [ + "answers" + ] + } + } + }, + "required": [ + "responses" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "count": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "message" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "tags": [ + "Registrations" + ], + "summary": "Replace the attendee forms", + "description": "Supervisors: every response on the registration is replaced by these.\n\n**Who:** Supervisors and admins.", + "operationId": "putRegistrationsIdForm-responses", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "responses": { + "maxItems": 500, + "type": "array", + "items": { + "type": "object", + "properties": { + "attendeeId": { + "description": "The named attendee this form is for", + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + { + "type": "null" + } + ] + }, + "answers": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {}, + "description": "Field id → answer (stored as text)" + } + }, + "required": [ + "answers" + ] + } + } + }, + "required": [ + "responses" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/events/{id}/registrations": { + "get": { + "tags": [ + "Registrations" + ], + "summary": "An event's registrations", + "description": "Oldest first, with tickets, payments and attendees. `search` matches the name, email or phone.\n\n**Who:** Staff, supervisors and admins.", + "operationId": "getEventsIdRegistrations", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + }, + { + "name": "search", + "in": "query", + "required": false, + "schema": { + "type": "string", + "maxLength": 200 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "confirmed", + "partial_paid", + "paid", + "cancelled" + ] + }, + "eventId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "userId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "totalDueComputed": { + "type": "number" + } + }, + "required": [ + "id", + "status", + "eventId", + "userId" + ], + "additionalProperties": {} + } + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/registrations/{id}/status": { + "patch": { + "tags": [ + "Registrations" + ], + "summary": "Set a registration's status", + "description": "Staff. `paid` issues and sends the tickets; leaving `paid` withdraws unused tickets (refused once one has been scanned); `cancelled` frees its places for the waitlist.\n\n**Who:** Staff, supervisors and admins.", + "operationId": "patchRegistrationsIdStatus", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The id", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "pending", + "confirmed", + "partial_paid", + "paid", + "cancelled" + ] + } + }, + "required": [ + "status" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "confirmed", + "partial_paid", + "paid", + "cancelled" + ] + }, + "eventId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "userId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "totalDueComputed": { + "type": "number" + } + }, + "required": [ + "id", + "status", + "eventId", + "userId" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/registrations/manual": { + "post": { + "tags": [ + "Registrations" + ], + "summary": "Register someone (at the door, by phone)", + "description": "Supervisors. Finds the person by email or phone (refused when those are two different accounts) or makes an account and sends them an activation link (`skipActivationNotice` to not).\n\nAdded to their existing registration for the event if they have one. Free ones are marked paid and get their tickets; otherwise they're sent a link to pay.\n\n**Who:** Supervisors and admins.", + "operationId": "postRegistrationsManual", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "eventId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "options": { + "minItems": 1, + "maxItems": 100, + "type": "array", + "items": { + "type": "object", + "properties": { + "eventOptionId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "variantId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + { + "type": "null" + } + ] + }, + "quantity": { + "type": "integer", + "minimum": 1, + "maximum": 1000 + }, + "sessionIds": { + "maxItems": 200, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + }, + "required": [ + "eventOptionId", + "quantity" + ] + } + }, + "user": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "email": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ] + }, + "phoneNumber": { + "anyOf": [ + { + "type": "string", + "maxLength": 40 + }, + { + "type": "null" + } + ] + }, + "password": { + "description": "Self-service kiosk: the visitor sets it, and the account is active at once", + "type": "string", + "maxLength": 200 + } + }, + "required": [ + "name" + ], + "additionalProperties": {} + }, + "notificationPreference": { + "description": "email, whatsapp or both (anything else: worked out from the contact details given)", + "anyOf": [ + { + "type": "string", + "maxLength": 20 + }, + { + "type": "null" + } + ] + }, + "skipActivationNotice": { + "type": "boolean" + }, + "couponCode": { + "anyOf": [ + { + "type": "string", + "maxLength": 40 + }, + { + "type": "null" + } + ] + }, + "attendees": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "description": "An attendee already on it (left out = removed)", + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "eventOptionId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "variantId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + { + "type": "null" + } + ] + }, + "name": { + "type": "string", + "maxLength": 200 + } + }, + "required": [ + "eventOptionId", + "name" + ], + "additionalProperties": {} + } + }, + "ticketDelivery": { + "type": "string", + "enum": [ + "payer", + "each" + ] + } + }, + "required": [ + "eventId", + "options", + "user" + ], + "additionalProperties": {} + } + } + } + }, + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "confirmed", + "partial_paid", + "paid", + "cancelled" + ] + }, + "eventId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "userId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "totalDueComputed": { + "type": "number" + }, + "couponError": { + "type": "string" + } + }, + "required": [ + "id", + "status", + "eventId", + "userId" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/registrations/bulk": { + "post": { + "tags": [ + "Registrations" + ], + "summary": "Do one thing to many registrations", + "description": "`markPaid`, `cancel`, `moveOption`, `allocate` or `message`, for up to 500 you may manage. Each is done on its own: the answer lists what worked and what didn't.\n\n**Who:** Supervisors and admins.", + "operationId": "postRegistrationsBulk", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": [ + "markPaid", + "cancel", + "moveOption", + "allocate", + "message" + ] + }, + "registrationIds": { + "minItems": 1, + "maxItems": 500, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + } + }, + "required": [ + "action", + "registrationIds" + ], + "additionalProperties": {} + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": {}, + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed for this role (FORBIDDEN)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/checkin/{qrCode}": { "get": { "tags": [ diff --git a/frontend/src/lib/api-v2/schema.d.ts b/frontend/src/lib/api-v2/schema.d.ts index 9ca1f02..b71c141 100644 --- a/frontend/src/lib/api-v2/schema.d.ts +++ b/frontend/src/lib/api-v2/schema.d.ts @@ -1133,7 +1133,13 @@ export interface paths { path?: never; cookie?: never; }; - get?: never; + /** + * Every registration (staff) + * @description Newest first, for the events you may see. `unpaid=true` for ones still owing; `userId` for one person's. + * + * **Who:** Staff, supervisors and admins. + */ + get: operations["getRegistrations"]; put?: never; /** * Register for an event @@ -1266,6 +1272,312 @@ export interface paths { patch?: never; trace?: never; }; + "/registrations/{id}/full": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * A registration with everything on it + * @description Items and prices, payments, coupons and bundles, named attendees, form answers and the total due. + * + * The owner, a named attendee or staff — or anyone with the link when not signed in (registration ids can't be guessed). Attendees' contact details are only shown to the payer and staff. + * + * **Who:** Anyone; signed-in staff may see more. + */ + get: operations["getRegistrationsIdFull"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/me/registrations/full": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * My registrations with everything on them + * @description What the dashboard shows: as `/registrations/{id}/full`, newest first, with the event and its form. Only upcoming ones unless `past=true`. + * + * **Who:** Any signed-in person. + */ + get: operations["getMeRegistrationsFull"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/registrations/{id}/items": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Change the tickets on a registration + * @description The whole list of items it should have. Added places need stock and are priced now; places already paid for keep their price, and nothing goes below tickets already issued or the amount paid. + * + * Not for registrations made with a season pass, nor once the event has ended or is closed. Staff can add kids and volunteer places; owners can only keep or lower them. + * + * **Who:** Any signed-in person. + */ + put: operations["putRegistrationsIdItems"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/registrations/{id}/invoice": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Send me the invoice again + * @description **Who:** Any signed-in person. + */ + post: operations["postRegistrationsIdInvoice"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/registrations/{id}/coupon": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Apply a coupon code + * @description By the owner, or by staff on their behalf (logged). Not on season pass registrations. + * + * **Who:** Any signed-in person. + */ + post: operations["postRegistrationsIdCoupon"]; + /** + * Take a coupon code off + * @description Staff. Its use is freed. Not once a ticket on it has been scanned; unused tickets are withdrawn if it's no longer paid. + * + * **Who:** Staff, supervisors and admins. + */ + delete: operations["deleteRegistrationsIdCoupon"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/registrations/{id}/attendees": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Name the people on a registration + * @description The whole list: attendees left out are removed (not once their ticket has been scanned). `ticketDelivery` says who gets the tickets. + * + * **Who:** Any signed-in person. + */ + put: operations["putRegistrationsIdAttendees"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/registrations/{id}/attendees/{attendeeId}/form-link": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Send an attendee their form + * @description A link to fill in their own attendee form, by email and/or WhatsApp. + * + * **Who:** Any signed-in person. + */ + post: operations["postRegistrationsIdAttendeesAttendeeIdForm-link"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/registrations/{id}/form-draft": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Attendee forms saved part-way + * @description **Who:** Anyone; signed-in staff may see more. + */ + get: operations["getRegistrationsIdForm-draft"]; + /** + * Save attendee forms part-way + * @description Kept for the registration's owner (also when staff save it), until the forms are submitted. + * + * **Who:** Anyone; signed-in staff may see more. + */ + put: operations["putRegistrationsIdForm-draft"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/registrations/{id}/form-responses": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Replace the attendee forms + * @description Supervisors: every response on the registration is replaced by these. + * + * **Who:** Supervisors and admins. + */ + put: operations["putRegistrationsIdForm-responses"]; + /** + * Submit attendee forms + * @description One response per main ticket at most; each named attendee answers once. Tickets are issued once it's paid and the forms are in. + * + * **Who:** Anyone; signed-in staff may see more. + */ + post: operations["postRegistrationsIdForm-responses"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/events/{id}/registrations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * An event's registrations + * @description Oldest first, with tickets, payments and attendees. `search` matches the name, email or phone. + * + * **Who:** Staff, supervisors and admins. + */ + get: operations["getEventsIdRegistrations"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/registrations/{id}/status": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + /** + * Set a registration's status + * @description Staff. `paid` issues and sends the tickets; leaving `paid` withdraws unused tickets (refused once one has been scanned); `cancelled` frees its places for the waitlist. + * + * **Who:** Staff, supervisors and admins. + */ + patch: operations["patchRegistrationsIdStatus"]; + trace?: never; + }; + "/registrations/manual": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Register someone (at the door, by phone) + * @description Supervisors. Finds the person by email or phone (refused when those are two different accounts) or makes an account and sends them an activation link (`skipActivationNotice` to not). + * + * Added to their existing registration for the event if they have one. Free ones are marked paid and get their tickets; otherwise they're sent a link to pay. + * + * **Who:** Supervisors and admins. + */ + post: operations["postRegistrationsManual"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/registrations/bulk": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Do one thing to many registrations + * @description `markPaid`, `cancel`, `moveOption`, `allocate` or `message`, for up to 500 you may manage. Each is done on its own: the answer lists what worked and what didn't. + * + * **Who:** Supervisors and admins. + */ + post: operations["postRegistrationsBulk"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/checkin/{qrCode}": { parameters: { query?: never; @@ -6338,6 +6650,76 @@ export interface operations { }; }; }; + getRegistrations: { + parameters: { + query?: { + page?: number; + /** @description At most 200 */ + limit?: number; + unpaid?: "true" | "false"; + userId?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: ({ + id: string; + /** @enum {string} */ + status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled"; + eventId: string; + userId: string; + totalDueComputed?: number; + } & { + [key: string]: unknown; + })[]; + meta: { + page: number; + limit: number; + total: number; + pages: number; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; postRegistrations: { parameters: { query?: never; @@ -6870,6 +7252,1062 @@ export interface operations { }; }; }; + getRegistrationsIdFull: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + id: string; + /** @enum {string} */ + status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled"; + eventId: string; + userId: string; + totalDueComputed?: number; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + getMeRegistrationsFull: { + parameters: { + query?: { + past?: "true" | "false"; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: ({ + id: string; + /** @enum {string} */ + status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled"; + eventId: string; + userId: string; + totalDueComputed?: number; + } & { + [key: string]: unknown; + })[]; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + putRegistrationsIdItems: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + options: { + eventOptionId: string; + variantId?: string | null; + quantity: number; + }[]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + id: string; + /** @enum {string} */ + status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled"; + eventId: string; + userId: string; + totalDueComputed?: number; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + postRegistrationsIdInvoice: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** + * @default email + * @enum {string} + */ + channel?: "email" | "whatsapp"; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + message: string; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + postRegistrationsIdCoupon: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + code: string; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + id: string; + /** @enum {string} */ + status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled"; + eventId: string; + userId: string; + totalDueComputed?: number; + message: string; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + deleteRegistrationsIdCoupon: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + message: string; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + putRegistrationsIdAttendees: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + attendees: ({ + /** @description An attendee already on it (left out = removed) */ + id?: string; + eventOptionId: string; + variantId?: string | null; + name: string; + } & { + [key: string]: unknown; + })[]; + /** @enum {string} */ + ticketDelivery?: "payer" | "each"; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + id: string; + ticketDelivery: string | null; + attendees: ({ + id: string; + name: string; + } & { + [key: string]: unknown; + })[]; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "postRegistrationsIdAttendeesAttendeeIdForm-link": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + attendeeId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + message: string; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "getRegistrationsIdForm-draft": { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + data: { + [key: string]: unknown; + }; + updatedAt: string | null; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "putRegistrationsIdForm-draft": { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + data: { + [key: string]: unknown; + }; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + message: string; + updatedAt: string; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "putRegistrationsIdForm-responses": { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + responses: { + /** @description The named attendee this form is for */ + attendeeId?: string | null; + /** @description Field id → answer (stored as text) */ + answers: { + [key: string]: unknown; + }; + }[]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + message: string; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "postRegistrationsIdForm-responses": { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + responses: { + /** @description The named attendee this form is for */ + attendeeId?: string | null; + /** @description Field id → answer (stored as text) */ + answers: { + [key: string]: unknown; + }; + }[]; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + message: string; + count?: number; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + getEventsIdRegistrations: { + parameters: { + query?: { + search?: string; + }; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: ({ + id: string; + /** @enum {string} */ + status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled"; + eventId: string; + userId: string; + totalDueComputed?: number; + } & { + [key: string]: unknown; + })[]; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + patchRegistrationsIdStatus: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The id */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** @enum {string} */ + status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled"; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + id: string; + /** @enum {string} */ + status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled"; + eventId: string; + userId: string; + totalDueComputed?: number; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not found (NOT_FOUND) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + postRegistrationsManual: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + eventId: string; + options: { + eventOptionId: string; + variantId?: string | null; + quantity: number; + sessionIds?: string[]; + }[]; + user: { + name: string; + email?: string | null; + phoneNumber?: string | null; + /** @description Self-service kiosk: the visitor sets it, and the account is active at once */ + password?: string; + } & { + [key: string]: unknown; + }; + /** @description email, whatsapp or both (anything else: worked out from the contact details given) */ + notificationPreference?: string | null; + skipActivationNotice?: boolean; + couponCode?: string | null; + attendees?: ({ + /** @description An attendee already on it (left out = removed) */ + id?: string; + eventOptionId: string; + variantId?: string | null; + name: string; + } & { + [key: string]: unknown; + })[]; + /** @enum {string} */ + ticketDelivery?: "payer" | "each"; + } & { + [key: string]: unknown; + }; + }; + }; + responses: { + /** @description OK */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + id: string; + /** @enum {string} */ + status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled"; + eventId: string; + userId: string; + totalDueComputed?: number; + couponError?: string; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + postRegistrationsBulk: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** @enum {string} */ + action: "markPaid" | "cancel" | "moveOption" | "allocate" | "message"; + registrationIds: string[]; + } & { + [key: string]: unknown; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not allowed for this role (FORBIDDEN) */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; getCheckinQrCode: { parameters: { query?: { diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 17d8818..704f46d 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -1,4 +1,4 @@ -import type { Event, Paginated, Payment, User } from "@/types"; +import type { Event, Paginated, Payment, Registration, User } from "@/types"; export type ApiOptions = { method?: string; @@ -216,6 +216,23 @@ export async function fetchManagedEvents(token: string | null | undef return data as unknown as T[]; } +/** + * Every registration staff may see (API v2 GET /registrations, all pages), newest first, in full. + * `unpaid`: only ones still owing; `userId`: one person's. + */ +export async function fetchAllRegistrations(token: string | null | undefined, filter: { unpaid?: boolean; userId?: string } = {}): Promise { + const { apiV2 } = await import("@/lib/apiV2"); + const out: T[] = []; + for (let page = 1; ; page++) { + const res = await apiV2("get", "/registrations", { + authToken: token, + query: { page, limit: 200, unpaid: filter.unpaid ? "true" : "false", ...(filter.userId ? { userId: filter.userId } : {}) }, + }); + out.push(...(res.data as unknown as T[])); + if (page >= res.meta.pages) return out; + } +} + /** * One event in full (API v2 GET /events/{id}/full): ticket options with what's left, sessions, * form, attachments, bundles. Staff signed in (`authToken`) also see inactive and not-yet-live diff --git a/package-lock.json b/package-lock.json index c42bdc8..77cb4f0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "hope-events", - "version": "1.51.9", + "version": "1.51.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "hope-events", - "version": "1.51.9", + "version": "1.51.10", "license": "ISC", "devDependencies": { "@axe-core/playwright": "^4.14.0", diff --git a/package.json b/package.json index 951767e..04b94db 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hope-events", - "version": "1.51.9", + "version": "1.51.10", "main": "index.js", "scripts": { "dev:backend": "cd backend && npm run dev",