Season passes (1.47.3)

A pass sells a ticket at each of several events in a series for one
price. Supervisors set passes up on the Event series page (events and
ticket per event; fixed once sold). Buying on the series page registers
the buyer at every event at once with one checkout (free passes give
tickets straight away; Pay now if online payment isn't possible). The
price is split over the events in proportion to their normal prices:
each registration line is priced at its share and the webhook records
one Payment per event, so cashups stay per event. Pass registrations
aren't repriced, take no coupons and can't be edited. Migration
20261028150000_season_pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 11:19:58 +02:00
co-authored by Claude Opus 5.5
parent 24cd604b43
commit cf7d00bdf3
34 changed files with 1396 additions and 26 deletions
@@ -0,0 +1,146 @@
const prisma = require('../config/db');
const { logAdminAction } = require('../utils/adminAudit');
const { getClientIp } = require('../utils/requestUtils');
const { scopeFor, canManage } = require('../utils/campusScope');
const passes = require('../utils/seasonPass');
const fail = (res, error) => res.status(error.statusCode || 400).json({ message: error.message });
const audit = (req, pass, action, metadata = {}) => logAdminAction({
actorId: req.user.id, actorRole: req.user.role, action: 'season_pass_changed', targetType: 'SeasonPass', targetId: pass.id,
metadata: { action, name: pass.name, ...metadata }, ip: getClientIp(req),
});
/** Campus-scoped supervisors may only put their own campuses' events on a pass. */
async function assertCampuses(req, campusIds) {
const scope = await scopeFor(req);
if (scope && campusIds.some(c => !canManage(scope, c))) {
const err = new Error('You can only put events from your own campuses on a pass (not events for all campuses).');
err.statusCode = 403;
throw err;
}
}
const frontendUrl = () => String(process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
// @desc A series' passes with their events, shares, and how many were sold
// @route GET /api/season-passes?seriesId=
// @access Private/Supervisor
const listPasses = async (req, res) => {
try {
const where = req.query.seriesId ? { seriesId: String(req.query.seriesId) } : {};
const rows = await prisma.seasonPass.findMany({ where, orderBy: { createdAt: 'asc' }, include: passes.PASS_INCLUDE });
const sold = await prisma.seasonPassPurchase.groupBy({ by: ['passId', 'status'], where: { passId: { in: rows.map(r => r.id) } }, _sum: { quantity: true } });
res.json(rows.map(p => ({
...passes.passView(p),
sold: sold.filter(s => s.passId === p.id && s.status === 'paid').reduce((n, s) => n + (s._sum.quantity || 0), 0),
unpaid: sold.filter(s => s.passId === p.id && s.status === 'pending').reduce((n, s) => n + (s._sum.quantity || 0), 0),
})));
} catch (error) { fail(res, error); }
};
// @route POST /api/season-passes { seriesId, name, description?, price, saleEndsAt?, items: [{ eventId, eventOptionId, variantId? }] }
// @access Private/Supervisor
const createPass = async (req, res) => {
try {
const seriesId = String(req.body?.seriesId || '');
if (!(await prisma.eventSeries.findUnique({ where: { id: seriesId }, select: { id: true } }))) return res.status(404).json({ message: 'Series not found' });
const { data, items } = await passes.cleanPassInput(req.body, seriesId);
await assertCampuses(req, items.map(i => i.campusId));
const pass = await prisma.seasonPass.create({
data: { ...data, seriesId, items: { create: items.map(({ campusId, ...i }) => i) } },
});
audit(req, pass, 'created', { events: items.length, price: pass.price });
res.status(201).json(passes.passView(await passes.loadPass(pass.id)));
} catch (error) { fail(res, error); }
};
// @desc Change a pass. Its events can only change while nobody has bought it.
// @route PUT /api/season-passes/:id
// @access Private/Supervisor
const updatePass = async (req, res) => {
try {
const current = await passes.loadPass(req.params.id);
await assertCampuses(req, current.items.map(i => i.event.campusId));
const { data, items } = await passes.cleanPassInput(req.body, current.seriesId, current);
const bought = await prisma.seasonPassPurchase.count({ where: { passId: current.id } });
if (bought > 0 && (items || (data.price !== undefined && data.price !== current.price))) {
return res.status(409).json({ message: 'People have bought this pass, so its events and price can\'t change. Switch it off and make a new one instead.' });
}
if (items) await assertCampuses(req, items.map(i => i.campusId));
await prisma.$transaction(async tx => {
await tx.seasonPass.update({ where: { id: current.id }, data });
if (items) {
await tx.seasonPassItem.deleteMany({ where: { passId: current.id } });
await tx.seasonPassItem.createMany({ data: items.map(({ campusId, ...i }) => ({ ...i, passId: current.id })) });
}
});
audit(req, current, 'updated', { changedKeys: [...Object.keys(data), ...(items ? ['items'] : [])] });
res.json(passes.passView(await passes.loadPass(current.id)));
} catch (error) { fail(res, error); }
};
// @desc Delete a pass nobody has bought (otherwise switch it off)
// @route DELETE /api/season-passes/:id
// @access Private/Supervisor
const deletePass = async (req, res) => {
try {
const current = await passes.loadPass(req.params.id);
await assertCampuses(req, current.items.map(i => i.event.campusId));
if (await prisma.seasonPassPurchase.count({ where: { passId: current.id } })) {
return res.status(409).json({ message: 'People have bought this pass, so it can\'t be deleted — switch it off instead.' });
}
await prisma.seasonPass.delete({ where: { id: current.id } });
audit(req, current, 'deleted');
res.json({ ok: true });
} catch (error) { fail(res, error); }
};
// @desc Buy passes: registers the buyer at every event on it, then the checkout (or tickets, if free)
// @route POST /api/season-passes/:id/buy { quantity, provider? }
// @access Private
const buy = async (req, res) => {
try {
const pass = await prisma.seasonPass.findUnique({ where: { id: req.params.id }, select: { series: { select: { slug: true } } } });
if (!pass) return res.status(404).json({ message: 'Season pass not found' });
const back = `${frontendUrl()}/series/${pass.series.slug}`;
const result = await passes.buyPass(req.params.id, req.user.id, {
quantity: req.body?.quantity ?? 1, provider: req.body?.provider || null,
successUrl: `${back}?pass=paid`, cancelUrl: `${back}?pass=cancelled`, failureUrl: `${back}?pass=failed`,
});
res.status(201).json(result);
} catch (error) { fail(res, error); }
};
// @desc Pay what's still owed on a purchase (a new checkout)
// @route POST /api/season-passes/purchases/:id/checkout
// @access Private (the buyer)
const payPurchase = async (req, res) => {
try {
const purchase = await prisma.seasonPassPurchase.findUnique({ where: { id: req.params.id }, select: { userId: true, pass: { select: { series: { select: { slug: true } } } } } });
if (!purchase || purchase.userId !== req.user.id) return res.status(404).json({ message: 'Purchase not found' });
const back = `${frontendUrl()}/series/${purchase.pass.series.slug}`;
res.json(await passes.startPassCheckout(req.params.id, req.user.id, {
provider: req.body?.provider || null, successUrl: `${back}?pass=paid`, cancelUrl: `${back}?pass=cancelled`, failureUrl: `${back}?pass=failed`,
}));
} catch (error) { fail(res, error); }
};
// @desc The signed-in person's pass purchases
// @route GET /api/season-passes/mine
// @access Private
const myPurchases = async (req, res) => {
try {
const rows = await prisma.seasonPassPurchase.findMany({
where: { userId: req.user.id }, orderBy: { createdAt: 'desc' },
select: {
id: true, quantity: true, total: true, status: true, createdAt: true,
pass: { select: { id: true, name: true, series: { select: { name: true, slug: true } } } },
registrations: { select: { id: true, status: true, event: { select: { id: true, title: true, startDate: true } } } },
},
});
res.json(rows);
} catch (error) { fail(res, error); }
};
module.exports = { listPasses, createPass, updatePass, deletePass, buy, payPurchase, myPurchases };
@@ -69,6 +69,9 @@ const deleteSeries = async (req, res) => {
try {
const current = await prisma.eventSeries.findUnique({ where: { id: req.params.id }, include: { _count: { select: { events: true, followers: true } } } });
if (!current) return res.status(404).json({ message: 'Series not found' });
if (await prisma.seasonPassPurchase.count({ where: { pass: { seriesId: current.id } } })) {
return res.status(409).json({ message: 'People have bought season passes for this series, so it can\'t be deleted.' });
}
await prisma.eventSeries.delete({ where: { id: current.id } });
audit(req, 'series_deleted', current, { events: current._count.events, followers: current._count.followers });
res.json({ ok: true });
@@ -92,7 +95,12 @@ const getSeriesBySlug = async (req, res) => {
});
const { upcoming, past } = splitEvents(events);
const following = req.user ? !!(await prisma.seriesFollow.findUnique({ where: { seriesId_userId: { seriesId: series.id, userId: req.user.id } } })) : false;
res.json({ ...series, upcoming, past, following });
// Season passes switched on (1.47.3); `unavailable` says why one can't be bought now.
const { passView, PASS_INCLUDE } = require('../utils/seasonPass');
const passes = (await prisma.seasonPass.findMany({ where: { seriesId: series.id, isActive: true }, orderBy: { createdAt: 'asc' }, include: PASS_INCLUDE }))
.map(p => passView(p))
.map(({ items, ...p }) => ({ ...p, items: items.map(({ campusId, ...i }) => i) }));
res.json({ ...series, upcoming, past, following, passes });
} catch (error) { fail(res, error); }
};
+5
View File
@@ -16,6 +16,11 @@ const BLOCKED = [
['POST', /^\/api\/events\/[^/]+\/copy-from\/?$/],
['POST', /^\/api\/series\/?$/],
['PUT', /^\/api\/series\/[^/]+\/?$/],
// Season passes: new or changed passes, and buying one (it makes registrations and payments).
['POST', /^\/api\/season-passes\/?$/],
['PUT', /^\/api\/season-passes\/[^/]+\/?$/],
['POST', /^\/api\/season-passes\/[^/]+\/buy\/?$/],
['POST', /^\/api\/season-passes\/purchases\/[^/]+\/checkout\/?$/],
['POST', /^\/api\/events\/[^/]+\/options\/?$/],
['PUT', /^\/api\/events\/options\/[^/]+\/?$/],
['POST', /^\/api\/events\/options\/[^/]+\/variants\/?$/],
+13
View File
@@ -186,6 +186,7 @@ app.use('/api/campuses', require('./routes/campusRoutes'));
app.use('/api/kids', require('./routes/kidsRoutes'));
app.use('/api/volunteers', require('./routes/volunteerRoutes'));
app.use('/api/series', require('./routes/seriesRoutes'));
app.use('/api/season-passes', require('./routes/seasonPassRoutes'));
app.use('/api/users', userRoutes);
app.use('/api/events', eventRoutes);
app.use('/api/registrations', registrationRoutes);
@@ -1010,6 +1011,18 @@ app.get('/docs', async (req, res) => {
{ method:'GET', path:'/api/series/:id/compare', auth:'supervisor+', desc:'Year on year: registrations, tickets, income (as on the dashboard), checked in (average per session on multi-session events) and attendance rate per event in the series, oldest first, with the % change from the one before. Campus-scoped staff: their campuses\x27 events only' },
]},
{ title: 'Season passes', base: '/api/season-passes', endpoints: [
{ method:'GET', path:'/api/season-passes?seriesId=', auth:'supervisor+', desc:'A series\x27 passes: events, normal prices, each event\x27s share, sold and unpaid counts' },
{ method:'POST', path:'/api/season-passes', auth:'supervisor+', desc:'Create a pass. Events must be in the series; not youth (consent) events, staff-only or per-session tickets. Campus-scoped supervisors: only their campuses\x27 events. Audited as season_pass_changed',
request:{ body:{ seriesId:'series-uuid', name:'2027 breakfasts', price:400, saleEndsAt:null, items:[{ eventId:'ev-uuid', eventOptionId:'opt-uuid', variantId:null }] } } },
{ method:'PUT', path:'/api/season-passes/:id', auth:'supervisor+', desc:'Change a pass (events and price only while nobody has bought it; 409 otherwise)' },
{ method:'DELETE', path:'/api/season-passes/:id', auth:'supervisor+', desc:'Delete a pass nobody has bought' },
{ method:'POST', path:'/api/season-passes/:id/buy', auth:'user', desc:'Buy passes: a registration at every event (lines priced at each event\x27s share), then one checkout for the total (redirectUrl), or tickets straight away when free. 409 when not on sale or an event has too few places',
request:{ body:{ quantity:2 } }, responses:[{ status:201, desc:'Bought', body:{ purchaseId:'uuid', total:800, paid:false, redirectUrl:'https://…', provider:'yoco', message:null } }] },
{ method:'POST', path:'/api/season-passes/purchases/:id/checkout', auth:'user', desc:'Pay what is still owed on my purchase (a new checkout)' },
{ method:'GET', path:'/api/season-passes/mine', auth:'user', desc:'My pass purchases with their registrations' },
]},
{ title: 'Volunteer rosters', base: '/api/volunteers', endpoints: [
{ method:'GET', path:'/api/volunteers/me', auth:'user', desc:'My shifts (upcoming and the last week), cover requests I could take, and events looking for volunteers' },
{ method:'GET', path:'/api/volunteers/events/:eventId', auth:'user', desc:'An event\'s serving roles: shift, how many are needed and signed up, whether I\'m in it, open cover requests' },
@@ -19,6 +19,12 @@ async function checkoutPaid(checkout) {
const refs = [checkout.id, checkout.externalId].filter(Boolean);
const tx = await prisma.providerTransaction.findFirst({ where: { checkoutId: { in: refs }, paymentId: { not: null } }, select: { id: true } });
if (tx) return true;
// A season pass checkout: paid once its purchase is.
const purchaseId = checkout.metadata?.purchaseId;
if (purchaseId) {
const purchase = await prisma.seasonPassPurchase.findUnique({ where: { id: String(purchaseId) }, select: { status: true } });
return purchase?.status === 'paid';
}
const registrationId = checkout.metadata?.registrationId;
if (!registrationId) return false;
const reg = await prisma.registration.findUnique({ where: { id: String(registrationId) }, select: { status: true } });
+8 -1
View File
@@ -71,7 +71,9 @@ const handleProviderWebhook = (providerId) => async (req, res) => {
if (!existingRegistration) {
const meta = tx.metadata || {};
const isDonation = meta.type === 'donation' || !!meta.isDonation || !!meta.eventId;
if (!isDonation) {
// A season pass checkout belongs to its purchase, not to one registration.
const isSeasonPass = meta.type === 'season_pass' && !!meta.purchaseId;
if (!isDonation && !isSeasonPass) {
try { await saveProviderTransaction(provider.id, event, body); } catch (e) { console.warn('Failed to save unreconciled transaction:', e?.message || e); }
return res.status(200).json({
success: true,
@@ -141,6 +143,11 @@ async function recordSucceededPayment(providerId, event, body) {
return { status: 'already_processed', paymentId: existingPayment.id, externalId };
}
// Season pass: split over the purchase's registrations, one Payment per event.
if (metadata.type === 'season_pass' && metadata.purchaseId) {
return require('../utils/seasonPass').recordPassPayment(providerId, event, body);
}
let registration = null;
const refs = event.checkoutRefs || [checkoutId].filter(Boolean);
if (refs.length) registration = await prisma.registration.findFirst({ where: { checkoutId: { in: refs } }, include: REG_INCLUDE });
@@ -18,6 +18,7 @@ const {
} = require('../controllers/registrationController');
const { protect, supervisor, staff, optionalAuth } = require('../middleware/authMiddleware');
const { scopeEvent, scopeList } = require('../utils/campusScope');
const { notOnSeasonPass } = require('../utils/seasonPass');
// Campus-scoped staff (utils/campusScope.js). Routes open to the registration's owner as well
// as to staff check staff against the registration's event, and let the owner through (ownerOk).
@@ -25,10 +26,10 @@ const { scopeEvent, scopeList } = require('../utils/campusScope');
// Registration - auth optional when event doesn't require it
router.post('/', optionalAuth, createRegistration);
router.get('/myregistrations', protect, getUserRegistrations);
router.put('/:id/options', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), updateRegistrationOptions);
router.put('/:id/options', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), notOnSeasonPass, updateRegistrationOptions);
router.delete('/:id', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), cancelRegistration);
router.post('/:id/send-invoice', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), sendInvoice);
router.post('/:id/coupon', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), applyCoupon);
router.post('/:id/coupon', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), notOnSeasonPass, applyCoupon);
router.delete('/:id/coupon', protect, staff, scopeEvent({ resolve: 'registration' }), removeCoupon);
router.put('/:id/attendees', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), updateAttendees);
router.post('/:id/attendees/:attendeeId/send-form-link', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), sendAttendeeFormLink);
@@ -0,0 +1,18 @@
const express = require('express');
const router = express.Router();
const { listPasses, createPass, updatePass, deletePass, buy, payPurchase, myPurchases } = require('../controllers/seasonPassController');
const { protect, supervisor } = require('../middleware/authMiddleware');
const { campusIndependent } = require('../utils/campusScope');
const SPANS = campusIndependent('a pass can span campuses; each event on it is checked against the person\'s campuses in the controller');
router.get('/mine', protect, myPurchases);
router.post('/:id/buy', protect, buy);
router.post('/purchases/:id/checkout', protect, payPurchase);
router.get('/', protect, supervisor, SPANS, listPasses);
router.post('/', protect, supervisor, SPANS, createPass);
router.put('/:id', protect, supervisor, SPANS, updatePass);
router.delete('/:id', protect, supervisor, SPANS, deletePass);
module.exports = router;
+2
View File
@@ -211,6 +211,8 @@ async function refreshPricingForRegistration(registrationId) {
}
});
if (!registration) return { changed: false };
// A season pass line is priced at its event's share of the pass, never at the ticket's price.
if (registration.seasonPassPurchaseId) return { changed: false };
const totalPaid = (registration.payments || []).reduce((sum, p) => sum + (p.amount || 0), 0);
+7 -1
View File
@@ -488,7 +488,7 @@ async function exportUserData(userId, db = prisma) {
});
if (!user) return null;
const [registrations, payments, tickets, waitlist, certificates, feedback, consents, security, requests, notices, family, volunteering, seriesFollowed] = await Promise.all([
const [registrations, payments, tickets, waitlist, certificates, feedback, consents, security, requests, notices, family, volunteering, seriesFollowed, seasonPasses] = await Promise.all([
db.registration.findMany({
where: { userId },
orderBy: { createdAt: 'asc' },
@@ -515,6 +515,7 @@ async function exportUserData(userId, db = prisma) {
require('./kids').exportFamily(userId, db),
require('./volunteers').exportVolunteering(userId, db),
require('./series').exportFollows(userId, db),
require('./seasonPass').exportPurchases(userId, db),
]);
return {
@@ -559,6 +560,7 @@ async function exportUserData(userId, db = prisma) {
kidsFamily: family,
volunteering,
seriesFollowed,
seasonPasses,
};
}
@@ -619,6 +621,10 @@ async function dataExportPdf(data) {
heading('Serving (volunteer rosters)');
for (const s of data.volunteering) para(`${fmt(s.from)} — ${s.role}, ${s.event}${s.checkedIn ? ' (checked in)' : ''}`);
}
if (data.seasonPasses?.length) {
heading('Season passes');
for (const s of data.seasonPasses) para(`${fmt(s.at)} — ${s.quantity} × ${s.pass}, R${Number(s.total).toFixed(2)} (${s.status})`);
}
if (data.seriesFollowed?.length) {
heading('Event series you follow');
for (const f of data.seriesFollowed) para(`${f.series} — since ${fmt(f.since)}`);
+361
View File
@@ -0,0 +1,361 @@
/**
* 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,
};