Files
web-nuxt/shared/staffing.ts
T
Noel Sabia b33e6ff001 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
2026-11-14 06:13:00 +01:00

255 lines
8.0 KiB
TypeScript

import type {
Coverage,
Point,
Scenario,
Shift,
StaffingAssumptions,
StaffingHour,
StaffingResponse,
Standard,
} from './types'
export const BERLIN_TZ = 'Europe/Berlin'
export const STANDARD_VISITORS_PER_STAFF_HOUR: Record<Standard, number> = {
relaxed: 35,
standard: 25,
premium: 18,
}
export const DEFAULT_ASSUMPTIONS: StaffingAssumptions = {
visitors_per_staff_hour: STANDARD_VISITORS_PER_STAFF_HOUR.standard,
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: BERLIN_TZ },
}
const partsFormatter = new Intl.DateTimeFormat('en-CA', {
timeZone: BERLIN_TZ,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
})
export interface LocalParts {
date: string
hour: number
minute: number
/** Monday = 0 ... Sunday = 6 */
weekday: number
}
/** Convert a wire timestamp (UTC) to Heilbronn wall-clock parts. */
export function berlinParts(iso: string): LocalParts {
const parts = Object.fromEntries(
partsFormatter.formatToParts(new Date(iso)).map((p) => [p.type, p.value]),
)
const date = `${parts.year}-${parts.month}-${parts.day}`
return {
date,
hour: Number(parts.hour),
minute: Number(parts.minute),
weekday: (new Date(`${date}T12:00:00Z`).getUTCDay() + 6) % 7,
}
}
export function addDays(date: string, days: number): string {
const d = new Date(`${date}T12:00:00Z`)
d.setUTCDate(d.getUTCDate() + days)
return d.toISOString().slice(0, 10)
}
/** Start of the plan window: the Monday after `now`. */
export function planWeekStart(nowIso: string): string {
const { date, weekday } = berlinParts(nowIso)
// Monday=0 -> next Monday (7 days); Tuesday=1 -> 6 days; Sunday=6 -> 1 day.
const days = weekday === 0 ? 7 : 7 - weekday
return addDays(date, days)
}
export function isInWeek(date: string, weekStart: string): boolean {
return date >= weekStart && date <= addDays(weekStart, 6)
}
export function parseHour(time: string): number {
return Number(time.split(':')[0] ?? 0)
}
export function hhmm(hour: number): string {
return `${String(hour).padStart(2, '0')}:00`
}
/**
* Mock scenario behaviour. The contract defines the scenario enum but not the
* size of each perturbation; these multipliers are demo assumptions and are
* shown in the UI. The Go/ML implementation must publish the same numbers.
*/
export function applyScenario(points: Point[], scenario: Scenario): Point[] {
if (scenario === 'base') return points
return points.map((point) => {
const { weekday, hour } = berlinParts(point.t)
let factor = 1
if (scenario === 'sunny-saturday-market' && weekday === 5) factor = 1.2
if (scenario === 'rainy-saturday' && weekday === 5) factor = 0.82
if (scenario === 'weekday-event' && weekday === 2 && hour >= 16 && hour < 20) factor = 1.25
if (factor === 1) return point
const v = Math.round(point.v * factor)
return {
...point,
v,
lo: point.lo === undefined ? undefined : Math.round(point.lo * factor),
hi: point.hi === undefined ? undefined : Math.round(point.hi * factor),
}
})
}
function requiredStaff(footfall: number, assumptions: StaffingAssumptions): number {
const raw = (Math.max(0, footfall) / assumptions.visitors_per_staff_hour) * assumptions.safety_factor
return Math.max(Math.ceil(raw), assumptions.min_staff)
}
function shiftBlocks(
open: number,
close: number,
length: number,
): Array<{ start: number; end: number }> {
const blocks: Array<{ start: number; end: number }> = []
let start = open
while (start < close) {
const end = Math.min(start + Math.max(1, length), close)
blocks.push({ start, end })
start = end
}
return blocks
}
export interface BuildStaffingInput {
sensor: string
scenario: Scenario
standard: Standard
points: Point[]
weekStart: string
assumptions?: Partial<Omit<StaffingAssumptions, 'store_hours'>> & {
store_hours?: Partial<StaffingAssumptions['store_hours']>
}
why?: string[]
cached?: boolean
data_version: string
model_version: string
context_version: string
}
export interface StaffingBuild {
response: StaffingResponse
/** Local date -> hours, used by the plan UI. */
byDate: Record<string, StaffingHour[]>
/** Local date -> shift blocks. */
shiftsByDate: Record<string, Shift[]>
}
/** Deterministic staffing heuristic v1, identical to CONTRACT.md section 5. */
export function buildStaffing(input: BuildStaffingInput): StaffingBuild {
const assumptions: StaffingAssumptions = {
...DEFAULT_ASSUMPTIONS,
...input.assumptions,
store_hours: {
...DEFAULT_ASSUMPTIONS.store_hours,
...input.assumptions?.store_hours,
},
}
const open = parseHour(assumptions.store_hours.open)
const close = parseHour(assumptions.store_hours.close)
const weekPoints = input.points
.map((point) => ({ point, local: berlinParts(point.t) }))
.filter(({ local }) => isInWeek(local.date, input.weekStart) && local.hour >= open && local.hour < close)
.sort((a, b) => a.point.t.localeCompare(b.point.t))
const blocks = shiftBlocks(open, close, assumptions.shift_length_h)
const byDate: Record<string, StaffingHour[]> = {}
const shiftsByDate: Record<string, Shift[]> = {}
const shifts: Shift[] = []
for (const { point, local } of weekPoints) {
const required = requiredStaff(point.v, assumptions)
const block = blocks.find((b) => local.hour >= b.start && local.hour < b.end)
if (!block) continue
const blockHours = weekPoints.filter(({ local: l }) => {
return l.date === local.date && l.hour >= block.start && l.hour < block.end
})
const blockStaff = Math.max(...blockHours.map(({ point: p }) => requiredStaff(p.v, assumptions)), required)
const scheduled = blockStaff
const coverage: Coverage = scheduled < required ? 'under' : scheduled > required ? 'over' : 'ok'
const hour: StaffingHour = {
t: point.t,
footfall: Math.round(point.v),
required_staff: required,
scheduled_staff: scheduled,
coverage,
}
;(byDate[local.date] ??= []).push(hour)
}
for (const date of Object.keys(byDate).sort()) {
const dayHours = byDate[date]
shiftsByDate[date] = []
for (const block of blocks) {
const blockHours = dayHours.filter((h) => {
const hour = berlinParts(h.t).hour
return hour >= block.start && hour < block.end
})
if (!blockHours.length) continue
const staff = Math.max(...blockHours.map((h) => h.scheduled_staff))
if (staff <= 0) continue
const shift: Shift = {
date,
start: hhmm(block.start),
end: hhmm(block.end),
staff,
}
shifts.push(shift)
shiftsByDate[date]!.push(shift)
}
}
const hours = Object.values(byDate).flat().sort((a, b) => a.t.localeCompare(b.t))
const covered = hours.filter((h) => h.scheduled_staff >= h.required_staff).length
const coveragePct = hours.length ? Math.round((covered / hours.length) * 1000) / 10 : 0
const cost = hours.reduce((sum, h) => sum + h.scheduled_staff * assumptions.labor_cost_eur_h, 0)
// CONTRACT.md §5: the flat schedule applies max(required) to every store
// hour. Go uses one global peak, not one peak per day; keep this identical.
const peakRequired = hours.reduce((peak, hour) => Math.max(peak, hour.required_staff), 0)
const flatCost = peakRequired * hours.length * assumptions.labor_cost_eur_h
return {
response: {
sensor: input.sensor,
scenario: input.scenario,
standard: input.standard,
assumptions,
hours,
shifts,
summary: {
coverage_pct: coveragePct,
cost_eur: cost,
flat_schedule_cost_eur: flatCost,
overstaffed_hours: hours.filter((h) => h.coverage === 'over').length,
understaffed_hours: hours.filter((h) => h.coverage === 'under').length,
},
why: input.why ?? [],
cached: input.cached ?? false,
data_version: input.data_version,
model_version: input.model_version,
context_version: input.context_version,
},
byDate,
shiftsByDate,
}
}