@burdenoff/microfe-movethewheels 2026.1107.7 → 2026.1108.1

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,449 @@
1
+ /**
2
+ * InventoryCoverPanel
3
+ *
4
+ * Inventory planning (BOFF-10926): weeks of stock cover per warehouse and
5
+ * SKU against forecast outbound demand, the week stock is projected to run
6
+ * out, and how much to reorder now to hold a target cover once the order
7
+ * lands. Outbound demand comes from the cargo lines of delivery jobs picked
8
+ * up at each warehouse, using the same closed-week history as the lane
9
+ * forecast.
10
+ *
11
+ * Read-only: the plan is computed by `inventoryCoverPlan` on request and
12
+ * never stored, so changing the lead time or the demand scenario has no
13
+ * side effects.
14
+ */
15
+
16
+ import { useState } from 'react';
17
+ import { CalendarClock, Info, RefreshCw } from 'lucide-react';
18
+
19
+ import {
20
+ Button,
21
+ Card,
22
+ CardContent,
23
+ CardDescription,
24
+ CardHeader,
25
+ CardTitle,
26
+ Input,
27
+ Label,
28
+ Select,
29
+ SelectContent,
30
+ SelectItem,
31
+ SelectTrigger,
32
+ SelectValue,
33
+ Skeleton,
34
+ Switch,
35
+ Table,
36
+ TableBody,
37
+ TableCell,
38
+ TableHead,
39
+ TableHeader,
40
+ TableRow,
41
+ } from './ui';
42
+ import { FormError } from './FormError';
43
+ import { formatDate } from '../utils/formatters';
44
+ import {
45
+ DEFAULT_COVER_REQUEST,
46
+ useInventoryCoverPlan,
47
+ type CoverPlanRequest,
48
+ type CoverPlanRow,
49
+ type CoverPlanSummary,
50
+ type CoverStatus,
51
+ } from '../hooks/useInventoryCoverPlan';
52
+
53
+ const ALL_WAREHOUSES = 'all';
54
+ const LIMITS = {
55
+ leadTime: { min: 0, max: 26 },
56
+ targetCover: { min: 1, max: 52 },
57
+ demandPct: { min: -100, max: 500 },
58
+ } as const;
59
+
60
+ const STATUS_META: Record<CoverStatus, { label: string; className: string }> = {
61
+ OUT_OF_STOCK: {
62
+ label: 'Out of stock',
63
+ className: 'bg-status-error-bg-subtle text-status-error-text',
64
+ },
65
+ AT_RISK: {
66
+ label: 'Runs out before lead time',
67
+ className: 'bg-status-error-bg-subtle text-status-error-text',
68
+ },
69
+ REORDER: {
70
+ label: 'Reorder',
71
+ className: 'bg-status-warning-bg-subtle text-status-warning-text',
72
+ },
73
+ HEALTHY: {
74
+ label: 'Healthy',
75
+ className: 'bg-status-success-bg-subtle text-status-success-text',
76
+ },
77
+ NOT_ENOUGH_HISTORY: {
78
+ label: 'Not enough history',
79
+ className: 'bg-muted text-text-secondary',
80
+ },
81
+ NO_DEMAND: {
82
+ label: 'No demand',
83
+ className: 'bg-muted text-text-secondary',
84
+ },
85
+ };
86
+
87
+ const SUMMARY_TILES: { status: CoverStatus; key: keyof CoverPlanSummary }[] = [
88
+ { status: 'OUT_OF_STOCK', key: 'outOfStock' },
89
+ { status: 'AT_RISK', key: 'atRisk' },
90
+ { status: 'REORDER', key: 'reorder' },
91
+ { status: 'HEALTHY', key: 'healthy' },
92
+ { status: 'NOT_ENOUGH_HISTORY', key: 'notEnoughHistory' },
93
+ { status: 'NO_DEMAND', key: 'noDemand' },
94
+ ];
95
+
96
+ const formatUnits = (value: number | null, digits = 1): string => {
97
+ if (value === null) return '—';
98
+ return value.toLocaleString(undefined, { maximumFractionDigits: digits });
99
+ };
100
+
101
+ interface DraftSettings {
102
+ warehouseId: string;
103
+ leadTime: string;
104
+ targetCover: string;
105
+ demandPct: string;
106
+ actionOnly: boolean;
107
+ }
108
+
109
+ const toDraft = (request: CoverPlanRequest): DraftSettings => ({
110
+ warehouseId: request.warehouseId ?? ALL_WAREHOUSES,
111
+ leadTime: String(request.leadTimeWeeks),
112
+ targetCover: String(request.targetCoverWeeks),
113
+ demandPct: String(request.demandChangePct),
114
+ actionOnly: request.actionOnly,
115
+ });
116
+
117
+ const inRange = (value: number, bounds: { min: number; max: number }): boolean =>
118
+ Number.isFinite(value) && value >= bounds.min && value <= bounds.max;
119
+
120
+ /** The request a draft describes, or the first problem with it. */
121
+ export function parseCoverDraft(
122
+ draft: DraftSettings
123
+ ): { request: CoverPlanRequest; problem: null } | { request: null; problem: string } {
124
+ const leadTimeWeeks = draft.leadTime.trim() === '' ? Number.NaN : Number(draft.leadTime);
125
+ const targetCoverWeeks = draft.targetCover.trim() === '' ? Number.NaN : Number(draft.targetCover);
126
+ const demandChangePct = draft.demandPct.trim() === '' ? 0 : Number(draft.demandPct);
127
+ if (!inRange(leadTimeWeeks, LIMITS.leadTime)) {
128
+ return { request: null, problem: 'Lead time must be between 0 and 26 weeks.' };
129
+ }
130
+ if (!inRange(targetCoverWeeks, LIMITS.targetCover)) {
131
+ return { request: null, problem: 'Target cover must be between 1 and 52 weeks.' };
132
+ }
133
+ if (!inRange(demandChangePct, LIMITS.demandPct)) {
134
+ return { request: null, problem: 'Demand change must be between -100% and 500%.' };
135
+ }
136
+ return {
137
+ request: {
138
+ warehouseId: draft.warehouseId === ALL_WAREHOUSES ? null : draft.warehouseId,
139
+ leadTimeWeeks,
140
+ targetCoverWeeks,
141
+ demandChangePct,
142
+ actionOnly: draft.actionOnly,
143
+ },
144
+ problem: null,
145
+ };
146
+ }
147
+
148
+ interface InventoryCoverPanelProps {
149
+ warehouses: { id: string; name: string }[];
150
+ }
151
+
152
+ export function InventoryCoverPanel({ warehouses }: InventoryCoverPanelProps) {
153
+ const { plan, isLoading, error, run } = useInventoryCoverPlan(DEFAULT_COVER_REQUEST);
154
+ const [draft, setDraft] = useState<DraftSettings>(() => toDraft(DEFAULT_COVER_REQUEST));
155
+ const [formError, setFormError] = useState<string | null>(null);
156
+
157
+ const update = (patch: Partial<DraftSettings>) =>
158
+ setDraft((current) => ({ ...current, ...patch }));
159
+
160
+ const submit = (next: DraftSettings) => {
161
+ const parsed = parseCoverDraft(next);
162
+ setFormError(parsed.problem);
163
+ if (parsed.request) run(parsed.request);
164
+ };
165
+
166
+ return (
167
+ <Card data-testid="inventory-cover-panel">
168
+ <CardHeader>
169
+ <CardTitle className="flex items-center gap-2">
170
+ <CalendarClock size={18} aria-hidden="true" />
171
+ Stock cover vs demand forecast
172
+ </CardTitle>
173
+ <CardDescription>
174
+ How many weeks your stock lasts at forecast outbound demand, when each item runs out, and
175
+ how much to reorder now so it lasts through the lead time and your target cover.
176
+ </CardDescription>
177
+ </CardHeader>
178
+ <CardContent className="space-y-6">
179
+ <form
180
+ className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-5 lg:items-end"
181
+ onSubmit={(event) => {
182
+ event.preventDefault();
183
+ submit(draft);
184
+ }}
185
+ >
186
+ <div className="space-y-1.5">
187
+ <Label htmlFor="cover-warehouse">Warehouse</Label>
188
+ <Select
189
+ value={draft.warehouseId}
190
+ onValueChange={(value) => {
191
+ const next = { ...draft, warehouseId: value };
192
+ setDraft(next);
193
+ submit(next);
194
+ }}
195
+ >
196
+ <SelectTrigger id="cover-warehouse" aria-label="Warehouse">
197
+ <SelectValue placeholder="All warehouses" />
198
+ </SelectTrigger>
199
+ <SelectContent>
200
+ <SelectItem value={ALL_WAREHOUSES}>All warehouses</SelectItem>
201
+ {warehouses.map((warehouse) => (
202
+ <SelectItem key={warehouse.id} value={warehouse.id}>
203
+ {warehouse.name}
204
+ </SelectItem>
205
+ ))}
206
+ </SelectContent>
207
+ </Select>
208
+ </div>
209
+ <div className="space-y-1.5">
210
+ <Label htmlFor="cover-lead-time">Lead time (weeks)</Label>
211
+ <Input
212
+ id="cover-lead-time"
213
+ type="number"
214
+ min={LIMITS.leadTime.min}
215
+ max={LIMITS.leadTime.max}
216
+ step="0.5"
217
+ value={draft.leadTime}
218
+ onChange={(e) => update({ leadTime: e.target.value })}
219
+ />
220
+ </div>
221
+ <div className="space-y-1.5">
222
+ <Label htmlFor="cover-target">Target cover (weeks)</Label>
223
+ <Input
224
+ id="cover-target"
225
+ type="number"
226
+ min={LIMITS.targetCover.min}
227
+ max={LIMITS.targetCover.max}
228
+ step="0.5"
229
+ value={draft.targetCover}
230
+ onChange={(e) => update({ targetCover: e.target.value })}
231
+ />
232
+ </div>
233
+ <div className="space-y-1.5">
234
+ <Label htmlFor="cover-demand">Demand change %</Label>
235
+ <Input
236
+ id="cover-demand"
237
+ type="number"
238
+ min={LIMITS.demandPct.min}
239
+ max={LIMITS.demandPct.max}
240
+ value={draft.demandPct}
241
+ onChange={(e) => update({ demandPct: e.target.value })}
242
+ />
243
+ </div>
244
+ <Button type="submit" disabled={isLoading}>
245
+ <RefreshCw size={16} aria-hidden="true" className="mr-1" />
246
+ {isLoading ? 'Planning…' : 'Update plan'}
247
+ </Button>
248
+ </form>
249
+
250
+ <div className="flex items-center gap-2">
251
+ <Switch
252
+ id="cover-action-only"
253
+ checked={draft.actionOnly}
254
+ onCheckedChange={(checked) => {
255
+ const next = { ...draft, actionOnly: checked === true };
256
+ setDraft(next);
257
+ submit(next);
258
+ }}
259
+ />
260
+ <Label htmlFor="cover-action-only" className="font-normal">
261
+ Only items that need action
262
+ </Label>
263
+ </div>
264
+
265
+ <FormError message={formError} />
266
+ {error && !isLoading && (
267
+ <FormError message={`Couldn't load the stock cover plan: ${error.message}`} />
268
+ )}
269
+
270
+ {isLoading && !plan && (
271
+ <div className="space-y-3">
272
+ <Skeleton className="h-16 w-full" />
273
+ <Skeleton className="h-40 w-full" />
274
+ </div>
275
+ )}
276
+
277
+ {plan && (
278
+ <>
279
+ <div
280
+ className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6"
281
+ data-testid="inventory-cover-summary"
282
+ >
283
+ {SUMMARY_TILES.map(({ status, key }) => (
284
+ <div key={status} className="rounded-lg border border-border/60 p-3">
285
+ <p className="text-xs text-text-secondary">{STATUS_META[status].label}</p>
286
+ <p className="text-xl font-semibold tabular-nums">{plan.summary[key]}</p>
287
+ </div>
288
+ ))}
289
+ </div>
290
+
291
+ <PlanNotes
292
+ totalSuggested={plan.summary.totalSuggestedReorderQuantity}
293
+ historyStart={plan.historyStart}
294
+ historyEnd={plan.historyEnd}
295
+ historyWeeks={plan.historyWeeks}
296
+ demandChangePct={plan.demandChangePct}
297
+ unattributedUnits={plan.unattributedUnits}
298
+ unattributedJobs={plan.unattributedJobs}
299
+ truncated={plan.truncated}
300
+ />
301
+
302
+ {plan.rows.length === 0 ? (
303
+ <p className="rounded-lg border border-border/60 p-4 text-sm text-text-secondary">
304
+ {plan.summary.totalItems === 0
305
+ ? 'No stock lines to plan yet. Receive stock into a warehouse to see its cover here.'
306
+ : 'No items need action with these settings.'}
307
+ </p>
308
+ ) : (
309
+ <CoverTable rows={plan.rows} />
310
+ )}
311
+ {plan.matchingItems > plan.rows.length && (
312
+ <p className="text-xs text-text-secondary">
313
+ Showing the {plan.rows.length} most urgent of {plan.matchingItems} items.
314
+ </p>
315
+ )}
316
+ </>
317
+ )}
318
+ </CardContent>
319
+ </Card>
320
+ );
321
+ }
322
+
323
+ interface PlanNotesProps {
324
+ totalSuggested: number;
325
+ historyStart: string;
326
+ historyEnd: string;
327
+ historyWeeks: number;
328
+ demandChangePct: number;
329
+ unattributedUnits: number;
330
+ unattributedJobs: number;
331
+ truncated: boolean;
332
+ }
333
+
334
+ function PlanNotes(props: PlanNotesProps) {
335
+ const lastClosedDay = new Date(new Date(props.historyEnd).getTime() - 24 * 60 * 60 * 1000);
336
+ return (
337
+ <div className="flex items-start gap-2 rounded-lg border border-border/60 bg-muted/40 p-4 text-sm text-text-secondary">
338
+ <Info size={16} aria-hidden="true" className="mt-0.5 shrink-0" />
339
+ <div className="space-y-1" data-testid="inventory-cover-notes">
340
+ <p>
341
+ Suggested reorder across these items:{' '}
342
+ <span className="font-medium text-text-primary">
343
+ {props.totalSuggested.toLocaleString()} units
344
+ </span>
345
+ . Demand is forecast from the cargo lines of delivery jobs picked up at each warehouse
346
+ over the last {props.historyWeeks} closed weeks ({formatDate(props.historyStart)} –{' '}
347
+ {formatDate(lastClosedDay)})
348
+ {props.demandChangePct !== 0
349
+ ? `, with a ${props.demandChangePct > 0 ? '+' : ''}${props.demandChangePct}% demand scenario`
350
+ : ''}
351
+ . Usable stock is on hand minus damaged.
352
+ </p>
353
+ {props.unattributedUnits > 0 && (
354
+ <p>
355
+ {formatUnits(props.unattributedUnits)} units on {props.unattributedJobs} delivery job
356
+ {props.unattributedJobs === 1 ? '' : 's'} could not be matched to a warehouse. Set{' '}
357
+ <code>warehouseId</code> or <code>warehouseCode</code> on the job&apos;s pickup address
358
+ to count them.
359
+ </p>
360
+ )}
361
+ {props.truncated && (
362
+ <p>This workspace has more history than one plan reads; the plan uses the newest.</p>
363
+ )}
364
+ </div>
365
+ </div>
366
+ );
367
+ }
368
+
369
+ function StatusPill({ status }: { status: CoverStatus }) {
370
+ const meta = STATUS_META[status];
371
+ return (
372
+ <span
373
+ className={`inline-flex whitespace-nowrap rounded-full px-2 py-0.5 text-xs font-medium ${meta.className}`}
374
+ >
375
+ {meta.label}
376
+ </span>
377
+ );
378
+ }
379
+
380
+ function demandCell(row: CoverPlanRow): string {
381
+ if (row.demandStatus === 'NOT_ENOUGH_HISTORY') return 'Not enough history';
382
+ if (row.forecastWeeklyDemand === null) return 'None';
383
+ return `${formatUnits(row.forecastWeeklyDemand)}/wk`;
384
+ }
385
+
386
+ function CoverTable({ rows }: { rows: CoverPlanRow[] }) {
387
+ return (
388
+ <div className="overflow-x-auto" data-testid="inventory-cover-table">
389
+ <Table>
390
+ <TableHeader>
391
+ <TableRow>
392
+ <TableHead>Item</TableHead>
393
+ <TableHead>Warehouse</TableHead>
394
+ <TableHead className="text-right">Usable stock</TableHead>
395
+ <TableHead className="text-right">Forecast demand</TableHead>
396
+ <TableHead className="text-right">Weeks of cover</TableHead>
397
+ <TableHead>Runs out</TableHead>
398
+ <TableHead className="text-right">Suggested order</TableHead>
399
+ <TableHead>Status</TableHead>
400
+ </TableRow>
401
+ </TableHeader>
402
+ <TableBody>
403
+ {rows.map((row) => (
404
+ <TableRow key={`${row.warehouseId}|${row.cargoItemId}`}>
405
+ <TableCell className="max-w-56">
406
+ <p className="truncate font-medium" title={row.name}>
407
+ {row.name}
408
+ </p>
409
+ <p className="text-xs text-text-secondary">{row.sku}</p>
410
+ </TableCell>
411
+ <TableCell className="max-w-40 truncate" title={row.warehouseName}>
412
+ {row.warehouseName}
413
+ </TableCell>
414
+ <TableCell className="text-right tabular-nums">
415
+ {row.usableStock.toLocaleString()}
416
+ </TableCell>
417
+ <TableCell
418
+ className="text-right tabular-nums"
419
+ title={
420
+ row.currentWeekUnits > 0
421
+ ? `${formatUnits(row.currentWeekUnits)} shipped so far this week`
422
+ : undefined
423
+ }
424
+ >
425
+ {demandCell(row)}
426
+ </TableCell>
427
+ <TableCell className="text-right tabular-nums">
428
+ {formatUnits(row.weeksOfCover)}
429
+ </TableCell>
430
+ <TableCell>
431
+ {row.projectedStockOutWeek
432
+ ? `Week of ${formatDate(row.projectedStockOutWeek)}`
433
+ : '—'}
434
+ </TableCell>
435
+ <TableCell className="text-right tabular-nums">
436
+ {row.suggestedReorderQuantity === null
437
+ ? '—'
438
+ : row.suggestedReorderQuantity.toLocaleString()}
439
+ </TableCell>
440
+ <TableCell>
441
+ <StatusPill status={row.status} />
442
+ </TableCell>
443
+ </TableRow>
444
+ ))}
445
+ </TableBody>
446
+ </Table>
447
+ </div>
448
+ );
449
+ }
@@ -0,0 +1,250 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+
3
+ import { useMoveTheWheels } from '../providers/MoveTheWheelsProvider';
4
+ import { executeGraphQL } from '../utils/graphqlClient';
5
+
6
+ /**
7
+ * Inventory planning (BOFF-10926). Runs the read-only `inventoryCoverPlan`
8
+ * query: weeks of stock cover per warehouse and SKU against forecast
9
+ * outbound demand, with the projected stock-out week and a suggested
10
+ * reorder quantity.
11
+ */
12
+
13
+ export type CoverStatus =
14
+ 'OUT_OF_STOCK' | 'AT_RISK' | 'REORDER' | 'HEALTHY' | 'NOT_ENOUGH_HISTORY' | 'NO_DEMAND';
15
+
16
+ export type DemandStatus = 'FORECAST' | 'NOT_ENOUGH_HISTORY' | 'NO_DEMAND';
17
+
18
+ /** Statuses that ask the planner to act, most urgent first. */
19
+ export const ACTION_STATUSES: CoverStatus[] = ['OUT_OF_STOCK', 'AT_RISK', 'REORDER'];
20
+
21
+ export interface CoverPlanRequest {
22
+ warehouseId: string | null;
23
+ leadTimeWeeks: number;
24
+ targetCoverWeeks: number;
25
+ demandChangePct: number;
26
+ /** Only rows that need action; the summary always counts every row. */
27
+ actionOnly: boolean;
28
+ }
29
+
30
+ export interface CoverPlanRow {
31
+ warehouseId: string;
32
+ warehouseName: string;
33
+ warehouseCode: string;
34
+ cargoItemId: string;
35
+ sku: string;
36
+ name: string;
37
+ onHand: number;
38
+ damaged: number;
39
+ usableStock: number;
40
+ reorderPoint: number | null;
41
+ safetyStock: number | null;
42
+ demandStatus: DemandStatus;
43
+ weeksOfHistory: number;
44
+ weeklyUnits: number[];
45
+ currentWeekUnits: number;
46
+ baselineWeeklyDemand: number | null;
47
+ forecastWeeklyDemand: number | null;
48
+ weeksOfCover: number | null;
49
+ projectedStockOutWeek: string | null;
50
+ stockOutBeforeLeadTime: boolean;
51
+ suggestedReorderQuantity: number | null;
52
+ status: CoverStatus;
53
+ }
54
+
55
+ export interface CoverPlanSummary {
56
+ totalItems: number;
57
+ outOfStock: number;
58
+ atRisk: number;
59
+ reorder: number;
60
+ healthy: number;
61
+ notEnoughHistory: number;
62
+ noDemand: number;
63
+ totalSuggestedReorderQuantity: number;
64
+ }
65
+
66
+ export interface CoverPlan {
67
+ generatedAt: string;
68
+ historyStart: string;
69
+ historyEnd: string;
70
+ historyWeeks: number;
71
+ warehouseId: string | null;
72
+ leadTimeWeeks: number;
73
+ targetCoverWeeks: number;
74
+ demandChangePct: number;
75
+ summary: CoverPlanSummary;
76
+ unattributedUnits: number;
77
+ unattributedJobs: number;
78
+ truncated: boolean;
79
+ matchingItems: number;
80
+ rows: CoverPlanRow[];
81
+ }
82
+
83
+ const COVER_PLAN_QUERY = `
84
+ query GetMovethewheelsInventoryCoverPlan($input: InventoryCoverPlanInput) {
85
+ inventoryCoverPlan(input: $input) {
86
+ generatedAt
87
+ historyStart
88
+ historyEnd
89
+ historyWeeks
90
+ warehouseId
91
+ leadTimeWeeks
92
+ targetCoverWeeks
93
+ demandChangePct
94
+ summary {
95
+ totalItems
96
+ outOfStock
97
+ atRisk
98
+ reorder
99
+ healthy
100
+ notEnoughHistory
101
+ noDemand
102
+ totalSuggestedReorderQuantity
103
+ }
104
+ unattributedUnits
105
+ unattributedJobs
106
+ truncated
107
+ matchingItems
108
+ rows {
109
+ warehouseId
110
+ warehouseName
111
+ warehouseCode
112
+ cargoItemId
113
+ sku
114
+ name
115
+ onHand
116
+ damaged
117
+ usableStock
118
+ reorderPoint
119
+ safetyStock
120
+ demandStatus
121
+ weeksOfHistory
122
+ weeklyUnits
123
+ currentWeekUnits
124
+ baselineWeeklyDemand
125
+ forecastWeeklyDemand
126
+ weeksOfCover
127
+ projectedStockOutWeek
128
+ stockOutBeforeLeadTime
129
+ suggestedReorderQuantity
130
+ status
131
+ }
132
+ }
133
+ }
134
+ `;
135
+
136
+ /** Rows the panel asks for; the summary still counts every position. */
137
+ export const COVER_PLAN_ROW_LIMIT = 200;
138
+
139
+ export const DEFAULT_COVER_REQUEST: CoverPlanRequest = {
140
+ warehouseId: null,
141
+ leadTimeWeeks: 2,
142
+ targetCoverWeeks: 6,
143
+ demandChangePct: 0,
144
+ actionOnly: false,
145
+ };
146
+
147
+ interface UseInventoryCoverPlanResult {
148
+ plan: CoverPlan | null;
149
+ isLoading: boolean;
150
+ error: Error | null;
151
+ /** Run a plan; the latest request wins if several overlap. */
152
+ run: (request: CoverPlanRequest) => void;
153
+ }
154
+
155
+ export function useInventoryCoverPlan(
156
+ initial: CoverPlanRequest = DEFAULT_COVER_REQUEST
157
+ ): UseInventoryCoverPlanResult {
158
+ const { apiGatewayUrl, authToken, workspaceToken, workspaceId, tenantId, currentUser } =
159
+ useMoveTheWheels();
160
+ const [plan, setPlan] = useState<CoverPlan | null>(null);
161
+ // The plan is fetched on mount, so start in the loading state to show the
162
+ // skeleton on the first render instead of an empty panel.
163
+ const [isLoading, setIsLoading] = useState(true);
164
+ const [error, setError] = useState<Error | null>(null);
165
+ const latest = useRef(0);
166
+ // The in-flight request, aborted when a newer one starts or on unmount.
167
+ const inFlight = useRef<AbortController | null>(null);
168
+ // Re-run the user's last request (not the initial one) when the auth
169
+ // context changes, so a token refresh never resets their settings.
170
+ const lastRequest = useRef(initial);
171
+
172
+ const graphQLOptions = useMemo(
173
+ () => ({
174
+ apiGatewayUrl,
175
+ authToken,
176
+ workspaceToken,
177
+ workspaceId,
178
+ tenantId,
179
+ actorId: currentUser?.id,
180
+ }),
181
+ [apiGatewayUrl, authToken, workspaceToken, workspaceId, tenantId, currentUser?.id]
182
+ );
183
+
184
+ const load = useCallback(
185
+ async (request: CoverPlanRequest) => {
186
+ lastRequest.current = request;
187
+ const id = latest.current + 1;
188
+ latest.current = id;
189
+ inFlight.current?.abort();
190
+ const controller = new AbortController();
191
+ inFlight.current = controller;
192
+ setIsLoading(true);
193
+ setError(null);
194
+ try {
195
+ const data = await executeGraphQL<{ inventoryCoverPlan: CoverPlan }>(
196
+ { ...graphQLOptions, signal: controller.signal },
197
+ COVER_PLAN_QUERY,
198
+ {
199
+ input: {
200
+ warehouseId: request.warehouseId,
201
+ leadTimeWeeks: request.leadTimeWeeks,
202
+ targetCoverWeeks: request.targetCoverWeeks,
203
+ demandChangePct: request.demandChangePct,
204
+ statuses: request.actionOnly ? ACTION_STATUSES : null,
205
+ limit: COVER_PLAN_ROW_LIMIT,
206
+ },
207
+ }
208
+ );
209
+ if (latest.current === id) {
210
+ setPlan(data.inventoryCoverPlan);
211
+ }
212
+ } catch (fetchError) {
213
+ if (latest.current === id && !controller.signal.aborted) {
214
+ setError(
215
+ fetchError instanceof Error
216
+ ? fetchError
217
+ : new Error('Failed to load the stock cover plan')
218
+ );
219
+ }
220
+ } finally {
221
+ if (latest.current === id) {
222
+ setIsLoading(false);
223
+ }
224
+ }
225
+ },
226
+ [graphQLOptions]
227
+ );
228
+
229
+ useEffect(() => {
230
+ void load(lastRequest.current);
231
+ }, [load]);
232
+
233
+ useEffect(
234
+ () => () => {
235
+ // Invalidate and cancel whatever is in flight when the panel unmounts.
236
+ latest.current += 1;
237
+ inFlight.current?.abort();
238
+ },
239
+ []
240
+ );
241
+
242
+ const run = useCallback(
243
+ (request: CoverPlanRequest) => {
244
+ void load(request);
245
+ },
246
+ [load]
247
+ );
248
+
249
+ return { plan, isLoading, error, run };
250
+ }