@burdenoff/microfe-movethewheels 2026.1107.3 → 2026.1107.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,539 @@
1
+ /**
2
+ * ScenarioPlanningPanel
3
+ *
4
+ * Supply-chain planning v2 (BOFF-10761): what-if scenarios on the lane
5
+ * forecast (demand change, lane closures, fleet capacity change) compared
6
+ * side by side with the baseline, each against fleet capacity, with lanes
7
+ * flagged where demand outruns capacity.
8
+ *
9
+ * Read-only: comparisons are computed by `demandScenarioComparison` on
10
+ * request and never stored, so editing a scenario has no side effects.
11
+ */
12
+
13
+ import { useMemo, useState } from 'react';
14
+ import { AlertTriangle, GitCompare, Plus, Trash2, Truck } from 'lucide-react';
15
+
16
+ import {
17
+ Badge,
18
+ Button,
19
+ Card,
20
+ CardContent,
21
+ CardDescription,
22
+ CardHeader,
23
+ CardTitle,
24
+ Checkbox,
25
+ Input,
26
+ Label,
27
+ Skeleton,
28
+ Table,
29
+ TableBody,
30
+ TableCell,
31
+ TableHead,
32
+ TableHeader,
33
+ TableRow,
34
+ Tabs,
35
+ TabsContent,
36
+ TabsList,
37
+ TabsTrigger,
38
+ } from './ui';
39
+ import { FormError } from './FormError';
40
+ import { formatCurrency } from '../utils/formatters';
41
+ import {
42
+ DEFAULT_REQUEST,
43
+ useScenarioPlanning,
44
+ type CapacityBasis,
45
+ type ScenarioComparisonRequest,
46
+ type ScenarioDraft,
47
+ type ScenarioLaneResult,
48
+ type ScenarioResult,
49
+ } from '../hooks/useScenarioPlanning';
50
+
51
+ const MAX_SCENARIOS = 4;
52
+ const MIN_PCT = -100;
53
+ const MAX_PCT = 500;
54
+ const MAX_NAME = 80;
55
+ /** The stored lane forecast covers four weeks; longer requests add nothing. */
56
+ const FORECAST_HORIZON_WEEKS = 4;
57
+
58
+ const formatNumber = (value: number, digits = 1): string =>
59
+ Number.isInteger(value) ? String(value) : value.toFixed(digits);
60
+
61
+ const formatSigned = (value: number): string => (value > 0 ? `+${value}` : String(value));
62
+
63
+ const formatPct = (value: number | null): string =>
64
+ value === null ? '—' : `${Math.round(value * 100)}%`;
65
+
66
+ const parseNumber = (raw: string): number => (raw.trim() === '' ? 0 : Number(raw));
67
+
68
+ /**
69
+ * A scenario being edited, with a client-side key that survives removals.
70
+ * Percentages are kept as typed so a half-typed value ("-" or "") is not
71
+ * coerced to 0 under the user's cursor; they are parsed on Compare.
72
+ */
73
+ type EditableScenario = Omit<ScenarioDraft, 'demandChangePct' | 'capacityChangePct'> & {
74
+ uid: number;
75
+ demandText: string;
76
+ capacityText: string;
77
+ };
78
+
79
+ let nextUid = 0;
80
+ const toEditable = ({ demandChangePct, capacityChangePct, ...rest }: ScenarioDraft) => {
81
+ nextUid += 1;
82
+ const editable: EditableScenario = {
83
+ ...rest,
84
+ uid: nextUid,
85
+ demandText: String(demandChangePct),
86
+ capacityText: String(capacityChangePct),
87
+ };
88
+ return editable;
89
+ };
90
+
91
+ const toDraft = ({ uid: _uid, demandText, capacityText, ...rest }: EditableScenario) => {
92
+ const draft: ScenarioDraft = {
93
+ ...rest,
94
+ demandChangePct: parseNumber(demandText),
95
+ capacityChangePct: parseNumber(capacityText),
96
+ };
97
+ return draft;
98
+ };
99
+
100
+ /** First problem with the request, or null when it can be sent. */
101
+ export function validateRequest(request: ScenarioComparisonRequest): string | null {
102
+ if (
103
+ request.jobsPerVehiclePerWeek !== null &&
104
+ (!Number.isFinite(request.jobsPerVehiclePerWeek) ||
105
+ request.jobsPerVehiclePerWeek <= 0 ||
106
+ request.jobsPerVehiclePerWeek > 1000)
107
+ ) {
108
+ return 'Jobs per vehicle per week must be greater than 0 and at most 1000.';
109
+ }
110
+ const names = new Set<string>();
111
+ for (const [index, scenario] of request.scenarios.entries()) {
112
+ const name = scenario.name.trim();
113
+ if (name.length === 0 || name.length > MAX_NAME) {
114
+ return `Scenario ${index + 1} needs a name of 1 to ${MAX_NAME} characters.`;
115
+ }
116
+ if (names.has(name.toLowerCase())) {
117
+ return `Scenario names must be unique; "${name}" is used twice.`;
118
+ }
119
+ if (name.toLowerCase() === 'baseline') {
120
+ return '"Baseline" is the unchanged forecast; give the scenario another name.';
121
+ }
122
+ names.add(name.toLowerCase());
123
+ for (const value of [scenario.demandChangePct, scenario.capacityChangePct]) {
124
+ if (!Number.isFinite(value) || value < MIN_PCT || value > MAX_PCT) {
125
+ return `Changes in "${name}" must be percentages between ${MIN_PCT} and ${MAX_PCT}.`;
126
+ }
127
+ }
128
+ }
129
+ return null;
130
+ }
131
+
132
+ function capacitySummary(capacity: CapacityBasis): string {
133
+ if (capacity.weeklyFleetCapacity === null || capacity.jobsPerVehiclePerWeek === null) {
134
+ return `${capacity.activeVehicles} available vehicles. No vehicle-assigned jobs in the last 12 weeks, so capacity is unknown: enter jobs per vehicle per week to compare against it.`;
135
+ }
136
+ const basis =
137
+ capacity.source === 'OVERRIDE'
138
+ ? 'as entered'
139
+ : `observed on ${capacity.observedVehicles} vehicle${capacity.observedVehicles === 1 ? '' : 's'} (busiest week, median)`;
140
+ const shares =
141
+ capacity.laneShareBasis === 'DEMAND_SHARE'
142
+ ? ' Lane capacity follows each lane’s share of forecast demand.'
143
+ : capacity.laneShareBasis === 'VEHICLE_HISTORY'
144
+ ? ' Lane capacity follows where vehicles ran in the last 12 weeks.'
145
+ : '';
146
+ return `${capacity.activeVehicles} available vehicles × ${formatNumber(capacity.jobsPerVehiclePerWeek)} jobs/vehicle/week (${basis}) = ${formatNumber(capacity.weeklyFleetCapacity)} jobs/week.${shares}`;
147
+ }
148
+
149
+ export function ScenarioPlanningPanel() {
150
+ const { comparison, isLoading, error, run } = useScenarioPlanning(DEFAULT_REQUEST);
151
+ const [weeks, setWeeks] = useState(String(DEFAULT_REQUEST.weeks));
152
+ const [throughput, setThroughput] = useState('');
153
+ const [drafts, setDrafts] = useState<EditableScenario[]>(() =>
154
+ DEFAULT_REQUEST.scenarios.map(toEditable)
155
+ );
156
+ const [formError, setFormError] = useState<string | null>(null);
157
+
158
+ const lanes = useMemo(
159
+ () =>
160
+ (comparison?.baseline.lanes ?? [])
161
+ .map((lane) => ({ key: lane.laneKey, label: lane.laneLabel }))
162
+ .sort((a, b) => a.label.localeCompare(b.label)),
163
+ [comparison]
164
+ );
165
+
166
+ const updateDraft = (index: number, patch: Partial<EditableScenario>) => {
167
+ setDrafts((current) => current.map((d, i) => (i === index ? { ...d, ...patch } : d)));
168
+ };
169
+
170
+ const toggleLane = (index: number, laneKey: string, closed: boolean) => {
171
+ setDrafts((current) =>
172
+ current.map((d, i) => {
173
+ if (i !== index) return d;
174
+ const without = d.closedLanes.filter((key) => key !== laneKey);
175
+ return { ...d, closedLanes: closed ? [...without, laneKey] : without };
176
+ })
177
+ );
178
+ };
179
+
180
+ const addScenario = () => {
181
+ setDrafts((current) => {
182
+ const taken = new Set(current.map((d) => d.name.trim().toLowerCase()));
183
+ let n = current.length + 1;
184
+ while (taken.has(`scenario ${n}`)) n += 1;
185
+ return [
186
+ ...current,
187
+ toEditable({
188
+ name: `Scenario ${n}`,
189
+ demandChangePct: 0,
190
+ capacityChangePct: 0,
191
+ closedLanes: [],
192
+ laneAdjustments: [],
193
+ }),
194
+ ];
195
+ });
196
+ };
197
+
198
+ const compare = () => {
199
+ const parsedWeeks = Math.min(
200
+ FORECAST_HORIZON_WEEKS,
201
+ Math.max(1, Math.round(parseNumber(weeks) || FORECAST_HORIZON_WEEKS))
202
+ );
203
+ const request: ScenarioComparisonRequest = {
204
+ weeks: parsedWeeks,
205
+ jobsPerVehiclePerWeek: throughput.trim() === '' ? null : Number(throughput),
206
+ scenarios: drafts.map(toDraft),
207
+ };
208
+ const problem = validateRequest(request);
209
+ setFormError(problem);
210
+ if (problem) return;
211
+ setWeeks(String(parsedWeeks));
212
+ run(request);
213
+ };
214
+
215
+ return (
216
+ <Card data-testid="scenario-planning-panel">
217
+ <CardHeader>
218
+ <CardTitle className="flex items-center gap-2">
219
+ <GitCompare size={18} aria-hidden="true" />
220
+ Scenario planning (S&amp;OP)
221
+ </CardTitle>
222
+ <CardDescription>
223
+ Try what-if changes on the lane forecast — demand up or down, lanes closed, fleet added or
224
+ removed — and compare them side by side against your fleet capacity.
225
+ </CardDescription>
226
+ </CardHeader>
227
+ <CardContent className="space-y-6">
228
+ {comparison && (
229
+ <div className="flex items-start gap-2 rounded-lg border border-border/60 bg-muted/40 p-4 text-sm text-text-secondary">
230
+ <Truck size={16} aria-hidden="true" className="mt-0.5 shrink-0" />
231
+ <p data-testid="scenario-capacity-basis">{capacitySummary(comparison.capacity)}</p>
232
+ </div>
233
+ )}
234
+
235
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
236
+ <div className="space-y-1.5">
237
+ <Label htmlFor="scenario-weeks">Weeks to compare</Label>
238
+ <Input
239
+ id="scenario-weeks"
240
+ type="number"
241
+ min={1}
242
+ max={FORECAST_HORIZON_WEEKS}
243
+ value={weeks}
244
+ onChange={(e) => setWeeks(e.target.value)}
245
+ />
246
+ </div>
247
+ <div className="space-y-1.5">
248
+ <Label htmlFor="scenario-throughput">Jobs per vehicle per week</Label>
249
+ <Input
250
+ id="scenario-throughput"
251
+ type="number"
252
+ min={0}
253
+ step="0.5"
254
+ placeholder="Observed from history"
255
+ value={throughput}
256
+ onChange={(e) => setThroughput(e.target.value)}
257
+ />
258
+ </div>
259
+ </div>
260
+
261
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
262
+ {drafts.map((draft, index) => (
263
+ <ScenarioEditor
264
+ key={draft.uid}
265
+ index={index}
266
+ draft={draft}
267
+ lanes={lanes}
268
+ onChange={(patch) => updateDraft(index, patch)}
269
+ onToggleLane={(laneKey, closed) => toggleLane(index, laneKey, closed)}
270
+ onRemove={() => setDrafts((current) => current.filter((_, i) => i !== index))}
271
+ />
272
+ ))}
273
+ </div>
274
+
275
+ <FormError message={formError} />
276
+
277
+ <div className="flex flex-wrap gap-2">
278
+ <Button
279
+ type="button"
280
+ variant="outline"
281
+ onClick={addScenario}
282
+ disabled={drafts.length >= MAX_SCENARIOS}
283
+ >
284
+ <Plus size={16} aria-hidden="true" className="mr-1" />
285
+ Add scenario
286
+ </Button>
287
+ <Button type="button" onClick={compare} disabled={isLoading}>
288
+ <GitCompare size={16} aria-hidden="true" className="mr-1" />
289
+ {isLoading ? 'Comparing…' : 'Compare scenarios'}
290
+ </Button>
291
+ </div>
292
+
293
+ {error && !isLoading && (
294
+ <FormError message={`Couldn't compare scenarios: ${error.message}`} />
295
+ )}
296
+
297
+ {isLoading && !comparison && (
298
+ <div className="space-y-3">
299
+ <Skeleton className="h-10 w-full" />
300
+ <Skeleton className="h-40 w-full" />
301
+ </div>
302
+ )}
303
+
304
+ {comparison && comparison.baseline.lanes.length === 0 && (
305
+ <p className="rounded-lg border border-border/60 p-4 text-sm text-text-secondary">
306
+ No lane forecast yet. Scenarios apply to the lanes your delivery jobs ran on in the last
307
+ 12 weeks.
308
+ </p>
309
+ )}
310
+
311
+ {comparison && comparison.baseline.lanes.length > 0 && (
312
+ <>
313
+ <ComparisonTable results={[comparison.baseline, ...comparison.scenarios]} />
314
+ <LaneBreakdown results={[comparison.baseline, ...comparison.scenarios]} />
315
+ </>
316
+ )}
317
+ </CardContent>
318
+ </Card>
319
+ );
320
+ }
321
+
322
+ interface ScenarioEditorProps {
323
+ index: number;
324
+ draft: EditableScenario;
325
+ lanes: { key: string; label: string }[];
326
+ onChange: (patch: Partial<EditableScenario>) => void;
327
+ onToggleLane: (laneKey: string, closed: boolean) => void;
328
+ onRemove: () => void;
329
+ }
330
+
331
+ function ScenarioEditor({
332
+ index,
333
+ draft,
334
+ lanes,
335
+ onChange,
336
+ onToggleLane,
337
+ onRemove,
338
+ }: ScenarioEditorProps) {
339
+ const prefix = `scenario-${index}`;
340
+ return (
341
+ <fieldset
342
+ className="space-y-3 rounded-lg border border-border/60 p-4"
343
+ aria-label={`Scenario ${index + 1}`}
344
+ >
345
+ <div className="flex items-end gap-2">
346
+ <div className="flex-1 space-y-1.5">
347
+ <Label htmlFor={`${prefix}-name`}>Scenario name</Label>
348
+ <Input
349
+ id={`${prefix}-name`}
350
+ value={draft.name}
351
+ maxLength={MAX_NAME}
352
+ onChange={(e) => onChange({ name: e.target.value })}
353
+ />
354
+ </div>
355
+ <Button
356
+ type="button"
357
+ variant="ghost"
358
+ size="icon"
359
+ aria-label={`Remove ${draft.name || `scenario ${index + 1}`}`}
360
+ onClick={onRemove}
361
+ >
362
+ <Trash2 size={16} aria-hidden="true" />
363
+ </Button>
364
+ </div>
365
+ <div className="grid grid-cols-2 gap-3">
366
+ <div className="space-y-1.5">
367
+ <Label htmlFor={`${prefix}-demand`}>Demand change %</Label>
368
+ <Input
369
+ id={`${prefix}-demand`}
370
+ type="number"
371
+ min={MIN_PCT}
372
+ max={MAX_PCT}
373
+ value={draft.demandText}
374
+ onChange={(e) => onChange({ demandText: e.target.value })}
375
+ />
376
+ </div>
377
+ <div className="space-y-1.5">
378
+ <Label htmlFor={`${prefix}-capacity`}>Capacity change %</Label>
379
+ <Input
380
+ id={`${prefix}-capacity`}
381
+ type="number"
382
+ min={MIN_PCT}
383
+ max={MAX_PCT}
384
+ value={draft.capacityText}
385
+ onChange={(e) => onChange({ capacityText: e.target.value })}
386
+ />
387
+ </div>
388
+ </div>
389
+ {lanes.length > 0 && (
390
+ <div className="space-y-2">
391
+ <p className="text-sm font-medium">Close lanes</p>
392
+ <div className="max-h-36 space-y-2 overflow-y-auto pr-1">
393
+ {lanes.map((lane) => {
394
+ const id = `${prefix}-close-${lane.key}`;
395
+ return (
396
+ <div key={lane.key} className="flex items-center gap-2">
397
+ <Checkbox
398
+ id={id}
399
+ checked={draft.closedLanes.includes(lane.key)}
400
+ onCheckedChange={(value) => onToggleLane(lane.key, value === true)}
401
+ />
402
+ <Label htmlFor={id} className="truncate text-sm font-normal" title={lane.label}>
403
+ {lane.label}
404
+ </Label>
405
+ </div>
406
+ );
407
+ })}
408
+ </div>
409
+ </div>
410
+ )}
411
+ </fieldset>
412
+ );
413
+ }
414
+
415
+ interface ResultsProps {
416
+ results: ScenarioResult[];
417
+ }
418
+
419
+ function ComparisonTable({ results }: ResultsProps) {
420
+ const rows: { label: string; value: (r: ScenarioResult) => string }[] = [
421
+ { label: 'Forecast jobs', value: (r) => String(r.totalVolume) },
422
+ { label: 'vs baseline', value: (r) => formatSigned(r.volumeDelta) },
423
+ { label: 'Revenue', value: (r) => formatCurrency(r.totalRevenue) },
424
+ { label: 'Jobs lost to closed lanes', value: (r) => String(r.lostVolume) },
425
+ {
426
+ label: 'Fleet capacity (jobs)',
427
+ value: (r) => (r.totalCapacity === null ? 'Unknown' : formatNumber(r.totalCapacity)),
428
+ },
429
+ { label: 'Utilisation', value: (r) => formatPct(r.utilization) },
430
+ { label: 'Shortfall (jobs)', value: (r) => formatNumber(r.totalShortfall) },
431
+ { label: 'Lanes short of capacity', value: (r) => String(r.shortfallLanes) },
432
+ ];
433
+ return (
434
+ <div className="overflow-x-auto" data-testid="scenario-comparison-table">
435
+ <Table>
436
+ <TableHeader>
437
+ <TableRow>
438
+ <TableHead>Metric</TableHead>
439
+ {results.map((r) => (
440
+ <TableHead key={r.name} className="text-right">
441
+ {r.name}
442
+ </TableHead>
443
+ ))}
444
+ </TableRow>
445
+ </TableHeader>
446
+ <TableBody>
447
+ {rows.map((row) => (
448
+ <TableRow key={row.label}>
449
+ <TableCell className="font-medium">{row.label}</TableCell>
450
+ {results.map((r) => (
451
+ <TableCell key={r.name} className="text-right tabular-nums">
452
+ {row.value(r)}
453
+ </TableCell>
454
+ ))}
455
+ </TableRow>
456
+ ))}
457
+ </TableBody>
458
+ </Table>
459
+ {results.some((r) => r.unknownLanes.length > 0) && (
460
+ <p className="mt-2 text-xs text-text-secondary">
461
+ Some lanes in a scenario have no forecast and were ignored.
462
+ </p>
463
+ )}
464
+ </div>
465
+ );
466
+ }
467
+
468
+ function laneStatus(lane: ScenarioLaneResult) {
469
+ if (lane.closed) return <Badge variant="secondary">Closed</Badge>;
470
+ if (lane.flagged)
471
+ return (
472
+ <Badge variant="destructive" className="inline-flex items-center gap-1">
473
+ <AlertTriangle size={12} aria-hidden="true" />
474
+ Short
475
+ </Badge>
476
+ );
477
+ if (lane.capacity === null) return <Badge variant="outline">No fleet share</Badge>;
478
+ return <Badge variant="outline">OK</Badge>;
479
+ }
480
+
481
+ function LaneBreakdown({ results }: ResultsProps) {
482
+ const [selected, setSelected] = useState(results[0]?.name ?? '');
483
+ const active = results.some((r) => r.name === selected) ? selected : (results[0]?.name ?? '');
484
+ return (
485
+ <div className="space-y-3" data-testid="scenario-lane-breakdown">
486
+ <p className="text-sm font-medium">Capacity vs demand by lane</p>
487
+ <Tabs value={active} onValueChange={setSelected}>
488
+ <TabsList className="flex-wrap h-auto">
489
+ {results.map((r) => (
490
+ <TabsTrigger key={r.name} value={r.name}>
491
+ {r.name}
492
+ {r.shortfallLanes > 0 ? ` (${r.shortfallLanes} short)` : ''}
493
+ </TabsTrigger>
494
+ ))}
495
+ </TabsList>
496
+ {results.map((r) => (
497
+ <TabsContent key={r.name} value={r.name}>
498
+ <div className="overflow-x-auto">
499
+ <Table>
500
+ <TableHeader>
501
+ <TableRow>
502
+ <TableHead>Lane</TableHead>
503
+ <TableHead className="text-right">Baseline jobs</TableHead>
504
+ <TableHead className="text-right">Scenario jobs</TableHead>
505
+ <TableHead className="text-right">Capacity</TableHead>
506
+ <TableHead className="text-right">Shortfall</TableHead>
507
+ <TableHead>Status</TableHead>
508
+ </TableRow>
509
+ </TableHeader>
510
+ <TableBody>
511
+ {r.lanes.map((lane) => (
512
+ <TableRow key={lane.laneKey}>
513
+ <TableCell className="max-w-56 truncate font-medium" title={lane.laneLabel}>
514
+ {lane.laneLabel}
515
+ </TableCell>
516
+ <TableCell className="text-right tabular-nums">
517
+ {lane.baselineVolume}
518
+ </TableCell>
519
+ <TableCell className="text-right tabular-nums">
520
+ {lane.scenarioVolume}
521
+ </TableCell>
522
+ <TableCell className="text-right tabular-nums">
523
+ {lane.capacity === null ? '—' : formatNumber(lane.capacity)}
524
+ </TableCell>
525
+ <TableCell className="text-right tabular-nums">
526
+ {formatNumber(lane.shortfall)}
527
+ </TableCell>
528
+ <TableCell>{laneStatus(lane)}</TableCell>
529
+ </TableRow>
530
+ ))}
531
+ </TableBody>
532
+ </Table>
533
+ </div>
534
+ </TabsContent>
535
+ ))}
536
+ </Tabs>
537
+ </div>
538
+ );
539
+ }
@@ -26,6 +26,8 @@ export interface CreateCarrierIntegrationInput {
26
26
  provider: SupportedProvider;
27
27
  name: string;
28
28
  apiSecret: string;
29
+ /** Provider mapping settings (e.g. Samsara's shipment external id key). Never secrets. */
30
+ config?: Record<string, string>;
29
31
  }
30
32
 
31
33
  export interface UpdateCarrierIntegrationInput {