/** * Paying a registration online (1.51.1). Moved from paymentController.createCheckout so * POST /api/payments/checkout (v1) and POST /api/v2/registrations/:id/checkout share it. */ 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 payments = require('../payments') as { MIN_ONLINE_AMOUNT: number }; const { createRegistrationCheckout } = require('../payments/checkouts') as { createRegistrationCheckout(registrationId: string, userId: string, opts: { successUrl?: string; cancelUrl?: string; failureUrl?: string; donationAmount?: number; amount?: number | null; provider?: string | null }): Promise<{ checkoutId: string; redirectUrl: string; provider: string; amount: number; registration: { id: string; eventId: string; eventTitle: string }; }>; }; const pricing = require('../utils/pricing') as { refreshPricingForRegistration(id: string): Promise<{ changed: boolean }>; computeRegistrationTotalDue(registration: any, at: Date): number; }; const { assertEventOpen } = require('../utils/cashupUtils') as { assertEventOpen(eventId: string): Promise }; export type CheckoutOptions = { /** Pay only this much of the balance (staff taking part payments). */ amount?: number | null; /** An optional donation added on top (the register form's "Donation amount"). */ donationAmount?: number | null; provider?: string | null; successUrl?: string; cancelUrl?: string; failureUrl?: string; }; export type CheckoutResult = | { priceUpdated: true; newTotal: number; message: string } | { priceUpdated?: false; checkoutId: string; redirectUrl: string; provider: string; amount: number; registration: { id: string; eventId: string; eventTitle: string } }; /** * Starts an online payment for what's owed on a registration (the owner, or a supervisor or * admin). If an early-bird price ran out since it was made, nothing is charged: the caller is * told the new total to show first. */ export async function startRegistrationCheckout(registrationId: string, actor: { id: string; role: Role }, opts: CheckoutOptions = {}): Promise { const reg = await prisma.registration.findUnique({ where: { id: registrationId }, select: { userId: true, eventId: true, event: { select: { endDate: true } } } }); if (!reg) return fail(404, 'Registration not found'); const staffSide = actor.role === 'admin' || actor.role === 'supervisor'; if (reg.userId !== actor.id && !staffSide) fail(403, 'Not authorized to create checkout for this registration'); // If event is in the past, block self-service payment (mirrors the registration-edit block) if (!staffSide && reg.event?.endDate && new Date(reg.event.endDate).getTime() < Date.now()) { fail(400, 'This event has already ended; payment can no longer be made for this registration'); } try { await assertEventOpen(reg.eventId); } catch (e: any) { throw new ServiceError(e.message === 'Event not found' ? 404 : 400, e.message); } // Refresh early-bird pricing — updates priceSnapshot if any tier has expired or sold out. // Must run before the balance is worked out so the checkout charges the right price. const { changed } = await pricing.refreshPricingForRegistration(registrationId); if (changed) { const fresh = await prisma.registration.findUniqueOrThrow({ where: { id: registrationId }, include: { registrationOptions: { include: { eventOption: { include: { earlyBirdTiers: true } }, tranches: true } }, payments: true }, }); const newTotal = pricing.computeRegistrationTotalDue(fresh, new Date()); const totalPaid = fresh.payments.reduce((s, p) => s + p.amount, 0); return { priceUpdated: true, newTotal: Math.max(0, newTotal - totalPaid), message: 'One or more early-bird prices have changed since your registration was created. Please review the updated total before proceeding.', }; } const urls = { successUrl: opts.successUrl, cancelUrl: opts.cancelUrl, failureUrl: opts.failureUrl, provider: opts.provider ?? null }; // Part of the balance (supervisor payments page) if (opts.amount !== undefined && opts.amount !== null && !isNaN(Number(opts.amount))) { return createRegistrationCheckout(registrationId, actor.id, { ...urls, amount: Number(opts.amount) }); } let donation = 0; if (opts.donationAmount !== undefined && opts.donationAmount !== null) { donation = Math.round(Number(opts.donationAmount) * 100) / 100; if (!(donation >= 0) || donation > 100000) fail(400, 'Invalid donation amount'); if (donation > 0 && donation < payments.MIN_ONLINE_AMOUNT) fail(400, `Minimum donation is R${payments.MIN_ONLINE_AMOUNT}`); } return createRegistrationCheckout(registrationId, actor.id, { ...urls, donationAmount: donation }); }