feat: wire Nitro API to Go, real staffing plan and train proxy

- Replace mock Nitro routes with server-side proxies to the Go API
- /plan reads Go /api/staffing; local assumption edits are a labeled preview
- /simulate reads base and scenario staffing from Go instead of local multipliers
- Route train upload and scenario POST through Nitro with server-only credentials
- Keep NUXT_PUBLIC_USE_MOCK=1 as an explicit dev fallback only
- Match Go's global-peak flat schedule and add a captured Go parity fixture
- Run the web runtime as numeric UID/GID 10001:10001
- Add make check, Gitea CI workflow and a proxy smoke script
This commit is contained in:
Noel Sabia committed 2026-11-14 06:13:00 +01:00
1 parent e8d141ca43
commit b33e6ff001
33 files changed
+1147 -317

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
name: ci
on:
push:
pull_request:
permissions:
contents: read
jobs:
check:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Check out
uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Check
run: make check
+11 -3
View File
@@ -1,5 +1,6 @@
# Multi-stage production build for the Nuxt SSR server.
# The runtime image runs as the unprivileged `node` user.
# The runtime image runs as numeric UID/GID 10001:10001 so Kubernetes can
# verify runAsNonRoot without a named user lookup.
FROM node:22-alpine AS build
WORKDIR /app
@@ -16,10 +17,17 @@ WORKDIR /app
ENV NODE_ENV=production
ENV HOST=0.0.0.0
ENV PORT=3000
ENV HOME=/tmp
ENV NITRO_TEMP_DIR=/tmp
COPY --from=build --chown=node:node /app/.output ./.output
# Create a numeric runtime identity. Keep the literal numbers in USER/COPY:
# the kubelet cannot resolve names such as "app" reliably.
RUN addgroup -g 10001 -S app \
&& adduser -u 10001 -S app -G app
USER node
COPY --from=build --chown=10001:10001 /app/.output ./.output
USER 10001:10001
EXPOSE 3000
CMD ["node", ".output/server/index.mjs"]
+28
View File
@@ -0,0 +1,28 @@
NPM ?= npm
.PHONY: install dev build test check preview docker-build smoke
install:
$(NPM) ci
dev:
$(NPM) run dev
build:
$(NPM) run build
test:
$(NPM) test
# Local equivalent of .gitea/workflows/ci.yml.
check: install build test
preview:
$(NPM) run preview
docker-build:
docker build -t pulsecast-web:local .
# Requires a running web server (npm run preview or node .output/server/index.mjs).
smoke:
node scripts/smoke-api.mjs
+113 -57
View File
@@ -10,8 +10,9 @@ evidence; the decision is the weekly plan.
- Nuxt `4.6.4`, `ssr: true`, Nitro `node-server`
- `@sit-onyx/nuxt` `1.2.0` + `sit-onyx` `1.22.0` for the entire shell and UI
- Mock JSON in `mock/`, mirrored by Nitro routes in `server/api/`
- Shared plan heuristic in `shared/staffing.ts`
- Nitro server routes proxy to the Go API; the browser only talks to this origin
- Shared plan heuristic in `shared/staffing.ts`, used for the mock fallback and
for the labeled local preview on `/plan`
Onyx is used for the navigation/app shell, page layout, cards, tables, buttons,
badges, tags, selects, segmented control, slider, stepper, accordion and file
@@ -21,56 +22,99 @@ upload. The app does not ship a parallel component design system.
```bash
npm ci
npm run dev # http://localhost:3000
npm run dev # http://localhost:3000, expects Go at http://localhost:8080
npm run build # production SSR build in .output/
npm run preview # preview the built app
npm test # heuristic unit tests
npm run mock # regenerate deterministic mock JSON
npm test # heuristic + Go parity tests
```
The built SSR server can also be started directly:
```bash
PORT=3000 node .output/server/index.mjs
NUXT_API_INTERNAL_BASE=http://localhost:8080 \
PORT=3000 node .output/server/index.mjs
```
## API wiring
Every route in `server/api/` is a proxy to the Go service. The default is the
real API; mock JSON is an explicit dev fallback only.
| Nitro route | Upstream |
| --- | --- |
| `GET /api/healthz` | `GET /api/healthz` |
| `GET /api/readyz` | `GET /api/readyz` |
| `GET /api/meta` | `GET /api/meta` |
| `GET /api/sensors` | `GET /api/sensors` |
| `GET /api/context` | `GET /api/context` |
| `GET /api/series` | `GET /api/series` |
| `GET /api/forecast` | `GET /api/forecast` |
| `GET /api/staffing` | `GET /api/staffing` |
| `GET /api/scenario` | `GET /api/scenario` |
| `POST /api/scenario` | `POST /api/scenario` with server-side control auth |
| `POST /api/train` | `POST /api/train` with server-side control auth |
| `GET /api/train/:job_id` | `GET /api/train/{job_id}` with server-side control auth |
| `GET /api/scenarios` | Local UI metadata only (labels/descriptions) |
`/plan` reads Go `/api/staffing` directly. The four local assumption controls
(safety factor, minimum staff, shift length, labour cost) are not query inputs
of the Go contract, so changing them renders an explicit **local preview** from
the API’s forecast hours; “Use API plan” restores the server values. The shared
heuristic is tested against a captured Go response in
`test/fixtures/go-staffing.json`.
### Environment
| Variable | Default | Purpose |
| --- | --- | --- |
| `NUXT_API_INTERNAL_BASE` | — | Preferred server-side Go base (`http://api:8080` in K8s) |
| `NUXT_API_BASE` | — | Alias for the server-side base |
| `NUXT_PUBLIC_API_BASE` | — | Fallback base; also exposed to the browser |
| `NUXT_API_TIMEOUT_MS` | `8000` | Upstream request timeout |
| `NUXT_PUBLIC_USE_MOCK` / `NUXT_USE_MOCK` | unset | `1` enables the mock fallback |
| `CONTROL_USER` / `CONTROL_PASS` | unset | Basic auth for `/api/scenario` and `/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.
The K8s web Deployment must mount the same `control-auth` secret as the API
Deployment:
```yaml
env:
- name: CONTROL_USER
valueFrom: { secretKeyRef: { name: control-auth, key: CONTROL_USER } }
- name: CONTROL_PASS
valueFrom: { secretKeyRef: { name: control-auth, key: CONTROL_PASS } }
```
### Mock fallback
```bash
NUXT_PUBLIC_USE_MOCK=1 npm run dev
```
Mock mode serves deterministic JSON from `mock/` and completes training
immediately. It is for developing the UI without Go; the default and the
deployed path are the real API.
## Screens
| Route | Purpose |
| ----------- | ----------------------------------------------------------------------- |
| `/` | Now: replay reading, 8-sensor schematic, weather, holiday, data versions |
| `/forecast` | 7-day daily forecast, uncertainty band, weather strip |
| `/plan` | **Hero.** Peak decision, shift blocks, coverage, cost, why, assumptions |
| `/simulate` | Scenario comparison (base vs sunny/rainy/Wednesday event) |
| `/about` | Method, metrics, limits, privacy, mock training form |
| Route | Purpose |
| --- | --- |
| `/` | Now: replay reading, 8-sensor schematic, weather, holiday, data versions |
| `/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` |
| `/about` | Method, metrics, limits, privacy, train form |
The layout is checked at **390 px** (single column, mobile Onyx nav, day cards)
and **1440 px** (Onyx horizontal nav, two-column plan with tables).
## Mock API
All mock routes return shapes from
`/home/noel/Documents/Hackathon_2026/CONTRACT.md` and are bundled into the Nitro
output, so the UI renders before the Go API exists:
```text
GET /api/healthz
GET /api/readyz
GET /api/meta
GET /api/sensors
GET /api/context
GET /api/series?sensor=&step=
GET /api/forecast?sensor=&horizon=&scenario=
GET /api/staffing?sensor=&scenario=&standard=
GET /api/scenario
POST /api/scenario
POST /api/train
GET /api/train/:job_id
```
`NUXT_PUBLIC_API_BASE` and `NUXT_PUBLIC_DEMO_NOW` are runtime config hooks for
the next integration slice. The current pages call the Nitro mock routes.
## Plan logic
`shared/staffing.ts` is the single implementation of the contract heuristic:
@@ -81,32 +125,44 @@ required = max(required, min_staff)
```
Store hours are 10:00–20:00 Europe/Berlin; default blocks are 4 h; labour cost is
€16/h; the default service standard is 25 visitors per staff-hour. Coverage is
at or above requirement by construction because each block is sized to its local
peak — the UI shows the resulting overstaffed hours instead of hiding them.
€16/h; the default service standard is 25 visitors per staff-hour. The flat
schedule applies the global peak requirement to every store hour, matching Go
and CONTRACT.md §5. Coverage is at or above requirement by construction because
each block is sized to its local peak — the UI shows the resulting overstaffed
hours instead of hiding them.
## What is still mocked
## Checks and CI
- Forecast, series, weather, holidays, sensor metadata, model metrics and
versions are deterministic JSON in `mock/`. Only `7d` has a full hourly mock;
`15m`, `1h` and `48h` are slices of that hourly series so the contract shape
is available to the next integration step.
- `POST /api/train` and `GET /api/train/:job_id` return an immediate success with
sample metrics. There is no real training run in the web tier.
- The sensor map is a **schematic** of relative positions. It does not yet
overlay the static MapLibre/basemap asset and makes no city-wide heatmap claim.
- Scenario changes are local; SSE (`/api/stream`) and the 5 s polling fallback
are not wired yet. The plan recomputes from the same deterministic heuristic.
- Approve/Export CSV are client-side actions; the CSV is real, the approval is
demo state only.
- No auth, no POS/sales/queue/payroll data, no live sensor feed.
```bash
make check # npm ci, npm run build, npm test
make smoke # against a running web server (WEB_URL=...)
```
The same `make check` runs in Gitea Actions (`.gitea/workflows/ci.yml`). The
workflow needs no secrets, no registry push and no cluster access.
`scripts/smoke-api.mjs` exercises the Nitro → Go chain: health, sensors,
context, meta, series, base and scenario forecasts, standard and premium
staffing, local presets, and 404/400 propagation.
## Docker
```bash
docker build -t pulsecast-web .
docker run --rm -p 3000:3000 pulsecast-web
docker run --rm -p 3000:3000 \
-e NUXT_API_INTERNAL_BASE=http://host.docker.internal:8080 \
pulsecast-web
```
The runtime stage is `node:22-alpine`, copies only `.output/`, and runs as the
non-root `node` user.
The multi-stage image copies only `.output/` into `node:22-alpine`. It creates
numeric UID/GID **`10001:10001`**, uses `COPY --chown=10001:10001` and runs
`USER 10001:10001`. Kubernetes should set `runAsUser: 10001`,
`runAsGroup: 10001` (never a named user such as `node`).
## Limits
- No POS, sales, queue or payroll data. Cost is an assumption.
- Forecast is model output; the plan is decision support, not an optimizer.
- Eight sensors in a 580 m cluster; no city-wide heatmap claim.
- SSE (`/api/stream`), `/live` and `/stage` are the next worktree.
- Raw CSV, secrets and kubeconfig never enter this repository.
+9 -2
View File
@@ -8,6 +8,13 @@ import {
} from '@sit-onyx/icons'
const route = useRoute()
const config = useRuntimeConfig()
const usingMock = computed(
() =>
config.public.useMock === true ||
config.public.useMock === '1' ||
config.public.useMock === 'true',
)
const navigation = [
{ to: '/', label: 'Now', icon: iconHome },
@@ -34,7 +41,7 @@ const activeLabel = computed(
:icon="item.icon"
/>
<template #contextArea>
<OnyxBadge color="warning">Mock data</OnyxBadge>
<OnyxBadge :color="usingMock ? 'warning' : 'success'">{{ usingMock ? 'Mock data' : 'Go API' }}</OnyxBadge>
</template>
<template #mobileActivePage>{{ activeLabel }}</template>
</OnyxNavBar>
@@ -46,7 +53,7 @@ const activeLabel = computed(
<footer class="app-footer">
<span><strong>PulseCast</strong> — staff the pulse, not the noise.</span>
<span class="muted small">
Prototype · mock forecast and weather · estimated devices, not people · 8 sensors in a 580 m cluster
Prototype · forecast from the Go API · estimated devices, not people · 8 sensors in a 580 m cluster
</span>
</footer>
</template>
+40 -23
View File
@@ -6,7 +6,6 @@ interface TrainResponse {
status: string
model: 'small' | 'forecast'
submitted_at: string
mock?: boolean
}
interface TrainJob {
@@ -44,70 +43,87 @@ const statusColor = computed(() => {
}
})
function apiErrorMessage(error: unknown, fallback: string): string {
const data = (
error as {
data?: { error?: { message?: string }; message?: string; statusMessage?: string }
}
)?.data
return data?.error?.message ?? data?.message ?? data?.statusMessage ?? fallback
}
function stopPolling() {
if (pollTimer) clearInterval(pollTimer)
pollTimer = undefined
polling.value = false
}
async function poll(jobId: string) {
stopPolling()
polling.value = true
let attempts = 0
pollTimer = setInterval(async () => {
attempts += 1
try {
const result = await $fetch<TrainJob>(`/api/train/${jobId}`)
const result = await $fetch<TrainJob>(`/api/train/${encodeURIComponent(jobId)}`)
job.value = result
if (result.status === 'succeeded' || result.status === 'failed') {
clearInterval(pollTimer)
polling.value = false
}
} catch {
if (attempts >= 12) {
clearInterval(pollTimer)
polling.value = false
errorMessage.value = 'Could not read the mock training job status.'
if (result.status === 'succeeded' || result.status === 'failed') stopPolling()
} catch (error) {
if (attempts >= 30) {
stopPolling()
errorMessage.value = apiErrorMessage(error, 'Could not read the training job status.')
}
}
}, 700)
}, 1000)
}
async function submit() {
errorMessage.value = ''
job.value = null
if (!file.value) {
errorMessage.value = 'Choose a CSV file first.'
return
}
submitting.value = true
try {
const formData = new FormData()
formData.append('model', model.value)
if (file.value) formData.append('file', file.value)
formData.append('file', file.value)
const response = await $fetch<TrainResponse>('/api/train', { method: 'POST', body: formData })
await poll(response.job_id)
} catch {
errorMessage.value = 'Training submission failed. The mock endpoint expects a CSV or model selection.'
} catch (error) {
errorMessage.value = apiErrorMessage(
error,
'Training submission failed. Check the Go API and its FastAPI training upstream.',
)
} finally {
submitting.value = false
}
}
onBeforeUnmount(() => {
if (pollTimer) clearInterval(pollTimer)
})
onBeforeUnmount(stopPolling)
</script>
<template>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Train new data</OnyxHeadline>
<OnyxBadge color="warning" density="compact">P1 mock</OnyxBadge>
<OnyxBadge color="info" density="compact">Server proxy</OnyxBadge>
</div>
<p class="small muted" style="margin-top: 0">
Posts to the mock <code>/api/train</code> contract. Replace the Nitro route with the Go endpoint when it
exists; the form shape stays the same.
Uploads through Nitro to Go <code>/api/train</code>. The control credentials stay in the Node process and are
never sent to the browser.
</p>
<form class="form-grid" @submit.prevent="submit">
<OnyxFileUpload
v-model="file"
label="Training CSV"
message="Optional in the mock."
message="Challenge CSV schema. Required."
:accept="['text/csv']"
max-size="50MiB"
/>
<p class="small muted" style="margin: 0">The real endpoint expects the challenge CSV schema.</p>
<OnyxSelect
v-model="model"
label="Model"
@@ -122,6 +138,7 @@ onBeforeUnmount(() => {
:loading="submitting || polling"
/>
<span v-if="submitting" class="small muted">Submitting…</span>
<span v-else-if="polling" class="small muted">Training job running…</span>
</div>
</form>
+16 -7
View File
@@ -6,6 +6,9 @@ import { formatDate, formatDateTime, formatPercent } from '~/utils/format'
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))
</script>
<template>
@@ -84,10 +87,10 @@ const { data: meta } = await useFetch<MetaResponse>('/api/meta')
<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 (mock 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 is rendered from <code>web-nuxt/mock/meta.json</code> until the Go API exists.</p>
<p class="small muted table-note">Meta comes from Go <code>/api/meta</code> through the Nitro proxy.</p>
</OnyxCard>
<TrainModelCard />
@@ -126,12 +129,18 @@ const { data: meta } = await useFetch<MetaResponse>('/api/meta')
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Mock status</OnyxHeadline>
<OnyxHeadline is="h3">Data source</OnyxHeadline>
<OnyxBadge :color="usingMock ? 'warning' : 'success'" density="compact">
{{ usingMock ? 'Mock mode' : 'Go API' }}
</OnyxBadge>
</div>
<p class="small muted" style="margin-top: 0">
Mock data renders the full app before the API exists. Nitro routes in <code>server/api</code> mirror the
contract. Versions and metrics are sample values; the plan heuristic is implemented once in
<code>shared/staffing.ts</code> and reused by the mock API.
<p v-if="usingMock" class="small muted" style="margin-top: 0">
Explicit dev fallback: <code>NUXT_PUBLIC_USE_MOCK=1</code>. Mock JSON renders the app without the Go
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
<code>NUXT_API_INTERNAL_BASE</code>; forecast, context and meta are served from there.
</p>
<p class="small muted" style="margin: 0">
Last context update: {{ meta ? formatDateTime(meta.context_version) : '—' }}
+12 -6
View File
@@ -21,6 +21,12 @@ 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')
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', {
query: computed(() => ({ sensor: sensorId.value, horizon: '7d', scenario: scenario.value })),
})
@@ -90,7 +96,7 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<p class="eyebrow">Forecast · {{ weekLabel(weekStart, weekEnd) }}</p>
<OnyxHeadline is="h1">Next week peaks on {{ weekPeak ? formatWeekday(weekPeak.date) : '—' }}.</OnyxHeadline>
<p class="lede">
A 168-hour mock forecast for <strong>{{ activeSensor?.name ?? 'Stadtgalerie' }}</strong>, aggregated by
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>
@@ -161,7 +167,7 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<template v-if="day.weather">
{{ Math.round(day.weather.tempMin) }}–{{ Math.round(day.weather.tempMax) }} °C · {{ day.weather.precipMm.toFixed(1) }} mm
</template>
<span v-else class="muted">outside mock window</span>
<span v-else class="muted">outside weather window</span>
</td>
<td><OnyxBadge color="neutral" density="compact">{{ day.requiredAtPeak }}</OnyxBadge></td>
</tr>
@@ -178,11 +184,11 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Weather strip</OnyxHeadline>
<OnyxBadge color="neutral" density="compact">Open-Meteo mock</OnyxBadge>
<OnyxBadge color="neutral" density="compact">Open-Meteo context</OnyxBadge>
</div>
<WeatherStrip :days="weekWeather" />
<p v-if="!weekWeather.length" class="small muted table-note">
The mock weather window does not cover the plan week.
The weather window does not cover the plan week.
</p>
<p class="small muted table-note">
Weather is the main accuracy driver in the model. Holidays are context and a smaller feature.
@@ -197,13 +203,13 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<ul class="why-list">
<li>
<OnyxIcon :icon="iconCalendar" size="16px" color="primary" />
<span>168 hourly points from the mock 7-day horizon, not a live stream.</span>
<span>168 hourly points from the API 7-day horizon, not a live stream.</span>
</li>
<li>
<OnyxIcon :icon="iconChart" size="16px" color="primary" />
<span>
Mean WAPE {{ meta ? formatPercent(meta.metrics.wape, 1) : '—' }} vs
{{ meta ? formatPercent(meta.metrics.baseline_wape, 1) : '—' }} seasonal naive in the mock meta;
{{ meta ? formatPercent(meta.metrics.baseline_wape, 1) : '—' }} seasonal naive in the API meta;
per-hour uncertainty is real.
</span>
</li>
+10 -6
View File
@@ -22,11 +22,15 @@ useHead({ title: 'Now in Heilbronn — PulseCast' })
const config = useRuntimeConfig()
const demoNow = String(config.public.demoNow)
const sensorId = ref('hn-stadtgalerie-01')
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 sensorId = ref(
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
'hn-stadtgalerie-01',
)
const { data: series } = await useFetch<SeriesResponse>('/api/series', {
query: computed(() => ({ sensor: sensorId.value, step: '1h' })),
})
@@ -93,7 +97,7 @@ const latestPulse = computed(() => {
<div class="card-header">
<div>
<OnyxHeadline is="h2">Latest replay reading</OnyxHeadline>
<p class="small muted" style="margin: 0">Last available hour in the mock series.</p>
<p class="small muted" style="margin: 0">Last available hour in the API series.</p>
</div>
<div style="min-width: 12rem">
<OnyxSelect
@@ -158,7 +162,7 @@ const latestPulse = computed(() => {
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Heilbronn weather</OnyxHeadline>
<OnyxBadge color="neutral" density="compact">Open-Meteo mock</OnyxBadge>
<OnyxBadge color="neutral" density="compact">Open-Meteo context</OnyxBadge>
</div>
<div class="reading-row">
<OnyxIcon :icon="weatherIcon" size="48px" color="primary" />
@@ -177,7 +181,7 @@ const latestPulse = computed(() => {
</dl>
<p class="small muted table-note">
Updated {{ context ? formatDateTime(context.updated_at) : '—' }} · context
{{ context?.cached ? 'cached' : 'mock' }}
{{ context?.cached ? 'cached' : 'live' }}
</p>
</OnyxCard>
@@ -192,7 +196,7 @@ const latestPulse = computed(() => {
<template v-if="nextHoliday">
Next: <strong>{{ nextHoliday.name }}</strong> on {{ formatDate(nextHoliday.date) }}.
</template>
<template v-else>No upcoming holiday in the mock calendar.</template>
<template v-else>No upcoming holiday in the holiday calendar.</template>
</p>
<p v-if="lastHoliday" class="small muted" style="margin: var(--onyx-density-xs) 0 0">
Last: {{ lastHoliday.name }} on {{ formatShortDate(lastHoliday.date) }}.
@@ -258,7 +262,7 @@ const latestPulse = computed(() => {
<div v-if="!sensors?.length" class="callout callout--warning">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
Sensor mock data is missing. Run <code>npm run mock</code> and reload.
Sensor data is missing. Check that the Go API is running and that NUXT_API_INTERNAL_BASE points to it.
</div>
</div>
</template>
+171 -54
View File
@@ -8,18 +8,26 @@ import {
iconTriangleWarning,
iconUserGroup,
} from '@sit-onyx/icons'
import { dailyWeather, planDrivers } from '#shared/insights'
import { addDays, berlinParts, buildStaffing, isInWeek, planWeekStart, STANDARD_VISITORS_PER_STAFF_HOUR } from '#shared/staffing'
import { dailyWeather } from '#shared/insights'
import {
addDays,
berlinParts,
buildStaffing,
DEFAULT_ASSUMPTIONS,
isInWeek,
planWeekStart,
STANDARD_VISITORS_PER_STAFF_HOUR,
} from '#shared/staffing'
import { SCENARIOS } from '#shared/types'
import type {
ContextResponse,
ForecastResponse,
MetaResponse,
Scenario,
ScenarioPreset,
Sensor,
Shift,
StaffingHour,
StaffingResponse,
Standard,
} from '#shared/types'
import {
@@ -39,42 +47,75 @@ useHead({ title: 'Plan next week — PulseCast' })
const config = useRuntimeConfig()
const route = useRoute()
const demoNow = String(config.public.demoNow)
const weekStart = planWeekStart(demoNow)
const weekEnd = addDays(weekStart, 6)
const usingMock = computed(
() =>
config.public.useMock === true ||
config.public.useMock === '1' ||
config.public.useMock === 'true',
)
function initialScenario(): Scenario {
const value = route.query.scenario
return typeof value === 'string' && SCENARIOS.includes(value as Scenario) ? (value as Scenario) : 'base'
}
const scenario = ref<Scenario>(initialScenario())
const sensorId = ref('hn-stadtgalerie-01')
const standard = ref<Standard>('standard')
const selectedDay = ref(addDays(weekStart, 5))
const approved = ref(false)
const generating = ref(false)
const generatedAt = ref('')
const openAssumptions = ref<PropertyKey[]>([])
const assumptions = reactive({
safety_factor: 1.15,
min_staff: 1,
shift_length_h: 4,
labor_cost_eur_h: 16,
})
/** Keep Stadtgalerie as the demo default, but follow the API when it differs. */
function preferredSensor(list: Sensor[] | null | undefined): string {
return list?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ?? list?.[0]?.id ?? 'hn-stadtgalerie-01'
}
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 sensorId = ref(preferredSensor(sensors.value))
const scenario = ref<Scenario>(initialScenario())
const standard = ref<Standard>('standard')
const approved = ref(false)
const generating = ref(false)
const generatedAt = ref('')
const openAssumptions = ref<PropertyKey[]>([])
const assumptions = reactive({
safety_factor: DEFAULT_ASSUMPTIONS.safety_factor,
min_staff: DEFAULT_ASSUMPTIONS.min_staff,
shift_length_h: DEFAULT_ASSUMPTIONS.shift_length_h,
labor_cost_eur_h: DEFAULT_ASSUMPTIONS.labor_cost_eur_h,
})
const EMPTY_PLAN: StaffingResponse = {
sensor: '',
scenario: 'base',
standard: 'standard',
assumptions: DEFAULT_ASSUMPTIONS,
hours: [],
shifts: [],
summary: {
coverage_pct: 0,
cost_eur: 0,
flat_schedule_cost_eur: 0,
overstaffed_hours: 0,
understaffed_hours: 0,
},
why: [],
cached: false,
data_version: '',
model_version: '',
context_version: '',
}
// The hero plan comes from the Go API. Local assumption edits only render a
// preview from the API's own forecast hours; they never replace the API plan.
const {
data: forecast,
data: apiPlanData,
status,
error,
refresh,
} = await useFetch<ForecastResponse>('/api/forecast', {
} = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({
sensor: sensorId.value,
horizon: '7d',
scenario: scenario.value,
standard: standard.value,
})),
})
@@ -87,10 +128,17 @@ watch(
},
)
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))
const visitorsPerStaffHour = computed(() => STANDARD_VISITORS_PER_STAFF_HOUR[standard.value])
const weekStart = computed(() => {
const first = apiPlan.value.hours[0]
return first ? berlinParts(first.t).date : planWeekStart(demoNow)
})
const weekEnd = computed(() => addDays(weekStart.value, 6))
const scenarioOptions = computed(() =>
(presets.value ?? []).map((preset) => ({ value: preset.id, label: preset.label })),
)
@@ -117,34 +165,65 @@ const shiftLengthOptions = [
{ value: 5, label: '5 hours' },
]
const build = computed(() =>
/** The /api/staffing contract has no assumption query params. Non-query edits
* are therefore an explicitly labeled local preview, never a silent swap. */
const previewActive = computed(() => {
const api = apiPlan.value.assumptions
return (
assumptions.safety_factor !== api.safety_factor ||
assumptions.min_staff !== api.min_staff ||
assumptions.shift_length_h !== api.shift_length_h ||
assumptions.labor_cost_eur_h !== api.labor_cost_eur_h
)
})
const previewBuild = computed(() =>
buildStaffing({
sensor: sensorId.value,
scenario: scenario.value,
standard: standard.value,
points: forecast.value?.points ?? [],
weekStart,
points: apiPlan.value.hours.map((hour) => ({ t: hour.t, v: hour.footfall })),
weekStart: weekStart.value,
assumptions: {
visitors_per_staff_hour: visitorsPerStaffHour.value,
safety_factor: assumptions.safety_factor,
min_staff: assumptions.min_staff,
shift_length_h: assumptions.shift_length_h,
labor_cost_eur_h: assumptions.labor_cost_eur_h,
store_hours: apiPlan.value.assumptions.store_hours,
},
data_version: forecast.value?.data_version ?? meta.value?.data_version ?? '',
model_version: forecast.value?.model_version ?? meta.value?.model_version ?? '',
context_version: forecast.value?.context_version ?? meta.value?.context_version ?? '',
data_version: apiPlan.value.data_version,
model_version: apiPlan.value.model_version,
context_version: apiPlan.value.context_version,
}),
)
const plan = computed(() => build.value.response)
const why = computed(() =>
context.value ? planDrivers(plan.value, context.value, weekStart, scenario.value) : [],
)
const plan = computed(() => (previewActive.value ? previewBuild.value.response : apiPlan.value))
const hoursByDate = computed<Record<string, StaffingHour[]>>(() => {
if (previewActive.value) return previewBuild.value.byDate
const grouped: Record<string, StaffingHour[]> = {}
for (const hour of apiPlan.value.hours) {
const date = berlinParts(hour.t).date
;(grouped[date] ??= []).push(hour)
}
return grouped
})
const shiftsByDate = computed<Record<string, Shift[]>>(() => {
if (previewActive.value) return previewBuild.value.shiftsByDate
const grouped: Record<string, Shift[]> = {}
for (const shift of apiPlan.value.shifts) {
;(grouped[shift.date] ??= []).push(shift)
}
return grouped
})
const why = computed(() => apiPlan.value.why)
const weekWeather = computed(() => {
if (!context.value) return []
return Object.values(dailyWeather(context.value.weather.forecast))
.filter((day) => isInWeek(day.date, weekStart))
.filter((day) => isInWeek(day.date, weekStart.value))
.sort((a, b) => a.date.localeCompare(b.date))
})
@@ -178,11 +257,11 @@ interface DaySummary {
}
const daySummaries = computed<DaySummary[]>(() =>
Object.keys(build.value.byDate)
Object.keys(hoursByDate.value)
.sort()
.map((date) => {
const hours = build.value.byDate[date] ?? []
const shifts = build.value.shiftsByDate[date] ?? []
const hours = hoursByDate.value[date] ?? []
const shifts = shiftsByDate.value[date] ?? []
const staffHours = hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0)
return {
date,
@@ -193,6 +272,17 @@ const daySummaries = computed<DaySummary[]>(() =>
}
}),
)
const dayDates = computed(() => daySummaries.value.map((day) => day.date))
const selectedDay = ref('')
watch(
() => dayDates.value.join(','),
() => {
if (dayDates.value.includes(selectedDay.value)) return
const preferred = addDays(weekStart.value, 5)
selectedDay.value = dayDates.value.includes(preferred) ? preferred : (dayDates.value[0] ?? '')
},
{ immediate: true },
)
const dayOptions = computed(() =>
daySummaries.value.map((day) => ({
@@ -200,7 +290,7 @@ const dayOptions = computed(() =>
label: `${formatWeekday(day.date)} ${formatShortDate(day.date)} · ${day.peakStaff} peak`,
})),
)
const selectedHours = computed<StaffingHour[]>(() => build.value.byDate[selectedDay.value] ?? [])
const selectedHours = computed<StaffingHour[]>(() => hoursByDate.value[selectedDay.value] ?? [])
const selectedCovered = computed(
() => selectedHours.value.filter((hour) => hour.scheduled_staff >= hour.required_staff).length,
)
@@ -224,20 +314,28 @@ async function generate() {
generating.value = true
try {
await refresh()
if (import.meta.client) generatedAt.value = formatTime(new Date().toISOString())
if (!error.value && import.meta.client) generatedAt.value = formatTime(new Date().toISOString())
} finally {
generating.value = false
}
}
function resetAssumptions() {
assumptions.safety_factor = 1.15
assumptions.min_staff = 1
assumptions.shift_length_h = 4
assumptions.labor_cost_eur_h = 16
assumptions.safety_factor = DEFAULT_ASSUMPTIONS.safety_factor
assumptions.min_staff = DEFAULT_ASSUMPTIONS.min_staff
assumptions.shift_length_h = DEFAULT_ASSUMPTIONS.shift_length_h
assumptions.labor_cost_eur_h = DEFAULT_ASSUMPTIONS.labor_cost_eur_h
standard.value = 'standard'
}
function useApiPlan() {
const api = apiPlan.value.assumptions
assumptions.safety_factor = api.safety_factor
assumptions.min_staff = api.min_staff
assumptions.shift_length_h = api.shift_length_h
assumptions.labor_cost_eur_h = api.labor_cost_eur_h
}
function exportPlan() {
if (!import.meta.client) return
const rows = [
@@ -254,7 +352,7 @@ function exportPlan() {
const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }))
const link = document.createElement('a')
link.href = url
link.download = `pulsecast-plan-${weekStart}.csv`
link.download = `pulsecast-plan-${weekStart.value}.csv`
link.click()
URL.revokeObjectURL(url)
}
@@ -273,7 +371,7 @@ function exportPlan() {
<template v-else>Build next week’s shift plan.</template>
</OnyxHeadline>
<p class="lede">
Forecast for <strong>{{ activeSensor?.name ?? 'Stadtgalerie' }}</strong> needs
Forecast for <strong>{{ activeSensor?.name ?? apiPlan.sensor ?? 'the selected store' }}</strong> needs
<strong>{{ peakHour?.required_staff ?? '—' }} staff at the busiest hour</strong>. The rest of the week
runs on {{ totalStaffHours }} staff-hours at {{ formatEuro(plan.summary.cost_eur) }}.
</p>
@@ -289,8 +387,14 @@ function exportPlan() {
<span v-else class="small muted">Draft for manager review</span>
</div>
<p class="small muted" style="margin: 0">
Mock forecast · updated {{ context ? formatDateTime(context.updated_at) : '—' }} · no POS, sales or
labour-cost feed.
<template v-if="usingMock">Mock mode · NUXT_PUBLIC_USE_MOCK=1 · no Go API call.</template>
<template v-else-if="previewActive">
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.
</template>
</p>
</div>
@@ -311,6 +415,7 @@ function exportPlan() {
<OnyxBadge color="success" density="compact">{{ formatPercent(plan.summary.coverage_pct, 1) }} covered</OnyxBadge>
<OnyxBadge color="warning" density="compact">{{ plan.summary.overstaffed_hours }} h over</OnyxBadge>
<OnyxBadge color="success" density="compact">{{ plan.summary.understaffed_hours }} h under</OnyxBadge>
<OnyxBadge v-if="apiPlan.cached" color="warning" density="compact">cached forecast</OnyxBadge>
</div>
</div>
</div>
@@ -318,7 +423,8 @@ function exportPlan() {
<div v-if="status === 'error'" class="callout callout--warning">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
The mock forecast could not be loaded. Check the Nitro mock routes and reload.
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>
<section class="summary-grid" aria-label="Plan summary">
@@ -357,10 +463,13 @@ function exportPlan() {
<div>
<OnyxHeadline is="h2">Plan inputs</OnyxHeadline>
<p class="small muted" style="margin: 0">
Change store, service standard or scenario. The plan recomputes from the mock forecast.
Store, service standard and scenario are sent to Go `/api/staffing`. Local assumption edits render a
preview from the API forecast.
</p>
</div>
<OnyxBadge color="info" density="compact">Mock forecast</OnyxBadge>
<OnyxBadge :color="usingMock ? 'warning' : previewActive ? 'warning' : 'success'" density="compact">
{{ usingMock ? 'Mock mode' : previewActive ? 'Local preview' : 'Go API' }}
</OnyxBadge>
</div>
<div class="form-grid">
@@ -445,9 +554,14 @@ function exportPlan() {
:step-size="1"
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;
“Use API plan” restores the server values.
</p>
<div class="form-actions" style="grid-column: 1 / -1">
<OnyxButton label="Reset assumptions" mode="outline" @click="resetAssumptions" />
<span class="small muted">Store hours 10:00–20:00, Europe/Berlin · {{ forecast?.model_version ?? 'mock' }}</span>
<OnyxButton v-if="previewActive" label="Use API plan" mode="outline" @click="useApiPlan" />
<span class="small muted">Store hours 10:00–20:00, Europe/Berlin · {{ apiPlan.model_version || 'API' }}</span>
</div>
</div>
</OnyxAccordionItem>
@@ -593,7 +707,7 @@ function exportPlan() {
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Why this plan</OnyxHeadline>
<OnyxBadge color="info" density="compact">Context</OnyxBadge>
<OnyxBadge color="info" density="compact">{{ usingMock ? 'Mock mode' : 'Go API' }}</OnyxBadge>
</div>
<ul class="why-list">
<li v-for="reason in why" :key="reason">
@@ -606,10 +720,13 @@ 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">
Weather forecast does not cover this window in the mock context.
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 mock forecast weather.' }}
{{ activeScenario?.description ?? 'Base scenario uses the API forecast weather.' }}
</p>
<p v-if="previewActive" class="small muted table-note">
This card explains the API plan; the assumption preview above is local.
</p>
</OnyxCard>
@@ -625,7 +742,7 @@ function exportPlan() {
<div><dt>Shift block</dt><dd>{{ plan.assumptions.shift_length_h }} h</dd></div>
<div><dt>Labour cost</dt><dd>{{ formatEuro(plan.assumptions.labor_cost_eur_h) }}/h</dd></div>
<div><dt>Store hours</dt><dd>{{ plan.assumptions.store_hours.open }}–{{ plan.assumptions.store_hours.close }}</dd></div>
<div><dt>Model / data</dt><dd>{{ forecast?.model_version ?? meta?.model_version ?? 'mock' }}</dd></div>
<div><dt>Model / data</dt><dd>{{ plan.model_version || meta?.model_version || '—' }}</dd></div>
</dl>
<p class="small muted table-note" style="margin-top: var(--onyx-density-md)">
No POS, sales, queue or labour-cost data exists. This is decision support with explicit assumptions,
+78 -51
View File
@@ -1,25 +1,74 @@
<script setup lang="ts">
import { iconArrowRight, iconCircleInformation, iconFlash } from '@sit-onyx/icons'
import { addDays, applyScenario, buildStaffing, planWeekStart } from '#shared/staffing'
import type { ContextResponse, ForecastResponse, Scenario, ScenarioPreset, Sensor } from '#shared/types'
import { addDays, berlinParts, planWeekStart } from '#shared/staffing'
import type {
ContextResponse,
Scenario,
ScenarioPreset,
Sensor,
StaffingResponse,
} from '#shared/types'
import { formatEuro, formatShortDate, formatWeekday, formatWeekdayShort, weekLabel } from '~/utils/format'
useHead({ title: 'Simulate a scenario — PulseCast' })
const config = useRuntimeConfig()
const demoNow = String(config.public.demoNow)
const weekStart = planWeekStart(demoNow)
const weekEnd = addDays(weekStart, 6)
const sensorId = ref('hn-stadtgalerie-01')
const scenario = ref<Scenario>('sunny-saturday-market')
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: context } = await useFetch<ContextResponse>('/api/context')
const { data: presets } = await useFetch<ScenarioPreset[]>('/api/scenarios')
const { data: baseForecast } = await useFetch<ForecastResponse>('/api/forecast', {
query: computed(() => ({ sensor: sensorId.value, horizon: '7d', scenario: 'base' })),
const sensorId = ref(
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
'hn-stadtgalerie-01',
)
const scenario = ref<Scenario>('sunny-saturday-market')
const EMPTY_PLAN: StaffingResponse = {
sensor: '',
scenario: 'base',
standard: 'standard',
assumptions: {
visitors_per_staff_hour: 25,
safety_factor: 1.15,
min_staff: 1,
shift_length_h: 4,
labor_cost_eur_h: 16,
store_hours: { open: '10:00', close: '20:00', tz: 'Europe/Berlin' },
},
hours: [],
shifts: [],
summary: {
coverage_pct: 0,
cost_eur: 0,
flat_schedule_cost_eur: 0,
overstaffed_hours: 0,
understaffed_hours: 0,
},
why: [],
cached: false,
data_version: '',
model_version: '',
context_version: '',
}
const { data: baseData } = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({ sensor: sensorId.value, scenario: 'base', standard: 'standard' })),
})
const { data: scenarioData, status } = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({ sensor: sensorId.value, scenario: scenario.value, standard: 'standard' })),
})
const basePlan = computed(() => baseData.value ?? EMPTY_PLAN)
const scenarioPlan = computed(() => scenarioData.value ?? basePlan.value)
const weekStart = computed(() => {
const first = basePlan.value.hours[0]
return first ? berlinParts(first.t).date : planWeekStart(demoNow)
})
const weekEnd = computed(() => addDays(weekStart.value, 6))
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const sensorOptions = computed(() =>
@@ -34,31 +83,6 @@ const radioOptions = computed(() =>
})),
)
const scenarioPoints = computed(() =>
applyScenario(baseForecast.value?.points ?? [], scenario.value),
)
const versions = computed(() => ({
data_version: baseForecast.value?.data_version ?? '',
model_version: baseForecast.value?.model_version ?? '',
context_version: baseForecast.value?.context_version ?? '',
}))
function makePlan(points: typeof scenarioPoints.value) {
return buildStaffing({
sensor: sensorId.value,
scenario: scenario.value,
standard: 'standard',
points,
weekStart,
...versions.value,
})
}
const basePlan = computed(() => makePlan(baseForecast.value?.points ?? []).response)
const scenarioBuild = computed(() => makePlan(scenarioPoints.value))
const scenarioPlan = computed(() => scenarioBuild.value.response)
const baseHours = computed(() => basePlan.value.hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0))
const scenarioHours = computed(() =>
scenarioPlan.value.hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0),
@@ -66,18 +90,19 @@ const scenarioHours = computed(() =>
const deltaHours = computed(() => scenarioHours.value - baseHours.value)
const deltaCost = computed(() => scenarioPlan.value.summary.cost_eur - basePlan.value.summary.cost_eur)
function peakStaffByDay(plan: ReturnType<typeof makePlan>) {
function peakStaffByDay(plan: StaffingResponse) {
const map: Record<string, number> = {}
for (const [date, hours] of Object.entries(plan.byDate)) {
map[date] = hours.reduce((peak, hour) => Math.max(peak, hour.required_staff), 0)
for (const hour of plan.hours) {
const date = berlinParts(hour.t).date
map[date] = Math.max(map[date] ?? 0, hour.required_staff)
}
return map
}
const basePeaks = computed(() => peakStaffByDay(makePlan(baseForecast.value?.points ?? [])))
const scenarioPeaks = computed(() => peakStaffByDay(scenarioBuild.value))
const basePeaks = computed(() => peakStaffByDay(basePlan.value))
const scenarioPeaks = computed(() => peakStaffByDay(scenarioPlan.value))
const days = computed(() =>
Object.keys(basePeaks.value)
[...new Set([...Object.keys(basePeaks.value), ...Object.keys(scenarioPeaks.value)])]
.sort()
.map((date) => ({
date,
@@ -111,8 +136,8 @@ const days = computed(() =>
<div class="callout">
<OnyxIcon :icon="iconCircleInformation" size="16px" color="primary" />
Local selection for now. 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`. SSE broadcast to <code>/stage</code> and
phones is the next slice; this page makes the recommendation change visible on one screen.
</div>
<div class="split-grid">
@@ -121,9 +146,11 @@ const days = computed(() =>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Scenario</OnyxHeadline>
<p class="small muted" style="margin: 0">The contract enum is fixed; perturbation sizes are mock assumptions.</p>
<p class="small muted" style="margin: 0">The contract enum is fixed; the API applies the perturbation.</p>
</div>
<OnyxBadge color="warning" density="compact">mock simulation</OnyxBadge>
<OnyxBadge :color="status === 'pending' ? 'warning' : 'success'" density="compact">
{{ status === 'pending' ? 'loading' : 'Go API' }}
</OnyxBadge>
</div>
<OnyxRadioGroup
v-model="scenario"
@@ -193,7 +220,7 @@ const days = computed(() =>
peak hour before cutting the block.
</template>
<template v-else>
This scenario does not change the shift requirements in the mock. That is a result, not a bug.
This scenario does not change the shift requirements. That is a result, not a bug.
</template>
</p>
</div>
@@ -212,14 +239,14 @@ const days = computed(() =>
<OnyxHeadline is="h3">Scenario rules</OnyxHeadline>
</div>
<ul class="why-list">
<li><span><strong>Sunny Saturday + market</strong> — ×1.20 Saturday footfall.</span></li>
<li><span><strong>Rainy Saturday</strong> — ×0.82 Saturday footfall.</span></li>
<li><span><strong>Wednesday event</strong> — ×1.25 Wed 16:00–20:00.</span></li>
<li><span>Base keeps the latest forecast weather and no event uplift.</span></li>
<li><span><strong>Base week</strong> — latest forecast weather, no scenario uplift.</span></li>
<li><span><strong>Sunny Saturday + market</strong> — Go applies the market/day uplift to next Saturday.</span></li>
<li><span><strong>Rainy Saturday</strong> — Go applies the wet-weather reduction.</span></li>
<li><span><strong>Wednesday event</strong> — Go applies the weekday evening event uplift.</span></li>
</ul>
<p class="small muted table-note">
These multipliers are mock demo assumptions. The Go/ML implementation must publish the same numbers or
the comparison is not comparable.
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.
</p>
</OnyxCard>
+20
View File
@@ -1,3 +1,8 @@
const useMock =
(process.env.NUXT_PUBLIC_USE_MOCK ?? process.env.NUXT_USE_MOCK ?? '').toLowerCase() === 'true' ||
process.env.NUXT_PUBLIC_USE_MOCK === '1' ||
process.env.NUXT_USE_MOCK === '1'
export default defineNuxtConfig({
compatibilityDate: '2026-11-01',
ssr: true,
@@ -5,8 +10,23 @@ export default defineNuxtConfig({
css: ['~/assets/css/main.css'],
devtools: { enabled: false },
runtimeConfig: {
// Server-side Go API. K8s sets NUXT_API_INTERNAL_BASE=http://api:8080.
apiBase:
process.env.NUXT_API_INTERNAL_BASE ??
process.env.NUXT_API_BASE ??
process.env.NUXT_PUBLIC_API_BASE ??
'http://localhost:8080',
apiTimeoutMs: Number(process.env.NUXT_API_TIMEOUT_MS ?? 8000),
// Explicit dev fallback. The default is the real Go API.
useMock,
// Server-only control credentials for POST /api/scenario and /api/train.
controlUser: process.env.CONTROL_USER ?? process.env.NUXT_CONTROL_USER ?? '',
controlPass: process.env.CONTROL_PASS ?? process.env.NUXT_CONTROL_PASS ?? '',
controlToken: process.env.CONTROL_TOKEN ?? process.env.NUXT_CONTROL_TOKEN ?? '',
public: {
// Browser never calls Go directly; this is for display/future SSE wiring.
apiBase: process.env.NUXT_PUBLIC_API_BASE ?? '',
useMock,
demoNow: process.env.NUXT_PUBLIC_DEMO_NOW ?? '2026-11-14T08:12:00Z',
},
},
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env node
// Smoke-test the Nitro -> Go proxy chain against a running web server.
// Usage: WEB_URL=http://localhost:3000 node scripts/smoke-api.mjs
const base = (process.env.WEB_URL ?? 'http://localhost:3000').replace(/\/+$/, '')
let failures = 0
async function request(path, expectedStatus = 200) {
const response = await fetch(`${base}${path}`, { headers: { accept: 'application/json' } })
const text = await response.text()
let body
try {
body = JSON.parse(text)
} catch {
throw new Error(`${path} returned non-JSON (${response.status}): ${text.slice(0, 120)}`)
}
if (response.status !== expectedStatus) {
throw new Error(`${path} returned ${response.status}, expected ${expectedStatus}: ${text.slice(0, 200)}`)
}
return body
}
async function check(name, fn) {
try {
const detail = await fn()
console.log(`PASS ${name}${detail ? ` — ${detail}` : ''}`)
} catch (error) {
failures += 1
console.log(`FAIL ${name} — ${error.message}`)
}
}
await check('/api/healthz', async () => {
const body = await request('/api/healthz')
if (body.ok !== true) throw new Error('ok is not true')
return 'ok'
})
let sensors = []
await check('/api/sensors', async () => {
sensors = await request('/api/sensors')
if (!Array.isArray(sensors) || sensors.length === 0) throw new Error('empty sensor list')
if (!sensors[0].id || !sensors[0].name) throw new Error('sensor missing id/name')
return `${sensors.length} sensors, first=${sensors[0].id}`
})
const sensor = sensors[0]?.id ?? 'hn-stadtgalerie-01'
await check('/api/context', async () => {
const body = await request('/api/context')
if (!body.weather?.now?.t) throw new Error('weather.now missing')
if (!Array.isArray(body.holidays)) throw new Error('holidays missing')
return `${body.holidays.length} holidays, updated=${body.updated_at}`
})
await check('/api/meta', async () => {
const body = await request('/api/meta')
if (!body.model_version || !body.data_version) throw new Error('versions missing')
return `model=${body.model_version}`
})
await check('/api/series', async () => {
const body = await request(`/api/series?sensor=${encodeURIComponent(sensor)}&step=1h`)
if (!Array.isArray(body.points) || body.points.length === 0) throw new Error('no points')
return `${body.points.length} hourly points`
})
await check('/api/forecast 7d base', async () => {
const body = await request(
`/api/forecast?sensor=${encodeURIComponent(sensor)}&horizon=7d&scenario=base`,
)
if (!Array.isArray(body.points) || body.points.length === 0) throw new Error('no points')
return `${body.points.length} points, cached=${body.cached}`
})
await check('/api/forecast 7d rainy-saturday', async () => {
const body = await request(
`/api/forecast?sensor=${encodeURIComponent(sensor)}&horizon=7d&scenario=rainy-saturday`,
)
if (body.scenario !== 'rainy-saturday') throw new Error('scenario not echoed')
return `${body.points.length} points`
})
await check('/api/staffing standard', async () => {
const body = await request(
`/api/staffing?sensor=${encodeURIComponent(sensor)}&scenario=base&standard=standard`,
)
if (!Array.isArray(body.hours) || body.hours.length === 0) throw new Error('no plan hours')
if (!Array.isArray(body.shifts) || body.shifts.length === 0) throw new Error('no shifts')
if (!body.summary || typeof body.summary.coverage_pct !== 'number') {
throw new Error('summary missing')
}
return `${body.hours.length} hours, ${body.shifts.length} shifts, cost=${body.summary.cost_eur}`
})
await check('/api/staffing premium', async () => {
const body = await request(
`/api/staffing?sensor=${encodeURIComponent(sensor)}&scenario=base&standard=premium`,
)
if (body.standard !== 'premium') throw new Error('standard not echoed')
return `cost=${body.summary.cost_eur}`
})
await check('/api/scenarios local presets', async () => {
const body = await request('/api/scenarios')
if (!Array.isArray(body) || body.length < 4) throw new Error('preset list missing')
return `${body.length} presets`
})
await check('unknown sensor propagates 404', async () => {
const body = await request('/api/staffing?sensor=does-not-exist', 404)
if (!body.error?.message && !body.statusMessage && !body.message) {
throw new Error('no error message')
}
return body.statusMessage ?? body.message ?? body.error?.message ?? '404'
})
await check('invalid standard propagates 400', async () => {
const body = await request(
`/api/staffing?sensor=${encodeURIComponent(sensor)}&standard=luxury`,
400,
)
if (!body.error?.message && !body.statusMessage && !body.message) {
throw new Error('no error message')
}
return body.statusMessage ?? body.message ?? body.error?.message ?? '400'
})
if (failures > 0) {
console.error(`\n${failures} smoke check(s) failed against ${base}`)
process.exit(1)
}
console.log(`\nAll smoke checks passed against ${base}`)
+6 -1
View File
@@ -1,3 +1,8 @@
import type { ContextResponse } from '../../shared/types'
import { apiRequest, isMockMode } from '../utils/api'
import { mockContext } from '../utils/mock-data'
export default defineEventHandler(() => mockContext)
export default defineEventHandler(async () => {
if (isMockMode()) return mockContext
return apiRequest<ContextResponse>('/api/context')
})
+23 -25
View File
@@ -1,34 +1,32 @@
import { applyScenario } from '../../shared/staffing'
import { HORIZONS, SCENARIOS } from '../../shared/types'
import type { Horizon, Scenario } from '../../shared/types'
import type { ForecastResponse, Horizon, Scenario } from '../../shared/types'
import { apiRequest, enumParam, isMockMode, sensorParam } from '../utils/api'
import { getMockForecast } from '../utils/mock-data'
export default defineEventHandler((event) => {
export default defineEventHandler(async (event) => {
const query = getQuery(event)
const sensor = String(query.sensor ?? 'hn-stadtgalerie-01')
const horizon = String(query.horizon ?? '7d') as Horizon
const scenario = String(query.scenario ?? 'base') as Scenario
const forecast = getMockForecast(sensor)
const sensor = sensorParam(query.sensor)
const horizon = enumParam<Horizon>(query.horizon, HORIZONS, 'horizon', '7d')
const scenario = enumParam<Scenario>(query.scenario, SCENARIOS, 'scenario', 'base')
if (!forecast) {
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
}
if (!HORIZONS.includes(horizon)) {
throw createError({ statusCode: 400, statusMessage: `Invalid horizon: ${horizon}` })
}
if (!SCENARIOS.includes(scenario)) {
throw createError({ statusCode: 400, statusMessage: `Invalid scenario: ${scenario}` })
if (isMockMode()) {
const forecast = getMockForecast(sensor)
if (!forecast) {
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
}
const points = applyScenario(forecast.points, scenario)
const limit = horizon === '15m' ? 1 : horizon === '1h' ? 4 : horizon === '48h' ? 48 : points.length
return {
...forecast,
horizon,
scenario,
points: points.slice(0, limit),
cached: false,
}
}
const points = applyScenario(forecast.points, scenario)
const limit = horizon === '15m' ? 1 : horizon === '1h' ? 4 : horizon === '48h' ? 48 : points.length
return {
...forecast,
horizon,
scenario,
points: points.slice(0, limit),
// The mock is computed locally; it is not a cached fallback from the Go API.
cached: false,
}
return apiRequest<ForecastResponse>('/api/forecast', {
query: { sensor, horizon, scenario },
})
})
+6 -1
View File
@@ -1 +1,6 @@
export default defineEventHandler(() => ({ ok: true }))
import { apiRequest, isMockMode } from '../utils/api'
export default defineEventHandler(async () => {
if (isMockMode()) return { ok: true }
return apiRequest<{ ok: boolean }>('/api/healthz')
})
+6 -1
View File
@@ -1,3 +1,8 @@
import type { MetaResponse } from '../../shared/types'
import { apiRequest, isMockMode } from '../utils/api'
import { mockMeta } from '../utils/mock-data'
export default defineEventHandler(() => mockMeta)
export default defineEventHandler(async () => {
if (isMockMode()) return mockMeta
return apiRequest<MetaResponse>('/api/meta')
})
+6 -1
View File
@@ -1 +1,6 @@
export default defineEventHandler(() => ({ ok: true, data: true, model: true }))
import { apiRequest, isMockMode } from '../utils/api'
export default defineEventHandler(async () => {
if (isMockMode()) return { ok: true, data: true, model: true }
return apiRequest<{ ok: boolean; data: boolean; model: boolean }>('/api/readyz')
})
+6 -1
View File
@@ -1,3 +1,8 @@
import type { ScenarioState } from '../../shared/types'
import { apiRequest, isMockMode } from '../utils/api'
import { mockScenario } from '../utils/mock-data'
export default defineEventHandler(() => mockScenario)
export default defineEventHandler(async () => {
if (isMockMode()) return mockScenario
return apiRequest<ScenarioState>('/api/scenario')
})
+18 -6
View File
@@ -1,5 +1,6 @@
import { SCENARIOS } from '../../shared/types'
import type { Scenario, ScenarioDefinition } 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
@@ -13,10 +14,21 @@ export default defineEventHandler(async (event) => {
statusMessage: 'Invalid scenario. Expected base | sunny-saturday-market | rainy-saturday | weekday-event.',
})
}
version += 1
return {
version,
scenario: body,
at: new Date().toISOString(),
if (isMockMode()) {
version += 1
return {
version,
scenario: body,
at: new Date().toISOString(),
}
}
// Control credentials are attached in the server process, never in the
// browser. Go returns 503 until CONTROL_USER/CONTROL_PASS are configured.
return apiRequest<ScenarioState>('/api/scenario', {
method: 'POST',
body,
control: true,
})
})
+4 -2
View File
@@ -1,3 +1,5 @@
import { mockScenarios } from '../utils/mock-data'
import { SCENARIO_PRESETS } from '../../shared/scenarios'
export default defineEventHandler(() => mockScenarios)
// Scenario labels are UI metadata, not a Go endpoint. The forecast values and
// the scenario enum come from the API.
export default defineEventHandler(() => SCENARIO_PRESETS)
+6 -1
View File
@@ -1,3 +1,8 @@
import type { Sensor } from '../../shared/types'
import { apiRequest, isMockMode } from '../utils/api'
import { mockSensors } from '../utils/mock-data'
export default defineEventHandler(() => mockSensors)
export default defineEventHandler(async () => {
if (isMockMode()) return mockSensors
return apiRequest<Sensor[]>('/api/sensors')
})
+24 -7
View File
@@ -1,12 +1,29 @@
import type { SeriesResponse } from '../../shared/types'
import { apiRequest, enumParam, isMockMode, sensorParam } from '../utils/api'
import { getMockSeries } from '../utils/mock-data'
export default defineEventHandler((event) => {
const STEPS = ['15m', '1h'] as const
export default defineEventHandler(async (event) => {
const query = getQuery(event)
const sensor = String(query.sensor ?? 'hn-stadtgalerie-01')
const series = getMockSeries(sensor)
if (!series) {
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
const sensor = sensorParam(query.sensor)
if (isMockMode()) {
const series = getMockSeries(sensor)
if (!series) {
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
}
const step = query.step === '15m' ? '15m' : '1h'
return { ...series, step }
}
const step = query.step === '15m' ? '15m' : '1h'
return { ...series, step }
const step = query.step ? enumParam(query.step, STEPS, 'step') : undefined
return apiRequest<SeriesResponse>('/api/series', {
query: {
sensor,
step,
from: query.from,
to: query.to,
},
})
})
+27 -26
View File
@@ -1,37 +1,38 @@
import { applyScenario, buildStaffing, planWeekStart } from '../../shared/staffing'
import { planDrivers } from '../../shared/insights'
import { SCENARIOS, STANDARDS } from '../../shared/types'
import type { Scenario, Standard } from '../../shared/types'
import type { Scenario, StaffingResponse, Standard } from '../../shared/types'
import { apiRequest, enumParam, isMockMode, sensorParam } from '../utils/api'
import { getMockForecast, mockContext, mockDemo } from '../utils/mock-data'
export default defineEventHandler((event) => {
export default defineEventHandler(async (event) => {
const query = getQuery(event)
const sensor = String(query.sensor ?? 'hn-stadtgalerie-01')
const scenario = String(query.scenario ?? 'base') as Scenario
const standard = String(query.standard ?? 'standard') as Standard
const forecast = getMockForecast(sensor)
const sensor = sensorParam(query.sensor)
const scenario = enumParam<Scenario>(query.scenario, SCENARIOS, 'scenario', 'base')
const standard = enumParam<Standard>(query.standard, STANDARDS, 'standard', 'standard')
if (!forecast) {
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
}
if (!SCENARIOS.includes(scenario)) {
throw createError({ statusCode: 400, statusMessage: `Invalid scenario: ${scenario}` })
}
if (!STANDARDS.includes(standard)) {
throw createError({ statusCode: 400, statusMessage: `Invalid standard: ${standard}` })
if (isMockMode()) {
const forecast = getMockForecast(sensor)
if (!forecast) {
throw createError({ statusCode: 404, statusMessage: `Unknown sensor: ${sensor}` })
}
const weekStart = planWeekStart(mockDemo.now)
const build = buildStaffing({
sensor,
scenario,
standard,
points: applyScenario(forecast.points, scenario),
weekStart,
data_version: forecast.data_version,
model_version: forecast.model_version,
context_version: forecast.context_version,
})
build.response.why = planDrivers(build.response, mockContext, weekStart, scenario)
return build.response
}
const weekStart = planWeekStart(mockDemo.now)
const build = buildStaffing({
sensor,
scenario,
standard,
points: applyScenario(forecast.points, scenario),
weekStart,
data_version: forecast.data_version,
model_version: forecast.model_version,
context_version: forecast.context_version,
// The Go API owns the plan. The browser never computes staffing in this path.
return apiRequest<StaffingResponse>('/api/staffing', {
query: { sensor, scenario, standard },
})
build.response.why = planDrivers(build.response, mockContext, weekStart, scenario)
return build.response
})
+46 -24
View File
@@ -1,34 +1,56 @@
import { apiForward, isMockMode } from '../utils/api'
import { createMockTrainJob } from '../utils/train-jobs'
export default defineEventHandler(async (event) => {
let model: 'small' | 'forecast' = 'small'
let filename: string | null = null
if (isMockMode()) {
let model: 'small' | 'forecast' = 'small'
let filename: string | null = null
const contentType = getRequestHeader(event, 'content-type') ?? ''
if (contentType.includes('multipart/form-data')) {
const parts = await readMultipartFormData(event)
for (const part of parts ?? []) {
if (part.name === 'model' && part.data) {
const value = part.data.toString()
if (value === 'small' || value === 'forecast') model = value
}
if (part.name === 'file' && part.filename) {
filename = part.filename
const contentType = getRequestHeader(event, 'content-type') ?? ''
if (contentType.includes('multipart/form-data')) {
const parts = await readMultipartFormData(event)
for (const part of parts ?? []) {
if (part.name === 'model' && part.data) {
const value = part.data.toString()
if (value === 'small' || value === 'forecast') model = value
}
if (part.name === 'file' && part.filename) {
filename = part.filename
}
}
} else {
const body = await readBody<{ model?: 'small' | 'forecast'; path?: string }>(event).catch(() => null)
if (body?.model === 'small' || body?.model === 'forecast') model = body.model
if (body?.path) filename = body.path
}
const job = createMockTrainJob(model, filename)
setResponseStatus(event, 202)
return {
job_id: job.job_id,
status: job.status,
model: job.model,
submitted_at: job.started_at,
mock: true,
}
} else {
const body = await readBody<{ model?: 'small' | 'forecast'; path?: string }>(event).catch(() => null)
if (body?.model === 'small' || body?.model === 'forecast') model = body.model
if (body?.path) filename = body.path
}
const job = createMockTrainJob(model, filename)
setResponseStatus(event, 202)
return {
job_id: job.job_id,
status: job.status,
model: job.model,
submitted_at: job.started_at,
mock: true,
// Stream the multipart CSV to Go unchanged. The control credentials are
// attached by the Nitro process and never reach the browser bundle.
const contentType = getRequestHeader(event, 'content-type') ?? ''
if (!contentType) {
throw createError({
statusCode: 400,
statusMessage: 'Content-Type must be application/json or multipart/form-data',
})
}
const body = await readRawBody(event)
return apiForward(event, '/api/train', {
method: 'POST',
body,
headers: { 'content-type': contentType },
control: true,
timeoutMs: 60_000,
})
})
+14 -5
View File
@@ -1,10 +1,19 @@
import { apiRequest, isMockMode } from '../../utils/api'
import { getMockTrainJob } from '../../utils/train-jobs'
export default defineEventHandler((event) => {
export default defineEventHandler(async (event) => {
const jobId = getRouterParam(event, 'jobId')
const job = jobId ? getMockTrainJob(jobId) : undefined
if (!job) {
throw createError({ statusCode: 404, statusMessage: `Unknown training job: ${jobId}` })
if (!jobId) {
throw createError({ statusCode: 400, statusMessage: 'jobId is required' })
}
return job
if (isMockMode()) {
const job = getMockTrainJob(jobId)
if (!job) {
throw createError({ statusCode: 404, statusMessage: `Unknown training job: ${jobId}` })
}
return job
}
return apiRequest(`/api/train/${encodeURIComponent(jobId)}`, { control: true })
})
+178
View File
@@ -0,0 +1,178 @@
// Server-side Go API client. Every Nitro route uses this module so the browser
// only ever talks to the Nuxt origin: the Go base URL and the control
// credentials stay in the Node process.
interface ApiErrorEnvelope {
error?: { code?: string; message?: string }
message?: string
statusMessage?: string
}
export interface ApiRequestOptions {
query?: Record<string, unknown>
method?: 'GET' | 'POST'
/** Raw request body, forwarded unchanged (multipart training uploads). */
body?: any
headers?: Record<string, string>
/** Attach CONTROL_USER/CONTROL_PASS as Basic auth. */
control?: boolean
timeoutMs?: number
}
const DEFAULT_API_BASE = 'http://localhost:8080'
function envValue(...names: string[]): string {
for (const name of names) {
const value = process.env[name]
if (value !== undefined && value !== '') return value
}
return ''
}
/** Runtime Go base URL. Reads the env directly so K8s can override the build. */
export function apiBaseUrl(): string {
const config = useRuntimeConfig()
return (
envValue('NUXT_API_INTERNAL_BASE', 'NUXT_API_BASE', 'NUXT_PUBLIC_API_BASE') ||
String(config.apiBase ?? '') ||
DEFAULT_API_BASE
).replace(/\/+$/, '')
}
/** True only when NUXT_USE_MOCK=1 / NUXT_PUBLIC_USE_MOCK=1 is set. */
export function isMockMode(): boolean {
const config = useRuntimeConfig()
const raw =
envValue('NUXT_USE_MOCK', 'NUXT_PUBLIC_USE_MOCK') || String(config.useMock ?? '')
return raw === '1' || raw.toLowerCase() === 'true'
}
function controlAuthorization(): string | undefined {
const config = useRuntimeConfig()
const user = envValue('CONTROL_USER', 'NUXT_CONTROL_USER') || String(config.controlUser ?? '')
const pass = envValue('CONTROL_PASS', 'NUXT_CONTROL_PASS') || String(config.controlPass ?? '')
if (user && pass) return `Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`
const token = envValue('CONTROL_TOKEN', 'NUXT_CONTROL_TOKEN') || String(config.controlToken ?? '')
// Go currently validates Basic auth; Bearer is accepted here for the future
// token-based control surface without exposing the token to the browser.
if (token) return `Bearer ${token}`
return undefined
}
function timeoutMs(override?: number): number {
if (override && Number.isFinite(override)) return override
const configured = Number(
envValue('NUXT_API_TIMEOUT_MS') || useRuntimeConfig().apiTimeoutMs,
)
return Number.isFinite(configured) && configured > 0 ? configured : 8000
}
function upstreamError(error: unknown): never {
const err = error as {
status?: number
statusCode?: number
data?: ApiErrorEnvelope
message?: string
code?: string
}
const status = err.status ?? err.statusCode
if (status && status >= 400 && status < 600) {
const message =
err.data?.error?.message ?? err.data?.message ?? err.message ?? 'Go API request failed'
throw createError({ statusCode: status, statusMessage: message, data: err.data })
}
const reason = err.code === 'ETIMEDOUT' ? 'timed out' : 'unreachable'
throw createError({
statusCode: 502,
statusMessage: `Go API ${reason} at ${apiBaseUrl()}`,
})
}
/**
* Call the Go API and return its JSON body. Non-2xx responses are converted to
* H3 errors carrying the upstream status, so the UI sees a real 400/404/503.
*/
export async function apiRequest<T>(path: string, options: ApiRequestOptions = {}): Promise<T> {
const headers: Record<string, string> = { accept: 'application/json', ...options.headers }
if (options.control) {
const authorization = controlAuthorization()
if (authorization) headers.authorization = authorization
}
const response = await $fetch
.raw<T>(`${apiBaseUrl()}${path}`, {
method: options.method ?? 'GET',
query: options.query,
body: options.body,
headers,
timeout: timeoutMs(options.timeoutMs),
})
.catch((error) => upstreamError(error))
if (response.status >= 400) {
const body = response._data as ApiErrorEnvelope | undefined
const message =
body?.error?.message ?? body?.message ?? `Go API returned ${response.status}`
throw createError({ statusCode: response.status, statusMessage: message, data: body })
}
return response._data as T
}
/**
* Forward a request body (training upload) and preserve Go's status code and
* JSON body, including 202/400/409/502 responses that are part of the flow.
*/
export async function apiForward<T>(
event: import('h3').H3Event,
path: string,
options: ApiRequestOptions = {},
): Promise<T> {
const headers: Record<string, string> = { accept: 'application/json', ...options.headers }
if (options.control) {
const authorization = controlAuthorization()
if (authorization) headers.authorization = authorization
}
const response = await $fetch
.raw<T>(`${apiBaseUrl()}${path}`, {
method: options.method ?? 'POST',
query: options.query,
body: options.body,
headers,
timeout: timeoutMs(options.timeoutMs),
})
.catch((error) => upstreamError(error))
setResponseStatus(event, response.status)
return response._data as T
}
/** Validate an enum-like query value before it reaches the Go API. */
export function enumParam<T extends string>(
value: unknown,
allowed: readonly T[],
name: string,
fallback?: T,
): T {
if (value === undefined || value === '') {
if (fallback !== undefined) return fallback
throw createError({ statusCode: 400, statusMessage: `${name} is required` })
}
const candidate = String(value) as T
if (!allowed.includes(candidate)) {
throw createError({
statusCode: 400,
statusMessage: `Invalid ${name}: ${candidate}. Expected ${allowed.join(' | ')}.`,
})
}
return candidate
}
export function sensorParam(value: unknown, fallback = 'hn-stadtgalerie-01'): string {
const sensor = value === undefined || value === '' ? fallback : String(value)
if (!sensor) throw createError({ statusCode: 400, statusMessage: 'sensor is required' })
return sensor
}
-3
View File
@@ -5,7 +5,6 @@ import context from '../../mock/context.json'
import demo from '../../mock/demo.json'
import meta from '../../mock/meta.json'
import scenario from '../../mock/scenario.json'
import scenarios from '../../mock/scenarios.json'
import sensors from '../../mock/sensors.json'
import forecast01 from '../../mock/forecast/hn-stadtgalerie-01.json'
@@ -30,7 +29,6 @@ import type {
ContextResponse,
ForecastResponse,
MetaResponse,
ScenarioPreset,
ScenarioState,
Sensor,
SeriesResponse,
@@ -39,7 +37,6 @@ import type {
export const mockMeta = meta as MetaResponse
export const mockContext = context as ContextResponse
export const mockSensors = sensors as Sensor[]
export const mockScenarios = scenarios as ScenarioPreset[]
export const mockScenario = scenario as ScenarioState
export const mockDemo = demo as {
now: string
+39
View File
@@ -0,0 +1,39 @@
import type { ScenarioPreset } from './types'
/**
* Demo scenario metadata shown in the UI. The scenario enum and the forecast
* perturbation itself live in the Go/ML services; this list only supplies the
* labels and the narrative used on /plan and /simulate.
*/
export const SCENARIO_PRESETS: ScenarioPreset[] = [
{
id: 'base',
label: 'Base week',
short: 'Base',
description: 'Normal week, latest forecast weather.',
weather: { temp_delta_c: 0, precip_mm: 0 },
},
{
id: 'sunny-saturday-market',
label: 'Sunny Saturday + market',
short: 'Sun + market',
description: 'Dry, mild Saturday with a market event; the API applies the forecast uplift.',
weather: { temp_delta_c: 4, precip_mm: 0 },
event: { type: 'market', uplift: 0.2 },
},
{
id: 'rainy-saturday',
label: 'Rainy Saturday',
short: 'Rainy Sat',
description: 'Steady rain on Saturday; the API applies the forecast reduction.',
weather: { temp_delta_c: -2, precip_mm: 3.2 },
},
{
id: 'weekday-event',
label: 'Wednesday evening event',
short: 'Wed event',
description: 'Evening event nearby; the API applies the weekday event uplift.',
weather: { temp_delta_c: 0, precip_mm: 0 },
event: { type: 'concert', uplift: 0.25 },
},
]
+4 -4
View File
@@ -222,10 +222,10 @@ export function buildStaffing(input: BuildStaffingInput): StaffingBuild {
const covered = hours.filter((h) => h.scheduled_staff >= h.required_staff).length
const coveragePct = hours.length ? Math.round((covered / hours.length) * 1000) / 10 : 0
const cost = hours.reduce((sum, h) => sum + h.scheduled_staff * assumptions.labor_cost_eur_h, 0)
const flatCost = Object.values(byDate).reduce((sum, dayHours) => {
const peak = dayHours.length ? Math.max(...dayHours.map((h) => h.required_staff)) : 0
return sum + peak * dayHours.length * assumptions.labor_cost_eur_h
}, 0)
// CONTRACT.md §5: the flat schedule applies max(required) to every store
// hour. Go uses one global peak, not one peak per day; keep this identical.
const peakRequired = hours.reduce((peak, hour) => Math.max(peak, hour.required_staff), 0)
const flatCost = peakRequired * hours.length * assumptions.labor_cost_eur_h
return {
response: {
+39
View File
@@ -0,0 +1,39 @@
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { berlinParts, buildStaffing } from '../shared/staffing'
import type { StaffingResponse } from '../shared/types'
// Captured from the real Go API:
// curl 'http://localhost:8080/api/staffing?sensor=hn-stadtgalerie-01&scenario=base&standard=standard'
// with api-go.git/main/testdata/data as DATA_DIR.
const fixture = JSON.parse(
readFileSync(new URL('./fixtures/go-staffing.json', import.meta.url), 'utf8'),
) as StaffingResponse
describe('Go /api/staffing parity', () => {
it('rebuilds the API plan from its own hourly forecast', () => {
const firstHour = fixture.hours[0]
expect(firstHour).toBeDefined()
const build = buildStaffing({
sensor: fixture.sensor,
scenario: fixture.scenario,
standard: fixture.standard,
points: fixture.hours.map((hour) => ({ t: hour.t, v: hour.footfall })),
weekStart: berlinParts(firstHour!.t).date,
data_version: fixture.data_version,
model_version: fixture.model_version,
context_version: fixture.context_version,
})
expect(build.response.assumptions).toEqual(fixture.assumptions)
expect(build.response.summary).toEqual(fixture.summary)
expect(build.response.shifts).toEqual(fixture.shifts)
// The API returns float footfall; the local display type rounds it. Every
// decision field must still be identical.
const decision = (hours: StaffingResponse['hours']) =>
hours.map(({ footfall: _footfall, ...rest }) => rest)
expect(decision(build.response.hours)).toEqual(decision(fixture.hours))
})
})
+1
View File
@@ -0,0 +1 @@
{"sensor":"hn-stadtgalerie-01","scenario":"base","standard":"standard","assumptions":{"visitors_per_staff_hour":25,"safety_factor":1.15,"min_staff":1,"shift_length_h":4,"labor_cost_eur_h":16,"store_hours":{"open":"10:00","close":"20:00","tz":"Europe/Berlin"}},"hours":[{"t":"2026-11-16T09:00:00Z","footfall":30.2,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-16T10:00:00Z","footfall":30.4,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-16T11:00:00Z","footfall":30.6,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-16T12:00:00Z","footfall":28.4,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-16T13:00:00Z","footfall":23.1,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-16T14:00:00Z","footfall":24.2,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-16T15:00:00Z","footfall":25.7,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-16T16:00:00Z","footfall":26.3,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-16T17:00:00Z","footfall":28.3,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-16T18:00:00Z","footfall":26.4,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-17T09:00:00Z","footfall":30.5,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-17T10:00:00Z","footfall":28.7,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-17T11:00:00Z","footfall":30.4,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-17T12:00:00Z","footfall":29.3,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-17T13:00:00Z","footfall":23.1,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-17T14:00:00Z","footfall":25,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-17T15:00:00Z","footfall":23,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-17T16:00:00Z","footfall":25.7,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-17T17:00:00Z","footfall":28.5,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-17T18:00:00Z","footfall":25.7,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-18T09:00:00Z","footfall":31,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-18T10:00:00Z","footfall":28.1,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-18T11:00:00Z","footfall":30.8,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-18T12:00:00Z","footfall":30.6,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-18T13:00:00Z","footfall":22.2,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-18T14:00:00Z","footfall":24.7,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-18T15:00:00Z","footfall":25.4,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-18T16:00:00Z","footfall":26.5,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-18T17:00:00Z","footfall":29.1,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-18T18:00:00Z","footfall":29.5,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-19T09:00:00Z","footfall":29.3,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-19T10:00:00Z","footfall":31.2,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-19T11:00:00Z","footfall":27.7,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-19T12:00:00Z","footfall":28.4,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-19T13:00:00Z","footfall":24.7,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-19T14:00:00Z","footfall":22.5,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-19T15:00:00Z","footfall":22.8,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-19T16:00:00Z","footfall":25.7,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-19T17:00:00Z","footfall":29.2,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-19T18:00:00Z","footfall":26.9,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-20T09:00:00Z","footfall":28,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-20T10:00:00Z","footfall":29.7,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-20T11:00:00Z","footfall":28.2,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-20T12:00:00Z","footfall":28.7,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-20T13:00:00Z","footfall":25.5,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-20T14:00:00Z","footfall":23.4,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-20T15:00:00Z","footfall":25.4,"required_staff":2,"scheduled_staff":2,"coverage":"ok"},{"t":"2026-11-20T16:00:00Z","footfall"Line truncated
+28
View File
@@ -62,6 +62,34 @@ describe('buildStaffing', () => {
expect(build.response.summary.overstaffed_hours).toBeGreaterThan(0)
expect(build.response.summary.understaffed_hours).toBe(0)
})
it('compares the flat schedule against the global peak, matching the Go API', () => {
// Monday needs 5, Tuesday needs 10. CONTRACT §5 applies max(required) to
// every hour: 10 * 20 h * €16 = €3200, not a per-day peak sum.
const points = [
...mondayPoints(100).map((point, index) => ({
...point,
t: new Date(Date.UTC(2026, 10, 15, 23 + index)).toISOString().replace('.000Z', 'Z'),
})),
...mondayPoints(200).map((point, index) => ({
...point,
t: new Date(Date.UTC(2026, 10, 16, 23 + index)).toISOString().replace('.000Z', 'Z'),
})),
]
const build = buildStaffing({
sensor: 'hn-stadtgalerie-01',
scenario: 'base',
standard: 'standard',
points,
weekStart: '2026-11-16',
data_version: 'data',
model_version: 'model',
context_version: 'context',
})
expect(build.response.summary.flat_schedule_cost_eur).toBe(3200)
expect(build.response.summary.cost_eur).toBe(2400)
})
})
describe('applyScenario', () => {