Files
julian 11567a417f docs(wiki): catch concept pages up to the booth-UX/shift/font-scale work
Bring three queryable pages current with the booth-UX commit (cce99aa) whose
breadth hadn't propagated:
- booth-console: Active Sessions as a real table, dropped status column/filter,
  inline live-feed rows, removed TARGE via-badge + redundant Direction filter,
  plate now searchable + backfilled via plate-recognized WS push, per-user font scale.
- shift: Z-report display simplified (shitje dropped, opening cash added) while
  the signed payload is untouched.
- i18n: users.font_scale recorded alongside language/theme as the matching
  per-user server-stored pref (migration 0014).

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
2026-06-29 11:43:12 +02:00

181 lines
13 KiB
Markdown
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.
---
type: concept
tags: [parking, frontend, booth, realtime, ui]
sources: []
updated: 2026-06-19
status: open
---
# Booth Console (operator UI architecture)
The **operator console** — the real-time UI an attendant runs at a manned booth. Built 2026-06-17/18
on top of the [[react-vite-spa]]. This page covers the *architecture* (stack, live feed, layout);
the booth's *business flows* live in [[booth-exit-flow]], [[shift]], [[parking-session]].
## Stack (added 2026-06-17, beyond plain React)
The operator UI outgrew "plain React + useState" once it needed live updates and a real layout:
- **TanStack Query** owns SERVER state (fetch/cache/refetch/loading-error), wrapping the existing thin
`apiFetch` client. Server data is never duplicated into client state.
- **TanStack Router** — real routes (`/booth`, `/shift`, `/setup`, `/tariff`, `/permits`, `/site`),
role-guarded (admin-only routes redirect non-admins to `/booth`). Code-based route tree.
- **Zustand** — small CLIENT state only: the live WebSocket status + a rolling in-memory event feed +
the latest pushed occupancy. Anything durable is re-fetched via Query.
- **Tailwind v4** with a **"Bloomberg-terminal" theme** (`apps/web/src/index.css`, `@theme`):
near-black surfaces, amber/green/red/cyan status accents, monospace, dense/keyboard-first. **Radix**
primitives (Dialog, etc.) for accessible unstyled components. The token VALUES are adopted from the
**"TRM" design system** (Claude Design project; race-timing kit) — **tokens only**, no TRM
components: the `term-*` accents are aligned onto TRM's `night`/semantic colours and TRM's full
vocabulary (night/ink/paper scales, flag/amber/green/blue, the spacing/type/shadow scales) is
exposed as utilities for new work. Offline appliance ⇒ no webfont `@import`; Goldplay (TRM's display
face) not self-hosted yet — display text falls back to a sans stack.
- **react-i18next** for [[i18n]] (Albanian default).
> This SUPERSEDES the original "plain React, no framework" note on [[react-vite-spa]] — that held
> while the UI was a few admin forms; the live booth console justified the additions.
## Live feed — one WebSocket (`/api/ws`)
The booth must reflect entries/exits/payments the instant they happen, so the console opens **one
authenticated WebSocket** app-wide instead of polling. See the WS tap in [[append-only-event-chain]]
(`EventLog.append` fires a read-side `onAppended` callback → the device bus `emitLedger` → the WS
route fans it out):
- On each signed **ledger** append (entry/exit/payment/void/anomaly/cash_movement/shift_*) the server
pushes the event **plus the recomputed [[capacity-occupancy|occupancy]]** (a fold over the same
ledger, always authoritative). Printer-status changes ([[printer-status-monitoring]]) ride the same
socket.
- The client appends to the Zustand feed for the live ticker AND **invalidates the matching Query
caches** (events, occupancy, active-sessions) — so Query stays the source of truth; the WS is the
freshness trigger. Auto-reconnect with capped backoff survives a server restart.
### Auth — anti-CSWSH
The handshake is a normal GET through Fastify, so the **HttpOnly JWT cookie** that guards the REST API
guards the WS too. But a browser `WebSocket` can't send the CSRF double-submit header, which would
leave the socket open to **Cross-Site WebSocket Hijacking** (a malicious page opens
`ws://<booth>/api/ws`, the browser auto-attaches the cookie, the attacker reads the live feed). So the
WS route replaces CSRF with an **Origin allowlist** (same-origin always; extra origins via
`WS_ALLOWED_ORIGINS` for the dev SPA): a missing/cross origin is rejected before auth. The stream is
read-only — it can never mutate state. (Found + fixed by automated security review, 2026-06-17.)
## The booth screen (`/booth`)
Dense terminal layout: a **ticket input** (HID-scanner-friendly — types the id + Enter) spanning the
top; a left column with the **occupancy gauge** above the **[[booth-exit-flow|Active Sessions]]** list;
a right column with the **live event ticker**. Submitting/clicking a ticket opens the **pay/exit
modal** (entry/duration/total, tender, voucher checkbox, entry/exit snapshots). All live-refreshed via
the WS.
> **Focus-independent scan capture (2026-06-21).** A scan now opens the pay/exit modal **regardless of
> focus** — the operator needn't click the ticket field first. A document-level listener (`useScanner`,
> `apps/web/src/lib/use-scanner.ts`) detects the HID scanner's fast keystroke BURST ended by Enter (a
> gap > 50ms resets the buffer, so human-paced typing with nothing focused never triggers it) and fires
> the same `setActiveTicket`. It ignores keystrokes into an `<input>/<textarea>/select/contenteditable`
> so the manual ticket field still works by hand. It is **paused while a modal is already open** — a
> scan must not abandon an in-progress payment; the operator finishes/closes, then scans the next car.
### Explainable activity log (2026-06-19)
The ticker used to flag an **anomaly** with no explanation — a red row with just an id, "nobody knows
what happened." Now every event is **self-describing and clickable**:
- **Inline reason + badges.** Each row surfaces the localized reason (from the signed `reasonCode` —
see [[i18n]]) and computed classification badges (entry/exit-refused, lot-full, barrier-failed,
manual-open…). Anomalies always show a reason line (or "no reason recorded") so a red flag is never
silent.
- **Clickable → event-detail modal.** A read-only modal with humanized labelled fields (not raw JSON),
the session's **entry/exit snapshots**, and the **signed-chain provenance** (signature / keyId /
prevHash) collapsed behind an "audit data" disclosure — operator sees the story, an auditor expands
for the crypto. *Why show signatures at all:* makes the [[append-only-event-chain|tamper-evidence]]
visible against the [[threat-model|booth-operator]] threat, and survives a signer swap (`keyId`).
- **Subscriber names, not opaque keys.** A [[subscription]] occurrence's `SUBSESS-…` id now renders as
the holder's name ("Aqif Kopertoni", fallback "Abonent"/"Subscriber"). Resolved **read-time
server-side** (events API + WS push attach a non-signed `subscriberLabel` from `permitId →
holder_name`; cached, invalidated on subscription edit/delete) so it needs no extra client
permission and the signed event stays minimal.
- **Failed-snapshot visibility.** A camera that was *attempted but unreachable* now shows a "⚠ camera
unreachable" tile (from snapshot [[device-events|telemetry]]) instead of a silent gap — so the
operator can tell "no camera" from "camera failed". (Surfaced a real incident: a subscriber's entry
snapshot failed `EHOSTUNREACH` while the exit one succeeded — by design a snapshot is *evidence, not
a gate*, so the open proceeded and only the image was missing.)
- **Subscriber access medium (`via`).** A subscription entry/exit row now shows HOW the subscriber was
identified — **QR code / RFID card·chip / plate** — as a cyan chip in the ticker and a labelled
"Entry medium" row in the detail modal. The flow already signed `via` (`"qr"|"card"|"plate"`) into
the [[subscription]] entry/exit payload; this just surfaces it (a lost-card investigation can now see
which credential opened a barrier). Rides the existing localized-display pattern, not a new signed
field.
- **Refused entry/exit now carry a snapshot too (2026-06-19).** Previously only an *accepted* open
captured an image. Now refusal/hold anomalies fire the directional camera as well (the photo of a
turned-away car is exactly the evidence an operator/auditor wants) — so the detail modal's snapshot
strip is populated for "lot full", unpaid-exit, no-session, and refused-subscription events. See
[[entry-exit-points]] for the coverage list and the synthetic `REFUSED-…` key used when a refused
entry has no ticket id.
### Layout & readability pass (2026-06-28)
- **Active Sessions is a real table** (columns: Ticket/subscriber · Plate · Entry · Elapsed), so
values align and long ones (subscriber names, ticket ids) no longer truncate. A subscriber shows
**★ + holder name**; an overstay keeps a red row tint; the audited "Open barrier" action sits in a
trailing cell. The **status column was dropped** (an unpaid transient is normal; a subscriber is
self-evident), and with it the **status filter** — only the Transient/Subscriber filter remains.
- **Live feed rows flow inline** — identity, plate, badges and reason sit on one line and wrap only
when the row runs out of width (no forced second line). The redundant `TARGË` *via*-badge was
dropped (the plate chip already conveys it), and the **Direction filter** (Hyrje/Dalje) was removed
— it duplicated the entry/exit options already in the Type filter.
- **Plate is searchable** in both the feed and active-sessions boxes (they now match the enriched
`plate` field, not the unsigned payload). A plate recognized AFTER its event shipped backfills the
feed row in place (a `plate-recognized` WS push), so it no longer needs a page refresh.
- **Per-user font scale.** An A−/A+ control in the header scales the whole UI; persisted on
`users.font_scale` and restored on login like the theme/language prefs (see [[i18n]]). Implemented
as a root `font-size` over rem-based type (NOT CSS `zoom`, which scaled viewport-locked modals out
of view) — so only text scales; `vh`/`h-screen` layout stays put.
## The shift control (header) + the booth gate
The header carries a single **shift button** that expresses the [[shift|site-wide single-open
shift]] (added 2026-06-18):
- **No shift open** → "Open shift" (green, enabled).
- **My shift open** → "Close shift" (red, enabled — signs + prints the Z-report).
- **Another operator's shift open** → **disabled**, titled with who holds it. You can neither open
yours nor close theirs until they hand over.
State comes from one shared Query (`useShift()` → `GET /api/shift/current`, returning `{ open:
{startedAt, operator} | null, isMine }`); the WS invalidates it on `shift_open` / `shift_z_report` /
`cash_movement`, so the button (and the per-shift log scope) update live without polling.
The **booth screen gates on this**: the pay/exit modal shows an "open a shift" banner (with a
one-click *Open shift now*) and disables pay/exit/voucher until **this operator's** shift is open;
the Active-Sessions "Open barrier" is disabled the same way. The server enforces it regardless
(`requireShift` 409 `no_shift`) — the UI just front-runs the rejection. The live feed is **scoped to
the open shift's window** (empty when no shift is open). See [[shift]] for the rule and the routes.
## The device-status footer
A **fixed footer** in the app shell shows the live status of every configured device — relays,
readers, cameras, printers — one chip each (coloured dot + name + fault detail), with an "all ready
/ N offline" roll-up. Fed by the unified [[device-status-monitoring|DeviceMonitor]] over the same
`/api/ws` socket (`hello` carries the initial set; a `device-status` frame per change), held in the
live store keyed by device id, with `GET /api/devices/status` as the seed/fallback. Visible on every
screen, so the operator always sees the barrier relay's reachability and the printer's paper state.
## Dev notes
- Vite proxies `/api/ws` (`ws: true`) to the backend; the backend's Origin allowlist must include the
dev SPA origin (`WS_ALLOWED_ORIGINS=http://localhost:5173`). In production Fastify serves the SPA
same-origin, so the allowlist isn't needed.
- Start the dev SPA via `pnpm dev` from `apps/web` (not `npx vite --host …`, which has mangled args
and served 404s in this environment).
## Open
- **Automated test coverage landed 2026-06-21** (was: "no automated tests anywhere"). `pnpm test`
now runs across all six packages (was shared + vision only): a fresh-SQLite harness
(`@parking/db/testing` → `createTestDb()`, real migrations, never the live DB) backs server-core
suites for the anti-fraud heart — event-log hash-chain + tamper detection, signer, occupancy +
reserved-spots, pay-station, the exit GATE, and the shift takings-split; `@parking/devices` pins the
ESC/POS byte stream (CP852 fallbacks + the Code128 width contract) and printer routing; an HTTP
integration suite boots the real Fastify app (`app.inject`) to exercise the auth/RBAC/CSRF guards;
and `@parking/web` covers the booth formatters + the focus-independent `useScanner` hook. **Still
manual (Playwright):** the live-feed/modal *rendering* and full booth UI flows — the front-end unit
layer covers pure logic + the scanner hook, not component rendering (no jsdom component suite yet).
- The pre-existing admin screens (Setup/Tariff/Permits/Site/Shift) still carry their **old inline
styles** — reachable and functional, not yet on the terminal component system.