diff --git a/wiki/concepts/booth-console.md b/wiki/concepts/booth-console.md new file mode 100644 index 0000000..5f362a6 --- /dev/null +++ b/wiki/concepts/booth-console.md @@ -0,0 +1,78 @@ +--- +type: concept +tags: [parking, frontend, booth, realtime, ui] +sources: [] +updated: 2026-06-18 +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. +- **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:///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. + +## 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 +- **No automated frontend tests** — the booth/live-feed/modal logic is verified manually + (Playwright + curl + DB inspection), not by a suite. The standing test-harness gap (see + [[reconciliation]]-adjacent notes) now spans front and back. +- 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. diff --git a/wiki/concepts/i18n.md b/wiki/concepts/i18n.md new file mode 100644 index 0000000..aaf0dce --- /dev/null +++ b/wiki/concepts/i18n.md @@ -0,0 +1,55 @@ +--- +type: concept +tags: [parking, frontend, i18n, localization] +sources: [] +updated: 2026-06-18 +status: open +--- + +# Internationalization (i18n) + +The operator UI ships in **two languages: Albanian (default) and English**. Language is a +**per-user preference stored server-side** and loaded on login — not a browser/localStorage setting, +not a site-wide one. So an operator's choice follows their account and is restored on every login from +any booth. (Decided + built 2026-06-18.) + +## Decisions + +- **Albanian is the default and fallback.** English is the second language. A missing English key + falls back to Albanian. +- **Per-user, server-side preference.** `users.language` (`'sq' | 'en'`, default `'sq'`; migration + 0003). Returned from `/api/auth/login` and `/api/auth/me`, and changed via **`PUT /api/auth/language`** + (self-service, any signed-in role). It is **deliberately NOT in the JWT** (identity/role only) — so + changing language is a DB write + immediate `/me`, with no token refresh / re-login. See + [[local-jwt-auth]]. +- **Library: react-i18next** (i18next). Chosen over a hand-rolled `t()` for pluralization, + interpolation, and headroom beyond two languages. The active language is applied after `/me` + resolves (App effect on `user.language`); the header **SQ/EN toggle** switches instantly *and* + persists. +- **Printed tickets/receipts stay Albanian.** Customer-facing paper is **independent** of the + operator's UI language — an operator reading the UI in English still prints Albanian tickets. The + print strings live in the device driver's `STR` table ([[ticket-encoding]], [[site-metadata]]); can + become a `site_config.print_language` setting later if a site ever needs English receipts. + +## As-built (2026-06-18) + +- **Backend:** `users.language` + the three auth touch-points above (`apps/server/src/routes/auth.ts`). +- **Frontend:** `apps/web/src/lib/i18n/` — `sq.ts` (default/fallback), `en.ts`, and `index.ts` (init + + `setLanguage()`). **Type-safe key parity:** `Catalog` is the *shape* of `sq` with string-typed + values, so TypeScript forces `en.ts` to supply every key (and the build fails on a missing/typo'd + key). Keys are dot-namespaced by area (`common`, `nav`, `status`, `auth`, `booth`, `pay`, `shift`, + `site`, `permits`, `tariff`). +- **Translated screens:** the booth ([[booth-console]] — screen, pay/exit modal, active sessions, + snapshots, status), Login, ShiftControl, SiteSettings, PermitManager, TariffComposer. + +## Open / deferred + +- **SetupWizard is NOT translated** (deliberate). Its content is mostly **server-provided** — driver + labels and config-field labels/help come from the backend device-catalog API ([[device-registry]], + [[first-run-setup]]). Translating only its static chrome would leave a half-English screen; it's + deferred until **backend catalog i18n** is scoped, then chrome + catalog localize together. +- **Server API error strings** are still English (surfaced raw in the UI). v1 relies on the + client mapping known errors; a fuller approach would translate by error *code*, not message. +- **Behaviour note (not a bug):** a *hard navigation* (new URL) re-bootstraps the language from the + user's stored preference via `/me` — so an un-persisted toggle resets. Correct: the stored pref + wins. The toggle persists via the PUT, so it survives once saved. diff --git a/wiki/entities/react-vite-spa.md b/wiki/entities/react-vite-spa.md index 1cd286c..c8634fe 100644 --- a/wiki/entities/react-vite-spa.md +++ b/wiki/entities/react-vite-spa.md @@ -2,14 +2,17 @@ type: entity tags: [parking, stack, frontend] sources: [parking-system-architecture] -updated: 2026-06-14 +updated: 2026-06-18 --- # React + Vite SPA -The frontend: a React single-page app built with Vite, **served by [[fastify]]** (MIT). Plain -React was chosen over an admin framework — see [[refine]], which was dropped because the -operator UI is simple enough that a framework's abstractions cost more than they save. -(See [[parking-system-architecture]] §2.) +The frontend: a React single-page app built with Vite, **served by [[fastify]]** (MIT). +(See [[parking-system-architecture]] §2.) Part of the [[technology-stack]]. -Part of the [[technology-stack]]. +> **Updated 2026-06-18:** the original "plain React, no framework" choice (an admin *framework* +> like [[refine]] was rejected) still holds — but the live operator console outgrew bare +> `useState` and now layers in **TanStack Query + Router, Zustand, Tailwind v4, Radix, and +> react-i18next**. These are libraries, not an admin framework, and each earns its place (live +> updates, routing, the terminal theme, [[i18n]]). The full operator-UI architecture — including the +> single `/api/ws` live feed — is in [[booth-console]]. diff --git a/wiki/index.md b/wiki/index.md index 649ab87..e453558 100644 --- a/wiki/index.md +++ b/wiki/index.md @@ -7,7 +7,7 @@ updated: 2026-06-14 # Index Content catalog for the wiki. Start at [[overview]]. Maintained on every ingest. -Counts: 4 sources · 19 entities · 27 concepts · 5 decision records. +Counts: 4 sources · 19 entities · 41 concepts · 5 decision records. ## Overview & navigation - [[overview]] — the top-level synthesis and entry point. @@ -80,7 +80,8 @@ Counts: 4 sources · 19 entities · 27 concepts · 5 decision records. - [[parking-session]] — the core domain entity; a projection over the signed log, never a mutable table. - [[tariff]] — fee model; pure, data-driven, offline; pay-on-foot adds a walk-back grace window. - [[tariff-time-tiers]] — design: happy-hour/off-peak/weekend/seasonal + vehicle categories via time-windowed rate cards. -- [[shift]] — manned-only accountability period; explicit Start/End (not time-based); End → signed + printed Z-report (cash + POS). +- [[booth-exit-flow]] — manned booth: pay → voucher (self-exit later) or immediate exit; active sessions; audited barrier re-open. +- [[shift]] — manned-only accountability period; explicit Start/End; End → signed + printed Z-report; drawer float carries across shifts. - [[capacity-occupancy]] — live count = open sessions; refuse entry + FULL sign when full (soft policy); exit never blocked. - [[site-metadata]] — optional park identity (name, operator, VAT, address, contact) in site_config; feeds the ticket header. - [[valet-overcapacity]] — "full" is soft: operator may valet-accept over capacity (keys handed over, custody). Manned, deferred. @@ -95,6 +96,10 @@ Counts: 4 sources · 19 entities · 27 concepts · 5 decision records. - [[opencv-anpr-service]] — host-side vision microservice: ANPR (plate identity) + vehicle verification (anti-plate-spoofing witness). - [[blocklist]] — barred plates/cards refused at entry (never at exit); signed, attributed. +## Concepts — frontend / operator UI +- [[booth-console]] — operator-UI architecture: TanStack Query/Router + Zustand + Tailwind terminal theme; one /api/ws live feed (anti-CSWSH). +- [[i18n]] — Albanian default + English; per-user server-stored language preference (users.language), loaded on login; tickets stay Albanian. + ## Dev environment (reference) - [[local-dev-workflow]] — running the stack locally; setup, the dev-hang gotchas, seed:admin. - [[wsl-dev-networking]] — WSL2 NAT blocks device broadcast; use mirrored mode + the gotchas after. diff --git a/wiki/log.md b/wiki/log.md index 0cf48b6..5dcb39c 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -780,3 +780,19 @@ Operator escape hatch for stuck cars (damaged ticket / dead scanner / phantom ba ## [2026-06-18] build | Drawer balance — opening float carry-over + admin cash movements Cash drawer that carries across shifts. New signed `cash_movement` ledger event type (shared); admin-only POST /api/cash-movement {amountMinor signed +load/-remove, reason}. ShiftService: #drawerBalanceAt(time) folds cash payments + cash_movements BY TIME (not operator — the movement is the admin's); open() auto-inherits openingFloat = drawerBalanceAt(start) and records it on shift_open; close() Z-report adds openingFloat/cashAdded/cashRemoved/expectedDrawer (= opening + taken + added − removed = next shift's opening float). Card payments excluded (settle to bank). GET /api/shift/current returns live drawerMinor. Frontend: ShiftControl shows live drawer + admin Load/Remove form + full Z-report drawer block (admin gate via router context). Verified the canonical scenario on a FRESH DB: load 5000 → shift1 takes 6500 → expected 11500 → shift2 inherits 11500, admin removes 5000, takes 4500 → expected 11000 → shift3 inherits 11000; chain ok. Also verified through the real UI (load/remove → Z-report opening 11200 removed 5000 expected 6200; both cash_movements signed+attributed; chain ok). Decision + worked example in [[shift]] (Drawer balance section). Standing gap: still no automated tests. + +## [2026-06-17] build | Live booth WebSocket feed (/api/ws) + +Added @fastify/websocket. EventLog.append fires a read-side onAppended callback after each durable insert (never touching the sign/chain path); device-events gained a `ledger` channel (emitLedger). New GET /api/ws fans out ledger + recomputed occupancy + printer-status to authenticated booth clients. Auth: JWT cookie (same as REST) + an Origin allowlist (WS_ALLOWED_ORIGINS) that REPLACES CSRF — a browser WebSocket can't send the double-submit header, so without an Origin check the read-only feed is open to Cross-Site WebSocket Hijacking (found + fixed by automated security review). See [[booth-console]], [[append-only-event-chain]]. + +## [2026-06-17] build | Frontend foundation — Tailwind terminal theme, Query/Router/Zustand, live booth screen + +Operator UI outgrew plain React. Added TanStack Query (server state, wraps apiFetch), TanStack Router (role-guarded routes), Zustand (small client state: WS status + live feed), Tailwind v4 with a Bloomberg-terminal theme + Radix primitives. A /api/ws client invalidates Query caches on ledger pushes. Built the live /booth screen (occupancy gauge + streaming entry/exit/payment ticker). Vite proxies the WS upgrade. SUPERSEDES the "plain React, no framework" note on [[react-vite-spa]]. See [[booth-console]]. + +## [2026-06-18] build | i18n — Albanian default + English, per-user server-stored preference + +Two languages via react-i18next, Albanian default/fallback. Language is a per-user preference: users.language (migration 0003), returned from login/me, changed via PUT /api/auth/language (NOT in the JWT — no re-login). Loaded on login, restored from any booth; SQ/EN header toggle persists. Type-safe key parity (en mirrors sq or the build fails). Translated booth + Login/Shift/Site/Permits/Tariff. SetupWizard deferred (server-provided catalog strings need backend i18n). Printed tickets stay Albanian (customer-facing). See [[i18n]], [[booth-console]]. + +## [2026-06-18] lint | Reconcile wiki with the session's work + +Audited wiki vs. the session: three major builds (live WebSocket, frontend foundation, i18n) had NO log entry and NO concept page. Filed [[i18n]] (resolved a dangling code-comment link) and [[booth-console]] (operator-UI architecture: stack, /api/ws live feed, anti-CSWSH, booth screen). Updated stale [[react-vite-spa]] (the "plain React, no framework" claim is now qualified). Backfilled the three missing build log entries. Standing gaps flagged across pages: NO automated tests (front or back); ATECC608 not yet wired (software-HMAC signing is tamper-evident, not tamper-proof); pre-existing admin screens not on the terminal theme.