Files
web-nuxt/app/pages/simulate.vue
Noel Sabia 233fdbf66c feat: live SSE stage, phone view and presenter control
- proxy Go /api/stream through Nitro; drive /stage, /live, /plan and /forecast from scenario events
- fall back to 5 s polling after SSE failures or heartbeat silence; show Live/Polling/Offline
- authenticate /control and POST /api/scenario in Nitro with server-side control credentials
- add big-screen stage with local QR and a no-login phone recommendation view
- add SSE unit tests and a live smoke test; refresh README/Makefile
2026-11-14 06:59:07 +01:00

271 lines
11 KiB
Vue

<script setup lang="ts">
import { iconArrowRight, iconCircleInformation, iconFlash } from '@sit-onyx/icons'
import { addDays, berlinParts, planWeekStart } from '#shared/staffing'
import type {
ContextResponse,
Scenario,
ScenarioPreset,
Sensor,
StaffingResponse,
} from '#shared/types'
import { formatEuro, formatShortDate, formatWeekday, formatWeekdayShort, weekLabel } from '~/utils/format'
useHead({ title: 'Simulate a scenario — PulseCast' })
const config = useRuntimeConfig()
const demoNow = String(config.public.demoNow)
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: context } = await useFetch<ContextResponse>('/api/context')
const { data: presets } = await useFetch<ScenarioPreset[]>('/api/scenarios')
const sensorId = ref(
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
'hn-stadtgalerie-01',
)
const scenario = ref<Scenario>('sunny-saturday-market')
const EMPTY_PLAN: StaffingResponse = {
sensor: '',
scenario: 'base',
standard: 'standard',
assumptions: {
visitors_per_staff_hour: 25,
safety_factor: 1.15,
min_staff: 1,
shift_length_h: 4,
labor_cost_eur_h: 16,
store_hours: { open: '10:00', close: '20:00', tz: 'Europe/Berlin' },
},
hours: [],
shifts: [],
summary: {
coverage_pct: 0,
cost_eur: 0,
flat_schedule_cost_eur: 0,
overstaffed_hours: 0,
understaffed_hours: 0,
},
why: [],
cached: false,
data_version: '',
model_version: '',
context_version: '',
}
const { data: baseData } = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({ sensor: sensorId.value, scenario: 'base', standard: 'standard' })),
})
const { data: scenarioData, status } = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({ sensor: sensorId.value, scenario: scenario.value, standard: 'standard' })),
})
const basePlan = computed(() => baseData.value ?? EMPTY_PLAN)
const scenarioPlan = computed(() => scenarioData.value ?? basePlan.value)
const weekStart = computed(() => {
const first = basePlan.value.hours[0]
return first ? berlinParts(first.t).date : planWeekStart(demoNow)
})
const weekEnd = computed(() => addDays(weekStart.value, 6))
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const sensorOptions = computed(() =>
(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 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: StaffingResponse) {
const map: Record<string, number> = {}
for (const hour of plan.hours) {
const date = berlinParts(hour.t).date
map[date] = Math.max(map[date] ?? 0, hour.required_staff)
}
return map
}
const basePeaks = computed(() => peakStaffByDay(basePlan.value))
const scenarioPeaks = computed(() => peakStaffByDay(scenarioPlan.value))
const days = computed(() =>
[...new Set([...Object.keys(basePeaks.value), ...Object.keys(scenarioPeaks.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" />
The base and scenario plans are generated by Go /api/staffing. The presenter broadcasts from
<NuxtLink to="/control">/control</NuxtLink>; <NuxtLink to="/stage">/stage</NuxtLink> and
<NuxtLink to="/live">/live</NuxtLink> follow the scenario over SSE with a 5 s polling fallback.
</div>
<div class="split-grid">
<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; the API applies the perturbation.</p>
</div>
<OnyxBadge :color="status === 'pending' ? 'warning' : 'success'" density="compact">
{{ status === 'pending' ? 'loading' : 'Go API' }}
</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. 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>Base week</strong> — latest forecast weather, no scenario uplift.</span></li>
<li><span><strong>Sunny Saturday + market</strong> — Go applies the market/day uplift to next Saturday.</span></li>
<li><span><strong>Rainy Saturday</strong> — Go applies the wet-weather reduction.</span></li>
<li><span><strong>Wednesday event</strong> — Go applies the weekday evening event uplift.</span></li>
</ul>
<p class="small muted table-note">
Scenario perturbations are produced by the Go/ML stack. This page reads the base and scenario plans from
/api/staffing; it does not invent its own multipliers.
</p>
</OnyxCard>
<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>