/** * Ticket stock — the one place that decides how many places are taken. * * Taken = places on registrations that aren't cancelled + places held for a live * waitlist offer (until it expires). An option's stock limit covers all its variants; * a variant can also have its own limit. 0 means unlimited. */ const prisma = require('../config/db'); /** * @param {{ eventOptionId: string, variantId?: string|null }} line - variantId given → that variant only * @param {{ excludeEntryId?: string, db?: object }} [opts] - excludeEntryId: ignore this * waitlist offer's hold (the person claiming it) */ async function takenCount({ eventOptionId, variantId = null }, { excludeEntryId = null, db = prisma } = {}) { const scope = variantId ? { variantId } : { eventOptionId }; const [registered, held] = await Promise.all([ db.registrationOption.aggregate({ where: { ...scope, registration: { status: { not: 'cancelled' } } }, _sum: { quantity: true }, }), db.waitlistEntry.aggregate({ where: { ...scope, status: 'offered', offerExpiresAt: { gt: new Date() }, ...(excludeEntryId ? { id: { not: excludeEntryId } } : {}), }, _sum: { offeredQuantity: true }, }), ]); return (registered._sum?.quantity || 0) + (held._sum?.offeredQuantity || 0); } /** * Places still free on a line: the tighter of the option and variant limits. * @returns {Promise} null when unlimited */ async function remainingFor(option, variant, opts = {}) { const limits = []; if (option?.stockLimit > 0) { limits.push(option.stockLimit - await takenCount({ eventOptionId: option.id }, opts)); } if (variant?.stockLimit > 0) { limits.push(variant.stockLimit - await takenCount({ eventOptionId: option.id, variantId: variant.id }, opts)); } if (limits.length === 0) return null; return Math.max(0, Math.min(...limits)); } module.exports = { takenCount, remainingFor };