feat(tier2): finish the finish line — Block H follow-ups, Block G geolocation, cross-cutting

Three threads of work land here together to close out Tier 2.

### Block H follow-ups — day-of check-in
- Scanner is now an "open on your phone" magic-link flow. Hosts on
  desktop mint a scoped JWT via POST /events/{id}/scanner-ticket and
  render its URL into a QR; phone scans it and lands on /scanner with
  the ticket as bearer. The ticket carries Audience=scanner so it can
  never substitute for a session token.
- Plus-one confirmation at the door: scan → POST /check-in/preview to
  fetch guest + expected party size → confirm buttons ("Just them",
  "Party of N", custom) → POST /check-in. No more silent arrival_count=1.
- Offline scan queue: failed POSTs go into an IndexedDB store and drain
  on the 'online' event with poison-message protection.
- Day-of arrivals headline widget on the event overview, gated to the
  host's local calendar date so it doesn't dominate the page weeks out.
- Tab nav restyled with inline heroicons + scrollable segmented control;
  Check-in moves to the rightmost slot.
- PWA: manifest + service worker scoped to /scanner, generated 192/512
  icons (Go scripted renderer in scripts/gen-scanner-icons.go).
- Confirmation email QR was rendering broken because html/template
  rewrites data: URLs to #ZgotmplZ; mark the value as template.URL.
- Email "open your invitation" link 404'd because we had no token to
  put after /rsvp/. Threaded AccessLink through the RSVPConfirmed NATS
  event from the API at submit time.

### Block G remainder — geolocation + threshold preview
- Pluggable GeoResolver in the fraud engine (NullResolver, IPApiResolver
  for the free ip-api.com fallback, MaxMindResolver behind GG_GEOIP_DB_PATH).
  Wrapped in a Redis cache (30d TTL). Geo flows through both gRPC and
  NATS scoring paths.
