/** * Kids check-in (1.45.0). Children are checked in at a staff desk, fully digitally: * * - Families (parent accounts, children, authorised adults) are kept between events. * - A check-in gives the family a pickup code for the occasion — a session, or the day on a * single-date event — shared by the children checked in together. The parent sees it on * their phone (My account → Kids) and gets it by WhatsApp/email; anyone with the code can * collect. The desk shows a "write on the sticker" panel instead of printing labels. * - Each child gets a free place on the event's kids option the first time (registration, * attendee, ticket under the parent), and every check-in writes a TicketUsage — so the * attendance register, reports and campus scoping treat them like any other attendee. * - Rooms are the groups of the event's "kids rooms" allocation set, with an age range, * capacity and a ratio (children per leader on duty). * * Allergies, medical and custody notes are encrypted and never put in messages. */ const crypto = require('crypto'); const { v4: uuidv4 } = require('uuid'); const prisma = require('../config/db'); const { encrypt, decrypt } = require('./encryption'); const sessionsUtil = require('./sessions'); // No 0/O or 1/I, so a code read out or copied onto a sticker can't be misread. const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const CODE_LENGTH = 4; const OFFLINE_CODES = 20; const MAX_TEXT = 1000; // What a pickup QR holds: the prefix and the code. const QR_PREFIX = 'KIDS-'; function kidsError(message, statusCode = 400, code = undefined) { return Object.assign(new Error(message), { statusCode, ...(code ? { code } : {}) }); } // ─── Pure helpers ───────────────────────────────────────────────────────────── function randomCode(length = CODE_LENGTH) { const bytes = crypto.randomBytes(length); let out = ''; for (let i = 0; i < length; i++) out += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length]; return out; } /** A typed or scanned code, cleaned up: "kids-k7p2" / " k7 p2 " → "K7P2"; null if it can't be one. */ function normaliseCode(raw) { let s = String(raw || '').trim().toUpperCase(); if (s.startsWith(QR_PREFIX)) s = s.slice(QR_PREFIX.length); s = s.replace(/[\s-]/g, ''); if (s.length !== CODE_LENGTH || [...s].some(c => !CODE_ALPHABET.includes(c))) return null; return s; } /** Age in whole years on `on` (null without a date of birth). */ function ageOn(dateOfBirth, on = new Date()) { if (!dateOfBirth) return null; const d = new Date(dateOfBirth), e = new Date(on); let age = e.getUTCFullYear() - d.getUTCFullYear(); if (e.getUTCMonth() < d.getUTCMonth() || (e.getUTCMonth() === d.getUTCMonth() && e.getUTCDate() < d.getUTCDate())) age -= 1; return age; } /** Whether a child of `age` fits a room's age range (no age or no range = fits). */ function fitsRoom(room, age) { if (age == null) return true; if (room.minAge != null && age < room.minAge) return false; if (room.maxAge != null && age > room.maxAge) return false; return true; } /** * The room to suggest for a child: rooms whose age range fits, not full, narrowest range * first (a 2–3 room beats a 0–12 room), then room order. `counts` = { roomId: children in }. * Returns null when nothing fits. */ function suggestRoom(rooms, age, counts = {}) { const span = r => (r.maxAge ?? 25) - (r.minAge ?? 0); const fits = rooms.filter(r => fitsRoom(r, age) && !(r.capacity && (counts[r.id] || 0) >= r.capacity)); if (!fits.length) return null; return [...fits].sort((a, b) => (age == null ? 0 : span(a) - span(b)) || (a.order || 0) - (b.order || 0))[0]; } /** * A room's state: children in, leaders on duty, how many leaders the ratio needs, and whether * it's full or over the ratio. */ function roomStatus(room, children, leaders) { const needed = room.ratio ? Math.ceil(children / room.ratio) : 0; return { children, leaders, leadersNeeded: needed, full: !!room.capacity && children >= room.capacity, overRatio: !!room.ratio && children > 0 && leaders * room.ratio < children, }; } /** The short alert copied onto a sticker: "ALLERGY: PEANUTS", "MEDICAL", or both; '' when none. */ function stickerAlert(allergies, medicalNotes) { const parts = []; const a = String(allergies || '').trim(); if (a) parts.push(`ALLERGY: ${a.toUpperCase().slice(0, 24)}${a.length > 24 ? '…' : ''}`); if (String(medicalNotes || '').trim()) parts.push('MEDICAL'); return parts.join(' · '); } /** * The occasion a check-in counts for: { occasion, sessionId }. On a multi-session event it's * today's session (or the one asked for, if it's open today); on a single-date event it's * today, while the event is on. Throws when check-in isn't open. */ function occasionFor(event, sessions, requestedSessionId = null, now = new Date()) { if (event.scheduleType === 'sessions') { const { session, error } = sessionsUtil.scanSession(event, sessions || [], requestedSessionId || null, now); if (!session) throw kidsError(error || 'No session is open for check-in today.'); return { occasion: session.id, sessionId: session.id }; } const today = sessionsUtil.dayKey(now); if (today < sessionsUtil.dayKey(event.startDate) || today > sessionsUtil.dayKey(event.endDate)) { throw kidsError(`Check-in for this event is open on ${sessionsUtil.dayKey(event.startDate)}${sessionsUtil.dayKey(event.endDate) !== sessionsUtil.dayKey(event.startDate) ? ` to ${sessionsUtil.dayKey(event.endDate)}` : ''}.`); } return { occasion: today, sessionId: null }; } const seal = v => { const s = String(v ?? '').trim().slice(0, MAX_TEXT); return s ? encrypt(s) : null; }; const open = v => (v ? decrypt(v) || '' : ''); function childName(c) { return [c.firstName, c.lastName].filter(Boolean).join(' '); } /** A child for the API. `notes` adds medical and custody notes (staff and the child's parents). */ function childView(c, { on = new Date(), notes = true } = {}) { const allergies = open(c.allergies); const medicalNotes = open(c.medicalNotes); return { id: c.id, firstName: c.firstName, lastName: c.lastName || '', name: childName(c), dateOfBirth: c.dateOfBirth, age: ageOn(c.dateOfBirth, on), gender: c.gender || null, allergies, hasMedical: !!medicalNotes, hasCustody: !!c.custodyNotes, ...(notes ? { medicalNotes, custodyNotes: open(c.custodyNotes) } : {}), lastCheckInAt: c.lastCheckInAt || null, }; } // ─── Families ───────────────────────────────────────────────────────────────── const FAMILY_INCLUDE = { members: { orderBy: { createdAt: 'asc' }, include: { user: { select: { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true } } } }, children: { orderBy: [{ dateOfBirth: 'asc' }, { firstName: 'asc' }] }, adults: { orderBy: { createdAt: 'asc' } }, }; const realEmail = e => (e && !/@(guest\.local|deleted\.invalid|deleted\.local)$/.test(e) ? e : null); function familyView(f, { notes = true, on = new Date() } = {}) { return { id: f.id, name: f.name, parents: f.members.map(m => ({ userId: m.user.id, name: m.user.name, phone: m.user.phoneNumber || null, email: realEmail(m.user.email) })), children: f.children.map(c => childView(c, { notes, on })), adults: f.adults.map(a => ({ id: a.id, name: a.name, phone: a.phone || null, relationship: a.relationship || null })), }; } async function loadFamily(id, db = prisma) { const f = await db.family.findUnique({ where: { id: String(id || '') }, include: FAMILY_INCLUDE }); if (!f) throw kidsError('Family not found', 404); return f; } /** The signed-in person's family, or null. */ async function familyOfUser(userId, db = prisma) { const m = await db.familyMember.findUnique({ where: { userId }, select: { familyId: true } }); return m ? db.family.findUnique({ where: { id: m.familyId }, include: FAMILY_INCLUDE }) : null; } /** Create a family with `userId` as its first parent (a person is in one family at most). */ async function createFamily({ name, userId }, db = prisma) { if (await db.familyMember.findUnique({ where: { userId } })) throw kidsError('This person is already a parent in a family.', 409); const clean = String(name || '').trim().slice(0, 100); if (!clean) throw kidsError('Enter a name for the family (e.g. "The Smith family").'); const f = await db.family.create({ data: { name: clean, qrToken: crypto.randomBytes(16).toString('hex'), members: { create: { userId } } } }); return loadFamily(f.id, db); } function cleanChild(input, existing = null) { const data = {}; const b = input || {}; if (b.firstName !== undefined || !existing) { const first = String(b.firstName || '').trim().slice(0, 60); if (!first) throw kidsError('Enter the child\'s first name.'); data.firstName = first; } if (b.lastName !== undefined) data.lastName = String(b.lastName || '').trim().slice(0, 60) || null; if (b.dateOfBirth !== undefined) { if (!b.dateOfBirth) data.dateOfBirth = null; else { const d = new Date(b.dateOfBirth); if (Number.isNaN(d.getTime()) || d > new Date() || ageOn(d) > 25) throw kidsError('Enter a valid date of birth.'); data.dateOfBirth = d; } } if (b.gender !== undefined) data.gender = ['male', 'female'].includes(b.gender) ? b.gender : null; if (b.allergies !== undefined) data.allergies = seal(b.allergies); if (b.medicalNotes !== undefined) data.medicalNotes = seal(b.medicalNotes); if (b.custodyNotes !== undefined) data.custodyNotes = seal(b.custodyNotes); return data; } function cleanAdult(input) { const name = String(input?.name || '').trim().slice(0, 100); if (!name) throw kidsError('Enter the adult\'s name.'); const { normalizeZAPhone } = require('./whatsapp'); const rawPhone = String(input?.phone || '').trim(); const phone = rawPhone ? (normalizeZAPhone(rawPhone) || rawPhone.replace(/[^\d+]/g, '')).slice(0, 20) : null; return { name, phone, relationship: String(input?.relationship || '').trim().slice(0, 60) || null }; } /** Whether custody notes change between the stored child and the cleaned update. */ function custodyChanged(existing, data) { return data.custodyNotes !== undefined && open(existing?.custodyNotes) !== open(data.custodyNotes); } /** * Families matching a search: family name, a child's name, a parent's name, email or phone. * Children's names and allergies are encrypted only in part (allergies), so names search fine. */ async function searchFamilies(q, db = prisma, { limit = 20 } = {}) { const term = String(q || '').trim(); if (term.length < 2) return []; const digits = term.replace(/\D/g, ''); const phoneTerms = digits.length >= 6 ? [digits, digits.startsWith('0') ? '27' + digits.slice(1) : null, digits.startsWith('27') ? '0' + digits.slice(2) : null].filter(Boolean) : []; const ci = { contains: term, mode: 'insensitive' }; const rows = await db.family.findMany({ where: { OR: [ { name: ci }, { children: { some: { OR: [{ firstName: ci }, { lastName: ci }] } } }, { members: { some: { user: { OR: [{ name: ci }, { email: ci }, ...phoneTerms.map(p => ({ phoneNumber: { contains: p } }))] } } } }, ...phoneTerms.map(p => ({ adults: { some: { phone: { contains: p } } } })), ], }, include: FAMILY_INCLUDE, orderBy: { name: 'asc' }, take: limit, }); return rows; } // ─── Events ─────────────────────────────────────────────────────────────────── async function loadKidsEvent(eventId, db = prisma) { const event = await db.event.findUnique({ where: { id: String(eventId || '') }, include: { sessions: { orderBy: { startsAt: 'asc' } } } }); if (!event) throw kidsError('Event not found', 404); if (!event.kidsCheckIn || !event.kidsOptionId || !event.kidsRoomSetId) throw kidsError('Kids check-in isn\'t set up for this event.', 400, 'KIDS_NOT_SET_UP'); return event; } async function roomsFor(event, db = prisma) { return db.allocationGroup.findMany({ where: { setId: event.kidsRoomSetId }, orderBy: { order: 'asc' } }); } /** * The event's kids settings, with what the supervisor can choose from: main-ticket options * that cover the whole event, and allocation sets. */ async function getSettings(eventId, db = prisma) { const event = await db.event.findUnique({ where: { id: String(eventId || '') }, select: { id: true, title: true, scheduleType: true, kidsCheckIn: true, kidsOptionId: true, kidsRoomSetId: true }, }); if (!event) throw kidsError('Event not found', 404); const [options, sets] = await Promise.all([ db.eventOption.findMany({ where: { eventId: event.id, isMainTicket: true, sessionMode: 'all' }, select: { id: true, name: true, price: true }, orderBy: { name: 'asc' } }), db.allocationSet.findMany({ where: { eventId: event.id }, select: { id: true, name: true, groups: { orderBy: { order: 'asc' }, select: { id: true, name: true, capacity: true, minAge: true, maxAge: true, ratio: true, order: true } } }, orderBy: { order: 'asc' } }), ]); return { event, options, sets }; } /** * Save an event's kids settings. `optionId: 'new'` adds a free "Kids check-in" main ticket; * `roomSetId: 'new'` adds a "Kids rooms" set. Switching on needs both. */ async function saveSettings(eventId, { enabled, optionId, roomSetId }, db = prisma) { const { event } = await getSettings(eventId, db); const data = {}; if (optionId !== undefined) { if (optionId === 'new') { const opt = await db.eventOption.create({ data: { eventId: event.id, name: 'Kids check-in', price: 0, isMainTicket: true, sessionMode: 'all' } }); data.kidsOptionId = opt.id; } else if (optionId) { const opt = await db.eventOption.findFirst({ where: { id: String(optionId), eventId: event.id, isMainTicket: true, sessionMode: 'all' } }); if (!opt) throw kidsError('Choose a main ticket of this event that covers the whole event.'); data.kidsOptionId = opt.id; } else data.kidsOptionId = null; } if (roomSetId !== undefined) { if (roomSetId === 'new') { const order = await db.allocationSet.count({ where: { eventId: event.id } }); const set = await db.allocationSet.create({ data: { eventId: event.id, name: 'Kids rooms', order } }); data.kidsRoomSetId = set.id; } else if (roomSetId) { const set = await db.allocationSet.findFirst({ where: { id: String(roomSetId), eventId: event.id } }); if (!set) throw kidsError('Choose one of this event\'s allocation sets.'); data.kidsRoomSetId = set.id; } else data.kidsRoomSetId = null; } if (enabled !== undefined) data.kidsCheckIn = !!enabled; const next = { ...event, ...data }; if (next.kidsCheckIn && (!next.kidsOptionId || !next.kidsRoomSetId)) throw kidsError('Choose the kids ticket and the rooms before switching kids check-in on.'); await db.event.update({ where: { id: event.id }, data }); return getSettings(event.id, db); } // ─── Codes ──────────────────────────────────────────────────────────────────── const isUniqueClash = e => e?.code === 'P2002'; /** The family's pickup code for the occasion, made if it has none yet. */ async function codeForFamily(eventId, occasion, familyId, db = prisma) { for (let i = 0; i < 30; i++) { const existing = await db.kidsPickupCode.findUnique({ where: { eventId_occasion_familyId: { eventId, occasion, familyId } } }); if (existing) return existing; try { return await db.kidsPickupCode.create({ data: { eventId, occasion, familyId, code: randomCode() } }); } catch (e) { if (!isUniqueClash(e)) throw e; // Either the code is taken (try another) or the family got one meanwhile (found above). } } throw kidsError('Could not make a pickup code — try again.', 503); } /** Codes held for an offline desk: tops its unused ones up to `count`. */ async function reserveCodes(eventId, occasion, deviceId, count = OFFLINE_CODES, db = prisma) { const have = await db.kidsPickupCode.findMany({ where: { eventId, occasion, deviceId, familyId: null }, select: { code: true } }); let need = Math.max(0, count - have.length); for (let tries = 0; need > 0 && tries < count * 5; tries++) { try { await db.kidsPickupCode.create({ data: { eventId, occasion, deviceId, code: randomCode() } }); need--; } catch (e) { if (!isUniqueClash(e)) throw e; } } const rows = await db.kidsPickupCode.findMany({ where: { eventId, occasion, deviceId, familyId: null }, select: { code: true }, orderBy: { createdAt: 'asc' } }); return rows.map(r => r.code); } // ─── Attendance ─────────────────────────────────────────────────────────────── /** * The child's ticket for the event: the one from an earlier check-in, or a new free place on * the kids option — on the parent's kids registration for this event (made the first time, * separate from any registration they paid for themselves). */ async function ticketForChild(tx, event, parentUserId, child) { const earlier = await tx.kidsCheckIn.findFirst({ where: { eventId: event.id, childId: child.id, ticketId: { not: null } }, select: { ticketId: true, attendeeId: true } }); if (earlier) { const ticket = await tx.ticket.findUnique({ where: { id: earlier.ticketId }, select: { id: true } }); if (ticket) return { ticketId: ticket.id, attendeeId: earlier.attendeeId }; } let registration = await tx.registration.findFirst({ where: { userId: parentUserId, eventId: event.id, status: { not: 'cancelled' }, registrationOptions: { some: { eventOptionId: event.kidsOptionId, sessionId: null } } }, include: { registrationOptions: { where: { eventOptionId: event.kidsOptionId, sessionId: null } } }, }); if (!registration) { registration = await tx.registration.create({ data: { userId: parentUserId, eventId: event.id, status: 'paid' }, include: { registrationOptions: true } }); } let line = registration.registrationOptions[0]; if (line) line = await tx.registrationOption.update({ where: { id: line.id }, data: { quantity: { increment: 1 } } }); else line = await tx.registrationOption.create({ data: { registrationId: registration.id, eventOptionId: event.kidsOptionId, quantity: 1, priceSnapshot: 0 } }); await tx.registrationOptionTranche.create({ data: { registrationOptionId: line.id, quantity: 1, priceSnapshot: 0 } }); const order = await tx.attendee.count({ where: { registrationId: registration.id } }); const parent = await tx.user.findUnique({ where: { id: parentUserId }, select: { name: true, email: true, phoneNumber: true } }); const attendee = await tx.attendee.create({ data: { registrationId: registration.id, registrationOptionId: line.id, eventOptionId: event.kidsOptionId, name: childName(child), dateOfBirth: child.dateOfBirth, gender: child.gender, parentName: parent?.name || null, parentEmail: realEmail(parent?.email), parentPhone: parent?.phoneNumber || null, order, }, }); const ticket = await tx.ticket.create({ data: { id: uuidv4(), qrCode: uuidv4(), registrationOptionId: line.id, userId: parentUserId, eventId: event.id, quantity: 1, attendeeId: attendee.id, emailSent: true }, }); return { ticketId: ticket.id, attendeeId: attendee.id }; } // ─── Check-in and check-out ─────────────────────────────────────────────────── /** * Check children of a family in. `children` = [{ childId, roomId? }] (room suggested from the * age when not given). Children already in for this occasion stay as they are (their room can * change); children checked out earlier today are checked in again. Offline syncs pass the * code row, `clientId`s and the time it happened. * Returns { code, family, checkIns, already }. */ async function checkIn({ eventId, sessionId = null, familyId, children, staffUserId, now = new Date(), occasionOverride = null, codeRow = null, offline = false }, db = prisma) { const event = await loadKidsEvent(eventId, db); const { occasion, sessionId: sid } = occasionOverride || occasionFor(event, event.sessions, sessionId, now); const family = await loadFamily(familyId, db); const parent = family.members[0]; if (!parent) throw kidsError('This family has no parent account — add a parent first.'); if (!Array.isArray(children) || !children.length) throw kidsError('Choose the children to check in.'); const rooms = await roomsFor(event, db); if (!rooms.length) throw kidsError('This event has no kids rooms yet — a supervisor adds them under Kids check-in → Setup.'); const counts = await roomCounts(event.id, occasion, db); const picks = children.map(p => { const child = family.children.find(c => c.id === p?.childId); if (!child) throw kidsError('That child isn\'t in this family.', 404); let room = p.roomId ? rooms.find(r => r.id === p.roomId) : null; if (p.roomId && !room) throw kidsError('That room isn\'t one of this event\'s kids rooms.'); if (!room) room = suggestRoom(rooms, ageOn(child.dateOfBirth, now), counts) || rooms[0]; counts[room.id] = (counts[room.id] || 0) + 1; return { child, room, clientId: p.clientId || null }; }); const code = codeRow || await codeForFamily(event.id, occasion, family.id, db); const at = new Date(now); const result = []; const already = []; await db.$transaction(async tx => { for (const { child, room, clientId } of picks) { const existing = await tx.kidsCheckIn.findUnique({ where: { eventId_occasion_childId: { eventId: event.id, occasion, childId: child.id } } }); if (existing && !existing.checkedOutAt) { if (existing.roomId !== room.id && !offline) await tx.kidsCheckIn.update({ where: { id: existing.id }, data: { roomId: room.id } }); already.push(existing.id); result.push(existing.id); continue; } if (existing) { await tx.kidsCheckIn.update({ where: { id: existing.id }, data: { roomId: room.id, pickupCodeId: code.id, checkedInAt: at, checkedInById: staffUserId, checkedOutAt: null, checkedOutById: null, collectedBy: null, overrideReason: null }, }); result.push(existing.id); continue; } const { ticketId, attendeeId } = await ticketForChild(tx, event, parent.userId, child); await tx.ticketUsage.create({ data: { ticketId, scannedById: staffUserId, scannedAt: at, sessionId: sid, offline, syncedAt: offline ? new Date() : null } }); if (event.scheduleType !== 'sessions') await tx.ticket.update({ where: { id: ticketId }, data: { isUsed: true } }); const row = await tx.kidsCheckIn.create({ data: { eventId: event.id, occasion, sessionId: sid, childId: child.id, childName: childName(child), roomId: room.id, pickupCodeId: code.id, attendeeId, ticketId, checkedInAt: at, checkedInById: staffUserId, clientId, offline, }, }); result.push(row.id); } await tx.child.updateMany({ where: { id: { in: picks.map(p => p.child.id) } }, data: { lastCheckInAt: at } }); }); const checkIns = await db.kidsCheckIn.findMany({ where: { id: { in: result } }, include: { room: { select: { id: true, name: true } }, child: true } }); return { event, occasion, sessionId: sid, code: code.code, family, checkIns, already }; } /** Children in per room for an occasion: { roomId: n }. */ async function roomCounts(eventId, occasion, db = prisma) { const rows = await db.kidsCheckIn.groupBy({ by: ['roomId'], where: { eventId, occasion, checkedOutAt: null }, _count: { _all: true } }); return Object.fromEntries(rows.filter(r => r.roomId).map(r => [r.roomId, r._count._all])); } /** * Check out with a pickup code. `checkInIds` limits it to some of the children on the code * (default all still in). A code that matches nothing raises a wrong-code alert for the room * and throws WRONG_CODE. */ async function checkOut({ eventId, sessionId = null, code: rawCode, checkInIds = null, collectedBy, roomId = null, staffUserId, now = new Date() }, db = prisma) { const event = await loadKidsEvent(eventId, db); const { occasion } = occasionFor(event, event.sessions, sessionId, now); const code = normaliseCode(rawCode); const row = code ? await db.kidsPickupCode.findUnique({ where: { eventId_occasion_code: { eventId: event.id, occasion, code } } }) : null; const open = row ? await db.kidsCheckIn.findMany({ where: { pickupCodeId: row.id, checkedOutAt: null, ...(checkInIds?.length ? { id: { in: checkInIds.map(String) } } : {}) } }) : []; if (!open.length) { const typed = String(rawCode || '').trim().slice(0, 20); const message = row ? `Code ${code} has no children still checked in.` : `Wrong pickup code entered: "${typed}".`; if (!row) await db.kidsAlert.create({ data: { eventId: event.id, occasion, kind: 'wrong_code', roomId: roomId || null, message, createdById: staffUserId } }); throw kidsError(row ? message : 'That pickup code doesn\'t match any child checked in. The room leader has been alerted.', 404, row ? 'NOTHING_TO_COLLECT' : 'WRONG_CODE'); } const who = String(collectedBy || '').trim().slice(0, 100) || null; await db.kidsCheckIn.updateMany({ where: { id: { in: open.map(c => c.id) } }, data: { checkedOutAt: new Date(now), checkedOutById: staffUserId, collectedBy: who } }); return { event, occasion, checkIns: await db.kidsCheckIn.findMany({ where: { id: { in: open.map(c => c.id) } }, include: { room: { select: { id: true, name: true } } } }) }; } /** Check one child out without the code (lost phone, etc.). The reason is required and logged. */ async function overrideCheckOut({ checkInId, reason, collectedBy, staffUserId, now = new Date() }, db = prisma) { const ci = await db.kidsCheckIn.findUnique({ where: { id: String(checkInId || '') } }); if (!ci) throw kidsError('Check-in not found', 404); if (ci.checkedOutAt) throw kidsError(`${ci.childName} has already been collected.`); const why = String(reason || '').trim().slice(0, 300); if (why.length < 5) throw kidsError('Give the reason for checking out without the code.'); const who = String(collectedBy || '').trim().slice(0, 100); if (!who) throw kidsError('Enter who collected the child.'); const updated = await db.kidsCheckIn.update({ where: { id: ci.id }, data: { checkedOutAt: new Date(now), checkedOutById: staffUserId, collectedBy: who, overrideReason: why } }); await db.kidsAlert.create({ data: { eventId: ci.eventId, occasion: ci.occasion, kind: 'override', roomId: ci.roomId, checkInId: ci.id, message: `${ci.childName} checked out without the code by ${who}: ${why}`, createdById: staffUserId, resolvedAt: new Date(now) } }); return updated; } // ─── Messages ───────────────────────────────────────────────────────────────── function listNames(names) { return names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`; } function frontendUrl() { return String(process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, ''); } /** The check-in message: who, where and the code. Never medical or custody details. */ // `forParent` adds where to find the QR code (authorised adults have no account to look in). function checkInMessage({ eventTitle, code, children, forParent = true }) { const names = children.map(c => c.name); const rooms = [...new Set(children.map(c => c.room).filter(Boolean))]; const how = forParent ? `Show this code — or the QR code in My account → Kids (${frontendUrl()}/dashboard/user/kids) —` : 'Show this code'; return `${listNames(names)} ${names.length === 1 ? 'is' : 'are'} checked in at ${eventTitle}${rooms.length ? ` (${rooms.join(', ')})` : ''}. Pickup code: ${code}. ${how} to collect ${names.length === 1 ? 'them' : 'them all'}.`; } /** Send a text to a parent the way they like it (WhatsApp, email, or whichever works). */ async function messageParent(user, { subject, heading, text }) { const { canWhatsApp, shouldEmail, waTextAny } = require('./notify'); const email = realEmail(user.email); const sent = []; if (canWhatsApp(user) || (!email && user.phoneNumber)) { await waTextAny(user, text); sent.push('whatsapp'); } if (email && (shouldEmail(user) || !sent.length)) { const { sendMail, buildPrivacyEmail } = require('./email'); await sendMail({ to: email, subject, ...buildPrivacyEmail({ name: user.name, heading, paragraphs: [text] }) }).catch(() => {}); sent.push('email'); } return sent; } /** Tell the family's parents (and an authorised adult, if chosen) the code. Fire-and-forget. */ async function sendCheckInMessages({ event, family, code, checkIns, adultId = null }) { const children = checkIns.map(ci => ({ name: ci.child?.firstName || ci.childName, room: ci.room?.name || null })); const text = checkInMessage({ eventTitle: event.title, code, children }); for (const m of family.members) { await messageParent(m.user, { subject: `Pickup code ${code} — ${event.title}`, heading: `Pickup code ${code}`, text }).catch(() => {}); } const adult = adultId ? family.adults.find(a => a.id === adultId) : null; if (adult?.phone) { const { sendText } = require('./whatsapp'); await sendText(adult.phone, `${family.name}: ${checkInMessage({ eventTitle: event.title, code, children, forParent: false })}`).catch(() => {}); } } /** Page a parent: "Please come to the Toddlers room". Logged as an alert the parent sees too. */ async function pageParent({ checkInId, message, staffUserId }, db = prisma) { const ci = await db.kidsCheckIn.findUnique({ where: { id: String(checkInId || '') }, include: { room: true, event: { select: { title: true } }, pickupCode: { select: { familyId: true } } } }); if (!ci) throw kidsError('Check-in not found', 404); if (ci.checkedOutAt) throw kidsError(`${ci.childName} has already been collected.`); const family = ci.pickupCode.familyId ? await loadFamily(ci.pickupCode.familyId, db) : null; if (!family?.members.length) throw kidsError('There\'s no parent to contact for this child.'); const extra = String(message || '').trim().slice(0, 300); const first = ci.childName.split(' ')[0]; const text = `Please come to the ${ci.room?.name || 'kids'} room for ${first} (${ci.event.title}).${extra ? ` ${extra}` : ''}`; const channels = new Set(); for (const m of family.members) { for (const c of await messageParent(m.user, { subject: `Please come to the ${ci.room?.name || 'kids'} room`, heading: `Please come to the ${ci.room?.name || 'kids'} room`, text }).catch(() => [])) channels.add(c); } await db.kidsAlert.create({ data: { eventId: ci.eventId, occasion: ci.occasion, kind: 'page_parent', roomId: ci.roomId, checkInId: ci.id, message: text, createdById: staffUserId } }); return { sent: [...channels], text }; } // ─── Boards ─────────────────────────────────────────────────────────────────── /** * Everything the desk and room screens show for an occasion: rooms with counts and leaders on * duty, the children checked in (with allergies, medical and custody notes), open alerts. */ async function board({ eventId, sessionId = null, now = new Date() }, db = prisma) { const event = await loadKidsEvent(eventId, db); const { occasion, sessionId: sid } = occasionFor(event, event.sessions, sessionId, now); const [rooms, checkIns, duties, alerts] = await Promise.all([ roomsFor(event, db), db.kidsCheckIn.findMany({ where: { eventId: event.id, occasion }, include: { child: true, pickupCode: { select: { code: true, familyId: true } }, checkedInBy: { select: { name: true } }, checkedOutBy: { select: { name: true } }, }, orderBy: { checkedInAt: 'asc' }, }), db.kidsRoomDuty.findMany({ where: { occasion, endedAt: null, room: { setId: event.kidsRoomSetId } }, include: { user: { select: { id: true, name: true } } } }), db.kidsAlert.findMany({ where: { eventId: event.id, occasion }, orderBy: { createdAt: 'desc' }, take: 50, include: { createdBy: { select: { name: true } } } }), ]); const familyIds = [...new Set(checkIns.map(c => c.pickupCode.familyId).filter(Boolean))]; const families = familyIds.length ? await db.family.findMany({ where: { id: { in: familyIds } }, include: FAMILY_INCLUDE }) : []; const famById = Object.fromEntries(families.map(f => [f.id, f])); const inByRoom = {}; for (const c of checkIns) if (!c.checkedOutAt && c.roomId) inByRoom[c.roomId] = (inByRoom[c.roomId] || 0) + 1; const sessionLabel = sid ? sessionsUtil.sessionLabel(event.sessions.find(s => s.id === sid), event.sessions) : null; return { event: { id: event.id, title: event.title, scheduleType: event.scheduleType }, occasion, sessionId: sid, sessionLabel, rooms: rooms.map(r => { const leaders = duties.filter(d => d.roomId === r.id).map(d => d.user); return { id: r.id, name: r.name, minAge: r.minAge, maxAge: r.maxAge, capacity: r.capacity, ratio: r.ratio, order: r.order, leaderNames: leaders.map(l => l.name), leaderIds: leaders.map(l => l.id), ...roomStatus(r, inByRoom[r.id] || 0, leaders.length) }; }), checkIns: checkIns.map(c => { const fam = famById[c.pickupCode.familyId]; const child = c.child ? childView(c.child, { on: now }) : null; return { id: c.id, childId: c.childId, name: c.childName, firstName: child?.firstName || c.childName.split(' ')[0], age: child?.age ?? null, roomId: c.roomId, code: c.pickupCode.code, checkedInAt: c.checkedInAt, checkedInBy: c.checkedInBy?.name || null, checkedOutAt: c.checkedOutAt, checkedOutBy: c.checkedOutBy?.name || null, collectedBy: c.collectedBy, override: !!c.overrideReason, offline: c.offline, allergies: child?.allergies || '', medicalNotes: child?.medicalNotes || '', custodyNotes: child?.custodyNotes || '', sticker: stickerAlert(child?.allergies, child?.medicalNotes), family: fam ? { id: fam.id, name: fam.name, parents: familyView(fam, { notes: false }).parents, adults: familyView(fam, { notes: false }).adults } : null, }; }), alerts: alerts.map(a => ({ id: a.id, kind: a.kind, roomId: a.roomId, checkInId: a.checkInId, message: a.message, by: a.createdBy?.name || null, at: a.createdAt, resolvedAt: a.resolvedAt })), }; } /** "I'm on duty" / "I'm off" in a room for the occasion. */ async function setDuty({ eventId, sessionId = null, roomId, userId, on, now = new Date() }, db = prisma) { const event = await loadKidsEvent(eventId, db); const { occasion } = occasionFor(event, event.sessions, sessionId, now); const room = await db.allocationGroup.findFirst({ where: { id: String(roomId || ''), setId: event.kidsRoomSetId } }); if (!room) throw kidsError('That room isn\'t one of this event\'s kids rooms.', 404); // One room at a time: going on duty somewhere ends duty elsewhere for this occasion. await db.kidsRoomDuty.updateMany({ where: { userId, occasion, endedAt: null, ...(on ? {} : { roomId: room.id }) }, data: { endedAt: new Date(now) } }); if (on) await db.kidsRoomDuty.create({ data: { roomId: room.id, occasion, userId } }); return { roomId: room.id, on: !!on }; } /** Move a child to another room. */ async function moveRoom({ checkInId, roomId }, db = prisma) { const ci = await db.kidsCheckIn.findUnique({ where: { id: String(checkInId || '') }, include: { event: { select: { kidsRoomSetId: true } } } }); if (!ci) throw kidsError('Check-in not found', 404); const room = await db.allocationGroup.findFirst({ where: { id: String(roomId || ''), setId: ci.event.kidsRoomSetId } }); if (!room) throw kidsError('That room isn\'t one of this event\'s kids rooms.', 404); return db.kidsCheckIn.update({ where: { id: ci.id }, data: { roomId: room.id } }); } // ─── The parent's view ──────────────────────────────────────────────────────── /** The parent's live codes: children checked in now (not collected), grouped by code, plus pages from today. */ async function activeForFamily(familyId, now = new Date(), db = prisma) { const since = new Date(now.getTime() - 24 * 60 * 60 * 1000); const checkIns = await db.kidsCheckIn.findMany({ where: { pickupCode: { familyId }, checkedOutAt: null, checkedInAt: { gte: since } }, include: { pickupCode: { select: { code: true } }, room: { select: { name: true } }, event: { select: { id: true, title: true } } }, orderBy: { checkedInAt: 'asc' }, }); const byCode = new Map(); for (const c of checkIns) { const key = `${c.eventId}:${c.pickupCode.code}`; if (!byCode.has(key)) byCode.set(key, { code: c.pickupCode.code, qr: QR_PREFIX + c.pickupCode.code, event: c.event, children: [] }); byCode.get(key).children.push({ name: c.childName, room: c.room?.name || null, checkedInAt: c.checkedInAt }); } const pages = checkIns.length ? await db.kidsAlert.findMany({ where: { kind: 'page_parent', checkInId: { in: checkIns.map(c => c.id) }, createdAt: { gte: since } }, orderBy: { createdAt: 'desc' }, select: { id: true, message: true, createdAt: true }, }) : []; return { codes: [...byCode.values()], pages }; } // ─── Offline desks ──────────────────────────────────────────────────────────── /** * What a desk downloads to keep checking in without a connection: the families (with * children), the rooms, who is already in, and codes reserved for this device. */ async function offlineSnapshot({ eventId, sessionId = null, deviceId, now = new Date() }, db = prisma) { const dev = String(deviceId || '').trim().slice(0, 64); if (!dev) throw kidsError('deviceId is required'); const b = await board({ eventId, sessionId, now }, db); const event = await loadKidsEvent(eventId, db); const families = await db.family.findMany({ where: { children: { some: {} }, members: { some: {} } }, include: FAMILY_INCLUDE, orderBy: { name: 'asc' }, take: 3000 }); const codes = await reserveCodes(event.id, b.occasion, dev, OFFLINE_CODES, db); return { occasion: b.occasion, sessionId: b.sessionId, sessionLabel: b.sessionLabel, event: b.event, rooms: b.rooms, checkIns: b.checkIns, families: families.map(f => familyView(f, { on: now })), codes, downloadedAt: new Date(now).toISOString(), }; } /** * Sync an offline desk. `checkIns` = [{ clientId, familyId, childId, roomId, code, at }] made * with the device's reserved codes; `checkOuts` = [{ clientId, collectedBy, at }] for children * checked in on this device. Idempotent (clientId). Returns { checkedIn, checkedOut, conflicts }. */ async function syncOffline({ eventId, deviceId, occasion, sessionId = null, checkIns = [], checkOuts = [], staffUserId }, db = prisma) { const event = await loadKidsEvent(eventId, db); const dev = String(deviceId || '').trim().slice(0, 64); const occ = String(occasion || ''); const validOccasion = event.scheduleType === 'sessions' ? event.sessions.some(s => s.id === occ) : /^\d{4}-\d{2}-\d{2}$/.test(occ); if (!dev || !validOccasion) throw kidsError('This offline list isn\'t for this event.'); const sid = event.scheduleType === 'sessions' ? occ : null; const out = { checkedIn: 0, checkedOut: 0, conflicts: [] }; for (const item of (Array.isArray(checkIns) ? checkIns : []).slice(0, 500)) { const clientId = String(item?.clientId || '').slice(0, 64); if (!clientId) continue; if (await db.kidsCheckIn.findUnique({ where: { clientId } })) continue; const at = item.at && !Number.isNaN(new Date(item.at).getTime()) ? new Date(item.at) : new Date(); try { const code = normaliseCode(item.code); let row = code ? await db.kidsPickupCode.findUnique({ where: { eventId_occasion_code: { eventId: event.id, occasion: occ, code } } }) : null; if (!row || (row.deviceId !== dev && row.familyId !== item.familyId)) throw kidsError(`Code ${item.code} wasn't reserved for this device.`); if (!row.familyId) { const theirs = await db.kidsPickupCode.findUnique({ where: { eventId_occasion_familyId: { eventId: event.id, occasion: occ, familyId: String(item.familyId || '') } } }); if (theirs) { out.conflicts.push({ clientId, message: `This family already had code ${theirs.code} from another desk — tell the parent their code is ${theirs.code}, not ${code}.` }); row = theirs; } else { row = await db.kidsPickupCode.update({ where: { id: row.id }, data: { familyId: String(item.familyId || '') } }); } } await checkIn({ eventId: event.id, familyId: item.familyId, children: [{ childId: item.childId, roomId: item.roomId, clientId }], staffUserId, now: at, occasionOverride: { occasion: occ, sessionId: sid }, codeRow: row, offline: true, }, db); out.checkedIn++; } catch (e) { out.conflicts.push({ clientId, message: e.message || 'Could not sync this check-in.' }); } } for (const item of (Array.isArray(checkOuts) ? checkOuts : []).slice(0, 500)) { const ci = item?.clientId ? await db.kidsCheckIn.findUnique({ where: { clientId: String(item.clientId) } }) : null; if (!ci) { out.conflicts.push({ clientId: item?.clientId || null, message: 'A check-out was for a check-in that never synced.' }); continue; } if (ci.checkedOutAt) continue; const at = item.at && !Number.isNaN(new Date(item.at).getTime()) ? new Date(item.at) : new Date(); await db.kidsCheckIn.update({ where: { id: ci.id }, data: { checkedOutAt: at, checkedOutById: staffUserId, collectedBy: String(item.collectedBy || '').trim().slice(0, 100) || null } }); out.checkedOut++; } return out; } // ─── Privacy ────────────────────────────────────────────────────────────────── /** For anonymiseUser: leave the family; a family nobody is left in is deleted with its children. */ async function removeFromFamily(tx, userId) { const m = await tx.familyMember.findUnique({ where: { userId } }); if (!m) return { familyDeleted: false }; await tx.familyMember.delete({ where: { id: m.id } }); const left = await tx.familyMember.count({ where: { familyId: m.familyId } }); if (left) return { familyDeleted: false }; await deleteFamilyData(tx, m.familyId); return { familyDeleted: true }; } /** Delete a family and its children; check-ins keep the attendance but lose who collected. */ async function deleteFamilyData(tx, familyId) { await tx.kidsCheckIn.updateMany({ where: { pickupCode: { familyId } }, data: { collectedBy: null, overrideReason: null } }); await tx.family.delete({ where: { id: familyId } }); } /** For "Download my data". */ async function exportFamily(userId, db = prisma) { const f = await familyOfUser(userId, db); if (!f) return null; const checkIns = await db.kidsCheckIn.findMany({ where: { pickupCode: { familyId: f.id } }, include: { event: { select: { title: true } }, room: { select: { name: true } } }, orderBy: { checkedInAt: 'asc' }, }); const v = familyView(f); return { name: v.name, parents: v.parents.map(p => p.name), children: v.children.map(c => ({ name: c.name, dateOfBirth: c.dateOfBirth, gender: c.gender, allergies: c.allergies, medicalNotes: c.medicalNotes, custodyNotes: c.custodyNotes })), authorisedAdults: v.adults, checkIns: checkIns.map(c => ({ child: c.childName, event: c.event?.title, room: c.room?.name || null, in: c.checkedInAt, out: c.checkedOutAt, collectedBy: c.collectedBy })), }; } /** * Retention: children not checked in (or added) for `months` are deleted, then families left * with no children. Who collected children (and override reasons) is cleared from check-ins as * old; alerts that old are deleted. */ async function runKidsRetention(cutoff, db = prisma) { const children = await db.child.deleteMany({ where: { OR: [{ lastCheckInAt: { lt: cutoff } }, { lastCheckInAt: null, createdAt: { lt: cutoff } }] }, }); const emptyFamilies = await db.family.findMany({ where: { children: { none: {} }, updatedAt: { lt: cutoff } }, select: { id: true } }); for (const f of emptyFamilies) await db.$transaction(tx => deleteFamilyData(tx, f.id)); const scrubbed = await db.kidsCheckIn.updateMany({ where: { checkedInAt: { lt: cutoff }, OR: [{ collectedBy: { not: null } }, { overrideReason: { not: null } }] }, data: { collectedBy: null, overrideReason: null } }); const alerts = await db.kidsAlert.deleteMany({ where: { createdAt: { lt: cutoff } } }); const duties = await db.kidsRoomDuty.deleteMany({ where: { startedAt: { lt: cutoff } } }); return { children: children.count, families: emptyFamilies.length, checkIns: scrubbed.count, alerts: alerts.count + duties.count }; } async function previewKidsRetention(cutoff, db = prisma) { return { count: await db.child.count({ where: { OR: [{ lastCheckInAt: { lt: cutoff } }, { lastCheckInAt: null, createdAt: { lt: cutoff } }] } }), }; } module.exports = { CODE_ALPHABET, CODE_LENGTH, QR_PREFIX, kidsError, randomCode, normaliseCode, ageOn, fitsRoom, suggestRoom, roomStatus, stickerAlert, occasionFor, checkInMessage, listNames, childView, familyView, loadFamily, familyOfUser, createFamily, cleanChild, cleanAdult, custodyChanged, searchFamilies, loadKidsEvent, roomsFor, getSettings, saveSettings, codeForFamily, reserveCodes, checkIn, checkOut, overrideCheckOut, sendCheckInMessages, pageParent, board, setDuty, moveRoom, activeForFamily, offlineSnapshot, syncOffline, removeFromFamily, exportFamily, runKidsRetention, previewKidsRetention, };