Files
web-nuxt/README.md
T
Noel Sabia 2bc52a314d
ci / check (push) Successful in 55s
feat: build the Cool City public route demo
- add /cool, /cool?vote=1, /cool/stage and /cool/city on the existing Nuxt/Onyx stack
- wire real route/shade metrics and OSM geometry from the route bundle; city-gap data for the city view
- show shade % and direct-sun minutes together; recommend Accessible for Ruth with the 15% ramp trade-off
- add in-memory time/scene/round state and one anonymous vote per session, polled every 2 s
- keep the retail module linked but out of the Cool City story
2026-11-14 13:49:22 +01:00

262 lines
11 KiB
Markdown
Raw 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.
# PulseCast web
Nuxt 4 SSR frontend for **PulseCast**, a staffing copilot that turns inner-city
footfall into a weekly shift plan for a Heilbronn retailer. `/plan` is the
decision surface; `/stage` and `/live` present that plan. The map, weather and
forecast are supporting evidence.
## Quick start
Node 22 is the CI and Docker version. Real data comes from the Go API on
`http://localhost:8080`; mock mode needs no API.
```bash
npm ci
npm run dev # http://localhost:3000
```
Without the Go API, use the checked-in mock data:
```bash
NUXT_PUBLIC_USE_MOCK=1 npm run dev
```
Build and test exactly as CI does:
```bash
make check # npm ci, npm run build, npm test
```
The built SSR server can also be started directly:
```bash
NUXT_API_INTERNAL_BASE=http://localhost:8080 \
PORT=3000 node .output/server/index.mjs
```
## Stack
- Nuxt `4.6.4`, `ssr: true`, Nitro `node-server`
- `@sit-onyx/nuxt` `1.2.0` + `sit-onyx` `1.22.0` for the entire shell and UI
- Nitro server routes proxy to the Go API; the browser only talks to this origin
- Shared plan heuristic in `shared/staffing.ts`, used for the mock fallback and
for the labeled local preview on `/plan`
Onyx is used for the navigation/app shell, page layout, cards, tables, buttons,
badges, tags, selects, segmented control, slider, stepper, accordion and file
upload. The app does not ship a parallel component design system.
## Live demo: `/stage`, `/live`, `/control`
```text
browser ──GET /api/stream──► Nuxt Nitro ──proxy──► Go /api/stream
◄── scenario/ping ── ◄────────── SSE hub
presenter ──POST /api/scenario──► Nitro (Basic auth + control credentials) ──► Go
```
- `app/composables/useLiveScenario.ts` opens one `EventSource` per tab. On a
`scenario` event it updates the shared state and tells the page to refetch;
`ping` heartbeats keep the connection marked **Live**.
- After two SSE errors, or when no heartbeat arrives for 32 s (a buffering
proxy), the client starts polling `GET /api/scenario` every 5 s. The badge
shows **Connecting**, **Live**, **Polling** or **Offline**, never a silent
stale plan.
- `POST /api/scenario` goes through Nitro; the Go control credentials stay in
the Node process. `/control` itself requires HTTP Basic auth
(`CONTROL_USER`/`CONTROL_PASS`); an HMAC cookie lets the page POST without
re-prompting. `/stage`, `/live` and all public GETs stay open.
- `/stage` renders a local SVG QR code (`/api/qr`) pointing at `/live`; no
third-party QR service is called.
### Live stack (read-only Go/ML worktrees)
```bash
# 1. ML on 18000 (from ML-py.git/main)
PYTHONPATH=src CONTROL_TOKEN=replace-me-token \
.venv/bin/uvicorn pulsecast.server:app --host 127.0.0.1 --port 18000
# 2. Go on 18080 (from api-go.git/main)
PORT=18080 FASTAPI_URL=http://127.0.0.1:18000 \
CONTROL_USER=control CONTROL_PASS=replace-me-pass CONTROL_TOKEN=replace-me-token \
go run ./cmd/api
# 3. Web preview on 13000 (from this worktree, after npm run build)
PORT=13000 NUXT_API_INTERNAL_BASE=http://127.0.0.1:18080 \
CONTROL_USER=control CONTROL_PASS=replace-me-pass CONTROL_TOKEN=replace-me-token \
node .output/server/index.mjs
# 4. Live smoke: auth boundary, /stage + /live SSR, QR, SSE event,
# polling read, and a staffing/forecast plan that differs from base.
CONTROL_USER=control CONTROL_PASS=replace-me-pass WEB_URL=http://127.0.0.1:13000 \
node scripts/smoke-live.mjs
```
## API wiring
Every route in `server/api/` is a proxy to the Go service. The default is the
real API; mock JSON is an explicit dev fallback only.
| Nitro route | Upstream |
| --- | --- |
| `GET /api/healthz` | `GET /api/healthz` |
| `GET /api/readyz` | `GET /api/readyz` |
| `GET /api/meta` | `GET /api/meta` |
| `GET /api/sensors` | `GET /api/sensors` |
| `GET /api/context` | `GET /api/context` |
| `GET /api/series` | `GET /api/series` |
| `GET /api/forecast` | `GET /api/forecast` |
| `GET /api/staffing` | `GET /api/staffing` |
| `GET /api/scenario` | `GET /api/scenario` |
| `GET /api/stream` | `GET /api/stream`, streamed chunk-by-chunk (SSE) |
| `POST /api/scenario` | `POST /api/scenario` with server-side control auth |
| `GET /api/qr?text=` | Local SVG QR generation, no upstream call |
| `POST /api/train` | `POST /api/train` with server-side control auth |
| `GET /api/train/:job_id` | `GET /api/train/{job_id}` with server-side control auth |
| `GET /api/scenarios` | Local UI metadata only (labels/descriptions) |
`/plan` reads Go `/api/staffing` through Nitro. The four local assumption
controls (safety factor, minimum staff, shift length, labour cost) are not query
inputs of the Go contract, so changing them renders an explicit **local
preview** from the API plan’s hourly footfall; “Use API plan” restores the
server values. The shared heuristic is tested against a captured Go response in
`test/fixtures/go-staffing.json`.
### Environment
| Variable | Default | Purpose |
| --- | --- | --- |
| `NUXT_API_INTERNAL_BASE` | — | Preferred server-side Go base (`http://api:8080` in K8s) |
| `NUXT_API_BASE` | — | Alias for the server-side base |
| `NUXT_PUBLIC_API_BASE` | — | Fallback base; also exposed to the browser |
| `NUXT_API_TIMEOUT_MS` | `8000` | Upstream request timeout |
| `NUXT_PUBLIC_USE_MOCK` / `NUXT_USE_MOCK` | unset | `1` enables the mock fallback |
| `NUXT_DISABLE_SSE` | unset | `1` forces the polling fallback (SSE failure drill) |
| `CONTROL_USER` / `CONTROL_PASS` | unset | Basic auth for `/control` and `POST /api/scenario`; also attached to Go `/api/train` |
| `CONTROL_TOKEN` | unset | Optional Bearer fallback when Basic is not configured; the Go control API requires Basic today |
| `NUXT_PUBLIC_DEMO_NOW` | `2026-11-14T08:12:00Z` | Replay clock used for labels |
Control credentials are read only in the Nitro process. They are never placed
in `runtimeConfig.public` and never reach the browser bundle. `/control` and
`POST /api/scenario` require Basic auth at Nitro, and Nitro then attaches the
same credentials to Go. In API mode, if `CONTROL_USER`/`CONTROL_PASS` are
unset, the control surface returns `503 control_auth_unconfigured`; public
screens keep working.
The K8s web Deployment must mount the same `control-auth` secret as the API
Deployment:
```yaml
env:
- name: CONTROL_USER
valueFrom: { secretKeyRef: { name: control-auth, key: CONTROL_USER } }
- name: CONTROL_PASS
valueFrom: { secretKeyRef: { name: control-auth, key: CONTROL_PASS } }
```
### Mock fallback
```bash
NUXT_PUBLIC_USE_MOCK=1 npm run dev
```
Mock mode serves deterministic JSON from `mock/` and completes training
immediately. It is for developing the UI without Go; the default and the
deployed path are the real API.
## Screens
| Route | Purpose |
| --- | --- |
| `/cool` | **Cool City public hero.** Ruth card, time, three real route options, vote buttons; `/cool?vote=1` is the minimal audience vote page |
| `/cool/stage` | **Cool City projector.** Ruth card, cool places, data honesty, route board with exact labels, live vote, city view, retail link |
| `/cool/city` | Cooling-gap module: eight ranked catchments, one-line reasons, top block and “What would help” |
| `/` | Landing: the live shift board, peak shift, cost vs flat, coverage and the measured/modelled/assumed chain |
| `/forecast` | 7-day daily forecast, uncertainty band, weather strip |
| `/plan` | **Hero.** Peak decision, weekly shift board, coverage, cost vs flat, settings, hourly detail |
| `/simulate` | Base vs scenario plan, both read from Go `/api/staffing` |
| `/stage` | Dark projector board: peak shift, weekly board, cost, coverage, QR to `/live` |
| `/live` | Phone answer: peak shift, staff count, reason, freshness, scenario and transport |
| `/control` | Presenter preset buttons; authenticated POST through Nitro |
| `/about` | Method, metrics, limits, privacy, train form |
The layout targets **390 px** (single column, mobile Onyx nav, day cards) and
**1440 px** (Onyx horizontal nav, two-column plan with tables).
### Cool City demo data and state
- `/cool` reads `public/cool-city/route.json`, normalised from
`cool-city-data/route/shade.json`, `routes.geojson` and `places.json`.
`/cool/city` reads `public/cool-city/city-gap.json`.
- Vote and demo state are in-memory Nitro routes: `GET/POST /api/cool/state`,
`GET/POST /api/cool/vote`, `POST /api/cool/reset`. `round` is
`preselection` or `final`; votes never mix. The stage and phones poll every
2 seconds. No database and no PII.
- Stage labels: `Cool places`, `Data honesty`, `Find routes`, `Shortest`,
`Shaded`, `Accessible`, `Start vote`, `Lock vote`, `City view`,
`Retail module`, `Reset round`. The model recommendation is
**“Accessible for Ruth”**.
## Plan logic
`shared/staffing.ts` is the single implementation of the contract heuristic:
```text
required = ceil(max(0, footfall) / visitors_per_staff_hour * safety_factor)
required = max(required, min_staff)
```
Store hours are 10:00–20:00 Europe/Berlin; default blocks are 4 h; labour cost is
€16/h; the default service standard is 25 visitors per staff-hour. The flat
schedule applies the global peak requirement to every store hour, matching Go
and the contract (§5). Coverage is at or above requirement by construction
because each block is sized to its local peak — the UI shows the resulting
overstaffed hours instead of hiding them.
## Checks and CI
```bash
make check # npm ci, npm run build, npm test
make smoke # Nitro -> Go API contract, against a running web server
make smoke-live # SSE + control + /stage + /live, against the 18080/18000/13000 stack
```
The same `make check` runs in Gitea Actions (`.gitea/workflows/ci.yml`). The
workflow needs no secrets, no registry push and no cluster access.
`scripts/smoke-api.mjs` exercises the Nitro → Go chain: health, sensors,
context, meta, series, base and scenario forecasts, standard and premium
staffing, local presets, and 404/400 propagation.
`scripts/smoke-live.mjs` proves the live path: unauthorised POST is rejected,
`/control` authenticates, `/stage` and `/live` render server-side, `/api/qr`
returns SVG, the SSE proxy emits `retry: 3000` and the initial scenario, a
presenter POST produces a `scenario` event (with matching `id` and version)
within the 2 s contract target (the script warns if slower), polling reads the
same version, and the target staffing and forecast responses differ from base.
It restores the base scenario at the end.
## Docker
```bash
docker build -t pulsecast-web:local .
docker run --rm -p 3000:3000 \
-e NUXT_API_INTERNAL_BASE=http://host.docker.internal:8080 \
pulsecast-web:local
```
On Linux, add `--add-host=host.docker.internal:host-gateway` or use the host IP.
The multi-stage image copies only `.output/` into `node:22-alpine`. It creates
numeric UID/GID **`10001:10001`**, uses `COPY --chown=10001:10001` and runs
`USER 10001:10001`. Kubernetes should set `runAsUser: 10001`,
`runAsGroup: 10001` (never a named user such as `node`).
## Limits
- No POS, sales, queue or payroll data. Cost is an assumption.
- Forecast is model output; the plan is decision support, not an optimizer.
- Eight sensors in a 580 m cluster; no city-wide heatmap claim.
- SSE state is in memory in the single Go pod. A pod restart drops streams;
clients reconnect via `retry: 3000` or fall back to 5 s polling.
- Raw CSV, secrets and kubeconfig never enter this repository.