"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; // Multi-day events: the session the downloaded ticket list is for. sessionLabel?: string | null; }; 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); }