/** * Corrections (1.52.0): putting registrations right when the normal flow didn't finish — tickets * held back by a required attendee form, tickets needed before it's paid, a balance to write off, * and check-ins after the event. Admins only, from Corrections; "Fill in later" (leaveFormForLater) * is for any staff at the door and in Manual registrations. * * Every change is in the audit log with who did it and the reason given. */ import { prisma as typedPrisma } from '../v2/legacy'; import { fail } from './errors'; /* eslint-disable @typescript-eslint/no-explicit-any -- the records are Prisma's with includes */ const prisma = typedPrisma as any; const { generateTicketsForRegistration, formsOutstanding, formPlaces, formNeedsAnswers } = require('../utils/ticketUtils') as { generateTicketsForRegistration(id: string): Promise; formsOutstanding(registration: string | object): Promise; formPlaces(registrationOptions: any[]): number; formNeedsAnswers(form: any): boolean; }; const { computeRegistrationTotalDue } = require('../utils/pricing') as { computeRegistrationTotalDue(registration: any, at: Date): number }; const { recalculateRegistrationDiscount } = require('../utils/coupons') as { recalculateRegistrationDiscount(id: string): Promise }; const { assertEventOpen } = require('../utils/cashupUtils') as { assertEventOpen(eventId: string): Promise }; const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise }; const sessions = require('../utils/sessions') as { activeSessions(sessions: any[]): any[]; sessionLabel(session: any, sessions: any[]): string; lineCovers(line: any, sessionId: string): boolean; lineSessions(line: any): string[] | null; redeemedForSession(usages: any[], sessionId: string | null): number; }; export type Actor = { id: string; role: string }; type Audit = { actor: Actor; ip?: string }; /** The key a single-date event's check-ins are counted under. */ export const WHOLE_EVENT = 'event'; const round2 = (n: number) => Math.round(n * 100) / 100; const realEmail = (email: string | null | undefined) => (email && !email.endsWith('@guest.local') ? email : null); const REGISTRATION_INCLUDE = { user: { select: { id: true, name: true, email: true, phoneNumber: true } }, payments: { select: { amount: true, createdAt: true } }, formResponses: { select: { id: true } }, attendees: { select: { id: true, name: true } }, registrationOptions: { include: { eventOption: { include: { earlyBirdTiers: true } }, variant: { select: { name: true } }, tranches: true, tickets: { include: { usages: { select: { quantityRedeemed: true, sessionId: true } }, attendee: { select: { name: true } }, holder: { select: { name: true } } }, orderBy: { createdAt: 'asc' }, }, }, }, }; async function emailTicketsTo(registrationId: string, userId: string) { const { emailTickets } = require('../controllers/ticketController') as { emailTickets(req: any, res: any): Promise }; const res: any = { status: () => res, json: () => {} }; try { await emailTickets({ user: { id: userId }, body: { registrationId } }, res); } catch (e: any) { console.error('[corrections] Failed to send tickets:', e?.message || e); } } async function loadEvent(eventId: string) { const event = await prisma.event.findUnique({ where: { id: eventId }, select: { id: true, title: true, startDate: true, endDate: true, scheduleType: true, cashupStatus: true, sessions: { select: { id: true, label: true, startsAt: true, endsAt: true, cancelledAt: true } }, form: { include: { fields: { select: { type: true } } } }, }, }); return event || fail(404, 'Event not found'); } /** One registration as Corrections shows it: money, forms, tickets and their check-ins. */ function correctionRow(reg: any, event: any, formRequired: boolean) { const now = new Date(); const totalDue = round2(computeRegistrationTotalDue(reg, now)); const paid = round2((reg.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0)); const active = sessions.activeSessions(event.sessions || []); const multi = event.scheduleType === 'sessions'; let places = 0; let ticketPlaces = 0; const tickets: any[] = []; for (const ro of reg.registrationOptions || []) { places += ro.quantity || 0; const session = ro.sessionId ? active.find((s: any) => s.id === ro.sessionId) : null; const label = [ro.eventOption?.name, ro.variant?.name].filter(Boolean).join(' — ') + (session ? ` (${sessions.sessionLabel(session, event.sessions)})` : ''); for (const t of ro.tickets || []) { ticketPlaces += t.quantity || 0; const covered = multi ? (sessions.lineSessions(ro) ?? active.map((s: any) => s.id)).filter((id: string) => active.some((s: any) => s.id === id)) : [WHOLE_EVENT]; const checkedIn: Record = {}; for (const key of covered) checkedIn[key] = sessions.redeemedForSession(t.usages, multi ? key : null); tickets.push({ id: t.id, qrCode: t.qrCode, label, isMainTicket: !!ro.eventOption?.isMainTicket, name: t.attendee?.name || t.holder?.name || reg.user?.name || '', quantity: t.quantity || 1, sessionIds: covered, checkedIn, }); } } const ticketsDue = reg.status === 'paid' || !!reg.ticketsReleasedAt; const formsNeeded = formRequired && !reg.formWaivedAt ? Math.max(0, formPlaces(reg.registrationOptions) - (reg.formResponses || []).length) : 0; return { id: reg.id, status: reg.status, createdAt: reg.createdAt, user: { id: reg.user?.id, name: reg.user?.name || '', email: realEmail(reg.user?.email), phoneNumber: reg.user?.phoneNumber || null }, totalDue, paid, balance: round2(Math.max(0, totalDue - paid)), places, ticketPlaces, missingTickets: ticketsDue && ticketPlaces < places, formsNeeded, formWaived: !!reg.formWaivedAt, ticketsReleased: !!reg.ticketsReleasedAt, complimentary: Number(reg.complimentaryDiscount || 0), tickets, }; } function eventSummary(event: any) { const active = sessions.activeSessions(event.sessions || []); return { id: event.id, title: event.title, startDate: event.startDate, endDate: event.endDate, closed: event.cashupStatus === 'closed', formRequired: formNeedsAnswers(event.form), sessions: event.scheduleType === 'sessions' ? active.map((s: any) => ({ id: s.id, label: sessions.sessionLabel(s, event.sessions), startsAt: s.startsAt })) : [], }; } /** An event's registrations (not cancelled) with what may need putting right. */ export async function eventCorrections(eventId: string) { const event = await loadEvent(eventId); const formRequired = formNeedsAnswers(event.form); const regs = await prisma.registration.findMany({ where: { eventId, status: { not: 'cancelled' } }, include: REGISTRATION_INCLUDE, orderBy: { createdAt: 'asc' }, }); return { event: eventSummary(event), registrations: regs.map((r: any) => correctionRow(r, event, formRequired)) }; } async function registrationRow(registrationId: string) { const reg = await prisma.registration.findUnique({ where: { id: registrationId }, include: REGISTRATION_INCLUDE }); if (!reg) return fail(404, 'Registration not found'); const event = await loadEvent(reg.eventId); return correctionRow(reg, event, formNeedsAnswers(event.form)); } async function activeRegistration(registrationId: string) { const reg = await prisma.registration.findUnique({ where: { id: registrationId }, include: { registrationOptions: { include: { eventOption: true } } } }); if (!reg) return fail(404, 'Registration not found'); if (reg.status === 'cancelled') return fail(400, 'This registration is cancelled.'); return reg; } async function waiveForm(reg: any, actorId: string) { if (reg.formWaivedAt || (await formsOutstanding(reg)) === 0) return false; await prisma.registration.update({ where: { id: reg.id }, data: { formWaivedAt: new Date(), formWaivedById: actorId, updatedAt: new Date() } }); return true; } /** * "Fill in later" at the door / in Manual registrations: the tickets stop waiting for the * attendee form, and the payer is sent a link to fill it in (`notify`). */ export async function leaveFormForLater(registrationId: string, { actor, ip }: Audit, { notify = true }: { notify?: boolean } = {}) { const reg = await activeRegistration(registrationId); const waived = await waiveForm(reg, actor.id); const created = await generateTicketsForRegistration(reg.id); if (created.length > 0) await emailTicketsTo(reg.id, reg.userId); let sentTo: string[] = []; if (waived) { logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'attendee_form_waived', targetType: 'Registration', targetId: reg.id, metadata: { eventId: reg.eventId, from: 'door' }, ip }); if (notify) { const { sendFormReminderMessage } = require('../utils/notifications') as { sendFormReminderMessage(id: string): Promise }; sentTo = await sendFormReminderMessage(reg.id).catch(() => []); } } return { ticketsIssued: created.length, sentTo }; } type IssueOptions = { skipForm?: boolean; payLater?: boolean; send?: boolean; reason?: string | null }; /** * Admin: issue a registration's tickets now — leaving the attendee form for later (`skipForm`) * and/or before it's paid (`payLater`, the balance is still owed). */ export async function issueTickets(registrationId: string, { actor, ip }: Audit, opts: IssueOptions) { const reg = await activeRegistration(registrationId); if (reg.status !== 'paid' && !reg.ticketsReleasedAt && !opts.payLater) { return fail(400, 'This registration isn\'t paid yet. Choose "pay later" or "make it free" to issue its tickets.'); } const outstanding = opts.skipForm ? 0 : await formsOutstanding(reg); if (outstanding > 0) { return fail(400, `${outstanding} attendee form${outstanding === 1 ? ' is' : 's are'} still to fill in. Fill ${outstanding === 1 ? 'it' : 'them'} in, or choose to leave the form for later.`); } const waived = opts.skipForm ? await waiveForm(reg, actor.id) : false; const released = !!opts.payLater && reg.status !== 'paid' && !reg.ticketsReleasedAt; if (released) { await prisma.registration.update({ where: { id: reg.id }, data: { ticketsReleasedAt: new Date(), ticketsReleasedById: actor.id, updatedAt: new Date() } }); } const created = await generateTicketsForRegistration(reg.id); logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'tickets_issued_override', targetType: 'Registration', targetId: reg.id, metadata: { eventId: reg.eventId, formLeftForLater: waived, payLater: released, ticketsCreated: created.length, reason: opts.reason || null }, ip, }); if (opts.send && created.length > 0) await emailTicketsTo(reg.id, reg.userId); if (waived) logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'attendee_form_waived', targetType: 'Registration', targetId: reg.id, metadata: { eventId: reg.eventId, from: 'corrections', reason: opts.reason || null }, ip }); return { ticketsIssued: created.length, registration: await registrationRow(reg.id) }; } /** * Admin: write off what's still owed ("make it free") — it comes off as a complimentary * discount, so income stays what was really paid — and issue the tickets. */ export async function makeComplimentary(registrationId: string, { actor, ip }: Audit, opts: Omit) { const reg = await activeRegistration(registrationId); try { await assertEventOpen(reg.eventId); } catch (e: any) { return fail(400, e?.message || 'This event is closed.'); } const full = await prisma.registration.findUnique({ where: { id: reg.id }, include: { registrationOptions: { include: { eventOption: { include: { earlyBirdTiers: true } }, tranches: true } }, payments: true }, }); const due = computeRegistrationTotalDue(full, new Date()); const paid = (full.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0); const balance = round2(due - paid); if (!(balance > 0.004)) return fail(400, 'Nothing is owed on this registration.'); await prisma.registration.update({ where: { id: reg.id }, data: { complimentaryDiscount: round2(Number(full.complimentaryDiscount || 0) + balance), updatedAt: new Date() } }); await recalculateRegistrationDiscount(reg.id); await prisma.registration.update({ where: { id: reg.id }, data: { status: 'paid', updatedAt: new Date() } }); logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'registration_complimentary', targetType: 'Registration', targetId: reg.id, metadata: { eventId: reg.eventId, amount: balance, reason: opts.reason || null }, ip, }); const waived = opts.skipForm ? await waiveForm(reg, actor.id) : false; if (waived) logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'attendee_form_waived', targetType: 'Registration', targetId: reg.id, metadata: { eventId: reg.eventId, from: 'corrections', reason: opts.reason || null }, ip }); const created = await generateTicketsForRegistration(reg.id); if (opts.send && created.length > 0) await emailTicketsTo(reg.id, reg.userId); return { amount: balance, ticketsIssued: created.length, registration: await registrationRow(reg.id) }; } /** * Admin: every paid registration (or one released unpaid) at an event that's missing tickets * gets them — forms still outstanding are left for later. */ export async function issueMissingTickets(eventId: string, { actor, ip }: Audit, { send = false }: { send?: boolean } = {}) { const { registrations } = await eventCorrections(eventId); const missing = registrations.filter((r: any) => r.missingTickets); let tickets = 0; let fixed = 0; const failed: { id: string; name: string; message: string }[] = []; for (const row of missing) { try { const reg = await activeRegistration(row.id); await waiveForm(reg, actor.id); const created = await generateTicketsForRegistration(reg.id); tickets += created.length; if (created.length > 0) fixed += 1; if (send && created.length > 0) await emailTicketsTo(reg.id, reg.userId); } catch (e: any) { failed.push({ id: row.id, name: row.user.name, message: e?.message || 'Failed' }); } } if (missing.length > 0) { logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'tickets_issued_override', targetType: 'Event', targetId: eventId, metadata: { registrations: fixed, ticketsCreated: tickets, formLeftForLater: true, sent: send, failed: failed.length }, ip, }); } return { registrations: fixed, tickets, failed }; } type CheckInOptions = { sessionId?: string | null; people?: number | null; present?: boolean; reason?: string | null }; /** * Admin: check a ticket in (or undo it) whatever the time — after the event or session has * ended, outside the check-in window, or once the event is closed. Recorded as a manual * check-in; no check-in message is sent. */ export async function correctCheckIn(ticketId: string, { actor, ip }: Audit, opts: CheckInOptions) { const ticket = await prisma.ticket.findUnique({ where: { id: ticketId }, include: { usages: true, event: { select: { id: true, scheduleType: true } }, registrationOption: { select: { sessionId: true, sessionIds: true, registration: { select: { status: true } } } } }, }); if (!ticket) return fail(404, 'Ticket not found'); if (ticket.registrationOption?.registration?.status === 'cancelled') return fail(400, 'This registration is cancelled.'); const multi = ticket.event.scheduleType === 'sessions'; let sessionId: string | null = null; if (multi) { const session = opts.sessionId ? await prisma.eventSession.findUnique({ where: { id: opts.sessionId } }) : null; if (!session || session.eventId !== ticket.eventId) return fail(400, 'Choose one of this event\'s sessions.'); if (session.cancelledAt) return fail(400, 'That session was cancelled.'); if (ticket.registrationOption && !sessions.lineCovers(ticket.registrationOption, session.id)) return fail(400, 'That ticket isn\'t booked for this session.'); sessionId = session.id; } const forSession = ticket.usages.filter((u: any) => (u.sessionId || null) === sessionId); const redeemed = sessions.redeemedForSession(ticket.usages, sessionId); const quantity = ticket.quantity || 1; let changed = 0; if (opts.present === false) { if (forSession.length === 0) return fail(400, 'This ticket isn\'t checked in.'); await prisma.ticketUsage.deleteMany({ where: { id: { in: forSession.map((u: any) => u.id) } } }); if (!multi) await prisma.ticket.update({ where: { id: ticket.id }, data: { isUsed: false, updatedAt: new Date() } }); changed = redeemed; } else { const left = quantity - redeemed; if (left <= 0) return fail(400, 'Everyone on this ticket is already checked in.'); const people = Math.min(Math.max(1, Math.trunc(Number(opts.people)) || left), left); await prisma.ticketUsage.create({ data: { ticketId: ticket.id, scannedById: actor.id, quantityRedeemed: people, sessionId, manual: true } }); if (!multi && redeemed + people >= quantity) await prisma.ticket.update({ where: { id: ticket.id }, data: { isUsed: true, updatedAt: new Date() } }); changed = people; } logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'checkin_corrected', targetType: 'Ticket', targetId: ticket.id, metadata: { eventId: ticket.eventId, sessionId, present: opts.present !== false, people: changed, reason: opts.reason || null }, ip, }); const after = await prisma.ticketUsage.findMany({ where: { ticketId: ticket.id }, select: { quantityRedeemed: true, sessionId: true } }); return { checkedIn: sessions.redeemedForSession(after, sessionId), quantity }; }