Files
crosscode-platform/apps/events/backend/src/utils/volunteers.js
T
joshuaandClaude Opus 5.5 a9f13a1b0a Volunteer rosters: roles, sign-ups, swaps, QR check-in, kids-room duty (backend)
Serving roles per event or session, sign-ups and assigning with an overlap
check, swaps that happen on accept (notify recipients emailed), QR and manual
check-in (kids-room roles start rostered duty), optional free volunteer ticket,
day-before reminder job, hours served, privacy hooks. The kids check-in and
volunteer tickets are left out of public event pages and public registration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 03:59:52 +02:00

783 lines
44 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Volunteer rosters (1.46.0). Who serves where at an event:
*
* - Serving roles (Welcome, Parking, Kids, Sound…) belong to one event, or — on a multi-session
* event — to one session, with the number of people needed and optional shift times (default:
* the session's or event's times). Rosters never repeat: each event/session has its own roles.
* - Anyone with an account can sign up for a role that isn't full; supervisors can also assign
* people (even beyond the number needed). Nobody can be in two roles whose shifts overlap.
* - Volunteers get a reminder the day before their shift. "Can't make it" asks for cover: the
* request shows on the Serving page and goes to the event's other volunteers, and the place
* moves as soon as someone accepts — the event's notify recipients are told, nobody approves.
* - On the day volunteers check themselves in by scanning the event's volunteer QR code (or staff
* tick them in). A role linked to a kids room puts its volunteers on duty in that room when they
* check in, so they count for the room's leader-to-children ratio.
* - A free volunteer place on a ticket of the event is off by default; a supervisor turns it on
* per event by choosing the ticket. Volunteers who already have a ticket keep theirs.
*/
const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid');
const prisma = require('../config/db');
const sessionsUtil = require('./sessions');
const MAX_NEEDED = 200;
const MAX_ROLES = 100;
const HOUR = 60 * 60 * 1000;
// Reminders go out this long before a shift, to people who signed up before then.
const REMIND_BEFORE_MS = 24 * HOUR;
// What the check-in QR code holds: the prefix, then the event's token.
const QR_PREFIX = 'SERVE-';
function volunteerError(message, statusCode = 400, code = undefined) {
return Object.assign(new Error(message), { statusCode, ...(code ? { code } : {}) });
}
// ─── Pure helpers ─────────────────────────────────────────────────────────────
/** A role's shift: its own times, else its session's, else the event's. */
function shiftOf(role, event) {
const session = role.session || (role.sessionId ? (event.sessions || []).find(s => s.id === role.sessionId) : null);
return {
startsAt: new Date(role.startsAt || session?.startsAt || event.startDate),
endsAt: new Date(role.endsAt || session?.endsAt || event.endDate),
};
}
/** Whether two shifts overlap (touching ends don't count: 08:00–10:00 and 10:00–12:00 are fine). */
function overlaps(a, b) {
return new Date(a.startsAt) < new Date(b.endsAt) && new Date(b.startsAt) < new Date(a.endsAt);
}
/** Hours in a shift, to the nearest quarter hour. */
function shiftHours(shift) {
const h = (new Date(shift.endsAt) - new Date(shift.startsAt)) / HOUR;
return h > 0 ? Math.round(h * 4) / 4 : 0;
}
/** { needed, filled, open, full } for a role with `filled` volunteers. */
function fillOf(needed, filled) {
return { needed, filled, open: Math.max(0, needed - filled), full: filled >= needed };
}
/** Volunteers can check in on the day(s) of their shift, until it ends. */
function checkInOpen(shift, now = new Date()) {
const today = sessionsUtil.dayKey(now);
return today >= sessionsUtil.dayKey(shift.startsAt) && today <= sessionsUtil.dayKey(shift.endsAt) && new Date(now) <= new Date(shift.endsAt);
}
/**
* Whether a slot's reminder is due: not sent yet, the shift starts within the next 24 hours, and
* the person signed up more than half an hour ago (someone who just signed up doesn't need one).
*/
function reminderDue({ remindedAt, createdAt }, shift, now = new Date()) {
if (remindedAt) return false;
const t = new Date(now).getTime();
const start = new Date(shift.startsAt).getTime();
return start > t && start - t <= REMIND_BEFORE_MS && t - new Date(createdAt).getTime() > HOUR / 2;
}
/** The kids room occasion a check-in counts for (see utils/kids.js occasionFor): the session, or today. */
function kidsOccasion(role, now = new Date()) {
return role.sessionId || sessionsUtil.dayKey(now);
}
/** Ticket options only staff hand out — the kids check-in and volunteer tickets — never sold publicly. */
function reservedOptionIds(event) {
return [event?.kidsOptionId, event?.volunteerOptionId].filter(Boolean);
}
/** The event's options without the reserved ones (for public event pages and lists). */
function publicOptions(event) {
const reserved = new Set(reservedOptionIds(event));
return (event?.eventOptions || []).filter(o => !reserved.has(o.id));
}
function fmtWhen(d) {
return new Date(d).toLocaleString('en-GB', { timeZone: sessionsUtil.TIMEZONE, weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
}
function fmtTime(d) {
return new Date(d).toLocaleTimeString('en-GB', { timeZone: sessionsUtil.TIMEZONE, hour: '2-digit', minute: '2-digit' });
}
/** "Sat 7 Nov, 08:00–10:30" (the end date is added when the shift runs past midnight). */
function shiftText(shift) {
const sameDay = sessionsUtil.dayKey(shift.startsAt) === sessionsUtil.dayKey(shift.endsAt);
return `${fmtWhen(shift.startsAt)}–${sameDay ? fmtTime(shift.endsAt) : fmtWhen(shift.endsAt)}`;
}
function cleanText(v, max) {
return String(v ?? '').trim().slice(0, max);
}
// ─── Loading ──────────────────────────────────────────────────────────────────
const EVENT_SELECT = {
id: true, title: true, startDate: true, endDate: true, scheduleType: true, isActive: true, location: true, campusId: true,
kidsCheckIn: true, kidsRoomSetId: true, kidsOptionId: true, volunteerOptionId: true, volunteerCheckInToken: true,
sessions: { orderBy: { startsAt: 'asc' } },
};
async function loadEvent(eventId, db = prisma) {
const event = await db.event.findUnique({ where: { id: String(eventId || '') }, select: EVENT_SELECT });
if (!event) throw volunteerError('Event not found', 404);
return event;
}
const USER_SELECT = { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true };
const ROLE_INCLUDE = {
session: true,
kidsRoom: { select: { id: true, name: true } },
slots: {
orderBy: { createdAt: 'asc' },
include: { user: { select: USER_SELECT }, assignedBy: { select: { name: true } }, checkedInBy: { select: { name: true } } },
},
swaps: { where: { status: 'open' }, orderBy: { createdAt: 'asc' } },
};
const realEmail = e => (e && !/@(guest\.local|deleted\.invalid|deleted\.local)$/.test(e) ? e : null);
/**
* A role for the API. `staff` adds the volunteers (names, contact, check-ins); others see only
* how full it is, whether they're in it, and open cover requests.
*/
function roleView(role, event, { staff = false, userId = null, now = new Date() } = {}) {
const shift = shiftOf(role, event);
const sessions = sessionsUtil.activeSessions(event.sessions);
const mine = userId ? role.slots.find(s => s.userId === userId) : null;
const swapBySlot = Object.fromEntries(role.swaps.map(w => [w.slotId, w]));
return {
id: role.id,
eventId: role.eventId,
sessionId: role.sessionId,
sessionLabel: role.session ? sessionsUtil.sessionLabel(role.session, sessions) : null,
name: role.name,
description: role.description || '',
startsAt: role.startsAt,
endsAt: role.endsAt,
shift: { startsAt: shift.startsAt, endsAt: shift.endsAt, text: shiftText(shift), hours: shiftHours(shift) },
kidsRoom: role.kidsRoom || null,
order: role.order,
past: new Date(shift.endsAt) < new Date(now),
...fillOf(role.needed, role.slots.length),
mine: mine ? { slotId: mine.id, checkedInAt: mine.checkedInAt, swapId: swapBySlot[mine.id]?.id || null } : null,
coverNeeded: role.swaps.filter(w => w.fromUserId !== userId).map(w => ({ swapId: w.id, note: w.note || '' })),
...(staff ? {
volunteers: role.slots.map(s => ({
slotId: s.id,
userId: s.user.id,
name: s.user.name,
phone: s.user.phoneNumber || null,
email: realEmail(s.user.email),
assignedBy: s.assignedBy?.name || null,
checkedInAt: s.checkedInAt,
checkedInBy: s.checkedInBy?.name || null,
checkInMethod: s.checkInMethod,
swapOpen: !!swapBySlot[s.id],
hasTicket: !!s.registrationId,
})),
} : {}),
};
}
/** An event's roster: its roles in order (by session, then shift start, then order). */
async function roster(eventId, { staff = false, userId = null, now = new Date() } = {}, db = prisma) {
const event = await loadEvent(eventId, db);
const roles = await db.servingRole.findMany({ where: { eventId: event.id }, include: ROLE_INCLUDE });
const views = roles.map(r => roleView(r, event, { staff, userId, now }))
.sort((a, b) => new Date(a.shift.startsAt) - new Date(b.shift.startsAt) || a.order - b.order || a.name.localeCompare(b.name));
const totals = views.reduce((t, r) => ({ needed: t.needed + r.needed, filled: t.filled + Math.min(r.filled, r.needed), checkedIn: t.checkedIn + (r.volunteers || []).filter(v => v.checkedInAt).length }), { needed: 0, filled: 0, checkedIn: 0 });
return {
event: { id: event.id, title: event.title, startDate: event.startDate, endDate: event.endDate, scheduleType: event.scheduleType, location: event.location, kidsCheckIn: event.kidsCheckIn },
sessions: sessionsUtil.activeSessions(event.sessions).map(s => ({ id: s.id, label: sessionsUtil.sessionLabel(s, event.sessions), startsAt: s.startsAt, endsAt: s.endsAt })),
roles: views,
totals: { ...totals, fillRate: totals.needed ? Math.round((totals.filled / totals.needed) * 100) : null },
};
}
// ─── Roles (supervisors) ──────────────────────────────────────────────────────
function parseTime(v, what) {
if (v === undefined) return undefined;
if (v === null || v === '') return null;
const d = new Date(v);
if (Number.isNaN(d.getTime())) throw volunteerError(`Enter a valid ${what}.`);
return d;
}
/** Check and clean a role from the request (`existing` when changing one). */
async function cleanRole(event, input, existing = null, db = prisma) {
const b = input || {};
const data = {};
if (b.name !== undefined || !existing) {
data.name = cleanText(b.name, 60);
if (!data.name) throw volunteerError('Enter a name for the role (e.g. Welcome, Parking, Sound).');
}
if (b.description !== undefined) data.description = cleanText(b.description, 500) || null;
if (b.needed !== undefined || !existing) {
const n = parseInt(b.needed ?? 1, 10);
if (!Number.isFinite(n) || n < 1 || n > MAX_NEEDED) throw volunteerError(`The number of people needed must be from 1 to ${MAX_NEEDED}.`);
data.needed = n;
}
if (b.sessionId !== undefined || !existing) {
if (event.scheduleType === 'sessions') {
const session = event.sessions.find(s => s.id === b.sessionId && !s.cancelledAt);
if (!session) throw volunteerError('Choose the session this role is for.');
data.sessionId = session.id;
} else data.sessionId = null;
}
const startsAt = parseTime(b.startsAt, 'start time');
const endsAt = parseTime(b.endsAt, 'end time');
if (startsAt !== undefined) data.startsAt = startsAt;
if (endsAt !== undefined) data.endsAt = endsAt;
const shift = shiftOf({ ...existing, ...data, session: undefined }, event);
if (shift.endsAt <= shift.startsAt) throw volunteerError('The shift has to end after it starts.');
if (b.kidsRoomId !== undefined) {
if (!b.kidsRoomId) data.kidsRoomId = null;
else {
const room = event.kidsRoomSetId ? await db.allocationGroup.findFirst({ where: { id: String(b.kidsRoomId), setId: event.kidsRoomSetId } }) : null;
if (!room) throw volunteerError('Choose one of this event\'s kids rooms (set up under Kids check-in setup).');
data.kidsRoomId = room.id;
}
}
if (b.order !== undefined) data.order = Math.max(0, Math.min(1000, parseInt(b.order, 10) || 0));
return data;
}
async function createRole(eventId, input, db = prisma) {
const event = await loadEvent(eventId, db);
if (await db.servingRole.count({ where: { eventId: event.id } }) >= MAX_ROLES) throw volunteerError(`An event can have up to ${MAX_ROLES} serving roles.`);
const data = await cleanRole(event, input, null, db);
if (input?.order === undefined) data.order = await db.servingRole.count({ where: { eventId: event.id, sessionId: data.sessionId } });
return db.servingRole.create({ data: { ...data, eventId: event.id } });
}
async function updateRole(roleId, input, db = prisma) {
const existing = await db.servingRole.findUnique({ where: { id: String(roleId || '') } });
if (!existing) throw volunteerError('Role not found', 404);
const event = await loadEvent(existing.eventId, db);
const data = await cleanRole(event, input, existing, db);
if (data.sessionId !== undefined && data.sessionId !== existing.sessionId && await db.volunteerSlot.count({ where: { roleId: existing.id } })) {
throw volunteerError('People have signed up for this role, so it can\'t move to another session — add a new role there instead.');
}
return db.servingRole.update({ where: { id: existing.id }, data });
}
/**
* Delete a role. Refused once someone has checked in for it (it counts for hours served).
* Returns the volunteers who were on it, so they can be told.
*/
async function deleteRole(roleId, db = prisma) {
const role = await db.servingRole.findUnique({ where: { id: String(roleId || '') }, include: { slots: { include: { user: { select: USER_SELECT } } } } });
if (!role) throw volunteerError('Role not found', 404);
if (role.slots.some(s => s.checkedInAt)) throw volunteerError('Someone has already checked in for this role, so it stays on the roster (it counts for hours served).');
const event = await loadEvent(role.eventId, db);
await db.$transaction(async tx => {
for (const s of role.slots) await releasePlace(tx, s);
await tx.servingRole.delete({ where: { id: role.id } });
});
return { role, event, volunteers: role.slots.map(s => s.user) };
}
// ─── Settings ─────────────────────────────────────────────────────────────────
/** The event's volunteer settings and the tickets that can be the volunteer ticket. */
async function getSettings(eventId, db = prisma) {
const event = await loadEvent(eventId, db);
const [options, rooms] = await Promise.all([
db.eventOption.findMany({ where: { eventId: event.id, isMainTicket: true, sessionMode: 'all' }, select: { id: true, name: true, price: true }, orderBy: { name: 'asc' } }),
event.kidsRoomSetId ? db.allocationGroup.findMany({ where: { setId: event.kidsRoomSetId }, select: { id: true, name: true }, orderBy: { order: 'asc' } }) : [],
]);
return {
event: { id: event.id, title: event.title, volunteerOptionId: event.volunteerOptionId },
options: options.filter(o => o.id !== event.kidsOptionId),
kidsRooms: rooms,
};
}
/**
* Turn the free volunteer place on or off. `optionId: 'new'` adds a free "Volunteer" main ticket
* (staff-only: it never shows publicly); null switches it off (places already given stay).
*/
async function saveSettings(eventId, { optionId }, db = prisma) {
const event = await loadEvent(eventId, db);
let next = null;
if (optionId === 'new') {
next = (await db.eventOption.create({ data: { eventId: event.id, name: 'Volunteer', price: 0, isMainTicket: true, sessionMode: 'all' } })).id;
} else if (optionId) {
const opt = await db.eventOption.findFirst({ where: { id: String(optionId), eventId: event.id, isMainTicket: true, sessionMode: 'all' } });
if (!opt || opt.id === event.kidsOptionId) throw volunteerError('Choose a main ticket of this event that covers the whole event (not the kids ticket).');
next = opt.id;
}
await db.event.update({ where: { id: event.id }, data: { volunteerOptionId: next } });
return getSettings(event.id, db);
}
/** The event's check-in QR value (the token is made the first time). */
async function checkInQr(eventId, db = prisma) {
const event = await loadEvent(eventId, db);
let token = event.volunteerCheckInToken;
if (!token) {
token = crypto.randomBytes(12).toString('hex');
await db.event.update({ where: { id: event.id }, data: { volunteerCheckInToken: token } });
}
return { token, qr: QR_PREFIX + token };
}
// ─── The free volunteer place ─────────────────────────────────────────────────
/**
* Give a volunteer a free place on the event's volunteer ticket, when that's switched on and they
* have no ticket for the event yet. Returns the registration id (shared by their slots), or null.
*/
async function givePlace(tx, event, userId) {
if (!event.volunteerOptionId) return null;
const shared = await tx.volunteerSlot.findFirst({ where: { userId, registrationId: { not: null }, role: { eventId: event.id }, registration: { status: { not: 'cancelled' } } }, select: { registrationId: true } });
if (shared) return shared.registrationId;
const hasTicket = await tx.ticket.count({ where: { eventId: event.id, OR: [{ userId }, { holderUserId: userId }], registrationOption: { registration: { status: { not: 'cancelled' } } } } });
if (hasTicket) return null;
const registration = await tx.registration.create({ data: { userId, eventId: event.id, status: 'paid' } });
const line = await tx.registrationOption.create({ data: { registrationId: registration.id, eventOptionId: event.volunteerOptionId, quantity: 1, priceSnapshot: 0 } });
await tx.registrationOptionTranche.create({ data: { registrationOptionId: line.id, quantity: 1, priceSnapshot: 0 } });
await tx.ticket.create({ data: { id: uuidv4(), qrCode: uuidv4(), registrationOptionId: line.id, userId, eventId: event.id, quantity: 1, emailSent: true } });
return registration.id;
}
/**
* When a slot goes (withdrawn, removed, swapped away): cancel its free place if no other slot of
* the person at the event still uses it and the ticket was never scanned.
*/
async function releasePlace(tx, slot) {
if (!slot.registrationId) return;
const others = await tx.volunteerSlot.count({ where: { registrationId: slot.registrationId, id: { not: slot.id }, userId: slot.userId } });
if (others) return;
const scanned = await tx.ticketUsage.count({ where: { ticket: { registrationOption: { registrationId: slot.registrationId } } } });
if (scanned) return;
await tx.registration.updateMany({ where: { id: slot.registrationId, status: { not: 'cancelled' } }, data: { status: 'cancelled' } });
}
// ─── Signing up ───────────────────────────────────────────────────────────────
async function loadRole(roleId, db = prisma) {
const role = await db.servingRole.findUnique({ where: { id: String(roleId || '') }, include: { session: true, slots: { select: { id: true, userId: true } } } });
if (!role) throw volunteerError('Role not found', 404);
return role;
}
/** Refuse a role whose shift is over, a cancelled session, or an inactive event. */
function assertOpen(role, event, now = new Date()) {
if (!event.isActive) throw volunteerError('This event isn\'t open any more.');
if (role.session?.cancelledAt) throw volunteerError('That session was cancelled.');
if (shiftOf(role, event).endsAt <= new Date(now)) throw volunteerError('This shift is already over.');
}
/** Refuse when the person serves in another role at the same time. */
async function assertFree(tx, event, role, userId) {
const shift = shiftOf(role, event);
const theirs = await tx.volunteerSlot.findMany({ where: { userId, roleId: { not: role.id }, role: { eventId: event.id } }, include: { role: { include: { session: true } } } });
const clash = theirs.find(s => overlaps(shiftOf(s.role, event), shift));
if (clash) throw volunteerError(`${clash.role.name} (${shiftText(shiftOf(clash.role, event))}) is at the same time.`, 409, 'SHIFT_CLASH');
}
/**
* Put someone on a role: they signed up (`assignedById` null — refused when the role is full), or
* a supervisor assigned them (allowed beyond the number needed).
*/
async function signUp({ roleId, userId, assignedById = null, now = new Date() }, db = prisma) {
const role = await loadRole(roleId, db);
const event = await loadEvent(role.eventId, db);
assertOpen(role, event, now);
if (role.slots.some(s => s.userId === userId)) throw volunteerError(assignedById ? 'This person is already on this role.' : 'You\'re already serving in this role.', 409);
const slot = await db.$transaction(async tx => {
if (!assignedById && await tx.volunteerSlot.count({ where: { roleId: role.id } }) >= role.needed) throw volunteerError('This role is full — thank you for offering!', 409, 'ROLE_FULL');
await assertFree(tx, event, role, userId);
const registrationId = await givePlace(tx, event, userId);
return tx.volunteerSlot.create({ data: { roleId: role.id, userId, assignedById, registrationId } });
});
return { slot, role, event };
}
async function loadSlot(slotId, db = prisma) {
const slot = await db.volunteerSlot.findUnique({ where: { id: String(slotId || '') }, include: { user: { select: USER_SELECT }, role: { include: { session: true } } } });
if (!slot) throw volunteerError('Not found', 404);
return slot;
}
/** Take someone off a role (they withdrew, or a supervisor removed them). Not after check-in. */
async function leave({ slotId, userId = null }, db = prisma) {
const slot = await loadSlot(slotId, db);
if (userId && slot.userId !== userId) throw volunteerError('Not found', 404);
if (slot.checkedInAt) throw volunteerError(`${userId ? 'You\'ve' : `${slot.user.name} has`} already checked in for this shift.`);
const event = await loadEvent(slot.role.eventId, db);
if (userId && shiftOf(slot.role, event).endsAt <= new Date()) throw volunteerError('This shift is already over.');
await db.$transaction(async tx => {
await tx.volunteerSwap.updateMany({ where: { slotId: slot.id, status: 'open' }, data: { status: 'cancelled', resolvedAt: new Date() } });
await releasePlace(tx, slot);
await tx.volunteerSlot.delete({ where: { id: slot.id } });
});
return { slot, event };
}
// ─── Swaps ────────────────────────────────────────────────────────────────────
/** "Can't make it": ask for someone to take over the slot. One open request per slot. */
async function requestSwap({ slotId, userId, note, now = new Date() }, db = prisma) {
const slot = await loadSlot(slotId, db);
if (slot.userId !== userId) throw volunteerError('Not found', 404);
const event = await loadEvent(slot.role.eventId, db);
assertOpen(slot.role, event, now);
if (slot.checkedInAt) throw volunteerError('You\'ve already checked in for this shift.');
const open = await db.volunteerSwap.findFirst({ where: { slotId: slot.id, status: 'open' } });
if (open) return { swap: open, slot, event, created: false };
const swap = await db.volunteerSwap.create({ data: { slotId: slot.id, roleId: slot.roleId, fromUserId: userId, note: cleanText(note, 300) || null } });
return { swap, slot, event, created: true };
}
async function cancelSwap({ swapId, userId }, db = prisma) {
const out = await db.volunteerSwap.updateMany({ where: { id: String(swapId || ''), fromUserId: userId, status: 'open' }, data: { status: 'cancelled', resolvedAt: new Date() } });
if (!out.count) throw volunteerError('Not found', 404);
return { cancelled: true };
}
/**
* Take over a slot someone can't make. Happens at once: the slot moves to the person accepting
* (their reminder and free place are theirs now). Returns { swap, slot, from, to, event }.
*/
async function acceptSwap({ swapId, userId, now = new Date() }, db = prisma) {
const swap = await db.volunteerSwap.findUnique({ where: { id: String(swapId || '') } });
if (!swap || swap.status !== 'open' || !swap.slotId) throw volunteerError('Someone has already taken this place, or it isn\'t needed any more.', 409, 'SWAP_CLOSED');
if (swap.fromUserId === userId) throw volunteerError('This is your own request — cancel it instead.');
const slot = await loadSlot(swap.slotId, db);
const event = await loadEvent(slot.role.eventId, db);
assertOpen(slot.role, event, now);
await db.$transaction(async tx => {
// Claim the request first, so two people accepting at once can't both take it.
const claimed = await tx.volunteerSwap.updateMany({ where: { id: swap.id, status: 'open' }, data: { status: 'accepted', toUserId: userId, resolvedAt: new Date(now) } });
if (!claimed.count) throw volunteerError('Someone has just taken this place.', 409, 'SWAP_CLOSED');
if (await tx.volunteerSlot.count({ where: { roleId: slot.roleId, userId } })) throw volunteerError('You\'re already serving in this role.', 409);
await assertFree(tx, event, slot.role, userId);
await releasePlace(tx, slot);
const registrationId = await givePlace(tx, event, userId);
await tx.volunteerSlot.update({ where: { id: slot.id }, data: { userId, assignedById: null, registrationId, remindedAt: null } });
});
const to = await db.user.findUnique({ where: { id: userId }, select: USER_SELECT });
return { swap, slot, from: slot.user, to, event };
}
/** Open cover requests the person could take (not their own, not a role they're in, not over). */
async function openSwaps({ userId, now = new Date() }, db = prisma) {
const swaps = await db.volunteerSwap.findMany({
where: { status: 'open', fromUserId: { not: userId }, role: { event: { isActive: true, endDate: { gte: now } }, slots: { none: { userId } } } },
include: { role: { include: { session: true, event: { select: EVENT_SELECT } } }, fromUser: { select: { name: true } } },
orderBy: { createdAt: 'asc' },
take: 50,
});
return swaps
.map(w => ({ w, shift: shiftOf(w.role, w.role.event) }))
.filter(({ shift }) => shift.endsAt > new Date(now))
.map(({ w, shift }) => ({
swapId: w.id, note: w.note || '', from: (w.fromUser?.name || '').split(' ')[0] || null,
role: { id: w.role.id, name: w.role.name, sessionLabel: w.role.session ? sessionsUtil.sessionLabel(w.role.session, w.role.event.sessions) : null },
event: { id: w.role.event.id, title: w.role.event.title },
shift: { startsAt: shift.startsAt, endsAt: shift.endsAt, text: shiftText(shift) },
}));
}
// ─── Check-in ─────────────────────────────────────────────────────────────────
/** Put a checked-in volunteer of a kids-room role on duty in that room for the occasion. */
async function startKidsDuty(tx, event, role, userId, now) {
if (!role.kidsRoomId || !event.kidsCheckIn || !event.kidsRoomSetId) return false;
const room = await tx.allocationGroup.findFirst({ where: { id: role.kidsRoomId, setId: event.kidsRoomSetId }, select: { id: true } });
if (!room) return false;
const occasion = kidsOccasion(role, now);
const already = await tx.kidsRoomDuty.findFirst({ where: { userId, occasion, roomId: room.id, endedAt: null } });
if (already) return true;
// One room at a time, as with "I'm on duty".
await tx.kidsRoomDuty.updateMany({ where: { userId, occasion, endedAt: null }, data: { endedAt: new Date(now) } });
await tx.kidsRoomDuty.create({ data: { roomId: room.id, occasion, userId, fromRoster: true, startedAt: new Date(now) } });
return true;
}
async function markCheckedIn(tx, event, slot, { by, method, now }) {
await tx.volunteerSlot.update({ where: { id: slot.id }, data: { checkedInAt: new Date(now), checkedInById: by, checkInMethod: method } });
return startKidsDuty(tx, event, slot.role, slot.userId, now);
}
/**
* A volunteer scanned the event's check-in QR code: check in every slot of theirs whose shift is
* on today. Returns { event, checkedIn: [{ role, kidsRoom }], already }.
*/
async function checkInWithQr({ qr, userId, now = new Date() }, db = prisma) {
const token = String(qr || '').trim().replace(new RegExp(`^${QR_PREFIX}`, 'i'), '');
const found = token ? await db.event.findUnique({ where: { volunteerCheckInToken: token }, select: { id: true } }) : null;
if (!found) throw volunteerError('That isn\'t a volunteer check-in code from this site.', 404, 'BAD_QR');
const event = await loadEvent(found.id, db);
const slots = await db.volunteerSlot.findMany({ where: { userId, role: { eventId: event.id } }, include: { role: { include: { session: true, kidsRoom: { select: { name: true } } } } } });
if (!slots.length) throw volunteerError(`You're not on the volunteer roster for ${event.title}.`, 404, 'NOT_ROSTERED');
const today = slots.filter(s => !s.role.session?.cancelledAt && checkInOpen(shiftOf(s.role, event), now));
if (!today.length) {
const next = slots.map(s => shiftOf(s.role, event)).filter(sh => sh.endsAt > new Date(now)).sort((a, b) => a.startsAt - b.startsAt)[0];
throw volunteerError(next ? `Check-in opens on the day of your shift (${shiftText(next)}).` : 'Your shifts at this event are over.', 400, 'NOT_TODAY');
}
const checkedIn = [];
const already = [];
await db.$transaction(async tx => {
for (const s of today) {
if (s.checkedInAt) { already.push(s.role.name); continue; }
const onDuty = await markCheckedIn(tx, event, s, { by: userId, method: 'qr', now });
checkedIn.push({ role: s.role.name, kidsRoom: onDuty ? s.role.kidsRoom?.name || null : null });
}
});
return { event: { id: event.id, title: event.title }, checkedIn, already };
}
/** Staff tick a volunteer in (or undo it, which also ends their rostered kids-room duty). */
async function checkInManual({ slotId, staffUserId, undo = false, now = new Date() }, db = prisma) {
const slot = await loadSlot(slotId, db);
const event = await loadEvent(slot.role.eventId, db);
if (undo) {
if (!slot.checkedInAt) return { slot, changed: false };
await db.$transaction(async tx => {
await tx.volunteerSlot.update({ where: { id: slot.id }, data: { checkedInAt: null, checkedInById: null, checkInMethod: null } });
if (slot.role.kidsRoomId) await tx.kidsRoomDuty.updateMany({ where: { userId: slot.userId, roomId: slot.role.kidsRoomId, fromRoster: true, endedAt: null }, data: { endedAt: new Date(now) } });
});
return { slot, changed: true };
}
if (slot.checkedInAt) return { slot, changed: false };
if (!checkInOpen(shiftOf(slot.role, event), now) && new Date(now) < shiftOf(slot.role, event).startsAt) {
throw volunteerError(`${slot.user.name} can be checked in on the day of the shift (${shiftText(shiftOf(slot.role, event))}).`);
}
await db.$transaction(tx => markCheckedIn(tx, event, slot, { by: staffUserId, method: 'manual', now }));
return { slot, changed: true };
}
/** For the kids board: who is rostered in each room for an occasion, and whether they've checked in. */
async function rosteredForRooms(event, occasion, db = prisma) {
if (!event.kidsRoomSetId) return {};
const roles = await db.servingRole.findMany({
where: { eventId: event.id, kidsRoom: { setId: event.kidsRoomSetId }, ...(event.scheduleType === 'sessions' ? { sessionId: occasion } : {}) },
include: { session: true, slots: { include: { user: { select: { id: true, name: true } } } } },
});
const out = {};
for (const r of roles) {
// Single-date events: only roles whose shift is on that day.
if (event.scheduleType !== 'sessions') {
const shift = shiftOf(r, event);
if (occasion < sessionsUtil.dayKey(shift.startsAt) || occasion > sessionsUtil.dayKey(shift.endsAt)) continue;
}
for (const s of r.slots) {
(out[r.kidsRoomId] ||= []).push({ userId: s.user.id, name: s.user.name, checkedIn: !!s.checkedInAt });
}
}
return out;
}
// ─── My serving ───────────────────────────────────────────────────────────────
/** The person's upcoming (and the last week's) slots, with open swap requests. */
async function mySlots({ userId, now = new Date() }, db = prisma) {
const since = new Date(new Date(now).getTime() - 7 * 24 * HOUR);
const slots = await db.volunteerSlot.findMany({
where: { userId, role: { event: { endDate: { gte: since } } } },
include: { role: { include: { session: true, kidsRoom: { select: { name: true } }, event: { select: EVENT_SELECT } } }, swaps: { where: { status: 'open' } } },
});
return slots
.map(s => {
const shift = shiftOf(s.role, s.role.event);
return {
slotId: s.id,
role: { id: s.role.id, name: s.role.name, description: s.role.description || '', sessionLabel: s.role.session ? sessionsUtil.sessionLabel(s.role.session, s.role.event.sessions) : null, kidsRoom: s.role.kidsRoom?.name || null },
event: { id: s.role.event.id, title: s.role.event.title, location: s.role.event.location },
shift: { startsAt: shift.startsAt, endsAt: shift.endsAt, text: shiftText(shift), hours: shiftHours(shift) },
checkedInAt: s.checkedInAt,
canCheckIn: !s.checkedInAt && checkInOpen(shift, now),
past: shift.endsAt < new Date(now),
swapId: s.swaps[0]?.id || null,
hasTicket: !!s.registrationId,
};
})
.sort((a, b) => new Date(a.shift.startsAt) - new Date(b.shift.startsAt));
}
/** Upcoming events with serving roles (for "Serve at an event"). */
async function eventsWithRoles({ now = new Date(), where = {} } = {}, db = prisma) {
return db.event.findMany({
where: { AND: [{ isActive: true, endDate: { gte: now }, servingRoles: { some: {} } }, where] },
select: { id: true, title: true, startDate: true, endDate: true, location: true, campusId: true, isHidden: true, _count: { select: { servingRoles: true } } },
orderBy: { startDate: 'asc' },
take: 100,
});
}
// ─── Reports ──────────────────────────────────────────────────────────────────
/**
* Hours served per person over the events matching `eventWhere` (checked-in shifts only), most
* hours first: [{ userId, name, shifts, hours, events }].
*/
async function hoursServed({ eventWhere = {}, from = null, to = null } = {}, db = prisma) {
const slots = await db.volunteerSlot.findMany({
where: { checkedInAt: { not: null, ...(from ? { gte: new Date(from) } : {}), ...(to ? { lte: new Date(to) } : {}) }, role: { event: eventWhere } },
include: { user: { select: { id: true, name: true } }, role: { include: { session: true, event: { select: { id: true, startDate: true, endDate: true, sessions: true } } } } },
});
const byUser = new Map();
for (const s of slots) {
const row = byUser.get(s.userId) || { userId: s.userId, name: s.user.name, shifts: 0, hours: 0, events: new Set() };
row.shifts += 1;
row.hours += shiftHours(shiftOf(s.role, s.role.event));
row.events.add(s.role.event.id);
byUser.set(s.userId, row);
}
return [...byUser.values()].map(r => ({ ...r, events: r.events.size })).sort((a, b) => b.hours - a.hours || a.name.localeCompare(b.name));
}
// ─── Messages ─────────────────────────────────────────────────────────────────
function frontendUrl() {
return String(process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
}
const servingUrl = () => `${frontendUrl()}/dashboard/user/serving`;
/** Send a text to a volunteer the way they like it (WhatsApp, email, or whichever works). Fire-and-forget. */
function tell(user, { subject, heading, text }) {
if (!user) return Promise.resolve([]);
return require('./kids').messageParent(user, { subject, heading, text }).catch(() => []);
}
/** Email the event's notify recipients (or its creator) about a roster change. */
async function tellOrganisers(eventId, { subject, text }, db = prisma) {
const event = await db.event.findUnique({
where: { id: eventId },
include: { createdBy: { select: { email: true } }, notifyRecipients: { select: { email: true } } },
});
const to = require('./notifications').getEventNotifyEmails(event);
if (!to.length) return;
const { sendMail, buildPrivacyEmail } = require('./email');
await sendMail({ to: to.join(','), subject, ...buildPrivacyEmail({ name: 'team', heading: subject, paragraphs: [text, `Roster: ${frontendUrl()}/dashboard/supervisor/volunteers?event=${eventId}`] }) }).catch(() => {});
}
function placeText(role, event) {
return `${role.name} at ${event.title}${role.session ? ` (${sessionsUtil.sessionLabel(role.session, event.sessions)})` : ''}, ${shiftText(shiftOf(role, event))}`;
}
function signedUpMessages({ user, role, event, by = null }) {
const text = by
? `${by} has put you on the volunteer roster: ${placeText(role, event)}. Thank you for serving! If you can't make it, ask for cover in My account → Serving (${servingUrl()}).`
: `Thank you for volunteering: ${placeText(role, event)}. You'll get a reminder the day before. If you can't make it, ask for cover in My account → Serving (${servingUrl()}).`;
return tell(user, { subject: `Serving: ${role.name} — ${event.title}`, heading: 'You\'re on the roster', text });
}
/** The cover request goes to the event's other volunteers (not the ones already in this role). */
async function sendSwapRequest({ swap, slot, event }, db = prisma) {
const others = await db.volunteerSlot.findMany({
where: { role: { eventId: event.id }, userId: { not: slot.userId }, NOT: { roleId: slot.roleId } },
distinct: ['userId'],
include: { user: { select: USER_SELECT } },
take: 200,
});
const inRole = new Set((await db.volunteerSlot.findMany({ where: { roleId: slot.roleId }, select: { userId: true } })).map(s => s.userId));
const first = (slot.user.name || '').split(' ')[0] || 'A volunteer';
const text = `${first} can't make it and is looking for someone to take over: ${placeText(slot.role, event)}.${swap.note ? ` "${swap.note}"` : ''} If you can, take it over in My account → Serving (${servingUrl()}) — the first to accept gets it.`;
for (const o of others) {
if (inRole.has(o.userId)) continue;
await tell(o.user, { subject: `Cover needed: ${slot.role.name} — ${event.title}`, heading: 'Can you take over?', text });
}
return others.length;
}
async function sendSwapAccepted({ slot, from, to, event }) {
const what = placeText(slot.role, event);
await tell(from, { subject: `${to.name} is taking over — ${event.title}`, heading: 'Your place is covered', text: `${to.name} has taken over ${what}. You're off the roster for it — thank you for finding cover.` });
await tell(to, { subject: `Serving: ${slot.role.name} — ${event.title}`, heading: 'You\'re on the roster', text: `Thank you for taking over from ${from.name}: ${what}. You'll get a reminder the day before.` });
await tellOrganisers(event.id, { subject: `Roster swap: ${slot.role.name} — ${event.title}`, text: `${to.name} has taken over from ${from.name}: ${what}.` });
}
async function sendLeft({ slot, event, byStaff = null }) {
const what = placeText(slot.role, event);
if (byStaff) {
await tell(slot.user, { subject: `Roster change — ${event.title}`, heading: 'Roster change', text: `${byStaff} has taken you off the roster for ${what}. Thank you for being willing to serve.` });
} else {
await tellOrganisers(event.id, { subject: `Volunteer withdrew: ${slot.role.name} — ${event.title}`, text: `${slot.user.name} has withdrawn from ${what}.` });
}
}
async function sendRoleDeleted({ role, event, volunteers }) {
for (const u of volunteers) {
await tell(u, { subject: `Roster change — ${event.title}`, heading: 'Roster change', text: `The ${role.name} role at ${event.title} is no longer needed, so you're off the roster for it. Thank you for being willing to serve.` });
}
}
/** Reminders for shifts starting within the next 24 hours. Returns { sent }. */
async function runReminderJob(now = new Date(), db = prisma) {
const slots = await db.volunteerSlot.findMany({
where: { remindedAt: null, checkedInAt: null, role: { event: { isActive: true, endDate: { gte: now }, startDate: { lte: new Date(new Date(now).getTime() + 31 * 24 * HOUR) } } } },
include: { user: { select: USER_SELECT }, role: { include: { session: true, event: { select: EVENT_SELECT } } } },
take: 2000,
});
let sent = 0;
for (const s of slots) {
if (s.role.session?.cancelledAt) continue;
const shift = shiftOf(s.role, s.role.event);
if (!reminderDue(s, shift, now)) continue;
// Claim it first so a second backend process doesn't send it again.
const claimed = await db.volunteerSlot.updateMany({ where: { id: s.id, remindedAt: null }, data: { remindedAt: new Date(now) } });
if (!claimed.count) continue;
const ev = s.role.event;
const place = ev.location ? ` at ${ev.location}` : '';
await tell(s.user, {
subject: `Reminder: serving ${s.role.name} — ${ev.title}`,
heading: 'See you soon',
text: `A reminder that you're serving: ${placeText(s.role, ev)}${place}. When you arrive, scan the volunteer check-in QR code with your phone. Can't make it? Ask for cover in My account → Serving (${servingUrl()}).`,
});
sent += 1;
}
return { sent };
}
// ─── Privacy ──────────────────────────────────────────────────────────────────
/** For "Download my data". */
async function exportVolunteering(userId, db = prisma) {
const slots = await db.volunteerSlot.findMany({
where: { userId },
include: { role: { include: { session: true, event: { select: { title: true, startDate: true, endDate: true, sessions: true } } } } },
orderBy: { createdAt: 'asc' },
});
return slots.map(s => {
const shift = shiftOf(s.role, s.role.event);
return { event: s.role.event.title, role: s.role.name, from: shift.startsAt, to: shift.endsAt, signedUp: s.createdAt, assigned: !!s.assignedById, checkedIn: s.checkedInAt };
});
}
/**
* For anonymiseUser: shifts still to come are given up (open places, free tickets released);
* past ones stay for the hours-served totals, under the anonymised account. Swap notes go.
*/
async function forgetVolunteer(tx, userId, now = new Date()) {
const slots = await tx.volunteerSlot.findMany({ where: { userId, checkedInAt: null }, include: { role: { include: { session: true, event: { select: { startDate: true, endDate: true, sessions: true } } } } } });
let removed = 0;
for (const s of slots) {
if (shiftOf(s.role, s.role.event).endsAt <= new Date(now)) continue;
await tx.volunteerSwap.updateMany({ where: { slotId: s.id, status: 'open' }, data: { status: 'cancelled', resolvedAt: new Date(now) } });
await releasePlace(tx, s);
await tx.volunteerSlot.delete({ where: { id: s.id } });
removed += 1;
}
await tx.volunteerSwap.updateMany({ where: { OR: [{ fromUserId: userId }, { toUserId: userId }], note: { not: null } }, data: { note: null } });
return removed;
}
module.exports = {
QR_PREFIX, MAX_NEEDED, volunteerError,
shiftOf, overlaps, shiftHours, fillOf, checkInOpen, reminderDue, kidsOccasion, reservedOptionIds, publicOptions, shiftText,
loadEvent, roleView, roster, createRole, updateRole, deleteRole, getSettings, saveSettings, checkInQr,
givePlace, releasePlace, signUp, leave, requestSwap, cancelSwap, acceptSwap, openSwaps,
checkInWithQr, checkInManual, rosteredForRooms, mySlots, eventsWithRoles, hoursServed,
signedUpMessages, sendSwapRequest, sendSwapAccepted, sendLeft, sendRoleDeleted, runReminderJob,
exportVolunteering, forgetVolunteer,
};