merge: sync main into sensing engine
ci / check (push) Successful in 6m26s
ci / check (pull_request) Successful in 1m15s

This commit is contained in:
Noel Sabia committed 2026-11-14 19:26:41 +01:00
commit 9ba70965ba
60 files changed
+15132 -87

No files matched your search

+97 -1
View File
@@ -1,5 +1,101 @@
<script setup lang="ts">
import {
iconCalendar,
iconChart,
iconCircleInformation,
iconFlash,
iconHome,
} from '@sit-onyx/icons'
const route = useRoute()
const config = useRuntimeConfig()
const usingMock = computed(() => {
const value = config.public.useMock
return value === true || value === '1' || value === 'true'
})
const isSensing = computed(() => route.path === '/' || route.path.startsWith('/sensors'))
const isCool = computed(() => route.path.startsWith('/cool'))
const isDarkPresentation = computed(
() => route.path === '/stage' || route.path === '/live' || route.path === '/cool/stage',
)
const isStandalone = computed(() => isCool.value || isDarkPresentation.value)
const bodyClass = computed(() =>
isDarkPresentation.value ? 'pc-presentation' : isCool.value ? 'pc-cool-presentation' : '',
)
const navigation = [
{ to: '/', label: 'Now', icon: iconHome },
{ to: '/forecast', label: 'Forecast', icon: iconChart },
{ to: '/plan', label: 'Plan', icon: iconCalendar },
{ to: '/simulate', label: 'Simulate', icon: iconFlash },
{ to: '/about', label: 'About', icon: iconCircleInformation },
]
const hiddenPageLabels: Record<string, string> = { '/control': 'Control' }
const activeLabel = computed(
() => navigation.find((item) => item.to === route.path)?.label ?? hiddenPageLabels[route.path] ?? 'PulseCast',
)
useHead(() => ({
bodyAttrs: { class: bodyClass.value },
}))
// Onyx renders its overflow navigation as a `menubar` whose direct child is a
// div, which fails the required-children rule. The list is site navigation,
// not an application menu, so remove the menu role rather than fake menuitems.
let navRoleObserver: MutationObserver | undefined
function fixNavAria() {
for (const list of document.querySelectorAll('.onyx-more-list[role="menubar"]')) {
list.setAttribute('role', 'none')
}
}
onMounted(() => {
fixNavAria()
navRoleObserver = new MutationObserver(fixNavAria)
navRoleObserver.observe(document.body, { childList: true, subtree: true })
})
onBeforeUnmount(() => navRoleObserver?.disconnect())
</script>
<template>
<NuxtLayout>
<NuxtLayout v-if="isSensing">
<NuxtPage />
</NuxtLayout>
<NuxtPage v-else-if="isStandalone" />
<OnyxAppLayout v-else>
<template #navBar>
<OnyxNavBar app-name="PulseCast" logo-url="/logo.svg" mobile="sm">
<OnyxUnstableNavButton
v-for="item in navigation"
:key="item.to"
:link="item.to"
:label="item.label"
:icon="item.icon"
/>
<template #contextArea>
<NuxtLink class="pc-present" to="/stage">Stage</NuxtLink>
<NuxtLink class="pc-present" to="/live">Live</NuxtLink>
</template>
<template #mobileActivePage>{{ activeLabel }}</template>
</OnyxNavBar>
</template>
<OnyxPageLayout>
<NuxtPage />
<template #footer>
<footer class="app-footer">
<span><strong>PulseCast</strong> — staff the pulse, not the noise.</span>
<span class="pc-small">
Decision support, not an optimizer.
<NuxtLink to="/about">Method &amp; limits</NuxtLink> ·
<NuxtLink to="/cool">Cool City public module</NuxtLink>
<template v-if="usingMock"> · demo data</template>
</span>
</footer>
</template>
</OnyxPageLayout>
</OnyxAppLayout>
</template>
+526
View File
@@ -0,0 +1,526 @@
:root {
--cc-ground: #f6f3ee;
--cc-surface: rgba(255, 255, 255, 0.86);
--cc-surface-solid: #fffdf9;
--cc-ink: #121212;
--cc-ink-2: #343434;
--cc-muted: #6b6b6b;
--cc-line: rgba(18, 18, 18, 0.12);
--cc-line-strong: rgba(18, 18, 18, 0.24);
--cc-heat: #e4572e;
--cc-heat-text: #a83a19;
--cc-heat-soft: #fbe8e2;
--cc-shade: #2f6fed;
--cc-shade-deep: #1f4fae;
--cc-shade-soft: #e5edff;
--cc-water: #3aa6b9;
--cc-focus: #a83a19;
--cc-radius: 28px;
--cc-shadow: 0 18px 60px rgba(18, 18, 18, 0.12);
--cc-shadow-soft: 0 8px 26px rgba(18, 18, 18, 0.07);
--cc-font: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Inter", "Segoe UI", sans-serif;
--cc-dark: #0b1114;
--cc-dark-2: #14191c;
--cc-dark-3: #1d2428;
--cc-dark-line: rgba(255, 255, 255, 0.14);
--cc-dark-muted: #a3a3a3;
--cc-heat-bright: #ff6b3d;
--cc-shade-bright: #6fa8ff;
--cc-water-bright: #7ad1df;
--cc-focus-dark: #ff9b76;
}
body.pc-cool-presentation {
background: var(--cc-ground);
color: var(--cc-ink);
}
body.pc-cool-presentation,
.cc-cool,
.cc-stage {
font-family: var(--cc-font);
}
.cc-cool,
.cc-cool *,
.cc-cool *::before,
.cc-cool *::after,
.cc-stage,
.cc-stage *,
.cc-stage *::before,
.cc-stage *::after,
.cc-city,
.cc-city *,
.cc-city *::before,
.cc-city *::after {
box-sizing: border-box;
font-family: var(--cc-font);
}
.cc-cool {
min-height: 100dvh;
padding-bottom: 3rem;
background: var(--cc-ground);
color: var(--cc-ink);
}
/* Top bar --------------------------------------------------------------- */
.cc-topbar {
position: sticky;
top: 0;
z-index: 10;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.55rem 0.9rem;
min-height: 60px;
padding: 0.65rem 1rem;
border-bottom: 1px solid var(--cc-line);
background: color-mix(in srgb, var(--cc-ground) 88%, transparent);
backdrop-filter: blur(18px) saturate(140%);
-webkit-backdrop-filter: blur(18px) saturate(140%);
}
.cc-wordmark {
display: inline-flex;
align-items: center;
gap: 0.5rem;
color: var(--cc-ink);
font-size: 0.96rem;
font-weight: 800;
letter-spacing: -0.03em;
text-decoration: none;
}
.cc-mark {
display: block;
width: 0.55rem;
height: 1.25rem;
border-radius: 999px;
background: linear-gradient(180deg, var(--cc-heat) 0 50%, var(--cc-shade) 50% 100%);
}
.cc-topbar__place {
color: var(--cc-muted);
font-size: 0.72rem;
font-variant-numeric: tabular-nums;
}
.cc-topbar__status {
display: inline-flex;
align-items: center;
gap: 0.3rem;
margin-inline-start: auto;
color: var(--cc-muted);
font-size: 0.62rem;
font-weight: 600;
letter-spacing: 0.03em;
}
.cc-topbar__status i {
display: block;
width: 0.4rem;
height: 0.4rem;
border-radius: 50%;
background: var(--cc-shade);
}
/* Phone ----------------------------------------------------------------- */
.cc-phone {
display: flex;
width: 100%;
max-width: 35rem;
flex-direction: column;
gap: 1rem;
margin-inline: auto;
padding: 1rem;
}
.cc-ruth {
display: flex;
flex-direction: column;
gap: 0.45rem;
padding: 0.4rem 0 0.7rem;
}
.cc-ruth h1 {
max-width: 13ch;
margin: 0;
font-size: clamp(2.6rem, 10.8vw, 4.2rem);
font-weight: 850;
letter-spacing: -0.06em;
line-height: 0.9;
text-wrap: balance;
}
.cc-ruth__copy {
max-width: 46ch;
margin: 0.15rem 0 0;
color: var(--cc-muted);
font-size: 0.98rem;
line-height: 1.5;
}
.cc-ruth__tag {
display: inline-flex;
width: fit-content;
margin-top: 0.25rem;
padding: 0.18rem 0.5rem;
border: 1px solid var(--cc-line);
border-radius: 999px;
color: var(--cc-muted);
font-size: 0.6rem;
font-weight: 600;
letter-spacing: 0.02em;
}
.cc-panel {
padding: 1rem;
border: 1px solid var(--cc-line);
border-radius: var(--cc-radius);
background: var(--cc-surface);
box-shadow: var(--cc-shadow-soft);
backdrop-filter: blur(18px) saturate(140%);
-webkit-backdrop-filter: blur(18px) saturate(140%);
}
.cc-time__head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 0.7rem;
margin-bottom: 0.55rem;
}
.cc-time__head h2 {
margin: 0;
color: var(--cc-muted);
font-size: 0.72rem;
font-weight: 650;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.cc-time__head strong {
font-size: clamp(2.6rem, 10vw, 3.6rem);
font-weight: 850;
letter-spacing: -0.06em;
line-height: 0.9;
font-variant-numeric: tabular-nums;
}
.cc-time :deep(.onyx-slider__marks),
.cc-time :deep(.onyx-slider__mark-label) {
color: var(--cc-muted);
font-family: var(--cc-font);
font-size: 0.65rem;
font-variant-numeric: tabular-nums;
}
.cc-time :deep(.onyx-slider__track) {
accent-color: var(--cc-shade);
}
.cc-vote-only {
display: flex;
min-height: calc(100dvh - 62px);
align-items: center;
justify-content: center;
padding: 2rem 1rem 3rem;
}
.cc-vote-only__inner {
width: 100%;
max-width: 34rem;
}
.cc-vote-only h1 {
max-width: 10ch;
margin: 0;
font-size: clamp(3rem, 12vw, 5rem);
font-weight: 850;
letter-spacing: -0.06em;
line-height: 0.9;
}
.cc-vote-only__lede {
max-width: 34ch;
margin: 0.8rem 0 1.4rem;
color: var(--cc-muted);
font-size: 1rem;
line-height: 1.45;
}
.cc-vote-only__buttons {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 0.5rem;
}
.cc-vote-only__confirmation {
padding: 1rem;
border: 1px solid var(--cc-line);
border-radius: 24px;
background: var(--cc-surface);
}
.cc-vote-only__confirmation p {
margin: 0;
font-size: 1rem;
line-height: 1.45;
}
.cc-details {
border: 1px solid var(--cc-line);
border-radius: 24px;
background: var(--cc-surface);
}
.cc-details summary:focus-visible,
.cc-city__method summary:focus-visible {
outline: 2px solid var(--cc-focus);
outline-offset: 2px;
}
.cc-details summary {
padding: 0.9rem 1rem;
color: var(--cc-ink);
font-size: 0.82rem;
font-weight: 650;
cursor: pointer;
}
.cc-details__body {
display: grid;
gap: 0.6rem;
padding: 0 1rem 1rem;
color: var(--cc-muted);
font-size: 0.82rem;
line-height: 1.55;
}
.cc-details__body p {
margin: 0;
}
.cc-details__body strong {
color: var(--cc-ink);
}
.cc-details__links {
display: flex;
flex-wrap: wrap;
gap: 0.8rem;
padding-top: 0.3rem;
}
.cc-details__links a {
color: var(--cc-ink);
font-weight: 700;
}
.cc-phone__footer {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 0.4rem 1rem;
padding-top: 1.1rem;
border-top: 1px solid var(--cc-line);
color: var(--cc-muted);
font-size: 0.68rem;
line-height: 1.45;
}
/* Onyx theming on the phone --------------------------------------------- */
.cc-cool {
--onyx-font-family-paragraph: var(--cc-font);
--onyx-font-family-h1: var(--cc-font);
--onyx-font-family-h2: var(--cc-font);
--onyx-font-family-h3: var(--cc-font);
--onyx-font-family-h4: var(--cc-font);
--onyx-font-family-data: var(--cc-font);
--onyx-radius-component-button: 999px;
--onyx-radius-component-container-soft: var(--cc-radius);
--onyx-radius-component-input: 999px;
--onyx-color-base-primary-500: var(--cc-ink);
--onyx-color-base-primary-600: var(--cc-ink);
--onyx-color-base-primary-900: var(--cc-ink);
--onyx-color-component-cta-default: var(--cc-ink);
--onyx-color-component-cta-default-hover: #000;
--onyx-color-text-icons-neutral-button: #fff;
--onyx-color-component-focus-primary: var(--cc-heat);
}
.cc-cool :deep(.onyx-button) {
min-height: 52px;
border-radius: 999px;
font-family: var(--cc-font);
font-weight: 650;
letter-spacing: -0.01em;
}
.cc-cool :deep(.onyx-button--outline) {
border-color: var(--cc-line-strong);
color: var(--cc-ink);
}
.cc-cool :deep(.onyx-button--outline:hover) {
background: var(--cc-ink);
border-color: var(--cc-ink);
color: var(--cc-ground);
}
.cc-cool :deep(.onyx-button__label) {
font-size: 0.92rem;
}
/* Stage ----------------------------------------------------------------- */
.cc-stage {
position: relative;
display: flex;
height: 100dvh;
flex-direction: column;
overflow: hidden;
background: var(--cc-dark);
color: var(--cc-ink);
}
.cc-stage__top {
position: relative;
z-index: 4;
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 0.7rem;
padding: 0.65rem clamp(1rem, 2.4vw, 2.4rem);
border-bottom: 1px solid var(--cc-line);
background: color-mix(in srgb, var(--cc-dark) 86%, transparent);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.cc-stage__wordmark {
color: var(--cc-ink);
}
.cc-stage__place {
color: var(--cc-muted);
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.cc-stage__round {
margin-inline-start: auto;
color: var(--cc-muted);
font-size: 0.7rem;
font-variant-numeric: tabular-nums;
letter-spacing: 0.03em;
}
.cc-dark {
--cc-ground: #0b1114;
--cc-surface: rgba(23, 28, 31, 0.88);
--cc-surface-solid: #131a1e;
--cc-ink: #f5f3ef;
--cc-ink-2: #dedbd4;
--cc-muted: #a3a3a3;
--cc-line: rgba(255, 255, 255, 0.14);
--cc-line-strong: rgba(255, 255, 255, 0.26);
--cc-heat: #ff6b3d;
--cc-heat-text: #ff9b76;
--cc-heat-soft: #2b1711;
--cc-shade: #6fa8ff;
--cc-shade-deep: #a9c8ff;
--cc-shade-soft: #142238;
--cc-water: #7ad1df;
--cc-focus: #ff9b76;
--cc-shadow: 0 24px 80px rgba(0, 0, 0, 0.45);
--cc-shadow-soft: 0 10px 30px rgba(0, 0, 0, 0.3);
color: var(--cc-ink);
}
.cc-dark .cc-wordmark {
color: var(--cc-ink);
}
.cc-dark .cc-topbar {
background: color-mix(in srgb, var(--cc-dark) 86%, transparent);
}
@media (min-width: 900px) {
.cc-phone {
display: grid;
max-width: 72rem;
grid-template-columns: minmax(0, 0.92fr) minmax(0, 1.08fr);
grid-template-areas:
"ruth routes"
"time routes"
"details details"
"footer footer";
gap: 1rem 1.5rem;
align-items: start;
padding: 1.5rem 1.5rem 3rem;
}
.cc-ruth {
grid-area: ruth;
padding-top: 0.5rem;
}
.cc-ruth h1 {
font-size: clamp(3rem, 4.6vw, 4.8rem);
}
.cc-time {
grid-area: time;
}
.cc-route {
grid-area: routes;
}
.cc-details {
grid-area: details;
margin-top: 0.5rem;
}
.cc-phone__footer {
grid-area: footer;
grid-column: 1 / -1;
margin-top: 0.5rem;
}
}
@media (max-width: 460px) {
.cc-topbar {
min-height: 56px;
padding: 0.55rem 0.8rem;
}
.cc-topbar__place {
font-size: 0.66rem;
}
.cc-topbar__status {
font-size: 0.58rem;
}
.cc-phone {
padding-inline: 0.8rem;
}
}
@media (prefers-reduced-motion: reduce) {
.cc-topbar,
.cc-panel {
backdrop-filter: none;
-webkit-backdrop-filter: none;
}
}
File diff suppressed because it is too large. Load diff
+155
View File
@@ -0,0 +1,155 @@
<script setup lang="ts">
import type { CoolCityCatchment, CoolCityPlace } from '#shared/cool'
import { createProjection, pathFromCoordinates } from '~/utils/cool-map'
const props = withDefaults(
defineProps<{
places: CoolCityPlace[]
catchments?: CoolCityCatchment[]
selectedRank?: number | null
showCatchments?: boolean
stage?: boolean
}>(),
{ catchments: () => [], selectedRank: null, showCatchments: false, stage: false },
)
const allPoints = computed(() => {
const placePoints = props.places.map((place) => ({ lat: place.lat, lon: place.lon }))
const centers = props.catchments.map((catchment) => catchment.center)
return [...placePoints, ...centers]
})
const project = computed(() => createProjection(allPoints.value, 1200, 800, 90))
const dots = computed(() =>
props.places.map((place) => ({
...place,
position: project.value({ lat: place.lat, lon: place.lon }),
})),
)
const rings = computed(() =>
props.catchments.map((catchment) => {
const ring = catchment.geometry.coordinates?.[0] ?? []
const path = ring.length
? pathFromCoordinates(
ring.map(([lon, lat]) => [lon, lat] as [number, number]),
project.value,
)
: ''
return {
...catchment,
path,
centerPoint: project.value(catchment.center),
selected: props.selectedRank === catchment.rank,
}
}),
)
</script>
<template>
<figure class="cc-placesmap" :class="{ 'cc-placesmap--stage': props.stage }">
<svg
class="cc-placesmap__canvas"
viewBox="0 0 1200 800"
preserveAspectRatio="xMidYMid meet"
role="img"
:aria-label="`Map of ${places.length} cool places near the eight Heilbronn sensor catchments.`"
>
<defs>
<pattern id="cc-places-grid" width="44" height="44" patternUnits="userSpaceOnUse">
<circle cx="1" cy="1" r="1" fill="currentColor" />
</pattern>
</defs>
<rect class="cc-placesmap__ground" x="0" y="0" width="1200" height="800" />
<rect class="cc-placesmap__grid" x="0" y="0" width="1200" height="800" fill="url(#cc-places-grid)" />
<g v-if="props.showCatchments">
<path
v-for="ring in rings"
:key="ring.sensor_id"
class="cc-placesmap__ring"
:class="{ 'is-selected': ring.selected }"
:d="ring.path"
/>
<g v-for="ring in rings" :key="`${ring.sensor_id}-label`" class="cc-placesmap__rank">
<text :x="ring.centerPoint.x" :y="ring.centerPoint.y + 6" text-anchor="middle">{{ ring.rank }}</text>
</g>
</g>
<g class="cc-placesmap__dots">
<circle
v-for="dot in dots"
:key="`${dot.name}-${dot.lat}-${dot.lon}`"
:cx="dot.position.x"
:cy="dot.position.y"
:r="props.stage ? 9 : 6"
/>
</g>
</svg>
<p class="cc-placesmap__stamp">Relative map · OSM cool places · no heatmap</p>
</figure>
</template>
<style scoped>
.cc-placesmap {
position: relative;
width: 100%;
height: 100%;
min-height: 24rem;
margin: 0;
overflow: hidden;
color: var(--cc-line);
}
.cc-placesmap__canvas {
display: block;
width: 100%;
height: 100%;
}
.cc-placesmap__ground {
fill: var(--cc-ground, #f6f3ee);
}
.cc-placesmap__grid {
color: var(--cc-line, rgba(18, 18, 18, 0.12));
opacity: 0.5;
}
.cc-placesmap__ring {
fill: color-mix(in srgb, var(--cc-shade) 8%, transparent);
stroke: var(--cc-line);
stroke-width: 1.5;
}
.cc-placesmap__ring.is-selected {
fill: color-mix(in srgb, var(--cc-heat) 14%, transparent);
stroke: var(--cc-heat);
stroke-width: 3;
}
.cc-placesmap__rank text {
fill: var(--cc-muted);
font-size: 17px;
font-weight: 750;
}
.cc-placesmap__dots circle {
fill: var(--cc-shade);
stroke: var(--cc-ground, #f6f3ee);
stroke-width: 2;
}
.cc-placesmap__stamp {
position: absolute;
right: 1rem;
bottom: 0.8rem;
margin: 0;
color: var(--cc-muted);
font-family: var(--cc-font);
font-size: 0.62rem;
letter-spacing: 0.03em;
}
</style>
+174
View File
@@ -0,0 +1,174 @@
<script setup lang="ts">
import type { CoolRouteOption, CoolRouteValues } from '#shared/cool'
import { coolDistance, coolMinutes, coolShade, coolStops, coolValues } from '~/utils/cool'
const props = defineProps<{
route: CoolRouteOption
values: CoolRouteValues | null
reason: string
}>()
const data = computed(() => coolValues(props.values))
const ramp = computed(() =>
props.route.ramp ? props.route.ramp.incline.replace('.0%', '%') : 'no ramp',
)
</script>
<template>
<article class="cc-route-card" :class="`cc-route-card--${route.id}`">
<div class="cc-route-card__head">
<span class="cc-route-card__dot" aria-hidden="true" />
<h3 class="cc-route-card__label">{{ route.label }}</h3>
</div>
<p class="cc-route-card__reason">{{ reason }}</p>
<p class="cc-route-card__metrics">
<span><strong>{{ coolShade(data.shadePct) }}</strong> shade</span>
<span><strong>{{ coolMinutes(data.directSunMin) }}</strong> direct sun</span>
<span>{{ coolDistance(data.distanceM) }}</span>
<span>{{ coolMinutes(data.durationMin) }}</span>
<span class="cc-route-card__metric-break" aria-hidden="true" />
<span>{{ ramp }}</span>
<span>water {{ coolStops(data.waterStops) }}</span>
<span>benches {{ coolStops(data.benchStops) }}</span>
</p>
<div class="cc-route-card__action">
<slot name="action" />
</div>
</article>
</template>
<style scoped>
.cc-route-card {
display: flex;
width: 100%;
min-width: 0;
flex-direction: column;
gap: 0.5rem;
padding: 1.1rem 1.15rem 1.05rem;
border-radius: 28px;
background: var(--cc-surface, rgba(255, 255, 255, 0.86));
box-shadow:
0 0 0 1px color-mix(in srgb, var(--cc-shade) 24%, transparent),
0 18px 48px rgba(18, 18, 18, 0.08);
backdrop-filter: blur(20px) saturate(140%);
-webkit-backdrop-filter: blur(20px) saturate(140%);
color: var(--cc-ink);
}
.cc-route-card__head {
display: flex;
align-items: center;
gap: 0.55rem;
}
.cc-route-card__dot {
display: block;
width: 0.5rem;
height: 0.5rem;
flex: 0 0 auto;
border-radius: 50%;
background: var(--cc-ink);
}
.cc-route-card--shortest .cc-route-card__dot {
background: var(--cc-heat);
}
.cc-route-card--shaded .cc-route-card__dot {
background: var(--cc-shade);
}
.cc-route-card__label {
margin: 0;
font-size: clamp(1.7rem, 5.6vw, 2.5rem);
font-weight: 850;
letter-spacing: -0.045em;
line-height: 0.95;
}
.cc-route-card__reason {
max-width: 52ch;
margin: 0;
color: var(--cc-muted);
font-size: 0.88rem;
line-height: 1.4;
}
.cc-route-card__metrics {
display: flex;
flex-wrap: wrap;
gap: 0.15rem 0;
margin: 0.1rem 0 0;
color: var(--cc-ink-2);
font-size: 0.82rem;
line-height: 1.6;
font-variant-numeric: tabular-nums;
}
.cc-route-card__metrics > span {
white-space: nowrap;
}
.cc-route-card__metrics > span:not(.cc-route-card__metric-break):not(:last-child)::after {
content: "·";
margin-inline: 0.55rem;
color: var(--cc-line-strong);
}
.cc-route-card__metric-break {
display: none;
}
.cc-route-card__metrics strong {
color: var(--cc-ink);
font-weight: 750;
}
.cc-route-card__action {
margin-top: 0.3rem;
}
.cc-route-card__action :deep(.onyx-button) {
width: 100%;
min-height: 52px;
border-radius: 999px;
font-family: var(--cc-font);
font-weight: 650;
letter-spacing: -0.01em;
}
.cc-route-card__action :deep(.onyx-button__label) {
font-size: 0.92rem;
}
@media (min-width: 640px) {
.cc-route-card {
padding: 1.35rem 1.45rem 1.3rem;
}
.cc-route-card__metric-break {
display: block;
flex-basis: 100%;
height: 0;
}
.cc-route-card__metrics > span:not(.cc-route-card__metric-break):has(+ .cc-route-card__metric-break)::after {
content: none;
}
.cc-route-card__action :deep(.onyx-button) {
width: auto;
min-width: 15rem;
}
}
@media (prefers-reduced-motion: reduce) {
.cc-route-card {
backdrop-filter: none;
-webkit-backdrop-filter: none;
}
}
</style>
+216
View File
@@ -0,0 +1,216 @@
<script setup lang="ts">
import type { CoolRouteBundle, CoolRouteId } from '#shared/cool'
import { createProjection, pathFromCoordinates } from '~/utils/cool-map'
const props = defineProps<{
bundle: CoolRouteBundle
selectedRoute?: CoolRouteId | null
stage?: boolean
}>()
const allPoints = computed(() => {
const routePoints = props.bundle.routes.flatMap((route) =>
route.geometry.map(([lon, lat]) => ({ lat, lon })),
)
const water = props.bundle.water.map((point) => ({ lat: point.lat, lon: point.lon }))
return [...routePoints, ...water]
})
const project = computed(() => createProjection(allPoints.value))
const routes = computed(() =>
props.bundle.routes.map((route) => ({
...route,
path: pathFromCoordinates(route.geometry, project.value),
isSelected: props.selectedRoute === route.id,
})),
)
const origin = computed(() => {
const lat = props.bundle.origin.lat
const lon = props.bundle.origin.lon
return lat !== undefined && lon !== undefined ? project.value({ lat, lon }) : null
})
const destination = computed(() => {
const lat = props.bundle.destination.lat
const lon = props.bundle.destination.lon
return lat !== undefined && lon !== undefined ? project.value({ lat, lon }) : null
})
const water = computed(() =>
props.bundle.water.map((point) => ({ ...point, position: project.value({ lat: point.lat, lon: point.lon }) })),
)
</script>
<template>
<figure class="cc-routemap" :class="{ 'cc-routemap--stage': props.stage }">
<svg
class="cc-routemap__canvas"
viewBox="0 0 1200 800"
preserveAspectRatio="xMidYMid meet"
role="img"
:aria-label="`Route map from ${props.bundle.origin.name} to ${props.bundle.destination.name}. Shortest, shaded and accessible routes with modelled shade.`"
>
<defs>
<pattern id="cc-route-grid" width="48" height="48" patternUnits="userSpaceOnUse">
<circle cx="1" cy="1" r="1" fill="currentColor" />
</pattern>
</defs>
<rect class="cc-routemap__ground" x="0" y="0" width="1200" height="800" />
<rect class="cc-routemap__grid" x="0" y="0" width="1200" height="800" fill="url(#cc-route-grid)" />
<path
v-for="route in routes"
:key="route.id"
class="cc-routemap__route"
:class="[
`cc-routemap__route--${route.id}`,
{ 'is-selected': route.isSelected, 'is-dim': props.selectedRoute && !route.isSelected },
]"
:d="route.path"
pathLength="1"
fill="none"
vector-effect="non-scaling-stroke"
/>
<g v-for="point in water" :key="point.name" class="cc-routemap__water">
<circle :cx="point.position.x" :cy="point.position.y" r="7" />
</g>
<g v-if="origin" class="cc-routemap__endpoint">
<circle :cx="origin.x" :cy="origin.y" r="16" />
<text :x="origin.x" :y="origin.y + 5" text-anchor="middle" class="cc-routemap__letter">S</text>
<text :x="origin.x" :y="origin.y + 44" text-anchor="middle" class="cc-routemap__place">{{ props.bundle.origin.name }}</text>
</g>
<g v-if="destination" class="cc-routemap__endpoint">
<circle :cx="destination.x" :cy="destination.y" r="16" />
<text :x="destination.x" :y="destination.y + 5" text-anchor="middle" class="cc-routemap__letter">M</text>
<text :x="destination.x" :y="destination.y - 30" text-anchor="middle" class="cc-routemap__place">{{ props.bundle.destination.name }}</text>
</g>
</svg>
<p class="cc-routemap__stamp">OSM route geometry · modelled shade · no basemap</p>
</figure>
</template>
<style scoped>
.cc-routemap {
position: relative;
width: 100%;
height: 100%;
min-height: 24rem;
margin: 0;
overflow: hidden;
color: var(--cc-line);
}
.cc-routemap__canvas {
display: block;
width: 100%;
height: 100%;
}
.cc-routemap__ground {
fill: var(--cc-ground, #f6f3ee);
}
.cc-routemap__grid {
color: var(--cc-line, rgba(18, 18, 18, 0.12));
opacity: 0.55;
}
.cc-routemap__route {
stroke-linecap: round;
stroke-linejoin: round;
opacity: 0.9;
transition: opacity 240ms ease;
animation: cc-route-draw 1.1s cubic-bezier(0.22, 1, 0.36, 1) both;
}
.cc-routemap__route--shortest {
stroke: var(--cc-heat);
stroke-width: 5;
}
.cc-routemap__route--shaded {
stroke: var(--cc-shade);
stroke-width: 6;
}
.cc-routemap__route--accessible {
stroke: var(--cc-ink);
stroke-width: 7;
}
.cc-routemap__route.is-selected {
opacity: 1;
stroke-width: 9;
}
.cc-routemap__route.is-dim {
opacity: 0.38;
}
.cc-routemap__water circle {
fill: var(--cc-shade);
stroke: var(--cc-ground, #f6f3ee);
stroke-width: 3;
}
.cc-routemap__endpoint circle {
fill: var(--cc-ink);
stroke: var(--cc-ground, #f6f3ee);
stroke-width: 4;
}
.cc-routemap__letter {
fill: var(--cc-ground, #f6f3ee);
font-size: 16px;
font-weight: 800;
}
.cc-routemap__place {
fill: var(--cc-ink);
font-size: 26px;
font-weight: 800;
letter-spacing: -0.03em;
}
.cc-routemap__stamp {
position: absolute;
right: 1rem;
bottom: 0.8rem;
margin: 0;
color: var(--cc-muted);
font-family: var(--cc-font);
font-size: 0.62rem;
letter-spacing: 0.03em;
}
.cc-routemap--stage {
min-height: 100%;
}
.cc-routemap--stage .cc-routemap__place,
.cc-routemap--stage .cc-routemap__endpoint {
display: none;
}
.cc-routemap--stage .cc-routemap__letter {
font-size: 20px;
}
@keyframes cc-route-draw {
from {
stroke-dasharray: 1;
stroke-dashoffset: 1;
}
to {
stroke-dasharray: 1;
stroke-dashoffset: 0;
}
}
@media (prefers-reduced-motion: reduce) {
.cc-routemap__route {
animation: none;
}
}
</style>
+128
View File
@@ -0,0 +1,128 @@
<script setup lang="ts">
import { LIVE_LABELS, liveAge } from '#shared/live'
import type { LiveConnection } from '#shared/live'
const props = withDefaults(
defineProps<{
status: LiveConnection
lastEventAt?: string
compact?: boolean
dark?: boolean
}>(),
{ lastEventAt: '', compact: false, dark: false },
)
const label = computed(() => LIVE_LABELS[props.status])
const age = computed(() => (props.lastEventAt ? liveAge(props.lastEventAt) : ''))
</script>
<template>
<span
class="pc-status"
:class="[`pc-status--${status}`, { 'pc-status--compact': compact, 'pc-status--dark': dark }]"
role="status"
aria-live="polite"
:title="lastEventAt ? `Last event ${age}` : undefined"
>
<span class="pc-status__dot" aria-hidden="true" />
<span class="pc-status__label">{{ label }}</span>
<span v-if="lastEventAt && !compact" class="pc-status__age">{{ age }}</span>
</span>
</template>
<style scoped>
.pc-status {
display: inline-flex;
align-items: center;
gap: 0.4rem;
color: var(--pc-muted, #6e665a);
font-size: 0.72rem;
font-weight: 700;
letter-spacing: 0.04em;
line-height: 1;
text-transform: uppercase;
white-space: nowrap;
}
.pc-status__dot {
width: 0.45rem;
height: 0.45rem;
flex: none;
border-radius: 50%;
background: currentColor;
}
.pc-status__label {
color: var(--pc-ink, #16130f);
}
.pc-status--live .pc-status__dot {
background: var(--pc-green, #2e6b4f);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--pc-green, #2e6b4f) 16%, transparent);
}
.pc-status--polling .pc-status__dot {
background: var(--pc-signal-text, #b63a00);
}
.pc-status--offline .pc-status__dot {
background: var(--pc-danger, #b3261e);
}
.pc-status--connecting .pc-status__dot {
background: var(--pc-muted, #6e665a);
}
.pc-status__age {
color: var(--pc-muted, #6e665a);
font-size: 0.66rem;
font-weight: 500;
letter-spacing: 0.02em;
text-transform: none;
}
.pc-status--compact .pc-status__label {
font-size: 0.66rem;
}
.pc-status--dark {
color: var(--pc-dark-muted, #b4ae9f);
}
.pc-status--dark .pc-status__label {
color: var(--pc-paper, #f4efe6);
}
.pc-status--dark .pc-status__age {
color: var(--pc-dark-muted, #b4ae9f);
}
.pc-status--dark.pc-status--live .pc-status__dot {
background: var(--pc-green-bright, #5fc99a);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--pc-green-bright, #5fc99a) 18%, transparent);
}
.pc-status--dark.pc-status--polling .pc-status__dot {
background: var(--pc-signal-bright, #ff6a2a);
}
.pc-status--dark.pc-status--offline .pc-status__dot {
background: var(--pc-danger-bright, #ff7a6e);
}
@media (prefers-reduced-motion: no-preference) {
.pc-status--live .pc-status__dot {
animation: pc-status-pulse 2.4s ease-in-out infinite;
}
}
@keyframes pc-status-pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.55;
}
}
</style>
+33
View File
@@ -0,0 +1,33 @@
<script setup lang="ts">
withDefaults(
defineProps<{
label: string
value: string
hint?: string
badge?: string
badgeColor?: 'neutral' | 'danger' | 'success' | 'primary' | 'warning' | 'info'
icon?: string
}>(),
{ badgeColor: 'neutral' },
)
</script>
<template>
<OnyxCard class="stat-card">
<p class="stat-label">
<OnyxIcon v-if="icon" :icon="icon" size="16px" color="primary" />
{{ label }}
</p>
<p class="stat-value">{{ value }}</p>
<OnyxBadge v-if="badge" :color="badgeColor" density="compact">{{ badge }}</OnyxBadge>
<p v-if="hint" class="stat-hint">{{ hint }}</p>
</OnyxCard>
</template>
<style scoped>
.stat-label {
display: flex;
align-items: center;
gap: 0.35rem;
}
</style>
+108
View File
@@ -0,0 +1,108 @@
<script setup lang="ts">
import type { Point } from '#shared/types'
const props = withDefaults(
defineProps<{
points: Point[]
label: string
height?: number
showPeak?: boolean
}>(),
{ height: 56, showPeak: true },
)
const chart = computed(() => {
const values = props.points.map((point) => point.v)
if (!values.length) return { path: 'M 0 30 L 100 30', peak: null as null | { x: number; y: number } }
const max = Math.max(...values, 1)
const step = values.length > 1 ? 100 / (values.length - 1) : 100
const coords = values.map((value, index) => ({
x: index * step,
y: 30 - (Math.max(0, value) / max) * 27,
}))
const path = coords.map((coord, index) => `${index === 0 ? 'M' : 'L'} ${coord.x.toFixed(2)} ${coord.y.toFixed(2)}`).join(' ')
const peakIndex = values.indexOf(Math.max(...values))
return { path, peak: coords[peakIndex] ?? null }
})
const pathKey = computed(() => `${props.points.length}-${props.points[0]?.t ?? ''}-${props.points.at(-1)?.v ?? ''}`)
</script>
<template>
<svg
class="pc-pulse"
:style="{ height: `${height}px` }"
viewBox="0 0 100 32"
preserveAspectRatio="none"
role="img"
:aria-label="label"
>
<title>{{ label }}</title>
<line class="pc-pulse__baseline" x1="0" y1="30" x2="100" y2="30" />
<path
:key="pathKey"
class="pc-pulse__line"
:d="chart.path"
pathLength="1"
fill="none"
vector-effect="non-scaling-stroke"
/>
<circle
v-if="showPeak && chart.peak"
class="pc-pulse__peak"
:cx="chart.peak.x"
:cy="chart.peak.y"
r="1.8"
vector-effect="non-scaling-stroke"
/>
</svg>
</template>
<style scoped>
.pc-pulse {
display: block;
width: 100%;
overflow: visible;
color: var(--pc-pulse-color, var(--pc-line-strong, #8e8475));
}
.pc-pulse__baseline {
stroke: currentColor;
stroke-width: 0.6;
opacity: 0.35;
vector-effect: non-scaling-stroke;
}
.pc-pulse__line {
stroke: currentColor;
stroke-width: 1.5;
stroke-linejoin: round;
stroke-linecap: round;
stroke-dasharray: 1;
stroke-dashoffset: 0;
vector-effect: non-scaling-stroke;
animation: pc-pulse-draw 900ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.pc-pulse__peak {
fill: var(--pc-signal, #e84100);
stroke: var(--pc-paper, #f4efe6);
stroke-width: 0.8;
vector-effect: non-scaling-stroke;
}
@keyframes pc-pulse-draw {
from {
stroke-dashoffset: 1;
}
to {
stroke-dashoffset: 0;
}
}
@media (prefers-reduced-motion: reduce) {
.pc-pulse__line {
animation: none;
}
}
</style>
+57
View File
@@ -0,0 +1,57 @@
<script setup lang="ts">
import type { Sensor } from '#shared/types'
const props = defineProps<{
sensors: Sensor[]
activeId: string
}>()
const emit = defineEmits<{
select: [sensorId: string]
}>()
const bounds = computed(() => {
const lats = props.sensors.map((sensor) => sensor.lat)
const lons = props.sensors.map((sensor) => sensor.lon)
const pad = 0.0009
return {
minLat: Math.min(...lats) - pad,
maxLat: Math.max(...lats) + pad,
minLon: Math.min(...lons) - pad,
maxLon: Math.max(...lons) + pad,
}
})
function position(sensor: Sensor) {
const { minLat, maxLat, minLon, maxLon } = bounds.value
const x = ((sensor.lon - minLon) / (maxLon - minLon)) * 76 + 12
const y = ((maxLat - sensor.lat) / (maxLat - minLat)) * 52 + 30
return { left: `${x}%`, top: `${y}%` }
}
</script>
<template>
<div class="map-frame" role="group" aria-label="Schematic map of the eight Heilbronn sensors">
<div class="map-frame__label">
<OnyxBadge color="info" density="compact">Schematic</OnyxBadge>
<p class="small muted" style="margin: 0.35rem 0 0">
Relative sensor positions in the 580 m cluster. Not a city-wide heatmap.
</p>
</div>
<button
v-for="(sensor, index) in props.sensors"
:key="sensor.id"
type="button"
class="sensor-pin"
:class="{ 'sensor-pin--active': sensor.id === props.activeId }"
:style="position(sensor)"
:aria-label="`${sensor.name}: mean ${sensor.mean}, p95 ${sensor.p95}`"
:aria-pressed="sensor.id === props.activeId"
@click="emit('select', sensor.id)"
>
<span class="sensor-pin__dot">{{ index + 1 }}</span>
<span class="sensor-pin__name">{{ sensor.name }}</span>
</button>
</div>
</template>
+168
View File
@@ -0,0 +1,168 @@
<script setup lang="ts">
import { iconUpload } from '@sit-onyx/icons'
interface TrainResponse {
job_id: string
status: string
model: 'small' | 'forecast'
submitted_at: string
}
interface TrainJob {
job_id: string
status: 'queued' | 'running' | 'succeeded' | 'failed'
model: 'small' | 'forecast'
metrics: Record<string, number | string> | null
model_version: string | null
error: string | null
}
const file = ref<File | null>(null)
const model = ref<'small' | 'forecast'>('small')
const submitting = ref(false)
const polling = ref(false)
const job = ref<TrainJob | null>(null)
const errorMessage = ref('')
let pollTimer: ReturnType<typeof setInterval> | undefined
const modelOptions = [
{ label: 'Small busy classifier (fast demo)', value: 'small' },
{ label: 'Global forecast model (slower)', value: 'forecast' },
]
const statusColor = computed(() => {
switch (job.value?.status) {
case 'succeeded':
return 'success' as const
case 'failed':
return 'danger' as const
case 'running':
return 'info' as const
default:
return 'neutral' as const
}
})
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/${encodeURIComponent(jobId)}`)
job.value = result
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.')
}
}
}, 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)
formData.append('file', file.value)
const response = await $fetch<TrainResponse>('/api/train', { method: 'POST', body: formData })
await poll(response.job_id)
} catch (error) {
errorMessage.value = apiErrorMessage(
error,
'Training submission failed. Check the Go API and its FastAPI training upstream.',
)
} finally {
submitting.value = false
}
}
onBeforeUnmount(stopPolling)
</script>
<template>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Train new data</OnyxHeadline>
<OnyxBadge color="info" density="compact">Server proxy</OnyxBadge>
</div>
<p class="small muted" style="margin-top: 0">
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="Challenge CSV schema. Required."
:accept="['text/csv']"
max-size="50MiB"
/>
<OnyxSelect
v-model="model"
label="Model"
list-label="Available models"
:options="modelOptions"
/>
<div class="form-actions">
<OnyxButton
type="submit"
label="Start training"
:icon="iconUpload"
: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>
<p v-if="errorMessage" class="small" style="color: var(--onyx-color-text-icons-danger-intense)">
{{ errorMessage }}
</p>
<div v-if="job" class="train-status">
<OnyxBadge :color="statusColor">{{ job.status }}</OnyxBadge>
<span class="small muted">Job {{ job.job_id }} · {{ job.model }}</span>
<OnyxBadge v-if="job.model_version" color="neutral" density="compact">
{{ job.model_version }}
</OnyxBadge>
</div>
<dl v-if="job?.metrics" class="metric-list" style="margin-top: var(--onyx-density-md)">
<div v-for="(value, key) in job.metrics" :key="key">
<dt>{{ key }}</dt>
<dd>{{ value }}</dd>
</div>
</dl>
<p v-if="job?.error" class="small" style="color: var(--onyx-color-text-icons-danger-intense)">
{{ job.error }}
</p>
</OnyxCard>
</template>
+25
View File
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { iconCloud, iconSunny } from '@sit-onyx/icons'
import type { DailyWeather } from '#shared/insights'
import { formatShortDate, formatWeekdayShort } from '~/utils/format'
const props = defineProps<{
days: DailyWeather[]
}>()
function iconFor(kind: DailyWeather['kind']) {
return kind === 'sunny' || kind === 'partly-cloudy' ? iconSunny : iconCloud
}
</script>
<template>
<div class="weather-strip" role="list" aria-label="Weather forecast for the plan week">
<div v-for="day in props.days" :key="day.date" class="weather-day" role="listitem">
<strong>{{ formatWeekdayShort(day.date) }} {{ formatShortDate(day.date) }}</strong>
<OnyxIcon :icon="iconFor(day.kind)" size="24px" color="primary" />
<span>{{ Math.round(day.tempMin) }}–{{ Math.round(day.tempMax) }} °C</span>
<span class="muted">{{ day.precipMm.toFixed(1) }} mm</span>
<span class="muted">{{ Math.round(day.cloudPct) }}% cloud</span>
</div>
</div>
</template>
+419
View File
@@ -0,0 +1,419 @@
<script setup lang="ts">
import type { Point } from '#shared/types'
import type { PlanDay } from '~/utils/plan'
const props = withDefaults(
defineProps<{
days: PlanDay[]
peakDate?: string
selectedDate?: string
interactive?: boolean
dense?: boolean
large?: boolean
dark?: boolean
showPulse?: boolean
label?: string
}>(),
{
peakDate: '',
selectedDate: '',
interactive: false,
dense: false,
large: false,
dark: false,
showPulse: false,
label: 'Weekly shift board',
},
)
const emit = defineEmits<{ select: [date: string] }>()
function duration(shift: { start: string; end: string }): number {
return Math.max(0.5, Number(shift.end.slice(0, 2)) - Number(shift.start.slice(0, 2)))
}
function pulseOf(day: PlanDay): Point[] {
return day.hours.map((hour) => ({ t: hour.t, v: hour.footfall }))
}
function dayLabel(day: PlanDay): string {
const blocks = day.shifts.map((shift) => `${shift.start}–${shift.end}: ${shift.staff} staff`).join(', ')
return `${day.weekdayLong} ${day.dayNumber} ${day.month}: ${blocks || 'no shifts'}. ${day.staffHours} staff-hours.`
}
function activate(day: PlanDay) {
if (props.interactive) emit('select', day.date)
}
</script>
<template>
<div
class="pc-board"
:class="{
'pc-board--dense': dense,
'pc-board--large': large,
'pc-board--dark': dark,
'pc-board--interactive': interactive,
}"
role="group"
:aria-label="label"
>
<component
:is="interactive ? 'button' : 'div'"
v-for="day in days"
:key="day.date"
class="pc-board__day"
:class="{
'pc-board__day--peak': day.date === peakDate,
'pc-board__day--selected': day.date === selectedDate,
}"
:type="interactive ? 'button' : undefined"
:aria-pressed="interactive ? day.date === selectedDate : undefined"
:aria-label="interactive ? dayLabel(day) : undefined"
@click="activate(day)"
>
<span class="pc-board__head">
<span class="pc-board__weekday">{{ day.weekday }}</span>
<span class="pc-board__date">{{ day.dayNumber }}</span>
<span v-if="day.date === peakDate" class="pc-board__peak" aria-hidden="true">Peak</span>
</span>
<PulseLine
v-if="showPulse && day.hours.length"
class="pc-board__pulse"
:points="pulseOf(day)"
:height="dense ? 16 : large ? 38 : 22"
:show-peak="false"
:label="`Forecast footfall for ${day.weekdayLong} ${day.dayNumber}`"
/>
<span class="pc-board__track" aria-hidden="true">
<span
v-for="shift in day.shifts"
:key="`${shift.date}-${shift.start}`"
class="pc-board__block"
:class="{ 'pc-board__block--short': duration(shift) < 3 }"
:style="{ flex: `${duration(shift)} 1 0` }"
>
<span class="pc-board__staff">{{ shift.staff }}</span>
<span v-if="!dense" class="pc-board__time">{{ shift.start }}–{{ shift.end }}</span>
</span>
<span v-if="!day.shifts.length" class="pc-board__empty">No shifts</span>
</span>
<span class="pc-board__foot" aria-hidden="true">
<span class="pc-board__hours">{{ day.staffHours }}h</span>
<span v-if="!dense" class="pc-board__peakstaff">{{ day.peakStaff }} peak</span>
</span>
</component>
</div>
</template>
<style scoped>
.pc-board {
--pc-board-block: var(--pc-paper-2, #e9e3d7);
--pc-board-border: var(--pc-line-strong, #a99f8e);
--pc-board-text: var(--pc-ink, #16130f);
display: grid;
grid-auto-flow: column;
grid-auto-columns: minmax(0, 1fr);
gap: 1px;
width: 100%;
background: var(--pc-line, #d3caba);
border-block: 1px solid var(--pc-board-border);
}
.pc-board--dense {
gap: 1px;
}
.pc-board__day {
display: flex;
min-width: 0;
min-height: 0;
flex-direction: column;
gap: 0.35rem;
padding: 0.55rem 0.5rem 0.5rem;
border: 0;
background: var(--pc-paper, #f4efe6);
color: var(--pc-board-text);
font: inherit;
text-align: left;
}
.pc-board--interactive .pc-board__day {
min-height: 44px;
cursor: pointer;
transition: background-color 160ms ease, outline-color 160ms ease;
}
.pc-board--interactive .pc-board__day:hover {
background: var(--pc-paper-2, #e9e3d7);
}
.pc-board__day:focus-visible {
outline: 2px solid var(--pc-focus, #b63a00);
outline-offset: -3px;
z-index: 1;
}
.pc-board__day--peak {
background: var(--pc-signal-wash, #ffe4d6);
box-shadow: inset 0 3px 0 var(--pc-signal, #e84100);
}
.pc-board__day--selected {
outline: 2px solid var(--pc-ink, #16130f);
outline-offset: -2px;
}
.pc-board__head {
display: flex;
align-items: baseline;
gap: 0.3rem;
min-width: 0;
}
.pc-board__weekday {
color: var(--pc-muted, #6e665a);
font-size: 0.62rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.pc-board__date {
font-size: 0.95rem;
font-weight: 800;
letter-spacing: -0.02em;
font-variant-numeric: tabular-nums;
}
.pc-board__peak {
margin-inline-start: auto;
color: var(--pc-signal-text, #b63a00);
font-size: 0.55rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.pc-board__pulse {
--pc-pulse-color: var(--pc-board-border);
margin-block: 0.1rem;
}
.pc-board__track {
display: flex;
min-height: 9rem;
flex: 1 1 auto;
flex-direction: column;
gap: 2px;
}
.pc-board__block {
display: flex;
min-height: 0;
flex-direction: column;
align-items: flex-start;
justify-content: center;
gap: 0.05rem;
padding: 0.2rem 0.35rem;
border: 1px solid var(--pc-board-border);
background: var(--pc-board-block);
color: var(--pc-board-text);
overflow: hidden;
}
.pc-board__day--peak .pc-board__block {
border-color: var(--pc-signal-text, #b63a00);
background: var(--pc-signal, #e84100);
color: var(--pc-ink, #16130f);
}
.pc-board__staff {
font-size: 1.35rem;
font-weight: 800;
line-height: 0.9;
letter-spacing: -0.03em;
font-variant-numeric: tabular-nums;
}
.pc-board__time {
color: var(--pc-ink-2, #2a261f);
font-size: 0.55rem;
font-weight: 650;
letter-spacing: 0.02em;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.pc-board__day--peak .pc-board__time {
color: var(--pc-ink, #16130f);
}
.pc-board__block--short .pc-board__time {
display: none;
}
.pc-board__block--short .pc-board__staff {
font-size: 1.05rem;
}
.pc-board__empty {
display: grid;
flex: 1;
place-items: center;
border: 1px dashed var(--pc-board-border);
color: var(--pc-muted, #6e665a);
font-size: 0.65rem;
}
.pc-board__foot {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 0.2rem;
margin-top: auto;
color: var(--pc-muted, #6e665a);
font-size: 0.62rem;
font-variant-numeric: tabular-nums;
}
.pc-board__hours {
color: var(--pc-board-text);
font-weight: 700;
}
.pc-board__peakstaff {
white-space: nowrap;
}
/* Dense phone/stage variants */
.pc-board--dense .pc-board__day {
padding: 0.35rem 0.25rem 0.3rem;
gap: 0.2rem;
}
.pc-board--dense .pc-board__track {
min-height: 6.5rem;
}
.pc-board--dense .pc-board__staff {
font-size: 0.9rem;
}
.pc-board--dense .pc-board__weekday {
font-size: 0.52rem;
}
.pc-board--dense .pc-board__date {
font-size: 0.78rem;
}
.pc-board--dense .pc-board__foot {
font-size: 0.52rem;
}
.pc-board--dense .pc-board__peak {
display: none;
}
/* Projector variant */
.pc-board--large {
gap: 2px;
border-block-width: 3px;
}
.pc-board--large .pc-board__day {
gap: 0.7rem;
padding: 1rem 0.9rem 0.9rem;
}
.pc-board--large .pc-board__weekday {
font-size: 1rem;
}
.pc-board--large .pc-board__date {
font-size: 1.9rem;
}
.pc-board--large .pc-board__peak {
display: none;
}
.pc-board--large .pc-board__track {
min-height: 21rem;
}
.pc-board--large .pc-board__staff {
font-size: 3rem;
}
.pc-board--large .pc-board__time {
display: none;
}
.pc-board--large .pc-board__block {
padding: 0.55rem 0.7rem;
}
.pc-board--large .pc-board__foot {
font-size: 1rem;
}
/* Dark board variant */
.pc-board--dark {
--pc-board-block: var(--pc-dark-2, #191c18);
--pc-board-border: var(--pc-dark-line, #343a31);
--pc-board-text: var(--pc-paper, #f4efe6);
background: var(--pc-dark-line, #343a31);
border-color: var(--pc-dark-line, #343a31);
}
.pc-board--dark .pc-board__day {
background: var(--pc-dark, #0e100e);
}
.pc-board--dark.pc-board--interactive .pc-board__day:hover {
background: var(--pc-dark-2, #191c18);
}
.pc-board--dark .pc-board__day--peak {
background: color-mix(in srgb, var(--pc-signal-bright, #ff6a2a) 12%, var(--pc-dark, #0e100e));
box-shadow: inset 0 3px 0 var(--pc-signal-bright, #ff6a2a);
}
.pc-board--dark .pc-board__day--selected {
outline-color: var(--pc-paper, #f4efe6);
}
.pc-board--dark .pc-board__weekday,
.pc-board--dark .pc-board__foot,
.pc-board--dark .pc-board__peakstaff,
.pc-board--dark .pc-board__time {
color: var(--pc-dark-muted, #b4ae9f);
}
.pc-board--dark .pc-board__peak {
color: var(--pc-signal-bright, #ff6a2a);
}
.pc-board--dark .pc-board__day--peak .pc-board__block {
border-color: var(--pc-signal-bright, #ff6a2a);
background: var(--pc-signal-bright, #ff6a2a);
color: var(--pc-dark, #0e100e);
}
.pc-board--dark .pc-board__day--peak .pc-board__time {
color: color-mix(in srgb, var(--pc-dark, #0e100e) 80%, transparent);
}
.pc-board--dark .pc-board__hours {
color: var(--pc-paper, #f4efe6);
}
.pc-board--dark .pc-board__pulse {
--pc-pulse-color: var(--pc-dark-line, #343a31);
}
</style>
+8
View File
@@ -0,0 +1,8 @@
import type { CoolCityBundle } from '#shared/cool'
export async function useCoolCityData() {
const { data } = await useFetch<CoolCityBundle>('/cool-city/city-gap.json', {
key: 'cool-city-gap',
})
return { city: data }
}
+72
View File
@@ -0,0 +1,72 @@
import { defaultCoolState, emptyCoolTally } from '#shared/cool'
import type { CoolDemoState, CoolRound, CoolVoteTally } from '#shared/cool'
/** State + tally polling for the stage and phone. 2 s is the demo fallback. */
export function useCoolDemo(
round: Ref<CoolRound>,
initialState?: CoolDemoState | null,
initialTally?: CoolVoteTally | null,
) {
const state = ref<CoolDemoState>(initialState ?? defaultCoolState(round.value))
const tally = ref<CoolVoteTally>(initialTally ?? emptyCoolTally(round.value))
const feedError = ref(false)
let timer: ReturnType<typeof setInterval> | undefined
watch(round, () => {
state.value = defaultCoolState(round.value)
tally.value = emptyCoolTally(round.value)
void poll()
})
async function poll() {
const [stateResult, tallyResult] = await Promise.allSettled([
$fetch<CoolDemoState>('/api/cool/state', {
query: { round: round.value },
headers: { accept: 'application/json', 'cache-control': 'no-cache' },
}),
$fetch<CoolVoteTally>('/api/cool/vote', {
query: { round: round.value },
headers: { accept: 'application/json', 'cache-control': 'no-cache' },
}),
])
if (stateResult.status === 'fulfilled') state.value = stateResult.value
if (tallyResult.status === 'fulfilled') tally.value = tallyResult.value
feedError.value = stateResult.status === 'rejected' || tallyResult.status === 'rejected'
}
async function update(patch: Partial<Pick<CoolDemoState, 'time' | 'selectedRoute' | 'scene' | 'voteOpen'>>) {
state.value = { ...state.value, ...patch, updatedAt: new Date().toISOString() }
try {
const next = await $fetch<CoolDemoState>('/api/cool/state', {
method: 'POST',
body: { round: round.value, ...patch },
})
state.value = next
} catch {
feedError.value = true
}
}
async function reset() {
try {
const result = await $fetch<{ state: CoolDemoState; tally: CoolVoteTally }>('/api/cool/reset', {
method: 'POST',
body: { round: round.value },
})
state.value = result.state
tally.value = result.tally
feedError.value = false
} catch {
feedError.value = true
}
}
onMounted(() => {
timer = setInterval(() => void poll(), 2000)
})
onBeforeUnmount(() => {
if (timer) clearInterval(timer)
})
return { state, tally, feedError, update, reset, poll }
}
+20
View File
@@ -0,0 +1,20 @@
import { pendingCoolRouteBundle } from '#shared/cool'
import type { CoolRouteBundle, CoolRouteId, CoolRouteValues, CoolTime } from '#shared/cool'
export async function useCoolRouteData() {
const { data } = await useFetch<CoolRouteBundle>('/cool-city/route.json', {
key: 'cool-route-bundle',
})
const bundle = computed(() => data.value ?? pendingCoolRouteBundle())
const pending = computed(() => bundle.value.status !== 'ready')
function routeForTime(time: CoolTime | string): CoolRouteId {
return bundle.value.recommendationByTime[time] ?? 'shortest'
}
function valuesFor(routeId: CoolRouteId, time: CoolTime | string): CoolRouteValues | null {
return bundle.value.routes.find((route) => route.id === routeId)?.values[time] ?? null
}
return { bundle, pending, routeForTime, valuesFor }
}
+72
View File
@@ -0,0 +1,72 @@
import { isCoolRouteId } from '#shared/cool'
import type { CoolRouteId, CoolRound, CoolVoteResponse, CoolVoteTally } from '#shared/cool'
const SESSION_KEY = 'cool-city-session-v1'
/** One anonymous vote per browser and round. No PII. */
export function useCoolVote(round: Ref<CoolRound>) {
const mounted = ref(false)
const sessionId = ref('')
const myVote = ref<CoolRouteId | ''>('')
const busy = ref(false)
const error = ref('')
const tally = ref<CoolVoteTally | null>(null)
function voteKey(value: CoolRound) {
return `cool-city-vote-v1:${value}`
}
function makeSessionId(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID()
return `cool_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`
}
function readStoredVote(value: CoolRound): CoolRouteId | '' {
const stored = localStorage.getItem(voteKey(value))
return isCoolRouteId(stored) ? stored : ''
}
onMounted(() => {
let storedSession = localStorage.getItem(SESSION_KEY)
if (!storedSession || storedSession.length < 8) {
storedSession = makeSessionId()
localStorage.setItem(SESSION_KEY, storedSession)
}
sessionId.value = storedSession
myVote.value = readStoredVote(round.value)
mounted.value = true
})
watch(round, (value) => {
if (!mounted.value) return
myVote.value = readStoredVote(value)
tally.value = null
error.value = ''
})
async function vote(route: CoolRouteId) {
if (!mounted.value || busy.value || myVote.value || !sessionId.value) return
busy.value = true
error.value = ''
try {
const response = await $fetch<CoolVoteResponse>('/api/cool/vote', {
method: 'POST',
body: { route, sessionId: sessionId.value, round: round.value },
})
myVote.value = response.yourRoute
tally.value = response.tally
localStorage.setItem(voteKey(round.value), response.yourRoute)
} catch (cause) {
const status = (cause as { statusCode?: number; status?: number })?.statusCode ??
(cause as { status?: number })?.status
error.value =
status === 409
? 'Voting is not open right now.'
: 'The vote could not be recorded. Try again.'
} finally {
busy.value = false
}
}
return { mounted, myVote, busy, error, tally, vote }
}
+276
View File
@@ -0,0 +1,276 @@
import {
LIVE_LABELS,
liveStatus,
parseScenarioEvent,
scenarioChanged,
SCENARIO_POLL_MS,
SSE_FAILURES_BEFORE_POLLING,
SSE_STALE_MS,
} from '#shared/live'
import type { LiveConnection } from '#shared/live'
import type { ScenarioState } from '#shared/types'
interface LiveStore {
status: LiveConnection
serverScenario: ScenarioState | null
lastEventAt: string
lastPollAt: string
sseFailures: number
pollFailures: number
revision: number
error: string
}
// One stream per browser tab. The module-level store survives page navigation
// and is only mutated from onMounted/EventSource callbacks (never during SSR).
const store = reactive<LiveStore>({
status: 'connecting',
serverScenario: null,
lastEventAt: '',
lastPollAt: '',
sseFailures: 0,
pollFailures: 0,
revision: 0,
error: '',
})
let source: EventSource | null = null
let pollTimer: ReturnType<typeof setInterval> | null = null
let staleTimer: ReturnType<typeof setInterval> | null = null
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
let subscribers = 0
let started = false
let lastStaleRetry = 0
function nowIso(): string {
return new Date().toISOString()
}
function refreshStatus() {
store.status = liveStatus({
online: import.meta.client ? navigator.onLine !== false : true,
sseOpen: source?.readyState === EventSource.OPEN,
sseFailures: store.sseFailures,
polling: pollTimer !== null,
pollFailures: store.pollFailures,
})
}
function clearPolling() {
if (pollTimer) clearInterval(pollTimer)
pollTimer = null
}
function applyScenario(next: ScenarioState, origin: 'sse' | 'poll') {
const changed = scenarioChanged(store.serverScenario, next)
store.serverScenario = next
store.lastEventAt = nowIso()
store.error = ''
if (origin === 'poll') store.lastPollAt = store.lastEventAt
if (changed) store.revision += 1
}
async function pollScenario(): Promise<void> {
if (!import.meta.client) return
try {
const next = await $fetch<ScenarioState>('/api/scenario', {
headers: { accept: 'application/json' },
timeout: 5000,
})
store.pollFailures = 0
applyScenario(next, 'poll')
// A successful poll proves the API is reachable; stay "Polling" until SSE
// opens again, so the audience can see the fallback is active.
if (store.status === 'offline') store.status = 'polling'
} catch (error) {
store.pollFailures += 1
store.error = (error as { statusMessage?: string })?.statusMessage ?? 'Scenario polling failed'
}
refreshStatus()
}
function startPolling() {
if (!import.meta.client || pollTimer) return
void pollScenario()
pollTimer = setInterval(() => void pollScenario(), SCENARIO_POLL_MS)
refreshStatus()
}
function closeSource() {
if (source) {
source.close()
source = null
}
if (reconnectTimer) clearTimeout(reconnectTimer)
reconnectTimer = null
}
function connectSse() {
if (!import.meta.client) return
closeSource()
if (navigator.onLine === false) {
store.status = 'offline'
startPolling()
return
}
const eventSource = new EventSource('/api/stream')
source = eventSource
eventSource.onopen = () => {
if (source !== eventSource) return
store.sseFailures = 0
store.pollFailures = 0
store.error = ''
// Start the stale watchdog now: a proxy can accept the SSE headers and
// then buffer the body, so "open" does not prove events are flowing.
store.lastEventAt = nowIso()
clearPolling()
refreshStatus()
}
eventSource.addEventListener('scenario', (event) => {
if (source !== eventSource) return
const parsed = parseScenarioEvent((event as MessageEvent).data)
if (!parsed) {
store.error = 'Ignored a malformed scenario event'
return
}
store.sseFailures = 0
applyScenario(parsed, 'sse')
refreshStatus()
})
eventSource.addEventListener('ping', () => {
if (source !== eventSource) return
store.sseFailures = 0
store.lastEventAt = nowIso()
if (pollTimer && eventSource.readyState === EventSource.OPEN) clearPolling()
refreshStatus()
})
eventSource.onerror = () => {
if (source !== eventSource) return
store.sseFailures += 1
// A non-200 response (Nitro 502/503, proxy error) leaves EventSource in
// CLOSED and the browser will not retry it. Treat that as a definitive
// failure: start polling now and try the stream again on a timer. Network
// errors while CONNECTING still use the browser's own retry loop.
const fatal = eventSource.readyState === EventSource.CLOSED
if (fatal) {
store.sseFailures = Math.max(store.sseFailures, SSE_FAILURES_BEFORE_POLLING)
if (!reconnectTimer) {
reconnectTimer = setTimeout(() => {
if (!started) return
connectSse()
}, 5000)
}
}
if (store.sseFailures >= SSE_FAILURES_BEFORE_POLLING) startPolling()
refreshStatus()
}
}
function checkStale() {
if (!import.meta.client || !started) return
const sseOpen = source?.readyState === EventSource.OPEN
if (sseOpen && store.lastEventAt) {
const age = Date.now() - Date.parse(store.lastEventAt)
if (age > SSE_STALE_MS) {
// Connection is open but no ping arrived: Cloudflare/path buffering.
// Polling is the contract fallback; retry SSE once a minute.
store.sseFailures = Math.max(store.sseFailures, SSE_FAILURES_BEFORE_POLLING)
startPolling()
refreshStatus()
if (Date.now() - lastStaleRetry > 60000) {
lastStaleRetry = Date.now()
connectSse()
}
}
}
if (store.pollFailures > 0) refreshStatus()
}
function start() {
if (!import.meta.client || started) return
started = true
store.sseFailures = 0
store.pollFailures = 0
store.lastEventAt = ''
store.error = ''
store.status = 'connecting'
window.addEventListener('online', handleOnline)
window.addEventListener('offline', handleOffline)
staleTimer = setInterval(checkStale, 5000)
connectSse()
}
function stop() {
if (!import.meta.client) return
started = false
closeSource()
clearPolling()
if (staleTimer) clearInterval(staleTimer)
staleTimer = null
window.removeEventListener('online', handleOnline)
window.removeEventListener('offline', handleOffline)
store.status = 'connecting'
}
function handleOnline() {
if (!started) return
store.pollFailures = 0
connectSse()
void pollScenario()
}
function handleOffline() {
if (!started) return
store.status = 'offline'
if (pollTimer) clearInterval(pollTimer)
pollTimer = null
}
/**
* Subscribe the current page to the Go scenario stream through Nitro.
*
* The first render uses `initial` from SSR; after mount the composable opens
* `/api/stream`, shows Live/Polling/Offline, and falls back to GET
* /api/scenario every 5 s when SSE fails or is buffered.
*/
export function useLiveScenario(initial?: ScenarioState | null) {
const initialScenario = initial ?? null
const current = computed<ScenarioState | null>(() => store.serverScenario ?? initialScenario)
const scenarioId = computed(() => current.value?.scenario.scenario ?? 'base')
const status = computed(() => store.status)
const statusLabel = computed(() => LIVE_LABELS[store.status])
onMounted(() => {
// Seed after hydration so the first client paint matches the SSR HTML.
if (initialScenario && !store.serverScenario) store.serverScenario = initialScenario
subscribers += 1
start()
})
onBeforeUnmount(() => {
subscribers = Math.max(0, subscribers - 1)
if (subscribers === 0) stop()
})
return reactive({
scenario: current,
scenarioId,
version: computed(() => current.value?.version ?? 0),
scenarioAt: computed(() => current.value?.at ?? ''),
status,
statusLabel,
lastEventAt: computed(() => store.lastEventAt),
lastPollAt: computed(() => store.lastPollAt),
error: computed(() => store.error),
revision: computed(() => store.revision),
pollNow: pollScenario,
})
}
+152
View File
@@ -0,0 +1,152 @@
<script setup lang="ts">
import { iconCircleInformation, iconShieldUser, iconTriangleWarning } from '@sit-onyx/icons'
import type { MetaResponse } from '#shared/types'
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(() => ['1', 'true'].includes(String(config.public.useMock).toLowerCase()))
</script>
<template>
<div class="page page-stack">
<header class="page-header">
<div>
<p class="eyebrow">About · method, data and limits</p>
<OnyxHeadline is="h1">A decision aid, not a city-wide truth.</OnyxHeadline>
<p class="lede">
PulseCast turns a footfall forecast into a weekly staffing plan. The forecast is a model output; the
staffing rule is a transparent heuristic. Both are shown, editable, and bounded.
</p>
</div>
<OnyxBadge color="warning">Hackathon prototype</OnyxBadge>
</header>
<div class="summary-grid">
<MetricCard
label="Sensors"
:value="String(meta?.coverage.sensors ?? 8)"
hint="Fixed points in a 580 m inner-city cluster."
:icon="iconCircleInformation"
/>
<MetricCard
label="Model WAPE"
:value="meta ? formatPercent(meta.metrics.wape, 1) : '—'"
:badge="meta ? `baseline ${formatPercent(meta.metrics.baseline_wape, 1)}` : undefined"
badge-color="success"
hint="Time-based holdout, not a random split."
/>
<MetricCard
label="R²"
:value="meta ? meta.metrics.r2.toFixed(3) : '—'"
:hint="meta ? `MAE ${meta.metrics.mae} devices/hour` : undefined"
/>
<MetricCard
label="Cadence"
:value="meta ? `${meta.coverage.cadence_min} min` : '—'"
:hint="meta ? `${formatDate(meta.coverage.from)} → ${formatDate(meta.coverage.to)}` : undefined"
/>
</div>
<div class="split-grid">
<div class="card-stack">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">How the plan is made</OnyxHeadline>
<OnyxBadge color="info" density="compact">transparent heuristic</OnyxBadge>
</div>
<ol class="small" style="margin: 0; padding-left: 1.2rem; display: grid; gap: var(--onyx-density-sm)">
<li>Forecast estimated devices per hour for the next 7 days.</li>
<li>Divide by visitors per staff-hour, multiply by a safety factor, round up, apply minimum staff.</li>
<li>Cover 10:00–20:00 with consecutive shift blocks; a block gets the peak requirement inside it.</li>
<li>Score coverage, cost, over/understaffed hours and compare with a flat schedule.</li>
<li>Show the weather, holiday and assumption drivers; let the manager edit and regenerate.</li>
</ol>
<div class="callout" style="margin-top: var(--onyx-density-md)">
<p class="small" style="margin: 0">
There is no POS, sales, queue, payroll or labour-cost feed. Cost is an assumption. The coverage score
is high by construction because shift blocks cover their local peak; overstaffed hours are the honest
trade-off.
</p>
</div>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Model and data coverage</OnyxHeadline>
</div>
<OnyxTable striped :table-attrs="{ style: 'min-width: 34rem' }">
<template #head>
<tr><th scope="col">Field</th><th scope="col">Value</th></tr>
</template>
<tr><th scope="row" style="text-align: left; font-weight: 600">Data version</th><td class="mono">{{ meta?.data_version ?? '—' }}</td></tr>
<tr><th scope="row" style="text-align: left; font-weight: 600">Model version</th><td class="mono">{{ meta?.model_version ?? '—' }}</td></tr>
<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 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 comes from Go <code>/api/meta</code> through the Nitro proxy.</p>
</OnyxCard>
<TrainModelCard />
</div>
<aside class="card-stack">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Limits</OnyxHeadline>
<OnyxIcon :icon="iconTriangleWarning" size="24px" color="warning" />
</div>
<ul class="why-list">
<li v-for="limit in meta?.limits ?? []" :key="limit">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
<span>{{ limit }}</span>
</li>
</ul>
<p class="small muted table-note">
Eight sensors in one pedestrian cluster cannot rank commercial zones across Heilbronn. There is no
city-wide heatmap claim here.
</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Privacy</OnyxHeadline>
<OnyxIcon :icon="iconShieldUser" size="24px" color="primary" />
</div>
<ul class="small" style="margin: 0; padding-left: 1.1rem; display: grid; gap: var(--onyx-density-xs)">
<li>No PII, MAC addresses or geolocation permission.</li>
<li>No analytics, tracking cookies or local storage on public screens.</li>
<li>Public read-only screens; control actions are authenticated separately.</li>
<li>Raw challenge CSV and secrets stay out of this repository.</li>
</ul>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">Data source</OnyxHeadline>
<OnyxBadge :color="usingMock ? 'warning' : 'success'" density="compact">
{{ usingMock ? 'Mock mode' : 'Go API' }}
</OnyxBadge>
</div>
<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) : '—' }}
</p>
</OnyxCard>
</aside>
</div>
</div>
</template>
+269
View File
@@ -0,0 +1,269 @@
<script setup lang="ts">
import {
iconArrowRight,
iconCircleCheck,
iconCircleX,
iconPresentionBoard,
iconSync,
iconTriangleWarning,
} from '@sit-onyx/icons'
import { scenarioLabel } from '#shared/live'
import type { ScenarioPreset, ScenarioState } from '#shared/types'
import { apiErrorMessage, apiErrorStatus } from '~/utils/api-error'
import { formatDateTime } from '~/utils/format'
useHead({ title: 'Presenter control — PulseCast' })
const { data: initialScenario } = await useFetch<ScenarioState>('/api/scenario')
const { data: presets, error: presetsError } = await useFetch<ScenarioPreset[]>('/api/scenarios')
const live = useLiveScenario(initialScenario.value)
const submitted = ref<ScenarioState | null>(null)
const busy = ref('')
const message = ref('')
const errorMessage = ref('')
const current = computed(() => {
const liveState = live.scenario
const local = submitted.value
if (!liveState) return local ?? initialScenario.value ?? null
if (!local) return liveState
// A remote presenter can move the stage on; always show the newer version.
return liveState.version >= local.version ? liveState : local
})
const activeId = computed(() => current.value?.scenario.scenario ?? '')
const presetList = computed(() => presets.value ?? [])
function applyBody(preset: ScenarioPreset) {
return {
scenario: preset.id,
weather: preset.weather ?? {},
event: preset.event,
}
}
async function apply(preset: ScenarioPreset) {
if (busy.value) return
busy.value = preset.id
message.value = ''
errorMessage.value = ''
try {
const response = await $fetch<ScenarioState>('/api/scenario', {
method: 'POST',
body: applyBody(preset),
})
submitted.value = response
message.value = `${preset.label} is now live · version ${response.version}.`
} catch (error) {
errorMessage.value =
apiErrorMessage(error, 'The scenario change failed. Check the Go API and control credentials.') +
(apiErrorStatus(error) === 401 ? ' Reload this page to sign in again.' : '')
} finally {
busy.value = ''
}
}
</script>
<template>
<div class="page page-stack control-page">
<header class="page-header">
<div>
<p class="eyebrow">Presenter control · not linked in public navigation</p>
<OnyxHeadline is="h1">Change the scenario once. Every screen follows.</OnyxHeadline>
<p class="lede">
Each button POSTs to this Nuxt origin. Nitro attaches the Go control credentials server-side; the browser
never sees them. <NuxtLink to="/stage">Stage</NuxtLink> and <NuxtLink to="/live">Live</NuxtLink> update through
SSE, with a 5-second polling fallback.
</p>
</div>
<div class="hero-actions">
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" />
<OnyxBadge v-if="current" color="neutral" density="compact">v{{ current.version }}</OnyxBadge>
</div>
</header>
<div v-if="errorMessage" class="callout callout--warning" role="alert">
<OnyxIcon :icon="iconCircleX" size="16px" color="danger" />
<span>{{ errorMessage }}</span>
</div>
<div v-if="message" class="callout" role="status">
<OnyxIcon :icon="iconCircleCheck" size="16px" color="success" />
<span>{{ message }}</span>
</div>
<div class="split-grid">
<div class="card-stack">
<OnyxCard>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Scenario presets</OnyxHeadline>
<p class="small muted" style="margin: 0">
The enum is fixed by the API contract. Weather and event values match the demo narrative.
</p>
</div>
<OnyxBadge color="info" density="compact">server proxy</OnyxBadge>
</div>
<div v-if="presetList.length" class="scenario-grid">
<button
v-for="preset in presetList"
:key="preset.id"
type="button"
class="scenario-button"
:class="{ 'scenario-button--active': preset.id === activeId }"
:disabled="Boolean(busy)"
:aria-pressed="preset.id === activeId"
@click="apply(preset)"
>
<span class="scenario-button__head">
<strong>{{ preset.label }}</strong>
<OnyxBadge v-if="preset.id === activeId" color="success" density="compact">on stage</OnyxBadge>
<OnyxBadge v-else color="neutral" density="compact">{{ preset.short }}</OnyxBadge>
</span>
<span class="small muted">{{ preset.description }}</span>
<span v-if="busy === preset.id" class="scenario-button__busy">
<OnyxIcon :icon="iconSync" size="16px" color="primary" class="spin" />
Broadcasting…
</span>
<span v-else class="scenario-button__action">
Apply
<OnyxIcon :icon="iconArrowRight" size="16px" color="primary" />
</span>
</button>
</div>
<div v-else class="callout callout--warning">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
Scenario presets could not be loaded.
<span v-if="presetsError" class="muted">{{ presetsError.statusMessage }}</span>
</div>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Open the audience views</OnyxHeadline>
<OnyxIcon :icon="iconPresentionBoard" size="24px" color="primary" />
</div>
<div class="hero-actions">
<OnyxButton label="Open /stage" link="/stage" color="primary" />
<OnyxButton label="Open /live" link="/live" mode="outline" />
<OnyxButton label="Open /plan" link="/plan" mode="outline" />
</div>
<p class="small muted table-note">
Put <code>/stage</code> on the projector and let the audience scan the QR code. <code>/live</code> needs no
login and keeps the last known plan if the stream drops.
</p>
</OnyxCard>
</div>
<aside class="card-stack">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Current scenario</OnyxHeadline>
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" compact />
</div>
<p class="control-current">{{ current ? scenarioLabel(current.scenario.scenario) : 'Unavailable' }}</p>
<dl class="metric-list">
<div><dt>Version</dt><dd>{{ current?.version ?? '—' }}</dd></div>
<div><dt>Broadcast at</dt><dd>{{ current ? formatDateTime(current.at) : '—' }}</dd></div>
<div><dt>Last SSE event</dt><dd>{{ live.lastEventAt ? formatDateTime(live.lastEventAt) : '—' }}</dd></div>
<div><dt>Transport</dt><dd>{{ live.statusLabel }}</dd></div>
</dl>
<p v-if="live.error" class="small muted table-note">{{ live.error }}</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h3">What the presenter says</OnyxHeadline>
</div>
<ul class="why-list">
<li><span><strong>Base week</strong> — normal weather, no event uplift.</span></li>
<li><span><strong>Sunny Saturday + market</strong> — the Saturday plan should add staff.</span></li>
<li><span><strong>Rainy Saturday</strong> — the Saturday plan should shed staff.</span></li>
<li><span><strong>Wednesday event</strong> — the weekday evening block should rise.</span></li>
</ul>
<p class="small muted table-note">
If the numbers do not move on stage, check the <code>cached</code> badge: Go may be serving its last good
forecast because the ML service is down.
</p>
</OnyxCard>
</aside>
</div>
</div>
</template>
<style scoped>
.control-current {
margin: 0 0 var(--onyx-density-md);
color: var(--onyx-color-text-icons-primary-intense);
font-size: clamp(1.6rem, 3vw, 2.4rem);
font-weight: 700;
line-height: 1.1;
}
.scenario-button {
display: flex;
flex-direction: column;
gap: var(--onyx-density-xs);
width: 100%;
padding: var(--onyx-density-md);
border: 1px solid var(--onyx-color-base-neutral-300);
border-radius: var(--onyx-radius-component-container-soft);
background: var(--onyx-color-base-neutral-100);
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.scenario-button:hover:not(:disabled),
.scenario-button:focus-visible {
border-color: var(--onyx-color-base-primary-500);
outline: 2px solid var(--onyx-color-base-primary-300);
outline-offset: 1px;
}
.scenario-button:disabled {
cursor: progress;
opacity: 0.65;
}
.scenario-button--active {
border-color: var(--onyx-color-base-primary-600);
background: var(--onyx-color-base-primary-100);
}
.scenario-button__head,
.scenario-button__action,
.scenario-button__busy {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--onyx-density-xs);
}
.scenario-button__action,
.scenario-button__busy {
justify-content: flex-start;
margin-top: var(--onyx-density-xs);
color: var(--onyx-color-text-icons-neutral-medium);
font-size: 0.8125rem;
}
.spin {
animation: spin 0.9s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.spin {
animation: none;
}
}
</style>
+447
View File
@@ -0,0 +1,447 @@
<script setup lang="ts">
import { isCoolRound } from '#shared/cool'
import type { CoolCityCatchment } from '#shared/cool'
import { formatPercent } from '~/utils/format'
const route = useRoute()
const round = isCoolRound(route.query.round) ? route.query.round : 'preselection'
const { city } = await useCoolCityData()
const selectedRank = ref(1)
const catchments = computed(() => city.value?.catchments ?? [])
const selected = computed<CoolCityCatchment | undefined>(
() => catchments.value.find((item) => item.rank === selectedRank.value) ?? catchments.value[0],
)
const top = computed(() => catchments.value[0])
const maxIndex = computed(() => Math.max(...catchments.value.map((item) => item.scores.gap_index), 0.001))
const places = computed(() => city.value?.official_cool_places ?? [])
const help = computed(() => {
const item = selected.value
if (!item) return []
const result: string[] = []
if (item.inputs.shade.tree_canopy_share_of_land_proxy < 0.05) result.push('Shade')
if (item.inputs.access.nearest_public_drinking_water_m > 150) result.push('Water')
if (item.inputs.access.nearest_bench_m > 100) result.push('Bench')
if (item.inputs.access.nearest_step_free_anchor_m > 100) result.push('Step-free access')
return result.length ? result : ['Maintain access']
})
const helpReason = computed(() => {
const item = selected.value
if (!item) return ''
return `p95 ${item.inputs.footfall.p95.toFixed(1)} · canopy ${formatPercent(item.inputs.shade.tree_canopy_share_of_land_proxy * 100, 1)} · water ${Math.round(item.inputs.access.nearest_public_drinking_water_m)} m`
})
useHead({
title: 'Cool City — where the city should act first',
meta: [
{
name: 'description',
content:
'A relative cooling-gap index across eight Heilbronn sensor catchments. Ranked priorities for shade, water and benches; not a temperature map.',
},
{ name: 'theme-color', content: '#f6f3ee' },
],
})
</script>
<template>
<div class="cc-city">
<header class="cc-topbar">
<NuxtLink to="/cool" class="cc-wordmark">
<span class="cc-mark" aria-hidden="true" />
Cool City
</NuxtLink>
<span class="cc-topbar__place">Heilbronn · city view</span>
<NuxtLink class="cc-city__back" :to="{ path: '/cool/stage', query: { round } }">Back to route</NuxtLink>
</header>
<main class="cc-city__main">
<header class="cc-city__head">
<h1>Where the city should act first.</h1>
<p class="cc-city__lede">
Eight sensor catchments, ranked by footfall, shade deficit, access deficit and vulnerability.
It is a relative priority list, not a temperature map.
</p>
</header>
<div class="cc-city__grid">
<section class="cc-city__map" aria-label="Map of sensor catchments and official cool places">
<CoolPlacesMap
:places="places"
:catchments="catchments"
:selected-rank="selectedRank"
show-catchments
/>
</section>
<aside class="cc-city__list" aria-labelledby="ranked-title">
<h2 id="ranked-title">Ranked catchments</h2>
<div class="cc-city__rows">
<button
v-for="item in catchments"
:key="item.sensor_id"
type="button"
class="cc-city__row"
:class="{ 'is-selected': selectedRank === item.rank }"
:aria-pressed="selectedRank === item.rank"
@click="selectedRank = item.rank"
>
<span class="cc-city__rank">{{ item.rank }}</span>
<span class="cc-city__name">{{ item.sensor_name }}</span>
<span class="cc-city__bar"><i :style="{ width: `${(item.scores.gap_index / maxIndex) * 100}%` }" /></span>
<span class="cc-city__score">{{ item.scores.gap_index.toFixed(3) }}</span>
<span class="cc-city__reason">{{ item.reason }}</span>
</button>
</div>
</aside>
</div>
<section v-if="selected" class="cc-city__detail" aria-labelledby="help-title">
<div class="cc-city__detail-copy">
<h2 id="help-title">What would help</h2>
<p class="cc-city__rankline">Rank {{ selected.rank }} · {{ selected.sensor_name }} · {{ selected.sensor_id }}</p>
<p class="cc-city__lede">{{ selected.reason }}</p>
<ul class="cc-city__help">
<li v-for="item in help" :key="item">{{ item }}</li>
</ul>
<p class="cc-city__fine">{{ helpReason }}</p>
</div>
<dl class="cc-city__facts">
<div><dt>Gap index</dt><dd>{{ selected.scores.gap_index.toFixed(3) }}</dd></div>
<div><dt>Nearest cool place</dt><dd>{{ selected.nearest_cool_place?.name ?? '—' }}</dd></div>
<div><dt>Distance</dt><dd>{{ selected.nearest_cool_place ? `${Math.round(selected.nearest_cool_place.distance_m)} m` : '—' }}</dd></div>
<div><dt>Ranking note</dt><dd>Top 2 are co-priority</dd></div>
</dl>
</section>
<details class="cc-city__method">
<summary>How the gap is calculated</summary>
<div>
<p>Gap index = 0.40 × footfall + 0.30 × shade deficit + 0.20 × access deficit + 0.10 × vulnerability. The weights are deliberative, not calibrated against heat outcomes.</p>
<p>Footfall is a relative device index, not people. Shade is modeled from building footprints and tree-canopy proxies. Access combines distance to water, benches, toilets and step-free anchors within 300 m.</p>
<p><strong>Vulnerability is constant across all eight catchments</strong> in this dataset (17.26% aged 65+), so it does not differentiate the ranking.</p>
<p>Catchment = 300 m Euclidean radius, not a network isochrone. No city-wide heatmap. Top ranks 1 and 2 differ by 2.5%; treat them as co-priority.</p>
</div>
</details>
<footer class="cc-city__footer">
<span>Cool City · {{ city?.meta.generated ?? '—' }} · {{ places.length }} official cool places</span>
<NuxtLink :to="{ path: '/cool/stage', query: { round } }">Back to route</NuxtLink>
</footer>
</main>
</div>
</template>
<style scoped>
.cc-city {
min-height: 100dvh;
background: var(--cc-ground);
color: var(--cc-ink);
}
.cc-city__back {
margin-inline-start: auto;
color: var(--cc-ink);
font-size: 0.7rem;
font-weight: 650;
text-decoration: none;
}
.cc-city__main {
width: 100%;
max-width: 78rem;
margin-inline: auto;
padding: 1.3rem 1.2rem 2.5rem;
}
.cc-city__head {
display: flex;
flex-direction: column;
gap: 0.7rem;
padding-bottom: 1.1rem;
}
.cc-city__rankline {
margin: 0.25rem 0 0.3rem;
color: var(--cc-muted);
font-size: 0.7rem;
font-variant-numeric: tabular-nums;
}
.cc-city__head h1 {
max-width: 15ch;
margin: 0;
font-size: clamp(2.8rem, 6vw, 5.2rem);
font-weight: 850;
letter-spacing: -0.06em;
line-height: 0.9;
}
.cc-city__lede {
max-width: 64ch;
margin: 0;
color: var(--cc-muted);
font-size: 0.95rem;
line-height: 1.5;
}
.cc-city__grid {
display: grid;
grid-template-columns: minmax(0, 1.15fr) minmax(20rem, 0.85fr);
gap: 1rem;
align-items: stretch;
}
.cc-city__map {
min-height: 30rem;
overflow: hidden;
border-radius: 28px;
background: var(--cc-ground);
}
.cc-city__list {
padding: 1rem;
border: 1px solid var(--cc-line);
border-radius: 28px;
background: var(--cc-surface);
}
.cc-city__list h2 {
margin: 0 0 0.6rem;
font-size: 1.2rem;
font-weight: 800;
letter-spacing: -0.03em;
}
.cc-city__rows {
display: flex;
flex-direction: column;
}
.cc-city__row {
display: grid;
grid-template-columns: 1.6rem minmax(0, 1fr) 3.2rem;
grid-template-rows: auto auto auto;
gap: 0.15rem 0.45rem;
align-items: center;
width: 100%;
padding: 0.55rem 0.2rem;
border: 0;
border-bottom: 1px solid var(--cc-line);
background: transparent;
color: var(--cc-ink);
font: inherit;
text-align: left;
cursor: pointer;
}
.cc-city__rank {
grid-row: 1 / 4;
}
.cc-city__name {
grid-column: 2;
grid-row: 1;
}
.cc-city__score {
grid-column: 3;
grid-row: 1;
}
.cc-city__bar {
grid-column: 2 / 4;
grid-row: 2;
}
.cc-city__reason {
grid-column: 2 / 4;
grid-row: 3;
overflow: hidden;
color: var(--cc-muted);
font-size: 0.66rem;
line-height: 1.3;
text-overflow: ellipsis;
white-space: nowrap;
}
.cc-city__row:hover {
background: color-mix(in srgb, var(--cc-shade) 7%, transparent);
}
.cc-city__row.is-selected {
background: color-mix(in srgb, var(--cc-heat) 8%, transparent);
}
.cc-city__row:focus-visible {
outline: 2px solid var(--cc-focus);
outline-offset: 1px;
}
.cc-city__rank {
color: var(--cc-muted);
font-size: 0.76rem;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.cc-city__name {
overflow: hidden;
font-size: 0.82rem;
font-weight: 650;
text-overflow: ellipsis;
white-space: nowrap;
}
.cc-city__bar {
height: 0.55rem;
overflow: hidden;
border-radius: 999px;
background: var(--cc-line);
}
.cc-city__bar i {
display: block;
height: 100%;
border-radius: inherit;
background: var(--cc-heat);
}
.cc-city__score {
color: var(--cc-muted);
font-size: 0.68rem;
text-align: right;
font-variant-numeric: tabular-nums;
}
.cc-city__detail {
display: grid;
grid-template-columns: minmax(0, 1.2fr) minmax(18rem, 0.8fr);
gap: 1rem;
margin-top: 1rem;
padding: 1rem;
border: 1px solid var(--cc-line);
border-radius: 28px;
background: var(--cc-surface);
}
.cc-city__detail-copy h2 {
margin: 0;
font-size: 1.7rem;
font-weight: 800;
letter-spacing: -0.04em;
}
.cc-city__help {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
margin: 0.7rem 0 0;
padding: 0;
list-style: none;
}
.cc-city__help li {
padding: 0.25rem 0.6rem;
border-radius: 999px;
background: var(--cc-heat-soft);
color: var(--cc-heat-text);
font-size: 0.8rem;
font-weight: 700;
}
.cc-city__fine {
margin: 0.4rem 0 0;
color: var(--cc-muted);
font-size: 0.72rem;
font-variant-numeric: tabular-nums;
}
.cc-city__facts {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.7rem;
margin: 0;
}
.cc-city__facts dt {
color: var(--cc-muted);
font-size: 0.65rem;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.cc-city__facts dd {
margin: 0.2rem 0 0;
font-size: 0.82rem;
font-weight: 650;
line-height: 1.3;
}
.cc-city__method {
margin-top: 1rem;
padding: 0.9rem 1rem;
border: 1px solid var(--cc-line);
border-radius: 24px;
background: var(--cc-surface);
}
.cc-city__method summary {
color: var(--cc-ink);
font-size: 0.82rem;
font-weight: 650;
cursor: pointer;
}
.cc-city__method div {
display: grid;
gap: 0.5rem;
padding-top: 0.7rem;
color: var(--cc-muted);
font-size: 0.82rem;
line-height: 1.5;
}
.cc-city__method p {
margin: 0;
}
.cc-city__method strong {
color: var(--cc-ink);
}
.cc-city__footer {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 0.5rem 1rem;
margin-top: 1rem;
padding-top: 0.8rem;
border-top: 1px solid var(--cc-line);
color: var(--cc-muted);
font-size: 0.7rem;
}
.cc-city__footer a {
color: var(--cc-ink);
font-weight: 650;
}
@media (max-width: 900px) {
.cc-city__grid,
.cc-city__detail {
grid-template-columns: minmax(0, 1fr);
}
.cc-city__map {
min-height: 22rem;
}
.cc-city__name {
overflow: visible;
white-space: normal;
}
}
</style>
+419
View File
@@ -0,0 +1,419 @@
<script setup lang="ts">
import { COOL_ROUTE_IDS, COOL_ROUTE_LABELS, COOL_TIMES, isCoolRound } from '#shared/cool'
import type { CoolDemoState, CoolRouteId, CoolRound, CoolVoteTally } from '#shared/cool'
import { coolMinutes, coolShade } from '~/utils/cool'
const route = useRoute()
const round = ref<CoolRound>(isCoolRound(route.query.round) ? route.query.round : 'preselection')
const voteOnly = computed(() => route.query.vote === '1')
const { bundle } = await useCoolRouteData()
const { data: initialState } = await useFetch<CoolDemoState>('/api/cool/state', {
query: computed(() => ({ round: round.value })),
})
const { data: initialTally } = await useFetch<CoolVoteTally>('/api/cool/vote', {
query: computed(() => ({ round: round.value })),
})
const { state, update } = useCoolDemo(round, initialState.value, initialTally.value)
const { myVote, busy, error: voteError, tally, mounted, vote } = useCoolVote(round)
const timeIndex = computed({
get: () => Math.max(0, COOL_TIMES.indexOf(state.value.time)),
set: (index: number) => {
const time = COOL_TIMES[index] ?? '10:00'
const nextRoute = bundle.value.recommendationByTime[time] ?? state.value.selectedRoute
void update({ time, selectedRoute: nextRoute })
},
})
const timeMarks = COOL_TIMES.map((time, index) => ({ value: index, label: time }))
const modelLabel = computed(() => bundle.value.modelLabel)
const myVoteLabel = computed(() => (myVote.value ? COOL_ROUTE_LABELS[myVote.value] : ''))
const voteStatus = computed(() => {
if (myVote.value) {
return `${myVoteLabel.value} recorded${tally.value ? ` · ${tally.value.total} ${tally.value.total === 1 ? 'vote' : 'votes'} in this room` : ''}.`
}
if (state.value.scene === 'locked' || state.value.scene === 'coda') return 'The vote is closed. The stage has the result.'
return 'The vote opens when the presenter starts it.'
})
const routeReasons: Record<CoolRouteId, string> = {
shortest: 'Fastest, but a 15% ramp at the Marktplatz tram crossing.',
shaded: 'Twice as long, so more minutes in the sun.',
accessible: 'One minute longer, no ramp, water and benches.',
}
const routeOptions = COOL_ROUTE_IDS.map((id) => ({ value: id, label: COOL_ROUTE_LABELS[id] }))
// The phone opens on the model's route. The one pristine state is Shortest at
// 10:00; in that case show Accessible for Ruth. Any explicit stage choice wins.
const localRoute = ref<CoolRouteId>(
state.value.selectedRoute === 'shortest' && state.value.time === '10:00'
? 'accessible'
: state.value.selectedRoute,
)
let lastRemoteRoute = state.value.selectedRoute
const activeRoute = computed<CoolRouteId>({
get: () => localRoute.value,
set: (value) => {
localRoute.value = value
lastRemoteRoute = value
void update({ selectedRoute: value })
},
})
watch(
() => state.value.selectedRoute,
(value) => {
if (value === lastRemoteRoute) return
lastRemoteRoute = value
localRoute.value = value
},
)
const activeRouteOption = computed(
() => bundle.value.routes.find((item) => item.id === activeRoute.value) ?? bundle.value.routes[0],
)
const activeValues = computed(
() => activeRouteOption.value?.values[state.value.time] ?? null,
)
const tradeoff = computed(() => {
const shortest = bundle.value.routes.find((item) => item.id === 'shortest')
const shaded = bundle.value.routes.find((item) => item.id === 'shaded')
const accessible = bundle.value.routes.find((item) => item.id === 'accessible')
if (!shortest || !shaded || !accessible) return ''
const shortestValues = shortest.values[state.value.time]
const shadedValues = shaded.values[state.value.time]
const accessibleValues = accessible.values[state.value.time]
if (!shortestValues || !shadedValues || !accessibleValues) return ''
const shortestRamp = shortest.ramp ? shortest.ramp.incline.replace('.0%', '%') : 'no'
return `Shaded: ${coolShade(shadedValues.shadePct)} shade, but ${coolMinutes(shadedValues.directSunMin)} sun because it is twice as long. Shortest: ${coolMinutes(shortestValues.directSunMin)} sun, ${shortestRamp} ramp. Accessible: ${coolMinutes(accessibleValues.directSunMin)} sun, no ramp.`
})
function tooltipTime(value: number): string {
return COOL_TIMES[value] ?? ''
}
function onSubmit(routeId: CoolRouteId) {
void vote(routeId)
}
watch(
() => route.query.round,
(value) => {
if (isCoolRound(value)) round.value = value
},
)
useHead({
title: voteOnly.value ? 'Vote — Cool City' : 'Cool City — a heat-safe route through Heilbronn',
meta: [
{
name: 'description',
content: voteOnly.value
? 'Which route for Ruth? One anonymous vote for the Cool City demo.'
: 'Cool City is Heilbronn’s public heat-safe route: shortest, shaded and accessible options from Stadtgalerie to Marktplatz, with modelled shade.',
},
{ name: 'theme-color', content: '#f6f3ee' },
],
})
</script>
<template>
<div class="cc-cool">
<header class="cc-topbar">
<NuxtLink to="/cool" class="cc-wordmark">
<span class="cc-mark" aria-hidden="true" />
Cool City
</NuxtLink>
<span class="cc-topbar__place">Heilbronn <span aria-hidden="true">·</span> {{ state.time }}</span>
<span class="cc-topbar__status"><i aria-hidden="true" /> Public route</span>
</header>
<main v-if="voteOnly" class="cc-vote-only">
<div class="cc-vote-only__inner">
<h1>Which route for Ruth?</h1>
<p class="cc-vote-only__lede">Shortest, shaded, or accessible? One tap. No name, no location.</p>
<div v-if="!myVote && state.voteOpen" class="cc-vote-only__buttons">
<OnyxButton
v-for="id in COOL_ROUTE_IDS"
:key="id"
:label="COOL_ROUTE_LABELS[id]"
mode="outline"
:disabled="busy"
@click="onSubmit(id)"
/>
</div>
<div v-else class="cc-vote-only__confirmation" role="status">
<p v-if="myVote">You chose <strong>{{ myVoteLabel }}</strong>.</p>
<p v-else>{{ voteStatus }}</p>
<p class="cc-fine">Aggregate only. One vote per browser and round.</p>
</div>
<p v-if="voteError" class="cc-error" role="alert">{{ voteError }}</p>
<p v-if="!mounted" class="cc-fine">Preparing your anonymous vote…</p>
</div>
</main>
<main v-else class="cc-phone">
<section class="cc-ruth" aria-labelledby="ruth-title">
<h1 id="ruth-title">Ruth, 78, needs to reach Marktplatz.</h1>
<p class="cc-ruth__copy">A hot day in Heilbronn. She needs bread.</p>
<span class="cc-ruth__tag">Composite persona — illustrative, not a real person</span>
</section>
<section class="cc-panel cc-time" aria-labelledby="time-title">
<div class="cc-time__head">
<h2 id="time-title">When?</h2>
<strong>{{ state.time }}</strong>
</div>
<OnyxSlider
v-model="timeIndex"
label="Time of day"
:min="0"
:max="COOL_TIMES.length - 1"
:step="1"
:marks="timeMarks"
:tooltip="{ formatter: tooltipTime }"
/>
<p class="cc-fine">Modeled shade, not measured. The stage follows this time.</p>
</section>
<section class="cc-route" aria-labelledby="route-title">
<div class="cc-route__head">
<h2 id="route-title">Which route for Ruth?</h2>
<p class="cc-route__model">Model recommendation · <strong>{{ modelLabel }}</strong></p>
</div>
<OnyxSegmentedControl
v-model="activeRoute"
class="cc-route__segment"
aria-label="Route"
name="cool-route"
:options="routeOptions"
/>
<CoolRouteCard
v-if="activeRouteOption"
:route="activeRouteOption"
:values="activeValues"
:reason="routeReasons[activeRoute]"
>
<template #action>
<div v-if="myVote" class="cc-route__vote-status" role="status">
<strong>You chose {{ myVoteLabel }}.</strong>
<span>One vote per browser.</span>
</div>
<OnyxButton
v-else-if="state.voteOpen"
:label="`Vote for ${activeRouteOption?.label ?? activeRoute}`"
color="primary"
:disabled="busy"
@click="onSubmit(activeRoute)"
/>
<p v-else class="cc-route__vote-status cc-route__vote-status--quiet">
Voting opens when the presenter starts it.
</p>
<p v-if="voteError" class="cc-error" role="alert">{{ voteError }}</p>
</template>
</CoolRouteCard>
<p v-if="tradeoff" class="cc-route__tradeoff">
<span class="cc-route__tradeoff-label">The trade-off at {{ state.time }}</span>
{{ tradeoff }}
</p>
</section>
<details class="cc-details">
<summary>Details</summary>
<div class="cc-details__body">
<p><strong>Shade is modeled, not measured.</strong> NOAA solar position, building footprints and tree canopies on 14 Aug 2026, a 35°C clear-sky day.</p>
<p><strong>At 16:00:</strong> Shortest 359.5 m / 4.8 min, 43.8% shade, 2.7 min direct sun, 15% ramp. Shaded 732.3 m / 9.8 min, 50.0% shade, 4.9 min direct sun. Accessible 438.2 m / 5.8 min, 43.8% shade, 3.3 min direct sun, no ramp, water 2, benches 6.</p>
<p><strong>All three routes are step-free.</strong> The 15% ramp is at the Marktplatz tram crossing. The city data is a relative index: estimated devices, not people.</p>
<p class="cc-details__links">
<NuxtLink to="/cool/city">How this works</NuxtLink>
<NuxtLink to="/plan">Retail module</NuxtLink>
<NuxtLink to="/cool/stage">Stage</NuxtLink>
</p>
</div>
</details>
<footer class="cc-phone__footer">
<span>Cool City · Heilbronn</span>
<span>Modeled shade, not measured. Estimated devices, not people.</span>
</footer>
</main>
</div>
</template>
<style scoped>
.cc-fine {
margin: 0.35rem 0 0;
color: var(--cc-muted);
font-size: 0.7rem;
line-height: 1.45;
}
.cc-error {
margin: 0.45rem 0 0;
color: var(--cc-heat-text);
font-size: 0.78rem;
}
.cc-vote-only__buttons {
grid-template-columns: minmax(0, 1fr);
}
.cc-vote-only__buttons :deep(.onyx-button) {
width: 100%;
min-height: 52px;
border-radius: 999px;
font-weight: 650;
}
.cc-route {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.cc-route__head h2 {
margin: 0;
font-size: clamp(1.5rem, 5.2vw, 1.9rem);
font-weight: 850;
letter-spacing: -0.045em;
line-height: 1;
}
.cc-route__model {
margin: 0.3rem 0 0;
color: var(--cc-muted);
font-size: 0.74rem;
line-height: 1.35;
}
.cc-route__model strong {
color: var(--cc-ink);
font-weight: 750;
}
.cc-route__segment {
width: 100%;
}
.cc-route__segment :deep(.onyx-segmented-control) {
display: grid;
max-width: none;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.18rem;
padding: 0.22rem;
overflow: visible;
border: 1px solid var(--cc-line);
border-radius: 999px;
background: color-mix(in srgb, var(--cc-ink) 5%, var(--cc-surface-solid));
}
.cc-route__segment :deep(.onyx-segmented-control-element) {
border-radius: 999px;
background: transparent;
color: var(--cc-ink-2);
font-family: var(--cc-font);
font-weight: 650;
}
.cc-route__segment :deep(.onyx-segmented-control-element__label) {
min-width: 0;
min-height: 42px;
align-items: center;
padding: 0.3rem 0.35rem;
font-size: 0.8rem;
font-weight: inherit;
}
.cc-route__segment :deep(.onyx-segmented-control-element:hover) {
color: var(--cc-ink);
background: color-mix(in srgb, var(--cc-ink) 4%, transparent);
}
.cc-route__segment :deep(.onyx-segmented-control-element:has(.onyx-segmented-control-element__input:checked)) {
background: var(--cc-ink);
color: var(--cc-ground);
}
.cc-route__segment :deep(.onyx-segmented-control-element:has(.onyx-segmented-control-element__input:checked):hover) {
background: var(--cc-ink);
color: var(--cc-ground);
}
.cc-route__segment :deep(.onyx-segmented-control-element:has(.onyx-segmented-control-element__input:focus-visible)) {
outline: 2px solid var(--cc-focus);
outline-offset: 2px;
}
.cc-route__vote-status {
display: flex;
min-height: 48px;
flex-wrap: wrap;
align-content: center;
align-items: baseline;
gap: 0.3rem 0.55rem;
color: var(--cc-muted);
font-size: 0.84rem;
line-height: 1.4;
}
.cc-route__vote-status strong {
color: var(--cc-ink);
font-weight: 750;
}
.cc-route__vote-status--quiet {
display: block;
padding-block: 0.65rem;
}
.cc-route__tradeoff {
max-width: 62ch;
margin: 0;
color: var(--cc-muted);
font-size: 0.78rem;
line-height: 1.5;
}
.cc-route__tradeoff-label {
display: block;
margin-bottom: 0.15rem;
color: var(--cc-ink);
font-size: 0.64rem;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
@media (min-width: 900px) {
.cc-route {
gap: 0.9rem;
}
.cc-route__head h2 {
font-size: 2rem;
}
.cc-route__segment {
max-width: 30rem;
}
.cc-route__tradeoff {
font-size: 0.8rem;
}
}
@media (max-width: 420px) {
.cc-route__vote-status {
display: block;
min-height: 0;
padding-block: 0.25rem;
}
}
</style>
File diff suppressed because it is too large. Load diff
+320
View File
@@ -0,0 +1,320 @@
<script setup lang="ts">
import { iconCalendar, iconChart, iconTriangleWarning } from '@sit-onyx/icons'
import { dailyWeather } from '#shared/insights'
import { berlinParts, planWeekStart, STANDARD_VISITORS_PER_STAFF_HOUR } from '#shared/staffing'
import type { ContextResponse, ForecastResponse, MetaResponse, Point, Scenario, ScenarioPreset, ScenarioState, Sensor } from '#shared/types'
import { formatDate, formatNumber, formatPercent, formatShortDate, formatWeekday, formatWeekdayShort, weekLabel } from '~/utils/format'
useHead({ title: 'Forecast — PulseCast' })
const config = useRuntimeConfig()
const demoNow = String(config.public.demoNow)
const weekStart = planWeekStart(demoNow)
const weekEnd = new Date(new Date(`${weekStart}T12:00:00Z`).getTime() + 6 * 86400000)
.toISOString()
.slice(0, 10)
const sensorId = ref('hn-stadtgalerie-01')
const scenario = ref<Scenario>('base')
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 { data: liveScenarioState } = await useFetch<ScenarioState>('/api/scenario')
const live = useLiveScenario(liveScenarioState.value)
scenario.value = live.scenarioId
sensorId.value =
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
sensorId.value
const {
data: forecast,
error: forecastError,
refresh: refreshForecast,
} = await useFetch<ForecastResponse>('/api/forecast', {
query: computed(() => ({ sensor: sensorId.value, horizon: '7d', scenario: scenario.value })),
})
watch(
() => live.revision,
() => {
if (live.scenarioId !== scenario.value) scenario.value = live.scenarioId
else void refreshForecast()
},
)
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 scenarioOptions = computed(() =>
(presets.value ?? []).map((preset) => ({ value: preset.id, label: preset.label })),
)
interface DayForecast {
date: string
points: Point[]
mean: number
peak: number
peakHour: number
weather?: ReturnType<typeof dailyWeather>[string]
requiredAtPeak: number
}
const days = computed<DayForecast[]>(() => {
const grouped: Record<string, Point[]> = {}
for (const point of forecast.value?.points ?? []) {
const { date } = berlinParts(point.t)
;(grouped[date] ??= []).push(point)
}
const weather = dailyWeather(context.value?.weather.forecast ?? [])
return Object.keys(grouped)
.sort()
.map((date) => {
const points = grouped[date]!
const peakPoint = points.reduce((best, point) => (point.v > best.v ? point : best))
const mean = points.reduce((sum, point) => sum + point.v, 0) / points.length
return {
date,
points,
mean: Math.round(mean),
peak: peakPoint.v,
peakHour: berlinParts(peakPoint.t).hour,
weather: weather[date],
requiredAtPeak: Math.max(
1,
Math.ceil((peakPoint.v / STANDARD_VISITORS_PER_STAFF_HOUR.standard) * 1.15),
),
}
})
})
const weekPeak = computed(() =>
days.value.length ? days.value.reduce((best, day) => (day.peak > best.peak ? day : best)) : undefined,
)
const dayMax = computed(() => Math.max(...days.value.map((day) => day.peak), 1))
// The API 7-day window starts at the current hour, so it spans up to eight
// calendar days. Label the real window instead of the Monday plan week.
const forecastStart = computed(() => days.value[0]?.date ?? weekStart)
const forecastEnd = computed(() => days.value.at(-1)?.date ?? weekEnd)
const forecastWindow = computed(() => weekLabel(forecastStart.value, forecastEnd.value))
const weekWeather = computed(() =>
Object.values(dailyWeather(context.value?.weather.forecast ?? []))
.filter((day) => day.date >= forecastStart.value && day.date <= forecastEnd.value)
.sort((a, b) => a.date.localeCompare(b.date)),
)
const total = computed(() => days.value.reduce((sum, day) => sum + day.mean, 0))
</script>
<template>
<div class="page page-stack">
<header class="page-header">
<div>
<p class="eyebrow">Forecast · {{ forecastWindow }}</p>
<OnyxHeadline is="h1">The window peaks on {{ weekPeak ? formatWeekday(weekPeak.date) : '—' }}.</OnyxHeadline>
<p class="lede">
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>
<div class="forecast-header-controls">
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" />
<div style="min-width: 14rem">
<OnyxSelect
v-model="sensorId"
label="Sensor"
list-label="Inner-city sensors"
:options="sensorOptions"
density="compact"
/>
</div>
</div>
</header>
<div v-if="forecastError" class="callout callout--warning" role="alert">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
The forecast could not be loaded. <span class="muted">{{ forecastError.statusMessage }}</span>
<OnyxButton label="Retry" mode="plain" density="compact" @click="refreshForecast()" />
</div>
<div v-else-if="forecast && !days.length" class="callout callout--warning" role="status">
<OnyxIcon :icon="iconTriangleWarning" size="16px" color="warning" />
No forecast points are available for this store yet. Try another sensor.
</div>
<OnyxCard>
<div class="card-header">
<div>
<OnyxHeadline is="h2">Daily shape</OnyxHeadline>
<p class="small muted" style="margin: 0">
Peak estimated devices per hour. Weather is context, not a causal claim.
</p>
</div>
<div style="min-width: 15rem">
<OnyxSelect
v-model="scenario"
label="Scenario"
list-label="Demo scenarios"
:options="scenarioOptions"
density="compact"
/>
</div>
</div>
<div class="forecast-bars" role="img" aria-label="Daily peak forecast">
<div v-for="day in days" :key="day.date" class="forecast-bar">
<span class="small muted">{{ formatNumber(day.peak) }}</span>
<div class="forecast-bar__track">
<div class="forecast-bar__fill" :style="{ height: `${Math.max(4, (day.peak / dayMax) * 100)}%` }" />
</div>
<strong>{{ formatWeekdayShort(day.date) }}</strong>
<span class="small muted">{{ formatShortDate(day.date) }}</span>
</div>
</div>
<OnyxTable striped with-page-scrolling :table-attrs="{ style: 'min-width: 46rem' }" style="margin-top: var(--onyx-density-lg)">
<template #head>
<tr>
<th scope="col">Day</th>
<th scope="col">Mean</th>
<th scope="col">Peak</th>
<th scope="col">Peak hour</th>
<th scope="col">80% band at peak</th>
<th scope="col">Weather</th>
<th scope="col">Staff at peak</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>
<OnyxBadge v-if="day.date === weekPeak?.date" color="warning" density="compact" style="margin-left: 0.35rem">peak</OnyxBadge>
</th>
<td>{{ formatNumber(day.mean) }}</td>
<td>{{ formatNumber(day.peak) }}</td>
<td>{{ String(day.peakHour).padStart(2, '0') }}:00</td>
<td>{{ formatNumber(day.points.find((point) => point.v === day.peak)?.lo ?? 0) }}–{{ formatNumber(day.points.find((point) => point.v === day.peak)?.hi ?? 0) }}</td>
<td>
<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 weather window</span>
</td>
<td><OnyxBadge color="neutral" density="compact">{{ day.requiredAtPeak }}</OnyxBadge></td>
</tr>
</OnyxTable>
<p class="small muted table-note">
Scroll the table sideways on a phone for the uncertainty band and staffing columns. Weekly mean
{{ formatNumber(total) }} estimated devices/hour across open+closed hours. Staff at peak uses 25
visitors/staff-hour × 1.15; the plan can use a different standard.
</p>
</OnyxCard>
<div class="split-grid">
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Weather strip</OnyxHeadline>
<OnyxBadge color="neutral" density="compact">Open-Meteo context</OnyxBadge>
</div>
<WeatherStrip :days="weekWeather" />
<p v-if="!weekWeather.length" class="small muted table-note">
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.
</p>
</OnyxCard>
<OnyxCard>
<div class="card-header">
<OnyxHeadline is="h2">Read it honestly</OnyxHeadline>
<OnyxIcon :icon="iconChart" size="24px" color="primary" />
</div>
<ul class="why-list">
<li>
<OnyxIcon :icon="iconCalendar" size="16px" color="primary" />
<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 API meta;
per-hour uncertainty is real.
</span>
</li>
<li>
<OnyxIcon :icon="iconCalendar" size="16px" color="primary" />
<span>
Forecast covers {{ formatDate(forecastStart) }} → {{ formatDate(forecastEnd) }} in Europe/Berlin.
</span>
</li>
</ul>
<OnyxButton label="Turn this into a plan" link="/plan" color="primary" style="margin-top: var(--onyx-density-md)" />
</OnyxCard>
</div>
</div>
</template>
<style scoped>
.forecast-bars {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(4.5rem, 1fr));
gap: var(--onyx-density-xs);
align-items: end;
min-height: 13rem;
}
.forecast-bar {
display: flex;
min-width: 0;
flex-direction: column;
align-items: center;
gap: 0.2rem;
text-align: center;
}
.forecast-bar strong {
font-size: 0.8125rem;
}
.forecast-bar__track {
display: flex;
width: 100%;
height: 8rem;
align-items: flex-end;
border-radius: 3px;
background: var(--onyx-color-base-neutral-200);
}
.forecast-bar__fill {
width: 100%;
border-radius: 3px 3px 0 0;
background: var(--onyx-color-base-primary-500);
}
.forecast-header-controls {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: var(--onyx-density-sm);
}
@media (max-width: 576px) {
.forecast-bars {
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: var(--onyx-density-2xs);
}
.forecast-bar strong {
font-size: 0.7rem;
}
.forecast-bar .small {
font-size: 0.65rem;
}
}
</style>
+506
View File
@@ -0,0 +1,506 @@
<script setup lang="ts">
import { iconSync, iconTriangleWarning } from '@sit-onyx/icons'
import { addDays, berlinParts, planWeekStart } from '#shared/staffing'
import { scenarioLabel } from '#shared/live'
import type { ScenarioState, Sensor, StaffingResponse } from '#shared/types'
import {
formatDateTime,
formatEuro,
formatNumber,
formatPercent,
formatShortDate,
formatTime,
formatWeekday,
weekLabel,
} from '~/utils/format'
import {
peakHourOf,
peakShiftOf,
planDays,
savingOf,
totalStaffHoursOf,
} from '~/utils/plan'
const config = useRuntimeConfig()
const demoNow = String(config.public.demoNow)
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: initialScenario } = await useFetch<ScenarioState>('/api/scenario')
const sensorId = ref(
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
'hn-stadtgalerie-01',
)
const live = useLiveScenario(initialScenario.value)
const {
data: planData,
error: planError,
refresh: refreshPlan,
} = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({
sensor: sensorId.value,
scenario: live.scenarioId,
standard: 'standard',
})),
})
let lastScenarioId = live.scenarioId
watch(
() => live.revision,
() => {
if (live.scenarioId === lastScenarioId) void refreshPlan()
lastScenarioId = live.scenarioId
},
)
const plan = computed(() => planData.value ?? null)
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const peakShift = computed(() => peakShiftOf(plan.value))
const peakHour = computed(() => peakHourOf(plan.value))
const totalStaffHours = computed(() => totalStaffHoursOf(plan.value))
const savingEur = computed(() => savingOf(plan.value))
const savingPct = computed(() => savingPctOf(plan.value))
const daySummaries = computed(() => planDays(plan.value))
const weekStart = computed(() => {
const first = plan.value?.hours[0]
return first ? berlinParts(first.t).date : planWeekStart(demoNow)
})
const weekEnd = computed(() => addDays(weekStart.value, 6))
const today = computed(() => berlinParts(demoNow).date)
const windowTag = computed(() => {
if (!plan.value) return 'No plan'
return weekStart.value <= today.value && today.value <= weekEnd.value ? 'Today–Friday' : 'Seven days'
})
const windowLabel = computed(() => (plan.value ? weekLabel(weekStart.value, weekEnd.value) : 'Window unavailable'))
const freshness = computed(() => live.lastEventAt || live.scenarioAt || plan.value?.context_version || '')
const scenarioName = computed(() => scenarioLabel(live.scenarioId))
const reason = computed(() => {
if (peakHour.value) {
return `Peak forecast ${formatNumber(peakHour.value.footfall)} est. devices/hour at ${formatTime(peakHour.value.t)}.`
}
return plan.value?.why[0] ?? 'Waiting for the forecast.'
})
const changed = ref(false)
let changedTimer: ReturnType<typeof setTimeout> | undefined
let mounted = false
watch(
() => live.revision,
() => {
if (!mounted) return
changed.value = true
if (changedTimer) clearTimeout(changedTimer)
changedTimer = setTimeout(() => {
changed.value = false
}, 8000)
},
)
onMounted(() => {
mounted = true
})
onBeforeUnmount(() => {
if (changedTimer) clearTimeout(changedTimer)
})
useHead({
title: 'Live plan — PulseCast',
meta: [{ name: 'theme-color', content: '#0e100e' }],
})
</script>
<template>
<div class="pc-dark live">
<header class="live__top">
<NuxtLink to="/" class="live__wordmark">
<span class="live__mark" aria-hidden="true" />
PulseCast
</NuxtLink>
<span class="live__top-status">
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" dark />
</span>
</header>
<main class="live__main">
<div v-if="planError" class="pc-alert pc-alert--dark live__alert" role="alert">
<OnyxIcon :icon="iconTriangleWarning" size="18px" color="warning" />
<span>The live plan is unavailable. Retry, or keep the last known plan on screen.</span>
<OnyxButton label="Retry" mode="outline" density="compact" :icon="iconSync" @click="refreshPlan()" />
</div>
<section class="live__hero" aria-labelledby="live-title">
<div class="live__hero-top">
<span class="pc-tag pc-tag--dark">{{ windowTag }}</span>
<span v-if="changed" class="pc-tag pc-tag--signal" role="status">Plan updated</span>
</div>
<p class="live__day">
<template v-if="peakShift">
{{ formatWeekday(peakShift.date) }} {{ formatShortDate(peakShift.date) }} · peak shift
</template>
<template v-else>Waiting for the plan</template>
</p>
<h1 id="live-title" class="live__number">
<template v-if="peakShift">{{ peakShift.staff }}<span class="live__unit">staff</span></template>
<template v-else><span class="live__number-empty">No plan</span></template>
</h1>
<p class="live__shift">
<template v-if="peakShift">{{ peakShift.start }}–{{ peakShift.end }}</template>
<template v-else>The next shift appears here.</template>
</p>
<p class="live__reason">{{ reason }}</p>
<p class="live__fresh">
<span>{{ freshness ? `Updated ${formatDateTime(freshness)}` : 'Waiting for the live stream' }}</span>
<span>v{{ live.version || '—' }}</span>
</p>
</section>
<section class="live__board" aria-labelledby="live-week-title">
<div class="live__section-head">
<h2 id="live-week-title" class="pc-label">The week</h2>
<span>{{ windowLabel }} · {{ windowTag }}</span>
</div>
<WeekBoard
v-if="daySummaries.length"
:days="daySummaries"
:peak-date="peakShift?.date"
dense
dark
label="The week at a glance"
/>
<div v-else class="pc-skeleton pc-skeleton--dark" style="height: 7rem" aria-busy="true" />
</section>
<section class="live__receipt" aria-label="Plan cost and coverage">
<div>
<span class="pc-label">Staff-hours</span>
<strong>{{ plan ? totalStaffHours : '—' }}</strong>
</div>
<div>
<span class="pc-label">Planned cost</span>
<strong>{{ plan ? formatEuro(plan.summary.cost_eur) : '—' }}</strong>
<small v-if="plan">vs {{ formatEuro(plan.summary.flat_schedule_cost_eur) }} flat · {{ formatEuro(savingEur) }} saved</small>
<small v-else>Waiting for the plan</small>
</div>
<div>
<span class="pc-label">Coverage</span>
<strong>{{ plan ? formatPercent(plan.summary.coverage_pct, 1) : '—' }}</strong>
<small v-if="plan">{{ plan.summary.understaffed_hours }} h short · {{ plan.summary.overstaffed_hours }} h over</small>
<small v-else>Waiting for the plan</small>
</div>
</section>
<section class="live__context" aria-label="Live context">
<div><span>Scenario</span><strong>{{ scenarioName }}</strong></div>
<div>
<span>Transport</span>
<strong>{{ live.statusLabel }}<template v-if="live.status === 'polling'"> · 5 s</template></strong>
</div>
<div><span>Updated</span><strong>{{ freshness ? formatDateTime(freshness) : '—' }}</strong></div>
</section>
<NuxtLink class="pc-link-button pc-link-button--primary live__cta" to="/plan">
Open the full plan <span aria-hidden="true">→</span>
</NuxtLink>
<p class="live__note">
Estimated devices, not people. {{ plan?.assumptions.visitors_per_staff_hour ?? 25 }} visitors/staff-hour ·
×{{ plan?.assumptions.safety_factor ?? 1.15 }} safety · €{{ plan?.assumptions.labor_cost_eur_h ?? 16 }}/h.
No login. If the stream drops, this page polls every five seconds.
</p>
<p v-if="activeSensor" class="live__sensor">{{ activeSensor.name }} · {{ activeSensor.id }}</p>
</main>
</div>
</template>
<style scoped>
.live {
min-height: 100dvh;
padding: max(1rem, env(safe-area-inset-top)) max(1rem, env(safe-area-inset-right))
max(1.25rem, env(safe-area-inset-bottom)) max(1rem, env(safe-area-inset-left));
}
.live__top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
width: 100%;
max-width: 34rem;
margin-inline: auto;
padding-bottom: 0.7rem;
border-bottom: 1px solid var(--pc-dark-line);
}
.live__wordmark {
display: inline-flex;
align-items: center;
gap: 0.45rem;
color: var(--pc-paper);
font-size: 0.82rem;
font-weight: 800;
letter-spacing: -0.02em;
text-decoration: none;
}
.live__mark {
display: block;
width: 0.42rem;
height: 1.1rem;
background: var(--pc-signal-bright);
}
.live__top-status {
display: inline-flex;
align-items: center;
}
.live__main {
display: flex;
width: 100%;
max-width: 34rem;
flex-direction: column;
gap: 0.9rem;
margin-inline: auto;
padding-top: 0.85rem;
}
.live__alert {
margin-top: 0.25rem;
}
.live__hero {
display: flex;
flex-direction: column;
gap: 0.25rem;
padding-bottom: 0.9rem;
border-bottom: 2px solid var(--pc-paper);
}
.live__hero-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
margin-bottom: 0.5rem;
}
.live__hero .pc-label {
color: var(--pc-dark-muted);
}
.live__day {
margin: 0;
color: var(--pc-dark-muted);
font-size: 0.8rem;
font-weight: 750;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.live__number {
display: flex;
align-items: baseline;
gap: 0.45rem;
margin: 0;
color: var(--pc-signal-bright);
font-size: clamp(7.5rem, 38vw, 12rem);
font-stretch: 74%;
font-weight: 850;
line-height: 0.78;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.live__unit {
color: var(--pc-paper);
font-size: clamp(1rem, 4.2vw, 1.35rem);
font-stretch: 100%;
font-weight: 700;
letter-spacing: 0;
text-transform: uppercase;
}
.live__number-empty {
color: var(--pc-paper);
font-size: clamp(2rem, 9vw, 3rem);
font-stretch: 100%;
letter-spacing: -0.02em;
}
.live__shift {
margin: 0.5rem 0 0;
color: var(--pc-paper);
font-size: clamp(1.8rem, 8.5vw, 2.6rem);
font-weight: 800;
letter-spacing: -0.03em;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.live__reason {
max-width: 34ch;
margin: 0.6rem 0 0;
color: var(--pc-dark-muted);
font-size: 0.86rem;
line-height: 1.4;
}
.live__fresh {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.4rem;
margin: 0.8rem 0 0;
color: var(--pc-dark-muted);
font-size: 0.7rem;
font-variant-numeric: tabular-nums;
letter-spacing: 0.02em;
}
.live__fresh span:last-child {
color: var(--pc-paper);
font-weight: 700;
}
.live__board {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.live__section-head {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 0.35rem;
color: var(--pc-dark-muted);
font-size: 0.68rem;
font-variant-numeric: tabular-nums;
}
.live__section-head .pc-label {
color: var(--pc-dark-muted);
}
.live__receipt {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
border-block: 1px solid var(--pc-dark-line);
}
.live__receipt > div {
min-width: 0;
padding: 0.55rem 0.5rem;
border-inline-end: 1px solid var(--pc-dark-line);
}
.live__receipt > div:first-child {
padding-inline-start: 0;
}
.live__receipt > div:last-child {
border-inline-end: 0;
padding-inline-end: 0;
}
.live__receipt .pc-label {
display: block;
color: var(--pc-dark-muted);
font-size: 0.58rem;
}
.live__receipt strong {
display: block;
margin-top: 0.25rem;
color: var(--pc-paper);
font-size: clamp(1.15rem, 5vw, 1.5rem);
font-weight: 800;
letter-spacing: -0.02em;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.live__receipt small {
display: block;
margin-top: 0.25rem;
color: var(--pc-dark-muted);
font-size: 0.58rem;
line-height: 1.3;
}
.live__context {
display: grid;
gap: 0.15rem;
padding-block: 0.55rem;
border-bottom: 1px solid var(--pc-dark-line);
}
.live__context > div {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 0.75rem;
padding-block: 0.22rem;
}
.live__context span {
color: var(--pc-dark-muted);
font-size: 0.68rem;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.live__context strong {
color: var(--pc-paper);
font-size: 0.76rem;
font-weight: 650;
text-align: right;
}
.live__cta {
width: 100%;
}
.live__note {
margin: 0;
color: var(--pc-dark-muted);
font-size: 0.68rem;
line-height: 1.5;
}
.live__sensor {
margin: 0;
color: var(--pc-dark-muted);
font-family: var(--pc-font);
font-size: 0.6rem;
letter-spacing: 0.03em;
opacity: 0.75;
}
@media (min-width: 700px) {
.live {
padding-block: 2rem;
}
.live__top,
.live__main {
max-width: 36rem;
}
.live__main {
gap: 1.1rem;
}
}
</style>
+1017
View File
File diff suppressed because it is too large. Load diff
+270
View File
@@ -0,0 +1,270 @@
<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>
+677
View File
@@ -0,0 +1,677 @@
<script setup lang="ts">
import { iconSync, iconTriangleWarning } from '@sit-onyx/icons'
import { addDays, berlinParts, planWeekStart } from '#shared/staffing'
import { scenarioLabel } from '#shared/live'
import type { ScenarioState, Sensor, StaffingResponse } from '#shared/types'
import {
formatDateTime,
formatEuro,
formatNumber,
formatPercent,
formatShortDate,
formatTime,
formatWeekday,
weekLabel,
} from '~/utils/format'
import {
peakHourOf,
peakShiftOf,
planDays,
planPulsePoints,
savingOf,
totalStaffHoursOf,
} from '~/utils/plan'
const config = useRuntimeConfig()
const demoNow = String(config.public.demoNow)
const { data: sensors } = await useFetch<Sensor[]>('/api/sensors')
const { data: initialScenario } = await useFetch<ScenarioState>('/api/scenario')
const sensorId = ref(
sensors.value?.find((sensor) => sensor.id === 'hn-stadtgalerie-01')?.id ??
sensors.value?.[0]?.id ??
'hn-stadtgalerie-01',
)
const live = useLiveScenario(initialScenario.value)
const {
data: planData,
error: planError,
refresh: refreshPlan,
} = await useFetch<StaffingResponse>('/api/staffing', {
query: computed(() => ({
sensor: sensorId.value,
scenario: live.scenarioId,
standard: 'standard',
})),
})
const {
error: forecastError,
refresh: refreshForecast,
} = await useFetch('/api/forecast', {
query: computed(() => ({
sensor: sensorId.value,
horizon: '7d',
scenario: live.scenarioId,
})),
})
let lastScenarioId = live.scenarioId
watch(
() => live.revision,
() => {
if (live.scenarioId === lastScenarioId) {
void refreshPlan()
void refreshForecast()
}
lastScenarioId = live.scenarioId
},
)
const plan = computed(() => planData.value ?? null)
const activeSensor = computed(() => sensors.value?.find((sensor) => sensor.id === sensorId.value))
const peakShift = computed(() => peakShiftOf(plan.value))
const peakHour = computed(() => peakHourOf(plan.value))
const totalStaffHours = computed(() => totalStaffHoursOf(plan.value))
const savingEur = computed(() => savingOf(plan.value))
const daySummaries = computed(() => planDays(plan.value))
const pulsePoints = computed(() => planPulsePoints(plan.value))
const weekStart = computed(() => {
const first = plan.value?.hours[0]
return first ? berlinParts(first.t).date : planWeekStart(demoNow)
})
const weekEnd = computed(() => addDays(weekStart.value, 6))
const today = computed(() => berlinParts(demoNow).date)
const windowTag = computed(() => {
if (!plan.value) return 'No plan'
return weekStart.value <= today.value && today.value <= weekEnd.value ? 'Today–Friday' : 'Seven days'
})
const windowLabel = computed(() => (plan.value ? weekLabel(weekStart.value, weekEnd.value) : 'Window unavailable'))
const freshness = computed(() => live.lastEventAt || live.scenarioAt || plan.value?.context_version || '')
const scenarioName = computed(() => scenarioLabel(live.scenarioId))
const reason = computed(() => {
if (peakHour.value) {
return `Peak forecast ${formatNumber(peakHour.value.footfall)} est. devices/hour at ${formatTime(peakHour.value.t)}.`
}
return plan.value?.why[0] ?? 'Waiting for the forecast.'
})
const requestUrl = useRequestURL()
const liveUrl = computed(() => {
const origin = import.meta.client ? window.location.origin : requestUrl.origin
return `${origin}/live`
})
const qrSrc = computed(() => `/api/qr?text=${encodeURIComponent(liveUrl.value)}`)
const changed = ref(false)
let changedTimer: ReturnType<typeof setTimeout> | undefined
let mounted = false
watch(
() => live.revision,
() => {
if (!mounted) return
changed.value = true
if (changedTimer) clearTimeout(changedTimer)
changedTimer = setTimeout(() => {
changed.value = false
}, 8000)
},
)
onMounted(() => {
mounted = true
})
onBeforeUnmount(() => {
if (changedTimer) clearTimeout(changedTimer)
})
useHead({
title: 'Stage — PulseCast live decision',
meta: [{ name: 'theme-color', content: '#0e100e' }],
})
</script>
<template>
<div class="pc-dark stage">
<header class="stage__top">
<div class="stage__brand">
<span class="stage__mark" aria-hidden="true" />
<span>PulseCast</span>
</div>
<div class="stage__context">
<span>{{ scenarioName }}</span>
<span class="stage__sep" aria-hidden="true">/</span>
<span>{{ windowLabel }}</span>
<span class="pc-tag pc-tag--dark">{{ windowTag }}</span>
</div>
<div class="stage__status">
<LiveStatusBadge :status="live.status" :last-event-at="live.lastEventAt" dark />
<span class="stage__version">v{{ live.version || '—' }}</span>
</div>
</header>
<section v-if="planError" class="stage__error" role="alert">
<OnyxIcon :icon="iconTriangleWarning" size="28px" color="warning" />
<div>
<h1 class="stage__error-title">The plan is unavailable.</h1>
<p>The plan service did not answer. Retry when the connection is back.</p>
<p v-if="forecastError" class="stage__muted">The forecast refresh also failed.</p>
</div>
<OnyxButton label="Retry" mode="outline" :icon="iconSync" @click="refreshPlan()" />
</section>
<main v-else-if="plan" class="stage__main">
<section class="stage__decision" aria-labelledby="stage-title">
<p class="stage__day">
<template v-if="peakShift">{{ formatWeekday(peakShift.date) }} {{ formatShortDate(peakShift.date) }}</template>
<template v-else>The week</template>
</p>
<h1 id="stage-title" class="stage__number">
<template v-if="peakShift">{{ peakShift.staff }}<span class="stage__unit">staff</span></template>
<template v-else>—</template>
</h1>
<p class="stage__shift">
<template v-if="peakShift">{{ peakShift.start }}–{{ peakShift.end }}</template>
<template v-else>No shift blocks</template>
</p>
<p class="stage__reason">{{ reason }}</p>
<p v-if="changed" class="pc-tag pc-tag--signal stage__changed" role="status">Plan updated</p>
<p class="stage__updated">
Updated {{ freshness ? formatDateTime(freshness) : '—' }} · {{ activeSensor?.name ?? 'Stadtgalerie' }}
</p>
</section>
<section class="stage__board" aria-labelledby="stage-week-title">
<div class="stage__board-head">
<h2 id="stage-week-title" class="pc-label">The week · forecast above, staff below</h2>
<span>{{ windowLabel }} · {{ windowTag }}</span>
</div>
<PulseLine
:points="pulsePoints"
:height="58"
label="Forecast footfall across the plan window, with the peak marked"
/>
<WeekBoard
:days="daySummaries"
:peak-date="peakShift?.date"
large
dark
label="Weekly shift board"
/>
</section>
<aside class="stage__side">
<div class="stage__receipt" aria-label="The week, costed">
<p class="stage__receipt-label">The week, costed</p>
<p class="stage__receipt-value">{{ formatEuro(plan.summary.cost_eur) }}</p>
<div class="stage__receipt-row">
<span>Staff-hours</span>
<strong>{{ totalStaffHours }}</strong>
</div>
<div class="stage__receipt-row">
<span>Flat schedule</span>
<strong>{{ formatEuro(plan.summary.flat_schedule_cost_eur) }}</strong>
</div>
<div class="stage__receipt-row">
<span>Saved</span>
<strong class="stage__green">{{ formatEuro(savingEur) }}</strong>
</div>
<div class="stage__receipt-row">
<span>Coverage</span>
<strong>{{ formatPercent(plan.summary.coverage_pct, 1) }}</strong>
</div>
<div class="stage__receipt-row">
<span>Under requirement</span>
<strong>{{ plan.summary.understaffed_hours }} h</strong>
</div>
<div class="stage__receipt-row">
<span>Over requirement</span>
<strong>{{ plan.summary.overstaffed_hours }} h</strong>
</div>
<p class="stage__receipt-note">Trade-off is visible. Overstaffed hours are not hidden.</p>
</div>
<div class="stage__qr">
<div class="stage__qr-frame">
<img :src="qrSrc" width="220" height="220" :alt="`QR code to ${liveUrl}`" />
</div>
<p class="stage__qr-label">Scan for the live plan</p>
<p class="stage__qr-url">{{ liveUrl }}</p>
</div>
</aside>
</main>
<main v-else class="stage__loading" aria-busy="true">
<div class="pc-skeleton pc-skeleton--dark" style="width: 24rem; height: 2rem" />
<div class="pc-skeleton pc-skeleton--dark" style="width: 34rem; height: 12rem; margin-top: 1.5rem" />
<div class="pc-skeleton pc-skeleton--dark" style="width: 100%; height: 18rem; margin-top: 2rem" />
<p>Building the week…</p>
</main>
<footer class="stage__footer">
<span><strong>Measured</strong> footfall → <strong>modelled</strong> forecast → <strong>declared</strong> assumptions.</span>
<span v-if="plan">
{{ plan.assumptions.visitors_per_staff_hour }} visitors/staff-h ·
×{{ plan.assumptions.safety_factor }} safety ·
{{ plan.assumptions.shift_length_h }} h blocks ·
€{{ plan.assumptions.labor_cost_eur_h }}/h ·
8 sensors in 580 m · no POS data
</span>
<span v-else>No plan data · 8 sensors in 580 m · no POS data</span>
<span>Decision support, not an optimizer.</span>
</footer>
</div>
</template>
<style scoped>
.stage {
display: grid;
min-height: 100dvh;
grid-template-rows: auto 1fr auto;
gap: 1.1rem;
padding: clamp(1.2rem, 2.6vw, 2.6rem) clamp(1.2rem, 3vw, 3.5rem) clamp(1rem, 1.6vw, 1.5rem);
}
.stage__top {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding-bottom: 0.8rem;
border-bottom: 1px solid var(--pc-dark-line);
}
.stage__brand {
display: inline-flex;
align-items: center;
gap: 0.55rem;
color: var(--pc-paper);
font-size: 0.95rem;
font-weight: 800;
letter-spacing: -0.02em;
}
.stage__mark {
display: block;
width: 0.55rem;
height: 1.5rem;
background: var(--pc-signal-bright);
}
.stage__context {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
color: var(--pc-dark-muted);
font-size: 0.74rem;
font-variant-numeric: tabular-nums;
letter-spacing: 0.02em;
}
.stage__sep {
color: var(--pc-dark-line);
}
.stage__status {
display: flex;
align-items: center;
gap: 0.7rem;
}
.stage__version {
color: var(--pc-dark-muted);
font-size: 0.7rem;
font-variant-numeric: tabular-nums;
}
.stage__main {
display: grid;
grid-template-columns: minmax(24rem, 0.9fr) minmax(0, 1.5fr) minmax(17rem, 0.62fr);
gap: clamp(1.5rem, 3vw, 3.2rem);
align-items: center;
min-height: 0;
}
.stage__decision {
display: flex;
min-width: 0;
flex-direction: column;
align-items: flex-start;
gap: 0.2rem;
}
.stage__day {
margin: 0;
color: var(--pc-dark-muted);
font-size: clamp(1.1rem, 1.5vw, 1.55rem);
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stage__number {
display: flex;
align-items: baseline;
gap: 0.65rem;
margin: 0.1rem 0 0;
color: var(--pc-signal-bright);
font-size: clamp(10rem, 18vw, 19rem);
font-stretch: 72%;
font-weight: 850;
line-height: 0.76;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.stage__unit {
color: var(--pc-paper);
font-size: clamp(1.4rem, 2.2vw, 2.2rem);
font-stretch: 100%;
font-weight: 700;
letter-spacing: 0;
text-transform: uppercase;
}
.stage__shift {
margin: 0.4rem 0 0;
color: var(--pc-paper);
font-size: clamp(2.4rem, 4.4vw, 4.6rem);
font-weight: 800;
letter-spacing: -0.035em;
line-height: 0.9;
font-variant-numeric: tabular-nums;
}
.stage__reason {
max-width: 30ch;
margin: 0.9rem 0 0;
color: var(--pc-dark-muted);
font-size: clamp(0.95rem, 1.3vw, 1.25rem);
line-height: 1.4;
}
.stage__changed {
margin-top: 0.75rem;
}
.stage__updated {
margin: 0.85rem 0 0;
color: var(--pc-dark-muted);
font-size: clamp(0.68rem, 0.95vw, 0.82rem);
font-variant-numeric: tabular-nums;
letter-spacing: 0.02em;
}
.stage__board {
display: flex;
min-width: 0;
flex-direction: column;
gap: 0.55rem;
}
.stage__board-head {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 0.5rem;
color: var(--pc-dark-muted);
font-size: 0.72rem;
font-variant-numeric: tabular-nums;
}
.stage__board-head .pc-label {
color: var(--pc-dark-muted);
}
.stage__board :deep(.pc-pulse) {
--pc-pulse-color: var(--pc-dark-line);
}
.stage__side {
display: flex;
min-width: 0;
flex-direction: column;
justify-content: center;
gap: clamp(1.2rem, 2vw, 2rem);
}
.stage__receipt {
padding-top: 0.5rem;
border-top: 3px solid var(--pc-paper);
}
.stage__receipt-label {
margin: 0;
color: var(--pc-dark-muted);
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.stage__receipt-value {
margin: 0.25rem 0 0.5rem;
color: var(--pc-paper);
font-size: clamp(2.4rem, 3.4vw, 3.6rem);
font-stretch: 84%;
font-weight: 850;
line-height: 0.9;
letter-spacing: -0.03em;
font-variant-numeric: tabular-nums;
}
.stage__receipt-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 0.6rem;
padding-block: 0.3rem;
border-bottom: 1px solid var(--pc-dark-line);
}
.stage__receipt-row span {
color: var(--pc-dark-muted);
font-size: 0.72rem;
letter-spacing: 0.03em;
}
.stage__receipt-row strong {
color: var(--pc-paper);
font-size: 0.92rem;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.stage__green {
color: var(--pc-green-bright) !important;
}
.stage__receipt-note {
margin: 0.5rem 0 0;
color: var(--pc-dark-muted);
font-size: 0.65rem;
line-height: 1.4;
}
.stage__qr {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.35rem;
}
.stage__qr-frame {
padding: 0.5rem;
background: var(--pc-paper);
}
.stage__qr-frame img {
display: block;
width: clamp(9rem, 11vw, 13rem);
height: auto;
}
.stage__qr-label {
margin: 0.2rem 0 0;
color: var(--pc-paper);
font-size: clamp(1rem, 1.15vw, 1.2rem);
font-weight: 700;
}
.stage__qr-url {
margin: 0;
color: var(--pc-dark-muted);
font-size: 0.66rem;
overflow-wrap: anywhere;
}
.stage__footer {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 0.7rem;
padding-top: 0.65rem;
border-top: 1px solid var(--pc-dark-line);
color: var(--pc-dark-muted);
font-size: 0.66rem;
line-height: 1.4;
}
.stage__footer strong {
color: var(--pc-paper);
font-weight: 700;
}
.stage__error,
.stage__loading {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 1.2rem;
align-self: center;
justify-self: center;
max-width: 60rem;
color: var(--pc-paper);
}
.stage__error {
flex-direction: column;
align-items: flex-start;
gap: 0.7rem;
}
.stage__error-title {
margin: 0;
color: var(--pc-paper);
font-size: clamp(2.5rem, 4vw, 4rem);
font-stretch: 80%;
font-weight: 850;
letter-spacing: -0.03em;
}
.stage__error p {
margin: 0.4rem 0;
color: var(--pc-dark-muted);
}
.stage__muted {
color: var(--pc-dark-muted);
}
.stage__loading {
flex-direction: column;
align-items: flex-start;
}
.stage__loading p {
margin: 0;
color: var(--pc-dark-muted);
}
@media (max-width: 1500px) {
.stage__main {
grid-template-columns: minmax(20rem, 0.9fr) minmax(0, 1.4fr) minmax(15rem, 0.6fr);
gap: 1.5rem;
}
.stage__number {
font-size: clamp(8rem, 15vw, 14rem);
}
.stage__shift {
font-size: clamp(2rem, 3.5vw, 3.6rem);
}
}
@media (max-width: 1100px) {
.stage__main {
grid-template-columns: minmax(0, 1fr);
gap: 1.5rem;
}
.stage__side {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: end;
}
.stage__number {
font-size: clamp(7rem, 25vw, 14rem);
}
.stage__qr {
align-items: flex-end;
}
.stage__qr-frame img {
width: 9rem;
}
}
@media (max-width: 640px) {
.stage {
padding: 0.9rem;
}
.stage__top {
align-items: flex-start;
}
.stage__context {
order: 3;
width: 100%;
}
.stage__main {
gap: 1rem;
}
.stage__number {
font-size: 7.5rem;
}
.stage__shift {
font-size: 2.2rem;
}
.stage__side {
grid-template-columns: minmax(0, 1fr);
}
.stage__qr {
align-items: flex-start;
}
.stage__footer {
flex-direction: column;
}
}
</style>
+7
View File
@@ -0,0 +1,7 @@
import type { RouterConfig } from '@nuxt/schema'
// Onyx scrolls inside .onyx-page__main, not the window, so the default Nuxt
// scroll behaviour does not reach the page container.
export default {
scrollBehavior: createOnyxScrollBehavior(),
} satisfies RouterConfig
+27
View File
@@ -0,0 +1,27 @@
interface ApiErrorLike {
status?: number
statusCode?: number
statusMessage?: string
message?: string
data?: {
error?: { message?: string; code?: string }
message?: string
}
}
/** Human-readable message from a Nuxt/$fetch error, without leaking tokens. */
export function apiErrorMessage(error: unknown, fallback: string): string {
const value = error as ApiErrorLike | undefined
return (
value?.data?.error?.message ??
value?.data?.message ??
value?.statusMessage ??
value?.message ??
fallback
)
}
export function apiErrorStatus(error: unknown): number | undefined {
const value = error as ApiErrorLike | undefined
return value?.status ?? value?.statusCode
}
+44
View File
@@ -0,0 +1,44 @@
export interface GeoPoint {
lat: number
lon: number
}
export interface ProjectedPoint {
x: number
y: number
}
export function createProjection(
points: GeoPoint[],
width = 1200,
height = 800,
padding = 80,
): (point: GeoPoint) => ProjectedPoint {
const lats = points.map((point) => point.lat)
const lons = points.map((point) => point.lon)
const minLat = Math.min(...lats)
const maxLat = Math.max(...lats)
const minLon = Math.min(...lons)
const maxLon = Math.max(...lons)
const spanLat = Math.max(maxLat - minLat, 0.0001)
const spanLon = Math.max(maxLon - minLon, 0.0001)
const innerW = width - padding * 2
const innerH = height - padding * 2
return (point: GeoPoint) => ({
x: padding + ((point.lon - minLon) / spanLon) * innerW,
y: padding + ((maxLat - point.lat) / spanLat) * innerH,
})
}
export function pathFromCoordinates(
coordinates: Array<[number, number]>,
project: (point: GeoPoint) => ProjectedPoint,
): string {
return coordinates
.map(([lon, lat], index) => {
const point = project({ lat, lon })
return `${index === 0 ? 'M' : 'L'} ${point.x.toFixed(1)} ${point.y.toFixed(1)}`
})
.join(' ')
}
+52
View File
@@ -0,0 +1,52 @@
import type { CoolRouteValues } from '#shared/cool'
export function coolValue(value: number | null | undefined, suffix = ''): string {
if (value === null || value === undefined || Number.isNaN(value)) return 'TBD'
return `${value}${suffix}`
}
export function coolShade(value: number | null | undefined): string {
if (value === null || value === undefined) return 'TBD'
return `${value.toFixed(1)}%`
}
export function coolDistance(value: number | null | undefined): string {
if (value === null || value === undefined) return 'TBD'
if (value >= 1000) return `${(value / 1000).toFixed(2)} km`
return `${Math.floor(value)} m`
}
export function coolMinutes(value: number | null | undefined): string {
if (value === null || value === undefined) return 'TBD'
return `${value.toFixed(1)} min`
}
export function coolYesNo(value: boolean | null | undefined): string {
if (value === null || value === undefined) return 'TBD'
return value ? 'Yes' : 'No'
}
export function coolStops(value: number | null | undefined): string {
if (value === null || value === undefined) return 'TBD'
return String(value)
}
export function coolValues(values: CoolRouteValues | null | undefined): CoolRouteValues {
return (
values ?? {
shadePct: null,
directSunMin: null,
distanceM: null,
durationMin: null,
stepFree: null,
waterStops: null,
benchStops: null,
rampInclinePct: null,
}
)
}
export function coolTallyPct(count: number, total: number): number {
if (!total) return 0
return Math.round((count / total) * 100)
}
+99
View File
@@ -0,0 +1,99 @@
import { BERLIN_TZ } from '#shared/staffing'
const dateFormatter = new Intl.DateTimeFormat('en-GB', {
timeZone: BERLIN_TZ,
day: 'numeric',
month: 'short',
year: 'numeric',
})
const shortDateFormatter = new Intl.DateTimeFormat('en-GB', {
timeZone: BERLIN_TZ,
day: 'numeric',
month: 'short',
})
const weekdayFormatter = new Intl.DateTimeFormat('en-GB', {
timeZone: BERLIN_TZ,
weekday: 'long',
})
const weekdayShortFormatter = new Intl.DateTimeFormat('en-GB', {
timeZone: BERLIN_TZ,
weekday: 'short',
})
const dateTimeFormatter = new Intl.DateTimeFormat('en-GB', {
timeZone: BERLIN_TZ,
day: 'numeric',
month: 'short',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
})
const timeFormatter = new Intl.DateTimeFormat('en-GB', {
timeZone: BERLIN_TZ,
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
})
const euroFormatter = new Intl.NumberFormat('en-GB', {
style: 'currency',
currency: 'EUR',
maximumFractionDigits: 0,
})
const numberFormatter = new Intl.NumberFormat('en-GB')
/** Date-only strings are parsed at noon UTC so the local date never shifts. */
function toDate(value: string): Date {
return value.length > 10 ? new Date(value) : new Date(`${value}T12:00:00Z`)
}
function formatWith(formatter: Intl.DateTimeFormat, value: string): string {
const date = toDate(value)
return Number.isNaN(date.getTime()) ? '—' : formatter.format(date)
}
export function formatDate(date: string): string {
return formatWith(dateFormatter, date)
}
export function formatShortDate(date: string): string {
return formatWith(shortDateFormatter, date)
}
export function formatWeekday(date: string): string {
return formatWith(weekdayFormatter, date)
}
export function formatWeekdayShort(date: string): string {
return formatWith(weekdayShortFormatter, date)
}
/** Format a wire timestamp in Heilbronn local time. */
export function formatDateTime(iso: string): string {
return formatWith(dateTimeFormatter, iso)
}
export function formatTime(iso: string): string {
return formatWith(timeFormatter, iso)
}
export function formatEuro(value: number): string {
return euroFormatter.format(value)
}
export function formatNumber(value: number): string {
return numberFormatter.format(value)
}
export function formatPercent(value: number, digits = 0): string {
return `${value.toFixed(digits)}%`
}
export function weekLabel(start: string, end: string): string {
return `${formatShortDate(start)} – ${formatDate(end)}`
}
+108
View File
@@ -0,0 +1,108 @@
import { berlinParts } from '#shared/staffing'
import type { Point, Shift, StaffingHour, StaffingResponse } from '#shared/types'
import { formatShortDate, formatWeekday, formatWeekdayShort } from '~/utils/format'
export interface PlanDay {
date: string
dayNumber: string
month: string
weekday: string
weekdayLong: string
shifts: Shift[]
hours: StaffingHour[]
staffHours: number
peakStaff: number
peakFootfall: number
peakHour: number
cost: number
overHours: number
underHours: number
}
export function maxOf<T>(items: T[], score: (item: T) => number): T | undefined {
let best: T | undefined
for (const item of items) {
if (!best || score(item) > score(best)) best = item
}
return best
}
export function peakShiftOf(plan: StaffingResponse | null | undefined): Shift | undefined {
return plan ? maxOf(plan.shifts, (shift) => shift.staff) : undefined
}
export function peakHourOf(plan: StaffingResponse | null | undefined): StaffingHour | undefined {
return plan ? maxOf(plan.hours, (hour) => hour.footfall) : undefined
}
export function totalStaffHoursOf(plan: StaffingResponse | null | undefined): number {
return plan ? plan.hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0) : 0
}
export function savingOf(plan: StaffingResponse | null | undefined): number {
if (!plan) return 0
return Math.max(0, plan.summary.flat_schedule_cost_eur - plan.summary.cost_eur)
}
export function savingPctOf(plan: StaffingResponse | null | undefined): number {
if (!plan || plan.summary.flat_schedule_cost_eur <= 0) return 0
return (savingOf(plan) / plan.summary.flat_schedule_cost_eur) * 100
}
export function planDays(plan: StaffingResponse | null | undefined): PlanDay[] {
if (!plan) return []
const shiftsByDate: Record<string, Shift[]> = {}
for (const shift of plan.shifts) (shiftsByDate[shift.date] ??= []).push(shift)
const hoursByDate: Record<string, StaffingHour[]> = {}
for (const hour of plan.hours) {
const date = berlinParts(hour.t).date
;(hoursByDate[date] ??= []).push(hour)
}
const dates = [...new Set([...Object.keys(shiftsByDate), ...Object.keys(hoursByDate)])].sort()
const costPerHour = plan.assumptions.labor_cost_eur_h
return dates.map((date) => {
const shifts = (shiftsByDate[date] ?? []).slice().sort((a, b) => a.start.localeCompare(b.start))
const hours = (hoursByDate[date] ?? []).slice().sort((a, b) => a.t.localeCompare(b.t))
const peakHour = maxOf(hours, (hour) => hour.footfall)
const staffHours = hours.reduce((sum, hour) => sum + hour.scheduled_staff, 0)
const [dayNumber = '', month = ''] = formatShortDate(date).split(' ')
return {
date,
dayNumber,
month,
weekday: formatWeekdayShort(date),
weekdayLong: formatWeekday(date),
shifts,
hours,
staffHours,
peakStaff: Math.max(0, ...hours.map((hour) => hour.scheduled_staff), ...shifts.map((shift) => shift.staff)),
peakFootfall: peakHour?.footfall ?? 0,
peakHour: peakHour ? berlinParts(peakHour.t).hour : 0,
cost: staffHours * costPerHour,
overHours: hours.filter((hour) => hour.coverage === 'over').length,
underHours: hours.filter((hour) => hour.coverage === 'under').length,
}
})
}
export function planPulsePoints(plan: StaffingResponse | null | undefined): Point[] {
return (plan?.hours ?? []).map((hour) => ({ t: hour.t, v: hour.footfall }))
}
export function numberWord(value: number): string {
const words = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
return words[value] ?? String(value)
}
export function shiftLabel(shift: Shift): string {
return `${shift.start}–${shift.end}`
}
export function coverWord(value: number, singular: string, plural = `${singular}s`): string {
return `${value} ${value === 1 ? singular : plural}`
}