From be621c49a2b9a4033c9e27a5d42fa9acc430c012 Mon Sep 17 00:00:00 2001 From: joshua Date: Mon, 19 Oct 2026 14:06:22 +0200 Subject: [PATCH] Add offline ticket scanning Staff can lock a section (or the whole event) to their device, download its tickets and keep scanning with no connection. Scans are queued in IndexedDB and synced idempotently when back online; conflicts go into a sync report for supervisors, who can also force-release a lost device. The server now validates scan sections and refuses scans in a scope locked to another device. Adds a web app manifest and a service worker for the scanner page. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 20 ++ FEATURES.md | 11 +- backend/API_DOCUMENTATION.md | 24 ++ .../migration.sql | 93 ++++++++ backend/prisma/schema.prisma | 76 ++++++- backend/src/controllers/scanLockController.js | 151 +++++++++++++ backend/src/controllers/ticketController.js | 21 ++ backend/src/index.js | 15 ++ backend/src/routes/scanLockRoutes.js | 15 ++ backend/src/utils/scanLocks.js | 213 ++++++++++++++++++ backend/tests/scanLocks.test.js | 54 +++++ frontend/package-lock.json | 67 +----- frontend/package.json | 1 + frontend/public/sw.js | 67 ++++++ .../app/dashboard/admin/audit-log/page.tsx | 8 + frontend/src/app/dashboard/admin/page.tsx | 3 +- .../dashboard/staff/ticket-scanning/page.tsx | 74 +++++- .../supervisor/offline-scans/page.tsx | 163 ++++++++++++++ .../src/app/dashboard/supervisor/page.tsx | 3 +- frontend/src/app/manifest.ts | 17 ++ .../components/scanner/OfflineScanPanel.tsx | 106 +++++++++ .../components/scanner/useOfflineScanning.ts | 115 ++++++++++ frontend/src/content/help/registry.ts | 6 + .../content/help/staff-ticket-scanning.tsx | 5 +- .../content/help/supervisor-offline-scans.tsx | 32 +++ frontend/src/contexts/AuthContext.tsx | 31 +++ frontend/src/lib/api.ts | 1 + frontend/src/lib/offlineScan.ts | 130 +++++++++++ info.md | 1 + 29 files changed, 1451 insertions(+), 72 deletions(-) create mode 100644 backend/prisma/migrations/20261019134441_add_offline_scanning/migration.sql create mode 100644 backend/src/controllers/scanLockController.js create mode 100644 backend/src/routes/scanLockRoutes.js create mode 100644 backend/src/utils/scanLocks.js create mode 100644 backend/tests/scanLocks.test.js create mode 100644 frontend/public/sw.js create mode 100644 frontend/src/app/dashboard/supervisor/offline-scans/page.tsx create mode 100644 frontend/src/app/manifest.ts create mode 100644 frontend/src/components/scanner/OfflineScanPanel.tsx create mode 100644 frontend/src/components/scanner/useOfflineScanning.ts create mode 100644 frontend/src/content/help/supervisor-offline-scans.tsx create mode 100644 frontend/src/lib/offlineScan.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e8c5adf..42c3028 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,26 @@ and this project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added + +- Offline ticket scanning. While online, staff pick an event and section on the scanner and tap "Enable offline mode". The section (or the whole event) is locked to their device and its tickets are downloaded to the device. + - With no connection, scans are checked against that list and queued on the device. + - The panel shows when the list was downloaded and how many scans are waiting. + - Queued scans sync automatically when the device is back online (or with "Sync now"), and check-in messages go out then. + - "Release section" ends offline mode and deletes the list from the device. +- Only one device can hold a section at a time (a whole-event lock clashes with every section). While a section is locked, other devices see who holds it and can't scan it, online or offline, so a ticket can never be redeemed twice by two offline devices. +- Syncing is idempotent and never redeems more than is left on a ticket. Anything that needs a person to look goes into a sync report: tickets not found, cancelled registrations, used-up tickets, scans outside the locked section, and check-ins without consent. +- Supervisor → Offline scanning page: active locks with force release (for a lost or flat phone; its scans still sync if it reconnects, and are flagged), and sync reports to review. Locks, releases, force-releases and syncs are recorded in the audit log. +- The scanner is installable as an app (web app manifest), and a service worker caches the scanner page and its scripts so it opens with no connection. +- The app now stays signed in with the last confirmed profile when it's reloaded without a connection, instead of sending the user to the login page. +- New `/api/scan-locks` endpoints. + - Requires the `add_offline_scanning` database migration. + +### Changed + +- `POST /api/tickets/scan/:qrCode` now accepts `sectionId` and checks it on the server; this was previously only checked in the browser. + - It now refuses (423) scans in a section that another device has locked for offline scanning. + ## [1.16.0] - 2026-10-19 ### Added diff --git a/FEATURES.md b/FEATURES.md index ae283e8..e9bc922 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -200,6 +200,13 @@ Items & Pricing → Sections → Form → Visibility → Attachments**. - **Check-in confirmation** — holders get an email/WhatsApp saying how many were checked in and how many remain. - **Scan stats** — recent scans and per-event scan counts. +- **Offline scanning** — while online, a staff member locks an event section (or the + whole event) to their device and downloads its tickets. They can then keep scanning + with no connection; scans are queued on the device and sync automatically when it's + back online (never redeeming more than is left). Only one device can hold a section, + and while it's locked nobody else can scan it, online or offline. Problems found + while syncing go into a report for a supervisor. Supervisors can force-release a + lost device. The scanner can be added to the home screen (PWA) and opens offline. - **Printing** — A4 sheets (8 tickets per page) and A6 single tickets. - **Resend** — send tickets to a different email/phone at the door. @@ -299,6 +306,8 @@ logout controls. Disconnected sessions are recovered automatically. Reconcile (Yoco transactions), and Payment Link. - **Coupon codes** (`/dashboard/supervisor/coupons`) — create, edit and turn off discount codes, and see who used each one. +- **Offline scanning** (`/dashboard/supervisor/offline-scans`) — devices holding + offline locks (with force release) and sync reports to review. - **Waitlist** (`/dashboard/supervisor/waitlist`) — the queue per event: offer a place now, move people up or down, or remove them. - **Parental consent** (`/dashboard/supervisor/consent`) — consent status per @@ -469,5 +478,5 @@ falling back to a general guide. | `/set-banner` | Supervisor | Site banner | | `/dashboard/user` (+ `/payments`, `/donate`, `/forms`, `/profile`, `/reset-password`) | User | My Events | | `/dashboard/staff` (+ `/ticket-scanning`, `/event-tickets`) | Staff | Staff tools | -| `/dashboard/supervisor` (+ `/events`, `/event-options`, `/at-the-door`, `/manual`, `/manual-registration`, `/payments`, `/coupons`, `/waitlist`, `/consent`, `/email-attendees`, `/whatsapp-attendees`, `/forms`, `/reports`) | Supervisor | Supervisor tools | +| `/dashboard/supervisor` (+ `/events`, `/event-options`, `/at-the-door`, `/manual`, `/manual-registration`, `/payments`, `/coupons`, `/waitlist`, `/consent`, `/offline-scans`, `/email-attendees`, `/whatsapp-attendees`, `/forms`, `/reports`) | Supervisor | Supervisor tools | | `/dashboard/admin` (+ `/users`, `/registrations`, `/forms`, `/cashup`, `/cashup/[id]`, `/audit-log`, `/settings`) | Admin | Admin tools | diff --git a/backend/API_DOCUMENTATION.md b/backend/API_DOCUMENTATION.md index fe906b7..cd60d7a 100644 --- a/backend/API_DOCUMENTATION.md +++ b/backend/API_DOCUMENTATION.md @@ -21,6 +21,7 @@ Tokens are issued by `POST /api/users/login`. - [Coupons](#coupons) - [Parental consent](#parental-consent) - [Waitlist](#waitlist) +- [Offline scanning](#offline-scanning) - [Payments](#payments) - [Tickets](#tickets) - [Broadcasts (Email)](#broadcasts-email) @@ -278,6 +279,29 @@ For unauthenticated (guest) registration on events with `requiresAuth: false`: --- +## Offline scanning + +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| GET | `/api/scan-locks?eventId=` | staff+ | Active offline locks for an event | +| POST | `/api/scan-locks` | staff+ | Lock `{ eventId, sectionId?, deviceId, deviceName? }` to this device (409 if the scope is held elsewhere) | +| GET | `/api/scan-locks/:id/snapshot?deviceId=` | staff+ | Tickets valid in the lock's scope (lock holder only) | +| POST | `/api/scan-locks/:id/sync` | staff+ | `{ deviceId, scans: [{ clientScanId, qrCode, qty, scannedAt }] }` — idempotent; returns accepted, duplicates, conflicts | +| DELETE | `/api/scan-locks/:id` | staff+ | Release (`{ deviceId }`, lock holder only) | +| POST | `/api/scan-locks/:id/force-release` | supervisor+ | Release a lost device's lock | +| GET | `/api/scan-locks/reports?eventId=&unreviewed=` | supervisor+ | Sync reports | +| POST | `/api/scan-locks/reports/:id/review` | supervisor+ | Mark a report reviewed | + +How locks work: +- One device per scope. A whole-event lock (`sectionId` null) clashes with every section lock on that event. +- `POST /api/tickets/scan/:qrCode` now accepts `sectionId` and `deviceId`. It enforces the section on the server, and returns `423 { code: "SCAN_LOCKED" }` when another device holds a lock covering the ticket. + +How syncing works: +- Synced scans never redeem more than is left on a ticket. +- Conflicts are recorded in the sync report: `not_found`, `cancelled`, `wrong_scope`, `already_used`, `partly_used` and `consent`. +- Check-in messages are sent after the sync. +- Locks, releases, force-releases and syncs are written to the admin audit log. + ## Waitlist Events with `waitlistEnabled` (plus `waitlistOfferHours`, default 24, and `waitlistPartialOffers`, default true) take a queue for sold-out lines. diff --git a/backend/prisma/migrations/20261019134441_add_offline_scanning/migration.sql b/backend/prisma/migrations/20261019134441_add_offline_scanning/migration.sql new file mode 100644 index 0000000..5077cdb --- /dev/null +++ b/backend/prisma/migrations/20261019134441_add_offline_scanning/migration.sql @@ -0,0 +1,93 @@ +-- 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 'scan_lock_acquired'; +ALTER TYPE "AdminAuditAction" ADD VALUE 'scan_lock_released'; +ALTER TYPE "AdminAuditAction" ADD VALUE 'scan_lock_force_released'; +ALTER TYPE "AdminAuditAction" ADD VALUE 'offline_sync'; + +-- AlterTable +ALTER TABLE "TicketUsage" ADD COLUMN "clientScanId" TEXT, +ADD COLUMN "offline" BOOLEAN NOT NULL DEFAULT false, +ADD COLUMN "scanLockId" TEXT, +ADD COLUMN "syncedAt" TIMESTAMP(3); + +-- CreateTable +CREATE TABLE "ScanLock" ( + "id" TEXT NOT NULL, + "eventId" TEXT NOT NULL, + "sectionId" TEXT, + "deviceId" TEXT NOT NULL, + "deviceName" TEXT, + "userId" TEXT NOT NULL, + "lockedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "snapshotAt" TIMESTAMP(3), + "lastSyncAt" TIMESTAMP(3), + "releasedAt" TIMESTAMP(3), + "forceReleasedById" TEXT, + + CONSTRAINT "ScanLock_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "OfflineSyncReport" ( + "id" TEXT NOT NULL, + "scanLockId" TEXT NOT NULL, + "accepted" INTEGER NOT NULL DEFAULT 0, + "duplicates" INTEGER NOT NULL DEFAULT 0, + "conflicts" JSONB NOT NULL DEFAULT '[]', + "afterForceRelease" BOOLEAN NOT NULL DEFAULT false, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "reviewedAt" TIMESTAMP(3), + "reviewedById" TEXT, + + CONSTRAINT "OfflineSyncReport_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "ScanLock_eventId_releasedAt_idx" ON "ScanLock"("eventId", "releasedAt"); + +-- CreateIndex +CREATE INDEX "ScanLock_userId_idx" ON "ScanLock"("userId"); + +-- CreateIndex +CREATE INDEX "ScanLock_sectionId_idx" ON "ScanLock"("sectionId"); + +-- CreateIndex +CREATE INDEX "ScanLock_forceReleasedById_idx" ON "ScanLock"("forceReleasedById"); + +-- CreateIndex +CREATE INDEX "OfflineSyncReport_scanLockId_idx" ON "OfflineSyncReport"("scanLockId"); + +-- CreateIndex +CREATE INDEX "OfflineSyncReport_reviewedById_idx" ON "OfflineSyncReport"("reviewedById"); + +-- CreateIndex +CREATE UNIQUE INDEX "TicketUsage_clientScanId_key" ON "TicketUsage"("clientScanId"); + +-- AddForeignKey +ALTER TABLE "TicketUsage" ADD CONSTRAINT "TicketUsage_scanLockId_fkey" FOREIGN KEY ("scanLockId") REFERENCES "ScanLock"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_sectionId_fkey" FOREIGN KEY ("sectionId") REFERENCES "Section"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_forceReleasedById_fkey" FOREIGN KEY ("forceReleasedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "OfflineSyncReport" ADD CONSTRAINT "OfflineSyncReport_scanLockId_fkey" FOREIGN KEY ("scanLockId") REFERENCES "ScanLock"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "OfflineSyncReport" ADD CONSTRAINT "OfflineSyncReport_reviewedById_fkey" FOREIGN KEY ("reviewedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE; + diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 8be9755..ac058ec 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -103,8 +103,11 @@ model User { couponsApplied CouponRedemption[] @relation("CouponRedemptionAppliedBy") attendeeProfiles Attendee[] - heldTickets Ticket[] @relation("TicketHolder") + heldTickets Ticket[] @relation("TicketHolder") waitlistEntries WaitlistEntry[] + scanLocks ScanLock[] @relation("ScanLockOwner") + scanLocksForced ScanLock[] @relation("ScanLockForcedBy") + syncReportsDone OfflineSyncReport[] @relation("SyncReportReviewer") twoFactorChallenges TwoFactorChallenge[] trustedDevices TrustedDevice[] @@ -175,6 +178,7 @@ model Event { coupons CouponEvent[] consentRequests ConsentRequest[] waitlistEntries WaitlistEntry[] + scanLocks ScanLock[] @@index([createdById]) @@index([closedById]) @@ -370,13 +374,20 @@ model Ticket { } model TicketUsage { - id String @id @default(uuid()) + id String @id @default(uuid()) ticketId String scannedById String - scannedAt DateTime @default(now()) - quantityRedeemed Int @default(1) - ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Restrict) - scannedBy User @relation(fields: [scannedById], references: [id], onDelete: Restrict) + scannedAt DateTime @default(now()) + quantityRedeemed Int @default(1) + // Offline scanning: the device's id for the scan (makes syncing idempotent), and + // the offline lock it was made under. + clientScanId String? @unique + offline Boolean @default(false) + scanLockId String? + syncedAt DateTime? + ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Restrict) + scannedBy User @relation(fields: [scannedById], references: [id], onDelete: Restrict) + scanLock ScanLock? @relation(fields: [scanLockId], references: [id], onDelete: SetNull) @@index([ticketId]) @@index([scannedAt]) @@ -461,6 +472,10 @@ enum AdminAuditAction { consent_override consent_rerequested medical_list_viewed + scan_lock_acquired + scan_lock_released + scan_lock_force_released + offline_sync } // Append-only audit trail for admin/supervisor-initiated actions with money or @@ -601,6 +616,7 @@ model Section { event Event @relation(fields: [eventId], references: [id], onDelete: Cascade) allowedOptions SectionOption[] + scanLocks ScanLock[] @@index([eventId]) } @@ -1085,3 +1101,51 @@ model WaitlistEntry { @@index([userId]) @@index([registrationId]) } + +// ─── Offline scanning ───────────────────────────────────────────────────────── + +// Locks a section (or the whole event, sectionId null) to one device for offline +// scanning, so two devices can never redeem the same ticket while offline. +// One active (releasedAt null) lock per scope — enforced in utils/scanLocks.js. +model ScanLock { + id String @id @default(uuid()) + eventId String + sectionId String? + deviceId String + deviceName String? + userId String + lockedAt DateTime @default(now()) + snapshotAt DateTime? + lastSyncAt DateTime? + releasedAt DateTime? + forceReleasedById String? + event Event @relation(fields: [eventId], references: [id], onDelete: Cascade) + section Section? @relation(fields: [sectionId], references: [id], onDelete: Cascade) + user User @relation("ScanLockOwner", fields: [userId], references: [id], onDelete: Cascade) + forceReleasedBy User? @relation("ScanLockForcedBy", fields: [forceReleasedById], references: [id], onDelete: SetNull) + usages TicketUsage[] + syncReports OfflineSyncReport[] + + @@index([eventId, releasedAt]) + @@index([userId]) + @@index([sectionId]) + @@index([forceReleasedById]) +} + +// One sync of queued offline scans; `conflicts` lists scans that needed a person to look. +model OfflineSyncReport { + id String @id @default(uuid()) + scanLockId String + accepted Int @default(0) + duplicates Int @default(0) + conflicts Json @default("[]") + afterForceRelease Boolean @default(false) + createdAt DateTime @default(now()) + reviewedAt DateTime? + reviewedById String? + scanLock ScanLock @relation(fields: [scanLockId], references: [id], onDelete: Cascade) + reviewedBy User? @relation("SyncReportReviewer", fields: [reviewedById], references: [id], onDelete: SetNull) + + @@index([scanLockId]) + @@index([reviewedById]) +} diff --git a/backend/src/controllers/scanLockController.js b/backend/src/controllers/scanLockController.js new file mode 100644 index 0000000..b53a494 --- /dev/null +++ b/backend/src/controllers/scanLockController.js @@ -0,0 +1,151 @@ +const prisma = require('../config/db'); +const { safeErrorMessage } = require('../utils/errorUtils'); +const { logAdminAction } = require('../utils/adminAudit'); +const { getClientIp } = require('../utils/requestUtils'); +const { LOCK_INCLUDE, activeLocks, acquireLock, snapshotFor, syncScans } = require('../utils/scanLocks'); + +const SUPERVISORS = ['admin', 'supervisor']; +const fail = (res, error) => res.status(error.statusCode || (res.statusCode === 200 ? 400 : res.statusCode)).json({ message: safeErrorMessage(error) }); +const audit = (req, action, lock, metadata = {}) => logAdminAction({ + actorId: req.user.id, actorRole: req.user.role, action, targetType: 'ScanLock', targetId: lock.id, + metadata: { eventId: lock.eventId, sectionId: lock.sectionId, deviceName: lock.deviceName, ...metadata }, + ip: getClientIp(req), +}); + +const lockView = (l) => ({ + id: l.id, eventId: l.eventId, sectionId: l.sectionId, sectionName: l.section?.name || null, + deviceId: l.deviceId, deviceName: l.deviceName, user: l.user, lockedAt: l.lockedAt, + snapshotAt: l.snapshotAt, lastSyncAt: l.lastSyncAt, releasedAt: l.releasedAt, +}); + +/** The lock, if the caller is the person holding it on this device. */ +async function ownLock(req, res) { + const lock = await prisma.scanLock.findUnique({ where: { id: req.params.id }, include: LOCK_INCLUDE }); + if (!lock) { res.status(404); throw new Error('Offline lock not found'); } + const deviceId = req.body?.deviceId || req.query?.deviceId; + if (lock.userId !== req.user.id || lock.deviceId !== deviceId) { res.status(403); throw new Error('This offline lock belongs to another device.'); } + return lock; +} + +// @desc Active offline locks for an event +// @route GET /api/scan-locks?eventId= +// @access Private/Staff +const listLocks = async (req, res) => { + try { + if (!req.query.eventId) { res.status(400); throw new Error('eventId is required'); } + res.json((await activeLocks(String(req.query.eventId))).map(lockView)); + } catch (error) { + fail(res, error); + } +}; + +// @desc Lock a section (or the whole event) to this device for offline scanning +// @route POST /api/scan-locks { eventId, sectionId?, deviceId, deviceName? } +// @access Private/Staff +const createLock = async (req, res) => { + try { + const { eventId, sectionId, deviceId, deviceName } = req.body || {}; + if (!eventId) { res.status(400); throw new Error('eventId is required'); } + const lock = await acquireLock({ eventId, sectionId: sectionId || null, deviceId, deviceName, userId: req.user.id }); + audit(req, 'scan_lock_acquired', lock); + res.status(201).json(lockView(lock)); + } catch (error) { + fail(res, error); + } +}; + +// @desc Download the tickets valid for this lock, for offline scanning +// @route GET /api/scan-locks/:id/snapshot?deviceId= +// @access Private/Staff (lock holder) +const getSnapshot = async (req, res) => { + try { + const lock = await ownLock(req, res); + if (lock.releasedAt) { res.status(410); throw new Error('This offline lock has been released.'); } + res.json({ lock: lockView(lock), ...(await snapshotFor(lock)) }); + } catch (error) { + fail(res, error); + } +}; + +// @desc Upload scans made offline +// @route POST /api/scan-locks/:id/sync { deviceId, scans: [{ clientScanId, qrCode, qty, scannedAt }] } +// @access Private/Staff (lock holder — also after a release, so nothing made offline is lost) +const syncLock = async (req, res) => { + try { + const lock = await ownLock(req, res); + const result = await syncScans(lock, req.body?.scans); + if (result.accepted || result.conflicts.length) { + audit(req, 'offline_sync', lock, { accepted: result.accepted, conflicts: result.conflicts.length, duplicates: result.duplicates, afterForceRelease: !!lock.forceReleasedById }); + } + res.json({ accepted: result.accepted, duplicates: result.duplicates, conflicts: result.conflicts, reportId: result.report.id, released: !!lock.releasedAt }); + } catch (error) { + fail(res, error); + } +}; + +// @desc End offline mode (the device should sync first) +// @route DELETE /api/scan-locks/:id { deviceId } +// @access Private/Staff (lock holder) +const releaseLock = async (req, res) => { + try { + const lock = await ownLock(req, res); + if (!lock.releasedAt) { + await prisma.scanLock.update({ where: { id: lock.id }, data: { releasedAt: new Date() } }); + audit(req, 'scan_lock_released', lock); + } + res.json({ message: 'Offline mode ended.' }); + } catch (error) { + fail(res, error); + } +}; + +// @desc Release someone else's lock (e.g. a lost or flat phone) +// @route POST /api/scan-locks/:id/force-release +// @access Private/Supervisor +const forceRelease = async (req, res) => { + try { + const lock = await prisma.scanLock.findUnique({ where: { id: req.params.id }, include: LOCK_INCLUDE }); + if (!lock) { res.status(404); throw new Error('Offline lock not found'); } + if (lock.releasedAt) return res.json({ message: 'Already released.' }); + await prisma.scanLock.update({ where: { id: lock.id }, data: { releasedAt: new Date(), forceReleasedById: req.user.id } }); + audit(req, 'scan_lock_force_released', lock, { heldBy: lock.user?.name }); + res.json({ message: `Released. If ${lock.user?.name || 'that device'} reconnects, its offline scans will still sync and be flagged for review.` }); + } catch (error) { + fail(res, error); + } +}; + +// @desc Offline sync reports for an event (with anything that needs review) +// @route GET /api/scan-locks/reports?eventId=&unreviewed=true +// @access Private/Supervisor +const listReports = async (req, res) => { + try { + const where = { + scanLock: { eventId: String(req.query.eventId || '') }, + ...(req.query.unreviewed === 'true' ? { reviewedAt: null } : {}), + }; + const reports = await prisma.offlineSyncReport.findMany({ + where, + include: { scanLock: { include: LOCK_INCLUDE }, reviewedBy: { select: { name: true } } }, + orderBy: { createdAt: 'desc' }, + take: 200, + }); + res.json(reports.map(r => ({ ...r, scanLock: lockView(r.scanLock) }))); + } catch (error) { + fail(res, error); + } +}; + +// @desc Mark a sync report as reviewed +// @route POST /api/scan-locks/reports/:id/review +// @access Private/Supervisor +const reviewReport = async (req, res) => { + try { + const report = await prisma.offlineSyncReport.update({ where: { id: req.params.id }, data: { reviewedAt: new Date(), reviewedById: req.user.id } }); + res.json(report); + } catch (error) { + fail(res, error); + } +}; + +module.exports = { SUPERVISORS, listLocks, createLock, getSnapshot, syncLock, releaseLock, forceRelease, listReports, reviewReport }; diff --git a/backend/src/controllers/ticketController.js b/backend/src/controllers/ticketController.js index 9a8b95c..988f10f 100644 --- a/backend/src/controllers/ticketController.js +++ b/backend/src/controllers/ticketController.js @@ -372,6 +372,27 @@ const scanTicket = async (req, res) => { return res.status(400).json({ message: 'Ticket belongs to a different event', ticket }); } + // Section checks used to happen only in the browser; enforce them here too. + const sectionId = String((req.query?.sectionId || req.body?.sectionId) || '').trim() || null; + if (sectionId) { + const section = await prisma.section.findUnique({ where: { id: sectionId }, include: { allowedOptions: true } }); + if (!section || section.eventId !== ticket.eventId) { + return res.status(400).json({ message: 'Section not found for this event', ticket }); + } + if (!section.allowedOptions.some(o => o.eventOptionId === r.eventOptionId)) { + return res.status(400).json({ message: 'This ticket is not valid for this section', ticket }); + } + } + + // A section (or the whole event) locked to another device for offline scanning + // can't be scanned online — those scans would be invisible to the offline device. + const { blockingLock } = require('../utils/scanLocks'); + const lock = await blockingLock({ eventId: ticket.eventId, optionId: r.eventOptionId }, { sectionId, deviceId: req.body?.deviceId || null }); + if (lock) { + const scope = lock.section ? `"${lock.section.name}"` : 'This event'; + return res.status(423).json({ message: `${scope} is offline-locked by ${lock.user?.name || 'another device'}${lock.deviceName ? ` on ${lock.deviceName}` : ''}. Scan it on that device, or ask a supervisor to release the lock.`, code: 'SCAN_LOCKED' }); + } + // Compute how many have already been redeemed const totalRedeemed = (ticket.usages || []).reduce((s, u) => s + (u.quantityRedeemed || 1), 0); const remaining = (ticket.quantity || 1) - totalRedeemed; diff --git a/backend/src/index.js b/backend/src/index.js index 2913e4a..6054093 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -178,6 +178,7 @@ app.use('/api/admin', adminRoutes); app.use('/api/coupons', require('./routes/couponRoutes')); app.use('/api/consent', require('./routes/consentRoutes')); app.use('/api/waitlist', require('./routes/waitlistRoutes')); +app.use('/api/scan-locks', require('./routes/scanLockRoutes')); app.use('/api/backups', backupRoutes); // Pre-warm the settings cache so synchronous helpers have DB values from startup @@ -634,6 +635,20 @@ app.get('/docs', async (req, res) => { ]}, ]}, + { title: 'Offline scanning', base: '/api/scan-locks', endpoints: [ + { method:'GET', path:'/api/scan-locks', auth:'staff+', desc:'Active offline locks for an event (?eventId=)' }, + { method:'POST', path:'/api/scan-locks', auth:'staff+', desc:'Lock a section (or the whole event) to this device for offline scanning', + request:{ body:{ eventId:'ev-uuid-...', sectionId:'sec-uuid-...', deviceId:'device-uuid', deviceName:'Chrome on Android' }}, + responses:[{ status:201, desc:'Locked', body:{ id:'lock-uuid-...', sectionName:'Main hall' }}, { status:409, desc:'Held elsewhere', body:{ message:'"Main hall" is offline-locked by Ann on Chrome on Android.' }}]}, + { method:'GET', path:'/api/scan-locks/:id/snapshot', auth:'staff+', desc:'Tickets valid in the lock scope, for the device to keep offline (lock holder, ?deviceId=)' }, + { method:'POST', path:'/api/scan-locks/:id/sync', auth:'staff+', desc:'Upload offline scans (idempotent by clientScanId; capped at what is left on each ticket)', + request:{ body:{ deviceId:'device-uuid', scans:[{ clientScanId:'scan-uuid', qrCode:'qr-uuid', qty:1, scannedAt:'2025-07-10T08:15:00.000Z' }] }}, + responses:[{ status:200, desc:'Synced', body:{ accepted:1, duplicates:0, conflicts:[] }}]}, + { method:'DELETE', path:'/api/scan-locks/:id', auth:'staff+', desc:'End offline mode (lock holder)' }, + { method:'POST', path:'/api/scan-locks/:id/force-release', auth:'supervisor+', desc:'Release a lost device\'s lock' }, + { method:'GET', path:'/api/scan-locks/reports', auth:'supervisor+', desc:'Offline sync reports for an event' }, + { method:'POST', path:'/api/scan-locks/reports/:id/review', auth:'supervisor+', desc:'Mark a sync report reviewed' }, + ]}, { title: 'Waitlist', base: '/api/waitlist', endpoints: [ { method:'POST', path:'/api/waitlist', auth:'public', desc:'Join the waitlist for a sold-out line (login needed when the event requires it)', request:{ body:{ eventId:'ev-uuid-...', eventOptionId:'opt-uuid-...', quantity:2 }}, diff --git a/backend/src/routes/scanLockRoutes.js b/backend/src/routes/scanLockRoutes.js new file mode 100644 index 0000000..40ac95d --- /dev/null +++ b/backend/src/routes/scanLockRoutes.js @@ -0,0 +1,15 @@ +const express = require('express'); +const router = express.Router(); +const { listLocks, createLock, getSnapshot, syncLock, releaseLock, forceRelease, listReports, reviewReport } = require('../controllers/scanLockController'); +const { protect, staff, supervisor } = require('../middleware/authMiddleware'); + +router.get('/', protect, staff, listLocks); +router.post('/', protect, staff, createLock); +router.get('/reports', protect, supervisor, listReports); +router.post('/reports/:id/review', protect, supervisor, reviewReport); +router.get('/:id/snapshot', protect, staff, getSnapshot); +router.post('/:id/sync', protect, staff, syncLock); +router.post('/:id/force-release', protect, supervisor, forceRelease); +router.delete('/:id', protect, staff, releaseLock); + +module.exports = router; diff --git a/backend/src/utils/scanLocks.js b/backend/src/utils/scanLocks.js new file mode 100644 index 0000000..80079dc --- /dev/null +++ b/backend/src/utils/scanLocks.js @@ -0,0 +1,213 @@ +/** + * Offline scanning — locks, snapshots and syncing. + * + * Rules: + * - Offline mode is per section (or the whole event), and only one device may hold a + * scope at a time: while offline, devices can't see each other's scans, so two + * devices on the same scope could redeem one ticket twice. A whole-event lock clashes + * with every section of that event, and a section lock with the whole event. + * - While a scope is locked, other devices can't scan it online either. + * - The lock holder downloads a snapshot of valid tickets; scans made offline are + * queued on the device and synced later. Syncing is idempotent (each scan carries a + * clientScanId) and never redeems more than is left on a ticket. + * - Anything that needs a person to look — unknown ticket, cancelled registration, used + * up, outside the locked scope, consent not given — goes into an OfflineSyncReport. + * - A supervisor can force-release a lock (lost phone). If that device syncs later its + * scans are still recorded, and the report is flagged. + */ + +const prisma = require('../config/db'); + +function lockError(message, statusCode = 400) { + const err = new Error(message); + err.statusCode = statusCode; + return err; +} + +// ─── Pure helpers ───────────────────────────────────────────────────────────── + +/** Whether a new lock on `sectionId` (null = whole event) clashes with `existing`. */ +function locksClash(existing, sectionId) { + if (!existing.sectionId || !sectionId) return true; + return existing.sectionId === sectionId; +} + +/** + * Whether `lock` covers a scan of a ticket with option `optionId`. When the scanner has + * picked a section, only a lock on that section (or the whole event) covers it; with no + * section picked, any lock on a section that admits the ticket does. + * @param {object} lock - { sectionId, section?: { allowedOptions: [{ eventOptionId }] } } + */ +function lockCovers(lock, { sectionId = null, optionId }) { + if (!lock.sectionId) return true; + if (sectionId) return sectionId === lock.sectionId; + return (lock.section?.allowedOptions || []).some(o => o.eventOptionId === optionId); +} + +/** + * What to do with one synced scan, given the ticket as the server sees it now. Pure. + * @param {object|null} ticket - { remaining, cancelled, inScope, consentOk } + * @param {number} qty - quantity the device redeemed + * @returns {{ redeem: number, conflict: string|null }} + */ +function judgeSyncedScan(ticket, qty) { + if (!ticket) return { redeem: 0, conflict: 'not_found' }; + if (ticket.cancelled) return { redeem: 0, conflict: 'cancelled' }; + if (!ticket.inScope) return { redeem: 0, conflict: 'wrong_scope' }; + if (ticket.remaining <= 0) return { redeem: 0, conflict: 'already_used' }; + const redeem = Math.min(Math.max(1, qty || 1), ticket.remaining); + if (!ticket.consentOk) return { redeem, conflict: 'consent' }; + return { redeem, conflict: redeem < (qty || 1) ? 'partly_used' : null }; +} + +const CONFLICT_TEXT = { + not_found: 'Ticket not found (possibly transferred or reissued)', + cancelled: 'Registration was cancelled', + wrong_scope: 'Ticket is not valid for this section', + already_used: 'Ticket had already been fully used', + partly_used: 'Fewer places were left than were checked in offline', + consent: 'Checked in without parental consent', +}; + +// ─── Database helpers ───────────────────────────────────────────────────────── + +const LOCK_INCLUDE = { + section: { include: { allowedOptions: true } }, + user: { select: { id: true, name: true } }, +}; + +async function activeLocks(eventId, db = prisma) { + return db.scanLock.findMany({ where: { eventId, releasedAt: null }, include: LOCK_INCLUDE, orderBy: { lockedAt: 'asc' } }); +} + +/** Locks a scope to this device. Re-locking by the same device and person returns the existing lock. */ +async function acquireLock({ eventId, sectionId = null, deviceId, deviceName, userId }) { + if (!deviceId || typeof deviceId !== 'string' || deviceId.length > 100) throw lockError('A device id is required'); + return prisma.$transaction(async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${'scanlock:' + eventId}))`; + const event = await tx.event.findUnique({ where: { id: eventId } }); + if (!event) throw lockError('Event not found', 404); + if (sectionId) { + const section = await tx.section.findUnique({ where: { id: sectionId } }); + if (!section || section.eventId !== eventId) throw lockError('Section not found for this event', 404); + } + const existing = await activeLocks(eventId, tx); + const same = existing.find(l => (l.sectionId || null) === (sectionId || null) && l.deviceId === deviceId && l.userId === userId); + if (same) return same; + const clash = existing.find(l => locksClash(l, sectionId)); + if (clash) { + const scope = clash.section ? `"${clash.section.name}"` : 'the whole event'; + throw lockError(`${scope} is offline-locked by ${clash.user.name}${clash.deviceName ? ` on ${clash.deviceName}` : ''}.`, 409); + } + return tx.scanLock.create({ data: { eventId, sectionId: sectionId || null, deviceId, deviceName: deviceName ? String(deviceName).slice(0, 100) : null, userId }, include: LOCK_INCLUDE }); + }); +} + +/** + * The lock (other than the scanner's own device) that stops this online scan, or null. + * @param {object} ticket - { eventId, optionId } + */ +async function blockingLock(ticket, { sectionId = null, deviceId = null } = {}) { + const locks = await activeLocks(ticket.eventId); + return locks.find(l => l.deviceId !== deviceId && lockCovers(l, { sectionId, optionId: ticket.optionId })) || null; +} + +/** Tickets valid in a lock's scope, for the device to keep offline. */ +async function snapshotFor(lock) { + const optionIds = lock.section ? lock.section.allowedOptions.map(o => o.eventOptionId) : null; + const tickets = await prisma.ticket.findMany({ + where: { + eventId: lock.eventId, + registrationOption: { registration: { status: { not: 'cancelled' } }, ...(optionIds ? { eventOptionId: { in: optionIds } } : {}) }, + }, + include: { + usages: { select: { quantityRedeemed: true } }, + attendee: { select: { name: true } }, + user: { select: { name: true } }, + registrationOption: { include: { eventOption: { select: { id: true, name: true, isMainTicket: true } }, variant: { select: { name: true } } } }, + }, + }); + const { consentStatusForTickets } = require('./consent'); + const consent = await consentStatusForTickets(tickets.map(t => t.id)); + const snapshotAt = new Date(); + await prisma.scanLock.update({ where: { id: lock.id }, data: { snapshotAt } }); + return { + snapshotAt, + tickets: tickets.map(t => { + const redeemed = t.usages.reduce((s, u) => s + (u.quantityRedeemed || 1), 0); + return { + id: t.id, + qrCode: t.qrCode, + holder: t.attendee?.name || t.user?.name || '', + bookedBy: t.attendee ? t.user?.name || '' : '', + option: t.registrationOption.eventOption.name, + variant: t.registrationOption.variant?.name || null, + quantity: t.quantity || 1, + remaining: Math.max(0, (t.quantity || 1) - redeemed), + consentStatus: consent.get(t.id) || 'not_required', + }; + }), + }; +} + +/** + * Records queued offline scans. Each scan: { clientScanId, qrCode, qty, scannedAt }. + * @returns {Promise<{ accepted, duplicates, conflicts, report }>} + */ +async function syncScans(lock, scans) { + const results = { accepted: 0, duplicates: 0, conflicts: [] }; + const optionIds = lock.section ? new Set(lock.section.allowedOptions.map(o => o.eventOptionId)) : null; + const { consentStatusForTickets } = require('./consent'); + const checkIns = []; + + for (const scan of (scans || []).slice(0, 2000)) { + const clientScanId = String(scan?.clientScanId || '').slice(0, 100); + if (!clientScanId) continue; + if (await prisma.ticketUsage.findUnique({ where: { clientScanId } })) { results.duplicates += 1; continue; } + + const qty = Math.max(1, parseInt(scan.qty, 10) || 1); + const scannedAt = scan.scannedAt && !isNaN(new Date(scan.scannedAt)) ? new Date(scan.scannedAt) : new Date(); + const ticket = await prisma.ticket.findUnique({ + where: { qrCode: String(scan.qrCode || '') }, + include: { usages: true, registrationOption: { include: { registration: { select: { status: true } }, eventOption: { select: { isMainTicket: true } } } } }, + }); + let state = null; + if (ticket && ticket.eventId === lock.eventId) { + const redeemed = ticket.usages.reduce((s, u) => s + (u.quantityRedeemed || 1), 0); + const consent = (await consentStatusForTickets([ticket.id])).get(ticket.id); + state = { + remaining: (ticket.quantity || 1) - redeemed, + cancelled: ticket.registrationOption.registration.status === 'cancelled', + inScope: !optionIds || optionIds.has(ticket.registrationOption.eventOptionId), + consentOk: ['not_required', 'given'].includes(consent), + }; + } + const verdict = judgeSyncedScan(state, qty); + if (verdict.redeem > 0) { + await prisma.ticketUsage.create({ + data: { ticketId: ticket.id, scannedById: lock.userId, scannedAt, quantityRedeemed: verdict.redeem, clientScanId, offline: true, scanLockId: lock.id, syncedAt: new Date() }, + }); + await prisma.ticket.update({ where: { id: ticket.id }, data: { isUsed: state.remaining - verdict.redeem <= 0, updatedAt: new Date() } }); + results.accepted += 1; + if (ticket.registrationOption.eventOption.isMainTicket) { + checkIns.push({ ticketId: ticket.id, qty: verdict.redeem, total: (ticket.quantity || 1) - state.remaining + verdict.redeem, left: state.remaining - verdict.redeem }); + } + } + if (verdict.conflict) { + results.conflicts.push({ clientScanId, qrCode: scan.qrCode, ticketId: ticket?.id || null, qty, redeemed: verdict.redeem, scannedAt, reason: verdict.conflict, message: CONFLICT_TEXT[verdict.conflict] }); + } + } + + await prisma.scanLock.update({ where: { id: lock.id }, data: { lastSyncAt: new Date() } }); + const report = await prisma.offlineSyncReport.create({ + data: { scanLockId: lock.id, accepted: results.accepted, duplicates: results.duplicates, conflicts: results.conflicts, afterForceRelease: !!lock.forceReleasedById }, + }); + + // Check-in confirmations go out after sync, not at the moment of the offline scan. + const { sendCheckInEmails } = require('./notifications'); + for (const c of checkIns) sendCheckInEmails(c.ticketId, c.qty, c.total, c.left).catch(() => {}); + + return { ...results, report }; +} + +module.exports = { lockError, locksClash, lockCovers, judgeSyncedScan, CONFLICT_TEXT, LOCK_INCLUDE, activeLocks, acquireLock, blockingLock, snapshotFor, syncScans }; diff --git a/backend/tests/scanLocks.test.js b/backend/tests/scanLocks.test.js new file mode 100644 index 0000000..4bc5100 --- /dev/null +++ b/backend/tests/scanLocks.test.js @@ -0,0 +1,54 @@ +const { locksClash, lockCovers, judgeSyncedScan } = require('../src/utils/scanLocks'); + +describe('locksClash', () => { + test('a whole-event lock clashes with everything', () => { + expect(locksClash({ sectionId: null }, 'hall')).toBe(true); + expect(locksClash({ sectionId: 'hall' }, null)).toBe(true); + }); + + test('section locks only clash with the same section', () => { + expect(locksClash({ sectionId: 'hall' }, 'hall')).toBe(true); + expect(locksClash({ sectionId: 'hall' }, 'dinner')).toBe(false); + }); +}); + +describe('lockCovers', () => { + const dinnerLock = { sectionId: 'dinner', section: { allowedOptions: [{ eventOptionId: 'meal' }] } }; + + test('a whole-event lock covers every scan', () => { + expect(lockCovers({ sectionId: null }, { sectionId: 'x', optionId: 'y' })).toBe(true); + }); + + test('with a section picked, only that section is covered', () => { + expect(lockCovers(dinnerLock, { sectionId: 'dinner', optionId: 'meal' })).toBe(true); + expect(lockCovers(dinnerLock, { sectionId: 'hall', optionId: 'meal' })).toBe(false); + }); + + test('with no section picked, tickets the locked section admits are covered', () => { + expect(lockCovers(dinnerLock, { optionId: 'meal' })).toBe(true); + expect(lockCovers(dinnerLock, { optionId: 'entry' })).toBe(false); + }); +}); + +describe('judgeSyncedScan', () => { + const ok = { remaining: 2, cancelled: false, inScope: true, consentOk: true }; + + test('records a normal scan', () => { + expect(judgeSyncedScan(ok, 1)).toEqual({ redeem: 1, conflict: null }); + }); + + test('never redeems more than is left', () => { + expect(judgeSyncedScan(ok, 3)).toEqual({ redeem: 2, conflict: 'partly_used' }); + expect(judgeSyncedScan({ ...ok, remaining: 0 }, 1)).toEqual({ redeem: 0, conflict: 'already_used' }); + }); + + test('flags unknown, cancelled and out-of-scope tickets without recording them', () => { + expect(judgeSyncedScan(null, 1)).toEqual({ redeem: 0, conflict: 'not_found' }); + expect(judgeSyncedScan({ ...ok, cancelled: true }, 1)).toEqual({ redeem: 0, conflict: 'cancelled' }); + expect(judgeSyncedScan({ ...ok, inScope: false }, 1)).toEqual({ redeem: 0, conflict: 'wrong_scope' }); + }); + + test('records but flags a check-in without consent', () => { + expect(judgeSyncedScan({ ...ok, consentOk: false }, 1)).toEqual({ redeem: 1, conflict: 'consent' }); + }); +}); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 23f2de1..0ac47e3 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -31,6 +31,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "date-fns": "^4.1.0", + "idb": "^8.0.4", "lucide-react": "^0.536.0", "next": "^15.5.24", "qrcode": "^1.5.4", @@ -869,9 +870,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -888,9 +886,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -907,9 +902,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -926,9 +918,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -945,9 +934,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -964,9 +950,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -983,9 +966,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -1002,9 +982,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -1021,9 +998,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1046,9 +1020,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1071,9 +1042,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1096,9 +1064,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1121,9 +1086,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1146,9 +1108,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1171,9 +1130,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1196,9 +1152,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1455,9 +1408,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1474,9 +1424,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1493,9 +1440,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1512,9 +1456,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -6865,6 +6806,12 @@ "node": ">= 6" } }, + "node_modules/idb": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/idb/-/idb-8.0.4.tgz", + "integrity": "sha512-jd0ITCrN+Zah4J7R/Z2jnR3W7A4BXDAjmo62MwWuSjxCiueUAf7X5rbodEdidWzeknwXHmLpdZkoiiCppNi30Q==", + "license": "ISC" + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", diff --git a/frontend/package.json b/frontend/package.json index 3d96f86..04ffd61 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -32,6 +32,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "date-fns": "^4.1.0", + "idb": "^8.0.4", "lucide-react": "^0.536.0", "next": "^15.5.24", "qrcode": "^1.5.4", diff --git a/frontend/public/sw.js b/frontend/public/sw.js new file mode 100644 index 0000000..5d99d6a --- /dev/null +++ b/frontend/public/sw.js @@ -0,0 +1,67 @@ +/* + * Service worker for offline ticket scanning. + * + * Only the scanner page and the static files it needs are cached: + * - /_next/static/* (hashed, never change): cache-first. + * - The scanner page itself: network-first, falling back to the cached copy offline. + * - The page can ask (postMessage { type: 'cache-urls', urls }) for the files it has + * loaded to be cached up front, so it works offline straight after "Enable offline mode". + * API calls are never cached — offline scans go through IndexedDB instead. + */ +const CACHE = 'hope-scanner-v1'; +const SCANNER_PATH = '/dashboard/staff/ticket-scanning'; + +self.addEventListener('install', () => self.skipWaiting()); +self.addEventListener('activate', (event) => { + event.waitUntil((async () => { + const keys = await caches.keys(); + await Promise.all(keys.filter(k => k.startsWith('hope-scanner-') && k !== CACHE).map(k => caches.delete(k))); + await self.clients.claim(); + })()); +}); + +self.addEventListener('message', (event) => { + const data = event.data || {}; + if (data.type !== 'cache-urls' || !Array.isArray(data.urls)) return; + event.waitUntil((async () => { + const cache = await caches.open(CACHE); + const sameOrigin = data.urls.filter(u => { + try { return new URL(u, self.location.origin).origin === self.location.origin; } catch { return false; } + }); + await Promise.all(sameOrigin.map(u => cache.add(u).catch(() => {}))); + })()); +}); + +self.addEventListener('fetch', (event) => { + const req = event.request; + if (req.method !== 'GET') return; + const url = new URL(req.url); + if (url.origin !== self.location.origin) return; + + if (url.pathname.startsWith('/_next/static/')) { + event.respondWith((async () => { + const cache = await caches.open(CACHE); + const hit = await cache.match(req); + if (hit) return hit; + const res = await fetch(req); + if (res.ok) cache.put(req, res.clone()); + return res; + })()); + return; + } + + if (url.pathname === SCANNER_PATH) { + event.respondWith((async () => { + const cache = await caches.open(CACHE); + try { + const res = await fetch(req); + if (res.ok) cache.put(SCANNER_PATH, res.clone()); + return res; + } catch { + const hit = (await cache.match(req, { ignoreSearch: true })) || (await cache.match(SCANNER_PATH)); + if (hit) return hit; + throw new Error('offline and not cached'); + } + })()); + } +}); diff --git a/frontend/src/app/dashboard/admin/audit-log/page.tsx b/frontend/src/app/dashboard/admin/audit-log/page.tsx index f8e70ff..d745c38 100644 --- a/frontend/src/app/dashboard/admin/audit-log/page.tsx +++ b/frontend/src/app/dashboard/admin/audit-log/page.tsx @@ -25,6 +25,10 @@ const ACTIONS = [ "consent_override", "consent_rerequested", "medical_list_viewed", + "scan_lock_acquired", + "scan_lock_released", + "scan_lock_force_released", + "offline_sync", ] as const; const ACTION_LABELS: Record = { @@ -44,6 +48,10 @@ const ACTION_LABELS: Record = { consent_override: "Consent overridden at check-in", consent_rerequested: "Consent re-requested", medical_list_viewed: "Medical list viewed", + scan_lock_acquired: "Offline scanning started", + scan_lock_released: "Offline scanning ended", + scan_lock_force_released: "Offline lock force-released", + offline_sync: "Offline scans synced", }; interface AuditLogEntry { diff --git a/frontend/src/app/dashboard/admin/page.tsx b/frontend/src/app/dashboard/admin/page.tsx index dd26c53..62df68f 100644 --- a/frontend/src/app/dashboard/admin/page.tsx +++ b/frontend/src/app/dashboard/admin/page.tsx @@ -8,7 +8,7 @@ import { useStableState } from "@/hooks/useStableState"; import { useVisiblePolling } from "@/hooks/useVisiblePolling"; import { Calendar, Banknote, Gift, Users, Ticket, QrCode, ClipboardList, - UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen, History, TicketPercent, ShieldCheck, ListChecks, + UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen, History, TicketPercent, ShieldCheck, ListChecks, WifiOff, } from "lucide-react"; import { StatCard, StatCardRow } from "@/components/shared/StatCard"; import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile"; @@ -27,6 +27,7 @@ const QUICK_ACTIONS = [ { href: "/dashboard/supervisor/manual", label: "Manual registration", description: "Register a guest and issue tickets", icon: UserPlus }, { href: "/dashboard/supervisor/at-the-door", label: "At the door", description: "Walk-ins, payments, ticket printing", icon: DoorOpen }, { href: "/dashboard/supervisor/payments", label: "Payments & donations", description: "Manual payments and assignment", icon: Wallet }, + { href: "/dashboard/supervisor/offline-scans", label: "Offline scanning", description: "Devices scanning offline and their synced scans", icon: WifiOff }, { href: "/dashboard/supervisor/waitlist", label: "Waitlist", description: "People waiting for sold-out tickets", icon: ListChecks }, { href: "/dashboard/supervisor/consent", label: "Parental consent", description: "Youth events: consent status and medical list", icon: ShieldCheck }, { href: "/dashboard/supervisor/coupons", label: "Coupon codes", description: "Discounts for staff, leaders and promotions", icon: TicketPercent }, diff --git a/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx b/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx index 8872ce9..3900298 100644 --- a/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx +++ b/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx @@ -7,6 +7,9 @@ import { apiFetch } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { useRouter } from "next/navigation"; import { QrCode } from "lucide-react"; +import { useOfflineScanning } from "@/components/scanner/useOfflineScanning"; +import { OfflineScanPanel } from "@/components/scanner/OfflineScanPanel"; +import type { SnapshotTicket } from "@/lib/offlineScan"; export default function TicketScanningPage() { const router = useRouter(); @@ -17,6 +20,7 @@ export default function TicketScanningPage() { const [alreadyUsedModal, setAlreadyUsedModal] = useState<{ message: string; ticket?: any } | null>(null); const [errorModal, setErrorModal] = useState(null); const { token, user } = useAuth(); + const offline = useOfflineScanning(token); const [recentScans, setRecentScans] = useState([]); const [stats, setStats] = useState(null); const [loadingStats, setLoadingStats] = useState(false); @@ -34,6 +38,7 @@ export default function TicketScanningPage() { qrCode: string; ticket: any; remaining: number; + offlineTicket?: SnapshotTicket; // scanned against the downloaded list (offline mode) } | null>(null); const [confirmQty, setConfirmQty] = useState(1); // Youth events: the preview says whether parental consent allows check-in. @@ -96,6 +101,16 @@ export default function TicketScanningPage() { })(); }, [selectedEventId, token]); + // In offline mode the event and section are fixed to the locked scope. + useEffect(() => { + if (!offline.lock) return; + setSelectedEventId(offline.lock.eventId); + }, [offline.lock]); + useEffect(() => { + if (!offline.lock) return; + setSelectedSectionId(offline.lock.sectionId || "all"); + }, [offline.lock, sections]); + // Bug fix: stop the scanner when the event or section filter changes so stale scan // context is never used. The user must press "Scan Ticket" again to resume. const isFirstFilterRender = useRef(true); @@ -114,6 +129,32 @@ export default function TicketScanningPage() { return; } + // Offline mode: check the ticket against the list downloaded to this device. + if (offline.lock) { + const t = await offline.findTicket(text); + if (!t) { setErrorModal("Not found in the offline ticket list. Check at the door desk."); return; } + if (t.remaining <= 0) { setAlreadyUsedModal({ message: "Ticket has already been fully used", ticket: { id: t.id } }); return; } + if (!["not_required", "given"].includes(t.consentStatus)) { + setErrorModal(t.consentStatus === "declined" ? "Parental consent was declined — this ticket can't be checked in." : "Parental consent is missing or pending — this ticket can't be checked in offline. Check at the door desk."); + return; + } + setConfirmQty(t.remaining); + setConfirmQtyRaw(String(t.remaining)); + setConfirmModal({ + qrCode: text, + remaining: t.remaining, + offlineTicket: t, + ticket: { + id: t.id, quantity: t.quantity, consentStatus: t.consentStatus, + event: { title: offline.lock.eventTitle }, + registrationOption: { eventOption: { name: t.option }, variant: t.variant ? { name: t.variant } : null }, + attendee: t.bookedBy ? { name: t.holder } : null, + user: { name: t.bookedBy || t.holder }, + }, + }); + return; + } + // Always preview first to validate the ticket before showing confirm step // Uses the lightweight scan-preview endpoint (only fetches fields needed for the confirm modal) let preview: any; @@ -172,7 +213,7 @@ export default function TicketScanningPage() { if (!confirmModal || !token) return; // Capture everything before clearing modal state - const { qrCode, ticket, remaining } = confirmModal; + const { qrCode, ticket, remaining, offlineTicket } = confirmModal; const qty = confirmQty; const baseName = ticket?.registrationOption?.eventOption?.name || "Ticket"; const variantName = ticket?.registrationOption?.variant?.name; @@ -194,6 +235,17 @@ export default function TicketScanningPage() { total: ticket?.quantity || 1, }); + // Offline mode: saved on this device, synced when there's a connection. + if (offlineTicket) { + try { + await offline.scanLocally(offlineTicket, qty); + } catch (e: any) { + setSuccessModal(null); + setErrorModal(e?.message || "Couldn't save the scan on this device"); + } + return; + } + // Background write — reverse the optimistic update on failure try { const url = `/api/tickets/scan/${encodeURIComponent(qrCode)}${ @@ -202,7 +254,12 @@ export default function TicketScanningPage() { await apiFetch(url, { method: "POST", authToken: token, - body: { qty, ...(overrideConsent ? { overrideConsent: true } : {}) }, + body: { + qty, + deviceId: offline.deviceId(), + ...(selectedSectionId && selectedSectionId !== "all" ? { sectionId: selectedSectionId } : {}), + ...(overrideConsent ? { overrideConsent: true } : {}), + }, }); refreshStatsAndRecent(); } catch (e: any) { @@ -270,8 +327,10 @@ export default function TicketScanningPage() { className="border rounded px-3 py-2 w-full sm:w-56 max-w-full" value={selectedEventId} onChange={(e) => setSelectedEventId(e.target.value)} + disabled={!!offline.lock} > + {offline.lock && !events.some(ev => ev.id === offline.lock!.eventId) && } {events.map((ev) => ( ))} @@ -289,6 +348,7 @@ export default function TicketScanningPage() { className="border rounded px-3 py-2 w-full sm:w-56 max-w-full" value={selectedSectionId} onChange={(e) => setSelectedSectionId(e.target.value)} + disabled={!!offline.lock} > {sections.map(section => ( @@ -299,6 +359,16 @@ export default function TicketScanningPage() { )} + ev.id === selectedEventId)?.title || offline.lock?.eventTitle || ""} + sectionId={selectedSectionId !== "all" ? selectedSectionId : null} + sectionName={sections.find(s => s.id === selectedSectionId)?.name || null} + onError={setError} + onInfo={setScanInfo} + /> (iso ? new Date(iso).toLocaleString() : "—"); + +export default function OfflineScansPage() { + const { user, loading, token } = useAuth(); + const router = useRouter(); + const canView = useMemo(() => user?.role === "admin" || user?.role === "supervisor", [user]); + + useEffect(() => { + if (loading) return; + if (!user) router.replace("/login"); + }, [user, loading, router]); + + const [events, setEvents] = useState([]); + const [eventId, setEventId] = useState(""); + const [locks, setLocks] = useState([]); + const [reports, setReports] = useState([]); + const [onlyOpen, setOnlyOpen] = useState(true); + const [error, setError] = useDismissingState(null); + const [info, setInfo] = useDismissingState(null); + + useEffect(() => { + if (!token || !canView) return; + apiFetch("/api/events/all?includePast=true", { authToken: token }) + .then(evs => { + const recent = (evs || []).filter(e => new Date(e.endDate).getTime() > Date.now() - 14 * 864e5); + setEvents(recent); + if (recent.length && !eventId) setEventId(recent[0].id); + }) + .catch(e => setError(e?.message || "Failed to load events")); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [token, canView]); + + const load = useCallback(async () => { + if (!token || !eventId) return; + try { + const [l, r] = await Promise.all([ + apiFetch(`/api/scan-locks?eventId=${encodeURIComponent(eventId)}`, { authToken: token }), + apiFetch(`/api/scan-locks/reports?eventId=${encodeURIComponent(eventId)}${onlyOpen ? "&unreviewed=true" : ""}`, { authToken: token }), + ]); + setLocks(l); + setReports(r.filter(x => !onlyOpen || x.conflicts.length > 0 || x.afterForceRelease)); + } catch (e: any) { + setError(e?.message || "Failed to load offline scanning"); + } + }, [token, eventId, onlyOpen, setError]); + useEffect(() => { load(); }, [load]); + + const forceRelease = async (l: Lock) => { + try { + const res = await apiFetch<{ message: string }>(`/api/scan-locks/${l.id}/force-release`, { method: "POST", authToken: token! }); + setInfo(res.message); + load(); + } catch (e: any) { setError(e?.message || "Failed"); } + }; + const review = async (r: Report) => { + try { + await apiFetch(`/api/scan-locks/reports/${r.id}/review`, { method: "POST", authToken: token! }); + load(); + } catch (e: any) { setError(e?.message || "Failed"); } + }; + + return ( +
+
+
+ +
+
+ +

