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:
@@ -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<string, string> = {
|
||||
@@ -44,6 +48,10 @@ const ACTION_LABELS: Record<string, string> = {
|
||||
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 {
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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<string | null>(null);
|
||||
const { token, user } = useAuth();
|
||||
const offline = useOfflineScanning(token);
|
||||
const [recentScans, setRecentScans] = useState<any[]>([]);
|
||||
const [stats, setStats] = useState<any | null>(null);
|
||||
const [loadingStats, setLoadingStats] = useState<boolean>(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<any>(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}
|
||||
>
|
||||
<option value="all">All events</option>
|
||||
{offline.lock && !events.some(ev => ev.id === offline.lock!.eventId) && <option value={offline.lock.eventId}>{offline.lock.eventTitle}</option>}
|
||||
{events.map((ev) => (
|
||||
<option key={ev.id} value={ev.id}>{ev.title}</option>
|
||||
))}
|
||||
@@ -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}
|
||||
>
|
||||
<option value="all">All sections</option>
|
||||
{sections.map(section => (
|
||||
@@ -299,6 +359,16 @@ export default function TicketScanningPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<OfflineScanPanel
|
||||
offline={offline}
|
||||
token={token}
|
||||
eventId={selectedEventId}
|
||||
eventTitle={events.find(ev => 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}
|
||||
/>
|
||||
<QRScanner
|
||||
ref={scannerRef}
|
||||
onResult={handleResult}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/date";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { WifiOff, Unlock, CheckCircle2 } from "lucide-react";
|
||||
|
||||
type Lock = { id: string; sectionName: string | null; deviceName: string | null; user: { name: string }; lockedAt: string; snapshotAt: string | null; lastSyncAt: string | null };
|
||||
type Report = {
|
||||
id: string; accepted: number; duplicates: number; afterForceRelease: boolean; createdAt: string; reviewedAt: string | null;
|
||||
reviewedBy: { name: string } | null;
|
||||
conflicts: { clientScanId: string; qrCode: string; qty: number; redeemed: number; scannedAt: string; reason: string; message: string }[];
|
||||
scanLock: Lock;
|
||||
};
|
||||
|
||||
const when = (iso: string | null) => (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<any[]>([]);
|
||||
const [eventId, setEventId] = useState("");
|
||||
const [locks, setLocks] = useState<Lock[]>([]);
|
||||
const [reports, setReports] = useState<Report[]>([]);
|
||||
const [onlyOpen, setOnlyOpen] = useState(true);
|
||||
const [error, setError] = useDismissingState<string | null>(null);
|
||||
const [info, setInfo] = useDismissingState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || !canView) return;
|
||||
apiFetch<any[]>("/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<Lock[]>(`/api/scan-locks?eventId=${encodeURIComponent(eventId)}`, { authToken: token }),
|
||||
apiFetch<Report[]>(`/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 (
|
||||
<div className="max-w-5xl mx-auto w-full p-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<WifiOff className="w-5 h-5 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard")}>← Back to dashboard</button>
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Offline scanning</h1>
|
||||
<p className="text-sm text-gray-500">Devices scanning without a connection, and their synced scans</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!canView && <div className="p-3 border rounded bg-yellow-50 text-yellow-800 text-sm mb-4">You need supervisor access to manage offline scanning.</div>}
|
||||
{error && <div className="mb-3 p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
|
||||
{info && <div className="mb-3 p-3 border rounded bg-green-50 text-green-800 text-sm">{info}</div>}
|
||||
|
||||
{canView && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div>
|
||||
<label className="block text-xs text-gray-600 mb-1">Event</label>
|
||||
<select className="border rounded-lg px-3 py-2 text-sm min-w-[16rem]" value={eventId} onChange={e => setEventId(e.target.value)}>
|
||||
{events.map(ev => <option key={ev.id} value={ev.id}>{ev.title} ({formatDate(new Date(ev.startDate))})</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm text-gray-700 pb-2">
|
||||
<input type="checkbox" checked={onlyOpen} onChange={e => setOnlyOpen(e.target.checked)} /> Only reports that need review
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm">
|
||||
<h2 className="font-semibold mb-2">Locked sections</h2>
|
||||
{locks.length === 0 ? <p className="text-sm text-gray-500">No device is scanning offline for this event.</p> : (
|
||||
<ul className="divide-y">
|
||||
{locks.map(l => (
|
||||
<li key={l.id} className="py-2 flex items-center justify-between gap-3 text-sm">
|
||||
<div>
|
||||
<div className="font-medium">{l.sectionName || "Whole event"} — {l.user.name}{l.deviceName ? ` on ${l.deviceName}` : ""}</div>
|
||||
<div className="text-xs text-gray-500">Locked {when(l.lockedAt)} · list downloaded {when(l.snapshotAt)} · last sync {when(l.lastSyncAt)}</div>
|
||||
</div>
|
||||
<button onClick={() => forceRelease(l)} className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border hover:bg-gray-50 shrink-0" title="For a lost or flat device. If it reconnects later, its scans still sync and are flagged here.">
|
||||
<Unlock className="w-3.5 h-3.5" /> Force release
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm">
|
||||
<h2 className="font-semibold mb-2">Sync reports</h2>
|
||||
{reports.length === 0 ? <p className="text-sm text-gray-500">{onlyOpen ? "Nothing needs review." : "No offline scans have been synced for this event."}</p> : (
|
||||
<div className="space-y-3">
|
||||
{reports.map(r => (
|
||||
<div key={r.id} className={`border rounded-lg p-3 ${r.reviewedAt ? "opacity-60" : ""}`}>
|
||||
<div className="flex items-center justify-between gap-3 text-sm">
|
||||
<div>
|
||||
<span className="font-medium">{when(r.createdAt)}</span> — {r.scanLock.user?.name}{r.scanLock.deviceName ? ` on ${r.scanLock.deviceName}` : ""}{r.scanLock.sectionName ? `, ${r.scanLock.sectionName}` : ""}
|
||||
<div className="text-xs text-gray-500">{r.accepted} scan(s) recorded{r.duplicates ? ` · ${r.duplicates} already synced` : ""}{r.afterForceRelease ? " · synced after the lock was force-released" : ""}</div>
|
||||
</div>
|
||||
{r.reviewedAt
|
||||
? <span className="text-xs text-gray-500 inline-flex items-center gap-1"><CheckCircle2 className="w-3.5 h-3.5" /> Reviewed by {r.reviewedBy?.name}</span>
|
||||
: <button onClick={() => review(r)} className="px-2.5 py-1 text-xs rounded bg-brand-600 text-white hover:bg-brand-700 shrink-0">Mark reviewed</button>}
|
||||
</div>
|
||||
{r.conflicts.length > 0 && (
|
||||
<ul className="mt-2 text-xs space-y-1">
|
||||
{r.conflicts.map(c => (
|
||||
<li key={c.clientScanId} className="text-red-800">
|
||||
{new Date(c.scannedAt).toLocaleTimeString()} · ticket {String(c.qrCode).slice(0, 8)}… · {c.message}{c.redeemed ? ` (recorded ${c.redeemed} of ${c.qty})` : " (not recorded)"}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 },
|
||||
|
||||
@@ -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" }],
|
||||
};
|
||||
}
|
||||
@@ -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<typeof import("./useOfflineScanning").useOfflineScanning>;
|
||||
|
||||
/**
|
||||
* 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<OtherLock[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const { lock, pending, online, syncing } = offline;
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || !eventId || eventId === "all" || !online) { setLocks([]); return; }
|
||||
apiFetch<OtherLock[]>(`/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 (
|
||||
<div className={`rounded-xl border p-3 mb-4 text-sm ${lock ? "bg-amber-50 border-amber-200" : "bg-white"}`}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{online ? <Wifi className="w-4 h-4 text-green-600" /> : <WifiOff className="w-4 h-4 text-red-600" />}
|
||||
<span className={online ? "text-green-700" : "text-red-700"}>{online ? "Online" : "Offline"}</span>
|
||||
{lock ? (
|
||||
<>
|
||||
<span className="text-gray-400">·</span>
|
||||
<span className="font-medium text-amber-900">Offline mode: {lock.eventTitle}{lock.sectionName ? ` — ${lock.sectionName}` : " — whole event"}</span>
|
||||
<span className="text-xs text-gray-600">Ticket list downloaded at {new Date(lock.snapshotAt).toLocaleTimeString()}</span>
|
||||
<span className="text-xs text-gray-600">· {pending} scan(s) waiting to sync</span>
|
||||
<div className="ml-auto flex gap-2">
|
||||
<button onClick={syncNow} disabled={!online || syncing || pending === 0} className="inline-flex items-center gap-1 px-2.5 py-1 rounded border bg-white text-xs disabled:opacity-50"><CloudUpload className="w-3.5 h-3.5" /> {syncing ? "Syncing…" : "Sync now"}</button>
|
||||
<button onClick={release} disabled={!online || busy} className="px-2.5 py-1 rounded bg-amber-600 text-white text-xs disabled:opacity-50">Release section</button>
|
||||
</div>
|
||||
</>
|
||||
) : eventId && eventId !== "all" ? (
|
||||
<div className="ml-auto">
|
||||
<button onClick={enable} disabled={!online || busy || others.some(l => !l.sectionId || !sectionId || l.sectionId === sectionId)} className="px-2.5 py-1 rounded border border-brand-300 text-brand-700 text-xs hover:bg-brand-50 disabled:opacity-50" title="Lock this section to this device and download its tickets, so you can keep scanning if the connection drops">
|
||||
{busy ? "Preparing…" : `Enable offline mode${sectionName ? ` for ${sectionName}` : " (whole event)"}`}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-xs text-gray-500 ml-1">Pick an event to use offline mode.</span>
|
||||
)}
|
||||
</div>
|
||||
{others.length > 0 && (
|
||||
<ul className="mt-2 space-y-0.5">
|
||||
{others.map(l => (
|
||||
<li key={l.id} className="flex items-center gap-1.5 text-xs text-gray-700">
|
||||
<Lock className="w-3.5 h-3.5 text-amber-600" />
|
||||
{l.sectionName ? `"${l.sectionName}"` : "The whole event"} is offline-locked by {l.user.name}{l.deviceName ? ` on ${l.deviceName}` : ""} — scan it on that device.
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{lock && !online && <p className="mt-2 text-xs text-amber-900">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.</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<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: 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 };
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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 = {
|
||||
<GuideItem icon={CheckCircle2} title="Outcomes" tone="green">
|
||||
You'll see Success (with redeemed/remaining counts), Already Used, or an Error if something's wrong with the ticket.
|
||||
</GuideItem>
|
||||
<GuideItem icon={WifiOff} title="Offline mode" tone="amber">
|
||||
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.
|
||||
</GuideItem>
|
||||
<GuideItem icon={ShieldAlert} title="Parental consent" tone="rose">
|
||||
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.
|
||||
</GuideItem>
|
||||
|
||||
@@ -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: (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-4">
|
||||
<GuideItem icon={Lock} title="Locked sections" tone="brand">
|
||||
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.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Unlock} title="Force release" tone="amber">
|
||||
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.
|
||||
</GuideItem>
|
||||
<GuideItem icon={CheckCircle2} title="Sync reports" tone="rose">
|
||||
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.
|
||||
</GuideItem>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -18,6 +18,25 @@ export type AuthContextValue = {
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(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<string | null>(null);
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
@@ -34,6 +53,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const me = await apiFetch<AuthUser>("/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);
|
||||
}, []);
|
||||
|
||||
@@ -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