/** * Waitlist for sold-out ticket options. * * Rules: * - Only on events with waitlistEnabled, and only for a line that's actually sold out. * - When places free up (a cancellation, a smaller booking, a raised stock limit, or an * offer expiring), processWaitlist offers them to the next people in line. An offer * holds the places for event.waitlistOfferHours — they count as taken (utils/stock.js) * so the public site can't sell them — and sends a claim link by email/WhatsApp. * - If fewer places are free than someone asked for: with waitlistPartialOffers they're * offered what's free; otherwise they're skipped for the next person who fits. * - Claiming = registering with the link (createRegistration's waitlistToken). Early-bird * and coupon rules apply as usual. An unclaimed offer expires and moves on. */ const crypto = require('crypto'); const prisma = require('../config/db'); const { remainingFor } = require('./stock'); const ACTIVE = ['waiting', 'offered']; function waitlistError(message, statusCode = 400) { const err = new Error(message); err.statusCode = statusCode; return err; } const hashToken = (token) => crypto.createHmac('sha256', process.env.JWT_SECRET || '').update(`waitlist:${token}`).digest('hex'); function claimLink(token) { const base = (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').split(',')[0].trim().replace(/\/$/, ''); return `${base}/waitlist/claim/${token}`; } /** * Who gets offered what, given the free places on a line. Pure. * @param {Array} waiting - entries in queue order [{ id, quantity }] * @param {number} free - places free * @param {boolean} partial - offer what's free when it's less than asked for * @returns {Array<{ entryId: string, quantity: number }>} */ function pickOffers(waiting, free, partial) { const offers = []; let left = free; for (const entry of waiting) { if (left <= 0) break; if (entry.quantity <= left) { offers.push({ entryId: entry.id, quantity: entry.quantity }); left -= entry.quantity; } else if (partial) { // First in line gets what's free; nobody behind them jumps the queue. offers.push({ entryId: entry.id, quantity: left }); left = 0; } // else: skip to the next person who fits } return offers; } async function notifyOffer(entry, token) { const { sendMail, emailWrapper, ctaButton, fallbackLink } = require('./email'); const { shouldEmail, waText, waTextAny } = require('./notify'); const ff = `-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif`; const user = entry.user; const link = claimLink(token); const item = `${entry.eventOption.name}${entry.variant ? ` (${entry.variant.name})` : ''}`; const until = new Date(entry.offerExpiresAt).toLocaleString('en-GB', { day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' }); const partialNote = entry.offeredQuantity < entry.quantity ? ` You asked for ${entry.quantity}; ${entry.offeredQuantity} came free, and you can take those now.` : ''; const line = `${entry.offeredQuantity} × ${item} for ${entry.event.title} ${entry.offeredQuantity === 1 ? 'is' : 'are'} now available for you.${partialNote} We'll hold ${entry.offeredQuantity === 1 ? 'it' : 'them'} until ${until}.`; const hasEmail = user?.email && !user.email.endsWith('@guest.local') && !user.email.endsWith('@deleted.invalid'); const sends = []; if (hasEmail && shouldEmail(user)) { const html = emailWrapper(`
A place has opened up!
Hi ${user.name},
${line}
${ctaButton('Claim my place', link)} ${fallbackLink(link)} `, { preheader: `Your waitlist place for ${entry.event.title}` }); sends.push(sendMail({ to: user.email, subject: `A place is available: ${entry.event.title}`, html, text: `Hi ${user.name},\n\n${line}\n\nClaim it here: ${link}` })); } const wa = `🎟️ Hi ${user?.name || 'there'}, ${line} Claim it here: ${link}`; sends.push(hasEmail ? waText(user, wa) : waTextAny(user, wa)); await Promise.allSettled(sends); } const OFFER_INCLUDE = { event: true, eventOption: true, variant: true, user: { select: { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true } } }; /** Puts an entry on offer (inside the caller's transaction); returns the raw token. */ async function writeOffer(db, entry, quantity, hours) { const token = crypto.randomBytes(24).toString('hex'); await db.waitlistEntry.update({ where: { id: entry.id }, data: { status: 'offered', offeredQuantity: quantity, offerTokenHash: hashToken(token), offeredAt: new Date(), offerExpiresAt: new Date(Date.now() + (hours || 24) * 60 * 60 * 1000), }, }); return token; } async function notifyOffers(offers) { for (const { entryId, token } of offers) { const entry = await prisma.waitlistEntry.findUnique({ where: { id: entryId }, include: OFFER_INCLUDE }); if (entry) notifyOffer(entry, token).catch(e => console.warn('[waitlist] notify failed:', e?.message || e)); } } /** Offers `quantity` places to one entry (e.g. a supervisor's manual offer) and notifies. */ async function makeOffer(entryId, quantity) { const entry = await prisma.waitlistEntry.findUnique({ where: { id: entryId }, include: { event: true } }); const token = await writeOffer(prisma, entry, quantity, entry.event.waitlistOfferHours); await notifyOffers([{ entryId, token }]); return prisma.waitlistEntry.findUnique({ where: { id: entryId } }); } /** * Offers any free places on an event to the people waiting for them. Safe to call any * time places might have freed up; runs one event at a time under an advisory lock. * @returns {Promise