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 <noreply@anthropic.com>
This commit is contained in:
@@ -121,6 +121,7 @@ export async function apiFetch<T = any>(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)}`;
|
||||
|
||||
@@ -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<IDBPDatabase> | 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<SnapshotTicket | undefined> {
|
||||
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<QueuedScan> {
|
||||
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<QueuedScan[]> {
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user