@burdenoff/microfe-movethewheels 2026.1107.6 → 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,318 @@
1
+ /**
2
+ * Shipment decision proposals (BOFF-10908).
3
+ *
4
+ * Reads a shipment's latest decision of one kind and drives its three steps:
5
+ *
6
+ * - `propose` calls `mtwRecommendCarrier` (carrier recommendation) or
7
+ * `mtwResolveException` (exception remediation). Both only store a proposal.
8
+ * - `accept(optionId)` calls `mtwAcceptShipmentDecision`. An APPLY option
9
+ * changes the shipment (carrier or promised delivery); FOLLOW_UP and RECORD
10
+ * options only record the decision.
11
+ * - `reject` calls `mtwRejectShipmentDecision`, which changes nothing.
12
+ *
13
+ * The server decides everything (ranking, staleness, expiry, AI credit gating).
14
+ * This hook only reflects the record the server returns after each call.
15
+ */
16
+
17
+ import { useCallback, useEffect, useMemo, useState } from 'react';
18
+ import { useMoveTheWheels } from '../providers/MoveTheWheelsProvider';
19
+ import { executeGraphQL } from '../utils/graphqlClient';
20
+ import type { DecisionRationaleStatus } from './useDispatchPlan';
21
+
22
+ export type ShipmentDecisionKind = 'CARRIER_RECOMMENDATION' | 'EXCEPTION_REMEDIATION';
23
+ export type ShipmentDecisionStatus = 'PROPOSED' | 'ACCEPTED' | 'REJECTED' | 'STALE' | 'EXPIRED';
24
+ export type ShipmentDecisionAction =
25
+ | 'USE_CARRIER'
26
+ | 'REASSIGN_VEHICLE'
27
+ | 'REPROMISE_DELIVERY'
28
+ | 'REQUEST_TRACKING_UPDATE'
29
+ | 'SWITCH_CARRIER'
30
+ | 'ACCEPT_SLIP';
31
+ export type ShipmentDecisionExecution = 'APPLY' | 'FOLLOW_UP' | 'RECORD';
32
+ export type ShipmentDecisionOutcome = 'APPLIED' | 'RECORDED' | 'FOLLOW_UP';
33
+
34
+ export interface ShipmentDecisionOption {
35
+ id: string;
36
+ rank: number;
37
+ action: ShipmentDecisionAction;
38
+ execution: ShipmentDecisionExecution;
39
+ confidence: number;
40
+ score: number | null;
41
+ reasons: string[];
42
+ rationale: string;
43
+ aiRationale: string | null;
44
+ carrierId: string | null;
45
+ newEstimatedDelivery: string | null;
46
+ followUpMutation: string | null;
47
+ followUpArgs: Record<string, string> | null;
48
+ deliveredCount: number | null;
49
+ onTimeCount: number | null;
50
+ laneDeliveredCount: number | null;
51
+ laneOnTimeCount: number | null;
52
+ medianLaneCost: number | null;
53
+ currency: string | null;
54
+ }
55
+
56
+ export interface ShipmentDecision {
57
+ id: string;
58
+ kind: ShipmentDecisionKind;
59
+ shipmentId: string;
60
+ shipmentNumber: string | null;
61
+ status: ShipmentDecisionStatus;
62
+ method: string;
63
+ options: ShipmentDecisionOption[];
64
+ chosenOptionId: string | null;
65
+ outcome: ShipmentDecisionOutcome | null;
66
+ decisionReason: string | null;
67
+ currentCarrierId: string | null;
68
+ promisedDelivery: string | null;
69
+ riskScore: number | null;
70
+ predictedSlipMinutes: number | null;
71
+ breached: boolean | null;
72
+ laneKnown: boolean | null;
73
+ historyCount: number | null;
74
+ aiStatus: DecisionRationaleStatus;
75
+ aiSummary: string | null;
76
+ aiModel: string | null;
77
+ expiresAt: string;
78
+ decidedAt: string | null;
79
+ createdAt: string;
80
+ }
81
+
82
+ const DECISION_FIELDS = `
83
+ id
84
+ kind
85
+ shipmentId
86
+ shipmentNumber
87
+ status
88
+ method
89
+ options {
90
+ id
91
+ rank
92
+ action
93
+ execution
94
+ confidence
95
+ score
96
+ reasons
97
+ rationale
98
+ aiRationale
99
+ carrierId
100
+ newEstimatedDelivery
101
+ followUpMutation
102
+ followUpArgs
103
+ deliveredCount
104
+ onTimeCount
105
+ laneDeliveredCount
106
+ laneOnTimeCount
107
+ medianLaneCost
108
+ currency
109
+ }
110
+ chosenOptionId
111
+ outcome
112
+ decisionReason
113
+ currentCarrierId
114
+ promisedDelivery
115
+ riskScore
116
+ predictedSlipMinutes
117
+ breached
118
+ laneKnown
119
+ historyCount
120
+ aiStatus
121
+ aiSummary
122
+ aiModel
123
+ expiresAt
124
+ decidedAt
125
+ createdAt
126
+ `;
127
+
128
+ const LATEST_QUERY = `
129
+ query LatestShipmentDecision($shipmentId: ID!, $kind: MtwShipmentDecisionKind!) {
130
+ mtwLatestShipmentDecision(shipmentId: $shipmentId, kind: $kind) {
131
+ ${DECISION_FIELDS}
132
+ }
133
+ }
134
+ `;
135
+
136
+ const RECOMMEND_CARRIER_MUTATION = `
137
+ mutation RecommendCarrier($shipmentId: ID!) {
138
+ mtwRecommendCarrier(shipmentId: $shipmentId) {
139
+ ${DECISION_FIELDS}
140
+ }
141
+ }
142
+ `;
143
+
144
+ const RESOLVE_EXCEPTION_MUTATION = `
145
+ mutation ResolveException($shipmentId: ID!) {
146
+ mtwResolveException(shipmentId: $shipmentId) {
147
+ ${DECISION_FIELDS}
148
+ }
149
+ }
150
+ `;
151
+
152
+ const ACCEPT_MUTATION = `
153
+ mutation AcceptShipmentDecision($decisionId: ID!, $optionId: ID!) {
154
+ mtwAcceptShipmentDecision(decisionId: $decisionId, optionId: $optionId) {
155
+ ${DECISION_FIELDS}
156
+ }
157
+ }
158
+ `;
159
+
160
+ const REJECT_MUTATION = `
161
+ mutation RejectShipmentDecision($decisionId: ID!) {
162
+ mtwRejectShipmentDecision(decisionId: $decisionId) {
163
+ ${DECISION_FIELDS}
164
+ }
165
+ }
166
+ `;
167
+
168
+ type PendingAction = 'propose' | 'accept' | 'reject';
169
+
170
+ /**
171
+ * @param shipmentId the shipment, or undefined while nothing is selected (no request is made)
172
+ */
173
+ export function useShipmentDecision(shipmentId: string | undefined, kind: ShipmentDecisionKind) {
174
+ const { apiGatewayUrl, authToken, workspaceToken, workspaceId, tenantId, currentUser } =
175
+ useMoveTheWheels();
176
+ const graphQLOptions = useMemo(
177
+ () => ({
178
+ apiGatewayUrl,
179
+ authToken,
180
+ workspaceToken,
181
+ workspaceId,
182
+ tenantId,
183
+ actorId: currentUser?.id,
184
+ }),
185
+ [apiGatewayUrl, authToken, workspaceToken, workspaceId, tenantId, currentUser?.id]
186
+ );
187
+ const [decision, setDecision] = useState<ShipmentDecision | null>(null);
188
+ const [isLoading, setIsLoading] = useState(false);
189
+ const [error, setError] = useState<Error | null>(null);
190
+ const [pendingAction, setPendingAction] = useState<PendingAction | null>(null);
191
+
192
+ const load = useCallback(
193
+ async (signal?: AbortSignal) => {
194
+ if (!shipmentId) return;
195
+ setIsLoading(true);
196
+ setError(null);
197
+ try {
198
+ const data = await executeGraphQL<{ mtwLatestShipmentDecision: ShipmentDecision | null }>(
199
+ { ...graphQLOptions, signal },
200
+ LATEST_QUERY,
201
+ { shipmentId, kind }
202
+ );
203
+ if (signal?.aborted) return;
204
+ setDecision(data.mtwLatestShipmentDecision);
205
+ } catch (fetchError) {
206
+ if (signal?.aborted) return;
207
+ setError(
208
+ fetchError instanceof Error ? fetchError : new Error('Failed to load the decision')
209
+ );
210
+ } finally {
211
+ if (!signal?.aborted) setIsLoading(false);
212
+ }
213
+ },
214
+ [graphQLOptions, shipmentId, kind]
215
+ );
216
+
217
+ useEffect(() => {
218
+ // A newer shipment (or unmount) cancels the older load, so a late reply cannot overwrite it.
219
+ const controller = new AbortController();
220
+ // A different shipment never shows the previous shipment's decision, not even while loading.
221
+ setDecision(null);
222
+ void load(controller.signal);
223
+ return () => controller.abort();
224
+ }, [load]);
225
+
226
+ const run = useCallback(
227
+ async <T>(
228
+ action: PendingAction,
229
+ call: () => Promise<T>,
230
+ pick: (data: T) => ShipmentDecision
231
+ ): Promise<ShipmentDecision> => {
232
+ setPendingAction(action);
233
+ try {
234
+ const next = pick(await call());
235
+ setDecision(next);
236
+ return next;
237
+ } catch (actionError) {
238
+ // The proposal may have changed underneath (expired, decided elsewhere): show the stored record.
239
+ void load();
240
+ throw actionError;
241
+ } finally {
242
+ setPendingAction(null);
243
+ }
244
+ },
245
+ [load]
246
+ );
247
+
248
+ const propose = useCallback(() => {
249
+ if (!shipmentId) return Promise.reject(new Error('No shipment selected'));
250
+ if (kind === 'CARRIER_RECOMMENDATION') {
251
+ return run(
252
+ 'propose',
253
+ () =>
254
+ executeGraphQL<{ mtwRecommendCarrier: ShipmentDecision }>(
255
+ graphQLOptions,
256
+ RECOMMEND_CARRIER_MUTATION,
257
+ { shipmentId },
258
+ 'SINGLE_ATTEMPT'
259
+ ),
260
+ (data) => data.mtwRecommendCarrier
261
+ );
262
+ }
263
+ return run(
264
+ 'propose',
265
+ () =>
266
+ executeGraphQL<{ mtwResolveException: ShipmentDecision }>(
267
+ graphQLOptions,
268
+ RESOLVE_EXCEPTION_MUTATION,
269
+ { shipmentId },
270
+ 'SINGLE_ATTEMPT'
271
+ ),
272
+ (data) => data.mtwResolveException
273
+ );
274
+ }, [graphQLOptions, kind, run, shipmentId]);
275
+
276
+ const accept = useCallback(
277
+ (decisionId: string, optionId: string) =>
278
+ run(
279
+ 'accept',
280
+ () =>
281
+ executeGraphQL<{ mtwAcceptShipmentDecision: ShipmentDecision }>(
282
+ graphQLOptions,
283
+ ACCEPT_MUTATION,
284
+ { decisionId, optionId },
285
+ 'SINGLE_ATTEMPT'
286
+ ),
287
+ (data) => data.mtwAcceptShipmentDecision
288
+ ),
289
+ [graphQLOptions, run]
290
+ );
291
+
292
+ const reject = useCallback(
293
+ (decisionId: string) =>
294
+ run(
295
+ 'reject',
296
+ () =>
297
+ executeGraphQL<{ mtwRejectShipmentDecision: ShipmentDecision }>(
298
+ graphQLOptions,
299
+ REJECT_MUTATION,
300
+ { decisionId },
301
+ 'SINGLE_ATTEMPT'
302
+ ),
303
+ (data) => data.mtwRejectShipmentDecision
304
+ ),
305
+ [graphQLOptions, run]
306
+ );
307
+
308
+ return {
309
+ decision,
310
+ isLoading,
311
+ error,
312
+ pendingAction,
313
+ refetch: () => void load(),
314
+ propose,
315
+ accept,
316
+ reject,
317
+ };
318
+ }
@@ -13,7 +13,7 @@
13
13
  */
