feat: build Onyx SSR shell and plan hero with mock data

This commit is contained in:
Noel Sabia committed 2026-11-14 05:17:36 +01:00
1 parent 84c20992f9
commit 2db494fb10
34 files changed
+3197 -2

No files matched your search

+70
View File
@@ -0,0 +1,70 @@
<script setup lang="ts">
import {
iconCalendar,
iconChart,
iconCircleInformation,
iconFlash,
iconHome,
} from '@sit-onyx/icons'
const route = useRoute()
const navigation = [
{ to: '/', label: 'Now', icon: iconHome },
{ to: '/forecast', label: 'Forecast', icon: iconChart },
{ to: '/plan', label: 'Plan', icon: iconCalendar },
{ to: '/simulate', label: 'Simulate', icon: iconFlash },
{ to: '/about', label: 'About', icon: iconCircleInformation },
]
const activeLabel = computed(
() => navigation.find((item) => item.to === route.path)?.label ?? 'PulseCast',
)
</script>
<template>
<OnyxAppLayout>
<template #navBar>
<OnyxNavBar app-name="PulseCast" logo-url="/logo.svg" mobile="sm">
<OnyxUnstableNavButton
v-for="item in navigation"
:key="item.to"
:link="item.to"
:label="item.label"
:icon="item.icon"
/>
<template #contextArea>
<OnyxBadge color="warning">Mock data</OnyxBadge>
</template>
<template #mobileActivePage>{{ activeLabel }}</template>
</OnyxNavBar>
</template>
<OnyxPageLayout>
<NuxtPage />
<template #footer>
<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
</span>
</footer>
</template>
</OnyxPageLayout>
</OnyxAppLayout>
</template>
<style scoped>
.app-footer {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: var(--onyx-density-sm);
width: 100%;
max-width: 1440px;
margin-inline: auto;
padding-block: var(--onyx-density-sm);
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.8125rem;
}
</style>
+555
View File
@@ -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;
}
}
+33
View File
@@ -0,0 +1,33 @@
<script setup lang="ts">
withDefaults(
defineProps<{
label: string
value: string
hint?: string
badge?: string
badgeColor?: 'neutral' | 'danger' | 'success' | 'primary' | 'warning' | 'info'
icon?: string
}>(),
{ badgeColor: 'neutral' },
)
</script>
<template>
<OnyxCard class="stat-card">
<p class="stat-label">
<OnyxIcon v-if="icon" :icon="icon" size="16px" color="primary" />
{{ label }}
</p>
<p class="stat-value">{{ value }}</p>
<OnyxBadge v-if="badge" :color="badgeColor" density="compact">{{ badge }}</OnyxBadge>
<p v-if="hint" class="stat-hint">{{ hint }}</p>
</OnyxCard>
</template>
<style scoped>
.stat-label {
display: flex;
align-items: center;
gap: 0.35rem;
}
</style>
+57
View File
@@ -0,0 +1,57 @@
<script setup lang="ts">
import type { Sensor } from '#shared/types'
const props = defineProps<{
sensors: Sensor[]
activeId: string
}>()
const emit = defineEmits<{
select: [sensorId: string]
}>()
const bounds = computed(() => {
const lats = props.sensors.map((sensor) => sensor.lat)
const lons = props.sensors.map((sensor) => sensor.lon)
const pad = 0.0009
return {
minLat: Math.min(...lats) - pad,
maxLat: Math.max(...lats) + pad,
minLon: Math.min(...lons) - pad,
maxLon: Math.max(...lons) + pad,
}
})
function position(sensor: Sensor) {
const { minLat, maxLat, minLon, maxLon } = bounds.value
const x = ((sensor.lon - minLon) / (maxLon - minLon)) * 76 + 12
const y = ((maxLat - sensor.lat) / (maxLat - minLat)) * 52 + 30
return { left: `${x}%`, top: `${y}%` }
}
</script>
<template>
<div class="map-frame" role="group" aria-label="Schematic map of the eight Heilbronn sensors">
<div class="map-frame__label">
<OnyxBadge color="info" density="compact">Schematic</OnyxBadge>
<p class="small muted" style="margin: 0.35rem 0 0">
Relative sensor positions in the 580 m cluster. Not a city-wide heatmap.
</p>
</div>
<button
v-for="(sensor, index) in props.sensors"
:key="sensor.id"
type="button"
class="sensor-pin"
:class="{ 'sensor-pin--active': sensor.id === props.activeId }"
:style="position(sensor)"
:aria-label="`${sensor.name}: mean ${sensor.mean}, p95 ${sensor.p95}`"
:aria-pressed="sensor.id === props.activeId"
@click="emit('select', sensor.id)"
>
<span class="sensor-pin__dot">{{ index + 1 }}</span>
<span class="sensor-pin__name">{{ sensor.name }}</span>
</button>
</div>
</template>
+151
View File
@@ -0,0 +1,151 @@
<script setup lang="ts">
import { iconUpload } from '@sit-onyx/icons'
interface TrainResponse {
job_id: string
status: string
model: 'small' | 'forecast'
submitted_at: string
mock?: boolean
}
interface TrainJob {
job_id: string
status: 'queued' | 'running' | 'succeeded' | 'failed'
model: 'small' | 'forecast'
metrics: Record<string, number | string> | null
model_version: string | null
error: string | null
}
const file = ref<File | null>(null)
const model = ref<'small' | 'forecast'>('small')
const submitting = ref(false)
const polling = ref(false)
const job = ref<TrainJob | null>(null)
const errorMessage = ref('')
let pollTimer: ReturnType<typeof setInterval> | undefined
const modelOptions = [
{ label: 'Small busy classifier (fast demo)', value: 'small' },
{ label: 'Global forecast model (slower)', value: 'forecast' },
]
const statusColor = computed(() => {
switch (job.value?.status) {
case 'succeeded':
return 'success' as const
case 'failed':
return 'danger' as const
case 'running':
return 'info' as const
default:
return 'neutral' as const
}
})
async function poll(jobId: string) {
polling.value = true
let attempts = 0
pollTimer = setInterval(async () => {
attempts += 1
try {
const result = await $fetch<TrainJob>(`/api/train/${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.'
}
}
}, 700)
}
async function submit() {
errorMessage.value = ''
job.value = null
submitting.value = true
try {
const formData = new FormData()
formData.append('model', model.value)
if (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.'
} finally {
submitting.value = false
}
}
onBeforeUnmount(() => {
if (pollTimer) clearInterval(pollTimer)
})
</script>
<template>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Train new data</OnyxHeadline>
<OnyxBadge color="warning" density="compact">P1 mock</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.
</p>
<form class="form-grid" @submit.prevent="submit">
<OnyxFileUpload
v-model="file"
label="Training CSV"
message="Optional in the mock."
: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"
list-label="Available models"
:options="modelOptions"
/>
<div class="form-actions">
<OnyxButton
type="submit"
label="Start training"
:icon="iconUpload"
:loading="submitting || polling"
/>
<span v-if="submitting" class="small muted">Submitting…</span>
</div>
</form>
<p v-if="errorMessage" class="small" style="color: var(--onyx-color-text-icons-danger-intense)">
{{ errorMessage }}
</p>
<div v-if="job" class="train-status">
<OnyxBadge :color="statusColor">{{ job.status }}</OnyxBadge>
<span class="small muted">Job {{ job.job_id }} · {{ job.model }}</span>
<OnyxBadge v-if="job.model_version" color="neutral" density="compact">
{{ job.model_version }}
</OnyxBadge>
</div>
<dl v-if="job?.metrics" class="metric-list" style="margin-top: var(--onyx-density-md)">
<div v-for="(value, key) in job.metrics" :key="key">
<dt>{{ key }}</dt>
<dd>{{ value }}</dd>
</div>
</dl>
<p v-if="job?.error" class="small" style="color: var(--onyx-color-text-icons-danger-intense)">
{{ job.error }}
</p>
</OnyxCard>
</template>
+25
View File
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { iconCloud, iconSunny } from '@sit-onyx/icons'
import type { DailyWeather } from '#shared/insights'
import { formatShortDate, formatWeekdayShort } from '~/utils/format'
const props = defineProps<{
days: DailyWeather[]
}>()
function iconFor(kind: DailyWeather['kind']) {
return kind === 'sunny' || kind === 'partly-cloudy' ? iconSunny : iconCloud
}
</script>
<template>
<div class="weather-strip" role="list" aria-label="Weather forecast for the plan week">
<div v-for="day in props.days" :key="day.date" class="weather-day" role="listitem">
<strong>{{ formatWeekdayShort(day.date) }} {{ formatShortDate(day.date) }}</strong>
<OnyxIcon :icon="iconFor(day.kind)" size="24px" color="primary" />
<span>{{ Math.round(day.tempMin) }}–{{ Math.round(day.tempMax) }} °C</span>
<span class="muted">{{ day.precipMm.toFixed(1) }} mm</span>
<span class="muted">{{ Math.round(day.cloudPct) }}% cloud</span>
</div>
</div>
</template>
+143
View File
@@ -0,0 +1,143 @@
<script setup lang="ts">
import { iconCircleInformation, iconShieldUser, iconTriangleWarning } from '@sit-onyx/icons'
import type { MetaResponse } from '#shared/types'
import { formatDate, formatDateTime, formatPercent } from '~/utils/format'
useHead({ title: 'About the data and limits — PulseCast' })
const { data: meta } = await useFetch<MetaResponse>('/api/meta')
</script>
<template>
<div class="page page-stack">
<header class="page-header">
<div>
<p class="eyebrow">About · method, data and limits</p>
<OnyxHeadline is="h1">A decision aid, not a city-wide truth.</OnyxHeadline>
<p class="lede">
PulseCast turns a footfall forecast into a next-week staffing plan. The forecast is a model output; the
staffing rule is a transparent heuristic. Both are shown, editable, and bounded.
</p>
</div>
<OnyxBadge color="warning">Hackathon prototype</OnyxBadge>
</header>
<div class="summary-grid">
<MetricCard
label="Sensors"
:value="String(meta?.coverage.sensors ?? 8)"
hint="Fixed points in a 580 m inner-city cluster."
:icon="iconCircleInformation"
/>
<MetricCard
label="Model WAPE"
:value="meta ? formatPercent(meta.metrics.wape, 1) : '—'"
:badge="meta ? `baseline ${formatPercent(meta.metrics.baseline_wape, 1)}` : undefined"
badge-color="success"
hint="Time-based holdout, not a random split."
/>
<MetricCard
label="R²"
:value="meta ? meta.metrics.r2.toFixed(3) : '—'"
:hint="meta ? `MAE ${meta.metrics.mae} devices/hour` : undefined"
/>
<MetricCard
label="Cadence"
:value="meta ? `${meta.coverage.cadence_min} min` : '—'"
:hint="meta ? `${formatDate(meta.coverage.from)} → ${formatDate(meta.coverage.to)}` : undefined"
/>
</div>
<div class="split-grid">
<div class="card-stack">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">How the plan is made</OnyxHeadline>
<OnyxBadge color="info" density="compact">transparent heuristic</OnyxBadge>
</div>
<ol class="small" style="margin: 0; padding-left: 1.2rem; display: grid; gap: var(--onyx-density-sm)">
<li>Forecast estimated devices per hour for the next 7 days.</li>
<li>Divide by visitors per staff-hour, multiply by a safety factor, round up, apply minimum staff.</li>
<li>Cover 10:00–20:00 with consecutive shift blocks; a block gets the peak requirement inside it.</li>
<li>Score coverage, cost, over/understaffed hours and compare with a flat schedule.</li>
<li>Show the weather, holiday and assumption drivers; let the manager edit and regenerate.</li>
</ol>
<div class="callout" style="margin-top: var(--onyx-density-md)">
<p class="small" style="margin: 0">
There is no POS, sales, queue, payroll or labour-cost feed. Cost is an assumption. The coverage score
is high by construction because shift blocks cover their local peak; overstaffed hours are the honest
trade-off.
</p>
</div>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Model and data coverage</OnyxHeadline>
</div>
<OnyxTable striped :table-attrs="{ style: 'min-width: 34rem' }">
<template #head>
<tr><th scope="col">Field</th><th scope="col">Value</th></tr>
</template>
<tr><th scope="row" style="text-align: left; font-weight: 600">Data version</th><td class="mono">{{ meta?.data_version ?? '—' }}</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Model version</th><td class="mono">{{ meta?.model_version ?? '—' }}</td></tr>
<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">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>
</OnyxCard>
<TrainModelCard />
</div>
<aside class="card-stack">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Limits</OnyxHeadline>
<OnyxIcon :icon="iconTriangleWarning" size="24px" color="warning" />
</div>
<ul class="why-list">
<li v-for="limit in meta?.limits ?? []" :key="limit">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
<span>{{ limit }}</span>
</li>
</ul>
<p class="small muted table-note">
Eight sensors in one pedestrian cluster cannot rank commercial zones across Heilbronn. There is no
city-wide heatmap claim here.
</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Privacy</OnyxHeadline>
<OnyxIcon :icon="iconShieldUser" size="24px" color="primary" />
</div>
<ul class="small" style="margin: 0; padding-left: 1.1rem; display: grid; gap: var(--onyx-density-xs)">
<li>No PII, MAC addresses or geolocation permission.</li>
<li>Audience sessions use a random ID only.</li>
<li>Public read-only screens; control actions are authenticated separately.</li>
<li>Raw challenge CSV and secrets stay out of this repository.</li>
</ul>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Mock status</OnyxHeadline>
</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>
<p class="small muted" style="margin: 0">
Last context update: {{ meta ? formatDateTime(meta.context_version) : '—' }}
</p>
</OnyxCard>
</aside>
</div>
</div>
</template>
+274
View File
@@ -0,0 +1,274 @@
<script setup lang="ts">
import { iconCalendar, iconChart } from '@sit-onyx/icons'
import { dailyWeather } from '#shared/insights'
import { berlinParts, planWeekStart, STANDARD_VISITORS_PER_STAFF_HOUR } from '#shared/staffing'
import type { ContextResponse, ForecastResponse, MetaResponse, Point, Scenario, ScenarioPreset, Sensor } from '#shared/types'
import { formatDate, formatNumber, formatPercent, formatShortDate, formatWeekday, formatWeekdayShort, weekLabel } from '~/utils/format'
useHead({ title: 'Forecast — PulseCast' })
const config = useRuntimeConfig()
const demoNow = String(config.public.demoNow)
const weekStart = planWeekStart(demoNow)
const weekEnd = new Date(new Date(`${weekStart}T12:00:00Z`).getTime() + 6 * 86400000)
.toISOString()
.slice(0, 10)
const sensorId = ref('hn-stadtgalerie-01')
const scenario = ref<Scenario>('base')
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: context } = await useFetch<ContextResponse>('/api/context')
const { data: meta } = await useFetch<MetaResponse>('/api/meta')
const { data: presets } = await useFetch<ScenarioPreset[]>('/api/scenarios')
const { data: forecast } = await useFetch<ForecastResponse>('/api/forecast', {
query: computed(() => ({ sensor: sensorId.value, horizon: '7d', scenario: scenario.value })),
})
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const sensorOptions = computed(() =>
(sensors.value ?? []).map((sensor) => ({ value: sensor.id, label: sensor.name })),
)
const scenarioOptions = computed(() =>
(presets.value ?? []).map((preset) => ({ value: preset.id, label: preset.label })),
)
interface DayForecast {
date: string
points: Point[]
mean: number
peak: number
peakHour: number
weather?: ReturnType<typeof dailyWeather>[string]
requiredAtPeak: number
}
const days = computed<DayForecast[]>(() => {
const grouped: Record<string, Point[]> = {}
for (const point of forecast.value?.points ?? []) {
const { date } = berlinParts(point.t)
;(grouped[date] ??= []).push(point)
}
const weather = dailyWeather(context.value?.weather.forecast ?? [])
return Object.keys(grouped)
.sort()
.map((date) => {
const points = grouped[date]!
const peakPoint = points.reduce((best, point) => (point.v > best.v ? point : best))
const mean = points.reduce((sum, point) => sum + point.v, 0) / points.length
return {
date,
points,
mean: Math.round(mean),
peak: peakPoint.v,
peakHour: berlinParts(peakPoint.t).hour,
weather: weather[date],
requiredAtPeak: Math.max(
1,
Math.ceil((peakPoint.v / STANDARD_VISITORS_PER_STAFF_HOUR.standard) * 1.15),
),
}
})
})
const weekPeak = computed(() =>
days.value.length ? days.value.reduce((best, day) => (day.peak > best.peak ? day : best)) : undefined,
)
const dayMax = computed(() => Math.max(...days.value.map((day) => day.peak), 1))
const weekWeather = computed(() =>
Object.values(dailyWeather(context.value?.weather.forecast ?? []))
.filter((day) => day.date >= weekStart && day.date <= weekEnd)
.sort((a, b) => a.date.localeCompare(b.date)),
)
const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
</script>
<template>
<div class="page page-stack">
<header class="page-header">
<div>
<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
day. The decision, shift blocks and hourly coverage are on <NuxtLink to="/plan">Plan</NuxtLink>.
</p>
</div>
<div style="min-width: 14rem">
<OnyxSelect
v-model="sensorId"
label="Sensor"
list-label="Inner-city sensors"
:options="sensorOptions"
density="compact"
/>
</div>
</header>
<OnyxCard>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Daily shape</OnyxHeadline>
<p class="small muted" style="margin: 0">
Peak estimated devices per hour. Weather is context, not a causal claim.
</p>
</div>
<div style="min-width: 15rem">
<OnyxSelect
v-model="scenario"
label="Scenario"
list-label="Demo scenarios"
:options="scenarioOptions"
density="compact"
/>
</div>
</div>
<div class="forecast-bars" role="img" aria-label="Daily peak forecast">
<div v-for="day in days" :key="day.date" class="forecast-bar">
<span class="small muted">{{ formatNumber(day.peak) }}</span>
<div class="forecast-bar__track">
<div class="forecast-bar__fill" :style="{ height: `${Math.max(4, (day.peak / dayMax) * 100)}%` }" />
</div>
<strong>{{ formatWeekdayShort(day.date) }}</strong>
<span class="small muted">{{ formatShortDate(day.date) }}</span>
</div>
</div>
<OnyxTable striped with-page-scrolling :table-attrs="{ style: 'min-width: 46rem' }" style="margin-top: var(--onyx-density-lg)">
<template #head>
<tr>
<th scope="col">Day</th>
<th scope="col">Mean</th>
<th scope="col">Peak</th>
<th scope="col">Peak hour</th>
<th scope="col">80% band at peak</th>
<th scope="col">Weather</th>
<th scope="col">Staff at peak</th>
</tr>
</template>
<tr v-for="day in days" :key="day.date">
<th scope="row" style="text-align: left; font-weight: 600">
{{ formatWeekday(day.date) }}
<span class="muted" style="font-weight: 400">{{ formatShortDate(day.date) }}</span>
<OnyxBadge v-if="day.date === weekPeak?.date" color="warning" density="compact" style="margin-left: 0.35rem">peak</OnyxBadge>
</th>
<td>{{ formatNumber(day.mean) }}</td>
<td>{{ formatNumber(day.peak) }}</td>
<td>{{ String(day.peakHour).padStart(2, '0') }}:00</td>
<td>{{ formatNumber(day.points.find((point) => point.v === day.peak)?.lo ?? 0) }}–{{ formatNumber(day.points.find((point) => point.v === day.peak)?.hi ?? 0) }}</td>
<td>
<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>
</td>
<td><OnyxBadge color="neutral" density="compact">{{ day.requiredAtPeak }}</OnyxBadge></td>
</tr>
</OnyxTable>
<p class="small muted table-note">
Scroll the table sideways on a phone for the uncertainty band and staffing columns. Weekly mean
{{ formatNumber(total) }} estimated devices/hour across open+closed hours. Staff at peak uses 25
visitors/staff-hour × 1.15; the plan can use a different standard.
</p>
</OnyxCard>
<div class="split-grid">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Weather strip</OnyxHeadline>
<OnyxBadge color="neutral" density="compact">Open-Meteo mock</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.
</p>
<p class="small muted table-note">
Weather is the main accuracy driver in the model. Holidays are context and a smaller feature.
</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Read it honestly</OnyxHeadline>
<OnyxIcon :icon="iconChart" size="24px" color="primary" />
</div>
<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>
</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;
per-hour uncertainty is real.
</span>
</li>
<li>
<OnyxIcon :icon="iconCalendar" size="16px" color="primary" />
<span>
Forecast covers {{ formatDate(days[0]?.date ?? weekStart) }} →
{{ formatDate(days[days.length - 1]?.date ?? weekEnd) }} in Europe/Berlin.
</span>
</li>
</ul>
<OnyxButton label="Turn this into a plan" link="/plan" color="primary" style="margin-top: var(--onyx-density-md)" />
</OnyxCard>
</div>
</div>
</template>
<style scoped>
.forecast-bars {
display: grid;
grid-template-columns: repeat(7, minmax(0, 1fr));
gap: var(--onyx-density-xs);
align-items: end;
min-height: 13rem;
}
.forecast-bar {
display: flex;
min-width: 0;
flex-direction: column;
align-items: center;
gap: 0.2rem;
text-align: center;
}
.forecast-bar strong {
font-size: 0.8125rem;
}
.forecast-bar__track {
display: flex;
width: 100%;
height: 8rem;
align-items: flex-end;
border-radius: 3px;
background: var(--onyx-color-base-neutral-200);
}
.forecast-bar__fill {
width: 100%;
border-radius: 3px 3px 0 0;
background: var(--onyx-color-base-primary-500);
}
@media (max-width: 576px) {
.forecast-bars {
gap: 2px;
}
.forecast-bar strong {
font-size: 0.7rem;
}
.forecast-bar .small {
font-size: 0.65rem;
}
}
</style>
+264
View File
@@ -0,0 +1,264 @@
<script setup lang="ts">
import {
iconCalendar,
iconCloud,
iconLocationPin,
iconSunny,
iconTriangleWarning,
} from '@sit-onyx/icons'
import { weatherKind } from '#shared/insights'
import { berlinParts } from '#shared/staffing'
import type { ContextResponse, MetaResponse, Sensor, SeriesResponse } from '#shared/types'
import {
formatDate,
formatDateTime,
formatNumber,
formatPercent,
formatShortDate,
formatTime,
} from '~/utils/format'
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 { data: series } = await useFetch<SeriesResponse>('/api/series', {
query: computed(() => ({ sensor: sensorId.value, step: '1h' })),
})
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const sensorOptions = computed(() =>
(sensors.value ?? []).map((sensor) => ({ value: sensor.id, label: sensor.name })),
)
const lastPoint = computed(() => series.value?.points.at(-1))
const previousPoint = computed(() => series.value?.points.at(-25))
const deltaPct = computed(() => {
if (!lastPoint.value || !previousPoint.value || previousPoint.value.v === 0) return 0
return ((lastPoint.value.v - previousPoint.value.v) / previousPoint.value.v) * 100
})
const last24 = computed(() => series.value?.points.slice(-24) ?? [])
const barMax = computed(() => Math.max(...last24.value.map((point) => point.v), 1))
const nowWeather = computed(() => context.value?.weather.now)
const weatherIcon = computed(() =>
nowWeather.value && weatherKind(nowWeather.value) === 'sunny' ? iconSunny : iconCloud,
)
const weatherLabel = computed(() => {
if (!nowWeather.value) return '—'
const kind = weatherKind(nowWeather.value)
return kind === 'sunny' ? 'Sunny' : kind === 'partly-cloudy' ? 'Partly cloudy' : kind === 'rain' ? 'Rain' : 'Cloudy'
})
const today = berlinParts(demoNow).date
const todayHoliday = computed(() => context.value?.holidays.find((holiday) => holiday.date === today))
const lastHoliday = computed(() =>
context.value?.holidays.filter((holiday) => holiday.date < today).at(-1),
)
const nextHoliday = computed(() =>
context.value?.holidays.find((holiday) => holiday.date > today),
)
const latestPulse = computed(() => {
if (!sensors.value?.length) return 0
return Math.round(sensors.value.reduce((sum, sensor) => sum + sensor.mean, 0) / sensors.value.length)
})
</script>
<template>
<div class="page page-stack">
<header class="page-header">
<div>
<p class="eyebrow">Now · replay clock {{ formatDateTime(demoNow) }}</p>
<OnyxHeadline is="h1">The pulse is in the pedestrian core.</OnyxHeadline>
<p class="lede">
Eight fixed sensors around Stadtgalerie and Kaiserstraße. This is estimated device density, not people,
and not a city-wide heatmap. The decision lives on <NuxtLink to="/plan">Plan</NuxtLink>.
</p>
</div>
<div class="hero-actions">
<OnyxBadge color="warning">Replay, not live</OnyxBadge>
<OnyxBadge color="neutral" density="compact">{{ sensors?.length ?? 8 }} sensors</OnyxBadge>
</div>
</header>
<div class="split-grid">
<div class="card-stack">
<OnyxCard>
<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>
</div>
<div style="min-width: 12rem">
<OnyxSelect
v-model="sensorId"
label="Sensor"
list-label="Inner-city sensors"
:options="sensorOptions"
density="compact"
/>
</div>
</div>
<div class="reading-row">
<p class="reading-value">{{ lastPoint ? formatNumber(lastPoint.v) : '—' }}</p>
<div>
<p style="margin: 0; font-weight: 600">estimated devices / hour</p>
<p class="small muted" style="margin: 0">
{{ activeSensor?.name }} · {{ activeSensor?.id }}
</p>
<OnyxBadge :color="deltaPct >= 0 ? 'success' : 'warning'" density="compact">
{{ deltaPct >= 0 ? '+' : '' }}{{ formatPercent(deltaPct, 0) }} vs 24 h earlier
</OnyxBadge>
</div>
</div>
<div class="bar-chart" role="img" :aria-label="`Last 24 hours for ${activeSensor?.name}`">
<div
v-for="(point, index) in last24"
:key="point.t"
class="bar-chart__bar"
:class="{ 'bar-chart__bar--now': index === last24.length - 1 }"
:style="{ height: `${Math.max(4, (point.v / barMax) * 100)}%` }"
:title="`${formatTime(point.t)} · ${point.v}`"
/>
</div>
<div class="legend" style="justify-content: space-between; margin-top: var(--onyx-density-2xs)">
<span class="small muted">{{ last24[0] ? formatTime(last24[0].t) : '—' }}</span>
<span class="small muted">{{ lastPoint ? formatDateTime(lastPoint.t) : '—' }}</span>
</div>
<p class="small muted table-note">
The CSV is static. The replay clock is {{ formatDateTime(demoNow) }}; the last measured point is
{{ lastPoint ? formatDateTime(lastPoint.t) : '—' }}. No live sensor feed is claimed.
</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Sensor cluster</OnyxHeadline>
<p class="small muted" style="margin: 0">
Select a sensor to update the reading. Bounds are relative; the basemap is the next map slice.
</p>
</div>
<OnyxBadge color="info" density="compact">580 m cluster</OnyxBadge>
</div>
<SensorClusterMap :sensors="sensors ?? []" :active-id="sensorId" @select="sensorId = $event" />
</OnyxCard>
</div>
<aside class="card-stack">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Heilbronn weather</OnyxHeadline>
<OnyxBadge color="neutral" density="compact">Open-Meteo mock</OnyxBadge>
</div>
<div class="reading-row">
<OnyxIcon :icon="weatherIcon" size="48px" color="primary" />
<div>
<p style="margin: 0; font-size: 2rem; font-weight: 700; line-height: 1">
{{ nowWeather ? `${nowWeather.temp_c} °C` : '—' }}
</p>
<p class="small muted" style="margin: 0">{{ weatherLabel }}</p>
</div>
</div>
<dl class="metric-list" style="margin-top: var(--onyx-density-md)">
<div><dt>Precipitation</dt><dd>{{ nowWeather?.precip_mm ?? '—' }} mm</dd></div>
<div><dt>Cloud cover</dt><dd>{{ nowWeather?.cloud_pct ?? '—' }}%</dd></div>
<div><dt>Wind</dt><dd>{{ nowWeather?.wind_kmh ?? '—' }} km/h</dd></div>
<div><dt>Humidity</dt><dd>{{ nowWeather?.humidity_pct ?? '—' }}%</dd></div>
</dl>
<p class="small muted table-note">
Updated {{ context ? formatDateTime(context.updated_at) : '—' }} · context
{{ context?.cached ? 'cached' : 'mock' }}
</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Holiday context</OnyxHeadline>
<OnyxIcon :icon="iconCalendar" size="24px" color="primary" />
</div>
<OnyxBadge v-if="todayHoliday" color="warning">{{ todayHoliday.name }} today</OnyxBadge>
<OnyxBadge v-else color="success">No public holiday today</OnyxBadge>
<p class="small muted" style="margin: var(--onyx-density-sm) 0 0">
<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>
</p>
<p v-if="lastHoliday" class="small muted" style="margin: var(--onyx-density-xs) 0 0">
Last: {{ lastHoliday.name }} on {{ formatShortDate(lastHoliday.date) }}.
</p>
<p class="small muted table-note">
Baden-Württemberg public holidays; used as model context, not as a causal claim.
</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">What to do next</OnyxHeadline>
<OnyxIcon :icon="iconLocationPin" size="24px" color="primary" />
</div>
<p class="small" style="margin-top: 0">
The average sensor is at <strong>{{ latestPulse }}</strong> estimated devices/hour. That is context,
not a staffing decision. Open the plan to turn next week’s forecast into shifts.
</p>
<OnyxButton label="Open the staffing plan" link="/plan" color="primary" />
</OnyxCard>
</aside>
</div>
<OnyxCard>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Eight sensors</OnyxHeadline>
<p class="small muted" style="margin: 0">Measured points, stable order by ID. Battery may be null in the API.</p>
</div>
<OnyxBadge color="neutral" density="compact">measured points only</OnyxBadge>
</div>
<OnyxTable striped with-page-scrolling :table-attrs="{ style: 'min-width: 36rem' }">
<template #head>
<tr>
<th scope="col">Sensor</th>
<th scope="col">Mean</th>
<th scope="col">P95</th>
<th scope="col">Battery</th>
<th scope="col">Source ID</th>
</tr>
</template>
<tr v-for="sensor in sensors" :key="sensor.id">
<th scope="row" style="text-align: left; font-weight: 600">
{{ sensor.name }}
<OnyxBadge v-if="sensor.id === sensorId" color="primary" density="compact" style="margin-left: 0.35rem">selected</OnyxBadge>
</th>
<td>{{ sensor.mean }}</td>
<td>{{ sensor.p95 }}</td>
<td>
<OnyxBadge :color="sensor.battery === null ? 'neutral' : sensor.battery >= 60 ? 'success' : 'warning'" density="compact">
{{ sensor.battery === null ? 'n/a' : `${sensor.battery}%` }}
</OnyxBadge>
</td>
<td class="mono">{{ sensor.id }}</td>
</tr>
</OnyxTable>
<p v-if="meta" class="small muted table-note">
Coverage {{ formatDate(meta.coverage.from) }} → {{ formatDate(meta.coverage.to) }} ·
{{ meta.coverage.cadence_min }}-min cadence · data {{ meta.data_version }} · model {{ meta.model_version }}
</p>
</OnyxCard>
<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.
</div>
</div>
</template>
+663
View File
@@ -0,0 +1,663 @@
<script setup lang="ts">
import {
iconCalendar,
iconCheck,
iconCircleInformation,
iconDownload,
iconSync,
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 { SCENARIOS } from '#shared/types'
import type {
ContextResponse,
ForecastResponse,
MetaResponse,
Scenario,
ScenarioPreset,
Sensor,
Shift,
StaffingHour,
Standard,
} from '#shared/types'
import {
formatDate,
formatDateTime,
formatEuro,
formatNumber,
formatPercent,
formatShortDate,
formatTime,
formatWeekday,
weekLabel,
} from '~/utils/format'
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)
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,
})
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: context } = await useFetch<ContextResponse>('/api/context')
const { data: meta } = await useFetch<MetaResponse>('/api/meta')
const { data: presets } = await useFetch<ScenarioPreset[]>('/api/scenarios')
const {
data: forecast,
status,
refresh,
} = await useFetch<ForecastResponse>('/api/forecast', {
query: computed(() => ({
sensor: sensorId.value,
horizon: '7d',
scenario: scenario.value,
})),
})
watch(
() => route.query.scenario,
(value) => {
if (typeof value === 'string' && SCENARIOS.includes(value as Scenario)) {
scenario.value = value as Scenario
}
},
)
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 scenarioOptions = computed(() =>
(presets.value ?? []).map((preset) => ({ value: preset.id, label: preset.label })),
)
const sensorOptions = computed(() =>
(sensors.value ?? []).map((sensor) => ({ value: sensor.id, label: sensor.name })),
)
const standardOptions = [
{ value: 'relaxed', label: 'Relaxed 35' },
{ value: 'standard', label: 'Standard 25' },
{ value: 'premium', label: 'Premium 18' },
]
const standardLabel = computed(
() =>
({
relaxed: 'relaxed · 35 visitors per staff-hour',
standard: 'standard · 25 visitors per staff-hour',
premium: 'premium · 18 visitors per staff-hour',
})[standard.value],
)
const shiftLengthOptions = [
{ value: 2, label: '2 hours' },
{ value: 3, label: '3 hours' },
{ value: 4, label: '4 hours' },
{ value: 5, label: '5 hours' },
]
const build = computed(() =>
buildStaffing({
sensor: sensorId.value,
scenario: scenario.value,
standard: standard.value,
points: forecast.value?.points ?? [],
weekStart,
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,
},
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 ?? '',
}),
)
const plan = computed(() => build.value.response)
const why = computed(() =>
context.value ? planDrivers(plan.value, context.value, weekStart, scenario.value) : [],
)
const weekWeather = computed(() => {
if (!context.value) return []
return Object.values(dailyWeather(context.value.weather.forecast))
.filter((day) => isInWeek(day.date, weekStart))
.sort((a, b) => a.date.localeCompare(b.date))
})
function maxOf<T>(items: T[], score: (item: T) => number): T | undefined {
let best: T | undefined
for (const item of items) {
if (!best || score(item) > score(best)) best = item
}
return best
}
const peakHour = computed(() => maxOf(plan.value.hours, (hour) => hour.footfall))
const peakShift = computed(() => maxOf(plan.value.shifts, (shift) => shift.staff))
const totalStaffHours = computed(() =>
plan.value.hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0),
)
const savingEur = computed(() =>
Math.max(0, plan.value.summary.flat_schedule_cost_eur - plan.value.summary.cost_eur),
)
const savingPct = computed(() => {
const flat = plan.value.summary.flat_schedule_cost_eur
return flat > 0 ? (savingEur.value / flat) * 100 : 0
})
interface DaySummary {
date: string
shifts: Shift[]
staffHours: number
peakStaff: number
cost: number
}
const daySummaries = computed<DaySummary[]>(() =>
Object.keys(build.value.byDate)
.sort()
.map((date) => {
const hours = build.value.byDate[date] ?? []
const shifts = build.value.shiftsByDate[date] ?? []
const staffHours = hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0)
return {
date,
shifts,
staffHours,
peakStaff: maxOf(hours, (hour) => hour.scheduled_staff)?.scheduled_staff ?? 0,
cost: staffHours * plan.value.assumptions.labor_cost_eur_h,
}
}),
)
const dayOptions = computed(() =>
daySummaries.value.map((day) => ({
value: day.date,
label: `${formatWeekday(day.date)} ${formatShortDate(day.date)} · ${day.peakStaff} peak`,
})),
)
const selectedHours = computed<StaffingHour[]>(() => build.value.byDate[selectedDay.value] ?? [])
const selectedCovered = computed(
() => selectedHours.value.filter((hour) => hour.scheduled_staff >= hour.required_staff).length,
)
const selectedOver = computed(
() => selectedHours.value.filter((hour) => hour.coverage === 'over').length,
)
function coverageColor(hour: StaffingHour) {
if (hour.coverage === 'under') return 'danger' as const
if (hour.coverage === 'over') return 'warning' as const
return 'success' as const
}
function coverageLabel(hour: StaffingHour) {
if (hour.coverage === 'under') return `${hour.required_staff - hour.scheduled_staff} short`
if (hour.coverage === 'over') return `+${hour.scheduled_staff - hour.required_staff} over`
return 'Covered'
}
async function generate() {
generating.value = true
try {
await refresh()
if (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
standard.value = 'standard'
}
function exportPlan() {
if (!import.meta.client) return
const rows = [
['date', 'shift_start', 'shift_end', 'staff', 'staff_hours'],
...plan.value.shifts.map((shift) => [
shift.date,
shift.start,
shift.end,
String(shift.staff),
String((Number(shift.end.slice(0, 2)) - Number(shift.start.slice(0, 2))) * shift.staff),
]),
]
const csv = rows.map((row) => row.join(',')).join('\n')
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.click()
URL.revokeObjectURL(url)
}
</script>
<template>
<div class="page page-stack">
<section class="hero" aria-labelledby="plan-headline">
<div class="hero-grid">
<div class="hero-copy">
<p class="eyebrow">Plan · {{ weekLabel(weekStart, weekEnd) }}</p>
<OnyxHeadline id="plan-headline" is="h1">
<template v-if="peakShift">
{{ formatWeekday(peakShift.date) }} peak: {{ peakShift.staff }} staff, {{ peakShift.start }}–{{ peakShift.end }}.
</template>
<template v-else>Build next week’s shift plan.</template>
</OnyxHeadline>
<p class="lede">
Forecast for <strong>{{ activeSensor?.name ?? 'Stadtgalerie' }}</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>
<div class="hero-actions">
<OnyxButton
:label="approved ? 'Plan approved' : 'Approve plan'"
:icon="approved ? iconCheck : iconCalendar"
color="primary"
@click="approved = !approved"
/>
<OnyxButton label="Export CSV" :icon="iconDownload" mode="outline" @click="exportPlan" />
<OnyxBadge v-if="approved" color="success">Approved · demo</OnyxBadge>
<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.
</p>
</div>
<div class="hero-decision">
<p class="stat-label">Peak staffing decision</p>
<p class="hero-decision__value">{{ peakShift?.staff ?? '—' }} staff</p>
<p class="hero-decision__label">
<template v-if="peakShift">
{{ formatWeekday(peakShift.date) }} {{ formatShortDate(peakShift.date) }}, {{ peakShift.start }}–{{ peakShift.end }}<br />
</template>
<template v-if="peakHour">
{{ formatWeekday(berlinParts(peakHour.t).date) }} {{ String(berlinParts(peakHour.t).hour).padStart(2, '0') }}:00
peak: {{ peakHour.footfall }} est. visitors/hour
</template>
</p>
<OnyxSeparator style="margin-block: var(--onyx-density-sm)" />
<div class="reading-row">
<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>
</div>
</div>
</div>
</section>
<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.
</div>
<section class="summary-grid" aria-label="Plan summary">
<MetricCard
label="Coverage"
:value="formatPercent(plan.summary.coverage_pct, 1)"
badge="All hours covered"
badge-color="success"
:icon="iconCheck"
hint="Shift blocks cover the block peak, so low hours are intentionally overstaffed."
/>
<MetricCard
label="Labour cost"
:value="formatEuro(plan.summary.cost_eur)"
:icon="iconUserGroup"
:hint="`${totalStaffHours} staff-hours × €${plan.assumptions.labor_cost_eur_h}/h assumption`"
/>
<MetricCard
label="vs flat schedule"
:value="`−${formatEuro(savingEur)}`"
:badge="`${formatPercent(savingPct, 0)} lower`"
badge-color="success"
:hint="`Flat schedule would cost ${formatEuro(plan.summary.flat_schedule_cost_eur)}.`"
/>
<MetricCard
label="Plan risk"
:value="`${plan.summary.overstaffed_hours} h over`"
:badge="`${plan.summary.understaffed_hours} h under`"
badge-color="success"
:hint="`${selectedOver} of ${selectedHours.length} selected-day hours are above requirement.`"
/>
</section>
<OnyxCard>
<div class="card-header">
<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.
</p>
</div>
<OnyxBadge color="info" density="compact">Mock forecast</OnyxBadge>
</div>
<div class="form-grid">
<div style="display: grid; gap: var(--onyx-density-md); grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr))">
<OnyxSelect
v-model="sensorId"
label="Store / sensor"
list-label="Inner-city sensors"
:options="sensorOptions"
:message="activeSensor ? `${activeSensor.id} · ${activeSensor.mean} mean / ${activeSensor.p95} p95` : undefined"
/>
<OnyxSelect
v-model="scenario"
label="Scenario"
list-label="Demo scenarios"
:options="scenarioOptions"
:message="activeScenario?.description"
/>
<div>
<p class="stat-label" style="margin-bottom: var(--onyx-density-xs)">Service standard</p>
<OnyxSegmentedControl
v-model="standard"
aria-label="Service standard"
:options="standardOptions"
name="service-standard"
/>
<p class="small muted" style="margin: var(--onyx-density-xs) 0 0">{{ standardLabel }}</p>
</div>
<div style="display: flex; align-items: flex-end; gap: var(--onyx-density-sm); flex-wrap: wrap">
<OnyxButton
label="Generate plan"
:icon="iconSync"
color="primary"
:loading="generating || status === 'pending'"
@click="generate"
/>
<span v-if="generatedAt" class="small muted">Updated {{ generatedAt }}</span>
</div>
</div>
<OnyxAccordion v-model="openAssumptions" type="card">
<OnyxAccordionItem id="assumptions" value="assumptions">
<template #header>
<span>
Assumptions
<span class="muted small">
· {{ visitorsPerStaffHour }} visitors/staff-h · ×{{ assumptions.safety_factor.toFixed(2) }} ·
min {{ assumptions.min_staff }}
</span>
</span>
</template>
<div class="assumption-grid">
<OnyxSlider
v-model="assumptions.safety_factor"
label="Safety factor"
:min="1"
:max="1.5"
:step="0.05"
control="input"
:message="`Higher values add buffer staff. Current ×${assumptions.safety_factor.toFixed(2)}.`"
/>
<OnyxStepper
v-model="assumptions.min_staff"
label="Minimum staff"
:min="1"
:max="10"
:step-size="1"
message="Floor applied to every open hour."
/>
<OnyxSelect
v-model="assumptions.shift_length_h"
label="Shift block length"
list-label="Shift lengths"
:options="shiftLengthOptions"
message="Blocks are scheduled independently; coverage is checked per hour."
/>
<OnyxStepper
v-model="assumptions.labor_cost_eur_h"
label="Labour cost (€/hour)"
:min="8"
:max="60"
:step-size="1"
message="Assumption only. No payroll or POS data exists."
/>
<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>
</div>
</div>
</OnyxAccordionItem>
</OnyxAccordion>
</div>
</OnyxCard>
<div class="split-grid">
<div class="card-stack">
<OnyxCard>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Recommended shifts</OnyxHeadline>
<p class="small muted" style="margin: 0">2–5 h blocks per day; staff count covers the block peak.</p>
</div>
<div class="legend">
<span class="legend__item"><span class="legend__swatch legend__swatch--over" /> over requirement</span>
<span class="legend__item"><span class="legend__swatch" /> scheduled staff</span>
</div>
</div>
<OnyxTable class="desktop-table" striped>
<template #head>
<tr>
<th scope="col">Day</th>
<th scope="col">Shift blocks (start–end · staff)</th>
<th scope="col">Staff-hours</th>
<th scope="col">Peak</th>
<th scope="col">Labour</th>
<th scope="col"><span class="onyx-visually-hidden">Inspect</span></th>
</tr>
</template>
<tr v-for="day in daySummaries" :key="day.date" :class="{ 'peak-row': day.date === peakShift?.date }">
<th scope="row" style="text-align: left; font-weight: 600">
{{ formatWeekday(day.date) }}
<span class="muted" style="font-weight: 400"> {{ formatShortDate(day.date) }}</span>
<OnyxBadge v-if="day.date === peakShift?.date" color="warning" density="compact" style="margin-left: 0.35rem">peak</OnyxBadge>
</th>
<td>
<div class="shift-tags">
<OnyxTag
v-for="shift in day.shifts"
:key="`${shift.date}-${shift.start}`"
:label="`${shift.start}–${shift.end} · ${shift.staff}`"
density="compact"
color="neutral"
/>
</div>
</td>
<td>{{ formatNumber(day.staffHours) }}</td>
<td>{{ day.peakStaff }}</td>
<td>{{ formatEuro(day.cost) }}</td>
<td>
<OnyxButton
label="Hours"
mode="plain"
density="compact"
@click="selectedDay = day.date"
/>
</td>
</tr>
</OnyxTable>
<div class="day-card-list">
<OnyxCard v-for="day in daySummaries" :key="day.date" density="compact">
<div class="day-card__header">
<p class="day-card__date">
{{ formatWeekday(day.date) }} <span class="muted">{{ formatShortDate(day.date) }}</span>
</p>
<OnyxBadge :color="day.date === peakShift?.date ? 'warning' : 'neutral'" density="compact">
{{ day.peakStaff }} peak
</OnyxBadge>
</div>
<div class="shift-tags" style="margin-top: var(--onyx-density-xs)">
<OnyxTag
v-for="shift in day.shifts"
:key="`${shift.date}-${shift.start}`"
:label="`${shift.start}–${shift.end} · ${shift.staff}`"
density="compact"
/>
</div>
<div class="day-card__metrics">
<span>{{ formatNumber(day.staffHours) }} staff-hours</span>
<span>{{ formatEuro(day.cost) }}</span>
</div>
<OnyxButton label="View hourly detail" mode="plain" density="compact" @click="selectedDay = day.date" />
</OnyxCard>
</div>
<p class="small muted table-note">
Total {{ totalStaffHours }} staff-hours · {{ formatEuro(plan.summary.cost_eur) }} at
€{{ plan.assumptions.labor_cost_eur_h }}/h · exported CSV has one row per shift block.
</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Hourly coverage</OnyxHeadline>
<p class="small muted" style="margin: 0">
{{ selectedCovered }}/{{ selectedHours.length }} open hours covered · {{ selectedOver }} over requirement
</p>
</div>
<div style="min-width: 13rem">
<OnyxSelect
v-model="selectedDay"
label="Inspect day"
list-label="Plan days"
:options="dayOptions"
density="compact"
/>
</div>
</div>
<OnyxTable striped with-page-scrolling :table-attrs="{ style: 'min-width: 34rem' }">
<template #head>
<tr>
<th scope="col">Hour</th>
<th scope="col">Forecast footfall</th>
<th scope="col">Required</th>
<th scope="col">Scheduled</th>
<th scope="col">Coverage</th>
</tr>
</template>
<tr v-for="hour in selectedHours" :key="hour.t">
<th scope="row" style="text-align: left; font-weight: 600">{{ String(berlinParts(hour.t).hour).padStart(2, '0') }}:00</th>
<td>{{ formatNumber(hour.footfall) }}</td>
<td>{{ hour.required_staff }}</td>
<td>{{ hour.scheduled_staff }}</td>
<td>
<OnyxBadge :color="coverageColor(hour)" density="compact">{{ coverageLabel(hour) }}</OnyxBadge>
</td>
</tr>
</OnyxTable>
<p class="small muted table-note">
Scheduled staff is constant inside a block. Coverage is <em>at or above</em> the service standard by
construction; the trade-off is visible as overstaffed hours. Store hours 10:00–20:00 local.
</p>
</OnyxCard>
</div>
<aside class="card-stack">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Why this plan</OnyxHeadline>
<OnyxBadge color="info" density="compact">Context</OnyxBadge>
</div>
<ul class="why-list">
<li v-for="reason in why" :key="reason">
<OnyxIcon :icon="iconCircleInformation" size="16px" color="primary" />
<span>{{ reason }}</span>
</li>
</ul>
<OnyxSeparator style="margin-block: var(--onyx-density-md)" />
<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.
</p>
<p class="small muted table-note">
{{ activeScenario?.description ?? 'Base scenario uses the mock forecast weather.' }}
</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Assumptions in this plan</OnyxHeadline>
</div>
<dl class="metric-list">
<div><dt>Service standard</dt><dd>{{ standard }}</dd></div>
<div><dt>Visitors / staff-hour</dt><dd>{{ plan.assumptions.visitors_per_staff_hour }}</dd></div>
<div><dt>Safety factor</dt><dd>×{{ plan.assumptions.safety_factor }}</dd></div>
<div><dt>Minimum staff</dt><dd>{{ plan.assumptions.min_staff }}</dd></div>
<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>
</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,
not a payroll calculation or a precise ROI.
</p>
<OnyxButton
label="Edit assumptions"
mode="plain"
density="compact"
@click="openAssumptions = ['assumptions']"
/>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Data and limits</OnyxHeadline>
</div>
<p class="small muted" style="margin-top: 0">
{{ meta?.coverage.sensors ?? 8 }} sensors · {{ meta?.coverage.cadence_min ?? 15 }}-min cadence ·
coverage {{ meta ? `${formatDate(meta.coverage.from)} → ${formatDate(meta.coverage.to)}` : '—' }}
</p>
<ul class="small muted" style="margin: var(--onyx-density-xs) 0 0; padding-left: 1.1rem">
<li v-for="limit in meta?.limits ?? []" :key="limit">{{ limit }}</li>
</ul>
</OnyxCard>
</aside>
</div>
</div>
</template>
<style scoped>
.peak-row {
background: var(--onyx-color-base-warning-100);
}
</style>
+242
View File
@@ -0,0 +1,242 @@
<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 { 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 activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const sensorOptions = computed(() =>
(sensors.value ?? []).map((sensor) => ({ value: sensor.id, label: sensor.name })),
)
const activePreset = computed(() => presets.value?.find((preset) => preset.id === scenario.value))
const radioOptions = computed(() =>
(presets.value ?? []).map((preset) => ({
value: preset.id,
label: preset.label,
description: preset.description,
})),
)
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),
)
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>) {
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)
}
return map
}
const basePeaks = computed(() => peakStaffByDay(makePlan(baseForecast.value?.points ?? [])))
const scenarioPeaks = computed(() => peakStaffByDay(scenarioBuild.value))
const days = computed(() =>
Object.keys(basePeaks.value)
.sort()
.map((date) => ({
date,
base: basePeaks.value[date] ?? 0,
scenario: scenarioPeaks.value[date] ?? 0,
})),
)
</script>
<template>
<div class="page page-stack">
<header class="page-header">
<div>
<p class="eyebrow">Simulate · {{ weekLabel(weekStart, weekEnd) }}</p>
<OnyxHeadline is="h1">Change the weather, watch the plan move.</OnyxHeadline>
<p class="lede">
A scenario changes forecast footfall, not history. Compare the shift requirement against the base week
for <strong>{{ activeSensor?.name ?? 'Stadtgalerie' }}</strong>.
</p>
</div>
<div style="min-width: 14rem">
<OnyxSelect
v-model="sensorId"
label="Sensor"
list-label="Inner-city sensors"
:options="sensorOptions"
density="compact"
/>
</div>
</header>
<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.
</div>
<div class="split-grid">
<div class="card-stack">
<OnyxCard>
<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>
</div>
<OnyxBadge color="warning" density="compact">mock simulation</OnyxBadge>
</div>
<OnyxRadioGroup
v-model="scenario"
label="Choose a scenario"
:options="radioOptions"
orientation="vertical"
/>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Day by day</OnyxHeadline>
<p class="small muted" style="margin: 0">Peak required staff per day, base vs scenario.</p>
</div>
</div>
<OnyxTable striped :table-attrs="{ style: 'min-width: 30rem' }">
<template #head>
<tr>
<th scope="col">Day</th>
<th scope="col">Base peak</th>
<th scope="col">Scenario peak</th>
<th scope="col">Δ staff</th>
</tr>
</template>
<tr v-for="day in days" :key="day.date">
<th scope="row" style="text-align: left; font-weight: 600">
{{ formatWeekday(day.date) }}
<span class="muted" style="font-weight: 400">{{ formatShortDate(day.date) }}</span>
</th>
<td>{{ day.base }}</td>
<td>{{ day.scenario }}</td>
<td>
<OnyxBadge :color="day.scenario > day.base ? 'warning' : day.scenario < day.base ? 'success' : 'neutral'" density="compact">
{{ day.scenario === day.base ? '±0' : `${day.scenario > day.base ? '+' : ''}${day.scenario - day.base}` }}
</OnyxBadge>
</td>
</tr>
</OnyxTable>
</OnyxCard>
</div>
<aside class="card-stack">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">What changes</OnyxHeadline>
<OnyxIcon :icon="iconFlash" size="24px" color="primary" />
</div>
<p style="margin-top: 0"><strong>{{ activePreset?.label ?? 'Base week' }}</strong></p>
<p class="small muted" style="margin-top: 0">{{ activePreset?.description }}</p>
<dl class="metric-list">
<div><dt>Base staff-hours</dt><dd>{{ baseHours }}</dd></div>
<div><dt>Scenario staff-hours</dt><dd>{{ scenarioHours }}</dd></div>
<div><dt>Δ staff-hours</dt><dd>{{ deltaHours >= 0 ? '+' : '' }}{{ deltaHours }}</dd></div>
<div><dt>Δ labour cost</dt><dd>{{ deltaCost >= 0 ? '+' : '' }}{{ formatEuro(deltaCost) }}</dd></div>
<div><dt>Base cost</dt><dd>{{ formatEuro(basePlan.summary.cost_eur) }}</dd></div>
<div><dt>Scenario cost</dt><dd>{{ formatEuro(scenarioPlan.summary.cost_eur) }}</dd></div>
</dl>
<div class="callout" style="margin-top: var(--onyx-density-md)">
<p class="small" style="margin: 0">
<template v-if="deltaHours > 0">
This scenario adds {{ deltaHours }} staff-hours. Check that the Saturday block can be covered before
approving.
</template>
<template v-else-if="deltaHours < 0">
This scenario removes {{ Math.abs(deltaHours) }} staff-hours. The plan gets cheaper, but check the
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.
</template>
</p>
</div>
<OnyxButton
:label="`Apply to plan`"
:icon="iconArrowRight"
icon-position="right"
color="primary"
:link="`/plan?scenario=${scenario}`"
style="margin-top: var(--onyx-density-md)"
/>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<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>
</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.
</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Context</OnyxHeadline>
</div>
<p class="small muted" style="margin-top: 0">
Weather now: {{ context?.weather.now.temp_c ?? '—' }} °C, {{ context?.weather.now.precip_mm ?? '—' }} mm
precipitation.
</p>
<p class="small muted" style="margin: 0">
{{ formatWeekdayShort(weekStart) }} {{ formatShortDate(weekStart) }} → {{ formatWeekdayShort(weekEnd) }}
{{ formatShortDate(weekEnd) }} · Europe/Berlin.
</p>
</OnyxCard>
</aside>
</div>
</div>
</template>
+7
View File
@@ -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
+99
View File
@@ -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)}`
}