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>