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

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

No files matched your search

+9 -2
View File
@@ -8,6 +8,13 @@ import {
} from '@sit-onyx/icons'
const route = useRoute()
const config = useRuntimeConfig()
const usingMock = computed(
() =>
config.public.useMock === true ||
config.public.useMock === '1' ||
config.public.useMock === 'true',
)
const navigation = [
{ to: '/', label: 'Now', icon: iconHome },
@@ -34,7 +41,7 @@ const activeLabel = computed(
:icon="item.icon"
/>
<template #contextArea>
<OnyxBadge color="warning">Mock data</OnyxBadge>
<OnyxBadge :color="usingMock ? 'warning' : 'success'">{{ usingMock ? 'Mock data' : 'Go API' }}</OnyxBadge>
</template>
<template #mobileActivePage>{{ activeLabel }}</template>
</OnyxNavBar>
@@ -46,7 +53,7 @@ const activeLabel = computed(
<footer class="app-footer">
<span><strong>PulseCast</strong> — staff the pulse, not the noise.</span>
<span class="muted small">
Prototype · mock forecast and weather · estimated devices, not people · 8 sensors in a 580 m cluster
Prototype · forecast from the Go API · estimated devices, not people · 8 sensors in a 580 m cluster
</span>
</footer>
</template>
+40 -23
View File
@@ -6,7 +6,6 @@ interface TrainResponse {
status: string
model: 'small' | 'forecast'
submitted_at: string
mock?: boolean
}
interface TrainJob {
@@ -44,70 +43,87 @@ const statusColor = computed(() => {
}
})
function apiErrorMessage(error: unknown, fallback: string): string {
const data = (
error as {
data?: { error?: { message?: string }; message?: string; statusMessage?: string }
}
)?.data
return data?.error?.message ?? data?.message ?? data?.statusMessage ?? fallback
}
function stopPolling() {
if (pollTimer) clearInterval(pollTimer)
pollTimer = undefined
polling.value = false
}
async function poll(jobId: string) {
stopPolling()
polling.value = true
let attempts = 0
pollTimer = setInterval(async () => {
attempts += 1
try {
const result = await $fetch<TrainJob>(`/api/train/${jobId}`)
const result = await $fetch<TrainJob>(`/api/train/${encodeURIComponent(jobId)}`)
job.value = result
if (result.status === 'succeeded' || result.status === 'failed') {
clearInterval(pollTimer)
polling.value = false
}
} catch {
if (attempts >= 12) {
clearInterval(pollTimer)
polling.value = false
errorMessage.value = 'Could not read the mock training job status.'
if (result.status === 'succeeded' || result.status === 'failed') stopPolling()
} catch (error) {
if (attempts >= 30) {
stopPolling()
errorMessage.value = apiErrorMessage(error, 'Could not read the training job status.')
}
}
}, 700)
}, 1000)
}
async function submit() {
errorMessage.value = ''
job.value = null
if (!file.value) {
errorMessage.value = 'Choose a CSV file first.'
return
}
submitting.value = true
try {
const formData = new FormData()
formData.append('model', model.value)
if (file.value) formData.append('file', file.value)
formData.append('file', file.value)
const response = await $fetch<TrainResponse>('/api/train', { method: 'POST', body: formData })
await poll(response.job_id)
} catch {
errorMessage.value = 'Training submission failed. The mock endpoint expects a CSV or model selection.'
} catch (error) {
errorMessage.value = apiErrorMessage(
error,
'Training submission failed. Check the Go API and its FastAPI training upstream.',
)
} finally {
submitting.value = false
}
}
onBeforeUnmount(() => {
if (pollTimer) clearInterval(pollTimer)
})
onBeforeUnmount(stopPolling)
</script>
<template>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Train new data</OnyxHeadline>
<OnyxBadge color="warning" density="compact">P1 mock</OnyxBadge>
<OnyxBadge color="info" density="compact">Server proxy</OnyxBadge>
</div>
<p class="small muted" style="margin-top: 0">
Posts to the mock <code>/api/train</code> contract. Replace the Nitro route with the Go endpoint when it
exists; the form shape stays the same.
Uploads through Nitro to Go <code>/api/train</code>. The control credentials stay in the Node process and are
never sent to the browser.
</p>
<form class="form-grid" @submit.prevent="submit">
<OnyxFileUpload
v-model="file"
label="Training CSV"
message="Optional in the mock."
message="Challenge CSV schema. Required."
:accept="['text/csv']"
max-size="50MiB"
/>
<p class="small muted" style="margin: 0">The real endpoint expects the challenge CSV schema.</p>
<OnyxSelect
v-model="model"
label="Model"
@@ -122,6 +138,7 @@ onBeforeUnmount(() => {
:loading="submitting || polling"
/>
<span v-if="submitting" class="small muted">Submitting…</span>
<span v-else-if="polling" class="small muted">Training job running…</span>
</div>
</form>
+16 -7
View File
@@ -6,6 +6,9 @@ import { formatDate, formatDateTime, formatPercent } from '~/utils/format'
useHead({ title: 'About the data and limits — PulseCast' })
const { data: meta } = await useFetch<MetaResponse>('/api/meta')
const config = useRuntimeConfig()
const usingMock = computed(() => Boolean(config.public.useMock))
</script>
<template>
@@ -84,10 +87,10 @@ const { data: meta } = await useFetch<MetaResponse>('/api/meta')
<tr><th scope="row" style="text-align: left; font-weight: 600">Context version</th><td class="mono">{{ meta?.context_version ?? '—' }}</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Coverage</th><td>{{ meta ? `${formatDate(meta.coverage.from)} → ${formatDate(meta.coverage.to)}` : '—' }}</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Validation</th><td>{{ meta ? `WAPE ${formatPercent(meta.metrics.wape, 1)} · baseline ${formatPercent(meta.metrics.baseline_wape, 1)} · R² ${meta.metrics.r2}` : '—' }}</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Weather source</th><td>Open-Meteo archive + forecast (mock context)</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Weather source</th><td>Open-Meteo archive + forecast via `/api/context`</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Holidays</th><td>Baden-Württemberg 2025–2026 public holidays</td></tr>
</OnyxTable>
<p class="small muted table-note">Meta is rendered from <code>web-nuxt/mock/meta.json</code> until the Go API exists.</p>
<p class="small muted table-note">Meta comes from Go <code>/api/meta</code> through the Nitro proxy.</p>
</OnyxCard>
<TrainModelCard />
@@ -126,12 +129,18 @@ const { data: meta } = await useFetch<MetaResponse>('/api/meta')
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Mock status</OnyxHeadline>
<OnyxHeadline is="h3">Data source</OnyxHeadline>
<OnyxBadge :color="usingMock ? 'warning' : 'success'" density="compact">
{{ usingMock ? 'Mock mode' : 'Go API' }}
</OnyxBadge>
</div>
<p class="small muted" style="margin-top: 0">
Mock data renders the full app before the API exists. Nitro routes in <code>server/api</code> mirror the
contract. Versions and metrics are sample values; the plan heuristic is implemented once in
<code>shared/staffing.ts</code> and reused by the mock API.
<p v-if="usingMock" class="small muted" style="margin-top: 0">
Explicit dev fallback: <code>NUXT_PUBLIC_USE_MOCK=1</code>. Mock JSON renders the app without the Go
service; the plan heuristic is the shared implementation in <code>shared/staffing.ts</code>.
</p>
<p v-else class="small muted" style="margin-top: 0">
The browser only talks to this Nuxt origin. Nitro proxies `/api/*` to the Go API at
<code>NUXT_API_INTERNAL_BASE</code>; forecast, context and meta are served from there.
</p>
<p class="small muted" style="margin: 0">
Last context update: {{ meta ? formatDateTime(meta.context_version) : '—' }}
+12 -6
View File
@@ -21,6 +21,12 @@ const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: context } = await useFetch<ContextResponse>('/api/context')
const { data: meta } = await useFetch<MetaResponse>('/api/meta')
const { data: presets } = await useFetch<ScenarioPreset[]>('/api/scenarios')
sensorId.value =
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
sensorId.value
const { data: forecast } = await useFetch<ForecastResponse>('/api/forecast', {
query: computed(() => ({ sensor: sensorId.value, horizon: '7d', scenario: scenario.value })),
})
@@ -90,7 +96,7 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<p class="eyebrow">Forecast · {{ weekLabel(weekStart, weekEnd) }}</p>
<OnyxHeadline is="h1">Next week peaks on {{ weekPeak ? formatWeekday(weekPeak.date) : '—' }}.</OnyxHeadline>
<p class="lede">
A 168-hour mock forecast for <strong>{{ activeSensor?.name ?? 'Stadtgalerie' }}</strong>, aggregated by
A 168-hour forecast for <strong>{{ activeSensor?.name ?? 'the selected store' }}</strong>, aggregated by
day. The decision, shift blocks and hourly coverage are on <NuxtLink to="/plan">Plan</NuxtLink>.
</p>
</div>
@@ -161,7 +167,7 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<template v-if="day.weather">
{{ Math.round(day.weather.tempMin) }}–{{ Math.round(day.weather.tempMax) }} °C · {{ day.weather.precipMm.toFixed(1) }} mm
</template>
<span v-else class="muted">outside mock window</span>
<span v-else class="muted">outside weather window</span>
</td>
<td><OnyxBadge color="neutral" density="compact">{{ day.requiredAtPeak }}</OnyxBadge></td>
</tr>
@@ -178,11 +184,11 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Weather strip</OnyxHeadline>
<OnyxBadge color="neutral" density="compact">Open-Meteo mock</OnyxBadge>
<OnyxBadge color="neutral" density="compact">Open-Meteo context</OnyxBadge>
</div>
<WeatherStrip :days="weekWeather" />
<p v-if="!weekWeather.length" class="small muted table-note">
The mock weather window does not cover the plan week.
The weather window does not cover the plan week.
</p>
<p class="small muted table-note">
Weather is the main accuracy driver in the model. Holidays are context and a smaller feature.
@@ -197,13 +203,13 @@ const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
<ul class="why-list">
<li>
<OnyxIcon :icon="iconCalendar" size="16px" color="primary" />
<span>168 hourly points from the mock 7-day horizon, not a live stream.</span>
<span>168 hourly points from the API 7-day horizon, not a live stream.</span>
</li>
<li>
<OnyxIcon :icon="iconChart" size="16px" color="primary" />
<span>
Mean WAPE {{ meta ? formatPercent(meta.metrics.wape, 1) : '—' }} vs
{{ meta ? formatPercent(meta.metrics.baseline_wape, 1) : '—' }} seasonal naive in the mock meta;
{{ meta ? formatPercent(meta.metrics.baseline_wape, 1) : '—' }} seasonal naive in the API meta;
per-hour uncertainty is real.
</span>
</li>
+10 -6
View File
@@ -22,11 +22,15 @@ useHead({ title: 'Now in Heilbronn — PulseCast' })
const config = useRuntimeConfig()
const demoNow = String(config.public.demoNow)
const sensorId = ref('hn-stadtgalerie-01')
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: context } = await useFetch<ContextResponse>('/api/context')
const { data: meta } = await useFetch<MetaResponse>('/api/meta')
const sensorId = ref(
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
'hn-stadtgalerie-01',
)
const { data: series } = await useFetch<SeriesResponse>('/api/series', {
query: computed(() => ({ sensor: sensorId.value, step: '1h' })),
})
@@ -93,7 +97,7 @@ const latestPulse = computed(() => {
<div class="card-header">
<div>
<OnyxHeadline is="h2">Latest replay reading</OnyxHeadline>
<p class="small muted" style="margin: 0">Last available hour in the mock series.</p>
<p class="small muted" style="margin: 0">Last available hour in the API series.</p>
</div>
<div style="min-width: 12rem">
<OnyxSelect
@@ -158,7 +162,7 @@ const latestPulse = computed(() => {
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Heilbronn weather</OnyxHeadline>
<OnyxBadge color="neutral" density="compact">Open-Meteo mock</OnyxBadge>
<OnyxBadge color="neutral" density="compact">Open-Meteo context</OnyxBadge>
</div>
<div class="reading-row">
<OnyxIcon :icon="weatherIcon" size="48px" color="primary" />
@@ -177,7 +181,7 @@ const latestPulse = computed(() => {
</dl>
<p class="small muted table-note">
Updated {{ context ? formatDateTime(context.updated_at) : '—' }} · context
{{ context?.cached ? 'cached' : 'mock' }}
{{ context?.cached ? 'cached' : 'live' }}
</p>
</OnyxCard>
@@ -192,7 +196,7 @@ const latestPulse = computed(() => {
<template v-if="nextHoliday">
Next: <strong>{{ nextHoliday.name }}</strong> on {{ formatDate(nextHoliday.date) }}.
</template>
<template v-else>No upcoming holiday in the mock calendar.</template>
<template v-else>No upcoming holiday in the holiday calendar.</template>
</p>
<p v-if="lastHoliday" class="small muted" style="margin: var(--onyx-density-xs) 0 0">
Last: {{ lastHoliday.name }} on {{ formatShortDate(lastHoliday.date) }}.
@@ -258,7 +262,7 @@ const latestPulse = computed(() => {
<div v-if="!sensors?.length" class="callout callout--warning">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
Sensor mock data is missing. Run <code>npm run mock</code> and reload.
Sensor data is missing. Check that the Go API is running and that NUXT_API_INTERNAL_BASE points to it.
</div>
</div>
</template>
+171 -54
View File
@@ -8,18 +8,26 @@ import {
iconTriangleWarning,
iconUserGroup,
} from '@sit-onyx/icons'
import { dailyWeather, planDrivers } from '#shared/insights'
import { addDays, berlinParts, buildStaffing, isInWeek, planWeekStart, STANDARD_VISITORS_PER_STAFF_HOUR } from '#shared/staffing'
import { dailyWeather } from '#shared/insights'
import {
addDays,
berlinParts,
buildStaffing,
DEFAULT_ASSUMPTIONS,
isInWeek,
planWeekStart,
STANDARD_VISITORS_PER_STAFF_HOUR,
} from '#shared/staffing'
import { SCENARIOS } from '#shared/types'
import type {
ContextResponse,
ForecastResponse,
MetaResponse,
Scenario,
ScenarioPreset,
Sensor,
Shift,
StaffingHour,
StaffingResponse,
Standard,
} from '#shared/types'
import {
@@ -39,42 +47,75 @@ useHead({ title: 'Plan next week — PulseCast' })
const config = useRuntimeConfig()
const route = useRoute()
const demoNow = String(config.public.demoNow)
const weekStart = planWeekStart(demoNow)
const weekEnd = addDays(weekStart, 6)
const usingMock = computed(
() =>
config.public.useMock === true ||
config.public.useMock === '1' ||
config.public.useMock === 'true',
)
function initialScenario(): Scenario {
const value = route.query.scenario
return typeof value === 'string' && SCENARIOS.includes(value as Scenario) ? (value as Scenario) : 'base'
}
const scenario = ref<Scenario>(initialScenario())
const sensorId = ref('hn-stadtgalerie-01')
const standard = ref<Standard>('standard')
const selectedDay = ref(addDays(weekStart, 5))
const approved = ref(false)
const generating = ref(false)
const generatedAt = ref('')
const openAssumptions = ref<PropertyKey[]>([])
const assumptions = reactive({
safety_factor: 1.15,
min_staff: 1,
shift_length_h: 4,
labor_cost_eur_h: 16,
})
/** Keep Stadtgalerie as the demo default, but follow the API when it differs. */
function preferredSensor(list: Sensor[] | null | undefined): string {
return list?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ?? list?.[0]?.id ?? 'hn-stadtgalerie-01'
}
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: context } = await useFetch<ContextResponse>('/api/context')
const { data: meta } = await useFetch<MetaResponse>('/api/meta')
const { data: presets } = await useFetch<ScenarioPreset[]>('/api/scenarios')
const sensorId = ref(preferredSensor(sensors.value))
const scenario = ref<Scenario>(initialScenario())
const standard = ref<Standard>('standard')
const approved = ref(false)
const generating = ref(false)
const generatedAt = ref('')
const openAssumptions = ref<PropertyKey[]>([])
const assumptions = reactive({
safety_factor: DEFAULT_ASSUMPTIONS.safety_factor,
min_staff: DEFAULT_ASSUMPTIONS.min_staff,
shift_length_h: DEFAULT_ASSUMPTIONS.shift_length_h,
labor_cost_eur_h: DEFAULT_ASSUMPTIONS.labor_cost_eur_h,
})
const EMPTY_PLAN: StaffingResponse = {
sensor: '',
scenario: 'base',
standard: 'standard',
assumptions: DEFAULT_ASSUMPTIONS,
hours: [],
shifts: [],
summary: {
coverage_pct: 0,
cost_eur: 0,
flat_schedule_cost_eur: 0,
overstaffed_hours: 0,
understaffed_hours: 0,
},
why: [],
cached: false,
data_version: '',
model_version: '',
context_version: '',
}
// The hero plan comes from the Go API. Local assumption edits only render a
// preview from the API's own forecast hours; they never replace the API plan.
const {
data: forecast,
data: apiPlanData,
status,
error,
refresh,
} = await useFetch<ForecastResponse>('/api/forecast', {
} = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({
sensor: sensorId.value,
horizon: '7d',
scenario: scenario.value,
standard: standard.value,
})),
})
@@ -87,10 +128,17 @@ watch(
},
)
const apiPlan = computed(() => apiPlanData.value ?? EMPTY_PLAN)
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const activeScenario = computed(() => presets.value?.find((preset) => preset.id === scenario.value))
const visitorsPerStaffHour = computed(() => STANDARD_VISITORS_PER_STAFF_HOUR[standard.value])
const weekStart = computed(() => {
const first = apiPlan.value.hours[0]
return first ? berlinParts(first.t).date : planWeekStart(demoNow)
})
const weekEnd = computed(() => addDays(weekStart.value, 6))
const scenarioOptions = computed(() =>
(presets.value ?? []).map((preset) => ({ value: preset.id, label: preset.label })),
)
@@ -117,34 +165,65 @@ const shiftLengthOptions = [
{ value: 5, label: '5 hours' },
]
const build = computed(() =>
/** The /api/staffing contract has no assumption query params. Non-query edits
* are therefore an explicitly labeled local preview, never a silent swap. */
const previewActive = computed(() => {
const api = apiPlan.value.assumptions
return (
assumptions.safety_factor !== api.safety_factor ||
assumptions.min_staff !== api.min_staff ||
assumptions.shift_length_h !== api.shift_length_h ||
assumptions.labor_cost_eur_h !== api.labor_cost_eur_h
)
})
const previewBuild = computed(() =>
buildStaffing({
sensor: sensorId.value,
scenario: scenario.value,
standard: standard.value,
points: forecast.value?.points ?? [],
weekStart,
points: apiPlan.value.hours.map((hour) => ({ t: hour.t, v: hour.footfall })),
weekStart: weekStart.value,
assumptions: {
visitors_per_staff_hour: visitorsPerStaffHour.value,
safety_factor: assumptions.safety_factor,
min_staff: assumptions.min_staff,
shift_length_h: assumptions.shift_length_h,
labor_cost_eur_h: assumptions.labor_cost_eur_h,
store_hours: apiPlan.value.assumptions.store_hours,
},
data_version: forecast.value?.data_version ?? meta.value?.data_version ?? '',
model_version: forecast.value?.model_version ?? meta.value?.model_version ?? '',
context_version: forecast.value?.context_version ?? meta.value?.context_version ?? '',
data_version: apiPlan.value.data_version,
model_version: apiPlan.value.model_version,
context_version: apiPlan.value.context_version,
}),
)
const plan = computed(() => build.value.response)
const why = computed(() =>
context.value ? planDrivers(plan.value, context.value, weekStart, scenario.value) : [],
)
const plan = computed(() => (previewActive.value ? previewBuild.value.response : apiPlan.value))
const hoursByDate = computed<Record<string, StaffingHour[]>>(() => {
if (previewActive.value) return previewBuild.value.byDate
const grouped: Record<string, StaffingHour[]> = {}
for (const hour of apiPlan.value.hours) {
const date = berlinParts(hour.t).date
;(grouped[date] ??= []).push(hour)
}
return grouped
})
const shiftsByDate = computed<Record<string, Shift[]>>(() => {
if (previewActive.value) return previewBuild.value.shiftsByDate
const grouped: Record<string, Shift[]> = {}
for (const shift of apiPlan.value.shifts) {
;(grouped[shift.date] ??= []).push(shift)
}
return grouped
})
const why = computed(() => apiPlan.value.why)
const weekWeather = computed(() => {
if (!context.value) return []
return Object.values(dailyWeather(context.value.weather.forecast))
.filter((day) => isInWeek(day.date, weekStart))
.filter((day) => isInWeek(day.date, weekStart.value))
.sort((a, b) => a.date.localeCompare(b.date))
})
@@ -178,11 +257,11 @@ interface DaySummary {
}
const daySummaries = computed<DaySummary[]>(() =>
Object.keys(build.value.byDate)
Object.keys(hoursByDate.value)
.sort()
.map((date) => {
const hours = build.value.byDate[date] ?? []
const shifts = build.value.shiftsByDate[date] ?? []
const hours = hoursByDate.value[date] ?? []
const shifts = shiftsByDate.value[date] ?? []
const staffHours = hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0)
return {
date,
@@ -193,6 +272,17 @@ const daySummaries = computed<DaySummary[]>(() =>
}
}),
)
const dayDates = computed(() => daySummaries.value.map((day) => day.date))
const selectedDay = ref('')
watch(
() => dayDates.value.join(','),
() => {
if (dayDates.value.includes(selectedDay.value)) return
const preferred = addDays(weekStart.value, 5)
selectedDay.value = dayDates.value.includes(preferred) ? preferred : (dayDates.value[0] ?? '')
},
{ immediate: true },
)
const dayOptions = computed(() =>
daySummaries.value.map((day) => ({
@@ -200,7 +290,7 @@ const dayOptions = computed(() =>
label: `${formatWeekday(day.date)} ${formatShortDate(day.date)} · ${day.peakStaff} peak`,
})),
)
const selectedHours = computed<StaffingHour[]>(() => build.value.byDate[selectedDay.value] ?? [])
const selectedHours = computed<StaffingHour[]>(() => hoursByDate.value[selectedDay.value] ?? [])
const selectedCovered = computed(
() => selectedHours.value.filter((hour) => hour.scheduled_staff >= hour.required_staff).length,
)
@@ -224,20 +314,28 @@ async function generate() {
generating.value = true
try {
await refresh()
if (import.meta.client) generatedAt.value = formatTime(new Date().toISOString())
if (!error.value && import.meta.client) generatedAt.value = formatTime(new Date().toISOString())
} finally {
generating.value = false
}
}
function resetAssumptions() {
assumptions.safety_factor = 1.15
assumptions.min_staff = 1
assumptions.shift_length_h = 4
assumptions.labor_cost_eur_h = 16
assumptions.safety_factor = DEFAULT_ASSUMPTIONS.safety_factor
assumptions.min_staff = DEFAULT_ASSUMPTIONS.min_staff
assumptions.shift_length_h = DEFAULT_ASSUMPTIONS.shift_length_h
assumptions.labor_cost_eur_h = DEFAULT_ASSUMPTIONS.labor_cost_eur_h
standard.value = 'standard'
}
function useApiPlan() {
const api = apiPlan.value.assumptions
assumptions.safety_factor = api.safety_factor
assumptions.min_staff = api.min_staff
assumptions.shift_length_h = api.shift_length_h
assumptions.labor_cost_eur_h = api.labor_cost_eur_h
}
function exportPlan() {
if (!import.meta.client) return
const rows = [
@@ -254,7 +352,7 @@ function exportPlan() {
const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }))
const link = document.createElement('a')
link.href = url
link.download = `pulsecast-plan-${weekStart}.csv`
link.download = `pulsecast-plan-${weekStart.value}.csv`
link.click()
URL.revokeObjectURL(url)
}
@@ -273,7 +371,7 @@ function exportPlan() {
<template v-else>Build next week’s shift plan.</template>
</OnyxHeadline>
<p class="lede">
Forecast for <strong>{{ activeSensor?.name ?? 'Stadtgalerie' }}</strong> needs
Forecast for <strong>{{ activeSensor?.name ?? apiPlan.sensor ?? 'the selected store' }}</strong> needs
<strong>{{ peakHour?.required_staff ?? '—' }} staff at the busiest hour</strong>. The rest of the week
runs on {{ totalStaffHours }} staff-hours at {{ formatEuro(plan.summary.cost_eur) }}.
</p>
@@ -289,8 +387,14 @@ function exportPlan() {
<span v-else class="small muted">Draft for manager review</span>
</div>
<p class="small muted" style="margin: 0">
Mock forecast · updated {{ context ? formatDateTime(context.updated_at) : '—' }} · no POS, sales or
labour-cost feed.
<template v-if="usingMock">Mock mode · NUXT_PUBLIC_USE_MOCK=1 · no Go API call.</template>
<template v-else-if="previewActive">
Local preview · the Go API plan is unchanged.
</template>
<template v-else>
Go `/api/staffing` · updated {{ context ? formatDateTime(context.updated_at) : '—' }} · no POS, sales
or labour-cost feed.
</template>
</p>
</div>
@@ -311,6 +415,7 @@ function exportPlan() {
<OnyxBadge color="success" density="compact">{{ formatPercent(plan.summary.coverage_pct, 1) }} covered</OnyxBadge>
<OnyxBadge color="warning" density="compact">{{ plan.summary.overstaffed_hours }} h over</OnyxBadge>
<OnyxBadge color="success" density="compact">{{ plan.summary.understaffed_hours }} h under</OnyxBadge>
<OnyxBadge v-if="apiPlan.cached" color="warning" density="compact">cached forecast</OnyxBadge>
</div>
</div>
</div>
@@ -318,7 +423,8 @@ function exportPlan() {
<div v-if="status === 'error'" class="callout callout--warning">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
The mock forecast could not be loaded. Check the Nitro mock routes and reload.
The staffing API could not be loaded. Check that the Go API is running and that NUXT_API_INTERNAL_BASE points
to it. <span v-if="error" class="muted">{{ error.statusMessage }}</span>
</div>
<section class="summary-grid" aria-label="Plan summary">
@@ -357,10 +463,13 @@ function exportPlan() {
<div>
<OnyxHeadline is="h2">Plan inputs</OnyxHeadline>
<p class="small muted" style="margin: 0">
Change store, service standard or scenario. The plan recomputes from the mock forecast.
Store, service standard and scenario are sent to Go `/api/staffing`. Local assumption edits render a
preview from the API forecast.
</p>
</div>
<OnyxBadge color="info" density="compact">Mock forecast</OnyxBadge>
<OnyxBadge :color="usingMock ? 'warning' : previewActive ? 'warning' : 'success'" density="compact">
{{ usingMock ? 'Mock mode' : previewActive ? 'Local preview' : 'Go API' }}
</OnyxBadge>
</div>
<div class="form-grid">
@@ -445,9 +554,14 @@ function exportPlan() {
:step-size="1"
message="Assumption only. No payroll or POS data exists."
/>
<p class="small muted" style="grid-column: 1 / -1; margin: 0">
These four values are not query inputs of Go `/api/staffing`. Changing them shows a local preview;
“Use API plan” restores the server values.
</p>
<div class="form-actions" style="grid-column: 1 / -1">
<OnyxButton label="Reset assumptions" mode="outline" @click="resetAssumptions" />
<span class="small muted">Store hours 10:00–20:00, Europe/Berlin · {{ forecast?.model_version ?? 'mock' }}</span>
<OnyxButton v-if="previewActive" label="Use API plan" mode="outline" @click="useApiPlan" />
<span class="small muted">Store hours 10:00–20:00, Europe/Berlin · {{ apiPlan.model_version || 'API' }}</span>
</div>
</div>
</OnyxAccordionItem>
@@ -593,7 +707,7 @@ function exportPlan() {
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Why this plan</OnyxHeadline>
<OnyxBadge color="info" density="compact">Context</OnyxBadge>
<OnyxBadge color="info" density="compact">{{ usingMock ? 'Mock mode' : 'Go API' }}</OnyxBadge>
</div>
<ul class="why-list">
<li v-for="reason in why" :key="reason">
@@ -606,10 +720,13 @@ function exportPlan() {
<p class="stat-label" style="margin-bottom: var(--onyx-density-xs)">Weather during the plan week</p>
<WeatherStrip :days="weekWeather" />
<p v-if="!weekWeather.length" class="small muted table-note">
Weather forecast does not cover this window in the mock context.
The weather forecast from `/api/context` does not cover this plan window yet.
</p>
<p class="small muted table-note">
{{ activeScenario?.description ?? 'Base scenario uses the mock forecast weather.' }}
{{ activeScenario?.description ?? 'Base scenario uses the API forecast weather.' }}
</p>
<p v-if="previewActive" class="small muted table-note">
This card explains the API plan; the assumption preview above is local.
</p>
</OnyxCard>
@@ -625,7 +742,7 @@ function exportPlan() {
<div><dt>Shift block</dt><dd>{{ plan.assumptions.shift_length_h }} h</dd></div>
<div><dt>Labour cost</dt><dd>{{ formatEuro(plan.assumptions.labor_cost_eur_h) }}/h</dd></div>
<div><dt>Store hours</dt><dd>{{ plan.assumptions.store_hours.open }}–{{ plan.assumptions.store_hours.close }}</dd></div>
<div><dt>Model / data</dt><dd>{{ forecast?.model_version ?? meta?.model_version ?? 'mock' }}</dd></div>
<div><dt>Model / data</dt><dd>{{ plan.model_version || meta?.model_version || '—' }}</dd></div>
</dl>
<p class="small muted table-note" style="margin-top: var(--onyx-density-md)">
No POS, sales, queue or labour-cost data exists. This is decision support with explicit assumptions,
+78 -51
View File
@@ -1,25 +1,74 @@
<script setup lang="ts">
import { iconArrowRight, iconCircleInformation, iconFlash } from '@sit-onyx/icons'
import { addDays, applyScenario, buildStaffing, planWeekStart } from '#shared/staffing'
import type { ContextResponse, ForecastResponse, Scenario, ScenarioPreset, Sensor } from '#shared/types'
import { addDays, berlinParts, planWeekStart } from '#shared/staffing'
import type {
ContextResponse,
Scenario,
ScenarioPreset,
Sensor,
StaffingResponse,
} from '#shared/types'
import { formatEuro, formatShortDate, formatWeekday, formatWeekdayShort, weekLabel } from '~/utils/format'
useHead({ title: 'Simulate a scenario — PulseCast' })
const config = useRuntimeConfig()
const demoNow = String(config.public.demoNow)
const weekStart = planWeekStart(demoNow)
const weekEnd = addDays(weekStart, 6)
const sensorId = ref('hn-stadtgalerie-01')
const scenario = ref<Scenario>('sunny-saturday-market')
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: context } = await useFetch<ContextResponse>('/api/context')
const { data: presets } = await useFetch<ScenarioPreset[]>('/api/scenarios')
const { data: baseForecast } = await useFetch<ForecastResponse>('/api/forecast', {
query: computed(() => ({ sensor: sensorId.value, horizon: '7d', scenario: 'base' })),
const sensorId = ref(
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
'hn-stadtgalerie-01',
)
const scenario = ref<Scenario>('sunny-saturday-market')
const EMPTY_PLAN: StaffingResponse = {
sensor: '',
scenario: 'base',
standard: 'standard',
assumptions: {
visitors_per_staff_hour: 25,
safety_factor: 1.15,
min_staff: 1,
shift_length_h: 4,
labor_cost_eur_h: 16,
store_hours: { open: '10:00', close: '20:00', tz: 'Europe/Berlin' },
},
hours: [],
shifts: [],
summary: {
coverage_pct: 0,
cost_eur: 0,
flat_schedule_cost_eur: 0,
overstaffed_hours: 0,
understaffed_hours: 0,
},
why: [],
cached: false,
data_version: '',
model_version: '',
context_version: '',
}
const { data: baseData } = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({ sensor: sensorId.value, scenario: 'base', standard: 'standard' })),
})
const { data: scenarioData, status } = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({ sensor: sensorId.value, scenario: scenario.value, standard: 'standard' })),
})
const basePlan = computed(() => baseData.value ?? EMPTY_PLAN)
const scenarioPlan = computed(() => scenarioData.value ?? basePlan.value)
const weekStart = computed(() => {
const first = basePlan.value.hours[0]
return first ? berlinParts(first.t).date : planWeekStart(demoNow)
})
const weekEnd = computed(() => addDays(weekStart.value, 6))
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const sensorOptions = computed(() =>
@@ -34,31 +83,6 @@ const radioOptions = computed(() =>
})),
)
const scenarioPoints = computed(() =>
applyScenario(baseForecast.value?.points ?? [], scenario.value),
)
const versions = computed(() => ({
data_version: baseForecast.value?.data_version ?? '',
model_version: baseForecast.value?.model_version ?? '',
context_version: baseForecast.value?.context_version ?? '',
}))
function makePlan(points: typeof scenarioPoints.value) {
return buildStaffing({
sensor: sensorId.value,
scenario: scenario.value,
standard: 'standard',
points,
weekStart,
...versions.value,
})
}
const basePlan = computed(() => makePlan(baseForecast.value?.points ?? []).response)
const scenarioBuild = computed(() => makePlan(scenarioPoints.value))
const scenarioPlan = computed(() => scenarioBuild.value.response)
const baseHours = computed(() => basePlan.value.hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0))
const scenarioHours = computed(() =>
scenarioPlan.value.hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0),
@@ -66,18 +90,19 @@ const scenarioHours = computed(() =>
const deltaHours = computed(() => scenarioHours.value - baseHours.value)
const deltaCost = computed(() => scenarioPlan.value.summary.cost_eur - basePlan.value.summary.cost_eur)
function peakStaffByDay(plan: ReturnType<typeof makePlan>) {
function peakStaffByDay(plan: StaffingResponse) {
const map: Record<string, number> = {}
for (const [date, hours] of Object.entries(plan.byDate)) {
map[date] = hours.reduce((peak, hour) => Math.max(peak, hour.required_staff), 0)
for (const hour of plan.hours) {
const date = berlinParts(hour.t).date
map[date] = Math.max(map[date] ?? 0, hour.required_staff)
}
return map
}
const basePeaks = computed(() => peakStaffByDay(makePlan(baseForecast.value?.points ?? [])))
const scenarioPeaks = computed(() => peakStaffByDay(scenarioBuild.value))
const basePeaks = computed(() => peakStaffByDay(basePlan.value))
const scenarioPeaks = computed(() => peakStaffByDay(scenarioPlan.value))
const days = computed(() =>
Object.keys(basePeaks.value)
[...new Set([...Object.keys(basePeaks.value), ...Object.keys(scenarioPeaks.value)])]
.sort()
.map((date) => ({
date,
@@ -111,8 +136,8 @@ const days = computed(() =>
<div class="callout">
<OnyxIcon :icon="iconCircleInformation" size="16px" color="primary" />
Local selection for now. SSE broadcast to <code>/stage</code> and phones is the next slice; this page makes the
recommendation change visible on one screen.
The base and scenario plans are generated by Go `/api/staffing`. SSE broadcast to <code>/stage</code> and
phones is the next slice; this page makes the recommendation change visible on one screen.
</div>
<div class="split-grid">
@@ -121,9 +146,11 @@ const days = computed(() =>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Scenario</OnyxHeadline>
<p class="small muted" style="margin: 0">The contract enum is fixed; perturbation sizes are mock assumptions.</p>
<p class="small muted" style="margin: 0">The contract enum is fixed; the API applies the perturbation.</p>
</div>
<OnyxBadge color="warning" density="compact">mock simulation</OnyxBadge>
<OnyxBadge :color="status === 'pending' ? 'warning' : 'success'" density="compact">
{{ status === 'pending' ? 'loading' : 'Go API' }}
</OnyxBadge>
</div>
<OnyxRadioGroup
v-model="scenario"
@@ -193,7 +220,7 @@ const days = computed(() =>
peak hour before cutting the block.
</template>
<template v-else>
This scenario does not change the shift requirements in the mock. That is a result, not a bug.
This scenario does not change the shift requirements. That is a result, not a bug.
</template>
</p>
</div>
@@ -212,14 +239,14 @@ const days = computed(() =>
<OnyxHeadline is="h3">Scenario rules</OnyxHeadline>
</div>
<ul class="why-list">
<li><span><strong>Sunny Saturday + market</strong> — ×1.20 Saturday footfall.</span></li>
<li><span><strong>Rainy Saturday</strong> — ×0.82 Saturday footfall.</span></li>
<li><span><strong>Wednesday event</strong> — ×1.25 Wed 16:00–20:00.</span></li>
<li><span>Base keeps the latest forecast weather and no event uplift.</span></li>
<li><span><strong>Base week</strong> — latest forecast weather, no scenario uplift.</span></li>
<li><span><strong>Sunny Saturday + market</strong> — Go applies the market/day uplift to next Saturday.</span></li>
<li><span><strong>Rainy Saturday</strong> — Go applies the wet-weather reduction.</span></li>
<li><span><strong>Wednesday event</strong> — Go applies the weekday evening event uplift.</span></li>
</ul>
<p class="small muted table-note">
These multipliers are mock demo assumptions. The Go/ML implementation must publish the same numbers or
the comparison is not comparable.
Scenario perturbations are produced by the Go/ML stack. This page reads the base and scenario plans from
`/api/staffing`; it does not invent its own multipliers.
</p>
</OnyxCard>