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

+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,