@burdenoff/microfe-movethewheels 2026.1107.5 → 2026.1107.7

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,54 @@
1
+ /**
2
+ * CarrierRecommendationDialog (BOFF-10908)
3
+ *
4
+ * Carrier recommendation cards for one PLANNED shipment, opened from the
5
+ * dispatch planner when the shipment should go with a carrier rather than the
6
+ * own fleet (no free vehicle, or the dispatcher prefers a carrier). Accepting
7
+ * a card assigns that carrier to the shipment; rejecting changes nothing.
8
+ */
9
+
10
+ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from './ui';
11
+ import { ShipmentDecisionPanel } from './ShipmentDecisionPanel';
12
+
13
+ type Translate = (key: string, fallback: string) => string;
14
+
15
+ interface CarrierRecommendationDialogProps {
16
+ shipment: { id: string; number: string | null } | null;
17
+ onOpenChange: (open: boolean) => void;
18
+ onApplied?: () => void;
19
+ t: Translate;
20
+ }
21
+
22
+ export function CarrierRecommendationDialog({
23
+ shipment,
24
+ onOpenChange,
25
+ onApplied,
26
+ t,
27
+ }: CarrierRecommendationDialogProps) {
28
+ return (
29
+ <Dialog open={shipment !== null} onOpenChange={onOpenChange}>
30
+ <DialogContent className="max-h-[90vh] max-w-xl overflow-y-auto">
31
+ <DialogHeader>
32
+ <DialogTitle>
33
+ {t('movethewheels.carrierDecision.title', 'Carrier recommendation')}
34
+ {shipment ? ` · ${shipment.number ?? shipment.id}` : ''}
35
+ </DialogTitle>
36
+ <DialogDescription>
37
+ {t(
38
+ 'movethewheels.carrierDecision.description',
39
+ 'Carriers ranked for this shipment’s lane from your own delivery history: on-time record on the lane and overall, and recorded lane cost. Nothing changes until you accept one.'
40
+ )}
41
+ </DialogDescription>
42
+ </DialogHeader>
43
+ {shipment && (
44
+ <ShipmentDecisionPanel
45
+ shipmentId={shipment.id}
46
+ kind="CARRIER_RECOMMENDATION"
47
+ onApplied={onApplied}
48
+ t={t}
49
+ />
50
+ )}
51
+ </DialogContent>
52
+ </Dialog>
53
+ );
54
+ }
@@ -12,7 +12,7 @@
12
12
  * until the person applies their decisions.
13
13
  */
14
14
 
15
- import { Check, Route as RouteIcon, Sparkles, Truck, User, X } from 'lucide-react';
15
+ import { Building2, Check, Route as RouteIcon, Sparkles, Truck, User, X } from 'lucide-react';
16
16
 
17
17
  import { Badge, Button, Card, CardContent } from './ui';
18
18
  import type { DispatchAssignment } from '../hooks/useDispatchPlan';
@@ -52,7 +52,8 @@ export function reasonLabel(reason: string, t: Translate): string {
52
52
  return entry ? t(entry[0], entry[1]) : reason;
53
53
  }
54
54
 
