Kids check-in: families, pickup codes, rooms, check-in/out, offline sync (backend)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,250 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "KidsAlertKind" AS ENUM ('wrong_code', 'page_parent', 'override');
|
||||
|
||||
-- AlterEnum
|
||||
-- This migration adds more than one value to an enum.
|
||||
-- With PostgreSQL versions 11 and earlier, this is not possible
|
||||
-- in a single migration. This can be worked around by creating
|
||||
-- multiple migrations, each migration adding only one value to
|
||||
-- the enum.
|
||||
|
||||
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'kids_settings_updated';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'kids_checkout_override';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'kids_wrong_code';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'kids_custody_notes_changed';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'kids_offline_sync';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "AllocationGroup" ADD COLUMN "maxAge" INTEGER,
|
||||
ADD COLUMN "minAge" INTEGER,
|
||||
ADD COLUMN "ratio" INTEGER;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Event" ADD COLUMN "kidsCheckIn" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "kidsOptionId" TEXT,
|
||||
ADD COLUMN "kidsRoomSetId" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Family" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"qrToken" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Family_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "FamilyMember" (
|
||||
"id" TEXT NOT NULL,
|
||||
"familyId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "FamilyMember_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Child" (
|
||||
"id" TEXT NOT NULL,
|
||||
"familyId" TEXT NOT NULL,
|
||||
"firstName" TEXT NOT NULL,
|
||||
"lastName" TEXT,
|
||||
"dateOfBirth" TIMESTAMP(3),
|
||||
"gender" TEXT,
|
||||
"allergies" TEXT,
|
||||
"medicalNotes" TEXT,
|
||||
"custodyNotes" TEXT,
|
||||
"lastCheckInAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Child_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AuthorisedAdult" (
|
||||
"id" TEXT NOT NULL,
|
||||
"familyId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"phone" TEXT,
|
||||
"relationship" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AuthorisedAdult_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "KidsPickupCode" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"occasion" TEXT NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"familyId" TEXT,
|
||||
"deviceId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "KidsPickupCode_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "KidsCheckIn" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"occasion" TEXT NOT NULL,
|
||||
"sessionId" TEXT,
|
||||
"childId" TEXT,
|
||||
"childName" TEXT NOT NULL,
|
||||
"roomId" TEXT,
|
||||
"pickupCodeId" TEXT NOT NULL,
|
||||
"attendeeId" TEXT,
|
||||
"ticketId" TEXT,
|
||||
"checkedInAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"checkedInById" TEXT,
|
||||
"checkedOutAt" TIMESTAMP(3),
|
||||
"checkedOutById" TEXT,
|
||||
"collectedBy" TEXT,
|
||||
"overrideReason" TEXT,
|
||||
"clientId" TEXT,
|
||||
"offline" BOOLEAN NOT NULL DEFAULT false,
|
||||
|
||||
CONSTRAINT "KidsCheckIn_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "KidsAlert" (
|
||||
"id" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"occasion" TEXT NOT NULL,
|
||||
"kind" "KidsAlertKind" NOT NULL,
|
||||
"roomId" TEXT,
|
||||
"checkInId" TEXT,
|
||||
"message" TEXT NOT NULL,
|
||||
"createdById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"resolvedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "KidsAlert_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "KidsRoomDuty" (
|
||||
"id" TEXT NOT NULL,
|
||||
"roomId" TEXT NOT NULL,
|
||||
"occasion" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"endedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "KidsRoomDuty_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Family_qrToken_key" ON "Family"("qrToken");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "FamilyMember_userId_key" ON "FamilyMember"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "FamilyMember_familyId_idx" ON "FamilyMember"("familyId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Child_familyId_idx" ON "Child"("familyId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Child_lastCheckInAt_idx" ON "Child"("lastCheckInAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AuthorisedAdult_familyId_idx" ON "AuthorisedAdult"("familyId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "KidsPickupCode_eventId_occasion_deviceId_idx" ON "KidsPickupCode"("eventId", "occasion", "deviceId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "KidsPickupCode_eventId_occasion_code_key" ON "KidsPickupCode"("eventId", "occasion", "code");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "KidsPickupCode_eventId_occasion_familyId_key" ON "KidsPickupCode"("eventId", "occasion", "familyId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "KidsCheckIn_clientId_key" ON "KidsCheckIn"("clientId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "KidsCheckIn_eventId_occasion_idx" ON "KidsCheckIn"("eventId", "occasion");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "KidsCheckIn_roomId_idx" ON "KidsCheckIn"("roomId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "KidsCheckIn_pickupCodeId_idx" ON "KidsCheckIn"("pickupCodeId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "KidsCheckIn_eventId_occasion_childId_key" ON "KidsCheckIn"("eventId", "occasion", "childId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "KidsAlert_eventId_occasion_createdAt_idx" ON "KidsAlert"("eventId", "occasion", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "KidsAlert_checkInId_idx" ON "KidsAlert"("checkInId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "KidsRoomDuty_roomId_occasion_idx" ON "KidsRoomDuty"("roomId", "occasion");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "KidsRoomDuty_userId_idx" ON "KidsRoomDuty"("userId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FamilyMember" ADD CONSTRAINT "FamilyMember_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "Family"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "FamilyMember" ADD CONSTRAINT "FamilyMember_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Child" ADD CONSTRAINT "Child_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "Family"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AuthorisedAdult" ADD CONSTRAINT "AuthorisedAdult_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "Family"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsPickupCode" ADD CONSTRAINT "KidsPickupCode_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsPickupCode" ADD CONSTRAINT "KidsPickupCode_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "Family"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsCheckIn" ADD CONSTRAINT "KidsCheckIn_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsCheckIn" ADD CONSTRAINT "KidsCheckIn_childId_fkey" FOREIGN KEY ("childId") REFERENCES "Child"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsCheckIn" ADD CONSTRAINT "KidsCheckIn_roomId_fkey" FOREIGN KEY ("roomId") REFERENCES "AllocationGroup"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsCheckIn" ADD CONSTRAINT "KidsCheckIn_pickupCodeId_fkey" FOREIGN KEY ("pickupCodeId") REFERENCES "KidsPickupCode"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsCheckIn" ADD CONSTRAINT "KidsCheckIn_checkedInById_fkey" FOREIGN KEY ("checkedInById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsCheckIn" ADD CONSTRAINT "KidsCheckIn_checkedOutById_fkey" FOREIGN KEY ("checkedOutById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsAlert" ADD CONSTRAINT "KidsAlert_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsAlert" ADD CONSTRAINT "KidsAlert_roomId_fkey" FOREIGN KEY ("roomId") REFERENCES "AllocationGroup"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsAlert" ADD CONSTRAINT "KidsAlert_checkInId_fkey" FOREIGN KEY ("checkInId") REFERENCES "KidsCheckIn"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsAlert" ADD CONSTRAINT "KidsAlert_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsRoomDuty" ADD CONSTRAINT "KidsRoomDuty_roomId_fkey" FOREIGN KEY ("roomId") REFERENCES "AllocationGroup"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "KidsRoomDuty" ADD CONSTRAINT "KidsRoomDuty_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -151,6 +151,13 @@ model User {
|
||||
// campuses are off (utils/campusScope.js).
|
||||
scopedCampuses Campus[] @relation("UserCampusScope")
|
||||
|
||||
// Kids check-in (1.45.0): the family this person is a parent in (at most one).
|
||||
familyMembership FamilyMember?
|
||||
kidsCheckInsDone KidsCheckIn[] @relation("KidsCheckInBy")
|
||||
kidsCheckOutsDone KidsCheckIn[] @relation("KidsCheckOutBy")
|
||||
kidsAlertsRaised KidsAlert[]
|
||||
kidsRoomDuties KidsRoomDuty[]
|
||||
|
||||
@@index([homeCampusId])
|
||||
}
|
||||
|
||||
@@ -286,6 +293,17 @@ model Event {
|
||||
sessions EventSession[]
|
||||
certificates Certificate[]
|
||||
|
||||
// Kids check-in (1.45.0): children are checked in at the kids desk instead of buying
|
||||
// tickets. Each child gets a free place on `kidsOptionId` (a main-ticket option of this
|
||||
// event) the first time, so they show on the attendance register; rooms are the groups of
|
||||
// the allocation set `kidsRoomSetId`. Plain ids (checked in utils/kids.js), not relations.
|
||||
kidsCheckIn Boolean @default(false)
|
||||
kidsOptionId String?
|
||||
kidsRoomSetId String?
|
||||
kidsPickupCodes KidsPickupCode[]
|
||||
kidsCheckIns KidsCheckIn[]
|
||||
kidsAlerts KidsAlert[]
|
||||
|
||||
@@index([createdById])
|
||||
@@index([closedById])
|
||||
@@index([reopenedById])
|
||||
@@ -655,6 +673,11 @@ enum AdminAuditAction {
|
||||
campus_deleted
|
||||
event_campus_changed
|
||||
user_campus_scope_changed
|
||||
kids_settings_updated
|
||||
kids_checkout_override
|
||||
kids_wrong_code
|
||||
kids_custody_notes_changed
|
||||
kids_offline_sync
|
||||
}
|
||||
|
||||
// Append-only audit trail for admin/supervisor-initiated actions with money or
|
||||
@@ -1328,11 +1351,19 @@ model AllocationGroup {
|
||||
gender String?
|
||||
leaderUserId String?
|
||||
order Int @default(0)
|
||||
// Kids rooms (1.45.0): the ages the room is for (whole years, inclusive) and how many
|
||||
// children one leader may look after. All optional.
|
||||
minAge Int?
|
||||
maxAge Int?
|
||||
ratio Int?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
set AllocationSet @relation(fields: [setId], references: [id], onDelete: Cascade)
|
||||
leader User? @relation("AllocationGroupLeader", fields: [leaderUserId], references: [id], onDelete: SetNull)
|
||||
assignments AllocationAssignment[]
|
||||
kidsCheckIns KidsCheckIn[]
|
||||
kidsAlerts KidsAlert[]
|
||||
kidsDuties KidsRoomDuty[]
|
||||
|
||||
@@index([setId])
|
||||
@@index([leaderUserId])
|
||||
@@ -1829,3 +1860,166 @@ model SecurityBreach {
|
||||
|
||||
@@index([status, discoveredAt])
|
||||
}
|
||||
|
||||
// ─── Kids check-in (1.45.0) ───────────────────────────────────────────────────
|
||||
|
||||
// A household whose children are checked in at the kids desk. Kept between events (weekly
|
||||
// kids church). `qrToken` is what the parent's family QR in My account → Kids holds.
|
||||
model Family {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
qrToken String @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
members FamilyMember[]
|
||||
children Child[]
|
||||
adults AuthorisedAdult[]
|
||||
codes KidsPickupCode[]
|
||||
}
|
||||
|
||||
// A parent account in a family. A person is a parent in one family at most.
|
||||
model FamilyMember {
|
||||
id String @id @default(uuid())
|
||||
familyId String
|
||||
userId String @unique
|
||||
createdAt DateTime @default(now())
|
||||
family Family @relation(fields: [familyId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([familyId])
|
||||
}
|
||||
|
||||
// A child in a family. allergies, medicalNotes and custodyNotes are encrypted
|
||||
// (utils/encryption.js). Deleted by the retention job after months without a check-in.
|
||||
model Child {
|
||||
id String @id @default(uuid())
|
||||
familyId String
|
||||
firstName String
|
||||
lastName String?
|
||||
dateOfBirth DateTime?
|
||||
gender String?
|
||||
allergies String?
|
||||
medicalNotes String?
|
||||
custodyNotes String?
|
||||
lastCheckInAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
family Family @relation(fields: [familyId], references: [id], onDelete: Cascade)
|
||||
checkIns KidsCheckIn[]
|
||||
|
||||
@@index([familyId])
|
||||
@@index([lastCheckInAt])
|
||||
}
|
||||
|
||||
// Someone the family allows to collect their children, who needn't have an account (a
|
||||
// grandparent, a friend). Anyone with the pickup code can collect; this list is what the
|
||||
// room leader checks the person against, and who the code can be sent to.
|
||||
model AuthorisedAdult {
|
||||
id String @id @default(uuid())
|
||||
familyId String
|
||||
name String
|
||||
phone String?
|
||||
relationship String?
|
||||
createdAt DateTime @default(now())
|
||||
family Family @relation(fields: [familyId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([familyId])
|
||||
}
|
||||
|
||||
// A pickup code: one per family per occasion (a session, or the day on a single-date event),
|
||||
// shared by the children checked in together. Codes for offline desks are reserved ahead with
|
||||
// `deviceId` and no family, and claimed when the desk syncs.
|
||||
model KidsPickupCode {
|
||||
id String @id @default(uuid())
|
||||
eventId String
|
||||
occasion String
|
||||
code String
|
||||
familyId String?
|
||||
deviceId String?
|
||||
createdAt DateTime @default(now())
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
||||
family Family? @relation(fields: [familyId], references: [id], onDelete: SetNull)
|
||||
checkIns KidsCheckIn[]
|
||||
|
||||
@@unique([eventId, occasion, code])
|
||||
@@unique([eventId, occasion, familyId])
|
||||
@@index([eventId, occasion, deviceId])
|
||||
}
|
||||
|
||||
// One child checked in to a room for an occasion. childId is cleared when the child's profile
|
||||
// is deleted; the attendance (attendee, ticket, ticket usage) stays.
|
||||
model KidsCheckIn {
|
||||
id String @id @default(uuid())
|
||||
eventId String
|
||||
occasion String
|
||||
sessionId String?
|
||||
childId String?
|
||||
childName String
|
||||
roomId String?
|
||||
pickupCodeId String
|
||||
attendeeId String?
|
||||
ticketId String?
|
||||
checkedInAt DateTime @default(now())
|
||||
checkedInById String?
|
||||
checkedOutAt DateTime?
|
||||
checkedOutById String?
|
||||
collectedBy String?
|
||||
overrideReason String?
|
||||
// Offline desks: the device's id for the check-in (makes syncing idempotent).
|
||||
clientId String? @unique
|
||||
offline Boolean @default(false)
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
||||
child Child? @relation(fields: [childId], references: [id], onDelete: SetNull)
|
||||
room AllocationGroup? @relation(fields: [roomId], references: [id], onDelete: SetNull)
|
||||
pickupCode KidsPickupCode @relation(fields: [pickupCodeId], references: [id], onDelete: Cascade)
|
||||
checkedInBy User? @relation("KidsCheckInBy", fields: [checkedInById], references: [id], onDelete: SetNull)
|
||||
checkedOutBy User? @relation("KidsCheckOutBy", fields: [checkedOutById], references: [id], onDelete: SetNull)
|
||||
alerts KidsAlert[]
|
||||
|
||||
@@unique([eventId, occasion, childId])
|
||||
@@index([eventId, occasion])
|
||||
@@index([roomId])
|
||||
@@index([pickupCodeId])
|
||||
}
|
||||
|
||||
enum KidsAlertKind {
|
||||
wrong_code
|
||||
page_parent
|
||||
override
|
||||
}
|
||||
|
||||
// Something the room needs to see: a wrong pickup code, a parent paged, an override.
|
||||
model KidsAlert {
|
||||
id String @id @default(uuid())
|
||||
eventId String
|
||||
occasion String
|
||||
kind KidsAlertKind
|
||||
roomId String?
|
||||
checkInId String?
|
||||
message String
|
||||
createdById String?
|
||||
createdAt DateTime @default(now())
|
||||
resolvedAt DateTime?
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
||||
room AllocationGroup? @relation(fields: [roomId], references: [id], onDelete: SetNull)
|
||||
checkIn KidsCheckIn? @relation(fields: [checkInId], references: [id], onDelete: SetNull)
|
||||
createdBy User? @relation(fields: [createdById], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([eventId, occasion, createdAt])
|
||||
@@index([checkInId])
|
||||
}
|
||||
|
||||
// A leader on duty in a kids room for an occasion ("I'm on duty"), for the ratio.
|
||||
model KidsRoomDuty {
|
||||
id String @id @default(uuid())
|
||||
roomId String
|
||||
occasion String
|
||||
userId String
|
||||
startedAt DateTime @default(now())
|
||||
endedAt DateTime?
|
||||
room AllocationGroup @relation(fields: [roomId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([roomId, occasion])
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
@@ -18,6 +18,13 @@ const cleanCapacity = (v) => {
|
||||
if (!Number.isFinite(n) || n < 1 || n > 10000) throw allocationError('Capacity must be a whole number of at least 1.');
|
||||
return n;
|
||||
};
|
||||
// Kids rooms: ages in whole years and children per leader. Blank = no limit.
|
||||
const cleanSmallInt = (v, what, min, max) => {
|
||||
if (v === undefined || v === null || v === '') return null;
|
||||
const n = parseInt(v, 10);
|
||||
if (!Number.isFinite(n) || n < min || n > max) throw allocationError(`${what} must be a whole number from ${min} to ${max}.`);
|
||||
return n;
|
||||
};
|
||||
|
||||
/** Named attendees on the event's live registrations. */
|
||||
async function eventAttendees(eventId) {
|
||||
@@ -110,8 +117,14 @@ const deleteSet = async (req, res) => {
|
||||
};
|
||||
|
||||
async function groupData(body, setId, existing = null) {
|
||||
const { name, capacity, gender, leaderUserId } = body || {};
|
||||
const { name, capacity, gender, leaderUserId, minAge, maxAge, ratio } = body || {};
|
||||
const data = {};
|
||||
if (minAge !== undefined) data.minAge = cleanSmallInt(minAge, 'The youngest age', 0, 25);
|
||||
if (maxAge !== undefined) data.maxAge = cleanSmallInt(maxAge, 'The oldest age', 0, 25);
|
||||
if (ratio !== undefined) data.ratio = cleanSmallInt(ratio, 'Children per leader', 1, 100);
|
||||
const lo = data.minAge !== undefined ? data.minAge : existing?.minAge;
|
||||
const hi = data.maxAge !== undefined ? data.maxAge : existing?.maxAge;
|
||||
if (lo != null && hi != null && lo > hi) throw allocationError("The youngest age can't be more than the oldest age.");
|
||||
if (name !== undefined || !existing) data.name = cleanName(name, 'group');
|
||||
if (capacity !== undefined) data.capacity = cleanCapacity(capacity);
|
||||
if (gender !== undefined) data.gender = cleanGender(gender);
|
||||
@@ -132,7 +145,7 @@ async function groupData(body, setId, existing = null) {
|
||||
return data;
|
||||
}
|
||||
|
||||
// @route POST /api/allocations/sets/:id/groups { name, capacity?, gender?, leaderUserId? }
|
||||
// @route POST /api/allocations/sets/:id/groups { name, capacity?, gender?, leaderUserId?, minAge?, maxAge?, ratio? }
|
||||
const createGroup = async (req, res) => {
|
||||
try {
|
||||
const set = await loadSet(req.params.id);
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
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 { findOrCreateAccount } = require('../utils/accountMatch');
|
||||
const { listWhere, withScope } = require('../utils/campusScope');
|
||||
const kids = require('../utils/kids');
|
||||
|
||||
const SUPERVISORS = ['admin', 'supervisor'];
|
||||
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) });
|
||||
|
||||
/** Child fields from a request; only supervisors, admins and the child's parents set custody notes. */
|
||||
function childInput(req, { parent = false } = {}) {
|
||||
const body = { ...(req.body || {}) };
|
||||
if (!parent && !SUPERVISORS.includes(req.user.role)) delete body.custodyNotes;
|
||||
return body;
|
||||
}
|
||||
|
||||
async function saveChild(req, familyId, childId, { parent }) {
|
||||
const existing = childId ? await prisma.child.findFirst({ where: { id: String(childId), familyId } }) : null;
|
||||
if (childId && !existing) throw kids.kidsError('Child not found', 404);
|
||||
const data = kids.cleanChild(childInput(req, { parent }), existing);
|
||||
const child = existing
|
||||
? await prisma.child.update({ where: { id: existing.id }, data })
|
||||
: await prisma.child.create({ data: { ...data, familyId } });
|
||||
if (kids.custodyChanged(existing, data)) audit(req, 'kids_custody_notes_changed', 'child', child.id, { familyId, by: parent ? 'parent' : 'staff' });
|
||||
return child;
|
||||
}
|
||||
|
||||
// ─── My account → Kids (parents) ──────────────────────────────────────────────
|
||||
|
||||
// @route GET /api/kids/me
|
||||
const getMine = async (req, res) => {
|
||||
try {
|
||||
const family = await kids.familyOfUser(req.user.id);
|
||||
if (!family) return res.json({ family: null, qrToken: null, codes: [], pages: [] });
|
||||
const active = await kids.activeForFamily(family.id);
|
||||
res.json({ family: kids.familyView(family), qrToken: family.qrToken, ...active });
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/me { name }
|
||||
const createMine = async (req, res) => {
|
||||
try {
|
||||
const family = await kids.createFamily({ name: req.body?.name || `${req.user.name || 'My'} family`, userId: req.user.id });
|
||||
res.status(201).json({ family: kids.familyView(family), qrToken: family.qrToken, codes: [], pages: [] });
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
async function myFamilyId(req) {
|
||||
const m = await prisma.familyMember.findUnique({ where: { userId: req.user.id } });
|
||||
if (!m) throw kids.kidsError('Add your family first.', 404);
|
||||
return m.familyId;
|
||||
}
|
||||
|
||||
// @route PUT /api/kids/me { name }
|
||||
const renameMine = async (req, res) => {
|
||||
try {
|
||||
const id = await myFamilyId(req);
|
||||
const name = String(req.body?.name || '').trim().slice(0, 100);
|
||||
if (!name) throw kids.kidsError('Enter a name for the family.');
|
||||
await prisma.family.update({ where: { id }, data: { name } });
|
||||
res.json(kids.familyView(await kids.loadFamily(id)));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/me/children, PUT /api/kids/me/children/:id
|
||||
const saveMyChild = async (req, res) => {
|
||||
try {
|
||||
const id = await myFamilyId(req);
|
||||
const child = await saveChild(req, id, req.params.id, { parent: true });
|
||||
res.status(req.params.id ? 200 : 201).json(kids.childView(child));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route DELETE /api/kids/me/children/:id
|
||||
const deleteMyChild = async (req, res) => {
|
||||
try {
|
||||
const id = await myFamilyId(req);
|
||||
const out = await prisma.child.deleteMany({ where: { id: String(req.params.id), familyId: id } });
|
||||
if (!out.count) throw kids.kidsError('Child not found', 404);
|
||||
res.json({ message: 'Deleted' });
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/me/adults, PUT /api/kids/me/adults/:id
|
||||
const saveMyAdult = async (req, res) => {
|
||||
try {
|
||||
const id = await myFamilyId(req);
|
||||
const data = kids.cleanAdult(req.body);
|
||||
if (req.params.id) {
|
||||
const out = await prisma.authorisedAdult.updateMany({ where: { id: String(req.params.id), familyId: id }, data });
|
||||
if (!out.count) throw kids.kidsError('Not found', 404);
|
||||
return res.json(await prisma.authorisedAdult.findUnique({ where: { id: String(req.params.id) } }));
|
||||
}
|
||||
if (await prisma.authorisedAdult.count({ where: { familyId: id } }) >= 10) throw kids.kidsError('A family can list up to 10 authorised adults.');
|
||||
res.status(201).json(await prisma.authorisedAdult.create({ data: { ...data, familyId: id } }));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route DELETE /api/kids/me/adults/:id
|
||||
const deleteMyAdult = async (req, res) => {
|
||||
try {
|
||||
const id = await myFamilyId(req);
|
||||
const out = await prisma.authorisedAdult.deleteMany({ where: { id: String(req.params.id), familyId: id } });
|
||||
if (!out.count) throw kids.kidsError('Not found', 404);
|
||||
res.json({ message: 'Deleted' });
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route DELETE /api/kids/me (leave the family; the last parent leaving deletes it)
|
||||
const leaveMine = async (req, res) => {
|
||||
try {
|
||||
await myFamilyId(req);
|
||||
const out = await prisma.$transaction(tx => kids.removeFromFamily(tx, req.user.id));
|
||||
res.json(out);
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── Staff: the desk and the rooms ────────────────────────────────────────────
|
||||
|
||||
// @desc Events with kids check-in that are on now or soon (and the last week's)
|
||||
// @route GET /api/kids/events
|
||||
const listEvents = async (req, res) => {
|
||||
try {
|
||||
const since = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
const events = await prisma.event.findMany({
|
||||
where: withScope({ kidsCheckIn: true, endDate: { gte: since } }, await listWhere(req)),
|
||||
select: {
|
||||
id: true, title: true, startDate: true, endDate: true, scheduleType: true, campusId: true,
|
||||
sessions: { where: { cancelledAt: null }, orderBy: { startsAt: 'asc' }, select: { id: true, label: true, startsAt: true, endsAt: true } },
|
||||
},
|
||||
orderBy: { startDate: 'asc' },
|
||||
take: 100,
|
||||
});
|
||||
res.json(events);
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route GET /api/kids/events/:eventId/board?sessionId=&log=1
|
||||
const getBoard = async (req, res) => {
|
||||
try {
|
||||
const data = await kids.board({ eventId: req.params.eventId, sessionId: req.query.sessionId || null });
|
||||
// Polling refreshes don't log; opening the screen does (it shows medical and custody notes).
|
||||
if (req.query.log === '1') {
|
||||
logDataAccess(req, { action: 'kids_rooms', eventId: data.event.id, records: data.checkIns.length, sensitive: true });
|
||||
}
|
||||
res.json(data);
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route GET /api/kids/events/:eventId/families?q=
|
||||
const searchFamilies = async (req, res) => {
|
||||
try {
|
||||
const rows = await kids.searchFamilies(req.query.q);
|
||||
res.json(rows.map(f => kids.familyView(f)));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route GET /api/kids/events/:eventId/families/qr/:token
|
||||
const familyByQr = async (req, res) => {
|
||||
try {
|
||||
const raw = String(req.params.token || '').trim().replace(/^FAMILY-/i, '');
|
||||
const f = await prisma.family.findUnique({ where: { qrToken: raw } });
|
||||
if (!f) throw kids.kidsError('That isn\'t a family QR code from this site.', 404);
|
||||
res.json(kids.familyView(await kids.loadFamily(f.id)));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route GET /api/kids/events/:eventId/families/:familyId
|
||||
const getFamily = async (req, res) => {
|
||||
try {
|
||||
res.json(kids.familyView(await kids.loadFamily(req.params.familyId)));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
/** A parent from the desk: their account (matched by email/phone, or a new inactive one). */
|
||||
async function parentAccount(input) {
|
||||
const name = String(input?.name || '').trim().slice(0, 100);
|
||||
if (!name) throw kids.kidsError('Enter the parent\'s name.');
|
||||
const email = String(input?.email || '').trim();
|
||||
const phone = String(input?.phone || '').trim();
|
||||
if (!email && !phone) throw kids.kidsError('Enter the parent\'s phone number or email address, so the pickup code can be sent to them.');
|
||||
const { user } = await findOrCreateAccount({ name, email, phone });
|
||||
return user;
|
||||
}
|
||||
|
||||
// @desc New family at the desk: a parent (found or created) and their children
|
||||
// @route POST /api/kids/events/:eventId/families { name, parent: { name, phone, email }, children: [...] }
|
||||
const createFamilyAtDesk = async (req, res) => {
|
||||
try {
|
||||
const user = await parentAccount(req.body?.parent);
|
||||
const existing = await kids.familyOfUser(user.id);
|
||||
// Don't tell the desk anything about an account beyond what they typed: if the person is
|
||||
// already in a family, that family is used (they're standing at the desk).
|
||||
const family = existing || await kids.createFamily({ name: req.body?.name || `${user.name.split(' ').slice(-1)[0]} family`, userId: user.id });
|
||||
for (const c of (Array.isArray(req.body?.children) ? req.body.children : []).slice(0, 12)) {
|
||||
await saveChild({ ...req, body: c }, family.id, null, { parent: false });
|
||||
}
|
||||
res.status(existing ? 200 : 201).json(kids.familyView(await kids.loadFamily(family.id)));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/events/:eventId/families/:familyId/parents { name, phone, email }
|
||||
const addParentAtDesk = async (req, res) => {
|
||||
try {
|
||||
const family = await kids.loadFamily(req.params.familyId);
|
||||
const user = await parentAccount(req.body);
|
||||
const m = await prisma.familyMember.findUnique({ where: { userId: user.id } });
|
||||
if (m && m.familyId !== family.id) throw kids.kidsError('This person is already a parent in another family.', 409);
|
||||
if (!m) await prisma.familyMember.create({ data: { familyId: family.id, userId: user.id } });
|
||||
res.json(kids.familyView(await kids.loadFamily(family.id)));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/events/:eventId/families/:familyId/children, PUT .../children/:id
|
||||
const saveChildAtDesk = async (req, res) => {
|
||||
try {
|
||||
const family = await kids.loadFamily(req.params.familyId);
|
||||
const child = await saveChild(req, family.id, req.params.childId, { parent: false });
|
||||
res.status(req.params.childId ? 200 : 201).json(kids.childView(child));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/events/:eventId/families/:familyId/adults { name, phone, relationship }
|
||||
const addAdultAtDesk = async (req, res) => {
|
||||
try {
|
||||
const family = await kids.loadFamily(req.params.familyId);
|
||||
if (family.adults.length >= 10) throw kids.kidsError('A family can list up to 10 authorised adults.');
|
||||
await prisma.authorisedAdult.create({ data: { ...kids.cleanAdult(req.body), familyId: family.id } });
|
||||
res.status(201).json(kids.familyView(await kids.loadFamily(family.id)));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/events/:eventId/check-in { familyId, sessionId?, children: [{ childId, roomId? }], sendToAdultId? }
|
||||
const checkIn = async (req, res) => {
|
||||
try {
|
||||
const out = await kids.checkIn({
|
||||
eventId: req.params.eventId, sessionId: req.body?.sessionId || null, familyId: req.body?.familyId,
|
||||
children: req.body?.children, staffUserId: req.user.id,
|
||||
});
|
||||
const fresh = out.checkIns.filter(c => !out.already.includes(c.id));
|
||||
if (fresh.length) kids.sendCheckInMessages({ event: out.event, family: out.family, code: out.code, checkIns: fresh, adultId: req.body?.sendToAdultId || null }).catch(() => {});
|
||||
res.status(201).json({
|
||||
code: out.code,
|
||||
qr: kids.QR_PREFIX + out.code,
|
||||
occasion: out.occasion,
|
||||
family: { id: out.family.id, name: out.family.name },
|
||||
checkIns: out.checkIns.map(c => {
|
||||
const child = c.child ? kids.childView(c.child) : null;
|
||||
return {
|
||||
id: c.id, name: c.childName, firstName: child?.firstName || c.childName, room: c.room, already: out.already.includes(c.id),
|
||||
sticker: kids.stickerAlert(child?.allergies, child?.medicalNotes),
|
||||
};
|
||||
}),
|
||||
});
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/events/:eventId/check-out { code, checkInIds?, collectedBy, roomId?, sessionId? }
|
||||
const checkOut = async (req, res) => {
|
||||
try {
|
||||
const out = await kids.checkOut({
|
||||
eventId: req.params.eventId, sessionId: req.body?.sessionId || null, code: req.body?.code, checkInIds: req.body?.checkInIds,
|
||||
collectedBy: req.body?.collectedBy, roomId: req.body?.roomId || null, staffUserId: req.user.id,
|
||||
});
|
||||
res.json({ checkedOut: out.checkIns.map(c => ({ id: c.id, name: c.childName, room: c.room?.name || null })) });
|
||||
} catch (error) {
|
||||
if (error.code === 'WRONG_CODE') audit(req, 'kids_wrong_code', 'event', req.params.eventId, { typed: String(req.body?.code || '').slice(0, 20), roomId: req.body?.roomId || null });
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Look up a code before checking out: which children are on it (to confirm who's collected)
|
||||
// @route GET /api/kids/events/:eventId/code/:code?sessionId=
|
||||
const lookupCode = async (req, res) => {
|
||||
try {
|
||||
const event = await kids.loadKidsEvent(req.params.eventId);
|
||||
const { occasion } = kids.occasionFor(event, event.sessions, req.query.sessionId || null);
|
||||
const code = kids.normaliseCode(req.params.code);
|
||||
const row = code ? await prisma.kidsPickupCode.findUnique({ where: { eventId_occasion_code: { eventId: event.id, occasion, code } } }) : null;
|
||||
if (!row) return res.json({ code, found: false, children: [] });
|
||||
const rows = await prisma.kidsCheckIn.findMany({ where: { pickupCodeId: row.id }, include: { room: { select: { id: true, name: true } } }, orderBy: { childName: 'asc' } });
|
||||
const family = row.familyId ? kids.familyView(await kids.loadFamily(row.familyId), { notes: false }) : null;
|
||||
res.json({
|
||||
code, found: true,
|
||||
family: family ? { name: family.name, parents: family.parents, adults: family.adults } : null,
|
||||
children: rows.map(c => ({ id: c.id, name: c.childName, room: c.room, checkedOutAt: c.checkedOutAt, collectedBy: c.collectedBy })),
|
||||
});
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/check-ins/:id/override { reason, collectedBy }
|
||||
const overrideCheckOut = async (req, res) => {
|
||||
try {
|
||||
const ci = await kids.overrideCheckOut({ checkInId: req.params.id, reason: req.body?.reason, collectedBy: req.body?.collectedBy, staffUserId: req.user.id });
|
||||
audit(req, 'kids_checkout_override', 'kids_check_in', ci.id, { child: ci.childName, collectedBy: ci.collectedBy, reason: ci.overrideReason });
|
||||
res.json({ id: ci.id, checkedOutAt: ci.checkedOutAt });
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/check-ins/:id/page { message? }
|
||||
const pageParent = async (req, res) => {
|
||||
try {
|
||||
res.json(await kids.pageParent({ checkInId: req.params.id, message: req.body?.message, staffUserId: req.user.id }));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route PUT /api/kids/check-ins/:id/room { roomId }
|
||||
const moveRoom = async (req, res) => {
|
||||
try {
|
||||
const ci = await kids.moveRoom({ checkInId: req.params.id, roomId: req.body?.roomId });
|
||||
res.json({ id: ci.id, roomId: ci.roomId });
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/events/:eventId/duty { roomId, on, sessionId? }
|
||||
const setDuty = async (req, res) => {
|
||||
try {
|
||||
res.json(await kids.setDuty({ eventId: req.params.eventId, sessionId: req.body?.sessionId || null, roomId: req.body?.roomId, userId: req.user.id, on: req.body?.on !== false }));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/alerts/:id/resolve
|
||||
const resolveAlert = async (req, res) => {
|
||||
try {
|
||||
const out = await prisma.kidsAlert.updateMany({ where: { id: String(req.params.id), resolvedAt: null }, data: { resolvedAt: new Date() } });
|
||||
res.json({ resolved: out.count });
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route GET /api/kids/events/:eventId/offline?deviceId=&sessionId=
|
||||
const offlineSnapshot = async (req, res) => {
|
||||
try {
|
||||
const data = await kids.offlineSnapshot({ eventId: req.params.eventId, sessionId: req.query.sessionId || null, deviceId: req.query.deviceId });
|
||||
logDataAccess(req, { action: 'kids_offline', eventId: req.params.eventId, records: data.families.length, sensitive: true });
|
||||
res.json(data);
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route POST /api/kids/events/:eventId/sync { deviceId, occasion, checkIns, checkOuts }
|
||||
const syncOffline = async (req, res) => {
|
||||
try {
|
||||
const out = await kids.syncOffline({ eventId: req.params.eventId, ...(req.body || {}), staffUserId: req.user.id });
|
||||
if (out.checkedIn || out.checkedOut || out.conflicts.length) audit(req, 'kids_offline_sync', 'event', req.params.eventId, { checkedIn: out.checkedIn, checkedOut: out.checkedOut, conflicts: out.conflicts.length });
|
||||
res.json(out);
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── Supervisor: setup ────────────────────────────────────────────────────────
|
||||
|
||||
// @route GET /api/kids/events/:eventId/settings
|
||||
const getSettings = async (req, res) => {
|
||||
try {
|
||||
res.json(await kids.getSettings(req.params.eventId));
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @route PUT /api/kids/events/:eventId/settings { enabled?, optionId?, roomSetId? } ('new' makes one)
|
||||
const saveSettings = async (req, res) => {
|
||||
try {
|
||||
const { enabled, optionId, roomSetId } = req.body || {};
|
||||
const out = await kids.saveSettings(req.params.eventId, { enabled, optionId, roomSetId });
|
||||
audit(req, 'kids_settings_updated', 'event', out.event.id, { enabled: out.event.kidsCheckIn, optionId: out.event.kidsOptionId, roomSetId: out.event.kidsRoomSetId });
|
||||
res.json(out);
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Events a supervisor can switch kids check-in on for (upcoming, newest first)
|
||||
// @route GET /api/kids/setup-events
|
||||
const setupEvents = async (req, res) => {
|
||||
try {
|
||||
const events = await prisma.event.findMany({
|
||||
where: withScope({ endDate: { gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } }, await listWhere(req)),
|
||||
select: { id: true, title: true, startDate: true, kidsCheckIn: true, campusId: true },
|
||||
orderBy: { startDate: 'asc' },
|
||||
take: 200,
|
||||
});
|
||||
res.json(events);
|
||||
} catch (error) {
|
||||
fail(res, error);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
getMine, createMine, renameMine, saveMyChild, deleteMyChild, saveMyAdult, deleteMyAdult, leaveMine,
|
||||
listEvents, getBoard, searchFamilies, familyByQr, getFamily, createFamilyAtDesk, addParentAtDesk, saveChildAtDesk, addAdultAtDesk,
|
||||
checkIn, checkOut, lookupCode, overrideCheckOut, pageParent, moveRoom, setDuty, resolveAlert, offlineSnapshot, syncOffline,
|
||||
getSettings, saveSettings, setupEvents,
|
||||
};
|
||||
@@ -183,6 +183,7 @@ app.get('/health', async (req, res) => {
|
||||
// Use routes
|
||||
app.use('/api/hub', require('./routes/hubRoutes'));
|
||||
app.use('/api/campuses', require('./routes/campusRoutes'));
|
||||
app.use('/api/kids', require('./routes/kidsRoutes'));
|
||||
app.use('/api/users', userRoutes);
|
||||
app.use('/api/events', eventRoutes);
|
||||
app.use('/api/registrations', registrationRoutes);
|
||||
@@ -942,6 +943,48 @@ app.get('/docs', async (req, res) => {
|
||||
{ method:'GET', path:'/api/campuses/:id/audience', auth:'supervisor+', desc:'"Everyone at campus X" for broadcasts: home campus X, plus with ?registrants=true people registered for its events in the last 12 months' },
|
||||
]},
|
||||
|
||||
{ title: 'Kids check-in', base: '/api/kids', endpoints: [
|
||||
{ method:'GET', path:'/api/kids/me', auth:'user', desc:'My family (children, authorised adults, parents), the family QR token, live pickup codes and pages from the last 24 hours' },
|
||||
{ method:'POST', path:'/api/kids/me', auth:'user', desc:'Start my family', request:{ body:{ name:'The Smith family' } } },
|
||||
{ method:'PUT', path:'/api/kids/me', auth:'user', desc:'Rename my family' },
|
||||
{ method:'DELETE', path:'/api/kids/me', auth:'user', desc:'Leave my family (the last parent leaving deletes it with its children)' },
|
||||
{ method:'POST', path:'/api/kids/me/children', auth:'user', desc:'Add a child (allergies, medical and custody notes are stored encrypted)',
|
||||
request:{ body:{ firstName:'Mia', lastName:'Smith', dateOfBirth:'2021-03-04', allergies:'Peanuts', medicalNotes:'', custodyNotes:'' } } },
|
||||
{ method:'PUT', path:'/api/kids/me/children/:id', auth:'user', desc:'Change a child (custody note changes are audited)' },
|
||||
{ method:'DELETE', path:'/api/kids/me/children/:id', auth:'user', desc:'Remove a child' },
|
||||
{ method:'POST', path:'/api/kids/me/adults', auth:'user', desc:'Add an authorised adult (no account needed; up to 10)', request:{ body:{ name:'Mary Smith', phone:'0821234567', relationship:'Gran' } } },
|
||||
{ method:'PUT', path:'/api/kids/me/adults/:id', auth:'user', desc:'Change an authorised adult' },
|
||||
{ method:'DELETE', path:'/api/kids/me/adults/:id', auth:'user', desc:'Remove an authorised adult' },
|
||||
{ method:'GET', path:'/api/kids/setup-events', auth:'supervisor+', desc:'Upcoming events to set kids check-in up for (campus-scoped)' },
|
||||
{ method:'GET', path:'/api/kids/events/:eventId/settings', auth:'supervisor+', desc:'Kids check-in settings, the main tickets that can be the kids ticket and the allocation sets' },
|
||||
{ method:'PUT', path:'/api/kids/events/:eventId/settings', auth:'supervisor+', desc:'Switch kids check-in on/off and choose the kids ticket and rooms ("new" makes a free "Kids check-in" ticket or a "Kids rooms" set). Audited as kids_settings_updated',
|
||||
request:{ body:{ enabled:true, optionId:'new', roomSetId:'new' } } },
|
||||
{ method:'GET', path:'/api/kids/events', auth:'staff+', desc:'Events with kids check-in from the last week on' },
|
||||
{ method:'GET', path:'/api/kids/events/:eventId/board', auth:'staff+', desc:'Rooms (counts, leaders on duty, full/over ratio), check-ins with allergies, medical and custody notes, and alerts for today\'s occasion. ?log=1 writes the access log' },
|
||||
{ method:'GET', path:'/api/kids/events/:eventId/families?q=', auth:'staff+', desc:'Find families by family, child or parent name, email or phone' },
|
||||
{ method:'POST', path:'/api/kids/events/:eventId/families', auth:'staff+', desc:'New family at the desk: the parent\'s account is matched by email/phone or created inactive',
|
||||
request:{ body:{ name:'The Smith family', parent:{ name:'Anna Smith', phone:'0821234567', email:'' }, children:[{ firstName:'Mia', dateOfBirth:'2021-03-04' }] } } },
|
||||
{ method:'GET', path:'/api/kids/events/:eventId/families/qr/:token', auth:'staff+', desc:'The family for a scanned family QR code' },
|
||||
{ method:'GET', path:'/api/kids/events/:eventId/families/:familyId', auth:'staff+', desc:'One family' },
|
||||
{ method:'POST', path:'/api/kids/events/:eventId/families/:familyId/parents', auth:'staff+', desc:'Add a parent to a family' },
|
||||
{ method:'POST', path:'/api/kids/events/:eventId/families/:familyId/children', auth:'staff+', desc:'Add a child (custody notes: supervisors only)' },
|
||||
{ method:'PUT', path:'/api/kids/events/:eventId/families/:familyId/children/:childId', auth:'staff+', desc:'Change a child' },
|
||||
{ method:'POST', path:'/api/kids/events/:eventId/families/:familyId/adults', auth:'staff+', desc:'Add an authorised adult' },
|
||||
{ method:'POST', path:'/api/kids/events/:eventId/check-in', auth:'staff+', desc:'Check children in: one pickup code per family per occasion, a free place on the kids ticket the first time, a ticket usage each time. Sends the code to the parents (and optionally an authorised adult)',
|
||||
request:{ body:{ familyId:'f_1', children:[{ childId:'c_1', roomId:'g_1' }], sendToAdultId:null } },
|
||||
responses:[{ status:201, desc:'Checked in', body:{ code:'K7P2', qr:'KIDS-K7P2', checkIns:[{ id:'k_1', name:'Mia Smith', room:{ id:'g_1', name:'Toddlers' }, sticker:'ALLERGY: PEANUTS' }] } }] },
|
||||
{ method:'GET', path:'/api/kids/events/:eventId/code/:code', auth:'staff+', desc:'The children on a pickup code (for confirming who is collected)' },
|
||||
{ method:'POST', path:'/api/kids/events/:eventId/check-out', auth:'staff+', desc:'Check out with the pickup code. 404 WRONG_CODE raises a room alert (audited as kids_wrong_code)',
|
||||
request:{ body:{ code:'K7P2', collectedBy:'Anna Smith', checkInIds:['k_1'] } } },
|
||||
{ method:'POST', path:'/api/kids/check-ins/:id/override', auth:'staff+', desc:'Check one child out without the code; reason and who collected required. Audited as kids_checkout_override' },
|
||||
{ method:'POST', path:'/api/kids/check-ins/:id/page', auth:'staff+', desc:'Ask the parents to come to the room (WhatsApp/email; shows on their Kids page)' },
|
||||
{ method:'PUT', path:'/api/kids/check-ins/:id/room', auth:'staff+', desc:'Move a child to another room' },
|
||||
{ method:'POST', path:'/api/kids/events/:eventId/duty', auth:'staff+', desc:'"I\'m on duty" in a room (on:false to go off), for the ratio' },
|
||||
{ method:'POST', path:'/api/kids/alerts/:id/resolve', auth:'staff+', desc:'Mark an alert as dealt with' },
|
||||
{ method:'GET', path:'/api/kids/events/:eventId/offline?deviceId=', auth:'staff+', desc:'Offline list for a desk: families, rooms, who is in, and 20 pickup codes reserved for the device' },
|
||||
{ method:'POST', path:'/api/kids/events/:eventId/sync', auth:'staff+', desc:'Sync an offline desk\'s check-ins and check-outs (idempotent by clientId). Audited as kids_offline_sync' },
|
||||
]},
|
||||
|
||||
{ title: 'Privacy (POPIA)', base: '/api/privacy', endpoints: [
|
||||
{ method:'GET', path:'/api/privacy/me', auth:'user', desc:'My news opt-in, its history, and my privacy requests',
|
||||
responses:[{ status:200, desc:'Success', body:{ news:{ email:true, whatsapp:false }, newsAskedAt:'2026-10-23T08:00:00.000Z', canWhatsApp:false, notificationPreference:'email', history:[{ channel:'email', granted:true, source:'signup', createdAt:'2026-10-23T08:00:00.000Z' }], requests:[] }}]},
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const c = require('../controllers/kidsController');
|
||||
const { protect, staff, supervisor } = require('../middleware/authMiddleware');
|
||||
const { scopeEvent, scopeList } = require('../utils/campusScope');
|
||||
|
||||
// My account → Kids (any signed-in parent; only their own family)
|
||||
router.get('/me', protect, c.getMine);
|
||||
router.post('/me', protect, c.createMine);
|
||||
router.put('/me', protect, c.renameMine);
|
||||
router.delete('/me', protect, c.leaveMine);
|
||||
router.post('/me/children', protect, c.saveMyChild);
|
||||
router.put('/me/children/:id', protect, c.saveMyChild);
|
||||
router.delete('/me/children/:id', protect, c.deleteMyChild);
|
||||
router.post('/me/adults', protect, c.saveMyAdult);
|
||||
router.put('/me/adults/:id', protect, c.saveMyAdult);
|
||||
router.delete('/me/adults/:id', protect, c.deleteMyAdult);
|
||||
|
||||
// Setup (supervisors)
|
||||
router.get('/setup-events', protect, supervisor, scopeList, c.setupEvents);
|
||||
router.get('/events/:eventId/settings', protect, supervisor, scopeEvent(), c.getSettings);
|
||||
router.put('/events/:eventId/settings', protect, supervisor, scopeEvent({ need: 'manage' }), c.saveSettings);
|
||||
|
||||
// The desk and the rooms (staff). Families are church-wide; staff reach them through an event
|
||||
// they can work on.
|
||||
router.get('/events', protect, staff, scopeList, c.listEvents);
|
||||
router.get('/events/:eventId/board', protect, staff, scopeEvent(), c.getBoard);
|
||||
router.get('/events/:eventId/families', protect, staff, scopeEvent(), c.searchFamilies);
|
||||
router.post('/events/:eventId/families', protect, staff, scopeEvent(), c.createFamilyAtDesk);
|
||||
router.get('/events/:eventId/families/qr/:token', protect, staff, scopeEvent(), c.familyByQr);
|
||||
router.get('/events/:eventId/families/:familyId', protect, staff, scopeEvent(), c.getFamily);
|
||||
router.post('/events/:eventId/families/:familyId/parents', protect, staff, scopeEvent(), c.addParentAtDesk);
|
||||
router.post('/events/:eventId/families/:familyId/children', protect, staff, scopeEvent(), c.saveChildAtDesk);
|
||||
router.put('/events/:eventId/families/:familyId/children/:childId', protect, staff, scopeEvent(), c.saveChildAtDesk);
|
||||
router.post('/events/:eventId/families/:familyId/adults', protect, staff, scopeEvent(), c.addAdultAtDesk);
|
||||
router.post('/events/:eventId/check-in', protect, staff, scopeEvent(), c.checkIn);
|
||||
router.post('/events/:eventId/check-out', protect, staff, scopeEvent(), c.checkOut);
|
||||
router.get('/events/:eventId/code/:code', protect, staff, scopeEvent(), c.lookupCode);
|
||||
router.post('/events/:eventId/duty', protect, staff, scopeEvent(), c.setDuty);
|
||||
router.get('/events/:eventId/offline', protect, staff, scopeEvent(), c.offlineSnapshot);
|
||||
router.post('/events/:eventId/sync', protect, staff, scopeEvent(), c.syncOffline);
|
||||
router.post('/check-ins/:id/override', protect, staff, scopeEvent({ resolve: 'kidsCheckIn' }), c.overrideCheckOut);
|
||||
router.post('/check-ins/:id/page', protect, staff, scopeEvent({ resolve: 'kidsCheckIn' }), c.pageParent);
|
||||
router.put('/check-ins/:id/room', protect, staff, scopeEvent({ resolve: 'kidsCheckIn' }), c.moveRoom);
|
||||
router.post('/alerts/:id/resolve', protect, staff, scopeEvent({ resolve: 'kidsAlert' }), c.resolveAlert);
|
||||
|
||||
module.exports = router;
|
||||
@@ -15,6 +15,8 @@ const ACCESS_ACTIONS = {
|
||||
medical_list: 'Medical list viewed',
|
||||
backup_download: 'Database backup downloaded',
|
||||
impersonation: 'Viewed the site as another user',
|
||||
kids_rooms: 'Kids check-in desk or room opened',
|
||||
kids_offline: 'Kids check-in list downloaded for offline use',
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -102,6 +102,8 @@ const RESOLVERS = {
|
||||
const c = await prisma.consentRequest.findUnique({ where: { id }, select: { event: EV, attendee: { select: { registration: { select: { userId: true } } } } } });
|
||||
return shape(c?.event, [c?.attendee?.registration?.userId]);
|
||||
},
|
||||
kidsCheckIn: async id => shape((await prisma.kidsCheckIn.findUnique({ where: { id }, select: { event: EV } }))?.event),
|
||||
kidsAlert: async id => shape((await prisma.kidsAlert.findUnique({ where: { id }, select: { event: EV } }))?.event),
|
||||
};
|
||||
|
||||
/** The event a record belongs to (see RESOLVERS), or null. */
|
||||
|
||||
@@ -0,0 +1,841 @@
|
||||
/**
|
||||
* 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,
|
||||
};
|
||||
@@ -455,7 +455,12 @@ async function anonymiseUser(userId, db = prisma) {
|
||||
await tx.passwordReset.deleteMany({ where: { userId } });
|
||||
await tx.twoFactorChallenge.deleteMany({ where: { userId } });
|
||||
|
||||
return { attendees: attendeeIds.length, formAnswers: answers.count, providerRecords: txns.length + checkouts.length };
|
||||
// Kids check-in: leave their family; a family with no parent left is deleted with its
|
||||
// children (their check-ins stay as attendance, without who collected them).
|
||||
const { familyDeleted } = await require('./kids').removeFromFamily(tx, userId);
|
||||
await tx.kidsCheckIn.updateMany({ where: { checkedOutById: userId }, data: { checkedOutById: null } });
|
||||
|
||||
return { attendees: attendeeIds.length, formAnswers: answers.count, providerRecords: txns.length + checkouts.length, familyDeleted };
|
||||
});
|
||||
|
||||
await clearTrustedDevices(userId);
|
||||
@@ -477,7 +482,7 @@ async function exportUserData(userId, db = prisma) {
|
||||
});
|
||||
if (!user) return null;
|
||||
|
||||
const [registrations, payments, tickets, waitlist, certificates, feedback, consents, security, requests, notices] = await Promise.all([
|
||||
const [registrations, payments, tickets, waitlist, certificates, feedback, consents, security, requests, notices, family] = await Promise.all([
|
||||
db.registration.findMany({
|
||||
where: { userId },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
@@ -501,6 +506,7 @@ async function exportUserData(userId, db = prisma) {
|
||||
db.securityEvent.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, take: 100, select: { type: true, ip: true, device: true, createdAt: true } }),
|
||||
db.dataRequest.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, select: { type: true, status: true, details: true, response: true, createdAt: true, closedAt: true } }),
|
||||
db.noticeAcceptance.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, select: { version: true, source: true, createdAt: true } }),
|
||||
require('./kids').exportFamily(userId, db),
|
||||
]);
|
||||
|
||||
return {
|
||||
@@ -542,6 +548,7 @@ async function exportUserData(userId, db = prisma) {
|
||||
feedback: feedback.map(f => ({ event: f.form?.event?.title, at: f.createdAt, answers: f.answers.map(a => ({ question: a.field?.label, answer: a.value })) })),
|
||||
accountActivity: security.map(s => ({ type: s.type, ip: s.ip, device: s.device, at: s.createdAt })),
|
||||
dataRequests: requests,
|
||||
kidsFamily: family,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -79,6 +79,10 @@ async function readiness(now = new Date(), db = prisma) {
|
||||
add('whatsapp_stop', 'WhatsApp STOP replies reach the site', seen && now - seen < 30 * DAY,
|
||||
seen ? `Last message from WAWP ${seen.toLocaleString('en-ZA')}${now - seen >= 30 * DAY ? ' — over a month ago, check the webhook' : ''}` : 'Paste the webhook URL from Site settings → WhatsApp into WAWP (events: message, session.status).',
|
||||
'/dashboard/admin/settings?tab=whatsapp', whatsappConfigured);
|
||||
const kidsEvents = await db.event.count({ where: { kidsCheckIn: true } });
|
||||
add('kids_retention', 'Children\'s kids check-in details expire', policies.policies.kids_profiles?.enabled,
|
||||
policies.policies.kids_profiles?.enabled ? `Deleted after ${retention.describeMonths(policies.policies.kids_profiles.months)} without a check-in` : 'Switch on the "Children at kids check-in" retention rule — it holds children\'s medical and custody notes.',
|
||||
'/dashboard/admin/privacy?tab=retention', kidsEvents > 0);
|
||||
const twoFactorOn = String(process.env.TWO_FACTOR_REQUIRED_ROLES || 'true').toLowerCase() !== 'false';
|
||||
add('two_factor', 'Two-factor login required for admins and supervisors', twoFactorOn,
|
||||
twoFactorOn ? 'Required' : 'TWO_FACTOR_REQUIRED_ROLES=false on the server — only for emergencies.', null);
|
||||
|
||||
@@ -43,6 +43,12 @@ const POLICIES = {
|
||||
defaults: { enabled: true, months: 24 },
|
||||
minMonths: 3,
|
||||
},
|
||||
kids_profiles: {
|
||||
label: 'Children at kids check-in',
|
||||
description: 'A child\'s profile (name, date of birth, allergies, medical and custody notes) is deleted when they haven\'t been checked in for this long, then families left without children. Who collected a child is cleared from check-ins this old; the attendance itself stays.',
|
||||
defaults: { enabled: true, months: 6 },
|
||||
minMonths: 1,
|
||||
},
|
||||
audit_logs: {
|
||||
label: 'Audit and access logs',
|
||||
description: 'The audit log, the access log and "view as" sessions.',
|
||||
@@ -227,7 +233,12 @@ async function runAuditLogs(policy, now, db = prisma) {
|
||||
return { audit: audit.count, access: access.count, viewAsSessions: sessions.count };
|
||||
}
|
||||
|
||||
async function runKidsProfiles(policy, now, db = prisma) {
|
||||
return require('./kids').runKidsRetention(monthsAgo(policy.months, now), db);
|
||||
}
|
||||
|
||||
const RUNNERS = {
|
||||
kids_profiles: runKidsProfiles,
|
||||
inactive_accounts: runInactiveAccounts,
|
||||
form_answers: runFormAnswers,
|
||||
login_history: runLoginHistory,
|
||||
@@ -267,12 +278,13 @@ async function preview(policies, now = new Date(), db = prisma) {
|
||||
const out = {};
|
||||
const p = policies;
|
||||
const inactiveCutoff = monthsAgo(p.inactive_accounts.months, now);
|
||||
const [toWarn, warnedDue, formAnswers, logins, audit] = await Promise.all([
|
||||
const [toWarn, warnedDue, formAnswers, logins, audit, kidsProfiles] = await Promise.all([
|
||||
inactiveAccounts(new Date(inactiveCutoff.getTime() + WARNING_DAYS * DAY), { warned: false, limit: 5000 }, db),
|
||||
inactiveAccounts(inactiveCutoff, { warnedBefore: new Date(now.getTime() - WARNING_DAYS * DAY), limit: 5000 }, db),
|
||||
db.formAnswer.count({ where: { response: { registration: { event: { endDate: { lt: monthsAgo(p.form_answers.months, now) } } } } } }),
|
||||
db.securityEvent.count({ where: { createdAt: { lt: monthsAgo(p.login_history.months, now) } } }),
|
||||
db.adminAuditLog.count({ where: { createdAt: { lt: monthsAgo(p.audit_logs.months, now) } } }),
|
||||
require('./kids').previewKidsRetention(monthsAgo(p.kids_profiles.months, now), db),
|
||||
]);
|
||||
const payments = await db.$queryRawUnsafe(
|
||||
`SELECT COUNT(*)::int AS n FROM "ProviderTransaction" WHERE "createdAt" < $1 AND "raw" IS NOT NULL AND jsonb_typeof("raw") = 'object' AND NOT ("raw" ? '_scrubbed')`,
|
||||
@@ -283,6 +295,7 @@ async function preview(policies, now = new Date(), db = prisma) {
|
||||
out.login_history = { count: logins };
|
||||
out.payment_details = { count: payments[0]?.n || 0 };
|
||||
out.audit_logs = { count: audit };
|
||||
out.kids_profiles = kidsProfiles;
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -298,6 +311,7 @@ async function noticeLines(db = prisma) {
|
||||
`• Medical and emergency-contact details from parental consent forms are deleted ${parseInt(medical, 10) || 30} days after the event. The record of who gave consent, when and to which wording is kept.`,
|
||||
line('login_history', t => `• Login history (time, IP address, device) is kept for ${t}.`, '• Login history is kept until you ask us to delete it.'),
|
||||
line('payment_details', t => `• Payer names and email addresses received with payments are removed after ${t}. Payment records themselves (amount, date, method) are kept as tax law requires.`, '• Payment records are kept as tax law requires.'),
|
||||
line('kids_profiles', t => `• Children's details for kids check-in (including allergies, medical and custody notes) are deleted when a child hasn't been checked in for ${t}.`, '• Children\'s details for kids check-in are kept until a parent removes them.'),
|
||||
line('audit_logs', t => `• Audit and access records (who did what in the system) are kept for ${t}.`, '• Audit and access records are kept for accountability.'),
|
||||
'• Detailed visit statistics become anonymous daily totals after 90 days.',
|
||||
`• Database backups are kept for about ${parseInt(backups, 10) || 14} days, so deleted information stays in them until they are replaced.`,
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
const kids = require('../src/utils/kids');
|
||||
|
||||
describe('pickup codes', () => {
|
||||
test('are 4 characters from the alphabet without 0/O/1/I', () => {
|
||||
for (let i = 0; i < 500; i++) {
|
||||
const c = kids.randomCode();
|
||||
expect(c).toHaveLength(4);
|
||||
expect(c).toMatch(/^[A-HJ-NP-Z2-9]{4}$/);
|
||||
}
|
||||
});
|
||||
|
||||
test('typed or scanned codes are cleaned up', () => {
|
||||
expect(kids.normaliseCode('k7p2')).toBe('K7P2');
|
||||
expect(kids.normaliseCode(' K7 P2 ')).toBe('K7P2');
|
||||
expect(kids.normaliseCode('KIDS-K7P2')).toBe('K7P2');
|
||||
expect(kids.normaliseCode('k7-p2')).toBe('K7P2');
|
||||
});
|
||||
|
||||
test('anything that cannot be a code is null', () => {
|
||||
expect(kids.normaliseCode('')).toBeNull();
|
||||
expect(kids.normaliseCode('K7P')).toBeNull();
|
||||
expect(kids.normaliseCode('K7P22')).toBeNull();
|
||||
expect(kids.normaliseCode('K0P2')).toBeNull(); // no zero
|
||||
expect(kids.normaliseCode('KOP2')).toBeNull(); // no O
|
||||
expect(kids.normaliseCode('K1P2')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ages and rooms', () => {
|
||||
const on = new Date('2026-11-01T08:00:00Z');
|
||||
|
||||
test('age in whole years, birthday counted on the day', () => {
|
||||
expect(kids.ageOn('2021-11-01', on)).toBe(5);
|
||||
expect(kids.ageOn('2021-11-02', on)).toBe(4);
|
||||
expect(kids.ageOn(null, on)).toBeNull();
|
||||
});
|
||||
|
||||
const rooms = [
|
||||
{ id: 'all', name: 'Everyone', minAge: null, maxAge: null, order: 0 },
|
||||
{ id: 'tod', name: 'Toddlers', minAge: 1, maxAge: 3, order: 1, capacity: 2 },
|
||||
{ id: 'jun', name: 'Juniors', minAge: 4, maxAge: 7, order: 2 },
|
||||
];
|
||||
|
||||
test('fitsRoom respects the range; no age fits anywhere', () => {
|
||||
expect(kids.fitsRoom(rooms[1], 2)).toBe(true);
|
||||
expect(kids.fitsRoom(rooms[1], 4)).toBe(false);
|
||||
expect(kids.fitsRoom(rooms[1], null)).toBe(true);
|
||||
});
|
||||
|
||||
test('suggests the narrowest room that fits', () => {
|
||||
expect(kids.suggestRoom(rooms, 2).id).toBe('tod');
|
||||
expect(kids.suggestRoom(rooms, 5).id).toBe('jun');
|
||||
expect(kids.suggestRoom(rooms, 11).id).toBe('all');
|
||||
});
|
||||
|
||||
test('skips full rooms', () => {
|
||||
expect(kids.suggestRoom(rooms, 2, { tod: 2 }).id).toBe('all');
|
||||
});
|
||||
|
||||
test('without an age, the first room in order', () => {
|
||||
expect(kids.suggestRoom(rooms, null).id).toBe('all');
|
||||
});
|
||||
|
||||
test('nothing fits → null', () => {
|
||||
expect(kids.suggestRoom([rooms[1]], 9)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('room status', () => {
|
||||
test('ratio: leaders needed and over ratio', () => {
|
||||
expect(kids.roomStatus({ ratio: 5 }, 6, 1)).toMatchObject({ leadersNeeded: 2, overRatio: true });
|
||||
expect(kids.roomStatus({ ratio: 5 }, 5, 1)).toMatchObject({ leadersNeeded: 1, overRatio: false });
|
||||
expect(kids.roomStatus({ ratio: 5 }, 0, 0)).toMatchObject({ leadersNeeded: 0, overRatio: false });
|
||||
});
|
||||
|
||||
test('no ratio is never over ratio; capacity makes it full', () => {
|
||||
expect(kids.roomStatus({ capacity: 3 }, 3, 0)).toMatchObject({ full: true, overRatio: false });
|
||||
expect(kids.roomStatus({}, 30, 0)).toMatchObject({ full: false, overRatio: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe('sticker text', () => {
|
||||
test('allergy and medical flags, kept short', () => {
|
||||
expect(kids.stickerAlert('Peanuts', '')).toBe('ALLERGY: PEANUTS');
|
||||
expect(kids.stickerAlert('', 'Asthma pump in bag')).toBe('MEDICAL');
|
||||
expect(kids.stickerAlert('nuts', 'epipen')).toBe('ALLERGY: NUTS · MEDICAL');
|
||||
expect(kids.stickerAlert('', '')).toBe('');
|
||||
expect(kids.stickerAlert('a'.repeat(40), '')).toMatch(/^ALLERGY: A{24}…$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('occasions', () => {
|
||||
const single = { scheduleType: 'single', startDate: '2026-11-01T07:00:00Z', endDate: '2026-11-01T10:00:00Z' };
|
||||
|
||||
test('a single-date event: its day, only while it is on', () => {
|
||||
expect(kids.occasionFor(single, [], null, new Date('2026-11-01T06:00:00Z'))).toEqual({ occasion: '2026-11-01', sessionId: null });
|
||||
expect(() => kids.occasionFor(single, [], null, new Date('2026-11-02T08:00:00Z'))).toThrow(/open on 2026-11-01/);
|
||||
});
|
||||
|
||||
test('a multi-session event: today\'s session', () => {
|
||||
const ev = { scheduleType: 'sessions', checkInWindow: 'whole_day' };
|
||||
const sessions = [
|
||||
{ id: 's1', startsAt: '2026-11-01T07:00:00Z', endsAt: '2026-11-01T09:00:00Z' },
|
||||
{ id: 's2', startsAt: '2026-11-08T07:00:00Z', endsAt: '2026-11-08T09:00:00Z' },
|
||||
];
|
||||
expect(kids.occasionFor(ev, sessions, null, new Date('2026-11-08T06:30:00Z'))).toEqual({ occasion: 's2', sessionId: 's2' });
|
||||
expect(() => kids.occasionFor(ev, sessions, null, new Date('2026-11-04T08:00:00Z'))).toThrow(/next one/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('messages', () => {
|
||||
test('check-in message has the code and rooms, nothing medical', () => {
|
||||
const text = kids.checkInMessage({ eventTitle: 'Sunday Kids', code: 'K7P2', children: [{ name: 'Mia', room: 'Toddlers' }, { name: 'Ben', room: 'Juniors' }] });
|
||||
expect(text).toContain('Mia and Ben are checked in at Sunday Kids (Toddlers, Juniors)');
|
||||
expect(text).toContain('Pickup code: K7P2');
|
||||
expect(text).toContain('/dashboard/user/kids');
|
||||
});
|
||||
|
||||
test('for an authorised adult, no link to an account', () => {
|
||||
const text = kids.checkInMessage({ eventTitle: 'Sunday Kids', code: 'K7P2', children: [{ name: 'Mia' }], forParent: false });
|
||||
expect(text).toContain('Mia is checked in');
|
||||
expect(text).not.toContain('My account');
|
||||
});
|
||||
|
||||
test('listNames', () => {
|
||||
expect(kids.listNames(['A'])).toBe('A');
|
||||
expect(kids.listNames(['A', 'B', 'C'])).toBe('A, B and C');
|
||||
});
|
||||
});
|
||||
|
||||
describe('children', () => {
|
||||
test('cleanChild needs a first name and seals the notes', () => {
|
||||
expect(() => kids.cleanChild({})).toThrow(/first name/);
|
||||
const data = kids.cleanChild({ firstName: ' Mia ', allergies: 'Peanuts', custodyNotes: 'Not to Mr X' });
|
||||
expect(data.firstName).toBe('Mia');
|
||||
expect(data.allergies).toMatch(/^enc:/);
|
||||
expect(data.custodyNotes).toMatch(/^enc:/);
|
||||
expect(kids.childView({ id: 'c', ...data }).allergies).toBe('Peanuts');
|
||||
});
|
||||
|
||||
test('a future date of birth is refused', () => {
|
||||
expect(() => kids.cleanChild({ firstName: 'A', dateOfBirth: '2999-01-01' })).toThrow(/date of birth/);
|
||||
});
|
||||
|
||||
test('custodyChanged only when the text changes', () => {
|
||||
const existing = kids.cleanChild({ firstName: 'A', custodyNotes: 'x' });
|
||||
expect(kids.custodyChanged(existing, kids.cleanChild({ custodyNotes: 'x' }, existing))).toBe(false);
|
||||
expect(kids.custodyChanged(existing, kids.cleanChild({ custodyNotes: 'y' }, existing))).toBe(true);
|
||||
expect(kids.custodyChanged(existing, kids.cleanChild({ allergies: 'y' }, existing))).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user