const prisma = require('../config/db'); const { v4: uuidv4 } = require('uuid'); const { planLineTickets } = require('./attendees'); /** Form fields that are only text to read (a statement, a heading). */ const DISPLAY_FIELDS = ['statement', 'paragraph']; /** A required form with at least one question to answer — the only kind tickets wait for. */ const formNeedsAnswers = (form) => !!(form && form.isRequired && (form.fields || []).some(f => !DISPLAY_FIELDS.includes(f.type))); /** * How many attendee forms a registration's places need: one per main-ticket place. A picked- * session booking has a line per session for the same people, so it counts once (its biggest * line), not once per session. */ function formPlaces(registrationOptions) { let total = 0; const picked = new Map(); for (const ro of registrationOptions || []) { if (!ro.eventOption?.isMainTicket) continue; const qty = ro.quantity || 0; if (!ro.sessionId) { total += qty; continue; } const key = `${ro.eventOptionId}::${ro.variantId || ''}`; picked.set(key, Math.max(picked.get(key) || 0, qty)); } for (const qty of picked.values()) total += qty; return total; } /** * The attendee forms a registration still needs before its tickets can be issued: 0 when the * event's form isn't required (or has no questions), when the form was left for later * (`formWaivedAt`), or when enough are in. `registration` is an id or a record with * registrationOptions[].eventOption. */ async function formsOutstanding(registration) { try { const reg = typeof registration === 'string' ? await prisma.registration.findUnique({ where: { id: registration }, include: { registrationOptions: { include: { eventOption: true } } } }) : registration; if (!reg || reg.formWaivedAt) return 0; const form = await prisma.eventForm.findUnique({ where: { eventId: reg.eventId }, include: { fields: true } }); if (!formNeedsAnswers(form)) return 0; const submitted = await prisma.formResponse.count({ where: { registrationId: reg.id } }); return Math.max(0, formPlaces(reg.registrationOptions) - submitted); } catch (_) { return 0; // form models unavailable — don't block } } /** * Generate tickets for a registration when payment status is "paid" (or an admin released * them unpaid) and no required attendee form is outstanding (see formsOutstanding). * * Rules: * - Each named attendee (group tickets) gets their own quantity-1 ticket; the rest of a * line's places share ONE quantity ticket per registrationOption (see * utils/attendees.js planLineTickets). * - If duplicate registrationOptions exist for the same eventOptionId (old data), * consolidate them: merge quantities, keep the one with scan history, delete the rest. * - If duplicate ticket records exist for the same registrationOption (old data), * keep the primary (scanned one, or oldest), update its quantity, delete the rest. * * @param {string} registrationId * @returns {Promise} newly-created ticket records (empty when all already existed) */ const generateTicketsForRegistration = async (registrationId) => { try { const registration = await prisma.registration.findUnique({ where: { id: registrationId }, include: { registrationOptions: { include: { eventOption: true, tickets: { include: { usages: true }, orderBy: { createdAt: 'asc' } } } }, event: true, user: true } }); if (!registration) throw new Error('Registration not found'); // Paid, or an admin issued the tickets before payment ("pay later", 1.52.0). if (registration.status !== 'paid' && !(registration.ticketsReleasedAt && registration.status !== 'cancelled')) return []; // A required attendee form comes first, unless it's been left for later. if ((await formsOutstanding(registration)) > 0) return []; // ── Step 1: Consolidate duplicate registrationOptions for the same (eventOptionId, variantId, session) ── // Key on both fields so that different variants of the same option are never merged const byOption = new Map(); for (const ro of registration.registrationOptions) { const key = `${ro.eventOptionId}::${ro.variantId || ''}::${ro.sessionId || ''}`; if (!byOption.has(key)) byOption.set(key, []); byOption.get(key).push(ro); } // For each group with duplicates, merge into the one that has tickets (or the first). // Different (eventOptionId, variantId) groups touch disjoint rows, so process groups // concurrently instead of one at a time. await Promise.all(Array.from(byOption.values()).map(async (group) => { if (group.length <= 1) return; // Prefer the option that already has tickets const withTickets = group.filter(ro => (ro.tickets || []).length > 0); const primary = withTickets.length > 0 ? withTickets[0] : group[0]; const duplicates = group.filter(ro => ro.id !== primary.id); // Move all tickets from duplicates to primary (independent rows — safe to parallelize) await Promise.all(duplicates.map(dup => Promise.all( (dup.tickets || []).map(t => prisma.ticket.update({ where: { id: t.id }, data: { registrationOptionId: primary.id, updatedAt: new Date() } }) ) ))); // Single write of the merged quantity, then delete the now-empty duplicate options const totalMergedQty = duplicates.reduce((s, d) => s + (d.quantity || 0), 0); await prisma.registrationOption.update({ where: { id: primary.id }, data: { quantity: (primary.quantity || 0) + totalMergedQty } }); await Promise.all(duplicates.map(dup => prisma.registrationOption.delete({ where: { id: dup.id } }))); // Re-load the primary's current quantity + tickets after merge const updated = await prisma.registrationOption.findUnique({ where: { id: primary.id } }); primary.quantity = updated?.quantity ?? primary.quantity; primary.tickets = await prisma.ticket.findMany({ where: { registrationOptionId: primary.id }, include: { usages: true }, orderBy: { createdAt: 'asc' } }); })); // ── Step 2: For each unique option, sync its tickets: one per named attendee, plus // one shared quantity ticket for any unnamed places ── // Re-read fresh list (some options may have been deleted above) const freshOptions = await prisma.registrationOption.findMany({ where: { registrationId }, include: { tickets: { include: { usages: true }, orderBy: { createdAt: 'asc' } }, attendees: { orderBy: { order: 'asc' } }, } }); // Each option owns disjoint tickets, so resolve them concurrently instead of one at a time. const perOptionResults = await Promise.all(freshOptions.map(async (option) => { const plan = planLineTickets({ quantity: option.quantity || 1 }, option.attendees || [], option.tickets || []); await Promise.all([ plan.remove.length ? prisma.ticket.deleteMany({ where: { id: { in: plan.remove } } }) : null, ...plan.update.map(u => prisma.ticket.update({ where: { id: u.id }, data: { ...u.data, updatedAt: new Date() } })), ]); return Promise.all(plan.create.map(c => prisma.ticket.create({ data: { id: uuidv4(), qrCode: uuidv4(), registrationOptionId: option.id, userId: registration.userId, eventId: registration.eventId, quantity: c.quantity, attendeeId: c.attendeeId, holderUserId: c.holderUserId, updatedAt: new Date() } }))); })); return perOptionResults.flat(); } catch (error) { console.error('Error generating tickets:', error); throw error; } }; module.exports = { generateTicketsForRegistration, formsOutstanding, formPlaces, formNeedsAnswers, DISPLAY_FIELDS };