/** * Bundle deals and coupon codes (1.51.9). Moved from bundleController.js and couponController.js * so v1 and /api/v2 share them; matching codes and working out discounts stays in * utils/coupons.js and utils/bundles.js. */ import { prisma } from '../v2/legacy'; import { fail, ServiceError } from './errors'; import type { Role } from './registrations'; /* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */ const bundlesUtil = require('../utils/bundles') as { KINDS: string[]; describeBundle(b: any): string; describeBundleItems(b: any): string; isBundleAvailable(b: any, now: Date): boolean; }; const coupons = require('../utils/coupons') as { normalizeCode(code: unknown): string; previewCoupon(args: object): Promise<{ coupon: any; discount: number; bundles: { discount: number; applications: any[] } }>; previewBundles(eventId: string, lines: any[]): Promise<{ discount: number; applications: any[] }>; buildCouponLines(reg: any): any[]; describeCoupon(c: any): string; countCouponUses(couponId: string, userId: string | null): Promise<{ usesTotal: number }>; }; const pricing = require('../utils/pricing') as { resolveOptionPrice(option: any, qty: number, buyer: any): Promise<{ price: number; tierId: string | null }>; resolveVariantTierPrice(option: any, variantId: string, qty: number, buyer: any): Promise<{ price: number; tierId: string | null }>; }; const campusScope = require('../utils/campusScope') as { couponAllowed(scope: object | null, campusIds: Array): boolean }; const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise }; export type Actor = { id: string; role: Role; email?: string }; export type Ctx = { scope: object | null; ip?: string }; const round2 = (n: unknown) => Math.round(Number(n || 0) * 100) / 100; const fmtR = (n: number) => `R${Number(n || 0).toFixed(2).replace(/\.00$/, '')}`; const STAFF_ROLES = ['staff', 'supervisor', 'admin']; /** Plain errors from the parsers and helpers are the caller's mistake (400), like v1. */ async function clientErrors(fn: () => Promise): Promise { try { return await fn(); } catch (e: any) { if (e instanceof ServiceError || /^P\d{4}$/.test(String(e?.code || ''))) throw e; throw new ServiceError(e?.statusCode || 400, e?.message || 'That could not be saved'); } } const optionalDate = (v: unknown, label: string): Date | null | undefined => { if (v === undefined) return undefined; if (v === null || v === '') return null; const d = new Date(String(v)); if (isNaN(d.getTime())) fail(400, `${label} is not a valid date`); return d; }; // ─── Pricing a basket (bundle quotes and coupon checks) ────────────────────── /** * Who a basket is being priced for: the signed-in buyer, or — for staff — the attendee * (`forUserId`) or a walk-in with no account yet (`forUserId: null`). */ export async function basketBuyer(actor: Actor | null, forUserId: string | null | undefined) { const isStaff = !!(actor && STAFF_ROLES.includes(actor.role)); let buyer: { id: string; role: string; email?: string } | null = actor ? { id: actor.id, role: actor.role, email: actor.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; return { buyer, isStaff }; } export type BasketLine = { eventOptionId: string; variantId?: string | null; quantity: number; sessionIds?: string[] }; /** Prices a basket the way registering will, as coupon/bundle lines. */ export async function priceBasket(event: { eventOptions: any[] } & Record, options: BasketLine[], buyer: any) { const registrationOptions: any[] = []; // A "pick sessions" line counts once per chosen session. const { isPickOption } = require('../utils/sessions') as { isPickOption(ev: any, opt: any): boolean }; const perSession = (o: BasketLine) => isPickOption(event, event.eventOptions.find(x => x.id === o.eventOptionId)); const expanded = (options || []).flatMap(o => (Array.isArray(o.sessionIds) && o.sessionIds.length && perSession(o) ? o.sessionIds.map(sessionId => ({ ...o, sessionId })) : [o])); for (const o of expanded) { 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 pricing.resolveVariantTierPrice(eo, o.variantId, qty, buyer) : await pricing.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 }] }); } return coupons.buildCouponLines({ registrationOptions }); } const basketEvent = async (eventId: string) => { const event = await prisma.event.findUnique({ where: { id: eventId }, include: { eventOptions: { include: { earlyBirdTiers: true, variants: true } } } }); if (!event) return fail(404, 'Event not found'); return event; }; /** The bundle deals a basket gets, before any coupon. */ export function quoteBundles(input: { eventId?: string; options?: BasketLine[]; forUserId?: string | null }, actor: Actor | null) { return clientErrors(async () => { if (!input.eventId || !Array.isArray(input.options)) fail(400, 'eventId and options are required'); const event = await basketEvent(input.eventId!); const { buyer } = await basketBuyer(actor, input.forUserId); const lines = await priceBasket(event, input.options!, buyer); const subtotal = round2(lines.reduce((s: number, l: any) => s + l.unitPrice * l.quantity, 0)); const b = await coupons.previewBundles(event.id, lines); return { subtotal, bundleDiscount: b.discount, bundles: b.applications, total: round2(Math.max(0, subtotal - b.discount)) }; }); } export type CodeCheck = | { valid: true; code: string; type: string; value: number; summary: string; description: string | null; discount: number; bundleDiscount: number; bundles: any[]; subtotal: number; total: number } | { valid: false; message: string }; /** * Checks a code against a basket. Staff can check on an attendee's behalf (`forUserId`), or * leave it out for a new attendee — restricted codes are then checked when they register. */ export function checkCode(input: { code?: string; eventId?: string; options?: BasketLine[]; forUserId?: string | null }, actor: Actor | null): Promise { return clientErrors(async () => { if (!input.code || !input.eventId || !Array.isArray(input.options) || input.options.length === 0) fail(400, 'code, eventId and options are required'); const event = await basketEvent(input.eventId!); const { buyer, isStaff } = await basketBuyer(actor, input.forUserId); const lines = await priceBasket(event, input.options!, buyer); const subtotal = lines.reduce((s: number, l: any) => s + l.unitPrice * l.quantity, 0); try { const { coupon, discount, bundles } = await coupons.previewCoupon({ code: input.code, eventId: event.id, user: buyer, lines, deferRestrictions: isStaff && !buyer }); return { valid: true as const, code: coupon.code, type: coupon.type, value: coupon.value, summary: coupons.describeCoupon(coupon), description: coupon.description, discount, bundleDiscount: bundles.discount, bundles: bundles.applications, subtotal, total: Math.max(0, subtotal - bundles.discount - discount), }; } catch (e: any) { if (!e.isCouponError) throw e; return { valid: false as const, message: e.message }; } }); } // ─── Bundle deals ──────────────────────────────────────────────────────────── const GROUP_PRICING = ['per_ticket', 'percent']; const PRICING_FIELDS = ['kind', 'price', 'setSize', 'freeCount', 'groupPricing', 'items']; const DETAIL_INCLUDE = { items: { include: { eventOption: { select: { id: true, name: true, price: true, variants: { select: { id: true, price: true } } } }, variant: { select: { id: true, name: true } }, }, }, } as const; /** Standard (variant or option) price of one unit of an item. */ function itemPrice(i: any) { const variant = i.variantId ? (i.eventOption?.variants || []).find((v: any) => v.id === i.variantId) : null; return Number((variant && variant.price !== null && variant.price !== undefined ? variant.price : i.eventOption?.price) || 0); } /** What the deal is worth at standard prices, and a short "save …" line (or null when the headline says it). */ function valueOf(bundle: any): { standardValue: number | null; savingText: string | null } { const kind = bundle.kind || 'exact'; const items = bundle.items || []; const dearest = items.reduce((m: number, i: any) => Math.max(m, itemPrice(i)), 0); const price = Number(bundle.price || 0); if (kind === 'exact') { const standard = round2(items.reduce((s: number, i: any) => s + itemPrice(i) * Number(i.quantity || 0), 0)); return { standardValue: standard, savingText: standard - price > 0.005 ? `save ${fmtR(standard - price)}` : null }; } if (kind === 'mix') { const standard = round2(dearest * Number(bundle.setSize || 0)); return { standardValue: standard, savingText: standard - price > 0.005 ? `save up to ${fmtR(standard - price)}` : null }; } if (kind === 'free') return { standardValue: null, savingText: dearest > 0 ? `save up to ${fmtR(dearest * Number(bundle.freeCount || 0))} a set` : null }; if (bundle.groupPricing === 'per_ticket' && dearest - price > 0.005) return { standardValue: null, savingText: `save up to ${fmtR(dearest - price)} a ticket` }; return { standardValue: null, savingText: null }; } function shapeBundle(bundle: any, now = new Date()) { const items = (bundle.items || []).map(({ eventOption, ...i }: any) => ({ ...i, eventOption: eventOption ? { id: eventOption.id, name: eventOption.name, price: eventOption.price } : null })); return { ...bundle, items, summary: bundlesUtil.describeBundleItems(bundle), headline: bundlesUtil.describeBundle(bundle), ...valueOf(bundle), available: bundlesUtil.isBundleAvailable(bundle, now) }; } /** * A create/update body as Prisma data plus the item list. On update, fields left out stay as * they are; when any pricing field is sent, the whole deal (saved + new values) is checked. */ async function parseBundleBody(body: any, eventId: string, { isCreate, current = null }: { isCreate: boolean; current?: any }) { const data: Record = {}; if (isCreate || body.name !== undefined) { const name = String(body.name || '').trim(); if (!name) fail(400, 'Give the bundle a name'); if (name.length > 80) fail(400, 'Keep the name under 80 characters'); data.name = name; } if (body.description !== undefined) data.description = body.description ? String(body.description).trim() : null; if (body.isActive !== undefined) data.isActive = !!body.isActive; if (body.order !== undefined) data.order = Number.isInteger(Number(body.order)) ? Number(body.order) : 0; const validFrom = optionalDate(body.validFrom, 'Available from'); const validUntil = optionalDate(body.validUntil, 'Available until'); if (validFrom !== undefined) data.validFrom = validFrom; if (validUntil !== undefined) data.validUntil = validUntil; if (validFrom && validUntil && validFrom > validUntil) fail(400, '"Available from" must be before "Available until"'); if (!isCreate && !PRICING_FIELDS.some(f => body[f] !== undefined)) return { data, items: undefined }; const pick = (f: string) => (body[f] !== undefined ? body[f] : current?.[f]); const kind = pick('kind') || 'exact'; if (!bundlesUtil.KINDS.includes(kind)) fail(400, 'Unknown bundle type'); data.kind = kind; const rawItems = body.items !== undefined ? body.items : (current?.items || []); // The same option/variant twice becomes one line. const merged = new Map(); for (const it of Array.isArray(rawItems) ? rawItems : []) { if (!it || !it.eventOptionId) continue; const quantity = kind === 'exact' ? Number(it.quantity) : 1; if (!Number.isInteger(quantity) || quantity < 1) fail(400, 'Each ticket needs a quantity of at least 1'); const key = `${it.eventOptionId}::${it.variantId || ''}`; const prev = merged.get(key); merged.set(key, { eventOptionId: it.eventOptionId, variantId: it.variantId || null, quantity: kind === 'exact' ? (prev?.quantity || 0) + quantity : 1 }); } const items = [...merged.values()]; if (items.length === 0) fail(400, kind === 'exact' ? 'Add at least one ticket to the bundle' : 'Choose at least one qualifying ticket'); const price = Number(pick('price')); const setSize = Number(pick('setSize')); const freeCount = Number(pick('freeCount')); const groupPricing = pick('groupPricing'); const priceGiven = pick('price') !== '' && pick('price') !== null && pick('price') !== undefined; if (kind === 'exact') { if (items.reduce((s, i) => s + i.quantity, 0) < 2) fail(400, 'A bundle needs at least two tickets in it'); if (!priceGiven || !(price >= 0)) fail(400, 'Enter the bundle price (zero or more)'); Object.assign(data, { price: round2(price), setSize: null, freeCount: null, groupPricing: null }); } else if (kind === 'mix') { if (!Number.isInteger(setSize) || setSize < 2) fail(400, 'A pick-any bundle needs at least 2 tickets per set'); if (!priceGiven || !(price >= 0)) fail(400, 'Enter the price for the set (zero or more)'); Object.assign(data, { price: round2(price), setSize, freeCount: null, groupPricing: null }); } else if (kind === 'free') { if (!Number.isInteger(freeCount) || freeCount < 1) fail(400, 'At least one ticket must be free'); if (!Number.isInteger(setSize) || setSize <= freeCount) fail(400, 'Buy at least one ticket to get the free ones'); Object.assign(data, { price: 0, setSize, freeCount, groupPricing: null }); } else { if (!Number.isInteger(setSize) || setSize < 2) fail(400, 'A group needs at least 2 tickets'); if (!GROUP_PRICING.includes(groupPricing)) fail(400, 'Choose a price per ticket or a percentage off'); if (groupPricing === 'percent' && !(price > 0 && price <= 100)) fail(400, 'Enter a percentage between 1 and 100'); if (groupPricing === 'per_ticket' && (!priceGiven || !(price >= 0))) fail(400, 'Enter the price per ticket (zero or more)'); Object.assign(data, { price: round2(price), setSize, freeCount: null, groupPricing }); } const options = await prisma.eventOption.findMany({ where: { id: { in: items.map(i => i.eventOptionId) } }, select: { id: true, eventId: true, variants: { select: { id: true } } } }); for (const i of items) { const row = options.find(o => o.id === i.eventOptionId); if (!row || row.eventId !== eventId) fail(400, 'One of the tickets isn\'t part of this event'); if (i.variantId && !row!.variants.some(v => v.id === i.variantId)) fail(400, 'One of the selected variants no longer exists'); } return { data, items }; } const eventOr404 = async (eventId: string) => { const event = await prisma.event.findUnique({ where: { id: eventId }, select: { id: true, title: true } }); if (!event) return fail(404, 'Event not found'); return event; }; /** An event's bundle deals with how often each has been used and the discount given. */ export async function listBundles(eventId: string) { await eventOr404(eventId); const bundles = await prisma.eventBundle.findMany({ where: { eventId }, include: DETAIL_INCLUDE, orderBy: [{ order: 'asc' }, { createdAt: 'asc' }] }); const totals = await prisma.registrationBundle.groupBy({ by: ['bundleId'], where: { bundle: { eventId }, registration: { status: { not: 'cancelled' } } }, _sum: { count: true, discount: true }, _count: { _all: true }, }); const byId = Object.fromEntries(totals.map(t => [t.bundleId, t])); const now = new Date(); return bundles.map(b => ({ ...shapeBundle(b, now), uses: byId[b.id]?._sum?.count || 0, registrations: byId[b.id]?._count?._all || 0, totalDiscount: round2(byId[b.id]?._sum?.discount || 0), })); } export function createBundle(eventId: string, body: any, actor: Actor, ctx: Ctx) { return clientErrors(async () => { const event = await eventOr404(eventId); const parsed = await parseBundleBody(body || {}, event.id, { isCreate: true }); const bundle = await prisma.eventBundle.create({ data: { ...(parsed.data as any), eventId: event.id, items: { create: parsed.items } }, include: DETAIL_INCLUDE }); logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'bundle_created', targetType: 'EventBundle', targetId: bundle.id, metadata: { eventId: event.id, name: bundle.name, kind: bundle.kind, deal: bundlesUtil.describeBundle(bundle) }, ip: ctx.ip, }); return { ...shapeBundle(bundle), uses: 0, registrations: 0, totalDiscount: 0 }; }); } /** Edits a deal (or switches it off). Registrations that have it are re-worked only when their own items change. */ export function updateBundle(bundleId: string, body: any, actor: Actor, ctx: Ctx) { return clientErrors(async () => { const existing = await prisma.eventBundle.findUnique({ where: { id: bundleId }, include: { items: true } }); if (!existing) return fail(404, 'Bundle not found'); const parsed = await parseBundleBody(body || {}, existing.eventId, { isCreate: false, current: existing }); const bundle = await prisma.eventBundle.update({ where: { id: existing.id }, data: { ...parsed.data, ...(parsed.items ? { items: { deleteMany: {}, create: parsed.items } } : {}) }, include: DETAIL_INCLUDE, }); logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'bundle_updated', targetType: 'EventBundle', targetId: bundle.id, metadata: { eventId: bundle.eventId, name: bundle.name, changedKeys: Object.keys(body || {}) }, ip: ctx.ip, }); return shapeBundle(bundle); }); } /** Deletes a deal; one that's been used is switched off instead, so registrations keep their price. */ export async function deleteBundle(bundleId: string, actor: Actor, ctx: Ctx) { const existing = await prisma.eventBundle.findUnique({ where: { id: bundleId } }); if (!existing) return fail(404, 'Bundle not found'); const used = await prisma.registrationBundle.count({ where: { bundleId: existing.id } }); if (used > 0) await prisma.eventBundle.update({ where: { id: existing.id }, data: { isActive: false } }); else await prisma.eventBundle.delete({ where: { id: existing.id } }); logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'bundle_deleted', targetType: 'EventBundle', targetId: existing.id, metadata: { eventId: existing.eventId, name: existing.name, switchedOff: used > 0 }, ip: ctx.ip, }); return used > 0 ? { switchedOff: true as const, message: 'This bundle has been used, so it\'s been switched off instead. Registrations that got it keep their price.' } : { deleted: true as const, message: 'Bundle deleted' }; } /** The deals shown on an event's page: available bundles, without internal fields. */ export async function publicBundlesForEvent(eventId: string) { const bundles = await prisma.eventBundle.findMany({ where: { eventId, isActive: true }, include: DETAIL_INCLUDE, orderBy: [{ order: 'asc' }, { createdAt: 'asc' }] }); const now = new Date(); return bundles.filter(b => bundlesUtil.isBundleAvailable(b, now)).map(b => { const s = shapeBundle(b, now); return { id: s.id, name: s.name, description: s.description, validUntil: s.validUntil, kind: s.kind, price: s.price, setSize: s.setSize, freeCount: s.freeCount, groupPricing: s.groupPricing, summary: s.summary, headline: s.headline, standardValue: s.standardValue, savingText: s.savingText, items: s.items.map((i: any) => ({ eventOptionId: i.eventOptionId, variantId: i.variantId, quantity: i.quantity })), }; }); } // ─── Coupon codes ──────────────────────────────────────────────────────────── const TYPES = ['percent', 'fixed', 'comp']; const ROLES = ['user', 'staff', 'supervisor', 'admin']; const COUPON_DETAIL_INCLUDE = { events: { include: { event: { select: { id: true, title: true, startDate: true, campusId: 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 } }, } as const; const SCOPED_COUPON_MSG = 'Supervisors for some campuses can only make coupons limited to events at their campuses.'; // Campus-scoped supervisors: only coupons limited to events at their campuses. const couponCampuses = (coupon: any): Array => (coupon.events || []).map((ce: any) => ce.event?.campusId ?? null); async function eventIdsAllowed(scope: object | null, eventIds: string[] | undefined) { if (!scope) return true; if (!eventIds || eventIds.length === 0) return false; // a coupon for every event const events = await prisma.event.findMany({ where: { id: { in: eventIds } }, select: { campusId: true } }); return events.length === eventIds.length && campusScope.couponAllowed(scope, events.map(e => e.campusId)); } const optionalInt = (v: unknown, label: string, min = 0): number | null | undefined => { if (v === undefined) return undefined; if (v === null || v === '') return null; const n = Number(v); if (!Number.isInteger(n) || n < min) fail(400, `${label} must be a whole number of at least ${min}`); return n; }; /** A create/update body as Prisma data plus the event, ticket and person lists. On update, fields left out stay. */ async function parseCouponBody(body: any, { isCreate }: { isCreate: boolean }) { const data: Record = {}; if (isCreate || body.code !== undefined) { const code = coupons.normalizeCode(body.code); if (!/^[A-Z0-9_-]{3,32}$/.test(code)) fail(400, 'Codes are 3–32 letters, numbers, hyphens or underscores'); data.code = code; } if (isCreate || body.type !== undefined) { if (!TYPES.includes(body.type)) fail(400, "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)) fail(400, 'Enter a discount value greater than zero'); if (type === 'percent' && value > 100) fail(400, '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) fail(400, '"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: string) => !ROLES.includes(r))) fail(400, '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)) fail(400, 'Enter an email domain like church.org'); data.restrictDomain = domain || null; } const eventIds: string[] | undefined = body.eventIds !== undefined ? [...new Set((body.eventIds || []).filter(Boolean))] : undefined; const scopes: Array<{ eventOptionId: string; variantId: string | null }> | undefined = body.options !== undefined ? (body.options || []).filter((o: any) => o && o.eventOptionId).map((o: any) => ({ eventOptionId: o.eventOptionId, variantId: o.variantId || null })) : undefined; const userIds: string[] | undefined = 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) return fail(400, 'One of the selected ticket options no longer exists'); if (s.variantId && !row.variants.some(v => v.id === s.variantId)) fail(400, '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)) fail(400, 'Selected ticket options must belong to the selected events'); } } return { data, eventIds, scopes, userIds }; } function relationWrites({ eventIds, scopes, userIds }: Awaited>, isCreate: boolean) { const out: Record = {}; const replace = isCreate ? {} : { deleteMany: {} }; if (eventIds !== undefined) out.events = { ...replace, create: eventIds.map(eventId => ({ eventId })) }; if (scopes !== undefined) out.options = { ...replace, create: scopes }; if (userIds !== undefined) out.allowedUsers = { ...replace, create: userIds.map(userId => ({ userId })) }; return out; } /** Codes the caller may see, with how often each has been used and the discount given. */ export async function listCoupons(ctx: Ctx) { const list = (await prisma.coupon.findMany({ include: COUPON_DETAIL_INCLUDE, orderBy: { createdAt: 'desc' } })).filter(c => campusScope.couponAllowed(ctx.scope, couponCampuses(c))); 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])); return list.map(c => ({ ...c, summary: coupons.describeCoupon(c), uses: byId[c.id]?._count?._all || 0, totalDiscount: byId[c.id]?._sum?.discountAmount || 0 })); } /** One code with its redemptions. */ export async function getCoupon(couponId: string, ctx: Ctx) { const coupon = await prisma.coupon.findUnique({ where: { id: couponId }, 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 || !campusScope.couponAllowed(ctx.scope, couponCampuses(coupon))) return fail(404, 'Coupon not found'); return { ...coupon, summary: coupons.describeCoupon(coupon) }; } export function createCoupon(body: any, actor: Actor, ctx: Ctx) { return clientErrors(async () => { const parsed = await parseCouponBody(body || {}, { isCreate: true }); if (!(await eventIdsAllowed(ctx.scope, parsed.eventIds))) fail(403, SCOPED_COUPON_MSG); if (await prisma.coupon.findUnique({ where: { code: parsed.data.code } })) fail(409, `The code ${parsed.data.code} already exists`); const coupon = await prisma.coupon.create({ data: { ...(parsed.data as any), createdById: actor.id, ...relationWrites(parsed, true) }, include: COUPON_DETAIL_INCLUDE }); logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'coupon_created', targetType: 'Coupon', targetId: coupon.id, metadata: { code: coupon.code, type: coupon.type, value: coupon.value }, ip: ctx.ip }); return { ...coupon, summary: coupons.describeCoupon(coupon), uses: 0, totalDiscount: 0 }; }); } /** Changes a code (or turns it off). Discounts already applied keep their locked amount; a used code can't be renamed. */ export function updateCoupon(couponId: string, body: any, actor: Actor, ctx: Ctx) { return clientErrors(async () => { const existing = await prisma.coupon.findUnique({ where: { id: couponId }, include: { events: { include: { event: { select: { campusId: true } } } } } }); if (!existing || !campusScope.couponAllowed(ctx.scope, couponCampuses(existing))) return fail(404, 'Coupon not found'); const parsed = await parseCouponBody({ type: existing.type, ...body }, { isCreate: false }); if (parsed.eventIds !== undefined && !(await eventIdsAllowed(ctx.scope, parsed.eventIds))) fail(403, SCOPED_COUPON_MSG); if (parsed.data.code && parsed.data.code !== existing.code) { if (await prisma.couponRedemption.count({ where: { couponId: existing.id } }) > 0) fail(400, '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 } })) fail(409, `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(body || {}); logAdminAction({ actorId: actor.id, actorRole: actor.role, action: disabled && changedKeys.length === 1 ? 'coupon_disabled' : 'coupon_updated', targetType: 'Coupon', targetId: coupon.id, metadata: { code: coupon.code, changedKeys }, ip: ctx.ip, }); const { usesTotal } = await coupons.countCouponUses(coupon.id, null); return { ...coupon, summary: coupons.describeCoupon(coupon), uses: usesTotal }; }); } /** * Coupon and bundle-deal uses for the Discounts report, newest first. `scopeWhere` limits it to * the caller's campuses (`{ event: … }` or `{}`). Bundle dates go by when the registration was made. */ export async function listRedemptions(opts: { eventIds: string[]; from: Date | null; to: Date | null }, scopeWhere: object) { const range = (opts.from || opts.to) ? { createdAt: { ...(opts.from ? { gte: opts.from } : {}), ...(opts.to ? { lte: opts.to } : {}) } } : {}; const events = opts.eventIds.length ? { eventId: { in: opts.eventIds } } : {}; const rows = await prisma.couponRedemption.findMany({ where: { releasedAt: null, registration: { status: { not: 'cancelled' }, ...events, ...scopeWhere }, ...range }, 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 } } } }, }, }); const bundleRows = await prisma.registrationBundle.findMany({ where: { registration: { status: { not: 'cancelled' }, ...events, ...range, ...scopeWhere } }, include: { bundle: { include: { items: { include: { eventOption: { select: { name: true } }, variant: { select: { name: true } } } } } }, registration: { select: { id: true, status: true, createdAt: true, user: { select: { id: true, name: true, email: true } }, event: { select: { id: true, title: true } } } }, }, }); return [ ...rows.map(r => ({ ...r, kind: 'coupon' as const, uses: 1, summary: coupons.describeCoupon(r.coupon) })), ...bundleRows.map(b => ({ id: b.id, kind: 'bundle' as const, uses: b.count, discountAmount: b.discount, createdAt: b.registration.createdAt, summary: bundlesUtil.describeBundle(b.bundle), coupon: { id: b.bundleId, code: b.bundle.name }, user: b.registration.user, appliedBy: null, registration: { id: b.registration.id, status: b.registration.status, event: b.registration.event }, })), ]; }