merge: live SSE, stage, live view

This commit is contained in:
Noel Sabia committed 2026-11-14 07:39:11 +01:00
commit 9b61d6859e
24 files changed
+2762 -49

No files matched your search

+6 -1
View File
@@ -1,6 +1,6 @@
NPM ?= npm
.PHONY: install dev build test check preview docker-build smoke
.PHONY: install dev build test check preview docker-build smoke smoke-live
install:
$(NPM) ci
@@ -26,3 +26,8 @@ docker-build:
# Requires a running web server (npm run preview or node .output/server/index.mjs).
smoke:
node scripts/smoke-api.mjs
# Requires Go on 18080, ML on 18000 and this app on 13000.
# See README "Live stack" for the exact environment.
smoke-live:
node scripts/smoke-live.mjs
+67 -7
View File
@@ -35,6 +35,50 @@ NUXT_API_INTERNAL_BASE=http://localhost:8080 \
PORT=3000 node .output/server/index.mjs
```
## 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 secret) ──► 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 closes ranks and polls `GET /api/scenario` every 5 s. The
badge shows **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`); a signed 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
@@ -51,7 +95,9 @@ real API; mock JSON is an explicit dev fallback only.
| `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) |
@@ -72,14 +118,16 @@ heuristic is tested against a captured Go response in
| `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 |
| `CONTROL_USER` / `CONTROL_PASS` | unset | Basic auth for `/api/scenario` and `/api/train` |
| `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 token for future control auth |
| `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. If they are
unset, Go returns `503 control_auth_unconfigured` / `401`; the UI surfaces that
error instead of exposing anything.
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. 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:
@@ -110,6 +158,9 @@ deployed path are the real API.
| `/forecast` | 7-day daily forecast, uncertainty band, weather strip |
| `/plan` | **Hero.** Peak decision, shift blocks, coverage, cost, why, assumptions |
| `/simulate` | Base vs scenario plan, both read from Go `/api/staffing` |
| `/stage` | Big-screen decision: headline, peak staff, cost, coverage, QR to `/live` |
| `/live` | Phone view: current recommendation, peak shift, scenario, last update |
| `/control` | Presenter preset buttons; authenticated POST through Nitro |
| `/about` | Method, metrics, limits, privacy, train form |
The layout is checked at **390 px** (single column, mobile Onyx nav, day cards)
@@ -134,8 +185,9 @@ hours instead of hiding them.
## Checks and CI
```bash
make check # npm ci, npm run build, npm test
make smoke # against a running web server (WEB_URL=...)
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
@@ -145,6 +197,13 @@ workflow needs no secrets, no registry push and no cluster access.
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) in
well under 2 s, 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
@@ -164,5 +223,6 @@ numeric UID/GID **`10001:10001`**, uses `COPY --chown=10001:10001` and runs
- 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 (`/api/stream`), `/live` and `/stage` are the next worktree.
- 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.
+6 -1
View File
@@ -5,6 +5,8 @@ import {
iconCircleInformation,
iconFlash,
iconHome,
iconMobileSignal,
iconPresentionBoard,
} from '@sit-onyx/icons'
const route = useRoute()
@@ -21,11 +23,14 @@ const navigation = [
{ to: '/forecast', label: 'Forecast', icon: iconChart },
{ to: '/plan', label: 'Plan', icon: iconCalendar },
{ to: '/simulate', label: 'Simulate', icon: iconFlash },
{ to: '/stage', label: 'Stage', icon: iconPresentionBoard },
{ to: '/live', label: 'Live', icon: iconMobileSignal },
{ to: '/about', label: 'About', icon: iconCircleInformation },
]
const hiddenPageLabels: Record<string, string> = { '/control': 'Control' }
const activeLabel = computed(
() => navigation.find((item) => item.to === route.path)?.label ?? 'PulseCast',
() => navigation.find((item) => item.to === route.path)?.label ?? hiddenPageLabels[route.path] ?? 'PulseCast',
)
</script>
+37
View File
@@ -0,0 +1,37 @@
<script setup lang="ts">
import { LIVE_COLORS, LIVE_LABELS, liveAge } from '#shared/live'
import type { LiveConnection } from '#shared/live'
const props = withDefaults(
defineProps<{
status: LiveConnection
lastEventAt?: string
compact?: boolean
}>(),
{ lastEventAt: '', compact: false },
)
const color = computed(() => LIVE_COLORS[props.status])
const label = computed(() => LIVE_LABELS[props.status])
const age = computed(() => (props.lastEventAt ? liveAge(props.lastEventAt) : ''))
</script>
<template>
<span class="live-status" role="status" aria-live="polite" :title="lastEventAt ? `Last event ${age}` : undefined">
<OnyxBadge :color="color" :density="compact ? 'compact' : 'default'">{{ label }}</OnyxBadge>
<span v-if="lastEventAt && !compact" class="live-status__age">{{ age }}</span>
</span>
</template>
<style scoped>
.live-status {
display: inline-flex;
align-items: center;
gap: 0.35rem;
}
.live-status__age {
color: var(--onyx-color-text-icons-neutral-soft);
font-size: 0.7rem;
}
</style>
+276
View File
@@ -0,0 +1,276 @@
import {
LIVE_LABELS,
liveStatus,
parseScenarioEvent,
scenarioChanged,
SCENARIO_POLL_MS,
SSE_FAILURES_BEFORE_POLLING,
SSE_STALE_MS,
} from '#shared/live'
import type { LiveConnection } from '#shared/live'
import type { ScenarioState } from '#shared/types'
interface LiveStore {
status: LiveConnection
serverScenario: ScenarioState | null
lastEventAt: string
lastPollAt: string
sseFailures: number
pollFailures: number
revision: number
error: string
}
// One stream per browser tab. The module-level store survives page navigation
// and is only mutated from onMounted/EventSource callbacks (never during SSR).
const store = reactive<LiveStore>({
status: 'connecting',
serverScenario: null,
lastEventAt: '',
lastPollAt: '',
sseFailures: 0,
pollFailures: 0,
revision: 0,
error: '',
})
let source: EventSource | null = null
let pollTimer: ReturnType<typeof setInterval> | null = null
let staleTimer: ReturnType<typeof setInterval> | null = null
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
let subscribers = 0
let started = false
let lastStaleRetry = 0
function nowIso(): string {
return new Date().toISOString()
}
function refreshStatus() {
store.status = liveStatus({
online: import.meta.client ? navigator.onLine !== false : true,
sseOpen: source?.readyState === EventSource.OPEN,
sseFailures: store.sseFailures,
polling: pollTimer !== null,
pollFailures: store.pollFailures,
})
}
function clearPolling() {
if (pollTimer) clearInterval(pollTimer)
pollTimer = null
}
function applyScenario(next: ScenarioState, origin: 'sse' | 'poll') {
const changed = scenarioChanged(store.serverScenario, next)
store.serverScenario = next
store.lastEventAt = nowIso()
store.error = ''
if (origin === 'poll') store.lastPollAt = store.lastEventAt
if (changed) store.revision += 1
}
async function pollScenario(): Promise<void> {
if (!import.meta.client) return
try {
const next = await $fetch<ScenarioState>('/api/scenario', {
headers: { accept: 'application/json' },
timeout: 5000,
})
store.pollFailures = 0
applyScenario(next, 'poll')
// A successful poll proves the API is reachable; stay "Polling" until SSE
// opens again, so the audience can see the fallback is active.
if (store.status === 'offline') store.status = 'polling'
} catch (error) {
store.pollFailures += 1
store.error = (error as { statusMessage?: string })?.statusMessage ?? 'Scenario polling failed'
}
refreshStatus()
}
function startPolling() {
if (!import.meta.client || pollTimer) return
void pollScenario()
pollTimer = setInterval(() => void pollScenario(), SCENARIO_POLL_MS)
refreshStatus()
}
function closeSource() {
if (source) {
source.close()
source = null
}
if (reconnectTimer) clearTimeout(reconnectTimer)
reconnectTimer = null
}
function connectSse() {
if (!import.meta.client) return
closeSource()
if (navigator.onLine === false) {
store.status = 'offline'
startPolling()
return
}
const eventSource = new EventSource('/api/stream')
source = eventSource
eventSource.onopen = () => {
if (source !== eventSource) return
store.sseFailures = 0
store.pollFailures = 0
store.error = ''
// Start the stale watchdog now: a proxy can accept the SSE headers and
// then buffer the body, so "open" does not prove events are flowing.
store.lastEventAt = nowIso()
clearPolling()
refreshStatus()
}
eventSource.addEventListener('scenario', (event) => {
if (source !== eventSource) return
const parsed = parseScenarioEvent((event as MessageEvent).data)
if (!parsed) {
store.error = 'Ignored a malformed scenario event'
return
}
store.sseFailures = 0
applyScenario(parsed, 'sse')
refreshStatus()
})
eventSource.addEventListener('ping', () => {
if (source !== eventSource) return
store.sseFailures = 0
store.lastEventAt = nowIso()
if (pollTimer && eventSource.readyState === EventSource.OPEN) clearPolling()
refreshStatus()
})
eventSource.onerror = () => {
if (source !== eventSource) return
store.sseFailures += 1
// A non-200 response (Nitro 502/503, proxy error) leaves EventSource in
// CLOSED and the browser will not retry it. Treat that as a definitive
// failure: start polling now and try the stream again on a timer. Network
// errors while CONNECTING still use the browser's own retry loop.
const fatal = eventSource.readyState === EventSource.CLOSED
if (fatal) {
store.sseFailures = Math.max(store.sseFailures, SSE_FAILURES_BEFORE_POLLING)
if (!reconnectTimer) {
reconnectTimer = setTimeout(() => {
if (!started) return
connectSse()
}, 5000)
}
}
if (store.sseFailures >= SSE_FAILURES_BEFORE_POLLING) startPolling()
refreshStatus()
}
}
function checkStale() {
if (!import.meta.client || !started) return
const sseOpen = source?.readyState === EventSource.OPEN
if (sseOpen && store.lastEventAt) {
const age = Date.now() - Date.parse(store.lastEventAt)
if (age > SSE_STALE_MS) {
// Connection is open but no ping arrived: Cloudflare/path buffering.
// Polling is the contract fallback; retry SSE once a minute.
store.sseFailures = Math.max(store.sseFailures, SSE_FAILURES_BEFORE_POLLING)
startPolling()
refreshStatus()
if (Date.now() - lastStaleRetry > 60000) {
lastStaleRetry = Date.now()
connectSse()
}
}
}
if (store.pollFailures > 0) refreshStatus()
}
function start() {
if (!import.meta.client || started) return
started = true
store.sseFailures = 0
store.pollFailures = 0
store.lastEventAt = ''
store.error = ''
store.status = 'connecting'
window.addEventListener('online', handleOnline)
window.addEventListener('offline', handleOffline)
staleTimer = setInterval(checkStale, 5000)
connectSse()
}
function stop() {
if (!import.meta.client) return
started = false
closeSource()
clearPolling()
if (staleTimer) clearInterval(staleTimer)
staleTimer = null
window.removeEventListener('online', handleOnline)
window.removeEventListener('offline', handleOffline)
store.status = 'connecting'
}
function handleOnline() {
if (!started) return
store.pollFailures = 0
connectSse()
void pollScenario()
}
function handleOffline() {
if (!started) return
store.status = 'offline'
if (pollTimer) clearInterval(pollTimer)
pollTimer = null
}
/**
* Subscribe the current page to the Go scenario stream through Nitro.
*
* The first render uses `initial` from SSR; after mount the composable opens
* `/api/stream`, shows Live/Polling/Offline, and falls back to GET
* /api/scenario every 5 s when SSE fails or is buffered.
*/
export function useLiveScenario(initial?: ScenarioState | null) {
const initialScenario = initial ?? null
const current = computed<ScenarioState | null>(() => store.serverScenario ?? initialScenario)
const scenarioId = computed(() => current.value?.scenario.scenario ?? 'base')
const status = computed(() => store.status)
const statusLabel = computed(() => LIVE_LABELS[store.status])
onMounted(() => {
// Seed after hydration so the first client paint matches the SSR HTML.
if (initialScenario && !store.serverScenario) store.serverScenario = initialScenario
subscribers += 1
start()
})
onBeforeUnmount(() => {
subscribers = Math.max(0, subscribers - 1)
if (subscribers === 0) stop()
})
return reactive({
scenario: current,
scenarioId,
version: computed(() => current.value?.version ?? 0),
scenarioAt: computed(() => current.value?.at ?? ''),
status,
statusLabel,
lastEventAt: computed(() => store.lastEventAt),
lastPollAt: computed(() => store.lastPollAt),
error: computed(() => store.error),
revision: computed(() => store.revision),
pollNow: pollScenario,
})
}
+3 -3
View File
@@ -8,7 +8,7 @@ useHead({ title: 'About the data and limits — PulseCast' })
const { data: meta } = await useFetch<MetaResponse>('/api/meta')
const config = useRuntimeConfig()
const usingMock = computed(() => Boolean(config.public.useMock))
const usingMock = computed(() => ['1', 'true'].includes(String(config.public.useMock).toLowerCase()))
</script>
<template>
@@ -87,7 +87,7 @@ const usingMock = computed(() => Boolean(config.public.useMock))
<tr><th scope="row" style="text-align: left; font-weight: 600">Context version</th><td class="mono">{{ meta?.context_version ?? '—' }}</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Coverage</th><td>{{ meta ? `${formatDate(meta.coverage.from)} → ${formatDate(meta.coverage.to)}` : '—' }}</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Validation</th><td>{{ meta ? `WAPE ${formatPercent(meta.metrics.wape, 1)} · baseline ${formatPercent(meta.metrics.baseline_wape, 1)} · R² ${meta.metrics.r2}` : '—' }}</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Weather source</th><td>Open-Meteo archive + forecast via `/api/context`</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Weather source</th><td>Open-Meteo archive + forecast via /api/context</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Holidays</th><td>Baden-Württemberg 2025–2026 public holidays</td></tr>
</OnyxTable>
<p class="small muted table-note">Meta comes from Go <code>/api/meta</code> through the Nitro proxy.</p>
@@ -139,7 +139,7 @@ const usingMock = computed(() => Boolean(config.public.useMock))
service; the plan heuristic is the shared implementation in <code>shared/staffing.ts</code>.
</p>
<p v-else class="small muted" style="margin-top: 0">
The browser only talks to this Nuxt origin. Nitro proxies `/api/*` to the Go API at
The browser only talks to this Nuxt origin. Nitro proxies /api/* to the Go API at
<code>NUXT_API_INTERNAL_BASE</code>; forecast, context and meta are served from there.
</p>
<p class="small muted" style="margin: 0">
+269
View File
@@ -0,0 +1,269 @@
<script setup lang="ts">
import {
iconArrowRight,
iconCircleCheck,
iconCircleX,
iconPresentionBoard,
iconSync,
iconTriangleWarning,
} from '@sit-onyx/icons'
import { scenarioLabel } from '#shared/live'
import type { ScenarioPreset, ScenarioState } from '#shared/types'
import { apiErrorMessage, apiErrorStatus } from '~/utils/api-error'
import { formatDateTime } from '~/utils/format'
useHead({ title: 'Presenter control — PulseCast' })
const { data: initialScenario } = await useFetch<ScenarioState>('/api/scenario')
const { data: presets, error: presetsError } = await useFetch<ScenarioPreset[]>('/api/scenarios')
const live = useLiveScenario(initialScenario.value)
const submitted = ref<ScenarioState | null>(null)
const busy = ref('')
const message = ref('')
const errorMessage = ref('')
const current = computed(() => {
const liveState = live.scenario
const local = submitted.value
if (!liveState) return local ?? initialScenario.value ?? null
if (!local) return liveState
// A remote presenter can move the stage on; always show the newer version.
return liveState.version >= local.version ? liveState : local
})
const activeId = computed(() => current.value?.scenario.scenario ?? '')
const presetList = computed(() => presets.value ?? [])
function applyBody(preset: ScenarioPreset) {
return {
scenario: preset.id,
weather: preset.weather ?? {},
event: preset.event,
}
}
async function apply(preset: ScenarioPreset) {
if (busy.value) return
busy.value = preset.id
message.value = ''
errorMessage.value = ''
try {
const response = await $fetch<ScenarioState>('/api/scenario', {
method: 'POST',
body: applyBody(preset),
})
submitted.value = response
message.value = `${preset.label} is now live · version ${response.version}.`
} catch (error) {
errorMessage.value =
apiErrorMessage(error, 'The scenario change failed. Check the Go API and control credentials.') +
(apiErrorStatus(error) === 401 ? ' Reload this page to sign in again.' : '')
} finally {
busy.value = ''
}
}
</script>
<template>
<div class="page page-stack control-page">
<header class="page-header">
<div>
<p class="eyebrow">Presenter control · not linked in public navigation</p>
<OnyxHeadline is="h1">Change the scenario once. Every screen follows.</OnyxHeadline>
<p class="lede">
Each button POSTs to this Nuxt origin. Nitro attaches the Go control credentials server-side; the browser
never sees them. <NuxtLink to="/stage">Stage</NuxtLink> and <NuxtLink to="/live">Live</NuxtLink> update through
SSE, with a 5-second polling fallback.
</p>
</div>
<div class="hero-actions">
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" />
<OnyxBadge v-if="current" color="neutral" density="compact">v{{ current.version }}</OnyxBadge>
</div>
</header>
<div v-if="errorMessage" class="callout callout--warning" role="alert">
<OnyxIcon :icon="iconCircleX" size="16px" color="danger" />
<span>{{ errorMessage }}</span>
</div>
<div v-if="message" class="callout" role="status">
<OnyxIcon :icon="iconCircleCheck" size="16px" color="success" />
<span>{{ message }}</span>
</div>
<div class="split-grid">
<div class="card-stack">
<OnyxCard>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Scenario presets</OnyxHeadline>
<p class="small muted" style="margin: 0">
The enum is fixed by CONTRACT.md. Weather and event values match the demo narrative.
</p>
</div>
<OnyxBadge color="info" density="compact">server proxy</OnyxBadge>
</div>
<div v-if="presetList.length" class="scenario-grid">
<button
v-for="preset in presetList"
:key="preset.id"
type="button"
class="scenario-button"
:class="{ 'scenario-button--active': preset.id === activeId }"
:disabled="Boolean(busy)"
:aria-pressed="preset.id === activeId"
@click="apply(preset)"
>
<span class="scenario-button__head">
<strong>{{ preset.label }}</strong>
<OnyxBadge v-if="preset.id === activeId" color="success" density="compact">on stage</OnyxBadge>
<OnyxBadge v-else color="neutral" density="compact">{{ preset.short }}</OnyxBadge>
</span>
<span class="small muted">{{ preset.description }}</span>
<span v-if="busy === preset.id" class="scenario-button__busy">
<OnyxIcon :icon="iconSync" size="16px" color="primary" class="spin" />
Broadcasting…
</span>
<span v-else class="scenario-button__action">
Apply
<OnyxIcon :icon="iconArrowRight" size="16px" color="primary" />
</span>
</button>
</div>
<div v-else class="callout callout--warning">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
Scenario presets could not be loaded.
<span v-if="presetsError" class="muted">{{ presetsError.statusMessage }}</span>
</div>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Open the audience views</OnyxHeadline>
<OnyxIcon :icon="iconPresentionBoard" size="24px" color="primary" />
</div>
<div class="hero-actions">
<OnyxButton label="Open /stage" link="/stage" color="primary" />
<OnyxButton label="Open /live" link="/live" mode="outline" />
<OnyxButton label="Open /plan" link="/plan" mode="outline" />
</div>
<p class="small muted table-note">
Put <code>/stage</code> on the projector and let the audience scan the QR code. <code>/live</code> needs no
login and keeps the last known plan if the stream drops.
</p>
</OnyxCard>
</div>
<aside class="card-stack">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Current scenario</OnyxHeadline>
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" compact />
</div>
<p class="control-current">{{ current ? scenarioLabel(current.scenario.scenario) : 'Unavailable' }}</p>
<dl class="metric-list">
<div><dt>Version</dt><dd>{{ current?.version ?? '—' }}</dd></div>
<div><dt>Broadcast at</dt><dd>{{ current ? formatDateTime(current.at) : '—' }}</dd></div>
<div><dt>Last SSE event</dt><dd>{{ live.lastEventAt ? formatDateTime(live.lastEventAt) : '—' }}</dd></div>
<div><dt>Transport</dt><dd>{{ live.statusLabel }}</dd></div>
</dl>
<p v-if="live.error" class="small muted table-note">{{ live.error }}</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">What the presenter says</OnyxHeadline>
</div>
<ul class="why-list">
<li><span><strong>Base week</strong> — normal weather, no event uplift.</span></li>
<li><span><strong>Sunny Saturday + market</strong> — the Saturday plan should add staff.</span></li>
<li><span><strong>Rainy Saturday</strong> — the Saturday plan should shed staff.</span></li>
<li><span><strong>Wednesday event</strong> — the weekday evening block should rise.</span></li>
</ul>
<p class="small muted table-note">
If the numbers do not move on stage, check the <code>cached</code> badge: Go may be serving its last good
forecast because the ML service is down.
</p>
</OnyxCard>
</aside>
</div>
</div>
</template>
<style scoped>
.control-current {
margin: 0 0 var(--onyx-density-md);
color: var(--onyx-color-text-icons-primary-intense);
font-size: clamp(1.6rem, 3vw, 2.4rem);
font-weight: 700;
line-height: 1.1;
}
.scenario-button {
display: flex;
flex-direction: column;
gap: var(--onyx-density-xs);
width: 100%;
padding: var(--onyx-density-md);
border: 1px solid var(--onyx-color-base-neutral-300);
border-radius: var(--onyx-radius-component-container-soft);
background: var(--onyx-color-base-neutral-100);
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.scenario-button:hover:not(:disabled),
.scenario-button:focus-visible {
border-color: var(--onyx-color-base-primary-500);
outline: 2px solid var(--onyx-color-base-primary-300);
outline-offset: 1px;
}
.scenario-button:disabled {
cursor: progress;
opacity: 0.65;
}
.scenario-button--active {
border-color: var(--onyx-color-base-primary-600);
background: var(--onyx-color-base-primary-100);
}
.scenario-button__head,
.scenario-button__action,
.scenario-button__busy {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--onyx-density-xs);
}
.scenario-button__action,
.scenario-button__busy {
justify-content: flex-start;
margin-top: var(--onyx-density-xs);
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.8125rem;
}
.spin {
animation: spin 0.9s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.spin {
animation: none;
}
}
</style>
+57 -17
View File
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { iconCalendar, iconChart } from '@sit-onyx/icons'
import { iconCalendar, iconChart, iconTriangleWarning } from '@sit-onyx/icons'
import { dailyWeather } from '#shared/insights'
import { berlinParts, planWeekStart, STANDARD_VISITORS_PER_STAFF_HOUR } from '#shared/staffing'
import type { ContextResponse, ForecastResponse, MetaResponse, Point, Scenario, ScenarioPreset, Sensor } from '#shared/types'
import type { ContextResponse, ForecastResponse, MetaResponse, Point, Scenario, ScenarioPreset, ScenarioState, Sensor } from '#shared/types'
import { formatDate, formatNumber, formatPercent, formatShortDate, formatWeekday, formatWeekdayShort, weekLabel } from '~/utils/format'
useHead({ title: 'Forecast — PulseCast' })
@@ -21,16 +21,31 @@ const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: context } = await useFetch<ContextResponse>('/api/context')
const { data: meta } = await useFetch<MetaResponse>('/api/meta')
const { data: presets } = await useFetch<ScenarioPreset[]>('/api/scenarios')
const { data: liveScenarioState } = await useFetch<ScenarioState>('/api/scenario')
const live = useLiveScenario(liveScenarioState.value)
scenario.value = live.scenarioId
sensorId.value =
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
sensorId.value
const { data: forecast } = await useFetch<ForecastResponse>('/api/forecast', {
const {
data: forecast,
error: forecastError,
refresh: refreshForecast,
} = await useFetch<ForecastResponse>('/api/forecast', {
query: computed(() => ({ sensor: sensorId.value, horizon: '7d', scenario: scenario.value })),
})
watch(
() => live.revision,
() => {
if (live.scenarioId !== scenario.value) scenario.value = live.scenarioId
else void refreshForecast()
},
)
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const sensorOptions = computed(() =>
(sensors.value ?? []).map((sensor) => ({ value: sensor.id, label: sensor.name })),
@@ -81,9 +96,14 @@ const weekPeak = computed(() =>
days.value.length ? days.value.reduce((best, day) => (day.peak > best.peak ? day : best)) : undefined,
)
const dayMax = computed(() => Math.max(...days.value.map((day) => day.peak), 1))
// The API 7-day window starts at the current hour, so it spans up to eight
// calendar days. Label the real window instead of the Monday plan week.
const forecastStart = computed(() => days.value[0]?.date ?? weekStart)
const forecastEnd = computed(() => days.value.at(-1)?.date ?? weekEnd)
const forecastWindow = computed(() => weekLabel(forecastStart.value, forecastEnd.value))
const weekWeather = computed(() =>
Object.values(dailyWeather(context.value?.weather.forecast ?? []))
.filter((day) => day.date >= weekStart && day.date <= weekEnd)
.filter((day) => day.date >= forecastStart.value && day.date <= forecastEnd.value)
.sort((a, b) => a.date.localeCompare(b.date)),
)
const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
@@ -93,24 +113,37 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<div class="page page-stack">
<header class="page-header">
<div>
<p class="eyebrow">Forecast · {{ weekLabel(weekStart, weekEnd) }}</p>
<p class="eyebrow">Forecast · {{ forecastWindow }}</p>
<OnyxHeadline is="h1">Next week peaks on {{ weekPeak ? formatWeekday(weekPeak.date) : '—' }}.</OnyxHeadline>
<p class="lede">
A 168-hour forecast for <strong>{{ activeSensor?.name ?? 'the selected store' }}</strong>, aggregated by
day. The decision, shift blocks and hourly coverage are on <NuxtLink to="/plan">Plan</NuxtLink>.
</p>
</div>
<div style="min-width: 14rem">
<OnyxSelect
v-model="sensorId"
label="Sensor"
list-label="Inner-city sensors"
:options="sensorOptions"
density="compact"
/>
<div class="forecast-header-controls">
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" />
<div style="min-width: 14rem">
<OnyxSelect
v-model="sensorId"
label="Sensor"
list-label="Inner-city sensors"
:options="sensorOptions"
density="compact"
/>
</div>
</div>
</header>
<div v-if="forecastError" class="callout callout--warning" role="alert">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
The forecast could not be loaded. <span class="muted">{{ forecastError.statusMessage }}</span>
<OnyxButton label="Retry" mode="plain" density="compact" @click="refreshForecast()" />
</div>
<div v-else-if="forecast && !days.length" class="callout callout--warning" role="status">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
No forecast points are available for this store yet. Try another sensor.
</div>
<OnyxCard>
<div class="card-header">
<div>
@@ -216,8 +249,7 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<li>
<OnyxIcon :icon="iconCalendar" size="16px" color="primary" />
<span>
Forecast covers {{ formatDate(days[0]?.date ?? weekStart) }} →
{{ formatDate(days[days.length - 1]?.date ?? weekEnd) }} in Europe/Berlin.
Forecast covers {{ formatDate(forecastStart) }} → {{ formatDate(forecastEnd) }} in Europe/Berlin.
</span>
</li>
</ul>
@@ -230,7 +262,7 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<style scoped>
.forecast-bars {
display: grid;
grid-template-columns: repeat(7, minmax(0, 1fr));
grid-template-columns: repeat(auto-fit, minmax(4.5rem, 1fr));
gap: var(--onyx-density-xs);
align-items: end;
min-height: 13rem;
@@ -264,9 +296,17 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
background: var(--onyx-color-base-primary-500);
}
.forecast-header-controls {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: var(--onyx-density-sm);
}
@media (max-width: 576px) {
.forecast-bars {
gap: 2px;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: var(--onyx-density-2xs);
}
.forecast-bar strong {
+324
View File
@@ -0,0 +1,324 @@
<script setup lang="ts">
import {
iconArrowRight,
iconCircleInformation,
iconMobileSignal,
iconSync,
iconTriangleWarning,
iconUserGroup,
} from '@sit-onyx/icons'
import { scenarioLabel } from '#shared/live'
import type { ScenarioState, Sensor, Shift, StaffingResponse } from '#shared/types'
import { formatDateTime, formatEuro, formatNumber, formatPercent, formatShortDate, formatWeekday } from '~/utils/format'
useHead({ title: 'Live recommendation — PulseCast' })
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: initialScenario } = await useFetch<ScenarioState>('/api/scenario')
const sensorId = ref(
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
'hn-stadtgalerie-01',
)
const live = useLiveScenario(initialScenario.value)
const {
data: planData,
status: planStatus,
error: planError,
refresh: refreshPlan,
} = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({
sensor: sensorId.value,
scenario: live.scenarioId,
standard: 'standard',
})),
})
let lastScenarioId = live.scenarioId
watch(
() => live.revision,
() => {
if (live.scenarioId === lastScenarioId) void refreshPlan()
lastScenarioId = live.scenarioId
},
)
const plan = computed(() => planData.value ?? null)
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
function maxOf<T>(items: T[], score: (item: T) => number): T | undefined {
let best: T | undefined
for (const item of items) if (!best || score(item) > score(best)) best = item
return best
}
const peakShift = computed<Shift | undefined>(() =>
plan.value ? maxOf(plan.value.shifts, (shift) => shift.staff) : undefined,
)
const peakStaff = computed(() => peakShift.value?.staff ?? 0)
const totalStaffHours = computed(() =>
plan.value ? plan.value.hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0) : 0,
)
const currentReason = computed(() => plan.value?.why[0] ?? '')
const lastUpdate = computed(() => {
if (live.scenarioAt) return live.scenarioAt
return plan.value?.context_version ?? ''
})
</script>
<template>
<div class="page page-stack live-page">
<header class="live-header">
<div>
<p class="eyebrow">Live · no login</p>
<OnyxHeadline is="h1">The plan on your phone.</OnyxHeadline>
<p class="lede">
{{ activeSensor?.name ?? 'Stadtgalerie' }} · {{ scenarioLabel(live.scenarioId) }}. Updates arrive over SSE;
if the stream drops, this page polls every 5 seconds.
</p>
</div>
<div class="live-header__status">
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" />
<OnyxBadge color="neutral" density="compact">v{{ live.version || '—' }}</OnyxBadge>
</div>
</header>
<div v-if="planError" class="callout callout--warning" role="alert">
<OnyxIcon :icon="iconTriangleWarning" size="18px" color="warning" />
<div>
<strong>The live plan is unavailable.</strong>
<span class="muted">&nbsp;{{ planError.statusMessage ?? 'The API did not answer.' }}</span>
</div>
<OnyxButton label="Retry" mode="outline" density="compact" :icon="iconSync" @click="refreshPlan()" />
</div>
<div v-else-if="planStatus === 'pending' && !plan" class="callout">
<OnyxIcon :icon="iconSync" size="18px" color="primary" />
<span>Loading the current recommendation…</span>
</div>
<div v-else-if="plan && !plan.shifts.length" class="callout callout--warning" role="status">
<OnyxIcon :icon="iconTriangleWarning" size="18px" color="warning" />
<span>No shift blocks are available yet. The presenter may still be preparing the plan.</span>
</div>
<section class="live-hero" aria-labelledby="live-decision">
<p class="live-hero__kicker"><OnyxIcon :icon="iconUserGroup" size="18px" color="primary" /> Current recommendation</p>
<p id="live-decision" class="live-hero__value">
<template v-if="plan">{{ peakStaff }} staff</template>
<template v-else>No plan yet</template>
</p>
<p class="live-hero__shift">
<template v-if="peakShift">
<strong>{{ formatWeekday(peakShift.date) }} {{ formatShortDate(peakShift.date) }}</strong><br />
{{ peakShift.start }}–{{ peakShift.end }} · peak shift
</template>
<template v-else>Waiting for the peak shift</template>
</p>
<p v-if="currentReason" class="live-hero__why">
<OnyxIcon :icon="iconCircleInformation" size="16px" color="primary" />
<span>{{ currentReason }}</span>
</p>
<OnyxButton
label="Open the full plan"
:link="`/plan?scenario=${live.scenarioId}`"
color="primary"
:icon="iconArrowRight"
icon-position="right"
/>
</section>
<section class="live-metrics" aria-label="Plan at a glance">
<div class="live-metric">
<p class="live-metric__label">Staff-hours</p>
<p class="live-metric__value">{{ plan ? formatNumber(totalStaffHours) : '—' }}</p>
</div>
<div class="live-metric">
<p class="live-metric__label">Labour cost</p>
<p class="live-metric__value">{{ plan ? formatEuro(plan.summary.cost_eur) : '—' }}</p>
</div>
<div class="live-metric">
<p class="live-metric__label">Coverage</p>
<p class="live-metric__value">{{ plan ? formatPercent(plan.summary.coverage_pct, 1) : '—' }}</p>
</div>
<div class="live-metric">
<p class="live-metric__label">Understaffed</p>
<p class="live-metric__value">{{ plan ? `${plan.summary.understaffed_hours} h` : '—' }}</p>
</div>
</section>
<section class="live-status-card">
<div class="live-status-card__row">
<span class="live-status-card__label">Scenario</span>
<strong>{{ scenarioLabel(live.scenarioId) }}</strong>
</div>
<div class="live-status-card__row">
<span class="live-status-card__label">Version</span>
<span>{{ live.version || '—' }}</span>
</div>
<div class="live-status-card__row">
<span class="live-status-card__label">Last update</span>
<span>{{ lastUpdate ? formatDateTime(lastUpdate) : '—' }}</span>
</div>
<div class="live-status-card__row">
<span class="live-status-card__label">Transport</span>
<span>{{ live.statusLabel }}<template v-if="live.status === 'polling'"> · 5 s</template></span>
</div>
<p v-if="live.error" class="small muted table-note">{{ live.error }}</p>
</section>
<footer class="live-footer">
<p>
<strong>Decision support, not an optimizer.</strong> The plan uses
{{ plan?.assumptions.visitors_per_staff_hour ?? 25 }} visitors per staff-hour,
×{{ plan?.assumptions.safety_factor ?? 1.15 }} safety, {{ plan?.assumptions.shift_length_h ?? 4 }} h shift
blocks and €{{ plan?.assumptions.labor_cost_eur_h ?? 16 }}/h.
</p>
<p class="muted">
Estimated devices, not people · {{ sensors?.length ?? 8 }} sensors in a 580 m cluster · no POS, sales or
payroll data.
</p>
</footer>
</div>
</template>
<style scoped>
.live-page {
max-width: 44rem;
gap: clamp(0.85rem, 2vw, 1.25rem);
}
.live-header {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: space-between;
gap: var(--onyx-density-sm);
}
.live-header h1 {
margin: 0;
}
.live-header__status {
display: flex;
flex-wrap: wrap;
gap: var(--onyx-density-xs);
align-items: center;
}
.live-hero {
padding: clamp(1.1rem, 3vw, 1.75rem);
border: 1px solid var(--onyx-color-base-primary-300);
border-radius: var(--onyx-radius-component-container-soft);
background:
radial-gradient(circle at 100% 0%, var(--onyx-color-base-primary-200), transparent 48%),
linear-gradient(135deg, var(--onyx-color-base-primary-100), var(--onyx-color-base-neutral-100) 72%);
}
.live-hero__kicker {
display: flex;
align-items: center;
gap: 0.35rem;
margin: 0;
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.8rem;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.live-hero__value {
margin: var(--onyx-density-xs) 0 0;
font-size: clamp(3rem, 16vw, 5.5rem);
font-weight: 800;
letter-spacing: -0.04em;
line-height: 0.95;
color: var(--onyx-color-text-icons-primary-intense);
}
.live-hero__shift {
margin: var(--onyx-density-sm) 0 0;
font-size: clamp(1rem, 3.5vw, 1.25rem);
line-height: 1.4;
}
.live-hero__why {
display: flex;
gap: var(--onyx-density-xs);
align-items: flex-start;
margin: var(--onyx-density-md) 0;
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.9rem;
line-height: 1.45;
}
.live-metrics {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--onyx-density-sm);
}
.live-metric {
min-width: 0;
padding: var(--onyx-density-md);
border: 1px solid var(--onyx-color-base-neutral-300);
border-radius: var(--onyx-radius-component-container-soft);
background: var(--onyx-color-base-neutral-100);
}
.live-metric__label {
margin: 0;
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.78rem;
font-weight: 600;
}
.live-metric__value {
margin: var(--onyx-density-xs) 0 0;
font-size: clamp(1.35rem, 6vw, 1.9rem);
font-weight: 700;
line-height: 1.1;
}
.live-status-card {
display: grid;
gap: var(--onyx-density-xs);
padding: var(--onyx-density-md);
border: 1px solid var(--onyx-color-base-neutral-300);
border-radius: var(--onyx-radius-component-container-soft);
background: var(--onyx-color-base-neutral-100);
}
.live-status-card__row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--onyx-density-sm);
}
.live-status-card__label {
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.8rem;
}
.live-footer {
padding-top: var(--onyx-density-sm);
border-top: 1px solid var(--onyx-color-base-neutral-300);
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.75rem;
line-height: 1.5;
}
.live-footer p {
margin: 0 0 var(--onyx-density-xs);
}
@media (min-width: 577px) {
.live-metrics {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
</style>
+25 -5
View File
@@ -24,6 +24,7 @@ import type {
MetaResponse,
Scenario,
ScenarioPreset,
ScenarioState,
Sensor,
Shift,
StaffingHour,
@@ -68,9 +69,13 @@ const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: context } = await useFetch<ContextResponse>('/api/context')
const { data: meta } = await useFetch<MetaResponse>('/api/meta')
const { data: presets } = await useFetch<ScenarioPreset[]>('/api/scenarios')
const { data: liveScenarioState } = await useFetch<ScenarioState>('/api/scenario')
const live = useLiveScenario(liveScenarioState.value)
const sensorId = ref(preferredSensor(sensors.value))
const scenario = ref<Scenario>(initialScenario())
// The stage scenario wins unless the URL explicitly asks for another one.
if (!route.query.scenario) scenario.value = live.scenarioId
const standard = ref<Standard>('standard')
const approved = ref(false)
const generating = ref(false)
@@ -128,6 +133,16 @@ watch(
},
)
// A scenario event changes the plan. If the enum is unchanged (same scenario,
// new override/version), the query string does not move, so refresh it here.
watch(
() => live.revision,
() => {
if (live.scenarioId !== scenario.value) scenario.value = live.scenarioId
else void refresh()
},
)
const apiPlan = computed(() => apiPlanData.value ?? EMPTY_PLAN)
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const activeScenario = computed(() => presets.value?.find((preset) => preset.id === scenario.value))
@@ -383,6 +398,7 @@ function exportPlan() {
@click="approved = !approved"
/>
<OnyxButton label="Export CSV" :icon="iconDownload" mode="outline" @click="exportPlan" />
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" />
<OnyxBadge v-if="approved" color="success">Approved · demo</OnyxBadge>
<span v-else class="small muted">Draft for manager review</span>
</div>
@@ -392,8 +408,8 @@ function exportPlan() {
Local preview · the Go API plan is unchanged.
</template>
<template v-else>
Go `/api/staffing` · updated {{ context ? formatDateTime(context.updated_at) : '—' }} · no POS, sales
or labour-cost feed.
Go /api/staffing · scenario v{{ live.version }} · broadcast
{{ live.scenarioAt ? formatDateTime(live.scenarioAt) : '—' }} · no POS, sales or labour-cost feed.
</template>
</p>
</div>
@@ -426,6 +442,10 @@ function exportPlan() {
The staffing API could not be loaded. Check that the Go API is running and that NUXT_API_INTERNAL_BASE points
to it. <span v-if="error" class="muted">{{ error.statusMessage }}</span>
</div>
<div v-else-if="status === 'success' && !apiPlan.hours.length" class="callout callout--warning">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
No open hours are available for this store and scenario yet. Pick another sensor or check the data window.
</div>
<section class="summary-grid" aria-label="Plan summary">
<MetricCard
@@ -463,7 +483,7 @@ function exportPlan() {
<div>
<OnyxHeadline is="h2">Plan inputs</OnyxHeadline>
<p class="small muted" style="margin: 0">
Store, service standard and scenario are sent to Go `/api/staffing`. Local assumption edits render a
Store, service standard and scenario are sent to Go /api/staffing. Local assumption edits render a
preview from the API forecast.
</p>
</div>
@@ -555,7 +575,7 @@ function exportPlan() {
message="Assumption only. No payroll or POS data exists."
/>
<p class="small muted" style="grid-column: 1 / -1; margin: 0">
These four values are not query inputs of Go `/api/staffing`. Changing them shows a local preview;
These four values are not query inputs of Go /api/staffing. Changing them shows a local preview;
“Use API plan” restores the server values.
</p>
<div class="form-actions" style="grid-column: 1 / -1">
@@ -720,7 +740,7 @@ function exportPlan() {
<p class="stat-label" style="margin-bottom: var(--onyx-density-xs)">Weather during the plan week</p>
<WeatherStrip :days="weekWeather" />
<p v-if="!weekWeather.length" class="small muted table-note">
The weather forecast from `/api/context` does not cover this plan window yet.
The weather forecast from /api/context does not cover this plan window yet.
</p>
<p class="small muted table-note">
{{ activeScenario?.description ?? 'Base scenario uses the API forecast weather.' }}
+4 -3
View File
@@ -136,8 +136,9 @@ const days = computed(() =>
<div class="callout">
<OnyxIcon :icon="iconCircleInformation" size="16px" color="primary" />
The base and scenario plans are generated by Go `/api/staffing`. SSE broadcast to <code>/stage</code> and
phones is the next slice; this page makes the recommendation change visible on one screen.
The base and scenario plans are generated by Go /api/staffing. The presenter broadcasts from
<NuxtLink to="/control">/control</NuxtLink>; <NuxtLink to="/stage">/stage</NuxtLink> and
<NuxtLink to="/live">/live</NuxtLink> follow the scenario over SSE with a 5 s polling fallback.
</div>
<div class="split-grid">
@@ -246,7 +247,7 @@ const days = computed(() =>
</ul>
<p class="small muted table-note">
Scenario perturbations are produced by the Go/ML stack. This page reads the base and scenario plans from
`/api/staffing`; it does not invent its own multipliers.
/api/staffing; it does not invent its own multipliers.
</p>
</OnyxCard>
+560
View File
@@ -0,0 +1,560 @@
<script setup lang="ts">
import {
iconArrowRight,
iconCalendar,
iconCheck,
iconMobileSignal,
iconQrCode,
iconSync,
iconTriangleWarning,
iconUserGroup,
} from '@sit-onyx/icons'
import { scenarioLabel } from '#shared/live'
import type {
ForecastResponse,
ScenarioState,
Sensor,
Shift,
StaffingHour,
StaffingResponse,
} from '#shared/types'
import { formatDateTime, formatEuro, formatPercent, formatShortDate, formatWeekday } from '~/utils/format'
useHead({ title: 'Stage — PulseCast live decision' })
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: initialScenario } = await useFetch<ScenarioState>('/api/scenario')
const sensorId = ref(
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
'hn-stadtgalerie-01',
)
const live = useLiveScenario(initialScenario.value)
const {
data: planData,
status: planStatus,
error: planError,
refresh: refreshPlan,
} = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({
sensor: sensorId.value,
scenario: live.scenarioId,
standard: 'standard',
})),
})
const {
data: forecastData,
error: forecastError,
refresh: refreshForecast,
} = await useFetch<ForecastResponse>('/api/forecast', {
query: computed(() => ({
sensor: sensorId.value,
horizon: '7d',
scenario: live.scenarioId,
})),
})
// A new version of the same scenario (new weather/event values) does not
// change the query string, so refresh explicitly. A different scenario id
// already triggers useFetch's own query watcher.
let lastScenarioId = live.scenarioId
watch(
() => live.revision,
() => {
if (live.scenarioId === lastScenarioId) {
void refreshPlan()
void refreshForecast()
}
lastScenarioId = live.scenarioId
},
)
const plan = computed<StaffingResponse | null>(() => planData.value ?? null)
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
function maxOf<T>(items: T[], score: (item: T) => number): T | undefined {
let best: T | undefined
for (const item of items) if (!best || score(item) > score(best)) best = item
return best
}
const peakShift = computed<Shift | undefined>(() =>
plan.value ? maxOf(plan.value.shifts, (shift) => shift.staff) : undefined,
)
const peakHour = computed<StaffingHour | undefined>(() =>
plan.value ? maxOf(plan.value.hours, (hour) => hour.required_staff) : undefined,
)
const peakStaff = computed(() => peakShift.value?.staff ?? peakHour.value?.required_staff ?? 0)
const totalStaffHours = computed(() =>
plan.value ? plan.value.hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0) : 0,
)
const forecastPeak = computed(() => {
const points = forecastData.value?.points ?? []
return points.length ? Math.max(...points.map((point) => point.v)) : 0
})
const saving = computed(() =>
plan.value ? Math.max(0, plan.value.summary.flat_schedule_cost_eur - plan.value.summary.cost_eur) : 0,
)
const requestUrl = useRequestURL()
const liveUrl = computed(() => {
const origin = import.meta.client ? window.location.origin : requestUrl.origin
return `${origin}/live`
})
const qrSrc = computed(() => `/api/qr?text=${encodeURIComponent(liveUrl.value)}`)
const headline = computed(() => {
if (!plan.value) return 'Waiting for the next staffing plan.'
const shift = peakShift.value
if (!shift) return 'Next week has no shift blocks yet.'
return `${formatWeekday(shift.date)} peak: ${shift.staff} staff, ${shift.start}–${shift.end}.`
})
</script>
<template>
<div class="page page-stack stage-page">
<header class="stage-hero">
<div class="stage-hero__copy">
<div class="stage-kicker">
<OnyxBadge color="neutral" density="compact">PulseCast stage</OnyxBadge>
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" />
<OnyxBadge v-if="plan?.cached" color="warning" density="compact">cached forecast</OnyxBadge>
</div>
<h1 class="stage-headline">{{ headline }}</h1>
<p class="stage-sub">
{{ activeSensor?.name ?? 'Stadtgalerie' }} · {{ scenarioLabel(live.scenarioId) }} ·
{{ plan ? `${totalStaffHours} staff-hours` : 'waiting for the API' }} · updates live via SSE
</p>
<div class="stage-scenario">
<OnyxIcon :icon="iconCalendar" size="18px" color="primary" />
<span>
<strong>Scenario version {{ live.version || '—' }}</strong>
<template v-if="live.scenarioAt"> · broadcast {{ formatDateTime(live.scenarioAt) }}</template>
</span>
</div>
</div>
<div class="stage-qr">
<div class="stage-qr__frame">
<img :src="qrSrc" width="220" height="220" :alt="`QR code to ${liveUrl}`" />
</div>
<p class="stage-qr__label">
<OnyxIcon :icon="iconQrCode" size="16px" color="primary" />
Scan for the phone view
</p>
<p class="stage-qr__url mono">{{ liveUrl }}</p>
</div>
</header>
<div v-if="planError" class="callout callout--warning" role="alert">
<OnyxIcon :icon="iconTriangleWarning" size="18px" color="warning" />
<div>
<strong>The plan is unavailable.</strong>
<span class="muted">&nbsp;{{ planError.statusMessage ?? 'Check the Go API and ML service.' }}</span>
</div>
<OnyxButton label="Retry" mode="outline" density="compact" :icon="iconSync" @click="refreshPlan()" />
</div>
<div v-else-if="planStatus === 'pending' && !plan" class="callout">
<OnyxIcon :icon="iconSync" size="18px" color="primary" class="spin-slow" />
<span>Loading the current staffing plan…</span>
</div>
<div v-else-if="plan && !plan.hours.length" class="callout callout--warning" role="status">
<OnyxIcon :icon="iconTriangleWarning" size="18px" color="warning" />
<span>No open hours are available for this sensor yet. Check the data window or pick another store.</span>
</div>
<section class="stage-metrics" aria-label="Decision summary">
<div class="stage-metric stage-metric--primary">
<p class="stage-metric__label"><OnyxIcon :icon="iconUserGroup" size="18px" color="primary" /> Peak staff</p>
<p class="stage-metric__value">{{ plan ? peakStaff : '—' }}</p>
<p class="stage-metric__hint">
<template v-if="peakShift">{{ formatWeekday(peakShift.date) }} {{ peakShift.start }}–{{ peakShift.end }}</template>
<template v-else>Per shift block</template>
</p>
</div>
<div class="stage-metric">
<p class="stage-metric__label">Labour cost</p>
<p class="stage-metric__value">{{ plan ? formatEuro(plan.summary.cost_eur) : '—' }}</p>
<p class="stage-metric__hint">{{ plan ? `€${plan.assumptions.labor_cost_eur_h}/h assumption` : '—' }}</p>
</div>
<div class="stage-metric">
<p class="stage-metric__label">Coverage</p>
<p class="stage-metric__value">{{ plan ? formatPercent(plan.summary.coverage_pct, 1) : '—' }}</p>
<p class="stage-metric__hint">
{{ plan ? `${plan.summary.understaffed_hours} h under` : '—' }}
</p>
</div>
<div class="stage-metric">
<p class="stage-metric__label">Forecast peak</p>
<p class="stage-metric__value">{{ forecastPeak ? Math.round(forecastPeak) : '—' }}</p>
<p class="stage-metric__hint">estimated devices/hour</p>
</div>
<div class="stage-metric">
<p class="stage-metric__label">vs flat schedule</p>
<p class="stage-metric__value">−{{ plan ? formatEuro(saving) : '—' }}</p>
<p class="stage-metric__hint">same coverage, fewer hours</p>
</div>
</section>
<div class="stage-grid">
<section class="stage-panel" aria-labelledby="stage-decision">
<div class="stage-panel__head">
<OnyxHeadline id="stage-decision" is="h2">The decision on stage</OnyxHeadline>
<OnyxBadge color="success" density="compact">{{ scenarioLabel(live.scenarioId) }}</OnyxBadge>
</div>
<p class="stage-decision">
<template v-if="peakShift">
Put <strong>{{ peakShift.staff }} staff</strong> on {{ formatWeekday(peakShift.date) }}
{{ formatShortDate(peakShift.date) }}, {{ peakShift.start }}–{{ peakShift.end }}.
</template>
<template v-else>Pick a store and scenario; the recommendation appears here.</template>
</p>
<p class="stage-why">
<OnyxIcon :icon="iconCheck" size="18px" color="success" />
<template v-if="plan">
{{ plan.summary.understaffed_hours === 0 ? 'Every open hour is covered by the block plan.' : `${plan.summary.understaffed_hours} hours are below requirement.` }}
{{ plan.summary.overstaffed_hours }} hours are intentionally over requirement.
</template>
<template v-else>Nothing to approve yet.</template>
</p>
<div class="stage-actions">
<OnyxButton label="Presenter control" link="/control" color="primary" :icon="iconArrowRight" icon-position="right" />
<OnyxButton label="Open full plan" link="/plan" mode="outline" />
<OnyxButton label="Refresh" mode="plain" :icon="iconSync" @click="refreshPlan()" />
</div>
<p v-if="forecastError" class="small muted">
Forecast refresh failed: {{ forecastError.statusMessage }}
</p>
</section>
<aside class="stage-panel stage-panel--aside">
<div class="stage-panel__head">
<OnyxHeadline is="h2">On every phone</OnyxHeadline>
<OnyxBadge color="info" density="compact">no login</OnyxBadge>
</div>
<div class="stage-phone">
<div class="stage-phone__screen">
<p class="stage-phone__kicker"><OnyxIcon :icon="iconMobileSignal" size="14px" color="primary" /> LIVE</p>
<p class="stage-phone__value">{{ plan ? peakStaff : '—' }} staff</p>
<p class="stage-phone__label">
<template v-if="peakShift">{{ formatWeekday(peakShift.date) }} · {{ peakShift.start }}–{{ peakShift.end }}</template>
<template v-else>Waiting for the plan</template>
</p>
<p class="stage-phone__scenario">{{ scenarioLabel(live.scenarioId) }} · v{{ live.version || '—' }}</p>
</div>
</div>
<p class="small muted">
The audience scans the QR code. The same scenario event refreshes the phone view and this screen within
the SSE round trip.
</p>
</aside>
</div>
<footer class="stage-footer">
<span>
<strong>Assumptions:</strong> {{ plan?.assumptions.visitors_per_staff_hour ?? 25 }} visitors per staff-hour,
×{{ plan?.assumptions.safety_factor ?? 1.15 }} safety, {{ plan?.assumptions.shift_length_h ?? 4 }} h blocks,
store hours {{ plan?.assumptions.store_hours.open ?? '10:00' }}–{{ plan?.assumptions.store_hours.close ?? '20:00' }}.
</span>
<span class="muted">
Estimated devices, not people · 8 sensors in a 580 m cluster · no POS or payroll feed ·
last update {{ plan ? formatDateTime(live.scenarioAt || plan.context_version) : '—' }}
</span>
</footer>
</div>
</template>
<style scoped>
.stage-page {
gap: clamp(1rem, 2vw, 1.75rem);
}
.stage-hero {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: clamp(1rem, 3vw, 2.5rem);
align-items: center;
padding: clamp(1.25rem, 2.5vw, 2.5rem);
border: 1px solid var(--onyx-color-base-primary-200);
border-radius: var(--onyx-radius-component-container-soft);
background:
radial-gradient(circle at 100% 0%, var(--onyx-color-base-primary-200), transparent 45%),
linear-gradient(135deg, var(--onyx-color-base-primary-100), var(--onyx-color-base-neutral-100) 70%);
}
.stage-kicker,
.stage-scenario,
.stage-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--onyx-density-sm);
}
.stage-headline {
max-width: 24ch;
margin: var(--onyx-density-sm) 0 0;
font-size: clamp(2.1rem, 4.8vw, 4.5rem);
font-weight: 800;
letter-spacing: -0.03em;
line-height: 1.02;
color: var(--onyx-color-text-icons-primary-intense);
}
.stage-sub {
max-width: 70ch;
margin: var(--onyx-density-sm) 0 0;
color: var(--onyx-color-text-icons-neutral-medium);
font-size: clamp(0.95rem, 1.5vw, 1.15rem);
}
.stage-scenario {
margin-top: var(--onyx-density-md);
font-size: 0.9rem;
}
.stage-qr {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--onyx-density-xs);
text-align: center;
}
.stage-qr__frame {
padding: 0.65rem;
border: 1px solid var(--onyx-color-base-neutral-300);
border-radius: var(--onyx-radius-component-container-soft);
background: #fff;
box-shadow: var(--onyx-shadow-soft-bottom);
}
.stage-qr__frame img {
display: block;
width: min(220px, 32vw);
height: auto;
}
.stage-qr__label {
display: flex;
align-items: center;
gap: 0.35rem;
margin: 0;
font-weight: 600;
}
.stage-qr__url {
max-width: 18rem;
margin: 0;
overflow-wrap: anywhere;
color: var(--onyx-color-text-icons-neutral-medium);
}
.stage-metrics {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: var(--onyx-density-sm);
}
.stage-metric {
min-width: 0;
padding: var(--onyx-density-md);
border: 1px solid var(--onyx-color-base-neutral-300);
border-radius: var(--onyx-radius-component-container-soft);
background: var(--onyx-color-base-neutral-100);
}
.stage-metric--primary {
border-color: var(--onyx-color-base-primary-400);
background: var(--onyx-color-base-primary-100);
}
.stage-metric__label {
display: flex;
align-items: center;
gap: 0.35rem;
margin: 0;
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.8rem;
font-weight: 600;
}
.stage-metric__value {
margin: var(--onyx-density-xs) 0 0;
font-size: clamp(1.5rem, 2.6vw, 2.5rem);
font-weight: 800;
line-height: 1.05;
}
.stage-metric__hint {
margin: var(--onyx-density-2xs) 0 0;
color: var(--onyx-color-text-icons-neutral-soft);
font-size: 0.75rem;
}
.stage-grid {
display: grid;
grid-template-columns: minmax(0, 1.65fr) minmax(16rem, 1fr);
gap: var(--onyx-density-lg);
align-items: start;
}
.stage-panel {
min-width: 0;
padding: clamp(1rem, 2vw, 1.75rem);
border: 1px solid var(--onyx-color-base-neutral-300);
border-radius: var(--onyx-radius-component-container-soft);
background: var(--onyx-color-base-neutral-100);
}
.stage-panel--aside {
background: var(--onyx-color-base-neutral-200);
}
.stage-panel__head {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--onyx-density-xs);
}
.stage-panel__head h2 {
margin: 0;
}
.stage-decision {
margin: var(--onyx-density-md) 0 0;
font-size: clamp(1.1rem, 2vw, 1.5rem);
line-height: 1.35;
}
.stage-why {
display: flex;
gap: var(--onyx-density-xs);
align-items: flex-start;
margin: var(--onyx-density-sm) 0 0;
color: var(--onyx-color-text-icons-neutral-medium);
}
.stage-actions {
margin-top: var(--onyx-density-lg);
}
.stage-phone {
display: flex;
justify-content: center;
margin-block: var(--onyx-density-md);
}
.stage-phone__screen {
width: min(15rem, 100%);
padding: var(--onyx-density-md);
border: 6px solid #1e293b;
border-radius: 1.5rem;
background: #fff;
box-shadow: var(--onyx-shadow-soft-bottom);
}
.stage-phone__kicker {
display: flex;
align-items: center;
gap: 0.25rem;
margin: 0;
color: var(--onyx-color-text-icons-primary-intense);
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.08em;
}
.stage-phone__value {
margin: 0.35rem 0 0;
font-size: 2.2rem;
font-weight: 800;
line-height: 1;
}
.stage-phone__label {
margin: 0.25rem 0 0;
font-size: 0.85rem;
}
.stage-phone__scenario {
margin: 0.75rem 0 0;
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.72rem;
}
.stage-footer {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: var(--onyx-density-sm);
padding-top: var(--onyx-density-sm);
border-top: 1px solid var(--onyx-color-base-neutral-300);
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.75rem;
line-height: 1.45;
}
.stage-footer span {
max-width: 75ch;
}
.spin-slow {
animation: spin 1.4s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.spin-slow {
animation: none;
}
}
@media (max-width: 1100px) {
.stage-metrics {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (max-width: 900px) {
.stage-hero,
.stage-grid {
grid-template-columns: minmax(0, 1fr);
}
.stage-qr {
align-items: flex-start;
text-align: left;
}
.stage-qr__frame img {
width: min(180px, 50vw);
}
}
@media (max-width: 576px) {
.stage-metrics {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.stage-headline {
font-size: clamp(1.8rem, 8vw, 2.6rem);
}
.stage-footnote {
display: none;
}
}
</style>
+27
View File
@@ -0,0 +1,27 @@
interface ApiErrorLike {
status?: number
statusCode?: number
statusMessage?: string
message?: string
data?: {
error?: { message?: string; code?: string }
message?: string
}
}
/** Human-readable message from a Nuxt/$fetch error, without leaking tokens. */
export function apiErrorMessage(error: unknown, fallback: string): string {
const value = error as ApiErrorLike | undefined
return (
value?.data?.error?.message ??
value?.data?.message ??
value?.statusMessage ??
value?.message ??
fallback
)
}
export function apiErrorStatus(error: unknown): number | undefined {
const value = error as ApiErrorLike | undefined
return value?.status ?? value?.statusCode
}
+325
View File
@@ -13,9 +13,11 @@
"chart.js": "4.6.1",
"maplibre-gl": "6.18.0",
"nuxt": "4.6.4",
"qrcode": "1.5.4",
"sit-onyx": "1.22.0"
},
"devDependencies": {
"@types/qrcode": "1.5.5",
"typescript": "5.9.3",
"vitest": "3.2.4"
}
@@ -2669,6 +2671,26 @@
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"license": "MIT"
},
"node_modules/@types/node": {
"version": "26.6.6",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
"integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/qrcode": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.5.tgz",
"integrity": "sha512-CdfBi/e3Qk+3Z/fXYShipBT13OJ2fDO2Q2w5CIP5anLTLIndQG9z6P1cnm+8zCWSpm5dnxMFd/uREtb0EXuQzg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/resolve": {
"version": "1.20.2",
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
@@ -3835,6 +3857,15 @@
"node": ">=20.19.0"
}
},
"node_modules/camelcase": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/caniuse-api": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-4.0.0.tgz",
@@ -3983,6 +4014,24 @@
"node": ">=0.10.0"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
"node_modules/commander": {
"version": "2.20.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
@@ -4230,6 +4279,15 @@
}
}
},
"node_modules/decamelize": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/deep-eql": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
@@ -4346,6 +4404,12 @@
"node": ">=0.3.1"
}
},
"node_modules/dijkstrajs": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
"license": "MIT"
},
"node_modules/dot-prop": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-10.2.0.tgz",
@@ -4718,6 +4782,19 @@
"node": ">=8"
}
},
"node_modules/find-up": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
"integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
"license": "MIT",
"dependencies": {
"locate-path": "^5.0.0",
"path-exists": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/flru": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz",
@@ -5186,6 +5263,15 @@
"node": ">=0.10.0"
}
},
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/is-glob": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
@@ -5795,6 +5881,18 @@
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/locate-path": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
"integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
"license": "MIT",
"dependencies": {
"p-locate": "^4.1.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/loupe": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
@@ -6684,6 +6782,42 @@
}
}
},
"node_modules/p-limit": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
"integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
"license": "MIT",
"dependencies": {
"p-try": "^2.0.0"
},
"engines": {
"node": ">=6"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/p-locate": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
"integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
"license": "MIT",
"dependencies": {
"p-limit": "^2.2.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/p-try": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/package-manager-detector": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.9.0.tgz",
@@ -6699,6 +6833,15 @@
"node": ">= 0.8"
}
},
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
@@ -6802,6 +6945,15 @@
"pathe": "^2.0.3"
}
},
"node_modules/pngjs": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
"integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
"license": "MIT",
"engines": {
"node": ">=10.13.0"
}
},
"node_modules/postcss": {
"version": "8.5.33",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
@@ -6919,6 +7071,145 @@
"integrity": "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==",
"license": "MIT"
},
"node_modules/qrcode": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
"integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
"license": "MIT",
"dependencies": {
"dijkstrajs": "^1.0.1",
"pngjs": "^5.0.0",
"yargs": "^15.3.1"
},
"bin": {
"qrcode": "bin/qrcode"
},
"engines": {
"node": ">=10.13.0"
}
},
"node_modules/qrcode/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/qrcode/node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/qrcode/node_modules/cliui": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
"integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
"license": "ISC",
"dependencies": {
"string-width": "^4.2.0",
"strip-ansi": "^6.0.0",
"wrap-ansi": "^6.2.0"
}
},
"node_modules/qrcode/node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"license": "MIT"
},
"node_modules/qrcode/node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/qrcode/node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/qrcode/node_modules/wrap-ansi": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
"integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/qrcode/node_modules/y18n": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
"license": "ISC"
},
"node_modules/qrcode/node_modules/yargs": {
"version": "15.4.1",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
"integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
"license": "MIT",
"dependencies": {
"cliui": "^6.0.0",
"decamelize": "^1.2.0",
"find-up": "^4.1.0",
"get-caller-file": "^2.0.1",
"require-directory": "^2.1.1",
"require-main-filename": "^2.0.0",
"set-blocking": "^2.0.0",
"string-width": "^4.2.0",
"which-module": "^2.0.0",
"y18n": "^4.0.0",
"yargs-parser": "^18.1.2"
},
"engines": {
"node": ">=8"
}
},
"node_modules/qrcode/node_modules/yargs-parser": {
"version": "18.1.3",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
"integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
"license": "ISC",
"dependencies": {
"camelcase": "^5.0.0",
"decamelize": "^1.2.0"
},
"engines": {
"node": ">=6"
}
},
"node_modules/quansync": {
"version": "0.2.11",
"resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz",
@@ -7070,6 +7361,15 @@
"node": ">=4"
}
},
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
@@ -7079,6 +7379,12 @@
"node": ">=0.10.0"
}
},
"node_modules/require-main-filename": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
"license": "ISC"
},
"node_modules/resolve": {
"version": "1.22.14",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.14.tgz",
@@ -7429,6 +7735,12 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/set-blocking": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
"license": "ISC"
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
@@ -8031,6 +8343,13 @@
"node": ">=22.19.0"
}
},
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"devOptional": true,
"license": "MIT"
},
"node_modules/unenv": {
"version": "2.0.0-rc.25",
"resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.25.tgz",
@@ -9170,6 +9489,12 @@
"node": "^20.17.0 || >=22.9.0"
}
},
"node_modules/which-module": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
"license": "ISC"
},
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+4 -1
View File
@@ -8,7 +8,8 @@
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"test": "vitest run",
"mock": "node scripts/generate-mock.mjs"
"mock": "node scripts/generate-mock.mjs",
"smoke:live": "node scripts/smoke-live.mjs"
},
"dependencies": {
"@sit-onyx/chartjs-plugin": "1.0.1",
@@ -17,9 +18,11 @@
"chart.js": "4.6.1",
"maplibre-gl": "6.18.0",
"nuxt": "4.6.4",
"qrcode": "1.5.4",
"sit-onyx": "1.22.0"
},
"devDependencies": {
"@types/qrcode": "1.5.5",
"typescript": "5.9.3",
"vitest": "3.2.4"
}
+387
View File
@@ -0,0 +1,387 @@
#!/usr/bin/env node
/**
* End-to-end live smoke test.
*
* Prerequisites (read-only use of the Go/ML worktrees):
* - Go API on http://127.0.0.1:18080 with CONTROL_USER/CONTROL_PASS
* - FastAPI ML on http://127.0.0.1:18000 (so Go can answer /api/readyz)
* - Built Nuxt server on http://127.0.0.1:13000 with
* NUXT_API_INTERNAL_BASE=http://127.0.0.1:18080
* CONTROL_USER=control CONTROL_PASS=secret
*
* What it proves: the presenter POST reaches Go through Nitro, a `scenario`
* SSE event arrives through the Nitro stream proxy, and the staffing/forecast
* APIs return the new scenario. It also checks /stage, /live, the QR route and
* the control-auth boundary.
*/
import assert from 'node:assert/strict'
const WEB_URL = (process.env.WEB_URL ?? 'http://127.0.0.1:13000').replace(/\/+$/, '')
const CONTROL_USER = process.env.CONTROL_USER ?? 'control'
const CONTROL_PASS = process.env.CONTROL_PASS ?? 'secret'
const SENSOR = process.env.SENSOR ?? 'hn-stadtgalerie-01'
const SSE_TIMEOUT_MS = Number(process.env.SSE_TIMEOUT_MS ?? 8000)
const EXPECT_HEARTBEAT = process.env.EXPECT_HEARTBEAT === '1'
const verbose = process.env.VERBOSE === '1'
const AUTHORIZATION = `Basic ${Buffer.from(`${CONTROL_USER}:${CONTROL_PASS}`).toString('base64')}`
function url(path) {
return new URL(path, `${WEB_URL}/`).toString()
}
function log(message) {
console.log(` ${message}`)
}
function pass(message) {
console.log(`PASS ${message}`)
}
function fail(message) {
console.error(`FAIL ${message}`)
}
async function fetchText(path, options = {}) {
const response = await fetch(url(path), options)
const text = await response.text()
if (verbose) log(`${options.method ?? 'GET'} ${path} -> ${response.status}`)
return { response, text }
}
async function fetchJson(path, options = {}) {
const { response, text } = await fetchText(path, {
...options,
headers: { accept: 'application/json', ...(options.headers ?? {}) },
})
let body
try {
body = JSON.parse(text)
} catch {
throw new Error(`${path} returned non-JSON (${response.status}): ${text.slice(0, 200)}`)
}
return { response, body }
}
async function expectJson(path, options, status = 200) {
const { response, body } = await fetchJson(path, options)
assert.equal(response.status, status, `${path} status ${response.status}, expected ${status}: ${JSON.stringify(body)}`)
return body
}
function parseFrame(frame) {
let name = 'message'
let id = ''
let retry = ''
const data = []
for (const line of frame.split('\n')) {
if (!line || line.startsWith(':')) continue
const separator = line.indexOf(':')
const field = separator < 0 ? line : line.slice(0, separator)
const value = separator < 0 ? '' : line.slice(separator + 1).replace(/^ /, '')
if (field === 'event') name = value
else if (field === 'id') id = value
else if (field === 'data') data.push(value)
else if (field === 'retry') retry = value
}
if (!data.length && name === 'message' && !retry) return null
return { name: data.length || name !== 'message' ? name : 'retry', id, retry, data: data.join('\n') }
}
/** Minimal incremental SSE reader over fetch (Node has no EventSource). */
function openSse(path) {
const controller = new AbortController()
const events = []
const waiters = new Set()
let raw = ''
let buffer = ''
let finished = false
const notify = () => {
for (const waiter of [...waiters]) waiter()
}
const consume = () => {
while (true) {
const match = buffer.match(/\r?\n\r?\n/)
if (!match || match.index === undefined) break
const frame = buffer.slice(0, match.index)
buffer = buffer.slice(match.index + match[0].length)
const event = parseFrame(frame)
if (event) {
events.push(event)
notify()
}
}
}
const responsePromise = fetch(url(path), {
headers: { accept: 'text/event-stream' },
signal: controller.signal,
}).then(async (response) => {
assert.equal(response.status, 200, `SSE status ${response.status}`)
const contentType = response.headers.get('content-type') ?? ''
assert.match(contentType, /text\/event-stream/, `SSE content-type: ${contentType}`)
const reader = response.body.getReader()
const decoder = new TextDecoder()
;(async () => {
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
const chunk = decoder.decode(value, { stream: true })
raw += chunk
buffer += chunk.replace(/\r\n/g, '\n')
consume()
}
} catch (error) {
if (error?.name !== 'AbortError') throw error
} finally {
finished = true
notify()
}
})()
return response
})
function waitFor(predicate, timeoutMs, label) {
const existing = events.find(predicate)
if (existing) return Promise.resolve(existing)
if (finished) return Promise.reject(new Error(`SSE closed before ${label}`))
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
waiters.delete(check)
reject(new Error(`Timed out after ${timeoutMs} ms waiting for ${label}`))
}, timeoutMs)
const check = () => {
const match = events.find(predicate)
if (!match) return
clearTimeout(timer)
waiters.delete(check)
resolve(match)
}
waiters.add(check)
})
}
return {
responsePromise,
waitFor,
get raw() {
return raw
},
close() {
controller.abort()
},
}
}
function decisionShape(plan) {
return JSON.stringify({
scenario: plan.scenario,
summary: plan.summary,
footfall: plan.hours.map((hour) => [hour.t, hour.footfall, hour.required_staff, hour.scheduled_staff]),
})
}
async function main() {
console.log(`PulseCast live smoke test -> ${WEB_URL}`)
const health = await expectJson('/api/healthz')
assert.equal(health.ok, true, 'healthz.ok')
pass('Nitro health endpoint')
const ready = await expectJson('/api/readyz')
assert.equal(ready.ok, true, 'readyz.ok')
assert.equal(ready.data, true, 'readyz.data (Go bootstrap snapshot)')
assert.equal(ready.model, true, 'readyz.model (FastAPI)')
pass('Go API ready with ML snapshot')
const initial = await expectJson('/api/scenario')
assert.equal(typeof initial.version, 'number', 'scenario.version')
assert.ok(initial.scenario?.scenario, 'scenario.scenario')
pass(`scenario state v${initial.version} (${initial.scenario.scenario})`)
const basePlan = await expectJson(
`/api/staffing?sensor=${encodeURIComponent(SENSOR)}&scenario=base&standard=standard`,
)
assert.equal(basePlan.sensor, SENSOR)
assert.equal(basePlan.scenario, 'base')
assert.ok(basePlan.hours.length > 0, 'base plan has open hours')
assert.ok(basePlan.shifts.length > 0, 'base plan has shift blocks')
pass(`base plan: ${basePlan.hours.length} hours, ${basePlan.shifts.length} shifts`)
const baseForecast = await expectJson(
`/api/forecast?sensor=${encodeURIComponent(SENSOR)}&horizon=7d&scenario=base`,
)
assert.ok(baseForecast.points.length > 0, 'base forecast has points')
pass(`base forecast: ${baseForecast.points.length} hourly points`)
const unauthenticated = await fetchJson('/api/scenario', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ scenario: 'rainy-saturday' }),
})
assert.equal(unauthenticated.response.status, 401, 'POST without presenter auth must be 401')
pass('unauthenticated scenario POST is rejected')
const controlPage = await fetchText('/control')
assert.equal(controlPage.response.status, 401, '/control without auth must be 401')
assert.match(controlPage.response.headers.get('www-authenticate') ?? '', /Basic/i)
pass('/control is presenter-protected')
const controlAuthed = await fetchText('/control', { headers: { authorization: AUTHORIZATION } })
assert.equal(controlAuthed.response.status, 200, '/control with auth')
assert.match(controlAuthed.text, /Presenter control/i)
pass('/control authenticates and renders')
for (const [path, needle] of [
['/stage', 'Scan for the phone view'],
['/live', 'The plan on your phone'],
]) {
const page = await fetchText(path)
assert.equal(page.response.status, 200, `${path} status`)
assert.match(page.response.headers.get('content-type') ?? '', /text\/html/i, `${path} content-type`)
assert.ok(page.text.includes(needle), `${path} contains "${needle}"`)
assert.ok(page.text.includes('PulseCast'), `${path} contains the app shell`)
pass(`${path} renders server-side`)
}
const qr = await fetchText(`/api/qr?text=${encodeURIComponent(`${WEB_URL}/live`)}`)
assert.equal(qr.response.status, 200, 'QR status')
assert.match(qr.response.headers.get('content-type') ?? '', /image\/svg\+xml/i, 'QR content-type')
assert.match(qr.text, /<svg/i, 'QR is SVG')
pass('QR route returns SVG locally')
const sse = openSse('/api/stream')
try {
await sse.responsePromise
const initialEvent = await sse.waitFor(
(event) => event.name === 'scenario' || event.name === 'retry',
5000,
'the initial SSE frame',
)
assert.ok(initialEvent, 'initial SSE frame')
if (EXPECT_HEARTBEAT) {
await sse.waitFor((event) => event.name === 'ping', SSE_TIMEOUT_MS, 'a heartbeat ping')
pass('SSE heartbeat observed')
}
assert.match(sse.raw, /retry:\s*3000/, 'SSE retry hint')
const initialScenarioEvent = await sse.waitFor(
(event) => event.name === 'scenario',
5000,
'the initial scenario event',
)
const initialPayload = JSON.parse(initialScenarioEvent.data)
assert.equal(typeof initialPayload.version, 'number', 'SSE initial version')
pass(`SSE connected: retry:3000, initial scenario v${initialPayload.version}`)
const target = initialPayload.scenario === 'rainy-saturday' ? 'sunny-saturday-market' : 'rainy-saturday'
const body =
target === 'sunny-saturday-market'
? {
scenario: target,
weather: { temp_delta_c: 4, precip_mm: 0 },
event: { type: 'market', uplift: 0.2 },
}
: {
scenario: target,
weather: { temp_delta_c: -2, precip_mm: 3.2 },
}
const started = performance.now()
const posted = await expectJson('/api/scenario', {
method: 'POST',
headers: { authorization: AUTHORIZATION, 'content-type': 'application/json' },
body: JSON.stringify(body),
})
assert.equal(posted.scenario.scenario, target, 'POST response scenario')
const postMs = performance.now() - started
const event = await sse.waitFor(
(candidate) => {
if (candidate.name !== 'scenario') return false
try {
const payload = JSON.parse(candidate.data)
return payload.version >= posted.version && payload.scenario?.scenario === target
} catch {
return false
}
},
5000,
`a scenario SSE event for ${target}`,
)
const elapsed = performance.now() - started
const payload = JSON.parse(event.data)
assert.equal(payload.scenario.scenario, target, 'SSE scenario id')
assert.equal(event.id, String(payload.version), 'SSE id equals the scenario version')
assert.ok(elapsed < 5000, `scenario event took ${elapsed.toFixed(0)} ms (max 5000)`)
if (elapsed >= 2000) {
console.warn(`WARN scenario propagated in ${elapsed.toFixed(0)} ms; contract target is <2000 ms`)
}
pass(`scenario POST -> SSE event in ${elapsed.toFixed(0)} ms (POST ${postMs.toFixed(0)} ms)`)
const polled = await expectJson('/api/scenario')
assert.equal(polled.version, posted.version, 'GET /api/scenario polling version')
assert.equal(polled.scenario.scenario, target, 'GET /api/scenario polling scenario')
pass(`polling fallback reads v${polled.version} (${target})`)
const targetPlan = await expectJson(
`/api/staffing?sensor=${encodeURIComponent(SENSOR)}&scenario=${target}&standard=standard`,
)
assert.equal(targetPlan.scenario, target, 'target plan scenario')
assert.ok(targetPlan.hours.length > 0, 'target plan has hours')
assert.notEqual(
decisionShape(targetPlan),
decisionShape(basePlan),
`${target} plan must differ from base`,
)
if (targetPlan.cached) {
console.warn('WARN Go served a cached plan; ML was not used for this request')
} else {
pass('target plan is live and differs from base')
}
const targetForecast = await expectJson(
`/api/forecast?sensor=${encodeURIComponent(SENSOR)}&horizon=7d&scenario=${target}`,
)
assert.equal(targetForecast.scenario, target, 'target forecast scenario')
assert.ok(targetForecast.points.length > 0, 'target forecast has points')
assert.notEqual(
JSON.stringify(targetForecast.points),
JSON.stringify(baseForecast.points),
`${target} forecast must differ from base`,
)
pass('target forecast is live and differs from base')
const stageAfter = await fetchText('/stage')
assert.equal(stageAfter.response.status, 200, 'stage after scenario')
const expectedLabel = target === 'rainy-saturday' ? 'Rainy Saturday' : 'Sunny Saturday'
assert.ok(stageAfter.text.includes(expectedLabel), `stage renders ${expectedLabel}`)
pass(`/stage server-renders the new scenario (${expectedLabel})`)
const liveAfter = await fetchText('/live')
assert.equal(liveAfter.response.status, 200, 'live after scenario')
assert.ok(liveAfter.text.includes(expectedLabel), `live renders ${expectedLabel}`)
pass(`/live server-renders the new scenario (${expectedLabel})`)
// Leave the demo in the base state so the next run is deterministic.
const restored = await expectJson('/api/scenario', {
method: 'POST',
headers: { authorization: AUTHORIZATION, 'content-type': 'application/json' },
body: JSON.stringify({ scenario: 'base', weather: { temp_delta_c: 0, precip_mm: 0 } }),
})
assert.equal(restored.scenario.scenario, 'base')
pass(`restored base (v${restored.version})`)
} finally {
sse.close()
}
console.log('\nAll live smoke checks passed.')
}
main().catch((error) => {
fail(error?.stack ?? String(error))
process.exitCode = 1
})
+35
View File
@@ -0,0 +1,35 @@
import QRCode from 'qrcode'
/**
* Generate the /stage QR code locally. No third-party QR image service is
* called at runtime, so the big screen keeps working without internet access.
*/
export default defineEventHandler(async (event) => {
const query = getQuery(event)
const text = typeof query.text === 'string' ? query.text.trim() : ''
if (!text) {
throw createError({ statusCode: 400, statusMessage: 'text is required' })
}
if (text.length > 1024) {
throw createError({ statusCode: 400, statusMessage: 'text is too long for a QR code' })
}
let svg: string
try {
svg = await QRCode.toString(text, {
type: 'svg',
margin: 1,
width: 320,
errorCorrectionLevel: 'M',
color: { dark: '#0f172a', light: '#ffffff' },
})
} catch {
throw createError({ statusCode: 400, statusMessage: 'could not encode text as a QR code' })
}
setResponseHeaders(event, {
'content-type': 'image/svg+xml; charset=utf-8',
'cache-control': 'public, max-age=300',
})
return svg
})
+2 -2
View File
@@ -1,8 +1,8 @@
import type { ScenarioState } from '../../shared/types'
import { apiRequest, isMockMode } from '../utils/api'
import { mockScenario } from '../utils/mock-data'
import { getMockScenario } from '../utils/mock-scenario'
export default defineEventHandler(async () => {
if (isMockMode()) return mockScenario
if (isMockMode()) return getMockScenario()
return apiRequest<ScenarioState>('/api/scenario')
})
+2 -9
View File
@@ -1,9 +1,7 @@
import { SCENARIOS } from '../../shared/types'
import type { Scenario, ScenarioDefinition, ScenarioState } from '../../shared/types'
import { apiRequest, isMockMode } from '../utils/api'
import { mockScenario } from '../utils/mock-data'
let version = mockScenario.version
import { setMockScenario } from '../utils/mock-scenario'
export default defineEventHandler(async (event) => {
const body = await readBody<ScenarioDefinition>(event)
@@ -16,12 +14,7 @@ export default defineEventHandler(async (event) => {
}
if (isMockMode()) {
version += 1
return {
version,
scenario: body,
at: new Date().toISOString(),
}
return setMockScenario(body)
}
// Control credentials are attached in the server process, never in the
+24
View File
@@ -0,0 +1,24 @@
import { apiBaseUrl, isMockMode } from '../utils/api'
/**
* Same-origin SSE proxy. The browser never talks to Go directly, so the
* Cloudflare/K8s CORS surface stays closed and the stream can be cached or
* authenticated at one edge only.
*
* h3's proxyRequest pipes response chunks as they arrive (it does not await
* the full body), which preserves the 15 s heartbeat and `retry: 3000`.
*/
export default defineEventHandler(async (event) => {
if (isMockMode() || process.env.NUXT_DISABLE_SSE === '1') {
// Failure drill: make the client prove the 5 s polling fallback. Mock mode
// has no upstream stream either, so both paths fail fast and visibly.
throw createError({
statusCode: 503,
statusMessage: 'SSE is disabled; the scenario polling fallback is active.',
})
}
return proxyRequest(event, `${apiBaseUrl()}/api/stream`, {
headers: { accept: 'text/event-stream' },
})
})
+101
View File
@@ -0,0 +1,101 @@
import { createHash, createHmac, timingSafeEqual } from 'node:crypto'
import { isMockMode } from '../utils/api'
const COOKIE_NAME = 'pulsecast_control'
const COOKIE_CONTEXT = 'pulsecast-control-v1'
function digest(value: string): Buffer {
return createHash('sha256').update(value).digest()
}
/** Constant-time compare that works for unequal-length strings. */
function safeEqual(a: string, b: string): boolean {
return timingSafeEqual(digest(a), digest(b))
}
function expectedCookie(pass: string): string {
return createHmac('sha256', pass).update(COOKIE_CONTEXT).digest('base64url')
}
function basicCredentials(event: import('h3').H3Event): { user: string; pass: string } | null {
const header = getHeader(event, 'authorization') ?? ''
if (!header.startsWith('Basic ')) return null
let decoded: string
try {
decoded = Buffer.from(header.slice('Basic '.length), 'base64').toString('utf8')
} catch {
return null
}
const separator = decoded.indexOf(':')
if (separator < 0) return null
return { user: decoded.slice(0, separator), pass: decoded.slice(separator + 1) }
}
function isProtected(event: import('h3').H3Event): boolean {
const path = getRequestURL(event).pathname.replace(/\/+$/, '') || '/'
if (path === '/control') return true
if (path === '/api/scenario' && getMethod(event) === 'POST') return true
return false
}
/**
* Presenter-only control surface. Basic auth is checked in Nitro; on success
* an HMAC cookie (signed with CONTROL_PASS) lets the page POST /api/scenario
* without re-prompting. The browser never receives the Go credentials, and
* /stage, /live and all public GETs stay open.
*/
export default defineEventHandler((event) => {
if (!isProtected(event)) return
if (isMockMode()) return
const user = process.env.CONTROL_USER ?? process.env.NUXT_CONTROL_USER ?? ''
const pass = process.env.CONTROL_PASS ?? process.env.NUXT_CONTROL_PASS ?? ''
const isApi = getRequestURL(event).pathname.startsWith('/api/')
setResponseHeader(event, 'cache-control', 'no-store')
if (!user || !pass) {
setResponseStatus(event, 503)
if (isApi) {
setResponseHeader(event, 'content-type', 'application/json; charset=utf-8')
return {
error: {
code: 'control_auth_unconfigured',
message: 'CONTROL_USER and CONTROL_PASS are not configured in the web server.',
},
}
}
setResponseHeader(event, 'content-type', 'text/plain; charset=utf-8')
return 'Control credentials are not configured. Set CONTROL_USER and CONTROL_PASS on the web server.'
}
const expected = expectedCookie(pass)
const cookie = getCookie(event, COOKIE_NAME)
const cookieValid = Boolean(cookie && safeEqual(cookie, expected))
let basicValid = false
const basic = basicCredentials(event)
if (basic && safeEqual(basic.user, user) && safeEqual(basic.pass, pass)) {
basicValid = true
const forwardedProto = (getHeader(event, 'x-forwarded-proto') ?? '').split(',')[0]?.trim()
setCookie(event, COOKIE_NAME, expected, {
httpOnly: true,
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 8,
secure: (forwardedProto || getRequestProtocol(event)) === 'https',
})
}
if (cookieValid || basicValid) return
setResponseStatus(event, 401)
setResponseHeader(event, 'www-authenticate', 'Basic realm="PulseCast presenter"')
if (isApi) {
setResponseHeader(event, 'content-type', 'application/json; charset=utf-8')
return {
error: { code: 'unauthorized', message: 'Presenter credentials are required to change the scenario.' },
}
}
setResponseHeader(event, 'content-type', 'text/plain; charset=utf-8')
return 'Authentication required.'
})
+24
View File
@@ -0,0 +1,24 @@
import type { ScenarioDefinition, ScenarioState } from '../../shared/types'
import { mockScenario } from './mock-data'
// Mock mode has no Go process, but the presenter controls and the 5 s polling
// fallback should still observe a version change. Nitro keeps this per-process
// state, exactly like the single Go pod keeps its in-memory scenario.
let current: ScenarioState = clone(mockScenario)
function clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T
}
export function getMockScenario(): ScenarioState {
return clone(current)
}
export function setMockScenario(input: ScenarioDefinition): ScenarioState {
current = {
version: current.version + 1,
scenario: clone(input),
at: new Date().toISOString(),
}
return clone(current)
}
+101
View File
@@ -0,0 +1,101 @@
import { SCENARIOS } from './types'
import type { Scenario, ScenarioState } from './types'
/** Client connection modes shown on /stage, /live and /plan. */
export type LiveConnection = 'connecting' | 'live' | 'polling' | 'offline'
/** Poll the public scenario endpoint every 5 s while SSE is unavailable. */
export const SCENARIO_POLL_MS = 5000
/** Two consecutive SSE errors are enough to start the polling fallback. */
export const SSE_FAILURES_BEFORE_POLLING = 2
/** The Go hub pings every 15 s; two missed pings mean the stream is buffered. */
export const SSE_STALE_MS = 32000
export const LIVE_LABELS: Record<LiveConnection, string> = {
connecting: 'Connecting',
live: 'Live',
polling: 'Polling',
offline: 'Offline',
}
export const LIVE_COLORS: Record<LiveConnection, 'neutral' | 'success' | 'warning' | 'danger'> = {
connecting: 'neutral',
live: 'success',
polling: 'warning',
offline: 'danger',
}
export interface LiveStatusInput {
online: boolean
sseOpen: boolean
sseFailures: number
polling: boolean
pollFailures: number
}
/**
* Resolve the visible connection state. Live means an open SSE stream,
* Polling means the 5 s fallback is working, Offline means neither path works.
*/
export function liveStatus(input: LiveStatusInput): LiveConnection {
if (!input.online) return 'offline'
if (input.sseOpen) return 'live'
if (input.polling) return input.pollFailures > 0 ? 'offline' : 'polling'
if (input.sseFailures >= SSE_FAILURES_BEFORE_POLLING) {
return input.pollFailures > 0 ? 'offline' : 'polling'
}
return 'connecting'
}
/** Parse and validate one `event: scenario` payload from Go /api/stream. */
export function parseScenarioEvent(raw: string): ScenarioState | null {
let value: unknown
try {
value = JSON.parse(raw)
} catch {
return null
}
if (!value || typeof value !== 'object') return null
const candidate = value as Partial<ScenarioState>
if (typeof candidate.version !== 'number' || !Number.isFinite(candidate.version)) return null
if (typeof candidate.at !== 'string' || !candidate.at) return null
if (!candidate.scenario || typeof candidate.scenario !== 'object') return null
const scenario = candidate.scenario as { scenario?: unknown }
if (typeof scenario.scenario !== 'string') return null
if (!SCENARIOS.includes(scenario.scenario as Scenario)) return null
return candidate as ScenarioState
}
/** A new server version, or a changed scenario id, is a reason to refetch. */
export function scenarioChanged(
previous: ScenarioState | null | undefined,
next: ScenarioState,
): boolean {
if (!previous) return true
return previous.version !== next.version || previous.scenario.scenario !== next.scenario.scenario
}
export function scenarioLabel(scenario: Scenario | string | undefined): string {
switch (scenario) {
case 'sunny-saturday-market':
return 'Sunny Saturday + market'
case 'rainy-saturday':
return 'Rainy Saturday'
case 'weekday-event':
return 'Wednesday evening event'
default:
return 'Base week'
}
}
/** Small, dependency-free age label for the last SSE/poll event. */
export function liveAge(lastEventAt: string, now = Date.now()): string {
if (!lastEventAt) return 'no event yet'
const time = Date.parse(lastEventAt)
if (Number.isNaN(time)) return 'no event yet'
const seconds = Math.max(0, Math.round((now - time) / 1000))
if (seconds < 5) return 'just now'
if (seconds < 60) return `${seconds}s ago`
const minutes = Math.round(seconds / 60)
return `${minutes} min ago`
}
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, it } from 'vitest'
import {
liveAge,
liveStatus,
parseScenarioEvent,
scenarioChanged,
scenarioLabel,
SSE_FAILURES_BEFORE_POLLING,
} from '../shared/live'
import type { ScenarioState } from '../shared/types'
const state = (version: number, scenario: ScenarioState['scenario']['scenario'] = 'base'): ScenarioState => ({
version,
scenario: { scenario },
at: '2026-11-14T09:12:00Z',
})
describe('parseScenarioEvent', () => {
it('accepts the Go /api/stream scenario shape', () => {
expect(parseScenarioEvent(JSON.stringify(state(7, 'rainy-saturday')))).toEqual(
state(7, 'rainy-saturday'),
)
})
it('rejects malformed JSON, missing versions and unknown scenarios', () => {
expect(parseScenarioEvent('{')).toBeNull()
expect(parseScenarioEvent(JSON.stringify({ scenario: { scenario: 'base' }, at: 'x' }))).toBeNull()
expect(
parseScenarioEvent(JSON.stringify({ version: 1, at: 'x', scenario: { scenario: 'party' } })),
).toBeNull()
})
})
describe('scenarioChanged', () => {
it('refreshes on a new version or a new scenario id', () => {
expect(scenarioChanged(null, state(1))).toBe(true)
expect(scenarioChanged(state(1), state(1))).toBe(false)
expect(scenarioChanged(state(1), state(2))).toBe(true)
expect(scenarioChanged(state(1, 'base'), state(1, 'rainy-saturday'))).toBe(true)
})
})
describe('liveStatus', () => {
const base = {
online: true,
sseOpen: false,
sseFailures: 0,
polling: false,
pollFailures: 0,
}
it('shows connecting before the first event and live once SSE opens', () => {
expect(liveStatus(base)).toBe('connecting')
expect(liveStatus({ ...base, sseOpen: true })).toBe('live')
})
it('switches to polling after repeated SSE failures', () => {
expect(
liveStatus({
...base,
sseFailures: SSE_FAILURES_BEFORE_POLLING,
polling: true,
}),
).toBe('polling')
})
it('reports offline when the browser or both transports are down', () => {
expect(liveStatus({ ...base, online: false, sseOpen: true })).toBe('offline')
expect(
liveStatus({
...base,
sseFailures: SSE_FAILURES_BEFORE_POLLING,
polling: true,
pollFailures: 1,
}),
).toBe('offline')
})
})
describe('scenarioLabel and liveAge', () => {
it('labels every contract enum', () => {
expect(scenarioLabel('sunny-saturday-market')).toBe('Sunny Saturday + market')
expect(scenarioLabel('rainy-saturday')).toBe('Rainy Saturday')
expect(scenarioLabel('weekday-event')).toBe('Wednesday evening event')
expect(scenarioLabel('base')).toBe('Base week')
expect(scenarioLabel('unknown')).toBe('Base week')
})
it('renders a short age without a date library', () => {
const now = Date.parse('2026-11-14T09:12:10Z')
expect(liveAge('', now)).toBe('no event yet')
expect(liveAge('2026-11-14T09:12:08Z', now)).toBe('just now')
expect(liveAge('2026-11-14T09:11:40Z', now)).toBe('30s ago')
expect(liveAge('2026-11-14T09:07:10Z', now)).toBe('5 min ago')
})
})