Archived
Event wizard: one date or multiple sessions with a repeat-pattern builder, and a new Attendance step (late joining and pricing, check-in window, session reminders, certificates with preview). Public pages show the schedule and late prices; the scanner picks today's session; new attendance register page, My Certificates, and a public verify page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
121 lines
5.7 KiB
TypeScript
121 lines
5.7 KiB
TypeScript
"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<OfflineLock | null>(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<string, typeof queue>();
|
|
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: unknown[] }>(`/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[]; session?: { id: string; label: string } | null; noSessionToday?: boolean }>(`/api/scan-locks/${created.id}/snapshot?deviceId=${encodeURIComponent(deviceId())}`, { authToken: token });
|
|
// Multi-day events: the downloaded list is for today's session, so there must be one.
|
|
if (snap.noSessionToday) {
|
|
await apiFetch(`/api/scan-locks/${created.id}`, { method: "DELETE", authToken: token, body: { deviceId: deviceId() } }).catch(() => {});
|
|
throw new Error("There's no session of this event open for check-in today, so offline mode can't start.");
|
|
}
|
|
const next: OfflineLock = { lockId: created.id, eventId, eventTitle, sectionId, sectionName, snapshotAt: snap.snapshotAt, sessionLabel: snap.session?.label || null };
|
|
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 };
|
|
}
|