const prisma = require('../config/db'); const { safeErrorMessage } = require('../utils/errorUtils'); const { logAdminAction } = require('../utils/adminAudit'); const { getClientIp } = require('../utils/requestUtils'); const { logDataAccess } = require('../utils/accessLog'); const { listWhere, withScope } = require('../utils/campusScope'); const v = require('../utils/volunteers'); const fail = (res, error) => res.status(error.statusCode || 400).json({ message: safeErrorMessage(error), ...(error.code && typeof error.code === 'string' && !error.code.startsWith('P') ? { code: error.code } : {}) }); const audit = (req, action, targetType, targetId, metadata) => logAdminAction({ actorId: req.user.id, actorRole: req.user.role, action, targetType, targetId, metadata, ip: getClientIp(req) }); const later = p => { Promise.resolve(p).catch(() => {}); }; const CONTACT = { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true, isActive: true }; // ─── My account → Serving (anyone signed in) ────────────────────────────────── // @desc My shifts, cover requests I could take, and events looking for volunteers // @route GET /api/volunteers/me const getMine = async (req, res) => { try { const now = new Date(); const [slots, cover, events] = await Promise.all([ v.mySlots({ userId: req.user.id, now }), v.openSwaps({ userId: req.user.id, now }), v.eventsWithRoles({ now, where: { isHidden: false, goLiveAt: { lte: now } } }), ]); res.json({ slots, cover, events: events.map(e => ({ id: e.id, title: e.title, startDate: e.startDate, endDate: e.endDate, location: e.location, roles: e._count.servingRoles })) }); } catch (error) { fail(res, error); } }; // @desc An event's serving roles: how full each is, and whether I'm in it // @route GET /api/volunteers/events/:eventId const getEventRoles = async (req, res) => { try { const out = await v.roster(req.params.eventId, { userId: req.user.id }); res.json(out); } catch (error) { fail(res, error); } }; // @route POST /api/volunteers/roles/:id/sign-up const signUp = async (req, res) => { try { const { slot, role, event } = await v.signUp({ roleId: req.params.id, userId: req.user.id }); // req.user has no notification preference; the message goes the way they like it. later(prisma.user.findUnique({ where: { id: req.user.id }, select: CONTACT }).then(user => v.signedUpMessages({ user, role, event }))); res.status(201).json({ slotId: slot.id, ticket: !!slot.registrationId }); } catch (error) { fail(res, error); } }; // @desc Withdraw from a shift (the event's notify recipients are told) // @route DELETE /api/volunteers/slots/:id const withdraw = async (req, res) => { try { const out = await v.leave({ slotId: req.params.id, userId: req.user.id }); later(v.sendLeft(out)); res.json({ message: 'You\'re off the roster for this shift.' }); } catch (error) { fail(res, error); } }; // @desc "Can't make it": ask the event's other volunteers to take over // @route POST /api/volunteers/slots/:id/swap { note? } const requestSwap = async (req, res) => { try { const out = await v.requestSwap({ slotId: req.params.id, userId: req.user.id, note: req.body?.note }); if (out.created) later(v.sendSwapRequest(out)); res.status(out.created ? 201 : 200).json({ swapId: out.swap.id }); } catch (error) { fail(res, error); } }; // @route DELETE /api/volunteers/swaps/:id const cancelSwap = async (req, res) => { try { res.json(await v.cancelSwap({ swapId: req.params.id, userId: req.user.id })); } catch (error) { fail(res, error); } }; // @desc Take over someone's place. Happens at once; the event's notify recipients are told. // @route POST /api/volunteers/swaps/:id/accept const acceptSwap = async (req, res) => { try { const out = await v.acceptSwap({ swapId: req.params.id, userId: req.user.id }); later(v.sendSwapAccepted(out)); res.json({ slotId: out.slot.id, role: out.slot.role.name, event: out.event.title }); } catch (error) { fail(res, error); } }; // @desc Check in by scanning the event's volunteer QR code // @route POST /api/volunteers/check-in { qr } const checkIn = async (req, res) => { try { res.json(await v.checkInWithQr({ qr: req.body?.qr, userId: req.user.id })); } catch (error) { fail(res, error); } }; // ─── Staff: the roster on the day ───────────────────────────────────────────── // @desc Events with serving roles (or upcoming, for supervisors setting them up) // @route GET /api/volunteers/manage/events?all=1 const listEvents = async (req, res) => { try { const since = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); const base = req.query.all === '1' && ['admin', 'supervisor'].includes(req.user.role) ? { endDate: { gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } } : { endDate: { gte: since }, servingRoles: { some: {} } }; const events = await prisma.event.findMany({ where: withScope(base, await listWhere(req)), select: { id: true, title: true, startDate: true, endDate: true, scheduleType: true, campusId: true, _count: { select: { servingRoles: true } } }, orderBy: { startDate: 'asc' }, take: 200, }); res.json(events.map(e => ({ id: e.id, title: e.title, startDate: e.startDate, endDate: e.endDate, scheduleType: e.scheduleType, campusId: e.campusId, roles: e._count.servingRoles }))); } catch (error) { fail(res, error); } }; // @desc The roster sheet: roles with their volunteers, contact details and check-ins // @route GET /api/volunteers/manage/events/:eventId?log=1 const getRoster = async (req, res) => { try { const out = await v.roster(req.params.eventId, { staff: true, userId: req.user.id }); if (req.query.log === '1') { logDataAccess(req, { action: 'volunteer_roster', eventId: out.event.id, records: out.roles.reduce((n, r) => n + r.volunteers.length, 0) }); } res.json(out); } catch (error) { fail(res, error); } }; // @desc The check-in QR code volunteers scan on the day // @route GET /api/volunteers/manage/events/:eventId/qr const getQr = async (req, res) => { try { res.json(await v.checkInQr(req.params.eventId)); } catch (error) { fail(res, error); } }; // @route POST /api/volunteers/manage/slots/:id/check-in { undo? } const checkInManual = async (req, res) => { try { const out = await v.checkInManual({ slotId: req.params.id, staffUserId: req.user.id, undo: !!req.body?.undo }); if (out.changed) audit(req, 'volunteer_checked_in_manual', 'volunteer_slot', out.slot.id, { volunteer: out.slot.user.name, role: out.slot.role.name, undo: !!req.body?.undo }); res.json({ slotId: out.slot.id, changed: out.changed }); } catch (error) { fail(res, error); } }; // ─── Supervisors: roles, people, settings, reports ──────────────────────────── // @route GET /api/volunteers/manage/events/:eventId/settings const getSettings = async (req, res) => { try { res.json(await v.getSettings(req.params.eventId)); } catch (error) { fail(res, error); } }; // @desc Free volunteer place on/off: { optionId } ('new' adds a free "Volunteer" ticket, null = off) // @route PUT /api/volunteers/manage/events/:eventId/settings const saveSettings = async (req, res) => { try { const out = await v.saveSettings(req.params.eventId, { optionId: req.body?.optionId ?? null }); audit(req, 'volunteer_settings_updated', 'event', out.event.id, { volunteerOptionId: out.event.volunteerOptionId }); res.json(out); } catch (error) { fail(res, error); } }; // @route POST /api/volunteers/manage/events/:eventId/roles { name, needed, sessionId?, startsAt?, endsAt?, description?, kidsRoomId? } const createRole = async (req, res) => { try { const role = await v.createRole(req.params.eventId, req.body); audit(req, 'volunteer_roles_changed', 'serving_role', role.id, { eventId: role.eventId, created: role.name, needed: role.needed }); res.status(201).json(role); } catch (error) { fail(res, error); } }; // @route PUT /api/volunteers/manage/roles/:id const updateRole = async (req, res) => { try { const role = await v.updateRole(req.params.id, req.body); audit(req, 'volunteer_roles_changed', 'serving_role', role.id, { eventId: role.eventId, updated: role.name, needed: role.needed }); res.json(role); } catch (error) { fail(res, error); } }; // @route DELETE /api/volunteers/manage/roles/:id (its volunteers are told) const deleteRole = async (req, res) => { try { const out = await v.deleteRole(req.params.id); audit(req, 'volunteer_roles_changed', 'serving_role', out.role.id, { eventId: out.role.eventId, deleted: out.role.name, volunteers: out.volunteers.length }); later(v.sendRoleDeleted(out)); res.json({ message: 'Deleted', volunteers: out.volunteers.length }); } catch (error) { fail(res, error); } }; // @desc Put someone on a role (allowed beyond the number needed); they're told // @route POST /api/volunteers/manage/roles/:id/assign { userId } const assign = async (req, res) => { try { const user = await prisma.user.findUnique({ where: { id: String(req.body?.userId || '') }, select: CONTACT }); if (!user) throw v.volunteerError('Choose who to put on the roster.', 404); const { slot, role, event } = await v.signUp({ roleId: req.params.id, userId: user.id, assignedById: req.user.id }); audit(req, 'volunteer_assigned', 'volunteer_slot', slot.id, { eventId: event.id, role: role.name, volunteer: user.name }); if (user.isActive) later(v.signedUpMessages({ user, role, event, by: req.user.name })); res.status(201).json({ slotId: slot.id, ticket: !!slot.registrationId }); } catch (error) { fail(res, error); } }; // @desc Take someone off a role (not after they've checked in); they're told // @route DELETE /api/volunteers/manage/slots/:id const remove = async (req, res) => { try { const out = await v.leave({ slotId: req.params.id }); audit(req, 'volunteer_removed', 'volunteer_slot', out.slot.id, { eventId: out.event.id, role: out.slot.role.name, volunteer: out.slot.user.name }); later(v.sendLeft({ ...out, byStaff: req.user.name })); res.json({ message: 'Removed' }); } catch (error) { fail(res, error); } }; // @desc Hours served per person (checked-in shifts), over the events the user can see // @route GET /api/volunteers/manage/hours?eventId=&from=&to= const hours = async (req, res) => { try { const scope = await listWhere(req); const eventWhere = withScope(req.query.eventId ? { id: String(req.query.eventId) } : {}, scope); const rows = await v.hoursServed({ eventWhere, from: req.query.from || null, to: req.query.to || null }); res.json(rows); } catch (error) { fail(res, error); } }; module.exports = { getMine, getEventRoles, signUp, withdraw, requestSwap, cancelSwap, acceptSwap, checkIn, listEvents, getRoster, getQr, checkInManual, getSettings, saveSettings, createRole, updateRole, deleteRole, assign, remove, hours, };