55
- function confidenceTone(confidence: number): string {
55
+ /** Text colour for a 0..1 confidence; shared by every decision card. */
56
+ export function confidenceTone(confidence: number): string {
56
57
  if (confidence >= 0.75) return 'text-status-success-text';
57
58
  if (confidence >= 0.5) return 'text-status-warning-text';
58
59
  return 'text-status-error-text';
@@ -66,6 +67,8 @@ interface DispatchDecisionCardProps {
66
67
  disabled: boolean;
67
68
  onChoose: (choice: DispatchChoice) => void;
68
69
  onOpenRoute: (routeId: string) => void;
70
+ /** When set, an open card also offers a carrier recommendation for its shipment. */
71
+ onRecommendCarrier?: (shipmentId: string, shipmentNumber: string | null) => void;
69
72
  t: Translate;
70
73
  }
71
74
 
@@ -118,6 +121,7 @@ export function DispatchDecisionCard({
118
121
  disabled,
119
122
  onChoose,
120
123
  onOpenRoute,
124
+ onRecommendCarrier,
121
125
  t,
122
126
  }: DispatchDecisionCardProps) {
123
127
  const percent = Math.round(assignment.confidence * 100);
@@ -233,6 +237,17 @@ export function DispatchDecisionCard({
233
237
  <X size={14} aria-hidden="true" />
234
238
  {t('movethewheels.dispatch.reject', 'Reject')}
235
239
  </Button>
240
+ {onRecommendCarrier && (
241
+ <Button
242
+ size="sm"
243
+ variant="ghost"
244
+ disabled={disabled}
245
+ onClick={() => onRecommendCarrier(assignment.shipmentId, assignment.shipmentNumber)}
246
+ >
247
+ <Building2 size={14} aria-hidden="true" />
248
+ {t('movethewheels.carrierDecision.useCarrier', 'Use a carrier instead')}
249
+ </Button>
250
+ )}
236
251
  </div>
237
252
  ) : (
238
253
  <DecisionOutcome assignment={assignment} onOpenRoute={onOpenRoute} t={t} />
@@ -0,0 +1,459 @@
1
+ /**
2
+ * ShipmentDecisionPanel (BOFF-10908)
3
+ *
4
+ * Decision cards for one shipment's carrier recommendation
5
+ * (`mtwRecommendCarrier`) or exception remediation (`mtwResolveException`).
6
+ * Each ranked option is a card with the ranker's confidence, reason chips, its
7
+ * factual rationale and, when the shared AI runtime wrote one, an AI rationale
8
+ * — the same layout as the dispatch decision cards. Accept decides the
9
+ * proposal with that option; Reject decides it with none and changes nothing.
10
+ *
11
+ * Graceful degradation: with AI switched off, credits spent or the model
12
+ * failing, the options are the same and only the AI text is missing; the
13
+ * manual paths around this panel stay available.
14
+ */
15
+
16
+ import { useState, type ReactNode } from 'react';
17
+ import { Building2, Check, Loader2, RefreshCw, Sparkles, Wand2, X } from 'lucide-react';
18
+
19
+ import { Badge, Button, Card, CardContent, Skeleton } from './ui';
20
+ import { confidenceTone } from './DispatchDecisionCard';
21
+ import { FormError } from './FormError';
22
+ import {
23
+ useShipmentDecision,
24
+ type ShipmentDecision,
25
+ type ShipmentDecisionKind,
26
+ type ShipmentDecisionOption,
27
+ } from '../hooks/useShipmentDecision';
28
+ import type { DecisionRationaleStatus } from '../hooks/useDispatchPlan';
29
+ import { formatCurrency, formatDateTime } from '../utils/formatters';
30
+
31
+ type Translate = (key: string, fallback: string) => string;
32
+
33
+ const ACTION_LABELS: Record<ShipmentDecisionOption['action'], [string, string]> = {
34
+ USE_CARRIER: ['movethewheels.decision.action.useCarrier', 'Use carrier'],
35
+ REASSIGN_VEHICLE: ['movethewheels.decision.action.reassignVehicle', 'Reassign the vehicle'],
36
+ REPROMISE_DELIVERY: ['movethewheels.decision.action.repromise', 'Re-promise the delivery'],
37
+ REQUEST_TRACKING_UPDATE: [
38
+ 'movethewheels.decision.action.trackingUpdate',
39
+ 'Get a tracking update',
40
+ ],
41
+ SWITCH_CARRIER: ['movethewheels.decision.action.switchCarrier', 'Switch carrier'],
42
+ ACCEPT_SLIP: ['movethewheels.decision.action.acceptSlip', 'Accept the delay'],
43
+ };
44
+
45
+ const REASON_LABELS: Record<string, [string, string]> = {
46
+ LANE_HISTORY: ['movethewheels.decision.reason.laneHistory', 'Lane history'],
47
+ LANE_HISTORY_THIN: ['movethewheels.decision.reason.laneThin', 'Little lane history'],
48
+ NO_LANE_HISTORY: ['movethewheels.decision.reason.noLane', 'No lane history'],
49
+ ON_TIME_STRONG: ['movethewheels.decision.reason.onTimeStrong', 'Strong on-time record'],
50
+ LATE_HISTORY: ['movethewheels.decision.reason.lateHistory', 'Often late'],
51
+ LOWEST_LANE_COST: ['movethewheels.decision.reason.lowestCost', 'Lowest lane cost'],
52
+ CURRENT_CARRIER: ['movethewheels.decision.reason.current', 'Current carrier'],
53
+ PREDICTED_SLIP: ['movethewheels.decision.reason.predictedSlip', 'Predicted late'],
54
+ PROMISE_MISSED: ['movethewheels.decision.reason.promiseMissed', 'Promise missed'],
55
+ VEHICLE_UNAVAILABLE: ['movethewheels.decision.reason.vehicleUnavailable', 'Vehicle unavailable'],
56
+ TRACKING_STALE: ['movethewheels.decision.reason.trackingStale', 'Tracking stale'],
57
+ BETTER_LANE_RECORD: ['movethewheels.decision.reason.betterRecord', 'Better lane record'],
58
+ CURRENT_CARRIER_LATE: ['movethewheels.decision.reason.currentLate', 'Current carrier often late'],
59
+ };
60
+
61
+ const CAUTION_REASONS = new Set([
62
+ 'LANE_HISTORY_THIN',
63
+ 'NO_LANE_HISTORY',
64
+ 'LATE_HISTORY',
65
+ 'PROMISE_MISSED',
66
+ 'CURRENT_CARRIER_LATE',
67
+ ]);
68
+
69
+ const EXECUTION_NOTES: Record<ShipmentDecisionOption['execution'], [string, string]> = {
70
+ APPLY: ['movethewheels.decision.execution.apply', 'Accepting changes the shipment.'],
71
+ FOLLOW_UP: [
72
+ 'movethewheels.decision.execution.followUp',
73
+ 'Accepting records the decision; you then carry out the step.',
74
+ ],
75
+ RECORD: [
76
+ 'movethewheels.decision.execution.record',
77
+ 'Accepting only records the decision; nothing on the shipment changes.',
78
+ ],
79
+ };
80
+
81
+ const STATUS_LABELS: Record<ShipmentDecision['status'], [string, string]> = {
82
+ PROPOSED: ['movethewheels.decision.status.proposed', 'Waiting for your decision'],
83
+ ACCEPTED: ['movethewheels.decision.status.accepted', 'Accepted'],
84
+ REJECTED: ['movethewheels.decision.status.rejected', 'Rejected — nothing changed'],
85
+ STALE: ['movethewheels.decision.status.stale', 'Not applied — the shipment changed'],
86
+ EXPIRED: ['movethewheels.decision.status.expired', 'Expired'],
87
+ };
88
+
89
+ const OUTCOME_LABELS: Record<NonNullable<ShipmentDecision['outcome']>, [string, string]> = {
90
+ APPLIED: ['movethewheels.decision.outcome.applied', 'Applied to the shipment'],
91
+ RECORDED: ['movethewheels.decision.outcome.recorded', 'Recorded'],
92
+ FOLLOW_UP: ['movethewheels.decision.outcome.followUp', 'Recorded — follow-up to do'],
93
+ };
94
+
95
+ const AI_STATUS_MESSAGES: Record<
96
+ Exclude<DecisionRationaleStatus, 'AVAILABLE'>,
97
+ [string, string]
98
+ > = {
99
+ NOT_NEEDED: [
100
+ 'movethewheels.decision.ai.notNeeded',
101
+ 'There was nothing to rank, so there was nothing for AI to explain.',
102
+ ],
103
+ AI_DISABLED: [
104
+ 'movethewheels.decision.ai.disabled',
105
+ 'AI explanations are switched off. The rule-based rationale below is complete.',
106
+ ],
107
+ CREDITS_EXHAUSTED: [
108
+ 'movethewheels.decision.ai.creditsExhausted',
109
+ 'This workspace has used its MoveTheWheels AI credits, so no AI explanation was written. The options are unaffected.',
110
+ ],
111
+ DAILY_CAP_REACHED: [
112
+ 'movethewheels.decision.ai.dailyCap',
113
+ "Today's AI explanation limit is reached. The options are unaffected.",
114
+ ],
115
+ UNAVAILABLE: [
116
+ 'movethewheels.decision.ai.unavailable',
117
+ 'The AI explanation could not be produced this time. The options are unaffected.',
118
+ ],
119
+ };
120
+
121
+ const KIND_COPY: Record<
122
+ ShipmentDecisionKind,
123
+ { propose: [string, string]; again: [string, string]; empty: [string, string] }
124
+ > = {
125
+ CARRIER_RECOMMENDATION: {
126
+ propose: ['movethewheels.carrierDecision.propose', 'Recommend a carrier'],
127
+ again: ['movethewheels.carrierDecision.again', 'Recommend again'],
128
+ empty: [
129
+ 'movethewheels.carrierDecision.empty',
130
+ 'No carrier has delivered for this workspace in the last 180 days, so there is nothing to rank yet. Set the carrier on the shipment by hand.',
131
+ ],
132
+ },
133
+ EXCEPTION_REMEDIATION: {
134
+ propose: ['movethewheels.exceptionDecision.propose', 'Propose remediations'],
135
+ again: ['movethewheels.exceptionDecision.again', 'Propose again'],
136
+ empty: ['movethewheels.exceptionDecision.empty', 'No remediation could be proposed.'],
137
+ },
138
+ };
139
+
140
+ function reasonLabel(reason: string, t: Translate): string {
141
+ const entry = REASON_LABELS[reason];
142
+ return entry ? t(entry[0], entry[1]) : reason;
143
+ }
144
+
145
+ function optionTitle(option: ShipmentDecisionOption, t: Translate): string {
146
+ const [key, fallback] = ACTION_LABELS[option.action];
147
+ const label = t(key, fallback);
148
+ if (option.carrierId) return `${label} · ${option.carrierId}`;
149
+ if (option.newEstimatedDelivery)
150
+ return `${label} · ${formatDateTime(option.newEstimatedDelivery)}`;
151
+ return label;
152
+ }
153
+
154
+ function CarrierStats({ option, t }: { option: ShipmentDecisionOption; t: Translate }) {
155
+ if (option.deliveredCount === null) return null;
156
+ return (
157
+ <dl className="grid grid-cols-2 gap-2 text-xs sm:grid-cols-3">
158
+ <div>
159
+ <dt className="text-text-secondary">
160
+ {t('movethewheels.carrierDecision.lane', 'On this lane')}
161
+ </dt>
162
+ <dd className="font-medium tabular-nums">
163
+ {option.laneOnTimeCount ?? 0}/{option.laneDeliveredCount ?? 0}{' '}
164
+ {t('movethewheels.carrierDecision.onTime', 'on time')}
165
+ </dd>
166
+ </div>
167
+ <div>
168
+ <dt className="text-text-secondary">
169
+ {t('movethewheels.carrierDecision.overall', 'All lanes')}
170
+ </dt>
171
+ <dd className="font-medium tabular-nums">
172
+ {option.onTimeCount ?? 0}/{option.deliveredCount}{' '}
173
+ {t('movethewheels.carrierDecision.onTime', 'on time')}
174
+ </dd>
175
+ </div>
176
+ {option.medianLaneCost !== null && (
177
+ <div>
178
+ <dt className="text-text-secondary">
179
+ {t('movethewheels.carrierDecision.cost', 'Median lane cost')}
180
+ </dt>
181
+ <dd className="font-medium tabular-nums">
182
+ {option.currency
183
+ ? formatCurrency(option.medianLaneCost, option.currency)
184
+ : option.medianLaneCost}
185
+ </dd>
186
+ </div>
187
+ )}
188
+ </dl>
189
+ );
190
+ }
191
+
192
+ interface OptionCardProps {
193
+ option: ShipmentDecisionOption;
194
+ decision: ShipmentDecision;
195
+ disabled: boolean;
196
+ accepting: boolean;
197
+ onAccept: () => void;
198
+ followUp?: ReactNode;
199
+ t: Translate;
200
+ }
201
+
202
+ function OptionCard({
203
+ option,
204
+ decision,
205
+ disabled,
206
+ accepting,
207
+ onAccept,
208
+ followUp,
209
+ t,
210
+ }: OptionCardProps) {
211
+ const open = decision.status === 'PROPOSED';
212
+ const chosen = decision.chosenOptionId === option.id;
213
+ const percent = Math.round(option.confidence * 100);
214
+ const [noteKey, noteFallback] = EXECUTION_NOTES[option.execution];
215
+ return (
216
+ <Card
217
+ className={chosen ? 'border-status-success-border' : 'border-border-default'}
218
+ data-option-id={option.id}
219
+ data-testid="shipment-decision-card"
220
+ >
221
+ <CardContent className="space-y-3 p-4">
222
+ <div className="flex flex-wrap items-start justify-between gap-3">
223
+ <div className="min-w-0 space-y-1">
224
+ <p className="text-xs text-text-secondary">
225
+ {t('movethewheels.decision.rank', 'Option')} {option.rank}
226
+ </p>
227
+ <p className="flex items-center gap-2 text-sm font-semibold break-words text-text-primary">
228
+ {option.carrierId && (
229
+ <Building2 size={14} className="shrink-0 text-text-secondary" aria-hidden="true" />
230
+ )}
231
+ {optionTitle(option, t)}
232
+ </p>
233
+ </div>
234
+ <div className="text-right">
235
+ <p className={`text-lg font-bold tabular-nums ${confidenceTone(option.confidence)}`}>
236
+ {percent}%
237
+ </p>
238
+ <p className="text-xs text-text-secondary">
239
+ {t('movethewheels.decision.confidence', 'Confidence')}
240
+ </p>
241
+ </div>
242
+ </div>
243
+
244
+ <ul
245
+ className="flex flex-wrap gap-1.5"
246
+ aria-label={t('movethewheels.dispatch.reasons', 'Reasons')}
247
+ >
248
+ {option.reasons.map((reason) => (
249
+ <li key={reason}>
250
+ <Badge variant={CAUTION_REASONS.has(reason) ? 'outline' : 'secondary'}>
251
+ {reasonLabel(reason, t)}
252
+ </Badge>
253
+ </li>
254
+ ))}
255
+ </ul>
256
+
257
+ <CarrierStats option={option} t={t} />
258
+
259
+ <p className="text-sm text-text-secondary">{option.rationale}</p>
260
+ {option.aiRationale && (
261
+ <p className="flex items-start gap-2 rounded-md bg-surface-secondary p-2 text-sm text-text-primary">
262
+ <Sparkles size={14} className="mt-0.5 shrink-0" aria-hidden="true" />
263
+ <span>
264
+ <span className="sr-only">
265
+ {t('movethewheels.dispatch.aiWritten', 'AI-written')}:{' '}
266
+ </span>
267
+ {option.aiRationale}
268
+ </span>
269
+ </p>
270
+ )}
271
+ <p className="text-xs text-text-secondary">{t(noteKey, noteFallback)}</p>
272
+
273
+ {open ? (
274
+ <Button size="sm" disabled={disabled} onClick={onAccept}>
275
+ {accepting ? (
276
+ <Loader2 size={14} className="animate-spin" aria-hidden="true" />
277
+ ) : (
278
+ <Check size={14} aria-hidden="true" />
279
+ )}
280
+ {t('movethewheels.dispatch.accept', 'Accept')}
281
+ </Button>
282
+ ) : (
283
+ chosen && (
284
+ <div className="space-y-2">
285
+ {decision.status === 'ACCEPTED' && decision.outcome ? (
286
+ <Badge variant="default">
287
+ {t(OUTCOME_LABELS[decision.outcome][0], OUTCOME_LABELS[decision.outcome][1])}
288
+ </Badge>
289
+ ) : (
290
+ <Badge variant="outline">
291
+ {t(STATUS_LABELS[decision.status][0], STATUS_LABELS[decision.status][1])}
292
+ </Badge>
293
+ )}
294
+ {decision.status === 'STALE' && decision.decisionReason && (
295
+ <p className="text-xs text-status-warning-text">{decision.decisionReason}</p>
296
+ )}
297
+ {decision.outcome === 'FOLLOW_UP' && followUp}
298
+ </div>
299
+ )
300
+ )}
301
+ </CardContent>
302
+ </Card>
303
+ );
304
+ }
305
+
306
+ interface ShipmentDecisionPanelProps {
307
+ shipmentId: string | undefined;
308
+ kind: ShipmentDecisionKind;
309
+ t: Translate;
310
+ /** Called after an accepted option changed the shipment. */
311
+ onApplied?: (decision: ShipmentDecision) => void;
312
+ /** The manual step for an accepted FOLLOW_UP option, rendered under its card. */
313
+ renderFollowUp?: (option: ShipmentDecisionOption) => ReactNode;
314
+ }
315
+
316
+ export function ShipmentDecisionPanel({
317
+ shipmentId,
318
+ kind,
319
+ t,
320
+ onApplied,
321
+ renderFollowUp,
322
+ }: ShipmentDecisionPanelProps) {
323
+ const { decision, isLoading, error, pendingAction, refetch, propose, accept, reject } =
324
+ useShipmentDecision(shipmentId, kind);
325
+ const [actionError, setActionError] = useState<string | null>(null);
326
+ const [acceptingId, setAcceptingId] = useState<string | null>(null);
327
+ const busy = pendingAction !== null;
328
+ const copy = KIND_COPY[kind];
329
+
330
+ const runAction = async (action: () => Promise<ShipmentDecision>) => {
331
+ setActionError(null);
332
+ try {
333
+ const next = await action();
334
+ if (next.status === 'ACCEPTED' && next.outcome === 'APPLIED') onApplied?.(next);
335
+ } catch (e) {
336
+ setActionError(e instanceof Error ? e.message : 'The request failed.');
337
+ } finally {
338
+ setAcceptingId(null);
339
+ }
340
+ };
341
+
342
+ const open = decision?.status === 'PROPOSED';
343
+ const aiMessage =
344
+ AI_STATUS_MESSAGES[
345
+ !decision || decision.aiStatus === 'AVAILABLE' ? 'UNAVAILABLE' : decision.aiStatus
346
+ ];
347
+
348
+ return (
349
+ <section className="space-y-3" data-testid={`shipment-decision-${kind}`}>
350
+ <div className="flex flex-wrap items-center gap-2">
351
+ {!open && (
352
+ <Button size="sm" disabled={busy || !shipmentId} onClick={() => runAction(propose)}>
353
+ {pendingAction === 'propose' ? (
354
+ <Loader2 size={14} className="animate-spin" aria-hidden="true" />
355
+ ) : (
356
+ <Wand2 size={14} aria-hidden="true" />
357
+ )}
358
+ {decision ? t(copy.again[0], copy.again[1]) : t(copy.propose[0], copy.propose[1])}
359
+ </Button>
360
+ )}
361
+ {decision && (
362
+ <Badge variant={open ? 'default' : 'secondary'}>
363
+ {t(STATUS_LABELS[decision.status][0], STATUS_LABELS[decision.status][1])}
364
+ </Badge>
365
+ )}
366
+ {decision && (
367
+ <span className="text-xs text-text-secondary">
368
+ {t('movethewheels.decision.method', 'Rule-based ranking')} ({decision.method}) ·{' '}
369
+ {formatDateTime(decision.createdAt)}
370
+ </span>
371
+ )}
372
+ </div>
373
+
374
+ <FormError message={actionError} />
375
+
376
+ {isLoading && !decision && <Skeleton className="h-24 w-full" />}
377
+ {error && !isLoading && (
378
+ <div role="alert" className="space-y-2 text-sm">
379
+ <p className="text-status-error-text">{error.message}</p>
380
+ <Button size="sm" variant="outline" onClick={refetch}>
381
+ <RefreshCw size={14} aria-hidden="true" />
382
+ {t('movethewheels.risk.retry', 'Retry')}
383
+ </Button>
384
+ </div>
385
+ )}
386
+
387
+ {decision && (
388
+ <>
389
+ {decision.aiStatus === 'AVAILABLE' && decision.aiSummary ? (
390
+ <div className="space-y-1 rounded-md bg-surface-secondary p-3 text-sm">
391
+ <p className="flex items-start gap-2 text-text-primary">
392
+ <Sparkles size={14} className="mt-0.5 shrink-0" aria-hidden="true" />
393
+ <span>{decision.aiSummary}</span>
394
+ </p>
395
+ <p className="text-xs text-text-secondary">
396
+ {t(
397
+ 'movethewheels.decision.ai.disclaimer',
398
+ 'Written by AI from the ranker’s facts. It never changes the ranking; check before accepting.'
399
+ )}
400
+ {decision.aiModel ? ` (${decision.aiModel})` : ''}
401
+ </p>
402
+ </div>
403
+ ) : (
404
+ <p
405
+ role="status"
406
+ className="rounded-md border border-status-info-border bg-status-info-bg-subtle px-3 py-2 text-xs text-status-info-text"
407
+ >
408
+ {t(aiMessage[0], aiMessage[1])}
409
+ </p>
410
+ )}
411
+
412
+ {decision.options.length === 0 ? (
413
+ <p className="text-sm text-text-secondary">{t(copy.empty[0], copy.empty[1])}</p>
414
+ ) : (
415
+ <div className="space-y-3">
416
+ {decision.options.map((option) => (
417
+ <OptionCard
418
+ key={option.id}
419
+ option={option}
420
+ decision={decision}
421
+ disabled={busy}
422
+ accepting={pendingAction === 'accept' && acceptingId === option.id}
423
+ onAccept={() => {
424
+ setAcceptingId(option.id);
425
+ void runAction(() => accept(decision.id, option.id));
426
+ }}
427
+ followUp={renderFollowUp?.(option)}
428
+ t={t}
429
+ />
430
+ ))}
431
+ </div>
432
+ )}
433
+
434
+ {open && (
435
+ <div className="flex flex-wrap items-center justify-between gap-2">
436
+ <span className="text-xs text-text-secondary">
437
+ {t('movethewheels.dispatch.expires', 'Valid until')}{' '}
438
+ {formatDateTime(decision.expiresAt)}
439
+ </span>
440
+ <Button
441
+ size="sm"
442
+ variant="outline"
443
+ disabled={busy}
444
+ onClick={() => runAction(() => reject(decision.id))}
445
+ >
446
+ {pendingAction === 'reject' ? (
447
+ <Loader2 size={14} className="animate-spin" aria-hidden="true" />
448
+ ) : (
449
+ <X size={14} aria-hidden="true" />
450
+ )}
451
+ {t('movethewheels.decision.rejectAll', 'Reject all')}
452
+ </Button>
453
+ </div>
454
+ )}
455
+ </>
456
+ )}
457
+ </section>
458
+ );
459
+ }
@@ -26,6 +26,7 @@ import {
26
26
  type RiskRecommendedAction,
27
27
  } from '../hooks/useShipmentRisk';
28
28
  import { formatDateTime } from '../utils/formatters';
29
+ import { ShipmentDecisionPanel } from './ShipmentDecisionPanel';
29
30
  import { formatSlip, riskSignalLabel } from '../utils/trackingAlerts';
30
31
 
31
32
  type Translate = (key: string, fallback: string) => string;
@@ -90,11 +91,14 @@ export function ShipmentRiskDialog({
90
91
  const [actionDone, setActionDone] = useState<string | null>(null);
91
92
  const [busy, setBusy] = useState(false);
92
93
  const [details, setDetails] = useState('');
94
+ // The remediation follow-up has its own text, separate from the manual action above.
95
+ const [followUpDetails, setFollowUpDetails] = useState('');
93
96
 
94
97
  useEffect(() => {
95
98
  setActionError(null);
96
99
  setActionDone(null);
97
100
  setDetails('');
101
+ setFollowUpDetails('');
98
102
  }, [shipmentId, open]);
99
103
 
100
104
  const run = async (work: () => Promise<void>, done: string) => {
@@ -121,7 +125,7 @@ export function ShipmentRiskDialog({
121
125
 
122
126
  return (
123
127
  <Dialog open={open} onOpenChange={onOpenChange}>
124
- <DialogContent className="max-w-lg">
128
+ <DialogContent className="max-h-[90vh] max-w-lg overflow-y-auto">
125
129
  <DialogHeader>
126
130
  <DialogTitle>
127
131
  {t('movethewheels.risk.title', 'Delivery risk')}
@@ -307,6 +311,68 @@ export function ShipmentRiskDialog({
307
311
  {t('movethewheels.risk.evaluated', 'Evaluated')}{' '}
308
312
  {formatDateTime(forecast.evaluatedAt)}
309
313
  </p>
314
+
315
+ {(forecast.atRisk || forecast.breached) && (
316
+ <div className="space-y-2 border-t border-border-primary pt-4">
317
+ <p className="text-sm font-semibold text-text-primary">
318
+ {t('movethewheels.exceptionDecision.title', 'Remediation options')}
319
+ </p>
320
+ <p className="text-xs text-text-secondary">
321
+ {t(
322
+ 'movethewheels.exceptionDecision.description',
323
+ 'Ranked ways to handle this exception, from the forecast above. Nothing changes until you accept one; the manual action above stays available.'
324
+ )}
325
+ </p>
326
+ <ShipmentDecisionPanel
327
+ shipmentId={shipmentId}
328
+ kind="EXCEPTION_REMEDIATION"
329
+ onApplied={() => {
330
+ refetch();
331
+ onChanged();
332
+ }}
333
+ renderFollowUp={(option) => {
334
+ const jobId = option.followUpArgs?.['id'] ?? reassignJobId;
335
+ if (option.action === 'REASSIGN_VEHICLE' && jobId) {
336
+ return (
337
+ <Button size="sm" variant="outline" onClick={() => onOpenOrder(jobId)}>
338
+ {t('movethewheels.risk.openOrder', 'Open order to reassign')}
339
+ </Button>
340
+ );
341
+ }
342
+ if (option.action === 'REQUEST_TRACKING_UPDATE') {
343
+ return (
344
+ <div className="space-y-2">
345
+ <Textarea
346
+ value={followUpDetails}
347
+ onChange={(event) => setFollowUpDetails(event.target.value)}
348
+ maxLength={500}
349
+ aria-label={t('movethewheels.risk.updateDetails', 'Tracking update')}
350
+ placeholder={t(
351
+ 'movethewheels.risk.updatePlaceholder',
352
+ 'What did the driver or carrier report?'
353
+ )}
354
+ />
355
+ <Button
356
+ size="sm"
357
+ disabled={busy || followUpDetails.trim().length === 0}
358
+ onClick={() =>
359
+ void run(
360
+ () => recordTrackingUpdate(followUpDetails.trim()),
361
+ t('movethewheels.risk.updateRecorded', 'Tracking update recorded')
362
+ )
363
+ }
364
+ >
365
+ {t('movethewheels.risk.recordUpdate', 'Record tracking update')}
366
+ </Button>
367
+ </div>
368
+ );
369
+ }
370
+ return null;
371
+ }}
372
+ t={t}
373
+ />
374
+ </div>
375
+ )}
310
376
  </div>
311
377
  )}
312
378
  </DialogContent>