Files
Behavision/web/src/views/Live.jsx
Suriyakumarvijayanayagam 9182f70442 A customer number people can say out loud
Every id in the schema is a uuid and stays one. What was wrong was
putting one in front of a person: RecordVisit named every new customer
'Visitor ' || left(id::text, 8), so the arrivals feed, the shop PC and
the mobile app all read "Visitor 3446ec35" - the string a shop assistant
reads to a colleague and types into a search box. label is a stored
column staff can overwrite and SearchVisitors matches on, so formatting
around it in a front end would have left the data wrong on three
surfaces.

Migration 012 adds a per-client visitors.number, taken from a counter on
clients with UPDATE ... RETURNING inside the visit transaction. Per
client rather than global: a global sequence would tell any customer who
signs up how many people the whole platform has ever seen, from their
own first visitor number. The backfill numbers existing rows by
first_seen_at and relabels only the eight-hex pattern the old statement
produced, so a human-typed name is never overwritten.

Three of the four things anyone addresses by URL already had a human
name and the API simply refused it - a site has a slug, a camera has the
id the engine knows it by. refs.go accepts either form anywhere an id is
taken; a uuid resolves with no lookup, so every URL a client already
stored keeps working.

- An ambiguous camera name resolves to nothing, never to a guess: two
  shops may each have an "Office1" and acting on the first row would
  edit the wrong shop's camera.
- 404 on a path, 400 on a query filter. /api/visits answered fine and it
  was the filter that was wrong.
- site and site_id are both accepted everywhere now. They differed per
  endpoint, and an unknown query parameter is silently ignored, so
  getting it the wrong way round returned the whole estate.
- The search matches V-13, which is what the product now shows.

Two bugs found by running it rather than testing it:

- 'Visitor ' || $2::text beside number = $2 makes Postgres deduce two
  types for one parameter and refuse the insert. It compiled and passed
  every in-memory test; the first real database rejected it, along with
  the existing face tests that share the path.
- The fallback avatar said "V1" for Visitor 13, Visitor 10 and Visitor
  15 alike, and read as the V-1 reference for a fourth person. It shows
  the number now. The prop is customerRef, not ref - React reserves
  that name and it would never have arrived.

Verified on the live database and through the running API: 13 hex labels
became Visitor 1-13 in first-seen order, two typed names left alone, and
the same customer reachable by uuid, V-13 and 13.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HViLj9gYNRtSr7YVZmW5sn
2026-09-07 11:52:32 +05:30

164 lines
5.8 KiB
JavaScript

