/** * Season passes (1.47.3): one price for a ticket at each of several events in a series. * * - A supervisor picks the events on the pass, and which ticket (and variant) at each. * - Buying registers the buyer at every event on it at once (`quantity` places each) and starts * one online checkout for the total. A free pass gives the tickets straight away. * - The price is split across the events in proportion to their normal ticket prices (whole * cents, `splitCents`), and each registration's line is priced at its event's share, so every * event's cashup and reports count only its part. Those lines are never repriced, take no * coupons, and can't be edited. * - The payment comes back as one provider payment; it's recorded as one Payment per event * (`recordPassPayment`), all linked to the purchase. * - A pass stops selling when the first event on it starts, at its sale end, or when switched off. */ const prisma = require('../config/db'); const { v4: uuidv4 } = require('uuid'); function passError(message, statusCode = 400) { const err = new Error(message); err.statusCode = statusCode; return err; } const toCents = n => Math.round(Number(n || 0) * 100); /** * Splits `totalCents` in proportion to `weights` (whole cents that add up exactly; the cents * left over by rounding down go to the largest remainders). All weights zero → equal parts. * Pure, for tests. */ function splitCents(totalCents, weights) { if (!weights.length) return []; const w = weights.map(x => Math.max(0, Number(x) || 0)); const sum = w.reduce((s, x) => s + x, 0); const shares = sum > 0 ? w.map(x => (totalCents * x) / sum) : w.map(() => totalCents / w.length); const out = shares.map(Math.floor); let left = totalCents - out.reduce((s, x) => s + x, 0); const order = shares.map((s, i) => ({ i, frac: s - Math.floor(s) })).sort((a, b) => b.frac - a.frac || a.i - b.i); for (let k = 0; left > 0; k = (k + 1) % order.length, left--) out[order[k].i]++; return out; } /** The normal price of one place on an item: the variant's own price, else the option's. */ function normalPrice(item) { const v = item.variant; return Number(v && v.price !== null && v.price !== undefined ? v.price : item.eventOption?.price || 0); } /** * Each item's share of the pass price (rand, one pass), in proportion to its normal price. * Pure, for tests: items need eventOption.price (and variant.price when there is one). */ function itemShares(price, items) { return splitCents(toCents(price), items.map(i => toCents(normalPrice(i)))).map(c => c / 100); } /** * How much of a payment goes to each registration: each gets what it still owes, in order, and * anything over goes to the last one. `dues` in rand. Pure, for tests. */ function allocate(dues, amount) { let left = toCents(amount); const out = dues.map(d => { const take = Math.min(left, Math.max(0, toCents(d))); left -= take; return take; }); if (left > 0 && out.length) out[out.length - 1] += left; return out.map(c => c / 100); } const ITEM_INCLUDE = { event: { select: { id: true, title: true, startDate: true, endDate: true, isActive: true, seriesId: true, campusId: true, registrationDeadline: true, scheduleType: true, attendanceMode: true, lateJoinEnabled: true, lateJoinUntilSessionId: true, requiresParentalConsent: true, requiresRegistration: true, cashupStatus: true, kidsOptionId: true, volunteerOptionId: true, sessions: { select: { id: true, startsAt: true, endsAt: true, cancelledAt: true } }, }, }, eventOption: { select: { id: true, name: true, price: true, stockLimit: true, eventId: true, sessionMode: true } }, variant: { select: { id: true, name: true, price: true, stockLimit: true, eventOptionId: true } }, }; const PASS_INCLUDE = { items: { orderBy: { order: 'asc' }, include: ITEM_INCLUDE }, series: { select: { id: true, name: true, slug: true } } }; /** Why a pass can't be bought right now, or null. */ function notOnSale(pass, now = new Date()) { if (!pass.isActive) return 'This pass isn\'t on sale.'; if (!pass.items.length) return 'This pass has no events yet.'; if (pass.saleEndsAt && new Date(pass.saleEndsAt) <= now) return 'This pass is no longer on sale.'; const { wholeCourseClosesAt } = require('./sessions'); for (const i of pass.items) { if (!i.event.isActive || i.event.cashupStatus === 'closed') return `${i.event.title} isn't taking registrations.`; if (new Date(i.event.startDate) <= now) return 'This pass stopped selling when its first event started.'; if (wholeCourseClosesAt(i.event, i.event.sessions) <= now) return `Registration for ${i.event.title} has closed.`; } return null; } /** A pass as shown to buyers and supervisors: its events with normal prices and shares. */ function passView(pass, now = new Date()) { const shares = itemShares(pass.price, pass.items); const normalValue = Math.round(pass.items.reduce((s, i) => s + normalPrice(i), 0) * 100) / 100; return { id: pass.id, seriesId: pass.seriesId, name: pass.name, description: pass.description, price: pass.price, isActive: pass.isActive, saleEndsAt: pass.saleEndsAt, series: pass.series, normalValue, saving: Math.max(0, Math.round((normalValue - pass.price) * 100) / 100), unavailable: notOnSale(pass, now), items: pass.items.map((i, k) => ({ id: i.id, eventId: i.eventId, eventOptionId: i.eventOptionId, variantId: i.variantId, eventTitle: i.event.title, startDate: i.event.startDate, endDate: i.event.endDate, campusId: i.event.campusId, ticket: i.variant ? `${i.eventOption.name} — ${i.variant.name}` : i.eventOption.name, normalPrice: normalPrice(i), share: shares[k], })), }; } // ─── Setting passes up ─────────────────────────────────────────────────────── /** * Checks a create/update body against the series' events: each item is an event in the series * with one of its tickets (not the staff-only kids/volunteer ones, not a per-session ticket) and * no parental consent (a pass can't collect children's details). Returns the data to save and the * events on it (for the campus check). */ async function cleanPassInput(body, seriesId, current = null, db = prisma) { const data = {}; if (body.name !== undefined || !current) { const name = String(body.name || '').trim(); if (!name) throw passError('Give the pass a name'); data.name = name.slice(0, 120); } if (body.description !== undefined) data.description = String(body.description || '').trim() || null; if (body.price !== undefined || !current) { const price = Number(body.price); if (!(price >= 0) || !Number.isFinite(price)) throw passError('Enter the pass price (0 for free)'); data.price = Math.round(price * 100) / 100; } if (body.isActive !== undefined) data.isActive = body.isActive !== false; if (body.saleEndsAt !== undefined) { const d = body.saleEndsAt ? new Date(body.saleEndsAt) : null; if (d && isNaN(d.getTime())) throw passError('The sale end date isn\'t valid'); data.saleEndsAt = d; } let items = null; if (body.items !== undefined || !current) { if (!Array.isArray(body.items) || body.items.length === 0) throw passError('Choose at least one event for the pass'); const seen = new Set(); items = []; for (const [order, raw] of body.items.entries()) { const eventId = String(raw?.eventId || ''); if (seen.has(eventId)) throw passError('Each event can only be on a pass once'); seen.add(eventId); const event = await db.event.findUnique({ where: { id: eventId }, select: { id: true, title: true, seriesId: true, campusId: true, requiresParentalConsent: true, requiresRegistration: true, kidsOptionId: true, volunteerOptionId: true, scheduleType: true, attendanceMode: true, eventOptions: { select: { id: true, sessionMode: true, variants: { select: { id: true } } } } }, }); if (!event || event.seriesId !== seriesId) throw passError('Every event on a pass must be in its series'); if (event.requiresParentalConsent) throw passError(`${event.title} is a youth event (parental consent), so it can't be on a pass`); if (event.requiresRegistration === false) throw passError(`${event.title} doesn't take registrations`); const option = event.eventOptions.find(o => o.id === raw.eventOptionId); if (!option || [event.kidsOptionId, event.volunteerOptionId].includes(option.id)) throw passError(`Choose a ticket for ${event.title}`); if (event.scheduleType === 'sessions' && event.attendanceMode === 'pick' && option.sessionMode === 'pick') { throw passError(`${event.title}: choose a ticket for all sessions, not a per-session one`); } const variantId = raw.variantId ? String(raw.variantId) : null; if (variantId && !option.variants.some(v => v.id === variantId)) throw passError(`That variant isn't one of the ticket's at ${event.title}`); items.push({ eventId, eventOptionId: option.id, variantId, order, campusId: event.campusId }); } } return { data, items }; } async function loadPass(id, db = prisma) { const pass = await db.seasonPass.findUnique({ where: { id }, include: PASS_INCLUDE }); if (!pass) throw passError('Season pass not found', 404); return pass; } // ─── Buying ────────────────────────────────────────────────────────────────── /** * Buys `quantity` passes for `userId`: a registration at each event (lines priced at the share), * then one checkout for the total — or, for a free pass, the tickets straight away. * @returns {Promise<{ purchaseId, total, paid, redirectUrl, provider, message }>} */ async function buyPass(passId, userId, { quantity = 1, provider = null, successUrl, cancelUrl, failureUrl } = {}) { const qty = parseInt(quantity, 10); if (!(qty >= 1 && qty <= 20)) throw passError('Choose how many passes (1 to 20)'); const pass = await loadPass(passId); const reason = notOnSale(pass); if (reason) throw passError(reason, 409); const shares = itemShares(pass.price, pass.items); const total = Math.round(pass.price * qty * 100) / 100; const free = total === 0; const { remainingFor } = require('./stock'); const purchase = await prisma.$transaction(async tx => { // One buyer at a time per pass, so the last places can't be sold twice through passes. await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${'seasonpass:' + pass.id}))`; for (const i of pass.items) { const left = await remainingFor(i.eventOption, i.variant, { db: tx }); if (left !== null && left < qty) throw passError(`${i.event.title} has ${left === 0 ? 'no places' : `only ${left} place${left === 1 ? '' : 's'}`} left for ${i.variant ? i.variant.name : i.eventOption.name}`, 409); } const created = await tx.seasonPassPurchase.create({ data: { passId: pass.id, userId, quantity: qty, total, status: free ? 'paid' : 'pending' } }); for (const [k, i] of pass.items.entries()) { const registration = await tx.registration.create({ data: { userId, eventId: i.eventId, status: free ? 'paid' : 'pending', seasonPassPurchaseId: created.id }, }); const line = await tx.registrationOption.create({ data: { registrationId: registration.id, eventOptionId: i.eventOptionId, variantId: i.variantId, quantity: qty, priceSnapshot: shares[k] }, }); await tx.registrationOptionTranche.create({ data: { registrationOptionId: line.id, quantity: qty, priceSnapshot: shares[k] } }); } return created; }); const registrations = await prisma.registration.findMany({ where: { seasonPassPurchaseId: purchase.id }, select: { id: true } }); if (free) { const { generateTicketsForRegistration } = require('./ticketUtils'); for (const r of registrations) await generateTicketsForRegistration(r.id).catch(e => console.error('[season-pass] tickets:', e?.message || e)); emailTicketsFor(userId, registrations.map(r => r.id)); return { purchaseId: purchase.id, total, paid: true, redirectUrl: null, provider: null, message: 'Your tickets are ready.' }; } return { purchaseId: purchase.id, total, paid: false, ...(await startPassCheckout(purchase.id, userId, { provider, successUrl, cancelUrl, failureUrl })) }; } /** * Starts (or restarts) the online checkout for what's still owed on a purchase. When online * payment isn't possible (none set up, or under the minimum) the places stay booked unpaid and * the buyer is told to pay the church. */ async function startPassCheckout(purchaseId, userId, { provider = null, successUrl, cancelUrl, failureUrl } = {}) { const purchase = await prisma.seasonPassPurchase.findUnique({ where: { id: purchaseId }, include: { pass: { select: { name: true } }, user: { select: { name: true, email: true } }, registrations: { include: { event: { select: { title: true } }, registrationOptions: { include: { tranches: true } }, payments: true } }, }, }); if (!purchase || purchase.userId !== userId) throw passError('Purchase not found', 404); const { computeRegistrationTotalDue } = require('./pricing'); const owed = purchase.registrations .filter(r => r.status !== 'cancelled') .map(r => ({ r, due: Math.max(0, computeRegistrationTotalDue(r, new Date()) - r.payments.reduce((s, p) => s + p.amount, 0)) })) .filter(x => x.due > 0.004); const amountCents = owed.reduce((s, x) => s + toCents(x.due), 0); if (amountCents <= 0) throw passError('This pass is already paid'); const payments = require('../payments'); try { const checkout = await payments.createCheckout(provider, { amountCents, metadata: { type: 'season_pass', purchaseId: purchase.id, userId, passName: purchase.pass.name }, lineItems: owed.map(x => ({ name: `${purchase.pass.name}: ${x.r.event.title}`, quantity: 1, unitCents: toCents(x.due) })), successUrl, cancelUrl, failureUrl, payer: { name: purchase.user?.name || '', email: purchase.user?.email || '' }, description: purchase.pass.name, idempotencyKey: `pass_${purchase.id}_${amountCents}_${Date.now()}`, }); await prisma.seasonPassPurchase.update({ where: { id: purchase.id }, data: { checkoutId: checkout.checkoutId } }); return { redirectUrl: checkout.redirectUrl, provider: checkout.provider, message: null }; } catch (e) { // Online payment not possible (switched off, not set up, or under the minimum): keep the places. if (e.statusCode && (e.statusCode < 500 || e.statusCode === 503)) { return { redirectUrl: null, provider: null, message: `Your places are booked. ${e.message}` }; } throw e; } } function emailTicketsFor(userId, registrationIds) { (async () => { const { emailTickets } = require('../controllers/ticketController'); for (const registrationId of registrationIds) { const mockReq = { user: { id: userId }, body: { registrationId } }; const mockRes = { status: () => mockRes, json: () => {} }; try { await emailTickets(mockReq, mockRes); } catch (e) { console.error('[season-pass] emailing tickets:', e?.message || e); } } })(); } /** * A pass checkout was paid (webhook or status check): one Payment per registration on the * purchase for what it owed, all linked to the purchase, then each registration's status and * tickets. Idempotent on the provider's payment id (the first Payment carries it). */ async function recordPassPayment(providerId, event, body) { const { externalId, amountCents, status, metadata = {}, methodType } = event.transaction; const webhook = require('../payments/webhook'); const existing = await prisma.payment.findFirst({ where: { externalId } }); if (existing) { await webhook.saveProviderTransaction(providerId, event, body, { reconciled: true, paymentId: existing.id }).catch(() => {}); return { status: 'already_processed', paymentId: existing.id, externalId }; } const purchase = await prisma.seasonPassPurchase.findUnique({ where: { id: String(metadata.purchaseId || '') }, include: { registrations: { orderBy: { createdAt: 'asc' }, include: { registrationOptions: { include: { tranches: true } }, payments: true } } }, }); if (!purchase) throw passError(`Season pass purchase ${metadata.purchaseId} not found`, 404); const { computeRegistrationTotalDue } = require('./pricing'); const regs = purchase.registrations.filter(r => r.status !== 'cancelled'); const dues = regs.map(r => Math.max(0, computeRegistrationTotalDue(r, new Date()) - r.payments.reduce((s, p) => s + p.amount, 0))); const parts = allocate(dues, (amountCents || 0) / 100); const method = methodType || 'card'; const paymentStatus = status === 'succeeded' ? 'completed' : status; const created = []; for (const [k, r] of regs.entries()) { if (!(parts[k] > 0)) continue; created.push(await prisma.payment.create({ data: { id: uuidv4(), amount: parts[k], method, provider: providerId, status: paymentStatus, externalId: created.length === 0 ? externalId : null, registrationId: r.id, eventId: r.eventId, userId: purchase.userId, recordedById: purchase.userId, seasonPassPurchaseId: purchase.id, }, })); } const paidIds = []; for (const r of regs) { const updated = await webhook.updateRegistrationStatus(r.id); if (updated.status === 'paid') paidIds.push(r.id); } if (paidIds.length === regs.length) await prisma.seasonPassPurchase.update({ where: { id: purchase.id }, data: { status: 'paid' } }); if (created[0]) await webhook.saveProviderTransaction(providerId, event, body, { reconciled: true, paymentId: created[0].id }).catch(() => {}); (async () => { const { sendPaymentEmails } = require('./notifications'); for (const p of created) { try { await sendPaymentEmails(p.id); } catch (e) { console.error('[season-pass] payment email:', e?.message || e); } } })(); emailTicketsFor(purchase.userId, paidIds); return { status: 'success', purchaseId: purchase.id, payments: created.map(p => ({ id: p.id, amount: p.amount, eventId: p.eventId })) }; } /** Route guard: a registration from a season pass keeps its lines as bought (no edits, no coupons). */ function notOnSeasonPass(req, res, next) { prisma.registration.findUnique({ where: { id: req.params.id }, select: { seasonPassPurchaseId: true } }) .then(r => (r?.seasonPassPurchaseId ? res.status(409).json({ message: 'This registration is part of a season pass, so its tickets can\'t be changed and codes can\'t be added. Ask the organiser if something needs to change.' }) : next())) .catch(next); } // ─── Privacy ───────────────────────────────────────────────────────────────── async function exportPurchases(userId, db = prisma) { const rows = await db.seasonPassPurchase.findMany({ where: { userId }, orderBy: { createdAt: 'asc' }, select: { quantity: true, total: true, status: true, createdAt: true, pass: { select: { name: true } } } }); return rows.map(r => ({ pass: r.pass.name, quantity: r.quantity, total: r.total, status: r.status, at: r.createdAt })); } module.exports = { splitCents, itemShares, allocate, normalPrice, notOnSale, passView, cleanPassInput, loadPass, buyPass, startPassCheckout, recordPassPayment, notOnSeasonPass, exportPurchases, passError, PASS_INCLUDE, };