436 lines
13 KiB
TypeScript
436 lines
13 KiB
TypeScript
import { COOL_TIMES } from './cool'
|
|
import type { CoolRouteBundle, CoolRouteId, CoolRouteValues, CoolTime } from './cool'
|
|
import { berlinParts } from './staffing'
|
|
import type { Sensor, StaffingHour, StaffingResponse, Shift } from './types'
|
|
|
|
/**
|
|
* UC1 Staffing · UC2 Smart Routing · UC3 PreZero.
|
|
*
|
|
* These helpers are shared by the page, the panels and the tests. Every number
|
|
* comes from a real bundle/API payload; no value is generated in the browser.
|
|
*/
|
|
export type UseCaseId = 'staffing' | 'routing' | 'prezero'
|
|
|
|
export interface UseCaseTab {
|
|
id: UseCaseId
|
|
eyebrow: string
|
|
title: string
|
|
subtitle: string
|
|
icon: string
|
|
}
|
|
|
|
export const USE_CASE_TABS: readonly UseCaseTab[] = [
|
|
{
|
|
id: 'staffing',
|
|
eyebrow: 'UC1: Staffing optimization',
|
|
title: 'Hourly occupancy vs workforce',
|
|
subtitle: 'Turn the forecast into a shift plan.',
|
|
icon: 'material-symbols:trending-up',
|
|
},
|
|
{
|
|
id: 'routing',
|
|
eyebrow: 'UC2: Smart micro-climate routing',
|
|
title: 'Fastest path with modeled shade and access',
|
|
subtitle: 'Modeled shade, solar position and street access.',
|
|
icon: 'material-symbols:route',
|
|
},
|
|
{
|
|
id: 'prezero',
|
|
eyebrow: 'UC3: PreZero depot logistics',
|
|
title: 'Container collection priority',
|
|
subtitle: 'Rank 449 anonymized container locations from reported states.',
|
|
icon: 'material-symbols:recycling',
|
|
},
|
|
] as const
|
|
|
|
export const DEFAULT_USE_CASE: UseCaseId = 'routing'
|
|
|
|
export function isUseCaseId(value: unknown): value is UseCaseId {
|
|
return value === 'staffing' || value === 'routing' || value === 'prezero'
|
|
}
|
|
|
|
export function useCaseById(id: UseCaseId): UseCaseTab {
|
|
return USE_CASE_TABS.find((tab) => tab.id === id) ?? USE_CASE_TABS[1]!
|
|
}
|
|
|
|
export function isCoolTimeValue(value: unknown): value is CoolTime {
|
|
return typeof value === 'string' && (COOL_TIMES as readonly string[]).includes(value)
|
|
}
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Routing */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
const ROUTE_TITLES: Record<CoolRouteId, string> = {
|
|
shortest: 'Shortest route',
|
|
shaded: 'Shaded route',
|
|
accessible: 'Accessible route',
|
|
}
|
|
|
|
export const ROUTE_ORDER: readonly CoolRouteId[] = ['shortest', 'shaded', 'accessible'] as const
|
|
|
|
export interface RouteComparisonRow {
|
|
id: CoolRouteId
|
|
title: string
|
|
description: string
|
|
values: CoolRouteValues
|
|
recommended: boolean
|
|
penaltyMin: number
|
|
tag: string
|
|
}
|
|
|
|
export function routeTitle(id: CoolRouteId): string {
|
|
return ROUTE_TITLES[id]
|
|
}
|
|
|
|
export function routeValuesFor(
|
|
bundle: CoolRouteBundle | null | undefined,
|
|
id: CoolRouteId,
|
|
time: CoolTime | string,
|
|
): CoolRouteValues | null {
|
|
return bundle?.routes.find((route) => route.id === id)?.values[time] ?? null
|
|
}
|
|
|
|
export function recommendedRouteId(
|
|
bundle: CoolRouteBundle | null | undefined,
|
|
time: CoolTime | string,
|
|
): CoolRouteId {
|
|
return bundle?.recommendationByTime[time] ?? 'shortest'
|
|
}
|
|
|
|
export function recommendedRoute(
|
|
bundle: CoolRouteBundle | null | undefined,
|
|
time: CoolTime | string,
|
|
) {
|
|
if (!bundle) return null
|
|
return bundle.routes.find((route) => route.id === recommendedRouteId(bundle, time)) ?? null
|
|
}
|
|
|
|
export function recommendedValues(
|
|
bundle: CoolRouteBundle | null | undefined,
|
|
time: CoolTime | string,
|
|
): CoolRouteValues | null {
|
|
return routeValuesFor(bundle, recommendedRouteId(bundle, time), time)
|
|
}
|
|
|
|
export function routeTag(
|
|
id: CoolRouteId,
|
|
recommended: boolean,
|
|
values: CoolRouteValues,
|
|
): string {
|
|
if (recommended) return 'Recommended'
|
|
if (id === 'shortest') return values.stepFree ? 'Fastest · 15% ramp' : 'Fastest'
|
|
if (id === 'shaded') return 'Shaded · longer walk'
|
|
return 'Step-free · water & benches'
|
|
}
|
|
|
|
/**
|
|
* Candidate rows for the comparison card. `penaltyMin` is the duration after
|
|
* the fastest candidate, so the values stay real even when the model picks a
|
|
* slower, step-free route.
|
|
*/
|
|
export function routeComparison(
|
|
bundle: CoolRouteBundle | null | undefined,
|
|
time: CoolTime | string,
|
|
): RouteComparisonRow[] {
|
|
if (!bundle) return []
|
|
const recommended = recommendedRouteId(bundle, time)
|
|
const rows = ROUTE_ORDER.flatMap((id) => {
|
|
const values = routeValuesFor(bundle, id, time)
|
|
const route = bundle.routes.find((entry) => entry.id === id)
|
|
if (!values || !route) return []
|
|
return [
|
|
{
|
|
id,
|
|
title: routeTitle(id),
|
|
description: route.description,
|
|
values,
|
|
recommended: id === recommended,
|
|
penaltyMin: 0,
|
|
tag: '',
|
|
},
|
|
]
|
|
})
|
|
const fastest = Math.min(...rows.map((row) => row.values.durationMin))
|
|
return rows.map((row) => ({
|
|
...row,
|
|
penaltyMin: Math.round((row.values.durationMin - fastest) * 10) / 10,
|
|
tag: routeTag(row.id, row.recommended, row.values),
|
|
}))
|
|
}
|
|
|
|
export function routeRationale(
|
|
bundle: CoolRouteBundle | null | undefined,
|
|
time: CoolTime | string,
|
|
): string {
|
|
if (!bundle) return 'The route bundle is unavailable. Nothing is estimated.'
|
|
const route = recommendedRoute(bundle, time)
|
|
const values = recommendedValues(bundle, time)
|
|
if (!route || !values) return 'The route bundle has no values for this hour.'
|
|
|
|
const fastest = routeComparison(bundle, time)
|
|
.slice()
|
|
.sort((a, b) => a.values.durationMin - b.values.durationMin)[0]
|
|
const delta =
|
|
fastest && fastest.id !== route.id
|
|
? ` It is ${formatMinutes(values.durationMin - fastest.values.durationMin)} longer than the fastest candidate.`
|
|
: ' It is also the fastest candidate.'
|
|
const access = values.stepFree
|
|
? values.rampInclinePct === null || values.rampInclinePct === undefined
|
|
? ' The route is step-free with no ramp.'
|
|
: ` The route is step-free but includes a ${values.rampInclinePct}% ramp.`
|
|
: ' The route is not step-free.'
|
|
const weather = bundle.hotDay
|
|
? `${bundle.hotDay.temperature_max_c} °C on the modeled ${bundle.hotDay.date} hot day`
|
|
: 'the modeled hot day'
|
|
|
|
return `Fusing ${weather}, the ${solarAzimuthLabel(bundle, time)}, and modeled shade from OSM buildings and tree crowns: the ${routeTitle(route.id).toLowerCase()} is ${formatPercent(values.shadePct)} shaded with ${formatMinutes(values.directSunMin)} of direct sun and ${values.waterStops} water ${values.waterStops === 1 ? 'stop' : 'stops'}.${access}${delta}`
|
|
}
|
|
|
|
export function solarPosition(
|
|
bundle: CoolRouteBundle | null | undefined,
|
|
time: CoolTime | string,
|
|
): { altitude_deg: number; azimuth_deg: number } | null {
|
|
return bundle?.meta?.solarPositions?.[time] ?? null
|
|
}
|
|
|
|
export function solarAzimuthLabel(
|
|
bundle: CoolRouteBundle | null | undefined,
|
|
time: CoolTime | string,
|
|
): string {
|
|
const position = solarPosition(bundle, time)
|
|
if (!position) return 'solar position unavailable'
|
|
return `solar azimuth ${Math.round(position.azimuth_deg)}° ${compassDirection(position.azimuth_deg)}`
|
|
}
|
|
|
|
export function compassDirection(degrees: number): string {
|
|
const points = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
|
|
const index = Math.round(((degrees % 360) + 360) % 360 / 45) % 8
|
|
return points[index]!
|
|
}
|
|
|
|
export function formatMinutes(value: number): string {
|
|
const rounded = Math.round(value * 10) / 10
|
|
return `${Number.isInteger(rounded) ? rounded : rounded.toFixed(1)} min`
|
|
}
|
|
|
|
export function formatPercent(value: number, digits = 1): string {
|
|
return `${value.toFixed(digits)}%`
|
|
}
|
|
|
|
/** A GPX 1.1 track from the real OSM route geometry. */
|
|
export function buildGpx(
|
|
bundle: CoolRouteBundle,
|
|
routeId: CoolRouteId,
|
|
time: CoolTime | string,
|
|
generatedAt = new Date().toISOString(),
|
|
): string {
|
|
const route = bundle.routes.find((entry) => entry.id === routeId)
|
|
if (!route || route.geometry.length === 0) {
|
|
throw new Error(`No geometry for route ${routeId}`)
|
|
}
|
|
const values = route.values[time]
|
|
const name = `${routeTitle(routeId)} · ${bundle.origin.name} → ${bundle.destination.name}`
|
|
const desc = values
|
|
? `${formatPercent(values.shadePct)} modeled shade, ${formatMinutes(values.directSunMin)} direct sun, ${formatMinutes(values.durationMin)} walk at ${time}. ${bundle.shadeLabel}.`
|
|
: `${bundle.shadeLabel}.`
|
|
const points = route.geometry
|
|
.map(
|
|
([lon, lat]) =>
|
|
` <trkpt lat="${lat.toFixed(6)}" lon="${lon.toFixed(6)}" />`,
|
|
)
|
|
.join('\n')
|
|
|
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
<gpx version="1.1" creator="Sensing Engine" xmlns="http://www.topografix.com/GPX/1/1">
|
|
<metadata>
|
|
<name>${escapeXml(name)}</name>
|
|
<desc>${escapeXml(desc)}</desc>
|
|
<time>${generatedAt}</time>
|
|
</metadata>
|
|
<trk>
|
|
<name>${escapeXml(name)}</name>
|
|
<desc>${escapeXml(desc)}</desc>
|
|
<trkseg>
|
|
${points}
|
|
</trkseg>
|
|
</trk>
|
|
</gpx>
|
|
`
|
|
}
|
|
|
|
function escapeXml(value: string): string {
|
|
return value
|
|
.replaceAll('&', '&')
|
|
.replaceAll('<', '<')
|
|
.replaceAll('>', '>')
|
|
.replaceAll('"', '"')
|
|
.replaceAll("'", ''')
|
|
}
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Staffing */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
export interface StaffingSnapshot {
|
|
peakHour: StaffingHour | null
|
|
peakShift: Shift | null
|
|
staffHours: number
|
|
peakFootfall: number
|
|
savedEur: number
|
|
savedPct: number
|
|
coveragePct: number
|
|
overstaffedHours: number
|
|
understaffedHours: number
|
|
days: number
|
|
}
|
|
|
|
export function staffingSnapshot(plan: StaffingResponse | null | undefined): StaffingSnapshot {
|
|
if (!plan) {
|
|
return {
|
|
peakHour: null,
|
|
peakShift: null,
|
|
staffHours: 0,
|
|
peakFootfall: 0,
|
|
savedEur: 0,
|
|
savedPct: 0,
|
|
coveragePct: 0,
|
|
overstaffedHours: 0,
|
|
understaffedHours: 0,
|
|
days: 0,
|
|
}
|
|
}
|
|
|
|
let peakHour: StaffingHour | null = null
|
|
for (const hour of plan.hours) {
|
|
if (!peakHour || hour.footfall > peakHour.footfall) peakHour = hour
|
|
}
|
|
|
|
let peakShift: Shift | null = null
|
|
for (const shift of plan.shifts) {
|
|
if (
|
|
!peakShift ||
|
|
shift.staff > peakShift.staff ||
|
|
(shift.staff === peakShift.staff && shift.date < peakShift.date)
|
|
) {
|
|
peakShift = shift
|
|
}
|
|
}
|
|
|
|
const staffHours = plan.hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0)
|
|
const savedEur = Math.max(0, plan.summary.flat_schedule_cost_eur - plan.summary.cost_eur)
|
|
const days = new Set(plan.hours.map((hour) => berlinParts(hour.t).date)).size
|
|
|
|
return {
|
|
peakHour,
|
|
peakShift,
|
|
staffHours,
|
|
peakFootfall: peakHour?.footfall ?? 0,
|
|
savedEur,
|
|
savedPct:
|
|
plan.summary.flat_schedule_cost_eur > 0
|
|
? (savedEur / plan.summary.flat_schedule_cost_eur) * 100
|
|
: 0,
|
|
coveragePct: plan.summary.coverage_pct,
|
|
overstaffedHours: plan.summary.overstaffed_hours,
|
|
understaffedHours: plan.summary.understaffed_hours,
|
|
days,
|
|
}
|
|
}
|
|
|
|
export function sensorForPlan(
|
|
sensors: Sensor[] | null | undefined,
|
|
plan: StaffingResponse | null | undefined,
|
|
): Sensor | null {
|
|
return sensors?.find((sensor) => sensor.id === plan?.sensor) ?? null
|
|
}
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* PreZero */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
export interface PrezeroMaterialStats {
|
|
readings: number
|
|
overfull: number
|
|
}
|
|
|
|
export interface PrezeroMeta {
|
|
source: string
|
|
generated_at: string
|
|
rows: number
|
|
containers: number
|
|
material_series: number
|
|
date_from: string
|
|
date_to: string
|
|
reference_date: string
|
|
overfull_readings: number
|
|
priority_rule: string
|
|
limitations: string[]
|
|
}
|
|
|
|
export interface PrezeroContainerMaterial {
|
|
readings: number
|
|
overfull_count: number
|
|
last_fill: number | null
|
|
last_is_overfull: boolean
|
|
last_date: string | null
|
|
}
|
|
|
|
export interface PrezeroContainer {
|
|
location_id: string
|
|
priority: 'high' | 'medium' | 'low'
|
|
priority_score: number
|
|
readings: number
|
|
overfull_count: number
|
|
overfull_rate: number
|
|
p95_fill: number
|
|
max_fill: number
|
|
mean_fill: number
|
|
last_fill: number | null
|
|
last_is_overfull: boolean
|
|
last_date: string | null
|
|
days_since_last: number | null
|
|
trend: number | null
|
|
materials: Record<string, PrezeroContainerMaterial>
|
|
}
|
|
|
|
export interface PrezeroBundle {
|
|
meta: PrezeroMeta
|
|
summary: {
|
|
priority_counts: { high: number; medium: number; low: number }
|
|
by_material: Record<string, PrezeroMaterialStats>
|
|
}
|
|
top: PrezeroContainer[]
|
|
}
|
|
|
|
export const PRIORITY_ORDER: readonly PrezeroContainer['priority'][] = [
|
|
'high',
|
|
'medium',
|
|
'low',
|
|
] as const
|
|
|
|
export function prezeroTotal(bundle: PrezeroBundle | null | undefined): number {
|
|
if (!bundle) return 0
|
|
const counts = bundle.summary.priority_counts
|
|
return counts.high + counts.medium + counts.low
|
|
}
|
|
|
|
export function priorityShare(bundle: PrezeroBundle | null | undefined, priority: string): number {
|
|
const total = prezeroTotal(bundle)
|
|
if (!total || !bundle) return 0
|
|
return (bundle.summary.priority_counts[priority as 'high' | 'medium' | 'low'] / total) * 100
|
|
}
|
|
|
|
export function shortContainerId(id: string): string {
|
|
return id.slice(0, 8)
|
|
}
|
|
|
|
/** One-line reason, built only from fields present in the artifact. */
|
|
export function prezeroReason(container: PrezeroContainer): string {
|
|
const pct = formatPercent(container.overfull_rate * 100, 0)
|
|
if (container.overfull_count > 0) {
|
|
return `${container.overfull_count} overfull ${container.overfull_count === 1 ? 'reading' : 'readings'} (${pct} of visits); p95 fill ${Math.round(container.p95_fill)}%.`
|
|
}
|
|
return `${container.readings} readings; p95 fill ${Math.round(container.p95_fill)}%; no overfull state reported.`
|
|
}
|