"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { apiV2Data } from "@/lib/apiV2"; 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 (apiV2Data("post", "/scan-locks/{id}/sync", { params: { id: lockId }, authToken: token, body: { deviceId: deviceId(), scans }, }) as Promise<{ accepted: number; duplicates: number; conflicts: unknown[] }>); 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 (apiV2Data("post", "/scan-locks", { authToken: token, body: { eventId, sectionId, deviceId: deviceId(), deviceName: deviceName() }, }) as Promise<{ id: string }>); const snap = await (apiV2Data("get", "/scan-locks/{id}/snapshot", { params: { id: created.id }, query: { deviceId: deviceId() }, authToken: token }) as Promise<{ snapshotAt: string; tickets: SnapshotTicket[]; session?: { id: string; label: string } | null; noSessionToday?: boolean }>); // Multi-day events: the downloaded list is for today's session, so there must be one. if (snap.noSessionToday) { await apiV2Data("delete", "/scan-locks/{id}", { params: { id: created.id }, 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 apiV2Data("delete", "/scan-locks/{id}", { params: { id: lock.lockId }, 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 }; }