From 2db494fb10c490ca9da0c281c258ffddf6cb5a09 Mon Sep 17 00:00:00 2001 From: Noel Sabia Date: Sat, 14 Nov 2026 05:17:36 +0100 Subject: [PATCH] feat: build Onyx SSR shell and plan hero with mock data --- .dockerignore | 9 + .gitignore | 1 + Dockerfile | 25 ++ README.md | 113 ++++- app/app.vue | 70 +++ app/assets/css/main.css | 555 +++++++++++++++++++++++ app/components/MetricCard.vue | 33 ++ app/components/SensorClusterMap.vue | 57 +++ app/components/TrainModelCard.vue | 151 +++++++ app/components/WeatherStrip.vue | 25 ++ app/pages/about.vue | 143 ++++++ app/pages/forecast.vue | 274 ++++++++++++ app/pages/index.vue | 264 +++++++++++ app/pages/plan.vue | 663 ++++++++++++++++++++++++++++ app/pages/simulate.vue | 242 ++++++++++ app/router.options.ts | 7 + app/utils/format.ts | 99 +++++ server/api/context.get.ts | 3 + server/api/forecast.get.ts | 34 ++ server/api/healthz.get.ts | 1 + server/api/meta.get.ts | 3 + server/api/readyz.get.ts | 1 + server/api/scenario.get.ts | 3 + server/api/scenario.post.ts | 22 + server/api/scenarios.get.ts | 3 + server/api/sensors.get.ts | 3 + server/api/series.get.ts | 12 + server/api/staffing.get.ts | 37 ++ server/api/train.post.ts | 34 ++ server/api/train/[jobId].get.ts | 10 + server/utils/mock-data.ts | 79 ++++ server/utils/train-jobs.ts | 47 ++ shared/insights.ts | 99 +++++ test/staffing.test.ts | 77 ++++ 34 files changed, 3197 insertions(+), 2 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 app/app.vue create mode 100644 app/assets/css/main.css create mode 100644 app/components/MetricCard.vue create mode 100644 app/components/SensorClusterMap.vue create mode 100644 app/components/TrainModelCard.vue create mode 100644 app/components/WeatherStrip.vue create mode 100644 app/pages/about.vue create mode 100644 app/pages/forecast.vue create mode 100644 app/pages/index.vue create mode 100644 app/pages/plan.vue create mode 100644 app/pages/simulate.vue create mode 100644 app/router.options.ts create mode 100644 app/utils/format.ts create mode 100644 server/api/context.get.ts create mode 100644 server/api/forecast.get.ts create mode 100644 server/api/healthz.get.ts create mode 100644 server/api/meta.get.ts create mode 100644 server/api/readyz.get.ts create mode 100644 server/api/scenario.get.ts create mode 100644 server/api/scenario.post.ts create mode 100644 server/api/scenarios.get.ts create mode 100644 server/api/sensors.get.ts create mode 100644 server/api/series.get.ts create mode 100644 server/api/staffing.get.ts create mode 100644 server/api/train.post.ts create mode 100644 server/api/train/[jobId].get.ts create mode 100644 server/utils/mock-data.ts create mode 100644 server/utils/train-jobs.ts create mode 100644 shared/insights.ts create mode 100644 test/staffing.test.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..1aff9b2 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +.git +.gitignore +.nuxt +.output +node_modules +coverage +test-results +*.log +.DS_Store diff --git a/.gitignore b/.gitignore index 2309cc8..59d2955 100644 --- a/.gitignore +++ b/.gitignore @@ -90,6 +90,7 @@ out # Nuxt.js build / generate output .nuxt +.output dist # Gatsby files diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a17d994 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +# Multi-stage production build for the Nuxt SSR server. +# The runtime image runs as the unprivileged `node` user. + +FROM node:22-alpine AS build +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci + +COPY . . +RUN npm run build + +FROM node:22-alpine AS runtime +WORKDIR /app + +ENV NODE_ENV=production +ENV HOST=0.0.0.0 +ENV PORT=3000 + +COPY --from=build --chown=node:node /app/.output ./.output + +USER node +EXPOSE 3000 + +CMD ["node", ".output/server/index.mjs"] diff --git a/README.md b/README.md index 9b67f35..4c34aee 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,112 @@ -# web-nuxt +# PulseCast web -Frontend with SSR and triggered via SSE to get a touch and feel \ No newline at end of file +Nuxt 4 SSR frontend for **PulseCast** — a staffing copilot that turns inner-city +footfall into a usable next-week shift plan for a Heilbronn retailer. + +The hero screen is **`/plan`**. The map, weather and forecast are supporting +evidence; the decision is the weekly plan. + +## Stack + +- Nuxt `4.6.4`, `ssr: true`, Nitro `node-server` +- `@sit-onyx/nuxt` `1.2.0` + `sit-onyx` `1.22.0` for the entire shell and UI +- Mock JSON in `mock/`, mirrored by Nitro routes in `server/api/` +- Shared plan heuristic in `shared/staffing.ts` + +Onyx is used for the navigation/app shell, page layout, cards, tables, buttons, +badges, tags, selects, segmented control, slider, stepper, accordion and file +upload. The app does not ship a parallel component design system. + +## Run + +```bash +npm ci +npm run dev # http://localhost:3000 +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 +``` + +The built SSR server can also be started directly: + +```bash +PORT=3000 node .output/server/index.mjs +``` + +## 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 | + +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: + +```text +required = ceil(max(0, footfall) / visitors_per_staff_hour * safety_factor) +required = max(required, min_staff) +``` + +Store hours are 10:00–20:00 Europe/Berlin; default blocks are 4 h; labour cost is +€16/h; the default service standard is 25 visitors per staff-hour. 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 + +- 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. + +## Docker + +```bash +docker build -t pulsecast-web . +docker run --rm -p 3000:3000 pulsecast-web +``` + +The runtime stage is `node:22-alpine`, copies only `.output/`, and runs as the +non-root `node` user. diff --git a/app/app.vue b/app/app.vue new file mode 100644 index 0000000..f40ca41 --- /dev/null +++ b/app/app.vue @@ -0,0 +1,70 @@ + + + + + diff --git a/app/assets/css/main.css b/app/assets/css/main.css new file mode 100644 index 0000000..82d940b --- /dev/null +++ b/app/assets/css/main.css @@ -0,0 +1,555 @@ +html, +body, +#__nuxt { + min-height: 100%; +} + +body { + margin: 0; + background: var(--onyx-color-base-neutral-100); +} + +.page { + width: 100%; + max-width: 1440px; + margin-inline: auto; +} + +.page-stack { + display: flex; + flex-direction: column; + gap: var(--onyx-density-xl); +} + +.page-header { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + justify-content: space-between; + gap: var(--onyx-density-md); +} + +.eyebrow { + margin: 0 0 var(--onyx-density-xs); + color: var(--onyx-color-text-icons-primary-bold); + font-size: 0.8125rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.lede { + max-width: 72ch; + margin: var(--onyx-density-sm) 0 0; + color: var(--onyx-color-text-icons-neutral-medium); + font-size: 1rem; + line-height: 1.5; +} + +.muted { + color: var(--onyx-color-text-icons-neutral-medium); +} + +.small { + font-size: 0.8125rem; + line-height: 1.45; +} + +.mono { + font-family: var(--onyx-font-family-mono); + font-size: 0.8125rem; +} + +.hero { + padding: clamp(1.25rem, 2.5vw, 2rem); + 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 42%), + linear-gradient(135deg, var(--onyx-color-base-primary-100), var(--onyx-color-base-neutral-100) 68%); +} + +.hero-grid { + display: grid; + gap: var(--onyx-density-xl); + align-items: start; +} + +.hero-copy { + display: flex; + flex-direction: column; + gap: var(--onyx-density-md); +} + +.hero-copy h1 { + max-width: 22ch; + margin: 0; +} + +.hero-copy p { + margin: 0; +} + +.hero-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--onyx-density-sm); +} + +.hero-decision { + padding: var(--onyx-density-lg); + border: 1px solid var(--onyx-color-base-primary-300); + border-radius: var(--onyx-radius-component-container-soft); + background: var(--onyx-color-base-neutral-100); +} + +.hero-decision__value { + margin: 0; + font-size: clamp(2rem, 3vw, 3rem); + font-weight: 700; + line-height: 1.05; + color: var(--onyx-color-text-icons-primary-intense); +} + +.hero-decision__label { + margin: var(--onyx-density-xs) 0 0; + color: var(--onyx-color-text-icons-neutral-medium); +} + +.summary-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--onyx-density-sm); +} + +.stat-card { + height: 100%; +} + +/* Onyx badges are flex children inside cards and otherwise stretch to full width. */ +.onyx-badge { + width: fit-content; +} + +.stat-label { + margin: 0; + color: var(--onyx-color-text-icons-neutral-medium); + font-size: 0.8125rem; + font-weight: 600; +} + +.stat-value { + margin: var(--onyx-density-xs) 0 0; + font-size: clamp(1.35rem, 2vw, 1.75rem); + font-weight: 700; + line-height: 1.15; +} + +.stat-hint { + margin: var(--onyx-density-xs) 0 0; + color: var(--onyx-color-text-icons-neutral-soft); + font-size: 0.8125rem; + line-height: 1.35; +} + +.split-grid { + display: grid; + gap: var(--onyx-density-lg); + align-items: start; +} + +.card-stack { + display: flex; + min-width: 0; + flex-direction: column; + gap: var(--onyx-density-md); +} + +/* Keep wide Onyx tables scrolling inside their card instead of widening the page + (Onyx wrappers are flex items and grid tracks default to min-width: auto). */ +.split-grid > *, +.summary-grid > *, +.onyx-card, +.onyx-table-wrapper, +.onyx-table-wrapper__container { + min-width: 0; + max-width: 100%; +} + +/* Onyx marks some wide tables as "no scroll" before layout settles. Keep the + scrollport so a phone never scrolls the whole page sideways. */ +.onyx-table-wrapper__container, +.onyx-table-wrapper__container--no-scroll { + overflow: auto; +} + +.card-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: var(--onyx-density-xs); + margin-bottom: var(--onyx-density-sm); +} + +.card-header h2, +.card-header h3 { + margin: 0; +} + +.form-grid { + display: grid; + gap: var(--onyx-density-md); +} + +.form-grid > *, +.onyx-form-element-v2, +.onyx-form-element-v2 > * { + min-width: 0; +} + +.form-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--onyx-density-sm); +} + +.assumption-grid { + display: grid; + gap: var(--onyx-density-md); +} + +.shift-tags { + display: flex; + flex-wrap: wrap; + gap: var(--onyx-density-2xs); +} + +.day-card-list { + display: none; + flex-direction: column; + gap: var(--onyx-density-sm); +} + +.day-card__header { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--onyx-density-sm); +} + +.day-card__date { + margin: 0; + font-weight: 600; +} + +.day-card__metrics { + display: flex; + flex-wrap: wrap; + gap: var(--onyx-density-sm); + margin-top: var(--onyx-density-sm); + color: var(--onyx-color-text-icons-neutral-medium); + font-size: 0.8125rem; +} + +.weather-strip { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(5.5rem, 1fr)); + gap: var(--onyx-density-2xs); + padding-bottom: var(--onyx-density-2xs); +} + +.weather-day { + display: flex; + min-width: 0; + flex-direction: column; + gap: 0.25rem; + padding: var(--onyx-density-xs); + border: 1px solid var(--onyx-color-base-neutral-300); + border-radius: var(--onyx-radius-component-container-soft); + background: var(--onyx-color-base-neutral-100); + font-size: 0.75rem; +} + +.weather-day strong { + font-size: 0.8125rem; +} + +.why-list { + display: flex; + flex-direction: column; + gap: var(--onyx-density-sm); + margin: 0; + padding: 0; + list-style: none; +} + +.why-list li { + display: flex; + gap: var(--onyx-density-xs); + align-items: flex-start; + line-height: 1.4; +} + +.why-list .onyx-icon { + flex: none; + margin-top: 0.1rem; +} + +.map-frame { + position: relative; + min-height: 320px; + overflow: hidden; + border: 1px solid var(--onyx-color-base-neutral-300); + border-radius: var(--onyx-radius-component-container-soft); + background: + linear-gradient(var(--onyx-color-base-neutral-200) 1px, transparent 1px), + linear-gradient(90deg, var(--onyx-color-base-neutral-200) 1px, transparent 1px), + var(--onyx-color-base-neutral-100); + background-size: 2.5rem 2.5rem; +} + +.map-frame__label { + position: absolute; + top: var(--onyx-density-sm); + left: var(--onyx-density-sm); + z-index: 2; + max-width: 14rem; +} + +.sensor-pin { + position: absolute; + display: flex; + flex-direction: column; + align-items: center; + gap: 0.15rem; + transform: translate(-50%, -50%); + border: 0; + background: transparent; + color: inherit; + cursor: pointer; + font: inherit; +} + +.sensor-pin__dot { + display: grid; + width: 2.25rem; + height: 2.25rem; + place-items: center; + border: 2px solid var(--onyx-color-base-neutral-100); + border-radius: 999px; + background: var(--onyx-color-base-primary-600); + color: var(--onyx-color-text-icons-neutral-inverted); + box-shadow: var(--onyx-shadow-soft-bottom); + font-size: 0.75rem; + font-weight: 700; +} + +.sensor-pin--active .sensor-pin__dot { + background: var(--onyx-color-base-primary-800); + outline: 3px solid var(--onyx-color-base-primary-300); +} + +.sensor-pin__name { + max-width: 7rem; + overflow: hidden; + padding: 0.1rem 0.3rem; + border-radius: 0.2rem; + background: color-mix(in srgb, var(--onyx-color-base-neutral-100) 88%, transparent); + font-size: 0.6875rem; + line-height: 1.2; + text-align: center; + text-overflow: ellipsis; + white-space: nowrap; +} + +.bar-chart { + display: flex; + height: 96px; + align-items: flex-end; + gap: 2px; + padding-top: var(--onyx-density-sm); +} + +.bar-chart__bar { + flex: 1; + min-width: 3px; + border-radius: 2px 2px 0 0; + background: var(--onyx-color-base-primary-500); +} + +.bar-chart__bar--now { + background: var(--onyx-color-base-primary-800); +} + +.reading-row { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: var(--onyx-density-sm); +} + +.reading-value { + margin: 0; + font-size: clamp(2.5rem, 6vw, 4rem); + font-weight: 700; + line-height: 1; +} + +.legend { + display: flex; + flex-wrap: wrap; + gap: var(--onyx-density-sm); + align-items: center; +} + +.legend__item { + display: inline-flex; + align-items: center; + gap: 0.35rem; + color: var(--onyx-color-text-icons-neutral-medium); + font-size: 0.75rem; +} + +.legend__swatch { + width: 0.75rem; + height: 0.75rem; + border-radius: 2px; + background: var(--onyx-color-base-primary-500); +} + +.legend__swatch--under { + background: var(--onyx-color-base-danger-500); +} + +.legend__swatch--over { + background: var(--onyx-color-base-warning-500); +} + +.table-note { + margin: var(--onyx-density-xs) 0 0; +} + +.callout { + padding: var(--onyx-density-sm) var(--onyx-density-md); + border-left: 3px solid var(--onyx-color-base-primary-500); + border-radius: 0 var(--onyx-radius-component-container-soft) var(--onyx-radius-component-container-soft) 0; + background: var(--onyx-color-base-primary-100); +} + +.callout--warning { + border-left-color: var(--onyx-color-base-warning-500); + background: var(--onyx-color-base-warning-100); +} + +.scenario-grid { + display: grid; + gap: var(--onyx-density-sm); +} + +.scenario-card { + cursor: pointer; +} + +.scenario-card--active { + outline: 2px solid var(--onyx-color-base-primary-500); + outline-offset: 2px; +} + +.metric-list { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--onyx-density-md); + margin: 0; +} + +.metric-list div { + min-width: 0; +} + +.metric-list dt { + color: var(--onyx-color-text-icons-neutral-medium); + font-size: 0.75rem; +} + +.metric-list dd { + margin: 0.15rem 0 0; + font-weight: 600; +} + +.train-status { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--onyx-density-sm); + margin-top: var(--onyx-density-sm); +} + +@media (min-width: 577px) { + .assumption-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@media (min-width: 769px) { + .summary-grid { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } + + .day-card-list { + display: none; + } +} + +@media (min-width: 993px) { + .hero-grid { + grid-template-columns: minmax(0, 1.65fr) minmax(18rem, 1fr); + } + + .split-grid { + grid-template-columns: minmax(0, 1.9fr) minmax(20rem, 1fr); + } + + .scenario-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@media (max-width: 768px) { + .desktop-table { + display: none; + } + + .day-card-list { + display: flex; + } +} + +@media (max-width: 576px) { + .sensor-pin__name { + display: none; + } + + .map-frame { + min-height: 360px; + } + + .card-header { + flex-direction: column; + align-items: stretch; + } + + .card-header .onyx-badge { + align-self: flex-start; + } +} + +@media print { + .hero-actions, + .form-actions, + .desktop-table { + display: none !important; + } +} diff --git a/app/components/MetricCard.vue b/app/components/MetricCard.vue new file mode 100644 index 0000000..dec4119 --- /dev/null +++ b/app/components/MetricCard.vue @@ -0,0 +1,33 @@ + + + + + diff --git a/app/components/SensorClusterMap.vue b/app/components/SensorClusterMap.vue new file mode 100644 index 0000000..a03b8b7 --- /dev/null +++ b/app/components/SensorClusterMap.vue @@ -0,0 +1,57 @@ + + + diff --git a/app/components/TrainModelCard.vue b/app/components/TrainModelCard.vue new file mode 100644 index 0000000..b8d1e76 --- /dev/null +++ b/app/components/TrainModelCard.vue @@ -0,0 +1,151 @@ + + + diff --git a/app/components/WeatherStrip.vue b/app/components/WeatherStrip.vue new file mode 100644 index 0000000..ba55608 --- /dev/null +++ b/app/components/WeatherStrip.vue @@ -0,0 +1,25 @@ + + + diff --git a/app/pages/about.vue b/app/pages/about.vue new file mode 100644 index 0000000..b0625f7 --- /dev/null +++ b/app/pages/about.vue @@ -0,0 +1,143 @@ + + + diff --git a/app/pages/forecast.vue b/app/pages/forecast.vue new file mode 100644 index 0000000..8d83821 --- /dev/null +++ b/app/pages/forecast.vue @@ -0,0 +1,274 @@ + + + + + diff --git a/app/pages/index.vue b/app/pages/index.vue new file mode 100644 index 0000000..2a662a5 --- /dev/null +++ b/app/pages/index.vue @@ -0,0 +1,264 @@ + + + diff --git a/app/pages/plan.vue b/app/pages/plan.vue new file mode 100644 index 0000000..f88dce6 --- /dev/null +++ b/app/pages/plan.vue @@ -0,0 +1,663 @@ + + + + + diff --git a/app/pages/simulate.vue b/app/pages/simulate.vue new file mode 100644 index 0000000..5a624be --- /dev/null +++ b/app/pages/simulate.vue @@ -0,0 +1,242 @@ + + + diff --git a/app/router.options.ts b/app/router.options.ts new file mode 100644 index 0000000..2f8222d --- /dev/null +++ b/app/router.options.ts @@ -0,0 +1,7 @@ +import type { RouterConfig } from '@nuxt/schema' + +// Onyx scrolls inside .onyx-page__main, not the window, so the default Nuxt +// scroll behaviour does not reach the page container. +export default { + scrollBehavior: createOnyxScrollBehavior(), +} satisfies RouterConfig diff --git a/app/utils/format.ts b/app/utils/format.ts new file mode 100644 index 0000000..960fdf2 --- /dev/null +++ b/app/utils/format.ts @@ -0,0 +1,99 @@ +import { BERLIN_TZ } from '#shared/staffing' + +const dateFormatter = new Intl.DateTimeFormat('en-GB', { + timeZone: BERLIN_TZ, + day: 'numeric', + month: 'short', + year: 'numeric', +}) + +const shortDateFormatter = new Intl.DateTimeFormat('en-GB', { + timeZone: BERLIN_TZ, + day: 'numeric', + month: 'short', +}) + +const weekdayFormatter = new Intl.DateTimeFormat('en-GB', { + timeZone: BERLIN_TZ, + weekday: 'long', +}) + +const weekdayShortFormatter = new Intl.DateTimeFormat('en-GB', { + timeZone: BERLIN_TZ, + weekday: 'short', +}) + +const dateTimeFormatter = new Intl.DateTimeFormat('en-GB', { + timeZone: BERLIN_TZ, + day: 'numeric', + month: 'short', + hour: '2-digit', + minute: '2-digit', + hourCycle: 'h23', +}) + +const timeFormatter = new Intl.DateTimeFormat('en-GB', { + timeZone: BERLIN_TZ, + hour: '2-digit', + minute: '2-digit', + hourCycle: 'h23', +}) + +const euroFormatter = new Intl.NumberFormat('en-GB', { + style: 'currency', + currency: 'EUR', + maximumFractionDigits: 0, +}) + +const numberFormatter = new Intl.NumberFormat('en-GB') + +/** Date-only strings are parsed at noon UTC so the local date never shifts. */ +function toDate(value: string): Date { + return value.length > 10 ? new Date(value) : new Date(`${value}T12:00:00Z`) +} + +function formatWith(formatter: Intl.DateTimeFormat, value: string): string { + const date = toDate(value) + return Number.isNaN(date.getTime()) ? '—' : formatter.format(date) +} + +export function formatDate(date: string): string { + return formatWith(dateFormatter, date) +} + +export function formatShortDate(date: string): string { + return formatWith(shortDateFormatter, date) +} + +export function formatWeekday(date: string): string { + return formatWith(weekdayFormatter, date) +} + +export function formatWeekdayShort(date: string): string { + return formatWith(weekdayShortFormatter, date) +} + +/** Format a wire timestamp in Heilbronn local time. */ +export function formatDateTime(iso: string): string { + return formatWith(dateTimeFormatter, iso) +} + +export function formatTime(iso: string): string { + return formatWith(timeFormatter, iso) +} + +export function formatEuro(value: number): string { + return euroFormatter.format(value) +} + +export function formatNumber(value: number): string { + return numberFormatter.format(value) +} + +export function formatPercent(value: number, digits = 0): string { + return `${value.toFixed(digits)}%` +} + +export function weekLabel(start: string, end: string): string { + return `${formatShortDate(start)} – ${formatDate(end)}` +} diff --git a/server/api/context.get.ts b/server/api/context.get.ts new file mode 100644 index 0000000..5acbc91 --- /dev/null +++ b/server/api/context.get.ts @@ -0,0 +1,3 @@ +import { mockContext } from '../utils/mock-data' + +export default defineEventHandler(() => mockContext) diff --git a/server/api/forecast.get.ts b/server/api/forecast.get.ts new file mode 100644 index 0000000..8ae7d3b --- /dev/null +++ b/server/api/forecast.get.ts @@ -0,0 +1,34 @@ +import { applyScenario } from '../../shared/staffing' +import { HORIZONS, SCENARIOS } from '../../shared/types' +import type { Horizon, Scenario } from '../../shared/types' +import { getMockForecast } from '../utils/mock-data' + +export default defineEventHandler((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) + + 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}` }) + } + + 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, + } +}) diff --git a/server/api/healthz.get.ts b/server/api/healthz.get.ts new file mode 100644 index 0000000..d7fa598 --- /dev/null +++ b/server/api/healthz.get.ts @@ -0,0 +1 @@ +export default defineEventHandler(() => ({ ok: true })) diff --git a/server/api/meta.get.ts b/server/api/meta.get.ts new file mode 100644 index 0000000..12899c9 --- /dev/null +++ b/server/api/meta.get.ts @@ -0,0 +1,3 @@ +import { mockMeta } from '../utils/mock-data' + +export default defineEventHandler(() => mockMeta) diff --git a/server/api/readyz.get.ts b/server/api/readyz.get.ts new file mode 100644 index 0000000..2d67bae --- /dev/null +++ b/server/api/readyz.get.ts @@ -0,0 +1 @@ +export default defineEventHandler(() => ({ ok: true, data: true, model: true })) diff --git a/server/api/scenario.get.ts b/server/api/scenario.get.ts new file mode 100644 index 0000000..5b950a8 --- /dev/null +++ b/server/api/scenario.get.ts @@ -0,0 +1,3 @@ +import { mockScenario } from '../utils/mock-data' + +export default defineEventHandler(() => mockScenario) diff --git a/server/api/scenario.post.ts b/server/api/scenario.post.ts new file mode 100644 index 0000000..1b2ba19 --- /dev/null +++ b/server/api/scenario.post.ts @@ -0,0 +1,22 @@ +import { SCENARIOS } from '../../shared/types' +import type { Scenario, ScenarioDefinition } from '../../shared/types' +import { mockScenario } from '../utils/mock-data' + +let version = mockScenario.version + +export default defineEventHandler(async (event) => { + const body = await readBody(event) + const scenario = body?.scenario + if (!scenario || !SCENARIOS.includes(scenario as Scenario)) { + throw createError({ + statusCode: 400, + statusMessage: 'Invalid scenario. Expected base | sunny-saturday-market | rainy-saturday | weekday-event.', + }) + } + version += 1 + return { + version, + scenario: body, + at: new Date().toISOString(), + } +}) diff --git a/server/api/scenarios.get.ts b/server/api/scenarios.get.ts new file mode 100644 index 0000000..0cced55 --- /dev/null +++ b/server/api/scenarios.get.ts @@ -0,0 +1,3 @@ +import { mockScenarios } from '../utils/mock-data' + +export default defineEventHandler(() => mockScenarios) diff --git a/server/api/sensors.get.ts b/server/api/sensors.get.ts new file mode 100644 index 0000000..d0ee596 --- /dev/null +++ b/server/api/sensors.get.ts @@ -0,0 +1,3 @@ +import { mockSensors } from '../utils/mock-data' + +export default defineEventHandler(() => mockSensors) diff --git a/server/api/series.get.ts b/server/api/series.get.ts new file mode 100644 index 0000000..0a4c580 --- /dev/null +++ b/server/api/series.get.ts @@ -0,0 +1,12 @@ +import { getMockSeries } from '../utils/mock-data' + +export default defineEventHandler((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 step = query.step === '15m' ? '15m' : '1h' + return { ...series, step } +}) diff --git a/server/api/staffing.get.ts b/server/api/staffing.get.ts new file mode 100644 index 0000000..59ee402 --- /dev/null +++ b/server/api/staffing.get.ts @@ -0,0 +1,37 @@ +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 { getMockForecast, mockContext, mockDemo } from '../utils/mock-data' + +export default defineEventHandler((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) + + 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}` }) + } + + 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 +}) diff --git a/server/api/train.post.ts b/server/api/train.post.ts new file mode 100644 index 0000000..595d1d3 --- /dev/null +++ b/server/api/train.post.ts @@ -0,0 +1,34 @@ +import { createMockTrainJob } from '../utils/train-jobs' + +export default defineEventHandler(async (event) => { + 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 + } + } + } 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, + } +}) diff --git a/server/api/train/[jobId].get.ts b/server/api/train/[jobId].get.ts new file mode 100644 index 0000000..79f9795 --- /dev/null +++ b/server/api/train/[jobId].get.ts @@ -0,0 +1,10 @@ +import { getMockTrainJob } from '../../utils/train-jobs' + +export default defineEventHandler((event) => { + const jobId = getRouterParam(event, 'jobId') + const job = jobId ? getMockTrainJob(jobId) : undefined + if (!job) { + throw createError({ statusCode: 404, statusMessage: `Unknown training job: ${jobId}` }) + } + return job +}) diff --git a/server/utils/mock-data.ts b/server/utils/mock-data.ts new file mode 100644 index 0000000..1a51aea --- /dev/null +++ b/server/utils/mock-data.ts @@ -0,0 +1,79 @@ +// Server-side mock dataset. Shapes follow /home/noel/Documents/Hackathon_2026/CONTRACT.md. +// The files are imported (not read from disk at runtime) so the Nitro build bundles them +// into the SSR output and the app renders before the Go API exists. +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' +import forecast02 from '../../mock/forecast/hn-kaiserstrasse-02.json' +import forecast03 from '../../mock/forecast/hn-marktplatz-03.json' +import forecast04 from '../../mock/forecast/hn-kilianskirche-04.json' +import forecast05 from '../../mock/forecast/hn-rathaus-05.json' +import forecast06 from '../../mock/forecast/hn-neckartor-06.json' +import forecast07 from '../../mock/forecast/hn-suelmerstrasse-07.json' +import forecast08 from '../../mock/forecast/hn-harmonie-08.json' + +import series01 from '../../mock/series/hn-stadtgalerie-01.json' +import series02 from '../../mock/series/hn-kaiserstrasse-02.json' +import series03 from '../../mock/series/hn-marktplatz-03.json' +import series04 from '../../mock/series/hn-kilianskirche-04.json' +import series05 from '../../mock/series/hn-rathaus-05.json' +import series06 from '../../mock/series/hn-neckartor-06.json' +import series07 from '../../mock/series/hn-suelmerstrasse-07.json' +import series08 from '../../mock/series/hn-harmonie-08.json' + +import type { + ContextResponse, + ForecastResponse, + MetaResponse, + ScenarioPreset, + ScenarioState, + Sensor, + SeriesResponse, +} from '../../shared/types' + +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 + plan_start: string + plan_end: string + timezone: string +} + +const forecasts: Record = { + 'hn-stadtgalerie-01': forecast01, + 'hn-kaiserstrasse-02': forecast02, + 'hn-marktplatz-03': forecast03, + 'hn-kilianskirche-04': forecast04, + 'hn-rathaus-05': forecast05, + 'hn-neckartor-06': forecast06, + 'hn-suelmerstrasse-07': forecast07, + 'hn-harmonie-08': forecast08, +} as Record + +const series: Record = { + 'hn-stadtgalerie-01': series01, + 'hn-kaiserstrasse-02': series02, + 'hn-marktplatz-03': series03, + 'hn-kilianskirche-04': series04, + 'hn-rathaus-05': series05, + 'hn-neckartor-06': series06, + 'hn-suelmerstrasse-07': series07, + 'hn-harmonie-08': series08, +} as Record + +export function getMockForecast(sensorId: string): ForecastResponse | undefined { + return forecasts[sensorId] +} + +export function getMockSeries(sensorId: string): SeriesResponse | undefined { + return series[sensorId] +} diff --git a/server/utils/train-jobs.ts b/server/utils/train-jobs.ts new file mode 100644 index 0000000..c67f5fe --- /dev/null +++ b/server/utils/train-jobs.ts @@ -0,0 +1,47 @@ +import { mockMeta } from './mock-data' + +export interface MockTrainJob { + job_id: string + status: 'queued' | 'running' | 'succeeded' | 'failed' + model: 'small' | 'forecast' + started_at: string + finished_at: string | null + metrics: Record | null + model_version: string | null + error: string | null + filename: string | null +} + +const jobs = new Map() + +export function createMockTrainJob(model: 'small' | 'forecast', filename: string | null): MockTrainJob { + const now = new Date().toISOString() + const job: MockTrainJob = { + job_id: `mock-${Date.now().toString(36)}`, + // The mock completes immediately. Replace this with polling of GET /api/train/{job_id} + // once the Go/FastAPI service exists. + status: 'succeeded', + model, + started_at: now, + finished_at: now, + metrics: + model === 'small' + ? { accuracy: 0.84, f1: 0.81, trained_rows: 12480, kind: 'busy classifier' } + : { + mae: mockMeta.metrics.mae, + wape: mockMeta.metrics.wape, + r2: mockMeta.metrics.r2, + baseline_wape: mockMeta.metrics.baseline_wape, + kind: 'global HistGB', + }, + model_version: `${mockMeta.model_version}-mock-${Date.now().toString(36)}`, + error: null, + filename, + } + jobs.set(job.job_id, job) + return job +} + +export function getMockTrainJob(jobId: string): MockTrainJob | undefined { + return jobs.get(jobId) +} diff --git a/shared/insights.ts b/shared/insights.ts new file mode 100644 index 0000000..6593498 --- /dev/null +++ b/shared/insights.ts @@ -0,0 +1,99 @@ +import { berlinParts, isInWeek } from './staffing' +import type { ContextResponse, Scenario, StaffingResponse, WeatherPoint } from './types' + +export type WeatherKind = 'sunny' | 'partly-cloudy' | 'cloudy' | 'rain' + +export interface DailyWeather { + date: string + tempMin: number + tempMax: number + precipMm: number + cloudPct: number + kind: WeatherKind +} + +export function weatherKind(point: Pick): WeatherKind { + if (point.precip_mm >= 0.5) return 'rain' + if (point.cloud_pct <= 35) return 'sunny' + if (point.cloud_pct <= 70) return 'partly-cloudy' + return 'cloudy' +} + +/** Group hourly weather into local Heilbronn days. */ +export function dailyWeather(forecast: WeatherPoint[]): Record { + const days: Record = {} + for (const point of forecast) { + const { date, hour } = berlinParts(point.t) + const day = (days[date] ??= { + date, + tempMin: point.temp_c, + tempMax: point.temp_c, + precipMm: 0, + cloudPct: 0, + kind: 'cloudy', + }) + day.tempMin = Math.min(day.tempMin, point.temp_c) + day.tempMax = Math.max(day.tempMax, point.temp_c) + day.precipMm = Math.max(day.precipMm, point.precip_mm) + // Cloud cover at midday is a better summary than the daily maximum. + if (hour >= 11 && hour <= 14) day.cloudPct = Math.max(day.cloudPct, point.cloud_pct) + } + for (const day of Object.values(days)) { + day.kind = weatherKind({ precip_mm: day.precipMm, cloud_pct: day.cloudPct }) + } + return days +} + +/** Plain-language drivers for the "why this plan" card. */ +export function planDrivers( + plan: StaffingResponse, + context: ContextResponse, + weekStart: string, + scenario: Scenario = 'base', +): string[] { + const reasons: string[] = [] + const weather = dailyWeather(context.weather.forecast) + const weekWeather = Object.values(weather).filter((day) => isInWeek(day.date, weekStart)) + + if (plan.hours.length) { + const peak = plan.hours.reduce((best, hour) => (hour.footfall > best.footfall ? hour : best)) + const parts = berlinParts(peak.t) + const weekday = new Intl.DateTimeFormat('en-GB', { weekday: 'long', timeZone: 'Europe/Berlin' }).format( + new Date(peak.t), + ) + reasons.push( + `${weekday} ${String(parts.hour).padStart(2, '0')}:00 is the forecast peak: ${peak.footfall} estimated visitors/hour needs ${peak.required_staff} staff.`, + ) + } + + if (scenario === 'base') { + const bestWeather = weekWeather + .filter((day) => day.precipMm < 0.5) + .sort((a, b) => b.tempMax - a.tempMax)[0] + if (bestWeather) { + const weekday = new Intl.DateTimeFormat('en-GB', { weekday: 'long', timeZone: 'Europe/Berlin' }).format( + new Date(`${bestWeather.date}T12:00:00Z`), + ) + reasons.push( + `Weather driver: ${weekday} is the mildest dry day (${Math.round(bestWeather.tempMax)} °C, ${bestWeather.precipMm.toFixed(1)} mm rain) in the current Open-Meteo mock.`, + ) + } + } else { + reasons.push( + `Scenario “${scenario}” applies a mock footfall perturbation. The weather strip stays the base context; it is not recomputed per scenario.`, + ) + } + + const holiday = context.holidays.find((entry) => isInWeek(entry.date, weekStart)) + reasons.push( + holiday + ? `Public holiday in this week: ${holiday.name} (${holiday.date}). Expect a different footfall shape.` + : 'No Baden-Württemberg public holiday falls inside this plan week.', + ) + + reasons.push( + `Rule: ${plan.assumptions.visitors_per_staff_hour} visitors per staff-hour × ${plan.assumptions.safety_factor} safety factor, minimum ${plan.assumptions.min_staff} staff, ${plan.assumptions.shift_length_h} h shift blocks.`, + ) + + return reasons +} diff --git a/test/staffing.test.ts b/test/staffing.test.ts new file mode 100644 index 0000000..71633e0 --- /dev/null +++ b/test/staffing.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest' +import { buildStaffing, planWeekStart, applyScenario } from '../shared/staffing' +import type { Point } from '../shared/types' + +const now = '2026-11-14T08:12:00Z' + +function mondayPoints(value = 100): Point[] { + return Array.from({ length: 24 }, (_, hour) => ({ + t: new Date(Date.UTC(2026, 10, 15, 23 + hour)).toISOString().replace('.000Z', 'Z'), + v: value, + })) +} + +describe('planWeekStart', () => { + it('returns the Monday after the demo Saturday', () => { + expect(planWeekStart(now)).toBe('2026-11-16') + }) +}) + +describe('buildStaffing', () => { + it('applies the contract heuristic to a flat 10:00-20:00 day', () => { + const build = buildStaffing({ + sensor: 'hn-stadtgalerie-01', + scenario: 'base', + standard: 'standard', + points: mondayPoints(100), + weekStart: '2026-11-16', + data_version: 'data', + model_version: 'model', + context_version: 'context', + }) + + expect(build.byDate['2026-11-16']).toHaveLength(10) + expect(build.response.shifts).toEqual([ + { date: '2026-11-16', start: '10:00', end: '14:00', staff: 5 }, + { date: '2026-11-16', start: '14:00', end: '18:00', staff: 5 }, + { date: '2026-11-16', start: '18:00', end: '20:00', staff: 5 }, + ]) + expect(build.response.summary.coverage_pct).toBe(100) + expect(build.response.summary.cost_eur).toBe(800) + expect(build.response.summary.flat_schedule_cost_eur).toBe(800) + expect(build.response.summary.understaffed_hours).toBe(0) + }) + + it('uses the block peak so low hours become overstaffed, not understaffed', () => { + const points = mondayPoints(60).map((point, index) => + index === 11 ? { ...point, v: 200 } : point, + ) + 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', + }) + const firstHour = build.byDate['2026-11-16']?.[0] + expect(firstHour?.required_staff).toBe(3) + expect(firstHour?.scheduled_staff).toBe(10) + expect(build.response.summary.overstaffed_hours).toBeGreaterThan(0) + expect(build.response.summary.understaffed_hours).toBe(0) + }) +}) + +describe('applyScenario', () => { + const saturday: Point = { t: '2026-11-21T12:00:00Z', v: 100, lo: 80, hi: 120 } + + it('raises Saturday for the sunny market scenario', () => { + expect(applyScenario([saturday], 'sunny-saturday-market')[0]?.v).toBe(120) + }) + + it('lowers Saturday for the rainy scenario', () => { + expect(applyScenario([saturday], 'rainy-saturday')[0]?.v).toBe(82) + }) +})