/** * Setting events up (1.51.7): create, edit, deactivate, the staff list, notification recipients * and copying set-up from another event. Moved from eventController.js so /api/events (v1) and * /api/v2/events share it. */ import { v4 as uuidv4 } from 'uuid'; import type { Prisma } from '@prisma/client'; 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 */ type CampusScope = object | null; const sessionsUtil = require('../utils/sessions') as { sessionError(message: string): Error; normalizeReminders(v: unknown): unknown; normalizeCertificateConfig(v: unknown): unknown; normalizeSessionsInput(v: unknown): Array<{ cancelled?: boolean } & Record>; scheduleBounds(sessions: unknown[]): { startDate: Date; endDate: Date }; forgetSchedule(eventId: string): void; syncEventSessions(tx: any, eventId: string, sessions: unknown[]): Promise<{ sessions: Array<{ id: string; order: number; cancelledAt: Date | null }>; changes: Record }>; activeSessions(sessions: any[]): any[]; registrationClosesAt(ev: any, sessions: any[]): Date; wholeCourseClosesAt(ev: any, sessions: any[]): Date; lateInfo(ev: any, sessions: any[], now: Date): unknown; }; const campuses = require('../utils/campuses') as { campusesEnabled(): Promise; campusForEvent(campusId: unknown, opts: { enabled: boolean; currentCampusId?: string | null }): Promise<{ campusId?: string | null; error?: string }>; campusWhere(filter: string, opts: { enabled: boolean; withAllCampuses?: boolean }): object; resolveCampusFilter(value: unknown): Promise; EVENT_CAMPUS_SELECT: Record; }; const campusScope = require('../utils/campusScope') as { canManage(scope: object, campusId: string | null): boolean; eventWhere(scope: CampusScope): object; withScope(where: object, scopeWhere: object): object; }; const seriesUtil = require('../utils/series') as { seriesForEvent(seriesId: unknown): Promise }; const { assertEventOpen } = require('../utils/cashupUtils') as { assertEventOpen(eventId: string): Promise }; const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise }; export type Actor = { id: string; role: Role }; /** The caller's campus scope (utils/campusScope.scopeFor) and IP, for checks and the audit log. */ export type Ctx = { scope: CampusScope; ip?: string }; /** An event body as the event wizard sends it (v1 and v2 take the same fields). */ export type EventInput = Record; export const SERIES_SELECT = { select: { id: true, name: true, slug: true } } as const; export const SESSIONS_INCLUDE = { orderBy: { startsAt: 'asc' as const }, include: { _count: { select: { usages: true } } } }; /** A campus-scoped supervisor may only create or move events to one of their campuses. */ export function assertCampusAllowed(scope: CampusScope, campusId: string | null): void { if (scope && !campusScope.canManage(scope, campusId)) { fail(403, campusId == null ? 'Choose one of your campuses — events for all campuses are set up by admins and supervisors for every campus.' : 'You can only put events at your own campuses.'); } } /** * Adds the multi-day schedule to an event for API responses: sessions (cancelled ones flagged), * when registration closes, the next session, and late-joiner pricing. `bookings` (Map * sessionId → people booked) adds `booked` and `placesLeft` per session. */ export function withSchedule(ev: E, bookings: Map | null = null) { const sessions = (ev.sessions || []).map(({ _count, ...s }: any) => ({ ...s, cancelled: !!s.cancelledAt, hasCheckIns: (_count?.usages || 0) > 0, ...(bookings ? { booked: bookings.get(s.id) || 0, placesLeft: s.capacity > 0 ? Math.max(0, s.capacity - (bookings.get(s.id) || 0)) : null } : {}), })); const active = sessionsUtil.activeSessions(sessions); const now = new Date(); return { ...ev, sessions, registrationClosesAt: sessionsUtil.registrationClosesAt(ev, sessions), wholeCourseClosesAt: ev.scheduleType === 'sessions' ? sessionsUtil.wholeCourseClosesAt(ev, sessions) : null, nextSession: ev.scheduleType === 'sessions' ? active.find((s: any) => new Date(s.endsAt) > now) || null : null, lateJoin: ev.scheduleType === 'sessions' ? sessionsUtil.lateInfo(ev, sessions, now) : null, }; } /** The schedule/attendance fields from a create/update body. `current` is the saved event on update. */ export function scheduleData(body: EventInput, current: Record = {}): Record { const has = (k: string) => body[k] !== undefined; const data: Record = {}; if (has('scheduleType')) data.scheduleType = body.scheduleType === 'sessions' ? 'sessions' : 'single'; if (has('attendanceMode')) data.attendanceMode = body.attendanceMode === 'pick' ? 'pick' : 'whole'; if ((data.attendanceMode ?? current.attendanceMode) === 'pick' && (body.requiresParentalConsent ?? current.requiresParentalConsent) === true) { throw sessionsUtil.sessionError("Choosing sessions isn't available on youth events (parental consent)."); } if (has('checkInWindow')) data.checkInWindow = body.checkInWindow === 'session_only' ? 'session_only' : 'whole_day'; if (has('lateJoinEnabled')) data.lateJoinEnabled = body.lateJoinEnabled === true; if (has('latePricing')) data.latePricing = ['prorata', 'fixed'].includes(body.latePricing) ? body.latePricing : 'full'; if (has('lateFixedPrice')) { const n = parseFloat(body.lateFixedPrice); data.lateFixedPrice = body.lateFixedPrice === null || body.lateFixedPrice === '' || isNaN(n) ? null : Math.max(0, n); } if (has('sessionReminders')) data.sessionReminders = sessionsUtil.normalizeReminders(body.sessionReminders) ?? null; if (has('certificatesEnabled')) data.certificatesEnabled = body.certificatesEnabled === true; if (has('certificateConfig')) data.certificateConfig = sessionsUtil.normalizeCertificateConfig(body.certificateConfig); const latePricing = data.latePricing ?? current.latePricing; const lateFixedPrice = data.lateFixedPrice !== undefined ? data.lateFixedPrice : current.lateFixedPrice; if (latePricing === 'fixed' && (lateFixedPrice === null || lateFixedPrice === undefined) && (data.lateJoinEnabled ?? current.lateJoinEnabled)) { throw sessionsUtil.sessionError('Enter the fixed late price, or choose another late price option'); } return data; } /** * Saves the session list and the "late joining until" session, inside the caller's transaction * so a refused change saves nothing. Returns the change counts, or null when nothing was sent. */ export async function saveSchedule(tx: Prisma.TransactionClient, eventId: string, body: EventInput): Promise | null> { sessionsUtil.forgetSchedule(eventId); if (body.scheduleType === 'single') { const used = await tx.ticketUsage.count({ where: { session: { eventId } } }); if (used > 0) throw sessionsUtil.sessionError("This event already has session check-ins, so it can't go back to a single date."); await tx.eventSession.deleteMany({ where: { eventId } }); await tx.event.update({ where: { id: eventId }, data: { lateJoinUntilSessionId: null } }); return null; } if (!Array.isArray(body.sessions)) return null; const { sessions, changes } = await sessionsUtil.syncEventSessions(tx, eventId, body.sessions); if (body.lateJoinUntilSessionIndex !== undefined) { const idx = parseInt(body.lateJoinUntilSessionIndex, 10); const ordered = [...sessions].sort((a, b) => a.order - b.order); const until = Number.isInteger(idx) && ordered[idx] && !ordered[idx].cancelledAt ? ordered[idx].id : null; await tx.event.update({ where: { id: eventId }, data: { lateJoinUntilSessionId: until } }); } return changes; } const yes = (v: unknown) => v === true || v === 'true'; const notNo = (v: unknown) => !(v === false || v === 'false'); /** Replaces the event's attendee form with the one sent (`{ isRequired, fields[] }`). */ async function saveForm(eventId: string, formInput: any): Promise { if (!formInput) return; try { let form = await prisma.eventForm.findUnique({ where: { eventId } }); if (!form) form = await prisma.eventForm.create({ data: { id: uuidv4(), eventId, isRequired: !!formInput.isRequired } }); else await prisma.eventForm.update({ where: { id: form.id }, data: { isRequired: !!formInput.isRequired } }); await prisma.eventFormField.deleteMany({ where: { formId: form.id } }); const fields = Array.isArray(formInput.fields) ? formInput.fields : []; for (let i = 0; i < fields.length; i++) { const f = fields[i]; if (!f || !f.type || !f.label) continue; await prisma.eventFormField.create({ data: { id: uuidv4(), formId: form.id, type: f.type, label: String(f.label), isRequired: !!f.isRequired, order: typeof f.order === 'number' ? f.order : i, helpText: f.helpText || null, options: f.options || undefined, }, }); } } catch (e: any) { console.error('[events] Failed to save form/fields:', e?.message || e); fail(400, 'Failed to save event form/fields'); } } /** Turns a helper's plain Error (session rules, series, campus) into a 400, like v1 did. */ async function asClientErrors(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 || 'The event could not be saved'); } } /** * A new event, with a "Main Ticket" at the event price (unless it's contact-only), its sessions * and its attendee form. A campus-scoped supervisor must put it at one of their campuses. */ export function createEvent(body: EventInput, actor: Actor, ctx: Ctx) { return asClientErrors(async () => { const campusPick = await campuses.campusForEvent(body.campusId, { enabled: await campuses.campusesEnabled() }); if (campusPick.error) fail(400, campusPick.error); // Not choosing a campus means all campuses, which a scoped supervisor can't create. assertCampusAllowed(ctx.scope, campusPick.campusId === undefined ? null : campusPick.campusId); const seriesId = await seriesUtil.seriesForEvent(body.seriesId); const data: Record = { id: uuidv4(), title: body.title, description: body.description, startDate: new Date(body.startDate), endDate: new Date(body.endDate), registrationDeadline: body.registrationDeadline ? new Date(body.registrationDeadline) : null, goLiveAt: body.goLiveAt ? new Date(body.goLiveAt) : undefined, price: parseFloat(body.price), picture: body.picture, updatedAt: new Date(), createdById: actor.id, redirectUrl: body.redirectUrl, isHidden: yes(body.isHidden), requiresAuth: notNo(body.requiresAuth), requiresRegistration: notNo(body.requiresRegistration), // A youth event needs names (with dates of birth), so it always takes them. allowNamedAttendees: yes(body.allowNamedAttendees) || body.requiresParentalConsent === true, requiresParentalConsent: body.requiresParentalConsent === true, consentText: body.consentText ? String(body.consentText) : null, consentCollectMedical: body.consentCollectMedical === true, consentCollectEmergency: body.consentCollectEmergency === true, consentCollectPhoto: body.consentCollectPhoto === true, waitlistEnabled: body.waitlistEnabled === true, allowTicketTransfer: body.allowTicketTransfer !== false, collectGender: body.collectGender === true, allowSponsorships: body.allowSponsorships === true, sponsorshipGoalSpots: body.sponsorshipGoalSpots ? Math.max(1, parseInt(body.sponsorshipGoalSpots, 10) || 0) || null : null, showSponsorshipProgress: body.showSponsorshipProgress !== false, waitlistOfferHours: Math.min(168, Math.max(1, parseInt(body.waitlistOfferHours, 10) || 24)), waitlistPartialOffers: body.waitlistPartialOffers !== false, contactName: body.contactName || null, contactPhone: body.contactPhone || null, contactEmail: body.contactEmail || null, location: body.location || null, ...(campusPick.campusId !== undefined ? { campusId: campusPick.campusId } : {}), ...(seriesId ? { seriesId } : {}), ...scheduleData(body), }; if (data.scheduleType === 'sessions') { // Check the sessions before anything is saved; the dates come from them. const bounds = sessionsUtil.scheduleBounds(sessionsUtil.normalizeSessionsInput(body.sessions).filter(s => !s.cancelled)); data.startDate = bounds.startDate; data.endDate = bounds.endDate; } const event = await prisma.event.create({ data: data as Prisma.EventUncheckedCreateInput }); logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'event_created', targetType: 'Event', targetId: event.id, metadata: { title: event.title, ...(body.clonedFromId ? { clonedFromId: String(body.clonedFromId) } : {}) }, ip: ctx.ip, }); if (data.scheduleType === 'sessions') await prisma.$transaction(tx => saveSchedule(tx, event.id, body)); // A main ticket at the event price — contact-only events have nothing to book. if (data.requiresRegistration !== false) { await prisma.eventOption.create({ data: { id: uuidv4(), eventId: event.id, name: 'Main Ticket', price: event.price || 0, isMainTicket: true } }) .catch((e: any) => console.warn('[events] Failed to auto-create main ticket option:', e?.message || e)); } await saveForm(event.id, body.form); return withSchedule(await prisma.event.findUniqueOrThrow({ where: { id: event.id }, include: { sessions: SESSIONS_INCLUDE, eventOptions: true } })); }); } /** * Edits an event: only the fields sent change. Its sessions save in the same transaction (a * refused schedule change saves nothing); a changed consent text starts a new version; moving it * to another series lets that series' followers hear about it. Closed (cashed-up) events can't * change. */ export function updateEvent(eventId: string, body: EventInput, actor: Actor, ctx: Ctx) { return asClientErrors(async () => { const event = await prisma.event.findUnique({ where: { id: eventId } }); if (!event) return fail(404, 'Event not found'); // A closed (cashed-up) event's pricing/structure must not change under the reconciled totals. await assertEventOpen(eventId); const campusPick = await campuses.campusForEvent(body.campusId, { enabled: await campuses.campusesEnabled(), currentCampusId: event.campusId }); if (campusPick.error) fail(400, campusPick.error); const campusChanged = campusPick.campusId !== undefined && campusPick.campusId !== event.campusId; const seriesPick = await seriesUtil.seriesForEvent(body.seriesId); // Moved into another series: that series' followers hear about it (once it's live). const seriesChanged = seriesPick !== undefined && seriesPick !== event.seriesId; if (campusChanged) assertCampusAllowed(ctx.scope, campusPick.campusId ?? null); const keep = (k: K, v: unknown, map: (x: any) => unknown = x => x) => (v !== undefined ? map(v) : event[k]); const requiresParentalConsent = body.requiresParentalConsent ?? event.requiresParentalConsent; const data: Record = { title: body.title || event.title, description: keep('description', body.description), startDate: body.startDate ? new Date(body.startDate) : event.startDate, endDate: body.endDate ? new Date(body.endDate) : event.endDate, registrationDeadline: keep('registrationDeadline', body.registrationDeadline, v => (v ? new Date(v) : null)), goLiveAt: body.goLiveAt !== undefined ? (body.goLiveAt ? new Date(body.goLiveAt) : new Date()) : (event.goLiveAt || undefined), price: body.price ? parseFloat(body.price) : event.price, picture: keep('picture', body.picture), isActive: keep('isActive', body.isActive), isHidden: body.isHidden !== undefined ? yes(body.isHidden) : (event.isHidden ?? false), requiresAuth: body.requiresAuth !== undefined ? notNo(body.requiresAuth) : (event.requiresAuth ?? true), requiresRegistration: body.requiresRegistration !== undefined ? notNo(body.requiresRegistration) : (event.requiresRegistration ?? true), allowNamedAttendees: requiresParentalConsent === true ? true : (body.allowNamedAttendees !== undefined ? yes(body.allowNamedAttendees) : event.allowNamedAttendees), requiresParentalConsent: keep('requiresParentalConsent', body.requiresParentalConsent, v => v === true), consentCollectMedical: keep('consentCollectMedical', body.consentCollectMedical, v => v === true), consentCollectEmergency: keep('consentCollectEmergency', body.consentCollectEmergency, v => v === true), consentCollectPhoto: keep('consentCollectPhoto', body.consentCollectPhoto, v => v === true), waitlistEnabled: keep('waitlistEnabled', body.waitlistEnabled, v => v === true), allowTicketTransfer: keep('allowTicketTransfer', body.allowTicketTransfer, v => v !== false), collectGender: keep('collectGender', body.collectGender, v => v === true), allowSponsorships: keep('allowSponsorships', body.allowSponsorships, v => v === true), sponsorshipGoalSpots: keep('sponsorshipGoalSpots', body.sponsorshipGoalSpots, v => (v ? Math.max(1, parseInt(v, 10) || 0) || null : null)), showSponsorshipProgress: keep('showSponsorshipProgress', body.showSponsorshipProgress, v => v !== false), waitlistOfferHours: keep('waitlistOfferHours', body.waitlistOfferHours, v => Math.min(168, Math.max(1, parseInt(v, 10) || 24))), waitlistPartialOffers: keep('waitlistPartialOffers', body.waitlistPartialOffers, v => v !== false), // Editing the consent text starts a new version; parents who already agreed keep their // record of the old one (supervisors can re-request consent). ...(body.consentText !== undefined && String(body.consentText || '') !== String(event.consentText || '') ? { consentText: body.consentText ? String(body.consentText) : null, consentTextVersion: (event.consentTextVersion || 1) + 1 } : {}), contactName: keep('contactName', body.contactName, v => v || null), contactPhone: keep('contactPhone', body.contactPhone, v => v || null), contactEmail: keep('contactEmail', body.contactEmail, v => v || null), location: keep('location', body.location, v => v || null), ...(campusChanged ? { campusId: campusPick.campusId } : {}), ...(seriesChanged ? { seriesId: seriesPick, seriesAnnouncedAt: null } : {}), updatedAt: new Date(), redirectUrl: keep('redirectUrl', body.redirectUrl), ...scheduleData(body, event), }; // A multi-session event's dates come from its sessions (set by saveSchedule). if ((data.scheduleType ?? event.scheduleType) === 'sessions') { data.startDate = event.startDate; data.endDate = event.endDate; if (Array.isArray(body.sessions)) sessionsUtil.normalizeSessionsInput(body.sessions); else if (event.scheduleType !== 'sessions') throw sessionsUtil.sessionError('Add the sessions for a multi-session event'); } // Event fields and sessions save together: a refused schedule change saves nothing. const scheduleBody = data.scheduleType === 'single' && event.scheduleType === 'sessions' ? { scheduleType: 'single' } : body; let sessionChanges: Record | null = null; const saved = await prisma.$transaction(async (tx) => { const updated = await tx.event.update({ where: { id: eventId }, data }); sessionChanges = updated.scheduleType === 'sessions' || scheduleBody.scheduleType === 'single' ? await saveSchedule(tx, updated.id, scheduleBody) : null; return updated; }); sessionsUtil.forgetSchedule(saved.id); if (campusChanged) { logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'event_campus_changed', targetType: 'Event', targetId: saved.id, metadata: { from: event.campusId, to: campusPick.campusId }, ip: ctx.ip }); } const changes = sessionChanges as Record | null; if (changes && Object.values(changes).some(n => n > 0)) { logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'event_sessions_changed', targetType: 'Event', targetId: saved.id, metadata: changes, ip: ctx.ip }); } await saveForm(saved.id, body.form); logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'event_updated', targetType: 'Event', targetId: eventId, metadata: { changedKeys: Object.keys(body || {}) }, ip: ctx.ip }); const fresh = withSchedule(await prisma.event.findUniqueOrThrow({ where: { id: saved.id }, include: { sessions: SESSIONS_INCLUDE } })); return { ...fresh, sessionChanges: changes }; }); } /** "Deleting" an event deactivates it (registrations, payments and tickets stay). Admins only. */ export async function deactivateEvent(eventId: string, actor: Actor, ctx: Ctx) { const event = await prisma.event.findUnique({ where: { id: eventId }, select: { id: true } }); if (!event) return fail(404, 'Event not found'); const updated = await prisma.event.update({ where: { id: eventId }, data: { isActive: false, updatedAt: new Date() } }); logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'event_deleted', targetType: 'Event', targetId: eventId, ip: ctx.ip }); return updated; } export type ManagedListOptions = { includePast?: boolean; includeInactive?: boolean; excludeClosed?: boolean; campus?: string }; /** * Every event staff may see (hidden ones too) — upcoming by default; past, inactive and * closed (cashed-up) on request; limited to their campuses when they're campus-scoped. With * ticket options (tiers, variants), the attendee form, sessions, campus and series. */ export async function listManagedEvents(opts: ManagedListOptions, ctx: Ctx) { const where: Record = {}; if (!opts.includeInactive) where.isActive = true; if (!opts.includePast) where.endDate = { gte: new Date() }; if (opts.excludeClosed) where.cashupStatus = { not: 'closed' }; // ?campus=: one campus's events, or only church-wide ones. const enabled = await campuses.campusesEnabled(); Object.assign(where, campuses.campusWhere(enabled ? await campuses.resolveCampusFilter(opts.campus) : '', { enabled })); const scoped = campusScope.withScope(where, campusScope.eventWhere(ctx.scope)); const events = await prisma.event.findMany({ where: scoped, include: { eventOptions: { include: { earlyBirdTiers: true, variants: { orderBy: { order: 'asc' } } } }, form: { include: { fields: true } }, sessions: SESSIONS_INCLUDE, campus: { select: campuses.EVENT_CAMPUS_SELECT }, series: SERIES_SELECT, }, orderBy: { startDate: 'asc' }, }); return events.map(ev => withSchedule(ev)); } const RECIPIENT_SELECT = { id: true, name: true, email: true, role: true } as const; /** Who gets this event's registration, payment and daily-summary emails. */ export async function getNotifyRecipients(eventId: string) { const event = await prisma.event.findUnique({ where: { id: eventId }, select: { notifyRecipients: { select: RECIPIENT_SELECT } } }); if (!event) return fail(404, 'Event not found'); return event.notifyRecipients; } export async function setNotifyRecipients(eventId: string, userIds: string[]) { if (!Array.isArray(userIds)) fail(400, 'userIds must be an array'); const event = await prisma.event.findUnique({ where: { id: eventId }, select: { id: true } }); if (!event) return fail(404, 'Event not found'); const updated = await prisma.event.update({ where: { id: eventId }, data: { notifyRecipients: { set: userIds.map(id => ({ id })) } }, include: { notifyRecipients: { select: RECIPIENT_SELECT } }, }); return updated.notifyRecipients; } /** Copies allocation groups (and, for admins, planned costs) from another event into this one. */ export async function copySetupFrom(eventId: string, fromEventId: string, actor: Actor) { if (!fromEventId) fail(400, 'fromEventId is required'); const { copyEventSetup } = require('../utils/eventClone') as { copyEventSetup(from: string, to: string, opts: { withCosts: boolean }): Promise }; return copyEventSetup(String(fromEventId), eventId, { withCosts: actor.role === 'admin' }); }