Offline scanning

+

Devices scanning without a connection, and their synced scans

+
+
+ + {!canView &&
You need supervisor access to manage offline scanning.
} + {error &&
{error}
} + {info &&
{info}
} + + {canView && ( +
+
+
+ + +
+ +
+ +
+

Locked sections

+ {locks.length === 0 ?

No device is scanning offline for this event.

: ( +
    + {locks.map(l => ( +
  • +
    +
    {l.sectionName || "Whole event"} — {l.user.name}{l.deviceName ? ` on ${l.deviceName}` : ""}
    +
    Locked {when(l.lockedAt)} · list downloaded {when(l.snapshotAt)} · last sync {when(l.lastSyncAt)}
    +
    + +
  • + ))} +
+ )} +
+ +
+

Sync reports

+ {reports.length === 0 ?

{onlyOpen ? "Nothing needs review." : "No offline scans have been synced for this event."}

: ( +
+ {reports.map(r => ( +
+
+
+ {when(r.createdAt)} — {r.scanLock.user?.name}{r.scanLock.deviceName ? ` on ${r.scanLock.deviceName}` : ""}{r.scanLock.sectionName ? `, ${r.scanLock.sectionName}` : ""} +
{r.accepted} scan(s) recorded{r.duplicates ? ` · ${r.duplicates} already synced` : ""}{r.afterForceRelease ? " · synced after the lock was force-released" : ""}
+
+ {r.reviewedAt + ? Reviewed by {r.reviewedBy?.name} + : } +
+ {r.conflicts.length > 0 && ( +
    + {r.conflicts.map(c => ( +
  • + {new Date(c.scannedAt).toLocaleTimeString()} · ticket {String(c.qrCode).slice(0, 8)}… · {c.message}{c.redeemed ? ` (recorded ${c.redeemed} of ${c.qty})` : " (not recorded)"} +
  • + ))} +
+ )} +
+ ))} +
+ )} +
+
+ )} +
+ ); +} diff --git a/frontend/src/app/dashboard/supervisor/page.tsx b/frontend/src/app/dashboard/supervisor/page.tsx index de0e0c7..21973a4 100644 --- a/frontend/src/app/dashboard/supervisor/page.tsx +++ b/frontend/src/app/dashboard/supervisor/page.tsx @@ -8,7 +8,7 @@ import { useStableState } from "@/hooks/useStableState"; import { useVisiblePolling } from "@/hooks/useVisiblePolling"; import { Calendar, Banknote, Gift, Users, Ticket, QrCode, DoorOpen, Wallet, - UserPlus, FileText, MessageCircle, BarChart2, Mail, TicketPercent, ShieldCheck, ListChecks, + UserPlus, FileText, MessageCircle, BarChart2, Mail, TicketPercent, ShieldCheck, ListChecks, WifiOff, } from "lucide-react"; import { StatCard, StatCardRow } from "@/components/shared/StatCard"; import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile"; @@ -24,6 +24,7 @@ const QUICK_ACTIONS = [ { href: "/dashboard/supervisor/manual", label: "Manual registration", description: "Register a guest and issue tickets", icon: UserPlus }, { href: "/dashboard/supervisor/events", label: "Manage events", description: "Create, edit, and update ticket types", icon: Calendar }, { href: "/dashboard/supervisor/payments", label: "Payments & donations", description: "Manual payments and assignment", icon: Wallet }, + { href: "/dashboard/supervisor/offline-scans", label: "Offline scanning", description: "Devices scanning offline and their synced scans", icon: WifiOff }, { href: "/dashboard/supervisor/waitlist", label: "Waitlist", description: "People waiting for sold-out tickets", icon: ListChecks }, { href: "/dashboard/supervisor/consent", label: "Parental consent", description: "Youth events: consent status and medical list", icon: ShieldCheck }, { href: "/dashboard/supervisor/coupons", label: "Coupon codes", description: "Discounts for staff, leaders and promotions", icon: TicketPercent }, diff --git a/frontend/src/app/manifest.ts b/frontend/src/app/manifest.ts new file mode 100644 index 0000000..458b977 --- /dev/null +++ b/frontend/src/app/manifest.ts @@ -0,0 +1,17 @@ +import type { MetadataRoute } from "next"; + +// Lets staff "Add to home screen" and open the ticket scanner like an app (it also +// works offline once offline mode has been enabled — see public/sw.js). +export default function manifest(): MetadataRoute.Manifest { + return { + name: "Ticket scanner", + short_name: "Scanner", + description: "Scan event tickets, online or offline", + start_url: "/dashboard/staff/ticket-scanning", + scope: "/", + display: "standalone", + background_color: "#ffffff", + theme_color: "#4F46E5", + icons: [{ src: "/favicon.ico", sizes: "any", type: "image/x-icon" }], + }; +} diff --git a/frontend/src/components/scanner/OfflineScanPanel.tsx b/frontend/src/components/scanner/OfflineScanPanel.tsx new file mode 100644 index 0000000..76fdc93 --- /dev/null +++ b/frontend/src/components/scanner/OfflineScanPanel.tsx @@ -0,0 +1,106 @@ +"use client"; + +import React, { useEffect, useState } from "react"; +import { Wifi, WifiOff, CloudUpload, Lock } from "lucide-react"; +import { apiFetch } from "@/lib/api"; +import type { OtherLock } from "./useOfflineScanning"; + +type Offline = ReturnType; + +/** + * Offline-mode controls above the scanner: shows who holds which section, lets this + * device lock the selected section and download its tickets, and shows the sync queue. + */ +export function OfflineScanPanel({ offline, token, eventId, eventTitle, sectionId, sectionName, onError, onInfo }: { + offline: Offline; + token: string | null; + eventId: string; + eventTitle: string; + sectionId: string | null; + sectionName: string | null; + onError: (m: string) => void; + onInfo: (m: string) => void; +}) { + const [locks, setLocks] = useState([]); + const [busy, setBusy] = useState(false); + const { lock, pending, online, syncing } = offline; + + useEffect(() => { + if (!token || !eventId || eventId === "all" || !online) { setLocks([]); return; } + apiFetch(`/api/scan-locks?eventId=${encodeURIComponent(eventId)}`, { authToken: token }) + .then(setLocks).catch(() => setLocks([])); + }, [token, eventId, online, lock]); + + const others = locks.filter(l => l.deviceId !== offline.deviceId()); + + const enable = async () => { + setBusy(true); + try { + const n = await offline.enable(eventId, eventTitle, sectionId, sectionName); + onInfo(`Offline mode on — ${n} ticket(s) downloaded. You can keep scanning without a connection.`); + } catch (e: any) { + onError(e?.message || "Couldn't turn on offline mode"); + } finally { + setBusy(false); + } + }; + const release = async () => { + setBusy(true); + try { + await offline.release(); + onInfo("Offline mode ended and the section is unlocked."); + } catch (e: any) { + onError(e?.message || "Couldn't end offline mode"); + } finally { + setBusy(false); + } + }; + const syncNow = async () => { + try { + const r = await offline.sync(); + if (r) onInfo(`Synced ${r.accepted} scan(s)${r.conflicts ? ` — ${r.conflicts} need a supervisor to review` : ""}.`); + } catch (e: any) { + onError(e?.message || "Sync failed — scans are kept on this device and will retry."); + } + }; + + return ( +
+
+ {online ? : } + {online ? "Online" : "Offline"} + {lock ? ( + <> + · + Offline mode: {lock.eventTitle}{lock.sectionName ? ` — ${lock.sectionName}` : " — whole event"} + Ticket list downloaded at {new Date(lock.snapshotAt).toLocaleTimeString()} + · {pending} scan(s) waiting to sync +
+ + +
+ + ) : eventId && eventId !== "all" ? ( +
+ +
+ ) : ( + Pick an event to use offline mode. + )} +
+ {others.length > 0 && ( +
    + {others.map(l => ( +
  • + + {l.sectionName ? `"${l.sectionName}"` : "The whole event"} is offline-locked by {l.user.name}{l.deviceName ? ` on ${l.deviceName}` : ""} — scan it on that device. +
  • + ))} +
+ )} + {lock && !online &&

Scans are saved on this device and will sync when the connection is back. Tickets bought after the download time won't be on the list.

} +
+ ); +} diff --git a/frontend/src/components/scanner/useOfflineScanning.ts b/frontend/src/components/scanner/useOfflineScanning.ts new file mode 100644 index 0000000..46818cb --- /dev/null +++ b/frontend/src/components/scanner/useOfflineScanning.ts @@ -0,0 +1,115 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { apiFetch } from "@/lib/api"; +import { + OfflineLock, SnapshotTicket, clearOffline, deviceId, deviceName, findTicket, getOfflineLock, + queuedScans, recordScan, removeQueued, startOffline, +} from "@/lib/offlineScan"; + +export type OtherLock = { id: string; sectionId: string | null; sectionName: string | null; deviceId: string; deviceName: string | null; user: { name: string } }; + +/** + * Offline mode for the ticket scanner: lock a section to this device, download its + * tickets, scan against them with no connection, and sync the queued scans whenever + * the device is back online. + */ +export function useOfflineScanning(token: string | null) { + const [lock, setLock] = useState(null); + const [pending, setPending] = useState(0); + const [online, setOnline] = useState(true); + const [syncing, setSyncing] = useState(false); + const [lastSync, setLastSync] = useState<{ accepted: number; conflicts: number; at: string } | null>(null); + const syncingRef = useRef(false); + + const refreshPending = useCallback(async () => { + try { setPending((await queuedScans()).length); } catch { setPending(0); } + }, []); + + useEffect(() => { + setLock(getOfflineLock()); + refreshPending(); + setOnline(typeof navigator === "undefined" ? true : navigator.onLine); + const up = () => setOnline(true); + const down = () => setOnline(false); + window.addEventListener("online", up); + window.addEventListener("offline", down); + // Cache the scanner page and everything it has loaded, so it opens offline. + if ("serviceWorker" in navigator) { + navigator.serviceWorker.register("/sw.js").then(async () => { + const reg = await navigator.serviceWorker.ready; + const urls = [window.location.pathname, ...performance.getEntriesByType("resource").map(e => e.name)]; + reg.active?.postMessage({ type: "cache-urls", urls }); + }).catch(() => {}); + } + return () => { window.removeEventListener("online", up); window.removeEventListener("offline", down); }; + }, [refreshPending]); + + /** Uploads queued scans. Returns the server's verdict, or null when nothing was sent. */ + const sync = useCallback(async () => { + if (!token || syncingRef.current) return null; + const queue = await queuedScans(); + if (queue.length === 0) return null; + syncingRef.current = true; + setSyncing(true); + try { + const byLock = new Map(); + queue.forEach(q => byLock.set(q.lockId, [...(byLock.get(q.lockId) || []), q])); + let accepted = 0, conflicts = 0; + for (const [lockId, scans] of byLock) { + const res = await apiFetch<{ accepted: number; duplicates: number; conflicts: any[] }>(`/api/scan-locks/${lockId}/sync`, { + method: "POST", authToken: token, body: { deviceId: deviceId(), scans }, + }); + accepted += res.accepted; + conflicts += res.conflicts.length; + // Synced (or already on the server) — either way they're done on this device. + await removeQueued(scans.map(s => s.clientScanId)); + } + const result = { accepted, conflicts, at: new Date().toISOString() }; + setLastSync(result); + return result; + } finally { + syncingRef.current = false; + setSyncing(false); + refreshPending(); + } + }, [token, refreshPending]); + + // Sync as soon as the connection is back, and every 30 seconds while online. + useEffect(() => { + if (!online || !token) return; + sync().catch(() => {}); + const t = setInterval(() => { if (navigator.onLine) sync().catch(() => {}); }, 30000); + return () => clearInterval(t); + }, [online, token, sync]); + + const enable = useCallback(async (eventId: string, eventTitle: string, sectionId: string | null, sectionName: string | null) => { + if (!token) throw new Error("Log in first."); + const created = await apiFetch<{ id: string }>("/api/scan-locks", { + method: "POST", authToken: token, body: { eventId, sectionId, deviceId: deviceId(), deviceName: deviceName() }, + }); + const snap = await apiFetch<{ snapshotAt: string; tickets: SnapshotTicket[] }>(`/api/scan-locks/${created.id}/snapshot?deviceId=${encodeURIComponent(deviceId())}`, { authToken: token }); + const next: OfflineLock = { lockId: created.id, eventId, eventTitle, sectionId, sectionName, snapshotAt: snap.snapshotAt }; + await startOffline(next, snap.tickets); + setLock(next); + return snap.tickets.length; + }, [token]); + + const release = useCallback(async () => { + if (!lock || !token) return; + await sync(); + if ((await queuedScans()).length > 0) throw new Error("Some scans haven't synced yet. Try again when you're online."); + await apiFetch(`/api/scan-locks/${lock.lockId}`, { method: "DELETE", authToken: token, body: { deviceId: deviceId() } }); + await clearOffline(); + setLock(null); + }, [lock, token, sync]); + + const scanLocally = useCallback(async (ticket: SnapshotTicket, qty: number) => { + if (!lock) throw new Error("Offline mode is not on."); + await recordScan(lock.lockId, ticket, qty); + await refreshPending(); + if (navigator.onLine) sync().catch(() => {}); + }, [lock, refreshPending, sync]); + + return { lock, pending, online, syncing, lastSync, enable, release, sync, scanLocally, findTicket, deviceId }; +} diff --git a/frontend/src/content/help/registry.ts b/frontend/src/content/help/registry.ts index 64c298e..6625efe 100644 --- a/frontend/src/content/help/registry.ts +++ b/frontend/src/content/help/registry.ts @@ -24,6 +24,7 @@ import { supervisorFormsHelpContent } from "./supervisor-forms"; import { supervisorCouponsHelpContent } from "./supervisor-coupons"; import { supervisorConsentHelpContent } from "./supervisor-consent"; import { supervisorWaitlistHelpContent } from "./supervisor-waitlist"; +import { supervisorOfflineScansHelpContent } from "./supervisor-offline-scans"; import { supervisorEmailAttendeesHelpContent } from "./supervisor-email-attendees"; import { supervisorWhatsappAttendeesHelpContent } from "./supervisor-whatsapp-attendees"; import { staffEventTicketsHelpContent } from "./staff-event-tickets"; @@ -150,6 +151,11 @@ const REGISTRY: HelpRegistryEntry[] = [ matches: pathname => pathname === "/dashboard/supervisor/payments", content: supervisorPaymentsHelpContent, }, + { + slug: "supervisor-offline-scans", + matches: pathname => pathname === "/dashboard/supervisor/offline-scans", + content: supervisorOfflineScansHelpContent, + }, { slug: "supervisor-waitlist", matches: pathname => pathname === "/dashboard/supervisor/waitlist", diff --git a/frontend/src/content/help/staff-ticket-scanning.tsx b/frontend/src/content/help/staff-ticket-scanning.tsx index cfe8952..b62d7d5 100644 --- a/frontend/src/content/help/staff-ticket-scanning.tsx +++ b/frontend/src/content/help/staff-ticket-scanning.tsx @@ -1,5 +1,5 @@ import React from "react"; -import { QrCode, Filter, CheckCircle2, ShieldAlert } from "lucide-react"; +import { QrCode, Filter, CheckCircle2, ShieldAlert, WifiOff } from "lucide-react"; import { GuideItem } from "@/components/shared/GuideItem"; import type { HelpContent } from "./types"; @@ -19,6 +19,9 @@ export const staffTicketScanningHelpContent: HelpContent = { You'll see Success (with redeemed/remaining counts), Already Used, or an Error if something's wrong with the ticket. + + Worried about the venue Wi-Fi? While you're online, pick the event and section and tap "Enable offline mode". The section is locked to your device and its tickets are downloaded, so you can keep scanning with no connection. Scans sync automatically when you're back online. Tickets bought after the download won't be on your list — send those people to the door desk. Tap "Release section" when you're done. Tip: add this page to your home screen so it opens offline. + On youth events, the confirm screen warns when a parent hasn't given consent yet (or declined). That person can't be checked in; a supervisor can override, and the override is recorded in the audit log. diff --git a/frontend/src/content/help/supervisor-offline-scans.tsx b/frontend/src/content/help/supervisor-offline-scans.tsx new file mode 100644 index 0000000..2bcea14 --- /dev/null +++ b/frontend/src/content/help/supervisor-offline-scans.tsx @@ -0,0 +1,32 @@ +import React from "react"; +import { WifiOff, Unlock, CheckCircle2, Lock } from "lucide-react"; +import { GuideItem } from "@/components/shared/GuideItem"; +import type { HelpContent } from "./types"; + +/** Help content for /dashboard/supervisor/offline-scans. */ +export const supervisorOfflineScansHelpContent: HelpContent = { + title: "Offline scanning", + subtitle: "Devices scanning without a connection, and what they synced.", + tabs: [ + { + key: "page", + label: "This page", + icon: WifiOff, + content: ( +
+
+ + Each section (or the whole event) in offline mode is locked to one device, so two devices can never check in the same ticket while offline. You can see who holds each lock, when their ticket list was downloaded, and when they last synced. + + + For a lost or flat device. The section is unlocked straight away. If the device reconnects later, its offline scans still sync and are flagged here. + + + Scans that need a person to look: tickets not found (e.g. transferred), cancelled registrations, tickets already used up, scans outside the locked section, or check-ins without parental consent. Mark each report reviewed once it's been dealt with. + +
+
+ ), + }, + ], +}; diff --git a/frontend/src/contexts/AuthContext.tsx b/frontend/src/contexts/AuthContext.tsx index dafb81f..f66b028 100644 --- a/frontend/src/contexts/AuthContext.tsx +++ b/frontend/src/contexts/AuthContext.tsx @@ -18,6 +18,25 @@ export type AuthContextValue = { const AuthContext = createContext(undefined); +// The last profile the server confirmed, so a page reloaded with no connection (e.g. the +// ticket scanner in offline mode) still knows who's signed in. The server checks the +// token on every API call regardless, so this never grants anything by itself. +const USER_CACHE_KEY = "hope_events_user_cache"; +function cacheUser(u: AuthUser | null) { + try { + if (u) localStorage.setItem(USER_CACHE_KEY, JSON.stringify(u)); + else localStorage.removeItem(USER_CACHE_KEY); + } catch { /* storage unavailable */ } +} +function cachedUser(): AuthUser | null { + try { + const raw = localStorage.getItem(USER_CACHE_KEY); + return raw ? JSON.parse(raw) : null; + } catch { + return null; + } +} + export function AuthProvider({ children }: { children: React.ReactNode }) { const [token, setToken] = useState(null); const [user, setUser] = useState(null); @@ -34,6 +53,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const me = await apiFetch("/api/users/profile", { authToken: t }); setToken(t); setUser(me); + cacheUser(me); } } catch (e) { // Only wipe the stored token when the server explicitly rejects it (401). @@ -41,8 +61,17 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { // token stays in localStorage so the next page load can retry. if (e instanceof ApiError && e.status === 401) { clearToken(); + cacheUser(null); setToken(null); setUser(null); + } else { + // No connection: carry on as the last confirmed user. + const t = getToken(); + const cached = cachedUser(); + if (t && cached) { + setToken(t); + setUser(cached); + } } } finally { setLoading(false); @@ -57,6 +86,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { saveToken(token); setToken(token); setUser(loggedInUser); + cacheUser(loggedInUser); return loggedInUser; }, []); @@ -99,6 +129,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { const logout = useCallback(() => { clearToken(); + cacheUser(null); setToken(null); setUser(null); }, []); diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 5648c98..09120ba 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -121,6 +121,7 @@ export async function apiFetch(path: string, options: ApiOptions = {}): // end it and send them to log in, where they enrol. if (res.status === 401 && data?.code === "TWO_FACTOR_REQUIRED" && typeof window !== "undefined") { localStorage.removeItem("hope_events_token"); + localStorage.removeItem("hope_events_user_cache"); if (!window.location.pathname.startsWith("/login")) { const back = window.location.pathname + window.location.search; window.location.href = `/login?reason=2fa&redirect=${encodeURIComponent(back)}`; diff --git a/frontend/src/lib/offlineScan.ts b/frontend/src/lib/offlineScan.ts new file mode 100644 index 0000000..ba3a8f8 --- /dev/null +++ b/frontend/src/lib/offlineScan.ts @@ -0,0 +1,130 @@ +"use client"; + +/** + * Offline scanning on this device: the ticket snapshot for a locked section and the + * queue of scans waiting to sync, both kept in IndexedDB (via `idb`). The active lock + * itself is in localStorage so the scanner page knows it's in offline mode after a + * reload with no connection. + */ +import { openDB, type IDBPDatabase } from "idb"; + +export type SnapshotTicket = { + id: string; + qrCode: string; + holder: string; + bookedBy: string; + option: string; + variant: string | null; + quantity: number; + remaining: number; + consentStatus: string; +}; + +export type QueuedScan = { clientScanId: string; lockId: string; qrCode: string; qty: number; scannedAt: string }; + +export type OfflineLock = { + lockId: string; + eventId: string; + eventTitle: string; + sectionId: string | null; + sectionName: string | null; + snapshotAt: string; +}; + +const DB_NAME = "hope-events-offline-scan"; +const LOCK_KEY = "hope_events_offline_lock"; +const DEVICE_KEY = "hope_events_scan_device"; + +let dbPromise: Promise | null = null; +function db() { + if (!dbPromise) { + dbPromise = openDB(DB_NAME, 1, { + upgrade(d) { + d.createObjectStore("tickets", { keyPath: "qrCode" }); + d.createObjectStore("queue", { keyPath: "clientScanId" }); + }, + }); + } + return dbPromise; +} + +/** A stable id for this browser, used to tie an offline lock to one device. */ +export function deviceId(): string { + try { + let id = localStorage.getItem(DEVICE_KEY); + if (!id) { + id = crypto.randomUUID(); + localStorage.setItem(DEVICE_KEY, id); + } + return id; + } catch { + return "unknown-device"; + } +} + +/** A short, human name for this device ("Chrome on Android"). */ +export function deviceName(): string { + const ua = typeof navigator !== "undefined" ? navigator.userAgent : ""; + const browser = /Edg\//.test(ua) ? "Edge" : /Chrome\//.test(ua) ? "Chrome" : /Firefox\//.test(ua) ? "Firefox" : /Safari\//.test(ua) ? "Safari" : "Browser"; + const os = /Android/.test(ua) ? "Android" : /iPhone|iPad/.test(ua) ? "iOS" : /Windows/.test(ua) ? "Windows" : /Mac OS/.test(ua) ? "Mac" : "device"; + return `${browser} on ${os}`; +} + +export function getOfflineLock(): OfflineLock | null { + try { + const raw = localStorage.getItem(LOCK_KEY); + return raw ? JSON.parse(raw) : null; + } catch { + return null; + } +} + +function setOfflineLock(lock: OfflineLock | null) { + try { + if (lock) localStorage.setItem(LOCK_KEY, JSON.stringify(lock)); + else localStorage.removeItem(LOCK_KEY); + } catch { /* storage unavailable */ } +} + +/** Keeps the downloaded ticket list and marks this device as in offline mode. */ +export async function startOffline(lock: OfflineLock, tickets: SnapshotTicket[]) { + const d = await db(); + const tx = d.transaction("tickets", "readwrite"); + await tx.store.clear(); + for (const t of tickets) await tx.store.put(t); + await tx.done; + setOfflineLock(lock); +} + +export async function findTicket(qrCode: string): Promise { + return (await db()).get("tickets", qrCode); +} + +/** Records a scan locally: lowers the ticket's remaining count and queues it for sync. */ +export async function recordScan(lockId: string, ticket: SnapshotTicket, qty: number): Promise { + const d = await db(); + const scan: QueuedScan = { clientScanId: crypto.randomUUID(), lockId, qrCode: ticket.qrCode, qty, scannedAt: new Date().toISOString() }; + const tx = d.transaction(["tickets", "queue"], "readwrite"); + await tx.objectStore("tickets").put({ ...ticket, remaining: Math.max(0, ticket.remaining - qty) }); + await tx.objectStore("queue").put(scan); + await tx.done; + return scan; +} + +export async function queuedScans(): Promise { + return (await db()).getAll("queue"); +} + +export async function removeQueued(ids: string[]) { + const d = await db(); + const tx = d.transaction("queue", "readwrite"); + for (const id of ids) await tx.store.delete(id); + await tx.done; +} + +/** Ends offline mode on this device: the ticket list is deleted (the queue must be empty). */ +export async function clearOffline() { + const d = await db(); + await d.clear("tickets"); + setOfflineLock(null); +} diff --git a/info.md b/info.md index 0a7c9f9..7e34fad 100644 --- a/info.md +++ b/info.md @@ -30,6 +30,7 @@ It runs in any web browser — on a phone, tablet, or computer — with nothing ### For staff on the day - **QR code scanner** — check people in by scanning their ticket with any phone camera. A single ticket can cover a whole family and be checked in a few people at a time. +- **Works without Wi-Fi** — lock a check-in point to a phone and keep scanning with no signal; scans sync automatically when the connection is back. - **Scan points** — set up separate check-in points (e.g. main hall, dinner) that only accept the right tickets. - **At-the-door desk** — search by name, phone, or ticket number; register walk-ins; take cash, card, or EFT payments; check people in; and print or resend tickets on the spot. - **Self-service kiosk** — set up a tablet where visitors register themselves. Returning visitors are recognised by their email or phone number.