import { useEffect, useRef, useState } from 'react'
import { api, streamArrivals } from '../api.js'
import { ago, Loading, Problem } from './Sites.jsx'
import Shot from './Shot.jsx'
// Who just walked in, pushed as it happens.
//
// The list is capped rather than unbounded: this screen is left open on a wall
// display for days, and an ever-growing array of arrivals — each holding an
// image URL — is a tab that eventually falls over. Older arrivals are in the
// reports; this view is about the last few minutes.
const KEEP = 60
export default function Live() {
const [arrivals, setArrivals] = useState([])
const [status, setStatus] = useState('connecting')
const [error, setError] = useState(null)
const seen = useRef(new Set())
useEffect(() => {
const ac = new AbortController()
let stop = () => {}
;(async () => {
try {
// One poll for the recent window, so the screen is never blank while
// waiting for the next person to walk through a door.
const page = await api.arrivals({ limit: 30 })
const rows = page.arrivals || []
rows.forEach(a => seen.current.add(a.visit_id))
setArrivals(rows.slice().reverse())
setStatus('live')
stop = streamArrivals({
cursor: page.cursor,
signal: ac.signal,
onPage: (p) => {
const fresh = (p.arrivals || []).filter(a => !seen.current.has(a.visit_id))
if (!fresh.length) return
fresh.forEach(a => seen.current.add(a.visit_id))
setStatus('live')
// Newest first on screen; the feed delivers oldest first.
setArrivals(prev => [...fresh.reverse(), ...prev].slice(0, KEEP))
},
onError: () => setStatus('reconnecting'),
})
} catch (err) {
setError(err)
}
})()
return () => { ac.abort(); stop() }
}, [])
if (error) return <Problem error={error} />
if (status === 'connecting' && !arrivals.length) return <Loading />
return (
<>
<header className="head">
<h1>Live</h1>
<p className="sub">
<span className={'dot ' + (status === 'live' ? 'ok' : 'warn')} aria-hidden="true" />
{status === 'live' ? 'Connected' : 'Reconnecting…'}
{' · '}last {KEEP} arrivals
</p>
</header>
{arrivals.length === 0 ? (
<div className="state">
<h2>Nobody yet</h2>
<p className="sub">
Arrivals appear here the moment a camera recognises someone.
</p>
</div>
) : (
<ul className="arrivals">
{arrivals.map(a => <Arrival key={a.visit_id} a={a} />)}
</ul>
)}
</>
)
}
function Arrival({ a }) {
const name = a.name || a.label || 'Unidentified'
return (
<li className="card arrival">
<Face image={a.image} name={name} customerRef={a.visitor_ref} />
<div className="who-col">
<strong>{name}</strong>
<span className="sub">
{/* Only beside a name somebody typed. The auto label already IS the
number, so "Visitor 13 · V-13" would read as two identifiers for
one person. */}
{a.name && a.visitor_ref ? `${a.visitor_ref} · ` : ''}
{a.site}{a.camera_id ? ` · ${a.camera_id}` : ''} · {ago(a.occurred_at)}
</span>
{a.attributes && <Attributes attrs={a.attributes} />}
</div>
{a.is_new_visitor
? <span className="pill new">New</span>
: <span className="pill">Returning</span>}
</li>
)
}
// Photos are off unless a shop turns them on, so "no photo" is the ordinary
// case. Initials, never an error state — a screen full of red for a system
// working exactly as configured teaches people to ignore it.
//
// The picture goes through Shot rather than a bare <img> because a face can
// now come from either of two places: a presigned link to object storage, or
// this server's own database on a deployment with no bucket. The second cannot
// be loaded by an <img> at all — it needs the session — so a plain src here
// showed a broken image on exactly the deployments that had just started
// storing photos.
// customerRef, not `ref`: React reserves that prop name, so it would never
// reach this component's props.
function Face({ image, name, customerRef }) {
if (image?.available) {
return <span className="face"><Shot image={image} alt="" /></span>
}
return (
<span className="face initials" title={image?.reason || ''} aria-hidden="true">
{avatarText(name, customerRef)}
</span>
)
}
// What goes in the circle when there is no photograph.
//
// Initials of a name a human typed; the NUMBER for a customer the system named
// itself. Running initials() over "Visitor 13" takes the first letter of each
// word and produces "V1" - which is also what "Visitor 10" and "Visitor 15"
// produce, so three different people wore the same badge, and it read as the
// V-1 reference for a fourth. Found by opening the page: every unit test here
// passes a human name.
function avatarText(name, customerRef) {
const auto = /^Visitor (\d+)$/.exec(String(name).trim())
if (auto) return auto[1]
if (customerRef) {
const n = /^V-(\d+)$/.exec(customerRef)
if (n) return n[1]
}
return initials(name)
}
function initials(name) {
const parts = String(name).trim().split(/\s+/).filter(Boolean)
if (!parts.length) return '?'
if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase()
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
}
function Attributes({ attrs }) {
const bits = []
if (attrs.gender) bits.push(attrs.gender)
if (attrs.age) bits.push(`~${Math.round(attrs.age)}`)
if (attrs.emotion) bits.push(attrs.emotion)
if (!bits.length) return null
return <span className="attrs">{bits.join(' · ')}</span>
}