Add coupon codes and staff pricing
Percentage, fixed-amount and comp codes, limited by event, ticket option or variant, dates, use counts, minimum quantity, and people, roles or an email domain. The discount is locked in on the registration (mirrored on Registration.discountTotal so every total sees it), shows on invoices, receipts, emails and the Yoco checkout, and is released on cancellation. Use limits are enforced under an advisory lock. Ticket options and variants can also carry a staff price that Staff and above get automatically. Adds a Supervisor > Coupon codes page, code fields on registration, My Events, manual registration, at the door and the kiosk, a Discounts report, and audit log entries. Also fixes Yoco line items and the free-registration check for lines spanning several price tranches. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,331 @@
|
||||
const prisma = require('../config/db');
|
||||
const { safeErrorMessage } = require('../utils/errorUtils');
|
||||
const { logAdminAction } = require('../utils/adminAudit');
|
||||
const { getClientIp } = require('../utils/requestUtils');
|
||||
const { normalizeCode, previewCoupon, buildCouponLines, describeCoupon, countCouponUses } = require('../utils/coupons');
|
||||
const { resolveOptionPrice, resolveVariantTierPrice } = require('../utils/pricing');
|
||||
|
||||
const TYPES = ['percent', 'fixed', 'comp'];
|
||||
const ROLES = ['user', 'staff', 'supervisor', 'admin'];
|
||||
const STAFF_ROLES = ['staff', 'supervisor', 'admin'];
|
||||
|
||||
const COUPON_DETAIL_INCLUDE = {
|
||||
events: { include: { event: { select: { id: true, title: true, startDate: true } } } },
|
||||
options: { include: { eventOption: { select: { id: true, name: true, eventId: true } }, variant: { select: { id: true, name: true } } } },
|
||||
allowedUsers: { include: { user: { select: { id: true, name: true, email: true } } } },
|
||||
createdBy: { select: { id: true, name: true } },
|
||||
};
|
||||
|
||||
const optionalDate = (v, label) => {
|
||||
if (v === undefined) return undefined;
|
||||
if (v === null || v === '') return null;
|
||||
const d = new Date(v);
|
||||
if (isNaN(d.getTime())) throw new Error(`${label} is not a valid date`);
|
||||
return d;
|
||||
};
|
||||
|
||||
const optionalInt = (v, label, min = 0) => {
|
||||
if (v === undefined) return undefined;
|
||||
if (v === null || v === '') return null;
|
||||
const n = Number(v);
|
||||
if (!Number.isInteger(n) || n < min) throw new Error(`${label} must be a whole number of at least ${min}`);
|
||||
return n;
|
||||
};
|
||||
|
||||
/**
|
||||
* Turns a create/update body into Prisma data plus the relation lists. On update,
|
||||
* fields left out of the body are left alone.
|
||||
*/
|
||||
async function parseCouponBody(body, { isCreate }) {
|
||||
const data = {};
|
||||
if (isCreate || body.code !== undefined) {
|
||||
const code = normalizeCode(body.code);
|
||||
if (!/^[A-Z0-9_-]{3,32}$/.test(code)) {
|
||||
throw new Error('Codes are 3–32 letters, numbers, hyphens or underscores');
|
||||
}
|
||||
data.code = code;
|
||||
}
|
||||
if (isCreate || body.type !== undefined) {
|
||||
if (!TYPES.includes(body.type)) throw new Error("Discount type must be 'percent', 'fixed' or 'comp'");
|
||||
data.type = body.type;
|
||||
}
|
||||
if (isCreate || body.value !== undefined) {
|
||||
const type = data.type || body.type;
|
||||
const value = type === 'comp' ? 0 : Number(body.value);
|
||||
if (type !== 'comp' && !(value > 0)) throw new Error('Enter a discount value greater than zero');
|
||||
if (type === 'percent' && value > 100) throw new Error('A percentage discount can\'t be more than 100');
|
||||
data.value = value;
|
||||
}
|
||||
if (body.description !== undefined) data.description = body.description ? String(body.description).trim() : null;
|
||||
if (body.stackEarlyBird !== undefined) data.stackEarlyBird = !!body.stackEarlyBird;
|
||||
if (body.active !== undefined) data.active = !!body.active;
|
||||
const validFrom = optionalDate(body.validFrom, 'Valid from');
|
||||
const validUntil = optionalDate(body.validUntil, 'Valid until');
|
||||
if (validFrom !== undefined) data.validFrom = validFrom;
|
||||
if (validUntil !== undefined) data.validUntil = validUntil;
|
||||
if (validFrom && validUntil && validFrom > validUntil) throw new Error('"Valid from" must be before "Valid until"');
|
||||
const maxUses = optionalInt(body.maxUses, 'Max total uses', 1);
|
||||
const maxUsesPerUser = optionalInt(body.maxUsesPerUser, 'Max uses per person', 1);
|
||||
const minQuantity = optionalInt(body.minQuantity, 'Minimum quantity', 1);
|
||||
if (maxUses !== undefined) data.maxUses = maxUses;
|
||||
if (maxUsesPerUser !== undefined) data.maxUsesPerUser = maxUsesPerUser;
|
||||
if (minQuantity !== undefined) data.minQuantity = minQuantity;
|
||||
if (body.restrictRoles !== undefined) {
|
||||
const roles = Array.isArray(body.restrictRoles) ? body.restrictRoles : [];
|
||||
if (roles.some(r => !ROLES.includes(r))) throw new Error('Unknown role in restrictions');
|
||||
data.restrictRoles = roles;
|
||||
}
|
||||
if (body.restrictDomain !== undefined) {
|
||||
const domain = String(body.restrictDomain || '').trim().toLowerCase().replace(/^@/, '');
|
||||
if (domain && !/^[a-z0-9.-]+\.[a-z]{2,}$/.test(domain)) throw new Error('Enter an email domain like church.org');
|
||||
data.restrictDomain = domain || null;
|
||||
}
|
||||
|
||||
const eventIds = body.eventIds !== undefined ? [...new Set((body.eventIds || []).filter(Boolean))] : undefined;
|
||||
const scopes = body.options !== undefined
|
||||
? (body.options || []).filter(o => o && o.eventOptionId).map(o => ({ eventOptionId: o.eventOptionId, variantId: o.variantId || null }))
|
||||
: undefined;
|
||||
const userIds = body.userIds !== undefined ? [...new Set((body.userIds || []).filter(Boolean))] : undefined;
|
||||
|
||||
if (scopes && scopes.length > 0) {
|
||||
const optionRows = await prisma.eventOption.findMany({
|
||||
where: { id: { in: scopes.map(s => s.eventOptionId) } },
|
||||
select: { id: true, eventId: true, variants: { select: { id: true } } },
|
||||
});
|
||||
for (const s of scopes) {
|
||||
const row = optionRows.find(o => o.id === s.eventOptionId);
|
||||
if (!row) throw new Error('One of the selected ticket options no longer exists');
|
||||
if (s.variantId && !row.variants.some(v => v.id === s.variantId)) throw new Error('One of the selected variants no longer exists');
|
||||
// A scoped option implies its event, so the code can't be used elsewhere by mistake.
|
||||
if (eventIds && eventIds.length > 0 && !eventIds.includes(row.eventId)) {
|
||||
throw new Error('Selected ticket options must belong to the selected events');
|
||||
}
|
||||
}
|
||||
}
|
||||
return { data, eventIds, scopes, userIds };
|
||||
}
|
||||
|
||||
function relationWrites({ eventIds, scopes, userIds }, isCreate) {
|
||||
const out = {};
|
||||
if (eventIds !== undefined) out.events = { ...(isCreate ? {} : { deleteMany: {} }), create: eventIds.map(eventId => ({ eventId })) };
|
||||
if (scopes !== undefined) out.options = { ...(isCreate ? {} : { deleteMany: {} }), create: scopes };
|
||||
if (userIds !== undefined) out.allowedUsers = { ...(isCreate ? {} : { deleteMany: {} }), create: userIds.map(userId => ({ userId })) };
|
||||
return out;
|
||||
}
|
||||
|
||||
// @desc List coupons with their use counts
|
||||
// @route GET /api/coupons
|
||||
// @access Private/Supervisor
|
||||
const listCoupons = async (req, res) => {
|
||||
try {
|
||||
const coupons = await prisma.coupon.findMany({ include: COUPON_DETAIL_INCLUDE, orderBy: { createdAt: 'desc' } });
|
||||
const totals = await prisma.couponRedemption.groupBy({
|
||||
by: ['couponId'],
|
||||
where: { releasedAt: null, registration: { status: { not: 'cancelled' } } },
|
||||
_count: { _all: true },
|
||||
_sum: { discountAmount: true },
|
||||
});
|
||||
const byId = Object.fromEntries(totals.map(t => [t.couponId, t]));
|
||||
res.json(coupons.map(c => ({
|
||||
...c,
|
||||
summary: describeCoupon(c),
|
||||
uses: byId[c.id]?._count?._all || 0,
|
||||
totalDiscount: byId[c.id]?._sum?.discountAmount || 0,
|
||||
})));
|
||||
} catch (error) {
|
||||
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Get one coupon with its redemptions
|
||||
// @route GET /api/coupons/:id
|
||||
// @access Private/Supervisor
|
||||
const getCoupon = async (req, res) => {
|
||||
try {
|
||||
const coupon = await prisma.coupon.findUnique({
|
||||
where: { id: req.params.id },
|
||||
include: {
|
||||
...COUPON_DETAIL_INCLUDE,
|
||||
redemptions: {
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
appliedBy: { select: { id: true, name: true } },
|
||||
registration: { select: { id: true, status: true, event: { select: { id: true, title: true } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!coupon) { res.status(404); throw new Error('Coupon not found'); }
|
||||
res.json({ ...coupon, summary: describeCoupon(coupon) });
|
||||
} catch (error) {
|
||||
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Create a coupon
|
||||
// @route POST /api/coupons
|
||||
// @access Private/Supervisor
|
||||
const createCoupon = async (req, res) => {
|
||||
try {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = await parseCouponBody(req.body || {}, { isCreate: true });
|
||||
} catch (e) { res.status(400); throw e; }
|
||||
if (await prisma.coupon.findUnique({ where: { code: parsed.data.code } })) {
|
||||
res.status(409); throw new Error(`The code ${parsed.data.code} already exists`);
|
||||
}
|
||||
const coupon = await prisma.coupon.create({
|
||||
data: { ...parsed.data, createdById: req.user.id, ...relationWrites(parsed, true) },
|
||||
include: COUPON_DETAIL_INCLUDE,
|
||||
});
|
||||
logAdminAction({
|
||||
actorId: req.user.id, actorRole: req.user.role, action: 'coupon_created',
|
||||
targetType: 'Coupon', targetId: coupon.id,
|
||||
metadata: { code: coupon.code, type: coupon.type, value: coupon.value },
|
||||
ip: getClientIp(req),
|
||||
});
|
||||
res.status(201).json({ ...coupon, summary: describeCoupon(coupon), uses: 0, totalDiscount: 0 });
|
||||
} catch (error) {
|
||||
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Update a coupon (including turning it off). Discounts already applied keep
|
||||
// their locked amount.
|
||||
// @route PUT /api/coupons/:id
|
||||
// @access Private/Supervisor
|
||||
const updateCoupon = async (req, res) => {
|
||||
try {
|
||||
const existing = await prisma.coupon.findUnique({ where: { id: req.params.id } });
|
||||
if (!existing) { res.status(404); throw new Error('Coupon not found'); }
|
||||
let parsed;
|
||||
try {
|
||||
parsed = await parseCouponBody({ type: existing.type, ...req.body }, { isCreate: false });
|
||||
} catch (e) { res.status(400); throw e; }
|
||||
if (parsed.data.code && parsed.data.code !== existing.code) {
|
||||
const used = await prisma.couponRedemption.count({ where: { couponId: existing.id } });
|
||||
if (used > 0) { res.status(400); throw new Error('This code has been used, so it can\'t be renamed. Turn it off and create a new one instead.'); }
|
||||
if (await prisma.coupon.findUnique({ where: { code: parsed.data.code } })) {
|
||||
res.status(409); throw new Error(`The code ${parsed.data.code} already exists`);
|
||||
}
|
||||
}
|
||||
const coupon = await prisma.coupon.update({
|
||||
where: { id: existing.id },
|
||||
data: { ...parsed.data, ...relationWrites(parsed, false) },
|
||||
include: COUPON_DETAIL_INCLUDE,
|
||||
});
|
||||
const disabled = existing.active && coupon.active === false;
|
||||
const changedKeys = Object.keys(req.body || {});
|
||||
logAdminAction({
|
||||
actorId: req.user.id, actorRole: req.user.role,
|
||||
action: disabled && changedKeys.length === 1 ? 'coupon_disabled' : 'coupon_updated',
|
||||
targetType: 'Coupon', targetId: coupon.id,
|
||||
metadata: { code: coupon.code, changedKeys },
|
||||
ip: getClientIp(req),
|
||||
});
|
||||
const { usesTotal } = await countCouponUses(coupon.id, null);
|
||||
res.json({ ...coupon, summary: describeCoupon(coupon), uses: usesTotal });
|
||||
} catch (error) {
|
||||
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Check a code against the items someone is about to register for
|
||||
// @route POST /api/coupons/validate
|
||||
// @access Public (login needed for restricted codes)
|
||||
// Body: { code, eventId, options: [{ eventOptionId, variantId?, quantity }], forUserId? }
|
||||
// Staff can pass forUserId to check on an attendee's behalf, or leave it out for a new
|
||||
// attendee — restricted codes are then checked when the registration is saved.
|
||||
const validateCode = async (req, res) => {
|
||||
try {
|
||||
const { code, eventId, options, forUserId } = req.body || {};
|
||||
if (!code || !eventId || !Array.isArray(options) || options.length === 0) {
|
||||
res.status(400); throw new Error('code, eventId and options are required');
|
||||
}
|
||||
const event = await prisma.event.findUnique({
|
||||
where: { id: eventId },
|
||||
include: { eventOptions: { include: { earlyBirdTiers: true, variants: true } } },
|
||||
});
|
||||
if (!event) { res.status(404); throw new Error('Event not found'); }
|
||||
|
||||
const isStaff = req.user && STAFF_ROLES.includes(req.user.role);
|
||||
let buyer = req.user ? { id: req.user.id, role: req.user.role, email: req.user.email } : null;
|
||||
if (isStaff && forUserId) {
|
||||
buyer = await prisma.user.findUnique({ where: { id: forUserId }, select: { id: true, role: true, email: true } });
|
||||
} else if (isStaff && forUserId === null) {
|
||||
buyer = null; // a walk-in without an account yet
|
||||
}
|
||||
|
||||
// Price the basket the same way registration will.
|
||||
const registrationOptions = [];
|
||||
for (const o of options) {
|
||||
const eo = event.eventOptions.find(x => x.id === o.eventOptionId);
|
||||
const qty = Number(o.quantity || 0);
|
||||
if (!eo || qty < 1) continue;
|
||||
const resolved = o.variantId
|
||||
? await resolveVariantTierPrice(eo, o.variantId, qty, buyer)
|
||||
: await resolveOptionPrice(eo, qty, buyer);
|
||||
registrationOptions.push({
|
||||
eventOptionId: eo.id, variantId: o.variantId || null, quantity: qty, eventOption: eo,
|
||||
tranches: [{ quantity: qty, priceSnapshot: resolved.price, appliedTierId: resolved.tierId }],
|
||||
});
|
||||
}
|
||||
const lines = buildCouponLines({ registrationOptions });
|
||||
const subtotal = lines.reduce((s, l) => s + l.unitPrice * l.quantity, 0);
|
||||
|
||||
try {
|
||||
const { coupon, discount } = await previewCoupon({
|
||||
code, eventId, user: buyer, lines,
|
||||
deferRestrictions: isStaff && !buyer,
|
||||
});
|
||||
res.json({
|
||||
valid: true,
|
||||
code: coupon.code,
|
||||
type: coupon.type,
|
||||
value: coupon.value,
|
||||
summary: describeCoupon(coupon),
|
||||
description: coupon.description,
|
||||
discount,
|
||||
subtotal,
|
||||
total: Math.max(0, subtotal - discount),
|
||||
});
|
||||
} catch (e) {
|
||||
if (!e.isCouponError) throw e;
|
||||
res.status(400).json({ valid: false, message: e.message });
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Coupon uses for the Discounts report
|
||||
// @route GET /api/coupons/redemptions?eventIds=a,b&from=&to=
|
||||
// @access Private/Supervisor
|
||||
const listRedemptions = async (req, res) => {
|
||||
try {
|
||||
const eventIds = String(req.query.eventIds || '').split(',').map(s => s.trim()).filter(Boolean);
|
||||
const from = req.query.from ? new Date(req.query.from) : null;
|
||||
const to = req.query.to ? new Date(req.query.to) : null;
|
||||
const where = {
|
||||
releasedAt: null,
|
||||
registration: { status: { not: 'cancelled' }, ...(eventIds.length ? { eventId: { in: eventIds } } : {}) },
|
||||
...(from || to ? { createdAt: { ...(from && !isNaN(from) ? { gte: from } : {}), ...(to && !isNaN(to) ? { lte: to } : {}) } } : {}),
|
||||
};
|
||||
const rows = await prisma.couponRedemption.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
coupon: { select: { id: true, code: true, type: true, value: true } },
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
appliedBy: { select: { id: true, name: true } },
|
||||
registration: { select: { id: true, status: true, event: { select: { id: true, title: true } } } },
|
||||
},
|
||||
});
|
||||
res.json(rows.map(r => ({ ...r, summary: describeCoupon(r.coupon) })));
|
||||
} catch (error) {
|
||||
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { listCoupons, getCoupon, createCoupon, updateCoupon, validateCode, listRedemptions };
|
||||
@@ -718,6 +718,15 @@ const deleteEvent = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Optional staff price from a request body: '' / null clears it, undefined leaves it.
|
||||
function parseStaffPrice(value, current = null) {
|
||||
if (value === undefined) return current;
|
||||
if (value === null || value === '') return null;
|
||||
const n = parseFloat(value);
|
||||
if (!(n >= 0)) throw new Error('Staff price must be zero or more');
|
||||
return n;
|
||||
}
|
||||
|
||||
// @desc Create event option
|
||||
// @route POST /api/events/:id/options
|
||||
// @access Private/Admin
|
||||
@@ -734,7 +743,7 @@ const createEventOption = async (req, res) => {
|
||||
|
||||
await assertEventOpen(req.params.id, res);
|
||||
|
||||
const { name, price, isMainTicket, stockLimit } = req.body;
|
||||
const { name, price, isMainTicket, stockLimit, staffPrice } = req.body;
|
||||
|
||||
const eventOption = await prisma.eventOption.create({
|
||||
data: {
|
||||
@@ -744,6 +753,7 @@ const createEventOption = async (req, res) => {
|
||||
price: parseFloat(price),
|
||||
isMainTicket: isMainTicket || false,
|
||||
stockLimit: stockLimit ? parseInt(stockLimit, 10) : 0,
|
||||
staffPrice: parseStaffPrice(staffPrice),
|
||||
}
|
||||
});
|
||||
|
||||
@@ -770,7 +780,7 @@ const updateEventOption = async (req, res) => {
|
||||
|
||||
await assertEventOpen(eventOption.eventId, res);
|
||||
|
||||
const { name, price, isMainTicket, stockLimit, earlyBirdTiers, variants } = req.body;
|
||||
const { name, price, isMainTicket, stockLimit, earlyBirdTiers, variants, staffPrice } = req.body;
|
||||
|
||||
const updatedEventOption = await prisma.eventOption.update({
|
||||
where: { id: req.params.id },
|
||||
@@ -779,6 +789,7 @@ const updateEventOption = async (req, res) => {
|
||||
price: price !== undefined ? parseFloat(price) : eventOption.price,
|
||||
isMainTicket: isMainTicket !== undefined ? isMainTicket : eventOption.isMainTicket,
|
||||
stockLimit: stockLimit !== undefined ? parseInt(stockLimit, 10) : eventOption.stockLimit,
|
||||
staffPrice: parseStaffPrice(staffPrice, eventOption.staffPrice),
|
||||
}
|
||||
});
|
||||
|
||||
@@ -847,10 +858,11 @@ const updateEventOption = async (req, res) => {
|
||||
if (!v.name) continue;
|
||||
const variantPrice = v.price !== undefined && v.price !== null && v.price !== '' ? parseFloat(v.price) : null;
|
||||
const variantStockLimit = v.stockLimit !== undefined ? parseInt(v.stockLimit, 10) : 0;
|
||||
const variantStaffPrice = parseStaffPrice(v.staffPrice);
|
||||
if (v.id) {
|
||||
await prisma.optionVariant.update({
|
||||
where: { id: v.id },
|
||||
data: { name: v.name, price: variantPrice, stockLimit: variantStockLimit, order: i }
|
||||
data: { name: v.name, price: variantPrice, stockLimit: variantStockLimit, staffPrice: variantStaffPrice, order: i }
|
||||
});
|
||||
} else {
|
||||
await prisma.optionVariant.create({
|
||||
@@ -860,6 +872,7 @@ const updateEventOption = async (req, res) => {
|
||||
name: v.name,
|
||||
price: variantPrice,
|
||||
stockLimit: variantStockLimit,
|
||||
staffPrice: variantStaffPrice,
|
||||
order: i,
|
||||
}
|
||||
});
|
||||
@@ -937,7 +950,7 @@ const createOptionVariant = async (req, res) => {
|
||||
const eventOption = await prisma.eventOption.findUnique({ where: { id: req.params.id } });
|
||||
if (!eventOption) { res.status(404); throw new Error('Event option not found'); }
|
||||
await assertEventOpen(eventOption.eventId, res);
|
||||
const { name, price, stockLimit, order } = req.body;
|
||||
const { name, price, stockLimit, order, staffPrice } = req.body;
|
||||
if (!name) { res.status(400); throw new Error('Variant name is required'); }
|
||||
const variant = await prisma.optionVariant.create({
|
||||
data: {
|
||||
@@ -946,6 +959,7 @@ const createOptionVariant = async (req, res) => {
|
||||
name,
|
||||
price: price !== undefined && price !== null && price !== '' ? parseFloat(price) : null,
|
||||
stockLimit: stockLimit ? parseInt(stockLimit, 10) : 0,
|
||||
staffPrice: parseStaffPrice(staffPrice),
|
||||
order: order !== undefined ? parseInt(order, 10) : 0,
|
||||
}
|
||||
});
|
||||
@@ -963,11 +977,12 @@ const updateOptionVariant = async (req, res) => {
|
||||
const variant = await prisma.optionVariant.findUnique({ where: { id: req.params.id }, include: { eventOption: { select: { eventId: true } } } });
|
||||
if (!variant) { res.status(404); throw new Error('Variant not found'); }
|
||||
await assertEventOpen(variant.eventOption.eventId, res);
|
||||
const { name, price, stockLimit, order } = req.body;
|
||||
const { name, price, stockLimit, order, staffPrice } = req.body;
|
||||
const updated = await prisma.optionVariant.update({
|
||||
where: { id: req.params.id },
|
||||
data: {
|
||||
name: name !== undefined ? name : variant.name,
|
||||
staffPrice: parseStaffPrice(staffPrice, variant.staffPrice),
|
||||
price: price !== undefined ? (price === null || price === '' ? null : parseFloat(price)) : variant.price,
|
||||
stockLimit: stockLimit !== undefined ? parseInt(stockLimit, 10) : variant.stockLimit,
|
||||
order: order !== undefined ? parseInt(order, 10) : variant.order,
|
||||
|
||||
@@ -913,6 +913,25 @@ const unassignDonationFromRegistration = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Yoco line items for a registration: one per item at each price actually charged
|
||||
* (tranche-aware, so a line bought partly at early-bird shows both prices), plus the
|
||||
* coupon discount as a negative line. Previous/partial payment lines are added by callers.
|
||||
*/
|
||||
function checkoutLineItems(registration) {
|
||||
const { buildLineItems, couponDiscountLine } = require('../utils/pdfDocs');
|
||||
const items = buildLineItems(registration.registrationOptions).map(row => ({
|
||||
displayName: row.label + (row.isEarlyBird ? ' (early bird)' : ''),
|
||||
quantity: row.quantity,
|
||||
pricingDetails: { price: Math.round(row.unitPrice * 100) },
|
||||
}));
|
||||
const coupon = couponDiscountLine(registration);
|
||||
if (coupon) {
|
||||
items.push({ displayName: coupon.label, quantity: 1, pricingDetails: { price: -Math.round(coupon.amount * 100) } });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
// Internal helper: create a Yoco checkout for a registration and return { checkoutId, redirectUrl, amount }
|
||||
// Does NOT check user authorization — callers are responsible for ensuring the user owns the registration.
|
||||
async function createRegistrationCheckoutInternal(registrationId, userId, { successUrl, cancelUrl, failureUrl } = {}) {
|
||||
@@ -927,6 +946,7 @@ async function createRegistrationCheckoutInternal(registrationId, userId, { succ
|
||||
}
|
||||
},
|
||||
payments: true,
|
||||
couponRedemptions: { where: { releasedAt: null }, include: { coupon: { select: { code: true } } } },
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
event: true
|
||||
}
|
||||
@@ -942,26 +962,7 @@ async function createRegistrationCheckoutInternal(registrationId, userId, { succ
|
||||
|
||||
const amountInCents = Math.round(remainingAmount * 100);
|
||||
const idempotencyKey = `reg_${registrationId}_${amountInCents}_${Date.now()}`;
|
||||
const now = new Date();
|
||||
|
||||
const lastPaymentAt = registration.payments.length > 0
|
||||
? new Date(Math.max(...registration.payments.map(p => new Date(p.createdAt).getTime())))
|
||||
: null;
|
||||
|
||||
const lineItems = registration.registrationOptions.map(option => {
|
||||
const variantLabel = option.variant?.name ? ` — ${option.variant.name}` : '';
|
||||
// Use priceSnapshot when available (variant-aware, authoritative); fall back to deadline-only check
|
||||
const unitPrice = (option.priceSnapshot !== null && option.priceSnapshot !== undefined)
|
||||
? option.priceSnapshot
|
||||
: require('../utils/pricing').getEffectiveUnitPrice(option.eventOption, lastPaymentAt, now);
|
||||
return {
|
||||
displayName: `${option.eventOption.name}${variantLabel}`,
|
||||
quantity: option.quantity,
|
||||
pricingDetails: {
|
||||
price: Math.round(unitPrice * 100)
|
||||
}
|
||||
};
|
||||
});
|
||||
const lineItems = checkoutLineItems(registration);
|
||||
|
||||
// Show prior payments as a deduction line
|
||||
if (totalPaid > 0) {
|
||||
@@ -1065,6 +1066,7 @@ const createYocoCheckout = async (req, res) => {
|
||||
}
|
||||
},
|
||||
payments: true,
|
||||
couponRedemptions: { where: { releasedAt: null }, include: { coupon: { select: { code: true } } } },
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
event: true
|
||||
}
|
||||
@@ -1078,21 +1080,7 @@ const createYocoCheckout = async (req, res) => {
|
||||
if (remainingAmount >= 15 && requested < 15) { res.status(400); throw new Error('Minimum payment is R15'); }
|
||||
const charge = Math.min(requested, remainingAmount);
|
||||
const amountInCents = Math.round(charge * 100);
|
||||
const now = new Date();
|
||||
const lastPaymentAt = registration.payments.length > 0
|
||||
? new Date(Math.max(...registration.payments.map(p => new Date(p.createdAt).getTime())))
|
||||
: null;
|
||||
const lineItems = registration.registrationOptions.map(option => {
|
||||
const variantLabel = option.variant?.name ? ` — ${option.variant.name}` : '';
|
||||
const unitPrice = (option.priceSnapshot !== null && option.priceSnapshot !== undefined)
|
||||
? option.priceSnapshot
|
||||
: require('../utils/pricing').getEffectiveUnitPrice(option.eventOption, lastPaymentAt, now);
|
||||
return {
|
||||
displayName: `${option.eventOption.name}${variantLabel}`,
|
||||
quantity: option.quantity,
|
||||
pricingDetails: { price: Math.round(unitPrice * 100) }
|
||||
};
|
||||
});
|
||||
const lineItems = checkoutLineItems(registration);
|
||||
// Previous payments deduction
|
||||
if (totalPaid > 0) {
|
||||
lineItems.push({ displayName: 'Previous Payments', quantity: 1, pricingDetails: { price: -Math.round(totalPaid * 100) } });
|
||||
|
||||
@@ -7,6 +7,47 @@ const { resolveOptionPrice, resolveVariantTierPrice, computeRegistrationTotalDue
|
||||
const { assertEventOpen } = require('../utils/cashupUtils');
|
||||
const { logAdminAction } = require('../utils/adminAudit');
|
||||
const { getClientIp } = require('../utils/requestUtils');
|
||||
const { buildCouponLines, previewCoupon, applyCouponToRegistration, recalculateRegistrationDiscount, releaseRegistrationCoupons, describeCoupon } = require('../utils/coupons');
|
||||
|
||||
// Active coupon on a registration, for API responses (the discount itself is
|
||||
// Registration.discountTotal).
|
||||
const ACTIVE_COUPONS_INCLUDE = {
|
||||
where: { releasedAt: null },
|
||||
select: { id: true, discountAmount: true, createdAt: true, coupon: { select: { id: true, code: true, type: true, value: true, description: true } } },
|
||||
};
|
||||
|
||||
/**
|
||||
* Coupon lines for options that haven't been saved yet, so a code can be checked
|
||||
* before anything is created. Mirrors buildCouponLines for one tranche per option.
|
||||
*/
|
||||
function pendingCouponLines(event, resolvedOptions) {
|
||||
return buildCouponLines({
|
||||
registrationOptions: resolvedOptions.map(o => ({
|
||||
eventOptionId: o.eventOptionId,
|
||||
variantId: o.variantId || null,
|
||||
quantity: o.quantity,
|
||||
eventOption: event.eventOptions.find(eo => eo.id === o.eventOptionId),
|
||||
tranches: [{ quantity: o.quantity, priceSnapshot: o.priceSnapshot, appliedTierId: o.appliedTierId }],
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Price one requested option for this buyer: early-bird tiers, then variant/option price,
|
||||
* then the staff price for Staff and above. Returns { priceSnapshot, appliedTierId }.
|
||||
*/
|
||||
async function priceRequestedOption(eventOption, variantId, qty, buyer) {
|
||||
try {
|
||||
const resolved = variantId
|
||||
? await resolveVariantTierPrice(eventOption, variantId, qty, buyer)
|
||||
: await resolveOptionPrice(eventOption, qty, buyer);
|
||||
return { priceSnapshot: resolved.price, appliedTierId: resolved.tierId };
|
||||
} catch (e) {
|
||||
const variant = variantId ? (eventOption.variants || []).find(v => v.id === variantId) : null;
|
||||
const price = variant && variant.price !== null && variant.price !== undefined ? variant.price : eventOption.price;
|
||||
return { priceSnapshot: Number(price || 0), appliedTierId: null };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check overall stock availability for an EventOption.
|
||||
@@ -44,7 +85,7 @@ async function checkVariantStock(variant, requestedQty) {
|
||||
// @access Private
|
||||
const createRegistration = async (req, res) => {
|
||||
try {
|
||||
const { eventId, options, guestName, guestEmail, guestPhone } = req.body;
|
||||
const { eventId, options, guestName, guestEmail, guestPhone, couponCode } = req.body;
|
||||
|
||||
// Check if event exists
|
||||
const canIncludeVariants = !!(prisma && prisma.optionVariant && typeof prisma.optionVariant.findMany === 'function');
|
||||
@@ -186,30 +227,12 @@ const createRegistration = async (req, res) => {
|
||||
variantPrice = variant.price; // null = use option price
|
||||
}
|
||||
|
||||
// Resolve price: variant-level tiers take priority, then option-level tiers, then base prices
|
||||
// Resolve price: variant-level tiers take priority, then option-level tiers, then
|
||||
// base prices, then the staff price for Staff and above.
|
||||
let priceSnapshot = null;
|
||||
let appliedTierId = null;
|
||||
if (canIncludeTiers) {
|
||||
try {
|
||||
if (variantId) {
|
||||
// Try variant-specific early-bird tier first
|
||||
const variantResolved = await resolveVariantTierPrice(eventOption, variantId, qty);
|
||||
if (variantResolved.tierId) {
|
||||
priceSnapshot = variantResolved.price;
|
||||
appliedTierId = variantResolved.tierId;
|
||||
} else {
|
||||
// No variant tier — use the variant's own price (may be null → falls back to option price below)
|
||||
priceSnapshot = variantPrice !== null && variantPrice !== undefined ? variantPrice : null;
|
||||
}
|
||||
} else {
|
||||
// No variant — use option-level early-bird tier
|
||||
const resolved = await resolveOptionPrice(eventOption, qty);
|
||||
priceSnapshot = resolved.price;
|
||||
appliedTierId = resolved.tierId;
|
||||
}
|
||||
} catch (e) {
|
||||
priceSnapshot = variantPrice !== null && variantPrice !== undefined ? variantPrice : eventOption.price;
|
||||
}
|
||||
({ priceSnapshot, appliedTierId } = await priceRequestedOption(eventOption, variantId, qty, req.user));
|
||||
} else {
|
||||
priceSnapshot = variantPrice !== null && variantPrice !== undefined ? variantPrice : null;
|
||||
}
|
||||
@@ -218,6 +241,13 @@ const createRegistration = async (req, res) => {
|
||||
return { ...option, variantId, appliedTierId, priceSnapshot };
|
||||
}));
|
||||
|
||||
// Check a coupon code before anything is saved, so a bad code doesn't leave a
|
||||
// half-made registration behind. It's applied (and re-checked under a lock) below.
|
||||
if (couponCode) {
|
||||
const buyer = req.user ? { id: req.user.id, role: req.user.role, email: req.user.email } : null;
|
||||
await previewCoupon({ code: couponCode, eventId, user: buyer, lines: pendingCouponLines(event, resolvedOptions) });
|
||||
}
|
||||
|
||||
// Check for existing non-cancelled registration for this user+event → merge instead
|
||||
const existingReg = await prisma.registration.findFirst({
|
||||
where: { userId, eventId, status: { not: 'cancelled' } },
|
||||
@@ -328,10 +358,34 @@ const createRegistration = async (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// Apply the coupon (or re-work an existing one over the merged items).
|
||||
let couponError = null;
|
||||
if (!isNewRegistration) await recalculateRegistrationDiscount(registration.id);
|
||||
if (couponCode) {
|
||||
try {
|
||||
await applyCouponToRegistration({ registrationId: registration.id, code: couponCode });
|
||||
} catch (e) {
|
||||
// Lost a race for the last use since the check above — keep the registration.
|
||||
if (!e.isCouponError) throw e;
|
||||
couponError = e.message;
|
||||
}
|
||||
}
|
||||
if (couponCode || !isNewRegistration) {
|
||||
registration = await prisma.registration.findUnique({
|
||||
where: { id: registration.id },
|
||||
include: {
|
||||
registrationOptions: { include: { eventOption: true, tranches: true } },
|
||||
event: true,
|
||||
user: { select: { id: true, name: true, email: true, phoneNumber: true } },
|
||||
couponRedemptions: ACTIVE_COUPONS_INCLUDE,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// If total due is zero, mark as paid and generate/update tickets if no required form
|
||||
let freeTicketMockReq = null, freeTicketMockRes = null;
|
||||
try {
|
||||
const totalDue = (registration.registrationOptions || []).reduce((sum, ro) => sum + ((ro.priceSnapshot ?? ro.eventOption?.price ?? 0) * (ro.quantity || 0)), 0);
|
||||
const totalDue = computeRegistrationTotalDue(registration, new Date());
|
||||
if (totalDue === 0) {
|
||||
// Mark paid (no-op if already paid)
|
||||
if (registration.status !== 'paid') {
|
||||
@@ -399,7 +453,7 @@ const createRegistration = async (req, res) => {
|
||||
}
|
||||
})();
|
||||
|
||||
res.status(201).json(attachComputedTotals(registration));
|
||||
res.status(201).json({ ...attachComputedTotals(registration), ...(couponError ? { couponError } : {}) });
|
||||
} catch (error) {
|
||||
res.status(400).json({ message: error.message });
|
||||
}
|
||||
@@ -411,6 +465,7 @@ const createRegistration = async (req, res) => {
|
||||
const getRegistrations = async (req, res) => {
|
||||
try {
|
||||
const include = {
|
||||
couponRedemptions: ACTIVE_COUPONS_INCLUDE,
|
||||
payments: { include: { recordedBy: { select: { id: true, name: true, email: true } } } },
|
||||
registrationOptions: {
|
||||
include: {
|
||||
@@ -488,6 +543,7 @@ const getUserRegistrations = async (req, res) => {
|
||||
tranches: true,
|
||||
}
|
||||
},
|
||||
couponRedemptions: ACTIVE_COUPONS_INCLUDE,
|
||||
// Nest the event's form so the frontend can tell whether attendee forms are
|
||||
// required without a separate GET /api/events/:id per registration.
|
||||
event: { include: { form: { include: { fields: true } } } },
|
||||
@@ -534,7 +590,8 @@ const getRegistrationById = async (req, res) => {
|
||||
}
|
||||
},
|
||||
payments: { include: { recordedBy: { select: { id: true, name: true, email: true } } } },
|
||||
formResponses: { include: { answers: true } }
|
||||
formResponses: { include: { answers: true } },
|
||||
couponRedemptions: ACTIVE_COUPONS_INCLUDE,
|
||||
};
|
||||
|
||||
let registration = await prisma.registration.findUnique({ where: { id: req.params.id }, include });
|
||||
@@ -631,6 +688,7 @@ const updateRegistrationStatus = async (req, res) => {
|
||||
// staff-initiated cancellation — log it the same way DELETE /:id does, so both
|
||||
// paths land under the one 'registration_cancelled' filter in the audit log.
|
||||
if (status === 'cancelled' && registration.status !== 'cancelled') {
|
||||
await releaseRegistrationCoupons(req.params.id);
|
||||
logAdminAction({
|
||||
actorId: req.user.id,
|
||||
actorRole: req.user.role,
|
||||
@@ -715,6 +773,7 @@ const cancelRegistration = async (req, res) => {
|
||||
updatedAt: new Date()
|
||||
}
|
||||
});
|
||||
await releaseRegistrationCoupons(req.params.id);
|
||||
|
||||
// Only log when staff cancels on someone else's behalf — a routine self-service
|
||||
// cancellation isn't an admin action worth cluttering the audit trail with.
|
||||
@@ -765,7 +824,8 @@ const getRegistrationsByEvent = async (req, res) => {
|
||||
}
|
||||
},
|
||||
payments: { include: { recordedBy: { select: { id: true, name: true, email: true } } } },
|
||||
user: { select: { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true, isActive: true } }
|
||||
user: { select: { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true, isActive: true } },
|
||||
couponRedemptions: ACTIVE_COUPONS_INCLUDE,
|
||||
},
|
||||
orderBy: { createdAt: 'asc' }
|
||||
});
|
||||
@@ -791,7 +851,7 @@ const getRegistrationsByEvent = async (req, res) => {
|
||||
const createManualRegistration = async (req, res) => {
|
||||
let userRecord;
|
||||
try {
|
||||
const { eventId, options, user, notificationPreference: prefFromBody, skipActivationNotice } = req.body;
|
||||
const { eventId, options, user, notificationPreference: prefFromBody, skipActivationNotice, couponCode } = req.body;
|
||||
|
||||
if (!eventId || !options || !user || !user.name || (!user.email && !user.phoneNumber)) {
|
||||
res.status(400);
|
||||
@@ -822,8 +882,7 @@ const createManualRegistration = async (req, res) => {
|
||||
throw new Error('At least one option must be selected');
|
||||
}
|
||||
|
||||
// Resolve pricing for each option (appliedTierId + priceSnapshot)
|
||||
const resolvedManualOptions = [];
|
||||
// Validate each option up front, before any account is created or changed.
|
||||
for (const option of options) {
|
||||
const eventOption = event.eventOptions.find(eo => eo.id === option.eventOptionId);
|
||||
if (!eventOption) {
|
||||
@@ -834,34 +893,17 @@ const createManualRegistration = async (req, res) => {
|
||||
res.status(400);
|
||||
throw new Error('Quantity must be at least 1');
|
||||
}
|
||||
|
||||
const variantId = option.variantId || null;
|
||||
let priceSnapshot = null;
|
||||
let appliedTierId = null;
|
||||
try {
|
||||
if (variantId) {
|
||||
const variantResolved = await resolveVariantTierPrice(eventOption, variantId, option.quantity);
|
||||
if (variantResolved.tierId) {
|
||||
priceSnapshot = variantResolved.price;
|
||||
appliedTierId = variantResolved.tierId;
|
||||
} else {
|
||||
const variant = (eventOption.variants || []).find(v => v.id === variantId);
|
||||
priceSnapshot = (variant && variant.price !== null && variant.price !== undefined)
|
||||
? Number(variant.price)
|
||||
: Number(eventOption.price || 0);
|
||||
}
|
||||
} else {
|
||||
const resolved = await resolveOptionPrice(eventOption, option.quantity);
|
||||
priceSnapshot = resolved.price;
|
||||
appliedTierId = resolved.tierId;
|
||||
}
|
||||
} catch (e) {
|
||||
priceSnapshot = Number(eventOption.price || 0);
|
||||
}
|
||||
|
||||
resolvedManualOptions.push({ ...option, variantId, appliedTierId, priceSnapshot });
|
||||
}
|
||||
|
||||
// Pricing (appliedTierId + priceSnapshot) depends on who the attendee is — Staff and
|
||||
// above get the staff price — so it runs once the account is resolved below.
|
||||
const priceManualOptions = (attendee) => Promise.all(options.map(async (option) => {
|
||||
const eventOption = event.eventOptions.find(eo => eo.id === option.eventOptionId);
|
||||
const variantId = option.variantId || null;
|
||||
const priced = await priceRequestedOption(eventOption, variantId, option.quantity, attendee);
|
||||
return { ...option, variantId, ...priced };
|
||||
}));
|
||||
|
||||
// Resolve or create a user
|
||||
let userId;
|
||||
|
||||
@@ -992,6 +1034,15 @@ const createManualRegistration = async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
let couponError = null;
|
||||
const attendee = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, role: true, email: true } });
|
||||
const resolvedManualOptions = await priceManualOptions(attendee);
|
||||
|
||||
// Check the coupon against this attendee before saving anything.
|
||||
if (couponCode) {
|
||||
await previewCoupon({ code: couponCode, eventId, user: attendee, lines: pendingCouponLines(event, resolvedManualOptions) });
|
||||
}
|
||||
|
||||
// Merge into existing non-cancelled registration if one exists, otherwise create new
|
||||
const existingReg = await prisma.registration.findFirst({
|
||||
where: { userId, eventId, status: { not: 'cancelled' } },
|
||||
@@ -1050,6 +1101,18 @@ const createManualRegistration = async (req, res) => {
|
||||
}
|
||||
});
|
||||
}));
|
||||
// Re-work any coupon over the merged items, and apply a new one, before the status
|
||||
// is worked out from the totals.
|
||||
await recalculateRegistrationDiscount(existingReg.id);
|
||||
if (couponCode) {
|
||||
try {
|
||||
await applyCouponToRegistration({ registrationId: existingReg.id, code: couponCode, appliedById: req.user.id });
|
||||
} catch (e) {
|
||||
if (!e.isCouponError) throw e;
|
||||
couponError = e.message;
|
||||
}
|
||||
}
|
||||
|
||||
// Recompute status based on totals across ALL current options and payments
|
||||
const freshForStatus = await prisma.registration.findUnique({
|
||||
where: { id: existingReg.id },
|
||||
@@ -1072,6 +1135,7 @@ const createManualRegistration = async (req, res) => {
|
||||
registrationOptions: { include: { eventOption: true, tranches: true } },
|
||||
event: true,
|
||||
user: { select: { id: true, name: true, email: true, phoneNumber: true } },
|
||||
couponRedemptions: ACTIVE_COUPONS_INCLUDE,
|
||||
},
|
||||
});
|
||||
registration.status = newExistingStatus;
|
||||
@@ -1109,10 +1173,39 @@ const createManualRegistration = async (req, res) => {
|
||||
user: { select: { id: true, name: true, email: true, phoneNumber: true } },
|
||||
},
|
||||
});
|
||||
if (couponCode) {
|
||||
try {
|
||||
await applyCouponToRegistration({ registrationId: registration.id, code: couponCode, appliedById: req.user.id });
|
||||
} catch (e) {
|
||||
if (!e.isCouponError) throw e;
|
||||
couponError = e.message;
|
||||
}
|
||||
registration = await prisma.registration.findUnique({
|
||||
where: { id: registration.id },
|
||||
include: {
|
||||
registrationOptions: { include: { eventOption: true, tranches: true } },
|
||||
event: true,
|
||||
user: { select: { id: true, name: true, email: true, phoneNumber: true } },
|
||||
couponRedemptions: ACTIVE_COUPONS_INCLUDE,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const registrationId = registration.id;
|
||||
|
||||
if (couponCode && !couponError) {
|
||||
logAdminAction({
|
||||
actorId: req.user.id,
|
||||
actorRole: req.user.role,
|
||||
action: 'coupon_applied_manual',
|
||||
targetType: 'Registration',
|
||||
targetId: registrationId,
|
||||
metadata: { code: String(couponCode).trim().toUpperCase(), discount: registration.discountTotal, forUserId: userId },
|
||||
ip: getClientIp(req),
|
||||
});
|
||||
}
|
||||
|
||||
// Auto mark paid and generate tickets if free and no required form (new registrations only)
|
||||
let hasRequiredForm = false;
|
||||
try {
|
||||
@@ -1122,7 +1215,7 @@ const createManualRegistration = async (req, res) => {
|
||||
|
||||
// Auto-mark paid and generate tickets for free registrations (new OR existing that became free)
|
||||
if (registration.status !== 'paid') try {
|
||||
const totalDue = (registration.registrationOptions || []).reduce((sum, ro) => sum + ((ro.priceSnapshot ?? ro.eventOption?.price ?? 0) * (ro.quantity || 0)), 0);
|
||||
const totalDue = computeRegistrationTotalDue(registration, new Date());
|
||||
if (totalDue === 0) {
|
||||
await prisma.registration.update({ where: { id: registration.id }, data: { status: 'paid', updatedAt: new Date() } });
|
||||
registration.status = 'paid';
|
||||
@@ -1185,7 +1278,7 @@ const createManualRegistration = async (req, res) => {
|
||||
ip: getClientIp(req),
|
||||
});
|
||||
|
||||
return res.status(201).json(attachComputedTotals(registration));
|
||||
return res.status(201).json({ ...attachComputedTotals(registration), ...(couponError ? { couponError } : {}) });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return res.status(400).json({message: error.message});
|
||||
@@ -1219,6 +1312,7 @@ const updateRegistrationOptions = async (req, res) => {
|
||||
},
|
||||
event: { include: { eventOptions: { include: { earlyBirdTiers: true, variants: true } } } },
|
||||
payments: true,
|
||||
user: { select: { id: true, role: true, email: true } },
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1347,19 +1441,7 @@ const updateRegistrationOptions = async (req, res) => {
|
||||
let removalPlan = null;
|
||||
|
||||
if (delta > 0) {
|
||||
try {
|
||||
if (variantId) {
|
||||
const variantResolved = await resolveVariantTierPrice(eventOption, variantId, delta);
|
||||
priceSnapshot = variantResolved.price;
|
||||
appliedTierId = variantResolved.tierId;
|
||||
} else {
|
||||
const resolved = await resolveOptionPrice(eventOption, delta);
|
||||
priceSnapshot = resolved.price;
|
||||
appliedTierId = resolved.tierId;
|
||||
}
|
||||
} catch (e) {
|
||||
priceSnapshot = Number(eventOption?.price || 0);
|
||||
}
|
||||
({ priceSnapshot, appliedTierId } = await priceRequestedOption(eventOption, variantId, delta, registration.user));
|
||||
newTotalDue += existingTotal + delta * (priceSnapshot || 0);
|
||||
} else if (delta < 0) {
|
||||
const existingTranches = existingRows.flatMap(ro => ro.tranches || []);
|
||||
@@ -1491,9 +1573,16 @@ const updateRegistrationOptions = async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Coupon: percentage/comp codes follow the new items, fixed codes keep their amount.
|
||||
const discount = await recalculateRegistrationDiscount(registrationId, tx);
|
||||
const dueAfterDiscount = Math.max(0, newTotalDue - discount);
|
||||
if (dueAfterDiscount < totalPaid - 0.001) {
|
||||
throw new Error('Cannot reduce items below the amount already paid');
|
||||
}
|
||||
|
||||
// Update updatedAt and potentially status based on payments vs due
|
||||
let newStatus = registration.status;
|
||||
if (totalPaid >= newTotalDue) newStatus = 'paid';
|
||||
if (totalPaid >= dueAfterDiscount) newStatus = 'paid';
|
||||
else if (totalPaid > 0) newStatus = 'partial_paid';
|
||||
else newStatus = 'pending';
|
||||
|
||||
@@ -1511,6 +1600,7 @@ const updateRegistrationOptions = async (req, res) => {
|
||||
event: true,
|
||||
user: { select: { id: true, name: true, email: true, phoneNumber: true } },
|
||||
payments: true,
|
||||
couponRedemptions: ACTIVE_COUPONS_INCLUDE,
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1818,7 +1908,145 @@ const sendInvoice = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* After a discount changes, bring the status in line with the new total. A registration
|
||||
* that a coupon has made fully paid gets its tickets, as any paid registration does.
|
||||
*/
|
||||
async function syncStatusAfterDiscount(registrationId) {
|
||||
const reg = await prisma.registration.findUnique({
|
||||
where: { id: registrationId },
|
||||
include: { registrationOptions: { include: { eventOption: true, tranches: true } }, payments: true },
|
||||
});
|
||||
const due = computeRegistrationTotalDue(reg, new Date());
|
||||
const paid = (reg.payments || []).reduce((s, p) => s + (p.amount || 0), 0);
|
||||
const status = paid >= due - 0.001 ? 'paid' : paid > 0 ? 'partial_paid' : 'pending';
|
||||
if (status !== reg.status) {
|
||||
await prisma.registration.update({ where: { id: registrationId }, data: { status, updatedAt: new Date() } });
|
||||
}
|
||||
if (status === 'paid' && reg.status !== 'paid') {
|
||||
(async () => {
|
||||
try {
|
||||
let hasRequiredForm = false;
|
||||
try {
|
||||
const form = await prisma.eventForm.findUnique({ where: { eventId: reg.eventId } });
|
||||
hasRequiredForm = !!(form && form.isRequired);
|
||||
} catch {}
|
||||
if (hasRequiredForm) return;
|
||||
await generateTicketsForRegistration(registrationId);
|
||||
const mockReq = { user: { id: reg.userId }, body: { registrationId } };
|
||||
const mockRes = { status: () => mockRes, json: () => {} };
|
||||
await emailTickets(mockReq, mockRes);
|
||||
} catch (e) {
|
||||
console.error('[coupon] Failed to issue tickets after discount:', e?.message || e);
|
||||
}
|
||||
})();
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
const isStaffRole = (role) => ['admin', 'supervisor', 'staff'].includes(role);
|
||||
|
||||
// @desc Apply a coupon code to an existing registration
|
||||
// @route POST /api/registrations/:id/coupon
|
||||
// @access Private (owner, or staff applying it on someone's behalf)
|
||||
const applyCoupon = async (req, res) => {
|
||||
try {
|
||||
const { code } = req.body || {};
|
||||
const registration = await prisma.registration.findUnique({
|
||||
where: { id: req.params.id },
|
||||
include: { event: { select: { endDate: true, cashupStatus: true } } },
|
||||
});
|
||||
if (!registration) { res.status(404); throw new Error('Registration not found'); }
|
||||
const byStaff = registration.userId !== req.user.id;
|
||||
if (byStaff && !isStaffRole(req.user.role)) { res.status(403); throw new Error('Not authorized to change this registration'); }
|
||||
if (registration.status === 'cancelled') { res.status(400); throw new Error('This registration is cancelled.'); }
|
||||
if (registration.event?.cashupStatus === 'closed') { res.status(400); throw new Error('This event is closed.'); }
|
||||
if (registration.event?.endDate && new Date(registration.event.endDate) < new Date()) {
|
||||
res.status(400); throw new Error('This event has already ended.');
|
||||
}
|
||||
|
||||
const { coupon, discount } = await applyCouponToRegistration({
|
||||
registrationId: registration.id,
|
||||
code,
|
||||
appliedById: byStaff ? req.user.id : null,
|
||||
});
|
||||
await syncStatusAfterDiscount(registration.id);
|
||||
|
||||
if (byStaff) {
|
||||
logAdminAction({
|
||||
actorId: req.user.id,
|
||||
actorRole: req.user.role,
|
||||
action: 'coupon_applied_manual',
|
||||
targetType: 'Registration',
|
||||
targetId: registration.id,
|
||||
metadata: { code: coupon.code, discount, forUserId: registration.userId },
|
||||
ip: getClientIp(req),
|
||||
});
|
||||
}
|
||||
|
||||
const { sendRegistrationUpdatedEmails } = require('../utils/notifications');
|
||||
sendRegistrationUpdatedEmails(registration.id).catch(e => console.error('Failed to send registration updated emails:', e));
|
||||
|
||||
const updated = await prisma.registration.findUnique({
|
||||
where: { id: registration.id },
|
||||
include: {
|
||||
registrationOptions: { include: { eventOption: true, variant: { select: { id: true, name: true, price: true } }, tranches: true } },
|
||||
payments: true,
|
||||
couponRedemptions: ACTIVE_COUPONS_INCLUDE,
|
||||
},
|
||||
});
|
||||
res.json({ ...attachComputedTotals(updated), message: `Code ${coupon.code} applied — ${describeCoupon(coupon)}.` });
|
||||
} catch (error) {
|
||||
res.status(error.statusCode || (res.statusCode === 200 ? 400 : res.statusCode)).json({ message: error.message });
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Remove the coupon from a registration (the use is freed)
|
||||
// @route DELETE /api/registrations/:id/coupon
|
||||
// @access Private/Staff
|
||||
const removeCoupon = async (req, res) => {
|
||||
try {
|
||||
const registration = await prisma.registration.findUnique({ where: { id: req.params.id } });
|
||||
if (!registration) { res.status(404); throw new Error('Registration not found'); }
|
||||
await assertEventOpen(registration.eventId, res);
|
||||
|
||||
// Removing a discount raises the total, which can take a paid registration back to
|
||||
// unpaid. Same rule as a staff status change: refuse once a ticket has been scanned,
|
||||
// otherwise withdraw the unused tickets until it's paid again.
|
||||
const tickets = await prisma.ticket.findMany({
|
||||
where: { registrationOption: { registrationId: registration.id } },
|
||||
include: { usages: true },
|
||||
});
|
||||
if (registration.status === 'paid' && tickets.some(t => t.isUsed || t.usages.length > 0)) {
|
||||
res.status(400);
|
||||
throw new Error('A ticket on this registration has already been scanned, so its code can\'t be removed.');
|
||||
}
|
||||
|
||||
const released = await releaseRegistrationCoupons(registration.id);
|
||||
if (!released) { res.status(400); throw new Error('No code is applied to this registration.'); }
|
||||
const status = await syncStatusAfterDiscount(registration.id);
|
||||
if (registration.status === 'paid' && status !== 'paid') {
|
||||
await prisma.ticket.deleteMany({ where: { registrationOption: { registrationId: registration.id }, isUsed: false } });
|
||||
}
|
||||
|
||||
logAdminAction({
|
||||
actorId: req.user.id,
|
||||
actorRole: req.user.role,
|
||||
action: 'coupon_applied_manual',
|
||||
targetType: 'Registration',
|
||||
targetId: registration.id,
|
||||
metadata: { removed: true, forUserId: registration.userId },
|
||||
ip: getClientIp(req),
|
||||
});
|
||||
res.json({ message: 'Code removed.' });
|
||||
} catch (error) {
|
||||
res.status(error.statusCode || (res.statusCode === 200 ? 400 : res.statusCode)).json({ message: error.message });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
applyCoupon,
|
||||
removeCoupon,
|
||||
createRegistration,
|
||||
getRegistrations,
|
||||
getUserRegistrations,
|
||||
|
||||
Reference in New Issue
Block a user