14
14
 
15
15
  import { useEffect, useMemo, useState } from 'react';
16
- import { Loader2, Navigation, Plus, RefreshCw, Sparkles, Wand2 } from 'lucide-react';
16
+ import { Building2, Loader2, Navigation, Plus, RefreshCw, Sparkles, Wand2 } from 'lucide-react';
17
17
  import { CTAOverflowMenu, EmphasisPanel, PagePurpose } from '@burdenoff/fe-libs/ui';
18
18
  import { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';
19
19
 
@@ -21,6 +21,7 @@ import { PageLayout } from '../components/PageLayout';
21
21
  import { FormError } from '../components/FormError';
22
22
  import { Notice, useNotice } from '../components/Notice';
23
23
  import { DispatchDecisionCard, type DispatchChoice } from '../components/DispatchDecisionCard';
24
+ import { CarrierRecommendationDialog } from '../components/CarrierRecommendationDialog';
24
25
  import {
25
26
  Badge,
26
27
  Button,
@@ -217,6 +218,7 @@ export default function DispatchPlanPage() {
217
218
  const [horizon, setHorizon] = useState<Horizon>('72h');
218
219
  const [choices, setChoices] = useState<Record<string, DispatchChoice>>({});
219
220
  const [actionError, setActionError] = useState<string | null>(null);
221
+ const [carrierFor, setCarrierFor] = useState<{ id: string; number: string | null } | null>(null);
220
222
  const { message, notify } = useNotice(6000);
221
223
 
222
224
  // A different plan (new proposal, or a decision returned by the server) starts with no choices.
@@ -463,6 +465,7 @@ export default function DispatchPlanPage() {
463
465
  setChoices((current) => ({ ...current, [assignment.id]: choice }))
464
466
  }
465
467
  onOpenRoute={(routeId) => goTo(`routes/${routeId}`)}
468
+ onRecommendCarrier={(id, number) => setCarrierFor({ id, number })}
466
469
  t={t}
467
470
  />
468
471
  ))}
