@burdenoff/microfe-movethewheels 2026.1107.2 → 2026.1107.3

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,243 @@
1
+ /**
2
+ * DispatchDecisionCard (BOFF-10562)
3
+ *
4
+ * One proposed shipment -> vehicle + driver pairing from `mtwPlanDispatch`,
5
+ * with the planner's confidence, the reasons behind the pairing, its factual
6
+ * rationale and, when the shared AI runtime produced one, an AI-written
7
+ * rationale. While the plan is open the card offers Accept / Reject; once the
8
+ * plan is decided it shows what happened (route created, rejected, or stale
9
+ * with the server's reason).
10
+ *
11
+ * Presentational only: the choice is held by the page and nothing is written
12
+ * until the person applies their decisions.
13
+ */
14
+
15
+ import { Check, Route as RouteIcon, Sparkles, Truck, User, X } from 'lucide-react';
16
+
17
+ import { Badge, Button, Card, CardContent } from './ui';
18
+ import type { DispatchAssignment } from '../hooks/useDispatchPlan';
19
+ import { formatDateTime } from '../utils/formatters';
20
+
21
+ export type DispatchChoice = 'accept' | 'reject' | null;
22
+
23
+ type Translate = (key: string, fallback: string) => string;
24
+
25
+ const REASON_LABELS: Record<string, [string, string]> = {
26
+ EARLIEST_DUE: ['movethewheels.dispatch.reason.earliestDue', 'Earliest due'],
27
+ MAINTENANCE_OK: ['movethewheels.dispatch.reason.maintenanceOk', 'No service due'],
28
+ MAINTENANCE_DUE_SOON: ['movethewheels.dispatch.reason.maintenanceDueSoon', 'Service due soon'],
29
+ MAINTENANCE_OVERDUE: ['movethewheels.dispatch.reason.maintenanceOverdue', 'Service overdue'],
30
+ FUEL_EFFICIENT: ['movethewheels.dispatch.reason.fuelEfficient', 'Most fuel-efficient'],
31
+ CAPACITY_FITS: ['movethewheels.dispatch.reason.capacityFits', 'Capacity fits'],
32
+ CAPACITY_UNKNOWN: ['movethewheels.dispatch.reason.capacityUnknown', 'Capacity not recorded'],
33
+ DRIVER_AVAILABLE: ['movethewheels.dispatch.reason.driverAvailable', 'Driver available'],
34
+ DRIVER_RATED: ['movethewheels.dispatch.reason.driverRated', 'Driver rated'],
35
+ LICENSE_EXPIRING: ['movethewheels.dispatch.reason.licenseExpiring', 'Licence expiring'],
36
+ LINKED_PAIR: ['movethewheels.dispatch.reason.linkedPair', 'Linked vehicle and driver'],
37
+ DISTANCE_MEASURED: ['movethewheels.dispatch.reason.distanceMeasured', 'Distance measured'],
38
+ DISTANCE_UNKNOWN: ['movethewheels.dispatch.reason.distanceUnknown', 'No coordinates'],
39
+ };
40
+
41
+ /** Reasons that ask the dispatcher to check something before accepting. */
42
+ const CAUTION_REASONS = new Set([
43
+ 'MAINTENANCE_DUE_SOON',
44
+ 'MAINTENANCE_OVERDUE',
45
+ 'CAPACITY_UNKNOWN',
46
+ 'LICENSE_EXPIRING',
47
+ 'DISTANCE_UNKNOWN',
48
+ ]);
49
+
50
+ export function reasonLabel(reason: string, t: Translate): string {
51
+ const entry = REASON_LABELS[reason];
52
+ return entry ? t(entry[0], entry[1]) : reason;
53
+ }
54
+
55
+ function confidenceTone(confidence: number): string {
56
+ if (confidence >= 0.75) return 'text-status-success-text';
57
+ if (confidence >= 0.5) return 'text-status-warning-text';
58
+ return 'text-status-error-text';
59
+ }
60
+
61
+ interface DispatchDecisionCardProps {
62
+ assignment: DispatchAssignment;
63
+ /** True while the plan can still be decided. */
64
+ open: boolean;
65
+ choice: DispatchChoice;
66
+ disabled: boolean;
67
+ onChoose: (choice: DispatchChoice) => void;
68
+ onOpenRoute: (routeId: string) => void;
69
+ t: Translate;
70
+ }
71
+
72
+ function DecisionOutcome({
73
+ assignment,
74
+ onOpenRoute,
75
+ t,
76
+ }: Pick<DispatchDecisionCardProps, 'assignment' | 'onOpenRoute' | 't'>) {
77
+ if (assignment.decision === 'ACCEPTED') {
78
+ return (
79
+ <div className="flex flex-wrap items-center gap-2">
80
+ <Badge variant="default">{t('movethewheels.dispatch.decision.accepted', 'Accepted')}</Badge>
81
+ {assignment.routeId && (
82
+ <Button
83
+ size="sm"
84
+ variant="outline"
85
+ onClick={() => onOpenRoute(assignment.routeId as string)}
86
+ >
87
+ <RouteIcon size={14} aria-hidden="true" />
88
+ {t('movethewheels.dispatch.openRoute', 'Open route')}
89
+ </Button>
90
+ )}
91
+ </div>
92
+ );
93
+ }
94
+ if (assignment.decision === 'STALE') {
95
+ return (
96
+ <div className="space-y-1">
97
+ <Badge variant="outline">{t('movethewheels.dispatch.decision.stale', 'Not applied')}</Badge>
98
+ {assignment.decisionReason && (
99
+ <p className="text-xs text-status-warning-text">{assignment.decisionReason}</p>
100
+ )}
101
+ </div>
102
+ );
103
+ }
104
+ if (assignment.decision === 'REJECTED') {
105
+ return (
106
+ <Badge variant="secondary">{t('movethewheels.dispatch.decision.rejected', 'Rejected')}</Badge>
107
+ );
108
+ }
109
+ return (
110
+ <Badge variant="outline">{t('movethewheels.dispatch.decision.pending', 'Not decided')}</Badge>
111
+ );
112
+ }
113
+
114
+ export function DispatchDecisionCard({
115
+ assignment,
116
+ open,
117
+ choice,
118
+ disabled,
119
+ onChoose,
120
+ onOpenRoute,
121
+ t,
122
+ }: DispatchDecisionCardProps) {
123
+ const percent = Math.round(assignment.confidence * 100);
124
+ const title = assignment.shipmentNumber ?? assignment.shipmentId;
125
+ let border = 'border-border-default';
126
+ if (open && choice === 'accept') border = 'border-status-success-border';
127
+ else if (open && choice === 'reject') border = 'border-status-error-border';
128
+
129
+ return (
130
+ <Card
131
+ className={border}
132
+ data-assignment-id={assignment.id}
133
+ data-testid="dispatch-decision-card"
134
+ >
135
+ <CardContent className="space-y-3 p-4">
136
+ <div className="flex flex-wrap items-start justify-between gap-3">
137
+ <div className="min-w-0 space-y-1">
138
+ <p className="text-sm font-semibold break-words text-text-primary">
139
+ {t('movethewheels.dispatch.shipment', 'Shipment')} {title}
140
+ </p>
141
+ {assignment.estimatedDelivery && (
142
+ <p className="text-xs text-text-secondary">
143
+ {t('movethewheels.dispatch.due', 'Due')}{' '}
144
+ {formatDateTime(assignment.estimatedDelivery)}
145
+ </p>
146
+ )}
147
+ </div>
148
+ <div className="text-right">
149
+ <p
150
+ className={`text-lg font-bold tabular-nums ${confidenceTone(assignment.confidence)}`}
151
+ >
152
+ {percent}%
153
+ </p>
154
+ <p className="text-xs text-text-secondary">
155
+ {t('movethewheels.dispatch.confidence', 'Planner confidence')}
156
+ </p>
157
+ </div>
158
+ </div>
159
+
160
+ <div className="grid gap-2 text-sm sm:grid-cols-2">
161
+ <p className="flex items-center gap-2 break-words">
162
+ <Truck size={16} className="shrink-0 text-text-secondary" aria-hidden="true" />
163
+ <span>
164
+ {assignment.vehicleNumber ?? assignment.vehicleId}
165
+ {assignment.vehicleType && (
166
+ <span className="text-text-secondary"> · {assignment.vehicleType}</span>
167
+ )}
168
+ </span>
169
+ </p>
170
+ <p className="flex items-center gap-2 break-words">
171
+ <User size={16} className="shrink-0 text-text-secondary" aria-hidden="true" />
172
+ <span>{assignment.driverName ?? assignment.driverId}</span>
173
+ </p>
174
+ </div>
175
+
176
+ <ul
177
+ className="flex flex-wrap gap-1.5"
178
+ aria-label={t('movethewheels.dispatch.reasons', 'Reasons')}
179
+ >
180
+ {assignment.reasons.map((reason) => (
181
+ <li key={reason}>
182
+ <Badge variant={CAUTION_REASONS.has(reason) ? 'outline' : 'secondary'}>
183
+ {reasonLabel(reason, t)}
184
+ </Badge>
185
+ </li>
186
+ ))}
187
+ </ul>
188
+
189
+ <p className="text-sm text-text-secondary">{assignment.rationale}</p>
190
+ {assignment.aiRationale && (
191
+ <p className="flex items-start gap-2 rounded-md bg-surface-secondary p-2 text-sm text-text-primary">
192
+ <Sparkles size={14} className="mt-0.5 shrink-0" aria-hidden="true" />
193
+ <span>
194
+ <span className="sr-only">
195
+ {t('movethewheels.dispatch.aiWritten', 'AI-written')}:{' '}
196
+ </span>
197
+ {assignment.aiRationale}
198
+ </span>
199
+ </p>
200
+ )}
201
+ {assignment.estimatedDistanceKm !== null && (
202
+ <p className="text-xs text-text-secondary">
203
+ {t('movethewheels.dispatch.distance', 'Straight-line distance')}{' '}
204
+ {assignment.estimatedDistanceKm} km
205
+ {assignment.estimatedDurationMinutes !== null &&
206
+ ` · ~${Math.round(assignment.estimatedDurationMinutes)} min`}
207
+ </p>
208
+ )}
209
+
210
+ {open ? (
211
+ <div
212
+ className="flex flex-wrap gap-2"
213
+ role="group"
214
+ aria-label={t('movethewheels.dispatch.decide', 'Decide this assignment')}
215
+ >
216
+ <Button
217
+ size="sm"
218
+ variant={choice === 'accept' ? 'default' : 'outline'}
219
+ aria-pressed={choice === 'accept'}
220
+ disabled={disabled}
221
+ onClick={() => onChoose(choice === 'accept' ? null : 'accept')}
222
+ >
223
+ <Check size={14} aria-hidden="true" />
224
+ {t('movethewheels.dispatch.accept', 'Accept')}
225
+ </Button>
226
+ <Button
227
+ size="sm"
228
+ variant={choice === 'reject' ? 'destructive' : 'outline'}
229
+ aria-pressed={choice === 'reject'}
230
+ disabled={disabled}
231
+ onClick={() => onChoose(choice === 'reject' ? null : 'reject')}
232
+ >
233
+ <X size={14} aria-hidden="true" />
234
+ {t('movethewheels.dispatch.reject', 'Reject')}
235
+ </Button>
236
+ </div>
237
+ ) : (
238
+ <DecisionOutcome assignment={assignment} onOpenRoute={onOpenRoute} t={t} />
239
+ )}
240
+ </CardContent>
241
+ </Card>
242
+ );
243
+ }
@@ -0,0 +1,286 @@
1
+ /**
2
+ * Dispatch decision proposals (BOFF-10562).
3
+ *
4
+ * Reads the workspace's latest dispatch plan and drives its three decisions:
5
+ *
6
+ * - `propose` calls `mtwPlanDispatch`, which proposes vehicle + driver pairings
7
+ * for PLANNED shipments and writes no route.
8
+ * - `apply(acceptIds)` calls `mtwApplyDispatchPlan`: one PLANNED route per
9
+ * accepted assignment, every other assignment rejected. Partial accept is the
10
+ * normal case.
11
+ * - `reject` calls `mtwRejectDispatchPlan`, which writes nothing else.
12
+ *
13
+ * The server decides everything (eligibility, staleness, expiry, AI credit
14
+ * gating). This hook only reflects the plan the server returns after each
15
+ * call, so what a person sees is always the stored record.
16
+ */
17
+
18
+ import { useCallback, useEffect, useMemo, useState } from 'react';
19
+ import { useMoveTheWheels } from '../providers/MoveTheWheelsProvider';
20
+ import { executeGraphQL } from '../utils/graphqlClient';
21
+
22
+ export type DispatchPlanStatus =
23
+ 'PROPOSED' | 'APPLYING' | 'APPLIED' | 'PARTIALLY_APPLIED' | 'REJECTED' | 'EXPIRED';
24
+ export type DispatchAssignmentDecision = 'PENDING' | 'ACCEPTED' | 'REJECTED' | 'STALE';
25
+ export type DecisionRationaleStatus =
26
+ | 'AVAILABLE'
27
+ | 'NOT_NEEDED'
28
+ | 'AI_DISABLED'
29
+ | 'CREDITS_EXHAUSTED'
30
+ | 'DAILY_CAP_REACHED'
31
+ | 'UNAVAILABLE';
32
+
33
+ export interface DispatchAssignment {
34
+ id: string;
35
+ sequence: number;
36
+ shipmentId: string;
37
+ shipmentNumber: string | null;
38
+ estimatedDelivery: string | null;
39
+ vehicleId: string;
40
+ vehicleNumber: string | null;
41
+ vehicleType: string | null;
42
+ driverId: string;
43
+ driverName: string | null;
44
+ confidence: number;
45
+ reasons: string[];
46
+ rationale: string;
47
+ aiRationale: string | null;
48
+ estimatedDistanceKm: number | null;
49
+ estimatedDurationMinutes: number | null;
50
+ decision: DispatchAssignmentDecision;
51
+ decisionReason: string | null;
52
+ routeId: string | null;
53
+ }
54
+
55
+ export interface UnassignedShipment {
56
+ shipmentId: string;
57
+ shipmentNumber: string | null;
58
+ reason: string;
59
+ }
60
+
61
+ export interface DispatchPlan {
62
+ id: string;
63
+ status: DispatchPlanStatus;
64
+ method: string;
65
+ aiStatus: DecisionRationaleStatus;
66
+ aiSummary: string | null;
67
+ aiModel: string | null;
68
+ assignments: DispatchAssignment[];
69
+ unassigned: UnassignedShipment[];
70
+ acceptedCount: number;
71
+ rejectedCount: number;
72
+ staleCount: number;
73
+ pendingCount: number;
74
+ expiresAt: string;
75
+ decidedAt: string | null;
76
+ createdAt: string;
77
+ }
78
+
79
+ const PLAN_FIELDS = `
80
+ id
81
+ status
82
+ method
83
+ aiStatus
84
+ aiSummary
85
+ aiModel
86
+ assignments {
87
+ id
88
+ sequence
89
+ shipmentId
90
+ shipmentNumber
91
+ estimatedDelivery
92
+ vehicleId
93
+ vehicleNumber
94
+ vehicleType
95
+ driverId
96
+ driverName
97
+ confidence
98
+ reasons
99
+ rationale
100
+ aiRationale
101
+ estimatedDistanceKm
102
+ estimatedDurationMinutes
103
+ decision
104
+ decisionReason
105
+ routeId
106
+ }
107
+ unassigned {
108
+ shipmentId
109
+ shipmentNumber
110
+ reason
111
+ }
112
+ acceptedCount
113
+ rejectedCount
114
+ staleCount
115
+ pendingCount
116
+ expiresAt
117
+ decidedAt
118
+ createdAt
119
+ `;
120
+
121
+ const LATEST_DISPATCH_PLAN_QUERY = `
122
+ query LatestDispatchPlan {
123
+ mtwLatestDispatchPlan {
124
+ ${PLAN_FIELDS}
125
+ }
126
+ }
127
+ `;
128
+
129
+ const PLAN_DISPATCH_MUTATION = `
130
+ mutation PlanDispatch($input: MtwPlanDispatchInput) {
131
+ mtwPlanDispatch(input: $input) {
132
+ ${PLAN_FIELDS}
133
+ }
134
+ }
135
+ `;
136
+
137
+ const APPLY_DISPATCH_PLAN_MUTATION = `
138
+ mutation ApplyDispatchPlan($planId: ID!, $accept: [ID!]!) {
139
+ mtwApplyDispatchPlan(planId: $planId, accept: $accept) {
140
+ ${PLAN_FIELDS}
141
+ }
142
+ }
143
+ `;
144
+
145
+ const REJECT_DISPATCH_PLAN_MUTATION = `
146
+ mutation RejectDispatchPlan($planId: ID!) {
147
+ mtwRejectDispatchPlan(planId: $planId) {
148
+ ${PLAN_FIELDS}
149
+ }
150
+ }
151
+ `;
152
+
153
+ export interface PlanDispatchOptions {
154
+ /** ISO date-time: only shipments due at or after this. */
155
+ from?: string;
156
+ /** ISO date-time: only shipments due at or before this. */
157
+ to?: string;
158
+ maxAssignments?: number;
159
+ }
160
+
161
+ function useGraphqlOptions() {
162
+ const { apiGatewayUrl, authToken, workspaceToken, workspaceId, tenantId, currentUser } =
163
+ useMoveTheWheels();
164
+ return useMemo(
165
+ () => ({
166
+ apiGatewayUrl,
167
+ authToken,
168
+ workspaceToken,
169
+ workspaceId,
170
+ tenantId,
171
+ actorId: currentUser?.id,
172
+ }),
173
+ [apiGatewayUrl, authToken, workspaceToken, workspaceId, tenantId, currentUser?.id]
174
+ );
175
+ }
176
+
177
+ export function useDispatchPlan() {
178
+ const graphQLOptions = useGraphqlOptions();
179
+ const [plan, setPlan] = useState<DispatchPlan | null>(null);
180
+ const [isLoading, setIsLoading] = useState(true);
181
+ const [error, setError] = useState<Error | null>(null);
182
+ const [pendingAction, setPendingAction] = useState<'propose' | 'apply' | 'reject' | null>(null);
183
+
184
+ const load = useCallback(async () => {
185
+ setIsLoading(true);
186
+ setError(null);
187
+ try {
188
+ const data = await executeGraphQL<{ mtwLatestDispatchPlan: DispatchPlan | null }>(
189
+ graphQLOptions,
190
+ LATEST_DISPATCH_PLAN_QUERY
191
+ );
192
+ setPlan(data.mtwLatestDispatchPlan);
193
+ } catch (fetchError) {
194
+ setError(
195
+ fetchError instanceof Error ? fetchError : new Error('Failed to load the dispatch plan')
196
+ );
197
+ } finally {
198
+ setIsLoading(false);
199
+ }
200
+ }, [graphQLOptions]);
201
+
202
+ useEffect(() => {
203
+ void load();
204
+ }, [load]);
205
+
206
+ const run = useCallback(
207
+ async <T>(
208
+ action: 'propose' | 'apply' | 'reject',
209
+ call: () => Promise<T>,
210
+ pickPlan: (data: T) => DispatchPlan
211
+ ): Promise<DispatchPlan> => {
212
+ setPendingAction(action);
213
+ try {
214
+ const next = pickPlan(await call());
215
+ setPlan(next);
216
+ return next;
217
+ } catch (actionError) {
218
+ // The plan may have changed underneath (expired, decided elsewhere): show the stored record.
219
+ void load();
220
+ throw actionError;
221
+ } finally {
222
+ setPendingAction(null);
223
+ }
224
+ },
225
+ [load]
226
+ );
227
+
228
+ const propose = useCallback(
229
+ (options: PlanDispatchOptions = {}) =>
230
+ run(
231
+ 'propose',
232
+ () =>
233
+ executeGraphQL<{ mtwPlanDispatch: DispatchPlan }>(
234
+ graphQLOptions,
235
+ PLAN_DISPATCH_MUTATION,
236
+ { input: options },
237
+ 'SINGLE_ATTEMPT'
238
+ ),
239
+ (data) => data.mtwPlanDispatch
240
+ ),
241
+ [graphQLOptions, run]
242
+ );
243
+
244
+ const apply = useCallback(
245
+ (planId: string, accept: string[]) =>
246
+ run(
247
+ 'apply',
248
+ () =>
249
+ executeGraphQL<{ mtwApplyDispatchPlan: DispatchPlan }>(
250
+ graphQLOptions,
251
+ APPLY_DISPATCH_PLAN_MUTATION,
252
+ { planId, accept },
253
+ 'SINGLE_ATTEMPT'
254
+ ),
255
+ (data) => data.mtwApplyDispatchPlan
256
+ ),
257
+ [graphQLOptions, run]
258
+ );
259
+
260
+ const reject = useCallback(
261
+ (planId: string) =>
262
+ run(
263
+ 'reject',
264
+ () =>
265
+ executeGraphQL<{ mtwRejectDispatchPlan: DispatchPlan }>(
266
+ graphQLOptions,
267
+ REJECT_DISPATCH_PLAN_MUTATION,
268
+ { planId },
269
+ 'SINGLE_ATTEMPT'
270
+ ),
271
+ (data) => data.mtwRejectDispatchPlan
272
+ ),
273
+ [graphQLOptions, run]
274
+ );
275
+
276
+ return {
277
+ plan,
278
+ isLoading,
279
+ error,
280
+ pendingAction,
281
+ refetch: () => void load(),
282
+ propose,
283
+ apply,
284
+ reject,
285
+ };
286
+ }