- geo_jump scoring feature: >500km in <1h flags ("accessed from Lagos
  and Paris within 12 minutes"); >500km in <6h is a softer signal. The
  existing single-signal cap keeps a lone geo_jump in MEDIUM.
- FraudScored event carries geo_country/city/lat/lon; ApplyScore uses
  COALESCE so a later re-score without geo doesn't wipe earlier data.
- Threshold-slider live preview: GET /events/{id}/security/thresholds/preview
  returns band counts the host's existing access events would have
  fallen into under the proposed thresholds. Debounced (250ms) widget
  under the Advanced sliders so the host gets concrete feedback instead
  of guessing.

### Cross-cutting — audit, tier-gating, feature flags
- audit_log table + internal/audit.Recorder (async fire-and-forget on
  detached context so an audit blip never fails the real action). Wired
  into branding update, thresholds update, allowlist add/remove,
  collaborator invite/role-change/remove, message create/send-now/cancel.
- Tier-gating: extended billing.Limits with MaxCollaborators,
  CustomBranding, Scanner, Broadcasts. Free = none; Pro = 5 + all;
  Business = unlimited. Gates the scanner-ticket, message create,
  branding put, and collaborator invite endpoints with 402 +
  structured upgrade payload. Auto-reminders, fraud detection, and
  analytics deliberately stay on every tier — those are safety + visibility
  features, not upsell levers.
- Feature flags: feature_flags table + internal/flags.Store with 30s
  in-memory refresh, stable sha256(key + user_id) percent bucketing,
  unknown-key-defaults-on. Six Tier 2 flags pre-seeded. Three handlers
  (branding, broadcasts, scanner) check the kill switch ahead of the
  tier gate so ops can pull a feature back without a redeploy.

### Verified
- go test ./... + fraud-engine pytest (12/12 incl. 3 new geo_jump tests + 5
  new flags tests).
- docker compose build + up across api, fraud-engine, notifier, frontend.
- /health endpoints 200; migrations 0014 + 0015 applied; 6 flags
  seeded; audit_log table + partial indexes confirmed.
- Fraud-engine logs confirm geo resolver kind=CachedGeoResolver provider=auto.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Kwaku Danso
2026-05-21 20:30:02 +01:00
parent 003a320690
commit 98678ff5a3
49 changed files with 3798 additions and 238 deletions
+163 -20
View File
@@ -1,12 +1,24 @@
<script setup lang="ts">
// Tier 2 Block H — day-of check-in. The host opens this on their phone
// at the venue, taps "Start scanning", and points the camera at each
// guest's QR. Live arrivals counter updates in place; walk-ins go in
// via the side button.
// Tier 2 Block H — day-of check-in.
//
// QR decoding uses jsQR loaded from a CDN at runtime so we don't bloat
// the regular bundle. The camera is requested only when the scanner
// is open and stopped on close.
// Reality check: a host's laptop or desktop almost never has a usable
// rear camera for scanning paper / phone-screen QR codes. Industry
// standard (Eventbrite, Lu.ma, Cvent) is to do the scanning on a
// phone or dedicated handheld. So:
//
// - On a desktop (or any device with a fine pointer), this card shows
// a "Scan with your phone" panel: a QR code containing a scoped
// magic link the host can scan with their phone camera. The phone
// opens /scanner with the scoped token in the URL, and that page
// drives the actual check-in. The desktop view focuses on live
// arrivals + walk-ins.
//
// - On a phone (coarse pointer / narrow viewport), the card embeds
// the scanner inline, exactly as before. A door volunteer on a
// phone doesn't need the magic-link detour.
//
// In either case, walk-ins + the arrivals counter are available on
// every device — those work just fine without a camera.
interface CheckInRecord {
id: string
@@ -28,6 +40,13 @@ interface ListResponse {
summary: Summary
}
interface ScannerTicket {
token: string
url: string
qr_image: string
expires_at: string
}
const props = defineProps<{
eventId: string
yourRole?: 'owner' | 'editor' | 'viewer' | null
@@ -64,7 +83,76 @@ async function refresh() {
}
onMounted(refresh)
// --- camera + scanner ---
// --- device class (desktop vs phone) ---
//
// Heuristic: a phone has a coarse pointer (touch) AND a narrow viewport.
// Anything else (laptops, big tablets with mice, desks) gets the
// magic-link UX. The host can still override with "Use this device's
// camera anyway" if they really want to.
const isMobileDevice = ref(false)
const useThisDevice = ref(false) // user override → behave as if mobile
function detectMobile() {
if (typeof window === 'undefined') return
const coarse = window.matchMedia('(pointer: coarse)').matches
const narrow = window.innerWidth < 768
isMobileDevice.value = coarse && narrow
}
onMounted(() => {
detectMobile()
window.addEventListener('resize', detectMobile)
})
onUnmounted(() => {
if (typeof window !== 'undefined') window.removeEventListener('resize', detectMobile)
})
const scannerOnThisDevice = computed(() => isMobileDevice.value || useThisDevice.value)
// --- magic-link / scanner ticket ---
const ticket = ref<ScannerTicket | null>(null)
const ticketLoading = ref(false)
const ticketError = ref<string | null>(null)
const linkCopied = ref(false)
async function mintTicket() {
ticketLoading.value = true
ticketError.value = null
try {
const res = await useApi<ScannerTicket>(`/events/${props.eventId}/scanner-ticket`, {
method: 'POST',
})
ticket.value = res
} catch (e: any) {
ticketError.value = useErrMessage(e, 'Could not create scanner link')
} finally {
ticketLoading.value = false
}
}
async function copyLink() {
if (!ticket.value) return
try {
await navigator.clipboard.writeText(ticket.value.url)
linkCopied.value = true
setTimeout(() => { linkCopied.value = false }, 1500)
} catch {
showToast({ kind: 'error', text: 'Could not copy link.' })
}
}
function expiresIn(iso: string): string {
const ms = new Date(iso).getTime() - Date.now()
if (ms <= 0) return 'expired'
const mins = Math.round(ms / 60000)
if (mins < 60) return `${mins} min`
const hrs = Math.floor(mins / 60)
const rem = mins % 60
return rem ? `${hrs}h ${rem}m` : `${hrs}h`
}
// --- camera + scanner (mobile / opt-in desktop) ---
const scannerOpen = ref(false)
const videoRef = ref<HTMLVideoElement | null>(null)
@@ -75,9 +163,6 @@ const lastScanAt = ref(0)
const recentlyScanned = ref<Set<string>>(new Set())
async function ensureJsQR() {
// Load jsQR from a CDN once. We attach it to window.jsQR so the
// scanner loop can call it. If it's already loaded (host opens +
// closes the scanner repeatedly) reuse the existing copy.
if (typeof window === 'undefined') return null
const w = window as any
if (w.jsQR) return w.jsQR
@@ -154,17 +239,12 @@ function scanLoop(jsQR: any) {
tick()
}
// shouldProcessScan throttles + dedupes scans. The camera grabs ~30
// frames per second; without a guard we'd POST 30x for one paper QR.
function shouldProcessScan(payload: string): boolean {
const now = Date.now()
if (now - lastScanAt.value < 1500) return false
if (recentlyScanned.value.has(payload)) return false
lastScanAt.value = now
recentlyScanned.value.add(payload)
// Expire from the dedupe set after 10s so a guest who legitimately
// re-scans (e.g. host re-pointing camera at the same code by accident)
// doesn't get stuck.
setTimeout(() => recentlyScanned.value.delete(payload), 10_000)
return true
}
@@ -263,7 +343,11 @@ const arrivalPct = computed(() => {
</div>
<div v-if="canEdit" class="flex items-center gap-2">
<button class="btn-ghost text-sm" @click="openWalkIn">+ Walk-in</button>
<button class="btn-primary text-sm" @click="openScanner">
<button
v-if="scannerOnThisDevice"
class="btn-primary text-sm"
@click="openScanner"
>
<svg class="mr-1 inline-block h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path d="M4 4a1 1 0 011-1h3a1 1 0 010 2H6v2a1 1 0 11-2 0V4zm0 12a1 1 0 011-1h2v-2a1 1 0 112 0v3a1 1 0 01-1 1H5a1 1 0 01-1-1zM16 4a1 1 0 00-1-1h-3a1 1 0 100 2h2v2a1 1 0 102 0V4zm0 12a1 1 0 01-1 1h-3a1 1 0 110-2h2v-2a1 1 0 112 0v3z" />
</svg>
@@ -276,6 +360,66 @@ const arrivalPct = computed(() => {
<p v-if="loading" class="text-sm text-zinc-500">Loading</p>
<div v-else class="space-y-5">
<!-- Desktop magic-link panel. Hosts almost never check guests in
from a laptop, so this nudges them onto the right device. -->
<div
v-if="canEdit && !scannerOnThisDevice"
class="rounded-lg border border-zinc-800 bg-zinc-950/60 p-4"
>
<div class="flex items-start justify-between gap-3">
<div>
<p class="text-sm font-medium text-zinc-100">Scan with your phone</p>
<p class="mt-1 text-xs text-zinc-500">
Webcams on laptops don't aim well at paper or phone-screen QR codes.
Open the scanner on a phone instead. Tap below to get a link.
</p>
</div>
</div>
<div v-if="!ticket && !ticketLoading" class="mt-3">
<button class="btn-primary text-sm" @click="mintTicket">Open scanner on phone</button>
<p class="mt-2 text-xs text-zinc-500">
Or <button class="underline hover:text-zinc-300" @click="useThisDevice = true">use this device's camera</button>.
</p>
</div>
<p v-if="ticketLoading" class="mt-3 text-xs text-zinc-500">Creating link</p>
<p v-if="ticketError" class="mt-3 text-xs text-red-400">{{ ticketError }}</p>
<div v-if="ticket" class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-[200px,1fr]">
<div class="rounded-md border border-zinc-800 bg-white p-3 text-center">
<img :src="ticket.qr_image" alt="Scanner magic link QR" class="mx-auto h-44 w-44" />
</div>
<div class="space-y-3">
<div>
<p class="text-xs font-medium uppercase tracking-wider text-zinc-500">Point your phone camera at the QR</p>
<p class="mt-1 text-sm text-zinc-300">
It'll open the scanner on your phone, already signed in for this event.
Hand the phone to whoever's on the door.
</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<button
class="rounded-md border border-zinc-700 px-3 py-1.5 text-xs hover:border-zinc-500 hover:bg-zinc-900"
@click="copyLink"
>{{ linkCopied ? 'Copied' : 'Copy link' }}</button>
<a
:href="ticket.url"
target="_blank"
rel="noopener"
class="rounded-md border border-zinc-700 px-3 py-1.5 text-xs hover:border-zinc-500 hover:bg-zinc-900"
>Open in new tab</a>
<button
class="rounded-md border border-zinc-700 px-3 py-1.5 text-xs hover:border-zinc-500 hover:bg-zinc-900"
@click="mintTicket"
>New link</button>
</div>
<p class="text-xs text-zinc-500">
Link expires in {{ expiresIn(ticket.expires_at) }}. Anyone with this link can check guests in for this event only.
</p>
</div>
</div>
</div>
<!-- Live arrivals widget. The big number is what a host glances
at "are we full yet?" -->
<div class="rounded-lg border border-brand-700/40 bg-brand-500/[0.06] p-4">
@@ -326,8 +470,8 @@ const arrivalPct = computed(() => {
</div>
</div>
<!-- Scanner modal. Camera is only mounted while open; closing tears
down the stream so the camera light goes off. -->
<!-- Scanner modal. Mounted only on phones (or opt-in via the
"use this device's camera" link). -->
<Teleport to="body">
<div
v-if="scannerOpen"
@@ -341,7 +485,6 @@ const arrivalPct = computed(() => {
<div class="relative flex-1 overflow-hidden">
<video ref="videoRef" playsinline class="h-full w-full object-cover"></video>
<canvas ref="canvasRef" class="hidden"></canvas>
<!-- A simple frame to guide the host. -->
<div class="pointer-events-none absolute inset-0 flex items-center justify-center">
<div class="h-64 w-64 rounded-lg border-2 border-brand-500/80 shadow-[0_0_0_9999px_rgba(0,0,0,0.55)]"></div>
</div>
+133 -80
View File
@@ -47,6 +47,11 @@ const countingRecipients = ref(false)
// Tab state for the message list.
const activeList = ref<'scheduled' | 'sent' | 'cancelled'>('scheduled')
// Compose form is collapsed by default so the screen leads with what's
// already scheduled. Hosts only need to open this when they want to
// send a custom broadcast — the auto-reminders take care of themselves.
const composeOpen = ref(false)
// Toast.
type Toast = { kind: 'success' | 'error'; text: string }
const toast = ref<Toast | null>(null)
@@ -208,9 +213,7 @@ const activeMessages = computed(() => {
<header class="mb-3">
<h2 class="text-lg font-semibold">Communications</h2>
<p class="text-xs text-zinc-500">
Reminders and broadcasts to your guests. The big day's automatic nudges
(7 days out, 3-day last call, 1 day before, and day-of) are pre-scheduled
for you; edit or cancel anything you don't want.
What gets sent to your guests and when.
</p>
</header>
@@ -218,88 +221,30 @@ const activeMessages = computed(() => {
<p v-if="loading" class="text-sm text-zinc-500">Loading</p>
<div v-else class="space-y-6">
<!-- Compose -->
<div v-if="canEdit" class="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<h3 class="mb-3 text-sm font-semibold text-zinc-100">Compose a message</h3>
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
<div>
<label class="label">Audience</label>
<select v-model="audience" class="input text-sm">
<option value="all">Everyone</option>
<option value="attending">Attending</option>
<option value="pending">Haven't replied yet</option>
<option value="declined">Declined</option>
<option value="maybe">Maybe</option>
</select>
<p class="mt-1 text-xs text-zinc-500">
<span v-if="countingRecipients">Counting…</span>
<span v-else-if="recipientCount !== null">
{{ recipientCount }} {{ recipientCount === 1 ? 'guest' : 'guests' }} will receive this.
</span>
<!-- Reassurance callout. Hosts often think the compose form
below means they have to *do something* to make reminders
work. This panel tells them the opposite. -->
<div class="rounded-lg border border-brand-700/40 bg-brand-500/[0.06] p-4">
<div class="flex items-start gap-3">
<svg class="mt-0.5 h-5 w-5 shrink-0 text-brand-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M16.704 5.296a1 1 0 010 1.408l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.592l7.296-7.296a1 1 0 011.408 0z" clip-rule="evenodd" />
</svg>
<div class="text-sm">
<p class="font-medium text-brand-200">
Reminders are already set up. You don't need to do anything.
</p>
<p class="mt-1 text-zinc-300">
When you created this event we scheduled four automatic nudges for guests who
haven't replied yet and your attending guests: a 7-day note, a 3-day last call,
a 1-day reminder, and a day-of message. You'll see them in the list below.
Cancel any you don't want, edit the wording, or hit <em>Send now</em> to fire
one early.
</p>
</div>
<div>
<label class="label">Subject (optional)</label>
<input v-model="subject" class="input text-sm" placeholder="A friendly nudge from us" />
</div>
</div>
<div class="mt-3">
<label class="label">Message</label>
<textarea
v-model="body"
class="input min-h-[100px] text-sm"
placeholder="Hi {{guest_name}}, just a reminder about {{event_name}} on {{event_date}}. RSVP here: {{rsvp_link}}"
></textarea>
<p class="mt-1 text-xs text-zinc-500">
You can use these placeholders, and they'll be filled in per guest:
<template v-for="(tok, i) in placeholderTokens" :key="tok">
<code class="text-zinc-400">{{ tok }}</code><span v-if="i < placeholderTokens.length - 1">, </span>
</template>.
</p>
</div>
<div class="mt-3 grid grid-cols-1 gap-3 md:grid-cols-[1fr_auto]">
<div>
<label class="label">When</label>
<div class="flex flex-wrap items-center gap-2">
<label class="flex items-center gap-1.5 text-sm">
<input v-model="sendMode" type="radio" value="now" />
Send now
</label>
<label class="flex items-center gap-1.5 text-sm">
<input v-model="sendMode" type="radio" value="schedule" />
Schedule for
</label>
<input
v-if="sendMode === 'schedule'"
v-model="sendAt"
type="datetime-local"
class="input text-sm"
/>
<label class="flex items-center gap-1.5 text-sm">
<input v-model="sendMode" type="radio" value="draft" />
Save as draft
</label>
</div>
</div>
<div class="flex items-end">
<button
class="btn-primary text-sm"
:disabled="sending || !body.trim() || (sendMode === 'schedule' && !sendAt)"
@click="compose"
>
{{ sending ? 'Saving…' :
sendMode === 'now' ? 'Send now' :
sendMode === 'schedule' ? 'Schedule' :
'Save draft' }}
</button>
</div>
</div>
</div>
<!-- List tabs -->
<!-- List tabs FIRST so the host sees the schedule before any compose UI. -->
<div>
<div class="mb-3 flex items-center gap-1 rounded-lg border border-zinc-800 bg-zinc-900/40 p-1 text-sm">
<button
@@ -388,6 +333,114 @@ const activeMessages = computed(() => {
</li>
</ul>
</div>
<!-- Custom broadcast explicitly demoted. Closed by default so
the page lands on the schedule, not a blank compose form
that implies you must fill it out for anything to happen. -->
<div v-if="canEdit" class="rounded-lg border border-zinc-800 bg-zinc-950">
<button
type="button"
class="flex w-full items-center justify-between p-4 text-left"
@click="composeOpen = !composeOpen"
>
<span>
<span class="block text-sm font-semibold text-zinc-100">Send a custom broadcast</span>
<span class="block text-xs text-zinc-500">
Optional. Use this only if you want to send something extra on top of the
automatic reminders above.
</span>
</span>
<svg
class="h-4 w-4 text-zinc-500 transition-transform"
:class="composeOpen ? 'rotate-180' : ''"
viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"
>
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</button>
<div v-show="composeOpen" class="border-t border-zinc-900 p-4">
<p class="mb-3 text-xs text-zinc-500">
For one-off messages change of venue, weather notice, dress-code reminder.
Compose once, picks the audience, and choose when it goes out.
</p>
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
<div>
<label class="label">Audience</label>
<select v-model="audience" class="input text-sm">
<option value="all">Everyone</option>
<option value="attending">Attending</option>
<option value="pending">Haven't replied yet</option>
<option value="declined">Declined</option>
<option value="maybe">Maybe</option>
</select>
<p class="mt-1 text-xs text-zinc-500">
<span v-if="countingRecipients">Counting…</span>
<span v-else-if="recipientCount !== null">
{{ recipientCount }} {{ recipientCount === 1 ? 'guest' : 'guests' }} will receive this.
</span>
</p>
</div>
<div>
<label class="label">Subject (optional)</label>
<input v-model="subject" class="input text-sm" placeholder="A friendly nudge from us" />
</div>
</div>
<div class="mt-3">
<label class="label">Message</label>
<textarea
v-model="body"
class="input min-h-[100px] text-sm"
placeholder="Hi {{guest_name}}, just a reminder about {{event_name}} on {{event_date}}. RSVP here: {{rsvp_link}}"
></textarea>
<p class="mt-1 text-xs text-zinc-500">
You can use these placeholders, and they'll be filled in per guest:
<template v-for="(tok, i) in placeholderTokens" :key="tok">
<code class="text-zinc-400">{{ tok }}</code><span v-if="i < placeholderTokens.length - 1">, </span>
</template>.
</p>
</div>
<div class="mt-3 grid grid-cols-1 gap-3 md:grid-cols-[1fr_auto]">
<div>
<label class="label">When</label>
<div class="flex flex-wrap items-center gap-2">
<label class="flex items-center gap-1.5 text-sm">
<input v-model="sendMode" type="radio" value="now" />
Send now
</label>
<label class="flex items-center gap-1.5 text-sm">
<input v-model="sendMode" type="radio" value="schedule" />
Schedule for
</label>
<input
v-if="sendMode === 'schedule'"
v-model="sendAt"
type="datetime-local"
class="input text-sm"
/>
<label class="flex items-center gap-1.5 text-sm">
<input v-model="sendMode" type="radio" value="draft" />
Save as draft
</label>
</div>
</div>
<div class="flex items-end">
<button
class="btn-primary text-sm"
:disabled="sending || !body.trim() || (sendMode === 'schedule' && !sendAt)"
@click="compose"
>
{{ sending ? 'Saving…' :
sendMode === 'now' ? 'Send now' :
sendMode === 'schedule' ? 'Schedule' :
'Save draft' }}
</button>
</div>
</div>
</div><!-- /v-show composeOpen -->
</div><!-- /custom broadcast disclosure -->
</div>
<Teleport to="body">
+78
View File
@@ -95,6 +95,21 @@ const thresholds = ref<Thresholds>({ medium: 30, high: 60, block: 85, defaults:
const allowlist = ref<AllowlistEntry[]>([])
const feedback = ref<FeedbackEntry[]>([])
// Threshold-preview state. Live counter under the sliders given the
// host's *proposed* settings, how would the event's past access events
// have been classified? Removes the "guess and wait for new scans"
// step that used to be the only way to feel confident before saving.
interface ThresholdPreview {
total: number
low: number
medium: number
high: number
block: number
}
const preview = ref<ThresholdPreview | null>(null)
const previewLoading = ref(false)
let previewTimer: ReturnType<typeof setTimeout> | null = null
const showAdvanced = ref(false)
const showAddNetwork = ref(false)
const newNetworkIP = ref('')
@@ -132,6 +147,33 @@ async function refresh() {
}
onMounted(refresh)
// Debounced preview fetch. Watching the threshold refs catches both
// slider drags and preset clicks; 250ms is short enough to feel
// instant while still avoiding a request per pixel of drag.
async function fetchPreview() {
try {
previewLoading.value = true
const t = thresholds.value
const data = await useApi<ThresholdPreview>(
`/events/${props.eventId}/security/thresholds/preview?medium=${t.medium}&high=${t.high}&block=${t.block}`,
)
preview.value = data
} catch {
// Network blip / 403 from viewer just hide the panel until next try.
preview.value = null
} finally {
previewLoading.value = false
}
}
watch(
() => [thresholds.value.medium, thresholds.value.high, thresholds.value.block],
() => {
if (previewTimer) clearTimeout(previewTimer)
previewTimer = setTimeout(fetchPreview, 250)
},
{ immediate: true },
)
// Which preset does the current threshold triple correspond to?
// Exact match wins; otherwise "Custom". Selecting a preset writes its
// triple over the current values and saves on the next click.
@@ -475,6 +517,42 @@ function verdictLabel(v: string) {
</p>
</label>
</div>
<!-- Threshold preview. Concrete counts answer the host's
unspoken "is this too strict?" question better than any
amount of explainer copy. Empty state when nothing's
been scored yet keeps the panel honest. -->
<div class="mt-4 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3 text-xs">
<div class="mb-2 flex items-center justify-between text-zinc-400">
<span>
With these settings applied to your last
<span class="font-medium text-zinc-200">{{ preview?.total ?? 0 }}</span>
{{ (preview?.total ?? 0) === 1 ? 'access event' : 'access events' }}:
</span>
<span v-if="previewLoading" class="text-zinc-500">refreshing</span>
</div>
<div v-if="!preview || preview.total === 0" class="text-zinc-500">
No scored access events yet. The preview will fill in as guests start opening invitations.
</div>
<div v-else class="grid grid-cols-4 gap-2">
<div class="rounded-md border border-zinc-800 bg-zinc-950 p-2 text-center">
<div class="text-[10px] uppercase tracking-wider text-zinc-500">Quiet</div>
<div class="mt-0.5 text-lg font-semibold tabular-nums text-zinc-200">{{ preview.low }}</div>
</div>
<div class="rounded-md border border-brand-700/40 bg-brand-500/[0.06] p-2 text-center">
<div class="text-[10px] uppercase tracking-wider text-brand-400">Watched</div>
<div class="mt-0.5 text-lg font-semibold tabular-nums text-brand-200">{{ preview.medium }}</div>
</div>
<div class="rounded-md border border-amber-800/40 bg-amber-500/[0.06] p-2 text-center">
<div class="text-[10px] uppercase tracking-wider text-amber-300">Flagged</div>
<div class="mt-0.5 text-lg font-semibold tabular-nums text-amber-200">{{ preview.high }}</div>
</div>
<div class="rounded-md border border-red-800/40 bg-red-500/[0.06] p-2 text-center">
<div class="text-[10px] uppercase tracking-wider text-red-300">Refused</div>
<div class="mt-0.5 text-lg font-semibold tabular-nums text-red-200">{{ preview.block }}</div>
</div>
</div>
</div>
</div>
</details>
</div>
+161 -20
View File
@@ -60,6 +60,46 @@ const eventId = route.params.id as string
const event = ref<EventDetail | null>(null)
const guests = ref<Guest[]>([])
const stats = ref<GuestStats>({ total: 0, attending: 0, declined: 0, maybe: 0, pending: 0 })
// Day-of arrivals headline. Visible above the tab bar once any check-in
// has been recorded; ticks up in real time via the check_in.recorded WS
// broadcast so the host doesn't have to flip to the Check-in tab to see
// progress on the door.
interface CheckInSummary {
arrived_headcount: number
expected_headcount: number
guests_checked_in: number
}
const checkInSummary = ref<CheckInSummary>({ arrived_headcount: 0, expected_headcount: 0, guests_checked_in: 0 })
const arrivalsPct = computed(() => {
const s = checkInSummary.value
if (!s.expected_headcount) return 0
return Math.min(100, Math.round((s.arrived_headcount / s.expected_headcount) * 100))
})
// The arrivals headline is a day-of tool, not a general-purpose
// counter. Surfacing it weeks before the event would be noise on the
// dashboard. Show it only when the host's local calendar date matches
// the event date (or there have actually been check-ins recorded
// today, which would imply the event is happening regardless of how
// event_date is stored).
const showArrivalsWidget = computed(() => {
if (!event.value?.event_date) return false
const evt = new Date(event.value.event_date)
if (isNaN(evt.getTime())) return false
const today = new Date()
return evt.getFullYear() === today.getFullYear()
&& evt.getMonth() === today.getMonth()
&& evt.getDate() === today.getDate()
})
async function refreshArrivals() {
try {
const data = await useApi<{ summary: CheckInSummary }>(`/events/${eventId}/check-ins`)
if (data?.summary) checkInSummary.value = data.summary
} catch {
// Viewer roles can read this; a transient failure shouldn't take
// down the rest of the page.
}
}
const filter = ref<'all' | 'attending' | 'declined' | 'maybe' | 'pending'>('all')
const loading = ref(true)
@@ -71,6 +111,53 @@ const loading = ref(true)
// clusters in the middle.
type EventTab = 'guests' | 'collaborators' | 'communications' | 'branding' | 'analytics' | 'gate' | 'checkin'
const validTabs: EventTab[] = ['guests', 'collaborators', 'communications', 'branding', 'analytics', 'gate', 'checkin']
// Tab metadata. Icons are inline heroicons-style outline marks at 24px
// viewBox; the template renders them at 18px and lets currentColor
// inherit the active/inactive text colour. Keeping the SVG data here
// (rather than in <template>) means the v-for stays one-liner clean.
interface TabDef {
id: EventTab
label: string
icon: string // inner SVG markup
}
const tabs: TabDef[] = [
{
id: 'guests',
label: 'Guests',
icon: '<path stroke-linecap="round" stroke-linejoin="round" d="M15 19.128a9.38 9.38 0 0 0 2.625.372 9.337 9.337 0 0 0 4.121-.952 4.125 4.125 0 0 0-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 0 1 8.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0 1 11.964-3.07M12 6.375a3.375 3.375 0 1 1-6.75 0 3.375 3.375 0 0 1 6.75 0Zm8.25 2.25a2.625 2.625 0 1 1-5.25 0 2.625 2.625 0 0 1 5.25 0Z"/>',
},
{
id: 'collaborators',
label: 'Collaborators',
icon: '<path stroke-linecap="round" stroke-linejoin="round" d="M18 18.72a9.094 9.094 0 0 0 3.741-.479 3 3 0 0 0-4.682-2.72m.94 3.198.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0 1 12 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 0 1 6 18.719m12 0a5.971 5.971 0 0 0-.941-3.197m0 0A5.995 5.995 0 0 0 12 12.75a5.995 5.995 0 0 0-5.058 2.772m0 0a3 3 0 0 0-4.681 2.72 8.986 8.986 0 0 0 3.74.477m.94-3.197a5.971 5.971 0 0 0-.94 3.197M15 6.75a3 3 0 1 1-6 0 3 3 0 0 1 6 0Zm6 3a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Zm-13.5 0a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z"/>',
},
{
id: 'communications',
label: 'Communications',
icon: '<path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 0 1-2.25 2.25h-15a2.25 2.25 0 0 1-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25m19.5 0v.243a2.25 2.25 0 0 1-1.07 1.916l-7.5 4.615a2.25 2.25 0 0 1-2.36 0L3.32 8.91a2.25 2.25 0 0 1-1.07-1.916V6.75"/>',
},
{
id: 'branding',
label: 'Branding',
icon: '<path stroke-linecap="round" stroke-linejoin="round" d="M9.53 16.122a3 3 0 0 0-5.78 1.128 2.25 2.25 0 0 1-2.4 2.245 4.5 4.5 0 0 0 8.4-2.245c0-.399-.078-.78-.22-1.128Zm0 0a15.998 15.998 0 0 0 3.388-1.62m-5.043-.025a15.994 15.994 0 0 1 1.622-3.395m3.42 3.42a15.995 15.995 0 0 0 4.764-4.648l3.876-5.814a1.151 1.151 0 0 0-1.597-1.597L14.146 6.32a15.996 15.996 0 0 0-4.649 4.763m3.42 3.42a6.776 6.776 0 0 0-3.42-3.42"/>',
},
{
id: 'analytics',
label: 'Analytics',
icon: '<path stroke-linecap="round" stroke-linejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 0 1 3 19.875v-6.75ZM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V8.625ZM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V4.125Z"/>',
},
{
id: 'gate',
label: 'Gate',
icon: '<path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12c0 1.268-.63 2.39-1.593 3.068a3.745 3.745 0 0 1-1.043 3.296 3.745 3.745 0 0 1-3.296 1.043A3.745 3.745 0 0 1 12 21c-1.268 0-2.39-.63-3.068-1.593a3.746 3.746 0 0 1-3.296-1.043 3.745 3.745 0 0 1-1.043-3.296A3.745 3.745 0 0 1 3 12c0-1.268.63-2.39 1.593-3.068a3.745 3.745 0 0 1 1.043-3.296 3.746 3.746 0 0 1 3.296-1.043A3.746 3.746 0 0 1 12 3c1.268 0 2.39.63 3.068 1.593a3.746 3.746 0 0 1 3.296 1.043 3.746 3.746 0 0 1 1.043 3.296A3.745 3.745 0 0 1 21 12Z"/>',
},
{
id: 'checkin',
label: 'Check-in',
icon: '<path stroke-linecap="round" stroke-linejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0 1 3.75 9.375v-4.5ZM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 0 1-1.125-1.125v-4.5ZM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5C19.746 3.75 20.25 4.254 20.25 4.875v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0 1 13.5 9.375v-4.5Z M6.75 6.75h.008v.008H6.75V6.75ZM6.75 16.5h.008v.008H6.75V16.5ZM16.5 6.75h.008v.008H16.5V6.75ZM13.5 13.5h.008v.008H13.5V13.5ZM13.5 19.5h.008v.008H13.5V19.5ZM19.5 13.5h.008v.008H19.5V13.5ZM19.5 19.5h.008v.008H19.5V19.5ZM16.5 16.5h.008v.008H16.5V16.5Z"/>',
},
]
function tabFromHash(): EventTab {
if (import.meta.client) {
const h = window.location.hash.replace('#', '') as EventTab
@@ -104,6 +191,10 @@ async function refresh() {
event.value = evt
guests.value = list.guests || []
if (list.stats) stats.value = list.stats
// Fire-and-forget so a slow check-ins query doesn't hold up the rest
// of the page. Viewer roles will 403 on this endpoint that's fine,
// refreshArrivals swallows it.
void refreshArrivals()
}
const filteredGuests = computed(() => {
@@ -713,6 +804,22 @@ onMounted(() => {
})
// Refresh stats and per-guest status so the counts reflect the new RSVP.
refresh().catch(() => {})
} else if (msg.type === 'check_in.recorded') {
// Day-of arrivals stream. The payload already carries the
// updated headcount so we don't have to re-fetch the summary.
const p = msg.payload || {}
if (typeof p.arrived_headcount === 'number') {
checkInSummary.value = {
arrived_headcount: p.arrived_headcount,
expected_headcount: p.expected_headcount ?? checkInSummary.value.expected_headcount,
guests_checked_in: p.guests_checked_in ?? checkInSummary.value.guests_checked_in,
}
}
pushFeed({
type: msg.type,
ts: msg.timestamp,
text: `${p.guest_name || 'Guest'} checked in${p.walk_in ? ' (walk-in)' : ''}.`,
})
} else if (msg.type === 'fraud.scored') {
const g = guestById.value[msg.payload.guest_id]
const who = g?.name || 'A guest'
@@ -770,39 +877,73 @@ function checkLabel(band?: string): string {
<p class="text-sm text-zinc-400">{{ event.venue }} · {{ fmtDate(event.event_date) }}</p>
</div>
<!-- Tab nav segmented-control style: a single bordered container
with a brand-tinted "lifted" state for the active tab. Stronger
visual weight than underlined tabs, no overflow tricks (the
previous absolute-positioned underline was leaking a 1px vertical
scrollbar on the sticky container). Mobile wraps onto two rows
when needed rather than introducing horizontal scroll. -->
<!-- Day-of arrivals headline. Only renders once anything's been
recorded so it doesn't dominate the page in the weeks before
the event. Updates live via WS. -->
<div
v-if="showArrivalsWidget"
class="flex items-center justify-between gap-4 rounded-lg border border-brand-700/40 bg-brand-500/[0.06] px-4 py-3"
>
<div class="min-w-0">
<p class="text-[10px] font-medium uppercase tracking-widest text-brand-400">Arrived</p>
<p class="mt-0.5 text-2xl font-semibold tabular-nums text-brand-200">
{{ checkInSummary.arrived_headcount }}
<span class="text-sm font-normal text-zinc-400">of {{ checkInSummary.expected_headcount }}</span>
<span class="ml-2 text-xs font-normal text-zinc-500">·
{{ checkInSummary.guests_checked_in }}
{{ checkInSummary.guests_checked_in === 1 ? 'guest' : 'guests' }} in
</span>
</p>
</div>
<div class="flex shrink-0 items-center gap-3">
<div class="hidden h-1.5 w-32 overflow-hidden rounded-full bg-zinc-900 sm:block">
<div class="h-full rounded-full bg-brand-500 transition-all" :style="{ width: arrivalsPct + '%' }"></div>
</div>
<p class="text-lg font-semibold text-brand-200 tabular-nums">{{ arrivalsPct }}%</p>
<button
class="rounded-md border border-zinc-700 px-2.5 py-1 text-xs hover:border-zinc-500 hover:bg-zinc-900"
@click="setTab('checkin')"
>Open scanner</button>
</div>
</div>
<!-- Tab nav. Segmented-control take inspired by Linear / Vercel:
icon + label per tab, soft active fill, accessible focus ring,
consistent 18px outline-style icons (heroicons set). On narrow
viewports the row scrolls horizontally instead of wrapping to
two ragged rows feels more "app-like" and keeps the labels
legible even on phones in portrait. -->
<nav
role="tablist"
aria-label="Event sections"
class="flex flex-wrap gap-1 rounded-lg border border-zinc-800 bg-zinc-900/40 p-1"
class="-mx-1 flex gap-1 overflow-x-auto rounded-xl border border-zinc-800 bg-zinc-900/60 p-1 shadow-inner [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
>
<button
v-for="t in [
{ id: 'guests', label: 'Guests' },
{ id: 'collaborators', label: 'Collaborators' },
{ id: 'communications', label: 'Communications' },
{ id: 'checkin', label: 'Check-in' },
{ id: 'branding', label: 'Branding' },
{ id: 'analytics', label: 'Analytics' },
{ id: 'gate', label: 'Gate' },
] as { id: EventTab, label: string }[]"
v-for="t in tabs"
:key="t.id"
role="tab"
:aria-selected="activeTab === t.id"
:class="[
'flex-1 whitespace-nowrap rounded-md px-3 py-2 text-sm font-medium transition',
'group relative inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-lg px-3.5 py-2 text-sm font-medium transition-all duration-150',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500/60 focus-visible:ring-offset-1 focus-visible:ring-offset-zinc-950',
activeTab === t.id
? 'border border-brand-700/40 bg-brand-500/10 text-brand-200 shadow-sm'
: 'border border-transparent text-zinc-400 hover:bg-zinc-800/60 hover:text-zinc-100',
? 'bg-brand-500/15 text-brand-100 shadow-[inset_0_-2px_0_0_#22c55e]'
: 'text-zinc-400 hover:bg-zinc-800/70 hover:text-zinc-100',
]"
@click="setTab(t.id)"
>
{{ t.label }}
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.6"
stroke="currentColor"
class="h-[18px] w-[18px] shrink-0 transition-colors"
:class="activeTab === t.id ? 'text-brand-300' : 'text-zinc-500 group-hover:text-zinc-300'"
aria-hidden="true"
v-html="t.icon"
/>
<span class="leading-none">{{ t.label }}</span>
</button>
</nav>
+41 -5
View File
@@ -216,6 +216,18 @@ function fmtDate(iso?: string) {
try { return new Date(iso).toLocaleString() } catch { return iso }
}
// Slug + filename for the downloaded QR. Keeps a guest's downloads
// folder readable when they save codes for several events instead of
// ending up with a stack of "qr (4).png" copies.
function qrDownloadFilename(): string {
const name = access.value?.event?.name || 'invitation'
const slug = name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
return `${slug || 'invitation'}-rsvp-qr.png`
}
// Calendar links come from the backend so we don't reimplement Google /
// Outlook / Yahoo encoding rules per provider. They're available as soon
// as /access loads the guest can grab them before submitting.
@@ -327,9 +339,9 @@ const submitLabel = computed(() => {
class="mt-5 border-t border-zinc-800 pt-4"
/>
<!-- Block H door QR for attending guests. Shown right under
"you're confirmed" because that's when the guest is most
likely to screenshot or save the email. -->
<!-- Block H door QR for attending guests. The same code is
also delivered in the confirmation email so the guest has
two ways to keep it. -->
<div
v-if="access?.check_in && result.rsvp.response === 'attending'"
class="mt-5 border-t border-zinc-800 pt-4"
@@ -338,8 +350,8 @@ const submitLabel = computed(() => {
Save for the day
</p>
<p class="mb-3 text-sm text-zinc-300">
Show this code at the door for a quick check-in. Screenshot it now,
or look out for the same code on your confirmation email.
Show this code at the door for a quick check-in. We've also sent it to your
email keep whichever's easier.
</p>
<div class="flex items-center justify-center rounded-md border border-zinc-800 bg-white p-3">
<img
@@ -348,6 +360,18 @@ const submitLabel = computed(() => {
class="h-44 w-44"
/>
</div>
<div class="mt-3 flex items-center justify-center">
<a
:href="access.check_in.qr_image"
:download="qrDownloadFilename()"
class="btn-ghost inline-flex items-center gap-1.5 text-sm"
>
<svg class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm6.293-3.707a1 1 0 011.414 0L13 15.586V5a1 1 0 112 0v10.586l2.293-2.293a1 1 0 011.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" />
</svg>
Download QR
</a>
</div>
</div>
<div v-if="!editLimitReached" class="mt-5 flex items-center justify-between gap-3 border-t border-zinc-800 pt-4">
@@ -399,6 +423,18 @@ const submitLabel = computed(() => {
class="h-44 w-44"
/>
</div>
<div class="mt-3 flex items-center justify-center">
<a
:href="access.check_in.qr_image"
:download="qrDownloadFilename()"
class="btn-ghost inline-flex items-center gap-1.5 text-sm"
>
<svg class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm6.293-3.707a1 1 0 011.414 0L13 15.586V5a1 1 0 112 0v10.586l2.293-2.293a1 1 0 011.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" />
</svg>
Download QR
</a>
</div>
</div>
<div v-if="!editLimitReached" class="flex items-center justify-between gap-3 border-t border-zinc-800 pt-4">
+790
View File
@@ -0,0 +1,790 @@
<script setup lang="ts">
// /scanner the page a door volunteer's phone lands on after the host
// shares a magic link (or the host points their own phone at the QR on
// their desktop event-detail page).
//
// Flow per scan:
//
// 1. Camera detects a QR handleScannedPayload()
// 2. Pause the camera + dedupe set
// 3. POST /events/{id}/check-in/preview guest name + expected party size
// 4. Show confirmation panel with "Just them / +1 / +2 / Other" buttons
// 5. Volunteer taps a count POST /check-in with arrival_count
// 6. Success toast + summary update; cancel resume scanning
//
// The preview step is what lets the door volunteer correctly record
// "the bride brought her cousin who wasn't invited" without making them
// type or wonder whether they're recording two people instead of one.
//
// Offline / flaky-network mode (task #42):
//
// When the record POST fails with a network error (no connectivity,
// 5xx), the {qr_payload, arrival_count, queued_at} tuple goes into an
// IndexedDB store. A small badge surfaces "N queued"; the queue
// drains automatically on 'online', and an explicit "Sync now" button
// gives the volunteer a manual lever if they're behind a captive
// portal. Server-side 4xx (already-checked-in, bad QR, scoped-to-
// different-event) deliberately don't re-queue those are user-
// facing problems, not transport problems.
definePageMeta({ layout: false })
useHead({
title: 'Door scanner · GuestGuard',
meta: [
{ name: 'viewport', content: 'width=device-width, initial-scale=1, viewport-fit=cover' },
{ name: 'theme-color', content: '#0a0a0a' },
{ name: 'apple-mobile-web-app-capable', content: 'yes' },
{ name: 'apple-mobile-web-app-status-bar-style', content: 'black-translucent' },
{ name: 'apple-mobile-web-app-title', content: 'GuestGuard Scanner' },
{ name: 'mobile-web-app-capable', content: 'yes' },
],
link: [
{ rel: 'manifest', href: '/manifest.json' },
],
})
interface Summary {
arrived_headcount: number
expected_headcount: number
guests_checked_in: number
}
interface CheckInRecord {
id: string
guest_id: string
checked_in_at: string
arrival_count: number
walk_in: boolean
}
interface ListResponse {
check_ins: CheckInRecord[]
summary: Summary
}
interface PreviewResponse {
guest: { id: string; name: string; plus_ones: number; email?: string | null }
expected_party_size: number
already_checked_in: boolean
existing_check_in?: CheckInRecord | null
}
const route = useRoute()
const router = useRouter()
const config = useRuntimeConfig()
const apiBase = config.public.apiBase as string
const token = ref<string>('')
const eventId = ref<string>('')
const tokenInvalid = ref(false)
const fatalError = ref<string | null>(null)
onMounted(() => {
token.value = String(route.query.token || '')
eventId.value = String(route.query.event || '')
if (!token.value || !eventId.value) {
tokenInvalid.value = true
return
}
void loadList()
void initQueue().then(() => {
void drainQueue()
refreshQueueCount()
})
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/scanner-sw.js').catch(() => {})
}
window.addEventListener('online', onOnline)
window.addEventListener('offline', onOffline)
})
onBeforeUnmount(() => {
if (typeof window === 'undefined') return
window.removeEventListener('online', onOnline)
window.removeEventListener('offline', onOffline)
})
async function authedFetch<T>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> {
return await $fetch<T>(path, {
baseURL: apiBase,
method: (init.method ?? 'GET') as any,
body: init.body as any,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token.value}`,
},
})
}
// --- summary + recent arrivals ---
const summary = ref<Summary>({ arrived_headcount: 0, expected_headcount: 0, guests_checked_in: 0 })
const recent = ref<CheckInRecord[]>([])
const offline = ref<boolean>(typeof navigator !== 'undefined' ? !navigator.onLine : false)
async function loadList() {
try {
const data = await authedFetch<ListResponse>(`/events/${eventId.value}/check-ins`)
summary.value = data.summary
recent.value = (data.check_ins || []).slice(0, 5)
} catch (e: any) {
const status = e?.response?.status ?? e?.statusCode
if (status === 401) {
tokenInvalid.value = true
return
}
// Network failure is fine we'll work from the queued local
// summary until the radio comes back.
if (!isNetworkError(e)) {
fatalError.value = e?.data?.error || 'Could not load arrivals.'
}
}
}
// --- IndexedDB queue ---
//
// Tiny one-store DB. We don't pull in idb-keyval to keep the bundle
// lean; the raw IndexedDB surface is enough for an append-only queue.
const QUEUE_DB = 'gg-scanner'
const QUEUE_STORE = 'pending-checkins'
const queueCount = ref(0)
let dbRef: IDBDatabase | null = null
function initQueue(): Promise<void> {
return new Promise((resolve) => {
if (typeof indexedDB === 'undefined') {
resolve()
return
}
const req = indexedDB.open(QUEUE_DB, 1)
req.onupgradeneeded = () => {
const db = req.result
if (!db.objectStoreNames.contains(QUEUE_STORE)) {
db.createObjectStore(QUEUE_STORE, { keyPath: 'id', autoIncrement: true })
}
}
req.onsuccess = () => {
dbRef = req.result
resolve()
}
req.onerror = () => resolve()
})
}
type QueueRow = {
id?: number
event_id: string
qr_payload: string
arrival_count: number
notes?: string
queued_at: number
}
function queueAdd(row: Omit<QueueRow, 'id'>): Promise<void> {
return new Promise((resolve) => {
if (!dbRef) { resolve(); return }
const tx = dbRef.transaction(QUEUE_STORE, 'readwrite')
tx.objectStore(QUEUE_STORE).add(row)
tx.oncomplete = () => { refreshQueueCount(); resolve() }
tx.onerror = () => resolve()
})
}
function queueAll(): Promise<QueueRow[]> {
return new Promise((resolve) => {
if (!dbRef) { resolve([]); return }
const tx = dbRef.transaction(QUEUE_STORE, 'readonly')
const req = tx.objectStore(QUEUE_STORE).getAll()
req.onsuccess = () => resolve((req.result as QueueRow[]) || [])
req.onerror = () => resolve([])
})
}
function queueDelete(id: number): Promise<void> {
return new Promise((resolve) => {
if (!dbRef) { resolve(); return }
const tx = dbRef.transaction(QUEUE_STORE, 'readwrite')
tx.objectStore(QUEUE_STORE).delete(id)
tx.oncomplete = () => { refreshQueueCount(); resolve() }
tx.onerror = () => resolve()
})
}
function refreshQueueCount() {
void queueAll().then((rows) => { queueCount.value = rows.length })
}
let draining = false
async function drainQueue() {
if (draining) return
if (typeof navigator !== 'undefined' && !navigator.onLine) return
draining = true
try {
const rows = await queueAll()
for (const row of rows) {
if (row.event_id !== eventId.value) continue // foreign event id leave it alone
try {
const res = await authedFetch<{ guest?: { name?: string }; summary: Summary; check_in: CheckInRecord }>(
`/events/${eventId.value}/check-in`,
{ method: 'POST', body: { qr_payload: row.qr_payload, arrival_count: row.arrival_count, notes: row.notes } },
)
summary.value = res.summary
recent.value = [res.check_in, ...recent.value].slice(0, 5)
if (row.id !== undefined) await queueDelete(row.id)
} catch (e: any) {
const status = e?.response?.status ?? e?.statusCode
if (status === 409 || status === 410 || status === 400 || status === 404) {
// Server says this scan will never succeed. Drop the row so
// the queue doesn't get stuck behind a poison message; surface
// it once to the volunteer.
if (row.id !== undefined) await queueDelete(row.id)
showToast({ kind: 'warn', text: `Queued scan dropped (${e?.data?.error || 'rejected'})` }, 3500)
continue
}
if (isNetworkError(e)) {
// Still offline stop and try again on next online event.
break
}
// 5xx etc. stop, retry later, but log fatally.
fatalError.value = e?.data?.error || 'Queued scan retry failed.'
break
}
}
} finally {
draining = false
refreshQueueCount()
}
}
function onOnline() {
offline.value = false
showToast({ kind: 'success', text: 'Back online. Syncing scans…' }, 2000)
void drainQueue()
}
function onOffline() {
offline.value = true
showToast({ kind: 'warn', text: 'Offline. Scans will sync when you reconnect.' }, 3000)
}
function isNetworkError(e: any): boolean {
if (!e) return false
if (e.name === 'FetchError' && !e.response) return true
if (e.message && /network|fetch|failed to fetch|load failed/i.test(e.message)) return true
if (typeof navigator !== 'undefined' && !navigator.onLine) return true
return false
}
// --- camera ---
type Toast = { kind: 'success' | 'warn' | 'error'; text: string }
const toast = ref<Toast | null>(null)
let toastTimer: ReturnType<typeof setTimeout> | null = null
function showToast(t: Toast, ms = 2500) {
toast.value = t
if (toastTimer) clearTimeout(toastTimer)
toastTimer = setTimeout(() => { toast.value = null }, ms)
}
const cameraOn = ref(false)
const startError = ref<string | null>(null)
const videoRef = ref<HTMLVideoElement | null>(null)
const canvasRef = ref<HTMLCanvasElement | null>(null)
let mediaStream: MediaStream | null = null
let scanLoopHandle: number | null = null
const lastScanAt = ref(0)
const recentlyScanned = ref<Set<string>>(new Set())
// True while the confirmation panel is showing scanning pauses so
// the camera doesn't keep firing previews on the same QR while the
// volunteer is choosing a party size.
const scanningPaused = computed(() => confirm.value !== null)
async function ensureJsQR() {
if (typeof window === 'undefined') return null
const w = window as any
if (w.jsQR) return w.jsQR
await new Promise<void>((resolve, reject) => {
const s = document.createElement('script')
s.src = 'https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js'
s.onload = () => resolve()
s.onerror = () => reject(new Error('Could not load scanner script'))
document.head.appendChild(s)
})
return w.jsQR
}
async function startCamera() {
startError.value = null
try {
const jsQR = await ensureJsQR()
if (!jsQR) {
startError.value = 'This browser can\'t scan QR codes. Try Chrome or Safari.'
return
}
mediaStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment' },
audio: false,
})
cameraOn.value = true
await nextTick()
if (videoRef.value) {
videoRef.value.srcObject = mediaStream
await videoRef.value.play()
scanLoop(jsQR)
}
} catch (e: any) {
startError.value = e?.message || 'Could not start the camera.'
}
}
function stopCamera() {
if (scanLoopHandle !== null) {
cancelAnimationFrame(scanLoopHandle)
scanLoopHandle = null
}
if (mediaStream) {
mediaStream.getTracks().forEach((t) => t.stop())
mediaStream = null
}
cameraOn.value = false
recentlyScanned.value.clear()
}
function scanLoop(jsQR: any) {
const video = videoRef.value
const canvas = canvasRef.value
if (!video || !canvas) return
const ctx = canvas.getContext('2d', { willReadFrequently: true })
if (!ctx) return
const tick = () => {
if (!cameraOn.value || !videoRef.value || !canvasRef.value) return
if (!scanningPaused.value && videoRef.value.readyState === videoRef.value.HAVE_ENOUGH_DATA) {
canvas.width = videoRef.value.videoWidth
canvas.height = videoRef.value.videoHeight
ctx.drawImage(videoRef.value, 0, 0, canvas.width, canvas.height)
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
const code = jsQR(imageData.data, imageData.width, imageData.height, { inversionAttempts: 'dontInvert' })
if (code && code.data && shouldProcessScan(code.data)) {
void handleScannedPayload(code.data)
}
}
scanLoopHandle = requestAnimationFrame(tick)
}
tick()
}
function shouldProcessScan(payload: string): boolean {
const now = Date.now()
if (now - lastScanAt.value < 1500) return false
if (recentlyScanned.value.has(payload)) return false
lastScanAt.value = now
recentlyScanned.value.add(payload)
setTimeout(() => recentlyScanned.value.delete(payload), 10_000)
return true
}
// --- confirm panel state ---
//
// confirm.value === null scanner is live, waiting for a QR
// confirm.value !== null showing the guest preview + party-size buttons
type ConfirmState = {
payload: string
guestName: string
expected: number // expected party size from preview
plusOnes: number // allowance from the guest record
alreadyIn: boolean
customCount: number // for "Other (N)" input
submitting: boolean
}
const confirm = ref<ConfirmState | null>(null)
async function handleScannedPayload(payload: string) {
// Preview lookup. Failures fall back: if we can't reach the API we
// still let the volunteer pick a count, defaulting to 1 the actual
// record POST will queue offline-style for sync later.
try {
const res = await authedFetch<PreviewResponse>(
`/events/${eventId.value}/check-in/preview`,
{ method: 'POST', body: { qr_payload: payload } },
)
confirm.value = {
payload,
guestName: res.guest?.name || 'Guest',
expected: res.expected_party_size,
plusOnes: res.guest?.plus_ones ?? 0,
alreadyIn: res.already_checked_in,
customCount: res.expected_party_size,
submitting: false,
}
if (navigator.vibrate) navigator.vibrate(60)
} catch (e: any) {
const status = e?.response?.status ?? e?.statusCode
if (status === 401 || status === 403) {
tokenInvalid.value = true
stopCamera()
return
}
if (status === 410) {
showToast({ kind: 'error', text: 'This guest code has expired.' })
return
}
if (status === 400 || status === 404) {
showToast({ kind: 'error', text: 'That doesn\'t look like one of your guests.' })
return
}
if (isNetworkError(e)) {
// No preview available offline. Open the confirm panel with a
// sensible default so the volunteer can still record. We don't
// know the name or plus-one cap; fall back to a generic prompt.
confirm.value = {
payload,
guestName: 'Guest (offline)',
expected: 1,
plusOnes: 5, // permissive cap on the +N buttons
alreadyIn: false,
customCount: 1,
submitting: false,
}
return
}
showToast({ kind: 'error', text: e?.data?.error || 'Could not look up that scan.' })
}
}
function cancelConfirm() {
confirm.value = null
}
async function commitCheckIn(arrivalCount: number) {
const c = confirm.value
if (!c || c.submitting) return
c.submitting = true
const body = { qr_payload: c.payload, arrival_count: arrivalCount }
try {
const res = await authedFetch<{ guest?: { name?: string }; summary: Summary; check_in: CheckInRecord }>(
`/events/${eventId.value}/check-in`,
{ method: 'POST', body },
)
summary.value = res.summary
recent.value = [res.check_in, ...recent.value].slice(0, 5)
showToast({ kind: 'success', text: `${c.guestName} · party of ${arrivalCount}` })
if (navigator.vibrate) navigator.vibrate(80)
confirm.value = null
} catch (e: any) {
const status = e?.response?.status ?? e?.statusCode
if (status === 409) {
showToast({ kind: 'warn', text: 'Already checked in.' })
confirm.value = null
return
}
if (status === 410 || status === 400 || status === 404) {
showToast({ kind: 'error', text: e?.data?.error || 'Could not check in.' })
confirm.value = null
return
}
if (status === 401 || status === 403) {
tokenInvalid.value = true
stopCamera()
return
}
if (isNetworkError(e)) {
await queueAdd({
event_id: eventId.value,
qr_payload: c.payload,
arrival_count: arrivalCount,
queued_at: Date.now(),
})
showToast({ kind: 'warn', text: `Queued · ${c.guestName} (will sync when online)` }, 3500)
confirm.value = null
return
}
showToast({ kind: 'error', text: e?.data?.error || 'Could not check in.' })
} finally {
if (confirm.value) confirm.value.submitting = false
}
}
onUnmounted(stopCamera)
// --- walk-in ---
const walkInOpen = ref(false)
const walkInForm = reactive({ name: '', arrival_count: 1 })
const walkInSubmitting = ref(false)
async function submitWalkIn() {
if (!walkInForm.name.trim()) return
walkInSubmitting.value = true
try {
const res = await authedFetch<{ guest: { name: string }; summary: Summary; check_in: CheckInRecord }>(
`/events/${eventId.value}/walk-ins`,
{
method: 'POST',
body: { name: walkInForm.name.trim(), arrival_count: walkInForm.arrival_count },
},
)
summary.value = res.summary
recent.value = [res.check_in, ...recent.value].slice(0, 5)
showToast({ kind: 'success', text: `${res.guest.name} added.` })
walkInForm.name = ''
walkInForm.arrival_count = 1
walkInOpen.value = false
} catch (e: any) {
showToast({ kind: 'error', text: e?.data?.error || 'Could not add walk-in.' })
} finally {
walkInSubmitting.value = false
}
}
const arrivalPct = computed(() => {
const exp = summary.value.expected_headcount
const arr = summary.value.arrived_headcount
if (exp === 0) return 0
return Math.min(100, Math.round((arr / exp) * 100))
})
// Party-size buttons. We always show 1, 1+plusOnes/2, and "Other"; the
// middle button is the recommended default (the guest's full party
// size from the preview).
const partyButtons = computed(() => {
const c = confirm.value
if (!c) return [] as { label: string; count: number; recommended: boolean }[]
const out: { label: string; count: number; recommended: boolean }[] = []
out.push({ label: 'Just them', count: 1, recommended: c.expected === 1 })
if (c.expected > 1) {
out.push({ label: `Party of ${c.expected}`, count: c.expected, recommended: true })
}
// Show intermediate plus-one counts if there's a gap (e.g. expected=3
// button for 2 as well).
for (let n = 2; n < c.expected; n++) {
out.splice(out.length - 1, 0, { label: `Party of ${n}`, count: n, recommended: false })
}
return out
})
function backToDashboard() {
router.push('/dashboard')
}
</script>
<template>
<div class="min-h-screen bg-zinc-950 text-zinc-100">
<!-- Invalid / expired token landing. -->
<div v-if="tokenInvalid" class="flex min-h-screen flex-col items-center justify-center px-6 text-center">
<div class="mb-4 text-4xl">🔒</div>
<h1 class="text-xl font-semibold">This scanner link can't be used</h1>
<p class="mt-2 max-w-sm text-sm text-zinc-400">
It may have expired, been revoked, or wasn't for this event.
Ask the host to send you a fresh link from their dashboard.
</p>
<button class="mt-6 rounded-md bg-brand-500 px-4 py-2 text-sm font-medium text-zinc-950 hover:bg-brand-400" @click="backToDashboard">
Back to GuestGuard
</button>
</div>
<!-- Active scanner. -->
<div v-else class="mx-auto flex min-h-screen max-w-md flex-col">
<header class="flex items-center justify-between px-4 py-3 text-sm">
<p class="font-medium">GuestGuard · Door scanner</p>
<div class="flex items-center gap-3 text-xs">
<span
v-if="offline"
class="rounded-full bg-amber-900/40 px-2 py-0.5 text-amber-200"
>Offline</span>
<button
v-if="queueCount > 0"
class="rounded-full bg-zinc-800 px-2 py-0.5 text-zinc-200 hover:bg-zinc-700"
@click="drainQueue"
>Sync {{ queueCount }}</button>
<button v-if="cameraOn" class="text-zinc-400 hover:text-zinc-200" @click="stopCamera">Pause</button>
</div>
</header>
<!-- Live counter what the door volunteer glances at between scans. -->
<div class="mx-4 mt-2 rounded-lg border border-brand-700/40 bg-brand-500/[0.06] p-4">
<div class="flex items-baseline justify-between">
<div>
<p class="text-[10px] font-medium uppercase tracking-widest text-brand-400">Arrived</p>
<p class="mt-1 text-3xl font-semibold tabular-nums text-brand-200">
{{ summary.arrived_headcount }}
<span class="text-sm font-normal text-zinc-400">of {{ summary.expected_headcount }}</span>
</p>
</div>
<div class="text-right">
<p class="text-2xl font-semibold text-brand-200 tabular-nums">{{ arrivalPct }}%</p>
</div>
</div>
<div class="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-zinc-900">
<div class="h-full rounded-full bg-brand-500 transition-all" :style="{ width: arrivalPct + '%' }"></div>
</div>
</div>
<!-- Camera viewport fills the rest of the screen. -->
<div class="relative mt-3 flex-1 overflow-hidden bg-black">
<video v-show="cameraOn" ref="videoRef" playsinline class="h-full w-full object-cover"></video>
<canvas ref="canvasRef" class="hidden"></canvas>
<div v-if="!cameraOn" class="flex h-full flex-col items-center justify-center px-6 text-center">
<div class="mb-3 text-5xl">📷</div>
<p class="text-sm text-zinc-300">Tap "Start scanning" to use the camera.</p>
<button
class="mt-4 rounded-md bg-brand-500 px-4 py-2 text-sm font-semibold text-zinc-950 hover:bg-brand-400"
@click="startCamera"
>Start scanning</button>
<p v-if="startError" class="mt-3 text-xs text-red-400">{{ startError }}</p>
</div>
<!-- Aiming reticule, while scanning. -->
<div v-if="cameraOn && !scanningPaused" class="pointer-events-none absolute inset-0 flex items-center justify-center">
<div class="h-56 w-56 rounded-lg border-2 border-brand-500/80 shadow-[0_0_0_9999px_rgba(0,0,0,0.55)]"></div>
</div>
<!-- Confirm party size after a scan. Overlays the camera so the
camera keeps running (and the next reticule reappears the
moment we close the panel). -->
<div
v-if="confirm"
class="absolute inset-0 flex items-end justify-center bg-black/85 px-4 pb-6 pt-10"
@click.self="cancelConfirm"
>
<div class="w-full max-w-md rounded-2xl border border-zinc-800 bg-zinc-900 p-5 shadow-2xl">
<p class="text-[10px] font-medium uppercase tracking-widest text-brand-400">Guest matched</p>
<h2 class="mt-1 text-xl font-semibold">{{ confirm.guestName }}</h2>
<p
v-if="confirm.alreadyIn"
class="mt-2 rounded-md border border-amber-700/50 bg-amber-900/30 px-3 py-2 text-xs text-amber-100"
>Already checked in earlier. Tapping a count below will re-record the latest party size.</p>
<p v-else class="mt-2 text-sm text-zinc-400">How many in their party walked in?</p>
<div class="mt-4 grid grid-cols-1 gap-2">
<button
v-for="b in partyButtons"
:key="b.count"
:disabled="confirm.submitting"
class="rounded-lg border px-4 py-3 text-left text-sm font-medium transition disabled:opacity-50"
:class="b.recommended
? 'border-brand-500 bg-brand-500/10 text-brand-100 hover:bg-brand-500/20'
: 'border-zinc-700 bg-zinc-950 text-zinc-100 hover:border-zinc-500'"
@click="commitCheckIn(b.count)"
>
<span class="float-right tabular-nums text-zinc-400">{{ b.count }}</span>
{{ b.label }}
<span v-if="b.recommended" class="ml-1 text-[10px] uppercase tracking-wider text-brand-400">recommended</span>
</button>
<!-- Other (custom). -->
<div class="mt-1 flex items-center gap-2">
<input
v-model.number="confirm.customCount"
type="number"
min="1"
max="20"
class="input w-20"
:disabled="confirm.submitting"
/>
<button
class="flex-1 rounded-lg border border-zinc-700 px-3 py-2 text-sm text-zinc-100 hover:border-zinc-500 disabled:opacity-50"
:disabled="confirm.submitting || !confirm.customCount || confirm.customCount < 1"
@click="commitCheckIn(confirm.customCount)"
>Other record {{ confirm.customCount || 0 }}</button>
</div>
</div>
<button
class="mt-4 w-full text-center text-xs text-zinc-400 hover:text-zinc-200"
:disabled="confirm.submitting"
@click="cancelConfirm"
>Cancel wrong guest</button>
</div>
</div>
</div>
<!-- Recent + walk-in. -->
<div class="mx-4 mt-3 mb-4 space-y-3">
<button
class="w-full rounded-md border border-zinc-700 px-4 py-2 text-sm hover:border-zinc-500 hover:bg-zinc-900"
@click="walkInOpen = true"
>+ Add walk-in</button>
<div v-if="recent.length">
<p class="mb-2 text-[10px] font-medium uppercase tracking-wider text-zinc-500">Just arrived</p>
<ul class="space-y-1.5">
<li
v-for="c in recent"
:key="c.id"
class="flex items-center justify-between rounded-md border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm"
>
<span>
Guest
<span v-if="c.walk_in" class="ml-1 rounded-full bg-amber-900/30 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-amber-300">walk-in</span>
</span>
<span class="text-xs text-zinc-500">party of {{ c.arrival_count }}</span>
</li>
</ul>
</div>
</div>
</div>
<!-- Walk-in sheet. -->
<Teleport to="body">
<div
v-if="walkInOpen"
class="fixed inset-0 z-40 flex items-end justify-center bg-black/60 backdrop-blur-sm"
@click.self="walkInOpen = false"
>
<div
role="dialog"
aria-modal="true"
class="w-full max-w-md rounded-t-2xl border-t border-zinc-800 bg-zinc-900 p-5 shadow-2xl"
>
<h3 class="mb-1 text-base font-semibold">Walk-in</h3>
<p class="mb-4 text-xs text-zinc-500">Adds them to the guest list and marks them in.</p>
<form class="space-y-3" @submit.prevent="submitWalkIn">
<div>
<label class="label">Name</label>
<input v-model="walkInForm.name" class="input" required autofocus />
</div>
<div>
<label class="label">Party size</label>
<input v-model.number="walkInForm.arrival_count" type="number" min="1" max="20" class="input" />
</div>
<div class="flex items-center justify-end gap-2 pt-2">
<button type="button" class="text-sm text-zinc-400 hover:text-zinc-200"
:disabled="walkInSubmitting" @click="walkInOpen = false">Cancel</button>
<button type="submit" class="btn-primary text-sm"
:disabled="walkInSubmitting || !walkInForm.name.trim()">
{{ walkInSubmitting ? 'Adding…' : 'Add walk-in' }}
</button>
</div>
</form>
</div>
</div>
</Teleport>
<!-- Toast. -->
<Teleport to="body">
<Transition
enter-active-class="transition duration-200 ease-out"
enter-from-class="translate-y-2 opacity-0"
enter-to-class="translate-y-0 opacity-100"
leave-active-class="transition duration-200 ease-in"
leave-from-class="translate-y-0 opacity-100"
leave-to-class="translate-y-2 opacity-0"
>
<div
v-if="toast"
class="pointer-events-none fixed left-1/2 bottom-24 z-[60] -translate-x-1/2 rounded-full px-5 py-2 text-sm shadow-lg"
:class="toast.kind === 'success' ? 'bg-brand-500 text-zinc-950'
: toast.kind === 'warn' ? 'bg-amber-500 text-zinc-950'
: 'bg-red-500 text-white'"
>{{ toast.text }}</div>
</Transition>
</Teleport>
<p v-if="fatalError" class="fixed bottom-2 left-2 right-2 rounded-md border border-red-700 bg-red-950/80 px-3 py-2 text-center text-xs text-red-200">{{ fatalError }}</p>
</div>
</template>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

+25
View File
@@ -0,0 +1,25 @@
{
"name": "GuestGuard Scanner",
"short_name": "GG Scanner",
"description": "Door check-in scanner for GuestGuard events. Add to home screen for a fullscreen experience.",
"start_url": "/scanner",
"scope": "/scanner",
"display": "standalone",
"orientation": "portrait",
"background_color": "#0a0a0a",
"theme_color": "#0a0a0a",
"icons": [
{
"src": "/icons/scanner-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/icons/scanner-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
]
}
+60
View File
@@ -0,0 +1,60 @@
// GuestGuard Scanner — minimal service worker.
//
// Why so light: the scanner is an online tool. Letting the SW cache and
// then serve stale check-in submissions would create double-arrivals
// and lost data. So this SW only:
//
// 1. Claims clients on install so the "Add to home screen" launcher
// opens the latest version straight away.
// 2. Caches the bare app shell (the page itself + jsQR) so the
// volunteer can re-open the scanner if the phone briefly drops
// 4G. Auth + check-in calls always go to network.
//
// Anything fancier (background sync queues, IndexedDB cache of pending
// check-ins) belongs in a later iteration once we have a story for
// merging conflicts.
const SHELL_CACHE = 'gg-scanner-shell-v1'
const SHELL_URLS = [
'/scanner',
'https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js',
]
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL_URLS)).catch(() => {}),
)
self.skipWaiting()
})
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== SHELL_CACHE).map((k) => caches.delete(k))),
),
)
self.clients.claim()
})
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url)
// Never cache API calls — stale check-ins are worse than offline.
if (url.pathname.startsWith('/events/') || url.pathname.startsWith('/auth/')) {
return
}
// Network-first for the shell URLs so a deployment is reflected on
// the next reload; fall back to cache only when offline.
if (event.request.mode === 'navigate' || SHELL_URLS.some((u) => event.request.url.endsWith(u))) {
event.respondWith(
fetch(event.request)
.then((res) => {
const copy = res.clone()
caches.open(SHELL_CACHE).then((c) => c.put(event.request, copy)).catch(() => {})
return res
})
.catch(() => caches.match(event.request).then((r) => r || Response.error())),
)
}
})