WIP 1.51.8: event detail, options, variants, attachments, calendar and alias on v2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
This commit is contained in:
2026-10-29 12:04:06 +02:00
co-authored by Claude Opus 5.5
parent 4a7f75a8ec
commit 006c4db02f
9 changed files with 4559 additions and 684 deletions
@@ -1,20 +1,18 @@
const prisma = require('../config/db');
const { v4: uuidv4 } = require('uuid');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { assertEventOpen } = require('../utils/cashupUtils');
const { getClientIp } = require('../utils/requestUtils');
const sessionsUtil = require('../utils/sessions');
const { publicOptions } = require('../utils/volunteers');
const { campusesEnabled, campusWhere, resolveCampusFilter, EVENT_CAMPUS_SELECT } = require('../utils/campuses');
const { scopeFor, canView } = require('../utils/campusScope');
const seriesUtil = require('../utils/series');
const { scopeFor } = require('../utils/campusScope');
// Setting events up is shared with /api/v2/events (TypeScript, 1.51.7).
const eventService = require('../services/events');
const { SERIES_SELECT, SESSIONS_INCLUDE, withSchedule } = eventService;
const details = require('../services/eventDetails');
// @desc Copy allocation groups (and, for admins, planned costs) from another event into a new copy
// @route POST /api/events/:id/copy-from
@@ -222,173 +220,9 @@ const getEventsAll = async (req, res) => {
// @access Public
const getEventById = async (req, res) => {
try {
const eventId = req.params.id;
// Determine if Prisma Client supports EarlyBirdTier / OptionVariant
const canIncludeTiers = !!(prisma && prisma.earlyBirdTier && typeof prisma.earlyBirdTier.findMany === 'function');
const canIncludeVariants = !!(prisma && prisma.optionVariant && typeof prisma.optionVariant.findMany === 'function');
const optionInclude = canIncludeTiers
? { earlyBirdTiers: true, ...(canIncludeVariants ? { variants: { orderBy: { order: 'asc' } } } : {}) }
: undefined;
const includeObj = { eventOptions: optionInclude ? { include: optionInclude } : true, sessions: SESSIONS_INCLUDE, campus: { select: EVENT_CAMPUS_SELECT }, series: SERIES_SELECT };
// Staff/supervisor/admin need the creator + notify-recipient list to populate the
// event edit screen's Notifications step; public callers don't need this.
const isStaffOrHigherForNotify = !!(req.user && ['admin', 'supervisor', 'staff'].includes(req.user.role));
if (isStaffOrHigherForNotify) {
includeObj.createdBy = { select: { id: true, name: true, email: true } };
includeObj.notifyRecipients = { select: { id: true, name: true, email: true, role: true } };
}
let event;
// Try to include attachments via Prisma if the client has the model
const canUsePrismaAttachments = (prisma && prisma.eventAttachment && typeof prisma.eventAttachment.findMany === 'function');
if (canUsePrismaAttachments) {
try {
// @ts-ignore - runtime guard ensures this exists
includeObj.attachments = true;
event = await prisma.event.findUnique({ where: { id: eventId }, include: includeObj });
} catch (e) {
// If relation/table does not exist (migration not deployed), fall back to fetching without attachments
try {
event = await prisma.event.findUnique({ where: { id: eventId }, include: { eventOptions: true, ...(isStaffOrHigherForNotify ? { createdBy: includeObj.createdBy, notifyRecipients: includeObj.notifyRecipients } : {}) } });
} catch (e2) {
// Notify-recipients relation not migrated yet either — fall back further
event = await prisma.event.findUnique({ where: { id: eventId }, include: { eventOptions: true } });
}
// And we will source attachments from the filesystem manifest below
}
} else {
// No model available on the Prisma client; fetch without attachments
try {
event = await prisma.event.findUnique({ where: { id: eventId }, include: { eventOptions: true, ...(isStaffOrHigherForNotify ? { createdBy: includeObj.createdBy, notifyRecipients: includeObj.notifyRecipients } : {}) } });
} catch (e) {
event = await prisma.event.findUnique({ where: { id: eventId }, include: { eventOptions: true } });
}
}
if (!event) {
res.status(404);
throw new Error('Event not found');
}
// Public gating: hide inactive or not-yet-live events from everyone except staff/supervisor/admin,
// who need to load inactive events for cashup, editing, etc. Campus-scoped staff get the
// public view of other campuses' events (and not their notification recipients).
const isStaffOrHigher = !!(req.user && ['admin', 'supervisor', 'staff'].includes(req.user.role)) && canView(await scopeFor(req), event.campusId);
if (!isStaffOrHigher) {
delete event.createdBy;
delete event.notifyRecipients;
// The kids check-in and volunteer tickets are handed out by staff, never sold.
event.eventOptions = publicOptions(event);
if (event.isActive === false) {
res.status(404);
throw new Error('Event not found');
}
// goLiveAt may not exist on older schemas — tolerate that read failing without
// affecting the isActive gate above.
let goLiveAt = null;
try { goLiveAt = event.goLiveAt ? new Date(event.goLiveAt) : null; } catch (e) {}
if (goLiveAt && new Date() < goLiveAt) {
res.status(404);
throw new Error('Event not found');
}
}
// Resolve attachments
let attachments = [];
if (event.attachments && Array.isArray(event.attachments)) {
attachments = event.attachments;
} else {
// Fall back to manifest on disk if DB attachments are not available
try {
const uploadDir = path.join(__dirname, '..', '..', 'public', 'uploads', 'event-files');
const manifestPath = path.join(uploadDir, `${eventId}.attachments.json`);
if (fs.existsSync(manifestPath)) {
const raw = fs.readFileSync(manifestPath, 'utf-8');
const list = JSON.parse(raw) || [];
attachments = list;
}
} catch {}
}
// Try include form definition if available
let form = null;
try {
if (prisma && prisma.eventForm && typeof prisma.eventForm.findUnique === 'function') {
const f = await prisma.eventForm.findUnique({
where: { eventId: eventId },
include: { fields: true },
});
if (f) {
form = {
id: f.id,
isRequired: !!f.isRequired,
fields: (f.fields || []).sort((a,b) => (a.order||0)-(b.order||0)).map(fl => ({
id: fl.id,
type: fl.type,
label: fl.label,
isRequired: !!fl.isRequired,
order: fl.order || 0,
helpText: fl.helpText || null,
options: fl.options || null,
}))
};
}
}
} catch {}
// Compute availableCount per option and variant
let eventOptionsWithStock = event.eventOptions || [];
try {
if (canIncludeVariants) {
eventOptionsWithStock = await Promise.all((event.eventOptions || []).map(async opt => {
// Taken = non-cancelled registrations + places held for live waitlist offers
const { takenCount } = require('../utils/stock');
// Picked-session options: the stock limit is places per session.
if (sessionsUtil.isPickOption(event, opt)) {
const sessionAvailability = {};
if (opt.stockLimit > 0) {
for (const s of sessionsUtil.activeSessions(event.sessions)) {
sessionAvailability[s.id] = Math.max(0, opt.stockLimit - await takenCount({ eventOptionId: opt.id, sessionId: s.id }));
}
}
return { ...opt, soldCount: 0, availableCount: null, sessionAvailability };
}
const soldCount = await takenCount({ eventOptionId: opt.id });
const availableCount = opt.stockLimit > 0 ? Math.max(0, opt.stockLimit - soldCount) : null;
// Per-variant stock
const variantsWithStock = await Promise.all((opt.variants || []).map(async v => {
if (!v.stockLimit) return { ...v, soldCount: 0, availableCount: null };
const vSold = await takenCount({ eventOptionId: opt.id, variantId: v.id });
return { ...v, soldCount: vSold, availableCount: Math.max(0, v.stockLimit - vSold) };
}));
return { ...opt, soldCount, availableCount, variants: variantsWithStock };
}));
}
} catch (e) {
// Non-fatal: fall back to options without stock info
}
if (!event.sessions) event.sessions = await prisma.eventSession.findMany({ where: { eventId }, ...SESSIONS_INCLUDE }).catch(() => []);
const bookings = event.scheduleType === 'sessions' ? await sessionsUtil.sessionBookings(eventId).catch(() => null) : null;
const mapped = withSchedule({
...event,
eventOptions: eventOptionsWithStock,
picture: toAbsoluteUrl(req, event.picture),
attachments: (attachments || []).map(att => ({
...att,
url: toAbsoluteUrl(req, att.url)
})),
form,
bundles: await require('./bundleController').publicBundlesForEvent(eventId).catch(() => []),
nextInSeries: await seriesUtil.nextInSeries(event).catch(() => null),
}, bookings);
res.json(mapped);
res.json(await details.getEventDetail(req.params.id, { staff: !!req.user && ['admin', 'supervisor', 'staff'].includes(req.user.role), scope: await scopeFor(req) }, (u) => toAbsoluteUrl(req, u)));
} catch (error) {
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
@@ -397,47 +231,12 @@ const getEventById = async (req, res) => {
// @access Public (same visibility gating as getEventById)
const getEventIcs = async (req, res) => {
try {
const eventId = req.params.id;
const event = await prisma.event.findUnique({
where: { id: eventId },
select: { id: true, title: true, description: true, startDate: true, endDate: true, location: true, isActive: true, goLiveAt: true, scheduleType: true, sessions: { orderBy: { startsAt: 'asc' } } },
});
if (!event) {
res.status(404);
throw new Error('Event not found');
}
// Same public-visibility gate as getEventById — a hidden/not-yet-live event's
// details shouldn't be enumerable via this route either.
const isStaffOrHigher = !!(req.user && ['admin', 'supervisor', 'staff'].includes(req.user.role)) && canView(await scopeFor(req), event.campusId);
if (!isStaffOrHigher) {
if (event.isActive === false) {
res.status(404);
throw new Error('Event not found');
}
let goLiveAt = null;
try { goLiveAt = event.goLiveAt ? new Date(event.goLiveAt) : null; } catch (e) {}
if (goLiveAt && new Date() < goLiveAt) {
res.status(404);
throw new Error('Event not found');
}
}
const { buildEventIcs } = require('../utils/icsUtils');
let frontendUrl = (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
// The ics library's url validator requires a scheme; guard against FRONTEND_URL/APP_BASE_URL
// being configured without one (e.g. "example.com" instead of "https://example.com").
if (!/^[a-z0-9+.-]+:\/\//i.test(frontendUrl)) {
frontendUrl = `https://${frontendUrl}`;
}
const ics = buildEventIcs(event, `${frontendUrl}/events/${event.id}`);
const { filename, ics } = await details.eventCalendar(req.params.id, { staff: !!req.user && ['admin', 'supervisor', 'staff'].includes(req.user.role), scope: await scopeFor(req) });
res.setHeader('Content-Type', 'text/calendar; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="${event.title.replace(/[^a-z0-9 -]/gi, '').slice(0, 60) || 'event'}.ics"`);
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.send(ics);
} catch (error) {
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
@@ -491,49 +290,14 @@ 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
const createEventOption = async (req, res) => {
try {
const event = await prisma.event.findUnique({
where: { id: req.params.id }
});
if (!event) {
res.status(404);
throw new Error('Event not found');
}
await assertEventOpen(req.params.id, res);
const { name, price, isMainTicket, stockLimit, staffPrice, sessionMode } = req.body;
const eventOption = await prisma.eventOption.create({
data: {
id: uuidv4(),
eventId: req.params.id,
name,
price: parseFloat(price),
isMainTicket: isMainTicket || false,
stockLimit: stockLimit ? parseInt(stockLimit, 10) : 0,
staffPrice: parseStaffPrice(staffPrice),
sessionMode: sessionMode === 'pick' ? 'pick' : 'all',
}
});
sessionsUtil.forgetSchedule(req.params.id);
res.status(201).json(eventOption);
res.status(201).json(await details.createOption(req.params.id, req.body || {}));
} catch (error) {
res.status(400).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
@@ -542,131 +306,9 @@ const createEventOption = async (req, res) => {
// @access Private/Admin
const updateEventOption = async (req, res) => {
try {
const eventOption = await prisma.eventOption.findUnique({
where: { id: req.params.id },
include: { earlyBirdTiers: true }
});
if (!eventOption) {
res.status(404);
throw new Error('Event option not found');
}
await assertEventOpen(eventOption.eventId, res);
const { name, price, isMainTicket, stockLimit, earlyBirdTiers, variants, staffPrice, sessionMode } = req.body;
const updatedEventOption = await prisma.eventOption.update({
where: { id: req.params.id },
data: {
name: name !== undefined ? name : eventOption.name,
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),
sessionMode: sessionMode !== undefined ? (sessionMode === 'pick' ? 'pick' : 'all') : eventOption.sessionMode,
}
});
// If earlyBirdTiers provided, upsert tiers for this option (including per-variant ones) by
// id — mirrors the variants upsert just below. Editing tiers used to delete-and-recreate
// every tier for the option on every save, which silently reassigned each one a brand-new
// id; RegistrationOption/RegistrationOptionTranche.appliedTierId (onDelete: SetNull) then
// pointed at nothing, so every past purchase under that tier lost its "early bird"
// attribution — even for tiers the admin didn't touch — and any stock-limit count for the
// tier reset to zero (allowing it to be oversold). Upserting by id keeps existing tiers'
// ids stable across edits so that history stays linked.
if (Array.isArray(earlyBirdTiers)) {
const incomingIds = earlyBirdTiers.filter(t => t && t.id).map(t => t.id);
const existingTiers = await prisma.earlyBirdTier.findMany({ where: { eventOptionId: updatedEventOption.id } });
for (const et of existingTiers) {
if (incomingIds.includes(et.id)) continue;
// Never delete a tier that's still attributed on past purchases — just leave it
// orphaned from the option's active tier list rather than nulling out history.
const usageCount = await prisma.registrationOptionTranche.count({ where: { appliedTierId: et.id } });
if (usageCount === 0) {
try { await prisma.earlyBirdTier.delete({ where: { id: et.id } }); } catch {}
}
}
for (let i = 0; i < earlyBirdTiers.length; i++) {
const t = earlyBirdTiers[i];
if (!t || !t.deadline || (t.price === undefined || t.price === null)) continue;
const deadline = new Date(t.deadline);
const p = parseFloat(t.price);
if (!(deadline instanceof Date) || isNaN(deadline.getTime()) || !(p >= 0)) continue;
const data = {
eventOptionId: updatedEventOption.id,
variantId: t.variantId || null,
deadline,
price: p,
order: typeof t.order === 'number' ? t.order : i,
stockLimit: t.stockLimit ? parseInt(t.stockLimit, 10) : 0,
};
if (t.id) {
await prisma.earlyBirdTier.upsert({
where: { id: t.id },
update: data,
create: { id: t.id, ...data },
});
} else {
await prisma.earlyBirdTier.create({ data: { id: require('uuid').v4(), ...data } });
}
}
}
// If variants array provided, upsert variants
if (Array.isArray(variants)) {
const incomingIds = variants.filter(v => v.id).map(v => v.id);
// Delete variants not in the new list (only if they have no registrations)
const existingVariants = await prisma.optionVariant.findMany({ where: { eventOptionId: updatedEventOption.id } });
for (const ev of existingVariants) {
if (!incomingIds.includes(ev.id)) {
const usageCount = await prisma.registrationOption.count({ where: { variantId: ev.id } });
if (usageCount === 0) {
await prisma.optionVariant.delete({ where: { id: ev.id } });
}
}
}
// Upsert incoming variants
for (let i = 0; i < variants.length; i++) {
const v = variants[i];
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, staffPrice: variantStaffPrice, order: i }
});
} else {
await prisma.optionVariant.create({
data: {
id: require('uuid').v4(),
eventOptionId: updatedEventOption.id,
name: v.name,
price: variantPrice,
stockLimit: variantStockLimit,
staffPrice: variantStaffPrice,
order: i,
}
});
}
}
}
if (stockLimit !== undefined || variants !== undefined) {
require('../utils/waitlist').queueWaitlist(eventOption.eventId);
}
const refreshed = await prisma.eventOption.findUnique({
where: { id: updatedEventOption.id },
include: { earlyBirdTiers: true, variants: { orderBy: { order: 'asc' } } }
});
res.json(refreshed);
res.json(await details.updateOption(req.params.id, req.body || {}));
} catch (error) {
res.status(400).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
@@ -675,49 +317,10 @@ const updateEventOption = async (req, res) => {
// @access Private/Admin
const deleteEventOption = async (req, res) => {
try {
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);
// If deleting a main ticket, ensure at least one other main ticket exists for the same event
if (eventOption.isMainTicket) {
const otherMainCount = await prisma.eventOption.count({
where: {
eventId: eventOption.eventId,
isMainTicket: true,
NOT: { id: eventOption.id },
}
});
if (otherMainCount === 0) {
res.status(400);
throw new Error('Cannot delete the only main ticket option');
}
}
// Check if there are any registrations using this option
const registrationOptions = await prisma.registrationOption.findMany({
where: { eventOptionId: req.params.id }
});
if (registrationOptions.length > 0) {
res.status(400);
throw new Error('Cannot delete event option that has registrations');
}
await prisma.eventOption.delete({
where: { id: req.params.id }
});
await details.deleteOption(req.params.id);
res.json({ message: 'Event option removed' });
} catch (error) {
res.status(400).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
@@ -726,25 +329,9 @@ const deleteEventOption = async (req, res) => {
// @access Private/Supervisor
const createOptionVariant = async (req, res) => {
try {
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, staffPrice } = req.body;
if (!name) { res.status(400); throw new Error('Variant name is required'); }
const variant = await prisma.optionVariant.create({
data: {
id: uuidv4(),
eventOptionId: req.params.id,
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,
}
});
res.status(201).json(variant);
res.status(201).json(await details.createVariant(req.params.id, req.body || {}));
} catch (error) {
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
@@ -753,23 +340,9 @@ const createOptionVariant = async (req, res) => {
// @access Private/Supervisor
const updateOptionVariant = async (req, res) => {
try {
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, 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,
}
});
res.json(updated);
res.json(await details.updateVariant(req.params.id, req.body || {}));
} catch (error) {
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
@@ -778,25 +351,19 @@ const updateOptionVariant = async (req, res) => {
// @access Private/Admin
const deleteOptionVariant = async (req, res) => {
try {
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 usageCount = await prisma.registrationOption.count({ where: { variantId: req.params.id } });
if (usageCount > 0) { res.status(400); throw new Error('Cannot delete variant with existing registrations'); }
await prisma.optionVariant.delete({ where: { id: req.params.id } });
await details.deleteVariant(req.params.id);
res.json({ message: 'Variant deleted' });
} catch (error) {
res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
// File upload setup for attachments (PDFs/docs)
// File upload for attachments (PDFs/docs), shared with /api/v2/events/{id}/attachments.
const attachmentsStorage = multer.diskStorage({
destination: function (req, file, cb) {
const uploadPath = path.join(__dirname, '..', '..', 'public', 'uploads', 'event-files');
try {
if (!fs.existsSync(uploadPath)) fs.mkdirSync(uploadPath, { recursive: true });
cb(null, uploadPath);
if (!fs.existsSync(details.ATTACHMENTS_DIR)) fs.mkdirSync(details.ATTACHMENTS_DIR, { recursive: true });
cb(null, details.ATTACHMENTS_DIR);
} catch (err) {
cb(err);
}
@@ -805,48 +372,31 @@ const attachmentsStorage = multer.diskStorage({
// Extension only — file.originalname is untrusted and joining it into a
// path allows `../` traversal to write outside the upload directory.
const ext = path.extname(file.originalname).toLowerCase();
const unique = `event-file-${Date.now()}-${crypto.randomBytes(8).toString('hex')}${ext}`;
cb(null, unique);
cb(null, `event-file-${Date.now()}-${crypto.randomBytes(8).toString('hex')}${ext}`);
}
});
const allowedDocs = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.csv', '.zip'];
const uploadAttachmentMulter = multer({
storage: attachmentsStorage,
limits: { fileSize: 20 * 1024 * 1024 }, // 20MB
fileFilter: (req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
if (!allowedDocs.includes(ext)) {
return cb(new Error('Unsupported file type'));
}
if (!details.ALLOWED_DOCS.includes(path.extname(file.originalname).toLowerCase())) return cb(new Error('Unsupported file type'));
cb(null, true);
}
});
// Saves the upload (field "file"); an error is kept on req for the handler to report.
const receiveAttachment = (req, res, next) => uploadAttachmentMulter.single('file')(req, res, (e) => {
if (e) req.multerError = e;
next();
});
// @desc List attachments for an event
// @route GET /api/events/:id/attachments
// @access Private/Supervisor (for dashboard) and could be public via event details
const listEventAttachments = async (req, res) => {
try {
const eventId = req.params.id;
// If attachments model isn't available yet (pre-migration/generate), fall back to filesystem manifest
if (!(prisma && prisma.eventAttachment && typeof prisma.eventAttachment.findMany === 'function')) {
try {
const uploadDir = path.join(__dirname, '..', '..', 'public', 'uploads', 'event-files');
const manifestPath = path.join(uploadDir, `${eventId}.attachments.json`);
if (!fs.existsSync(manifestPath)) return res.json([]);
const raw = fs.readFileSync(manifestPath, 'utf-8');
const list = JSON.parse(raw);
return res.json(list.map(att => ({ ...att, url: toAbsoluteUrl(req, att.url) })));
} catch (e) {
// If manifest is corrupt or unreadable, return empty list rather than failing
return res.json([]);
}
}
const items = await prisma.eventAttachment.findMany({ where: { eventId }, orderBy: { createdAt: 'desc' } });
res.json(items.map(att => ({ ...att, url: toAbsoluteUrl(req, att.url) })));
res.json(await details.listAttachments(req.params.id, (u) => toAbsoluteUrl(req, u)));
} catch (error) {
res.status(400).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
@@ -854,97 +404,14 @@ const listEventAttachments = async (req, res) => {
// @route POST /api/events/:id/attachments
// @access Private/Supervisor
const uploadEventAttachment = [
(req, res, next) => uploadAttachmentMulter.single('file')(req, res, (err) => {
if (err) req.multerError = err;
next();
}),
receiveAttachment,
async (req, res) => {
try {
if (req.multerError) throw req.multerError;
if (!req.file) return res.status(400).json({ message: 'No file uploaded' });
const eventId = req.params.id;
const relUrl = `/uploads/event-files/${req.file.filename}`;
// Fallback: if attachments model is not available yet, store in filesystem manifest
if (!(prisma && prisma.eventAttachment && typeof prisma.eventAttachment.create === 'function')) {
try { console.warn('[attachments] Falling back to filesystem manifest: Prisma client lacks EventAttachment model. Ensure prisma generate ran in the deployed app dir and server restarted.'); } catch {}
try {
const uploadDir = path.join(__dirname, '..', '..', 'public', 'uploads', 'event-files');
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
const manifestPath = path.join(uploadDir, `${eventId}.attachments.json`);
const entry = {
id: uuidv4(),
eventId,
originalName: req.file.originalname,
filename: req.file.filename,
mimeType: req.file.mimetype,
size: req.file.size,
url: relUrl,
createdAt: new Date().toISOString()
};
let list = [];
if (fs.existsSync(manifestPath)) {
try {
list = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) || [];
} catch {}
}
list.unshift(entry);
fs.writeFileSync(manifestPath, JSON.stringify(list, null, 2), 'utf-8');
return res.status(201).json({ ...entry, url: toAbsoluteUrl(req, entry.url) });
} catch (e) {
return res.status(500).json({ message: 'Failed to record attachment', detail: e?.message });
}
}
// Normal path: DB-backed
try {
const created = await prisma.eventAttachment.create({
data: {
id: uuidv4(),
eventId,
originalName: req.file.originalname,
filename: req.file.filename,
mimeType: req.file.mimetype,
size: req.file.size,
url: relUrl,
}
});
return res.status(201).json({ ...created, url: toAbsoluteUrl(req, created.url) });
} catch (e) {
const msg = String(e?.message || e || '');
const isMissingTable = msg.includes('does not exist') || msg.includes('relation') || msg.includes('P2021');
if (isMissingTable) {
try { console.warn('[attachments] DB create failed, falling back to filesystem manifest. Error:', msg); } catch {}
try {
const uploadDir = path.join(__dirname, '..', '..', 'public', 'uploads', 'event-files');
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
const manifestPath = path.join(uploadDir, `${eventId}.attachments.json`);
const entry = {
id: uuidv4(),
eventId,
originalName: req.file.originalname,
filename: req.file.filename,
mimeType: req.file.mimetype,
size: req.file.size,
url: relUrl,
createdAt: new Date().toISOString()
};
let list = [];
if (fs.existsSync(manifestPath)) {
try { list = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) || []; } catch {}
}
list.unshift(entry);
fs.writeFileSync(manifestPath, JSON.stringify(list, null, 2), 'utf-8');
return res.status(201).json({ ...entry, url: toAbsoluteUrl(req, entry.url) });
} catch (fallbackErr) {
return res.status(500).json({ message: 'Failed to record attachment', detail: String(fallbackErr?.message || fallbackErr) });
}
}
// Unknown error
throw e;
}
res.status(201).json(await details.recordAttachment(req.params.id, req.file, (u) => toAbsoluteUrl(req, u)));
} catch (error) {
res.status(400).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
}
];
@@ -954,43 +421,10 @@ const uploadEventAttachment = [
// @access Private/Admin or Supervisor
const deleteEventAttachment = async (req, res) => {
try {
const { eventId, attachmentId } = req.params;
// If attachments model is not available yet, fall back to filesystem manifest
if (!(prisma && prisma.eventAttachment && typeof prisma.eventAttachment.findUnique === 'function')) {
try {
const uploadDir = path.join(__dirname, '..', '..', 'public', 'uploads', 'event-files');
const manifestPath = path.join(uploadDir, `${eventId}.attachments.json`);
if (!fs.existsSync(manifestPath)) return res.status(404).json({ message: 'Attachment not found' });
const list = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) || [];
const idx = list.findIndex((x) => x.id === attachmentId);
if (idx === -1) return res.status(404).json({ message: 'Attachment not found' });
const att = list[idx];
// Remove file on disk (best-effort)
try {
const filePath = path.join(uploadDir, att.filename);
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
} catch {}
// Remove from manifest
list.splice(idx, 1);
fs.writeFileSync(manifestPath, JSON.stringify(list, null, 2), 'utf-8');
return res.json({ message: 'Attachment deleted' });
} catch (e) {
return res.status(500).json({ message: 'Failed to delete attachment', detail: e?.message });
}
}
const att = await prisma.eventAttachment.findUnique({ where: { id: attachmentId } });
if (!att || att.eventId !== eventId) {
return res.status(404).json({ message: 'Attachment not found' });
}
// Remove file on disk (best-effort)
try {
const filePath = path.join(__dirname, '..', '..', 'public', 'uploads', 'event-files', att.filename);
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
} catch {}
await prisma.eventAttachment.delete({ where: { id: attachmentId } });
await details.deleteAttachment(req.params.eventId, req.params.attachmentId);
res.json({ message: 'Attachment deleted' });
} catch (error) {
res.status(400).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
@@ -999,52 +433,20 @@ const deleteEventAttachment = async (req, res) => {
// @access Private/Admin
const attachmentsStatus = async (req, res) => {
try {
const hasModel = !!(prisma && prisma.eventAttachment && typeof prisma.eventAttachment.findMany === 'function');
let tableQueryable = false;
let probeError = null;
if (hasModel) {
try {
await prisma.eventAttachment.findFirst({});
tableQueryable = true;
} catch (e) {
probeError = String(e?.message || e);
}
}
// Mask DB URL to avoid leaking secrets
const dbUrl = process.env.DATABASE_URL || '';
let dbInfo = null;
try {
const u = new URL(dbUrl);
dbInfo = {
protocol: u.protocol.replace(':',''),
host: u.hostname,
port: u.port || undefined,
database: (u.pathname || '').replace(/^\//,'') || undefined,
};
} catch {}
res.json({
prismaClientHasEventAttachmentModel: hasModel,
databaseTableQueryable: tableQueryable,
probeError,
database: dbInfo,
});
res.json(await details.attachmentsStatus());
} catch (error) {
res.status(400).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
// @desc Admin-triggered sync: import manifest files into DB
// @route POST /api/events/attachments/sync
// @access Private/Admin
const { syncManifestsToDb } = require('../utils/attachmentsSync');
const attachmentsSync = async (req, res) => {
try {
const dryRun = String(req.query.dryRun || '').toLowerCase() === 'true';
const remove = String(req.query.remove || '').toLowerCase() === 'true';
const summary = await syncManifestsToDb(prisma, { dryRun, removeManifestAfterImport: remove });
res.json({ dryRun, remove, ...summary });
res.json(await details.syncAttachmentManifests({ dryRun: String(req.query.dryRun || '').toLowerCase() === 'true', remove: String(req.query.remove || '').toLowerCase() === 'true' }));
} catch (error) {
res.status(400).json({ message: error.message });
res.status(error.statusCode || 400).json({ message: error.message });
}
};
@@ -1635,58 +1037,17 @@ const scheduleWhatsappEventAttendees = async (req, res) => {
// catch-all [redirectUrl] route, so it's what every bot/scanner probe hitting
// an unmatched top-level path (/wp-login.php, /.env, etc.) ends up calling.
// Rejecting non-slug-shaped values here skips a DB round-trip for that traffic.
const VALID_ALIAS = /^[a-zA-Z0-9_-]{1,100}$/;
const getEventByAlias = async (req, res) => {
const { redirectUrl } = req.params;
if (!VALID_ALIAS.test(redirectUrl)) {
return res.status(404).json({ message: 'Event not found' });
}
try {
const event = await prisma.event.findFirst({
where: {
redirectUrl: {
equals: redirectUrl,
mode: 'insensitive',
},
isActive: true,
},
select: {
id: true,
title: true,
description: true,
startDate: true,
endDate: true,
registrationDeadline: true,
goLiveAt: true,
price: true,
picture: true,
isActive: true,
redirectUrl: true,
},
});
if (!event) {
return res.status(404).json({ message: 'Event not found or inactive' });
}
const now = new Date();
const start = event.startDate ? new Date(event.startDate) : null;
const end = event.endDate ? new Date(event.endDate) : null;
const isLive =
(!start || start >= now) &&
(!end || end >= now);
res.json({ ...event, isLive });
res.json(await details.eventByAlias(req.params.redirectUrl));
} catch (error) {
console.error('[getEventByAlias] Error:', error);
res.status(500).json({ message: 'Internal server error' });
res.status(error.statusCode || 500).json({ message: error.statusCode ? error.message : 'Internal server error' });
}
};
module.exports = {
receiveAttachment,
createEvent,
copyEventSetupFrom,
getEvents,