Files
Kwaku Danso 98678ff5a3 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>
2026-05-21 20:30:02 +01:00

578 lines
21 KiB
Vue
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
// Tier 2 Block H — day-of check-in.
//
// 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
guest_id: string
checked_in_at: string
arrival_count: number
walk_in: boolean
notes?: string | null
}
interface Summary {
arrived_headcount: number
expected_headcount: number
guests_checked_in: number
}
interface ListResponse {
check_ins: CheckInRecord[]
summary: Summary
}
interface ScannerTicket {
token: string
url: string
qr_image: string
expires_at: string
}
const props = defineProps<{
eventId: string
yourRole?: 'owner' | 'editor' | 'viewer' | null
}>()
const canEdit = computed(() => props.yourRole === 'owner' || props.yourRole === 'editor')
const loading = ref(true)
const error = ref<string | null>(null)
const checkIns = ref<CheckInRecord[]>([])
const summary = ref<Summary>({ arrived_headcount: 0, expected_headcount: 0, guests_checked_in: 0 })
// Toast (success / error per scan).
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 = 3000) {
toast.value = t
if (toastTimer) clearTimeout(toastTimer)
toastTimer = setTimeout(() => { toast.value = null }, ms)
}
async function refresh() {
loading.value = true
try {
const data = await useApi<ListResponse>(`/events/${props.eventId}/check-ins`)
checkIns.value = data.check_ins || []
summary.value = data.summary
} catch (e: any) {
error.value = useErrMessage(e, 'Could not load check-ins')
} finally {
loading.value = false
}
}
onMounted(refresh)
// --- 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)
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())
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 QR scanner script'))
document.head.appendChild(s)
})
return w.jsQR
}
async function openScanner() {
if (!canEdit.value) return
try {
const jsQR = await ensureJsQR()
if (!jsQR) {
showToast({ kind: 'error', text: 'QR scanner is not available in this browser.' })
return
}
mediaStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment' },
audio: false,
})
scannerOpen.value = true
await nextTick()
if (videoRef.value) {
videoRef.value.srcObject = mediaStream
await videoRef.value.play()
scanLoop(jsQR)
}
} catch (e: any) {
showToast({ kind: 'error', text: e?.message || 'Could not start the camera.' })
}
}
function closeScanner() {
if (scanLoopHandle !== null) {
cancelAnimationFrame(scanLoopHandle)
scanLoopHandle = null
}
if (mediaStream) {
mediaStream.getTracks().forEach((t) => t.stop())
mediaStream = null
}
scannerOpen.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 (!scannerOpen.value || !videoRef.value || !canvasRef.value) return
if (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)) {
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
}
async function handleScannedPayload(payload: string) {
try {
const res = await useApi<{ guest: any; summary: Summary; check_in: CheckInRecord }>(
`/events/${props.eventId}/check-in`,
{ method: 'POST', body: { qr_payload: payload, arrival_count: 1 } },
)
summary.value = res.summary
checkIns.value = [res.check_in, ...checkIns.value]
showToast({ kind: 'success', text: `${res.guest?.name || 'Guest'} is in.` })
if (navigator.vibrate) navigator.vibrate(80)
} catch (e: any) {
const status = e?.response?.status ?? e?.statusCode
if (status === 409) {
showToast({ kind: 'warn', text: 'Already checked in.' })
} else if (status === 410) {
showToast({ kind: 'error', text: 'This code has expired.' })
} else if (status === 400) {
showToast({ kind: 'error', text: 'That doesnt look like one of your guests.' })
} else {
showToast({ kind: 'error', text: useErrMessage(e, 'Could not check in') })
}
}
}
onUnmounted(closeScanner)
// --- walk-in ---
const walkInOpen = ref(false)
const walkInForm = reactive({
name: '',
email: '',
arrival_count: 1,
notes: '',
})
const walkInSubmitting = ref(false)
function openWalkIn() {
walkInForm.name = ''
walkInForm.email = ''
walkInForm.arrival_count = 1
walkInForm.notes = ''
walkInOpen.value = true
}
async function submitWalkIn() {
if (!walkInForm.name.trim()) return
walkInSubmitting.value = true
try {
const res = await useApi<{ guest: any; summary: Summary; check_in: CheckInRecord }>(
`/events/${props.eventId}/walk-ins`,
{
method: 'POST',
body: {
name: walkInForm.name.trim(),
email: walkInForm.email.trim() || undefined,
arrival_count: walkInForm.arrival_count,
notes: walkInForm.notes.trim() || undefined,
},
},
)
summary.value = res.summary
checkIns.value = [res.check_in, ...checkIns.value]
showToast({ kind: 'success', text: `${res.guest?.name || 'Walk-in'} added.` })
walkInOpen.value = false
} catch (e: any) {
showToast({ kind: 'error', text: useErrMessage(e, 'Could not add walk-in') })
} finally {
walkInSubmitting.value = false
}
}
function fmtTime(iso?: string | null) {
if (!iso) return ''
try { return new Date(iso).toLocaleTimeString() } catch { return iso }
}
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))
})
</script>
<template>
<section class="card">
<header class="mb-3 flex items-center justify-between">
<div>
<h2 class="text-lg font-semibold">Check-in</h2>
<p class="text-xs text-zinc-500">Door scanner and live arrivals.</p>
</div>
<div v-if="canEdit" class="flex items-center gap-2">
<button class="btn-ghost text-sm" @click="openWalkIn">+ Walk-in</button>
<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>
Start scanning
</button>
</div>
</header>
<p v-if="error" class="mb-3 text-sm text-red-400">{{ error }}</p>
<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">
<div class="flex items-baseline justify-between">
<div>
<p class="text-xs font-medium uppercase tracking-widest text-brand-400">Arrived</p>
<p class="mt-1 text-4xl font-semibold tabular-nums text-brand-200">
{{ summary.arrived_headcount }}
<span class="text-base font-normal text-zinc-400">of {{ summary.expected_headcount }}</span>
</p>
<p class="mt-1 text-xs text-zinc-400">
{{ summary.guests_checked_in }}
{{ summary.guests_checked_in === 1 ? 'guest' : 'guests' }} checked in
</p>
</div>
<div class="text-right">
<p class="text-3xl font-semibold text-brand-200 tabular-nums">{{ arrivalPct }}%</p>
<p class="text-xs text-zinc-500">of expected</p>
</div>
</div>
<div class="mt-3 h-2 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>
<!-- Recent arrivals keeps a host's confidence that scans are
actually landing. -->
<div>
<p class="mb-2 text-xs font-medium uppercase tracking-wider text-zinc-500">Recent arrivals</p>
<p v-if="!checkIns.length" class="text-sm text-zinc-500">No one's checked in yet.</p>
<ul v-else class="space-y-1.5">
<li
v-for="c in checkIns.slice(0, 12)"
:key="c.id"
class="flex items-center justify-between rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm"
>
<div class="min-w-0 flex-1">
<p class="text-zinc-100">
Guest checked in
<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>
</p>
<p class="text-xs text-zinc-500">
{{ fmtTime(c.checked_in_at) }} · party of {{ c.arrival_count }}
</p>
</div>
</li>
</ul>
</div>
</div>
<!-- Scanner modal. Mounted only on phones (or opt-in via the
"use this device's camera" link). -->
<Teleport to="body">
<div
v-if="scannerOpen"
class="fixed inset-0 z-50 flex flex-col bg-black"
@click.self="closeScanner"
>
<div class="flex items-center justify-between px-4 py-3 text-white">
<p class="text-sm font-medium">Scanning</p>
<button class="text-sm text-white/70 hover:text-white" @click="closeScanner">Close</button>
</div>
<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>
<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>
</div>
<div class="px-4 py-3 text-center text-xs text-white/70">
Hold the guest's code in the frame. Toasts pop when each scan registers.
</div>
</div>
</Teleport>
<!-- Walk-in modal. -->
<Teleport to="body">
<div
v-if="walkInOpen"
class="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm"
@click.self="walkInOpen = false"
>
<div
role="dialog"
aria-modal="true"
class="w-full max-w-md rounded-lg border 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 your guest list and marks them checked in.
</p>
<form class="space-y-3" @submit.prevent="submitWalkIn">
<div>
<label class="label">Name</label>
<input v-model="walkInForm.name" class="input" required />
</div>
<div>
<label class="label">Email (optional)</label>
<input v-model="walkInForm.email" type="email" class="input" />
</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>
<label class="label">Notes (optional)</label>
<input v-model="walkInForm.notes" class="input" placeholder="Friend of the bride" />
</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"
>
<button
v-if="toast"
type="button"
class="fixed bottom-6 right-6 z-[60] flex max-w-sm items-center gap-2 rounded-lg border px-4 py-3 text-left text-sm shadow-lg backdrop-blur"
:class="toast.kind === 'success' ? 'border-brand-700/60 bg-brand-950/90 text-brand-100'
: toast.kind === 'warn' ? 'border-amber-700/60 bg-amber-950/90 text-amber-100'
: 'border-red-800/60 bg-red-950/90 text-red-100'"
@click="toast = null"
>{{ toast.text }}</button>
</Transition>
</Teleport>
</section>
</template>