@@ -491,6 +494,18 @@ export default function DispatchPlanPage() {
491
494
  <span className="text-text-secondary">
492
495
  {entry ? t(entry[0], entry[1]) : u.reason}
493
496
  </span>
497
+ {u.reason !== 'NOT_PLANNABLE' && (
498
+ <Button
499
+ size="sm"
500
+ variant="outline"
501
+ onClick={() =>
502
+ setCarrierFor({ id: u.shipmentId, number: u.shipmentNumber })
503
+ }
504
+ >
505
+ <Building2 size={14} aria-hidden="true" />
506
+ {t('movethewheels.carrierDecision.propose', 'Recommend a carrier')}
507
+ </Button>
508
+ )}
494
509
  </li>
495
510
  );
496
511
  })}
@@ -500,6 +515,20 @@ export default function DispatchPlanPage() {
500
515
  )}
501
516
  </>
502
517
  )}
518
+
519
+ <CarrierRecommendationDialog
520
+ shipment={carrierFor}
521
+ onOpenChange={(isOpen) => !isOpen && setCarrierFor(null)}
522
+ onApplied={() =>
523
+ notify(
524
+ t(
525
+ 'movethewheels.carrierDecision.applied',
526
+ 'Carrier assigned to the shipment. It stays planned for you to hand over.'
527
+ )
528
+ )
529
+ }
530
+ t={t}
531
+ />
503
532
  </PageLayout>
504
533
  );
505
534
  }