@burdenoff/microfe-movethewheels 2026.1101.1 → 2026.1101.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.
@@ -1,460 +1,545 @@
1
1
  /**
2
- * Delivery Capture Page — driver-facing electronic proof-of-delivery (ePOD)
3
- * capture flow (BOFF-4399).
2
+ * My Deliveries — the driver-facing mobile task list (BOFF-3991), built on
3
+ * the electronic proof-of-delivery capture core from BOFF-4399.
4
4
  *
5
- * Lists the calling driver's own delivery jobs still awaiting capture
6
- * (`myPendingEpodDeliveryJobs`, Type C self-list — no other driver's jobs are
7
- * ever visible here) and lets them capture: recipient name, signature
8
- * (drawn or typed), an optional delivery photo (uploaded via the platform
9
- * files primitive), device GPS if available, and notes. Submitting calls
10
- * `captureEpod`, which the backend owner-verifies against the assigned
11
- * driver and marks the job DELIVERED.
5
+ * Shows the calling driver's stops for a day (`myDeliveryDay`, a Type C
6
+ * self-list: no other driver's jobs are ever visible here) in driving
7
+ * sequence with progress, the next stop, turn-by-turn hand-off to the
8
+ * device's maps app (one stop, or the remaining stops as a route), a stop
9
+ * detail screen with recipient contact and delivery instructions, and the
10
+ * ePOD capture form. The layout is single-column and touch-sized so it works
11
+ * as the driver surface inside the Capacitor mobile build and on a phone
12
+ * browser.
12
13
  *
13
- * Deferred (see BOFF-4399 follow-up notes): barcode/RFID scan-based capture,
14
- * multi-language delivery instructions, and the full standalone mobile
15
- * driver app (BOFF-3991) — this page is the capture core, reachable from the
16
- * existing web MFE.
14
+ * Offline: the last loaded day stays on screen and a banner explains that
15
+ * capture is paused. Capture is deliberately not queued offline — it needs
16
+ * the live linked shipment status and an acknowledged server write
17
+ * (see EpodCaptureForm).
17
18
  */
18
- import { useEffect, useRef, useState } from 'react';
19
+ import { useEffect, useMemo, useRef, useState } from 'react';
19
20
  import {
21
+ AlertTriangle,
22
+ ArrowLeft,
23
+ CalendarDays,
20
24
  CheckCircle2,
21
- Loader2,
22
- MapPin,
23
- Package,
24
- PenLine,
25
- Truck,
26
- Type as TypeIcon,
27
- Upload,
28
25
  ChevronLeft,
29
26
  ChevronRight,
27
+ Clock,
28
+ Navigation,
29
+ Package,
30
+ Phone,
31
+ RefreshCw,
32
+ Route as RouteIcon,
33
+ Truck,
34
+ WifiOff,
30
35
  } from 'lucide-react';
31
36
  import { PageLayout } from '../components/PageLayout';
32
- import {
33
- Button,
34
- Card,
35
- CardContent,
36
- CardHeader,
37
- CardTitle,
38
- Input,
39
- Label,
40
- Textarea,
41
- } from '../components/ui';
42
- import { SignaturePad, type SignaturePadHandle } from '../components/SignaturePad';
43
- import { StatusBadge, PriorityBadge } from '../components/StatusBadge';
44
- import { mapOrderPriority, mapOrderStatus } from '../hooks/useOrders';
37
+ import { Badge, Button, Card, CardContent, Input, Progress } from '../components/ui';
38
+ import { PriorityBadge } from '../components/StatusBadge';
39
+ import { EpodCaptureForm } from '../components/EpodCaptureForm';
45
40
  import { FormError } from '../components/FormError';
46
41
  import { Notice, useNotice } from '../components/Notice';
42
+ import { mapOrderPriority } from '../hooks/useOrders';
43
+ import type { PendingEpodDeliveryJob } from '../hooks/useEpod';
44
+ import {
45
+ useMyDeliveryDay,
46
+ useOnlineStatus,
47
+ type DriverStop,
48
+ type DriverStopState,
49
+ } from '../hooks/useDriverDay';
47
50
  import {
48
- useCaptureEpod,
49
- useEpodPhotoUpload,
50
- useMyPendingEpodDeliveryJobs,
51
- type PendingEpodDeliveryJob,
52
- } from '../hooks/useEpod';
53
- import { formatAddress, formatDate } from '../utils/formatters';
54
- import type { SignatureType } from '../types';
55
- import { useShipmentStatusQuery } from '../hooks/useShipmentStatusAuthority';
56
- import { StatusAuthorityOwnedDeliveryDocument } from '../../generated/shipment-status-authority-operations';
57
- import type { StatusAuthorityOwnedDeliveryQuery } from '../../generated/shipment-status-authority-operations';
51
+ formatLocalDay,
52
+ localDateString,
53
+ phoneHref,
54
+ routeNavigationUrl,
55
+ shiftLocalDate,
56
+ stopNavigationUrl,
57
+ } from '../utils/driverNavigation';
58
+ import { formatAddress, formatDate, formatTime } from '../utils/formatters';
58
59
  import { useMoveTheWheels } from '../providers/MoveTheWheelsProvider';
59
60
 
60
- /** Resolves the device's current position, if the browser grants it. Never blocks submission. */
61
- function getCurrentPosition(): Promise<GeolocationPosition | null> {
62
- return new Promise((resolve) => {
63
- if (!navigator.geolocation) {
64
- resolve(null);
65
- return;
66
- }
67
- navigator.geolocation.getCurrentPosition(
68
- (position) => resolve(position),
69
- () => resolve(null),
70
- { enableHighAccuracy: true, timeout: 8000, maximumAge: 30000 }
71
- );
72
- });
73
- }
74
-
75
- function CaptureForm({
76
- job,
77
- onCaptured,
78
- onCancel,
79
- }: {
80
- job: PendingEpodDeliveryJob;
81
- onCaptured: (deliveryJobId: string) => void;
82
- onCancel: () => void;
83
- }) {
84
- const { captureEpod, isSubmitting, error: captureError, captureFeedback } = useCaptureEpod();
85
- const [statusRefresh, setStatusRefresh] = useState(0);
86
- const ownedStatus = useShipmentStatusQuery<StatusAuthorityOwnedDeliveryQuery>(
87
- StatusAuthorityOwnedDeliveryDocument,
88
- { deliveryJobId: job.id },
89
- statusRefresh
90
- );
91
- const [completionAttestation, setCompletionAttestation] = useState(false);
92
- const uploadedPhoto = useRef<{ file: File; id: string } | null>(null);
93
- const submissionLock = useRef(false);
94
- const active = useRef(true);
95
- useEffect(() => {
96
- active.current = true;
97
- return () => {
98
- active.current = false;
99
- };
100
- }, []);
101
- const [preparing, setPreparing] = useState(false);
102
- const [requiredStatusRefresh, setRequiredStatusRefresh] = useState(0);
103
- const { upload: uploadPhoto, isUploading, error: uploadError } = useEpodPhotoUpload();
104
- const signaturePadRef = useRef<SignaturePadHandle>(null);
105
-
106
- const [recipientName, setRecipientName] = useState('');
107
- const [signatureType, setSignatureType] = useState<SignatureType>('drawn');
108
- const [typedSignature, setTypedSignature] = useState('');
109
- const [photoFile, setPhotoFile] = useState<File | null>(null);
110
- const [notes, setNotes] = useState('');
111
- const [validationError, setValidationError] = useState<string | null>(null);
61
+ type StopFilter = 'all' | 'remaining' | 'completed';
112
62
 
113
- const handleSubmit = async () => {
114
- if (submissionLock.current) return;
115
- setValidationError(null);
116
- if (
117
- ownedStatus.loading ||
118
- ownedStatus.error ||
119
- !ownedStatus.data ||
120
- statusRefresh < requiredStatusRefresh ||
121
- !completionAttestation ||
122
- captureFeedback?.kind === 'UNKNOWN'
123
- ) {
124
- setValidationError(
125
- 'Review the current linked shipment status and confirm completion before capture. Do not resend an uncertain capture.'
126
- );
127
- return;
128
- }
63
+ type View = { kind: 'list' } | { kind: 'stop'; jobId: string } | { kind: 'capture'; jobId: string };
129
64
 
130
- const trimmedRecipient = recipientName.trim();
131
- if (!trimmedRecipient) {
132
- setValidationError('Recipient name is required.');
133
- return;
134
- }
65
+ const STATE_LABEL: Record<DriverStopState, string> = {
66
+ COMPLETED: 'Delivered',
67
+ EN_ROUTE: 'En route',
68
+ UPCOMING: 'Upcoming',
69
+ FAILED: 'Not delivered',
70
+ };
135
71
 
136
- const signatureData =
137
- signatureType === 'typed'
138
- ? typedSignature.trim()
139
- : (signaturePadRef.current?.toDataUrl() ?? null);
140
- if (!signatureData) {
141
- setValidationError(
142
- signatureType === 'typed'
143
- ? 'Type the recipient full name as their signature.'
144
- : 'A signature is required.'
145
- );
146
- return;
147
- }
72
+ const STATE_VARIANT: Record<DriverStopState, 'default' | 'secondary' | 'destructive' | 'outline'> =
73
+ {
74
+ COMPLETED: 'secondary',
75
+ EN_ROUTE: 'default',
76
+ UPCOMING: 'outline',
77
+ FAILED: 'destructive',
78
+ };
148
79
 
149
- submissionLock.current = true;
150
- setPreparing(true);
151
- try {
152
- let photoFileIds: string[] | undefined;
153
- if (photoFile) {
154
- if (uploadedPhoto.current?.file === photoFile) photoFileIds = [uploadedPhoto.current.id];
155
- else {
156
- const uploaded = await uploadPhoto(photoFile);
157
- uploadedPhoto.current = { file: photoFile, id: uploaded.fileId };
158
- photoFileIds = [uploaded.fileId];
159
- }
160
- }
80
+ function isDone(stop: DriverStop): boolean {
81
+ return stop.state === 'COMPLETED' || stop.state === 'FAILED';
82
+ }
161
83
 
162
- if (!active.current) return;
163
- const position = await getCurrentPosition();
164
- if (!active.current) return;
84
+ function toCaptureJob(stop: DriverStop): PendingEpodDeliveryJob {
85
+ return {
86
+ id: stop.jobId,
87
+ deliveryJobNumber: stop.deliveryJobNumber,
88
+ status: stop.status,
89
+ priority: stop.priority,
90
+ deliveryAddress: stop.deliveryAddress,
91
+ scheduledDelivery: stop.scheduledDelivery,
92
+ customerName: stop.customerName,
93
+ customerPhone: stop.customerPhone,
94
+ };
95
+ }
165
96
 
166
- const proof = await captureEpod({
167
- expectedShipmentId: ownedStatus.data.myEpodShipmentStatus?.id ?? null,
168
- expectedShipmentStatusRevision: ownedStatus.data.myEpodShipmentStatus?.statusRevision,
169
- completionAttestation,
170
- deliveryJobId: job.id,
171
- recipientName: trimmedRecipient,
172
- signatureType,
173
- signatureData,
174
- photoFileIds,
175
- latitude: position?.coords.latitude,
176
- longitude: position?.coords.longitude,
177
- locationAccuracy: position?.coords.accuracy,
178
- notes: notes.trim() || undefined,
179
- });
97
+ function openExternal(url: string | null) {
98
+ if (url) window.open(url, '_blank', 'noopener,noreferrer');
99
+ }
180
100
 
181
- if (!active.current) return;
182
- onCaptured(proof.deliveryJobId);
183
- } catch {
184
- setCompletionAttestation(false);
185
- setRequiredStatusRefresh(statusRefresh + 1);
186
- // captureError / uploadError already carry the message for display below.
187
- } finally {
188
- submissionLock.current = false;
189
- setPreparing(false);
190
- }
191
- };
101
+ function StopStateBadge({ state }: { state: DriverStopState }) {
102
+ return <Badge variant={STATE_VARIANT[state]}>{STATE_LABEL[state]}</Badge>;
103
+ }
192
104
 
193
- const submitting = isSubmitting || isUploading || preparing;
105
+ function SequenceMarker({ stop }: { stop: DriverStop }) {
106
+ const done = isDone(stop);
107
+ return (
108
+ <span
109
+ aria-hidden="true"
110
+ className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full border text-sm font-semibold ${
111
+ stop.state === 'EN_ROUTE'
112
+ ? 'border-primary bg-primary text-primary-foreground'
113
+ : done
114
+ ? 'border-border bg-surface-secondary text-text-secondary'
115
+ : 'border-border bg-surface text-text-primary'
116
+ }`}
117
+ >
118
+ {stop.state === 'COMPLETED' ? <CheckCircle2 size={16} /> : stop.sequence}
119
+ </span>
120
+ );
121
+ }
194
122
 
123
+ function StopCard({
124
+ stop,
125
+ onOpen,
126
+ onCapture,
127
+ offline,
128
+ }: {
129
+ stop: DriverStop;
130
+ onOpen: () => void;
131
+ onCapture: () => void;
132
+ offline: boolean;
133
+ }) {
195
134
  return (
196
135
  <Card>
197
- <CardHeader>
198
- <CardTitle className="flex items-center gap-2">
199
- <Truck size={18} /> Capture delivery for {job.deliveryJobNumber}
200
- </CardTitle>
201
- </CardHeader>
202
- <CardContent className="space-y-4">
203
- <div className="text-sm text-text-secondary space-y-1">
204
- {job.customerName && <p>Recipient on file: {job.customerName}</p>}
205
- {job.deliveryAddress && <p>{formatAddress(job.deliveryAddress)}</p>}
206
- </div>
207
- <section aria-label="Linked shipment status" className="space-y-2">
208
- <p>
209
- Recorded shipment:{' '}
210
- {ownedStatus.data?.myEpodShipmentStatus
211
- ? `${ownedStatus.data.myEpodShipmentStatus.status.toLowerCase().replaceAll('_', ' ')} · revision ${ownedStatus.data.myEpodShipmentStatus.statusRevision}`
212
- : ownedStatus.data
213
- ? 'No linked shipment'
214
- : 'Loading current record'}
136
+ <CardContent className="flex items-start gap-3 py-4">
137
+ <SequenceMarker stop={stop} />
138
+ <button
139
+ type="button"
140
+ onClick={onOpen}
141
+ aria-label={`Stop ${stop.sequence}, ${stop.deliveryJobNumber}, open details`}
142
+ className="min-w-0 flex-1 text-left"
143
+ >
144
+ <div className="flex flex-wrap items-center gap-1.5">
145
+ <span className="font-medium">Stop {stop.sequence}</span>
146
+ <StopStateBadge state={stop.state} />
147
+ {stop.overdue && <Badge variant="destructive">Overdue</Badge>}
148
+ </div>
149
+ {stop.deliveryAddress && (
150
+ <p className="mt-1 text-sm text-text-secondary">
151
+ {formatAddress(stop.deliveryAddress)}
152
+ </p>
153
+ )}
154
+ <p className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs text-text-secondary">
155
+ {stop.scheduledDelivery && (
156
+ <span className="flex items-center gap-1">
157
+ <Clock size={12} /> {formatTime(stop.scheduledDelivery)}
158
+ </span>
159
+ )}
160
+ <span className="flex items-center gap-1">
161
+ <Package size={12} /> {stop.deliveryJobNumber}
162
+ </span>
163
+ {stop.routeName && (
164
+ <span className="flex items-center gap-1">
165
+ <RouteIcon size={12} /> {stop.routeName}
166
+ </span>
167
+ )}
215
168
  </p>
216
- {ownedStatus.error && <p role="alert">{ownedStatus.error}</p>}
217
- <Button
218
- variant="outline"
219
- disabled={ownedStatus.loading || submitting}
220
- onClick={() => {
221
- setCompletionAttestation(false);
222
- setStatusRefresh((value) => value + 1);
223
- }}
224
- >
225
- Refresh linked status
169
+ </button>
170
+ {stop.awaitingCapture && (
171
+ <Button type="button" size="sm" onClick={onCapture} disabled={offline}>
172
+ Capture
226
173
  </Button>
227
- <label className="flex items-start gap-2">
228
- <input
229
- type="checkbox"
230
- checked={completionAttestation}
231
- disabled={
232
- ownedStatus.loading ||
233
- !!ownedStatus.error ||
234
- submitting ||
235
- statusRefresh < requiredStatusRefresh ||
236
- captureFeedback?.kind === 'UNKNOWN'
237
- }
238
- onChange={(event) => setCompletionAttestation(event.target.checked)}
239
- />
240
- I reviewed the recorded linked status and attest to this delivery completion.
241
- </label>
242
- <p>
243
- This records an assigned driver's attestation; it does not independently verify physical
244
- freight movement.
245
- </p>
246
- {captureFeedback && <p role="status">{captureFeedback.message}</p>}
247
- </section>
174
+ )}
175
+ </CardContent>
176
+ </Card>
177
+ );
178
+ }
248
179
 
249
- <div className="space-y-1.5">
250
- <Label htmlFor="epod-recipient-name">Recipient name</Label>
251
- <Input
252
- id="epod-recipient-name"
253
- value={recipientName}
254
- onChange={(event) => setRecipientName(event.target.value)}
255
- placeholder="Who received the delivery?"
256
- />
257
- </div>
180
+ function StopDetail({
181
+ stop,
182
+ onBack,
183
+ onCapture,
184
+ offline,
185
+ }: {
186
+ stop: DriverStop;
187
+ onBack: () => void;
188
+ onCapture: () => void;
189
+ offline: boolean;
190
+ }) {
191
+ const navigateUrl = stopNavigationUrl(stop.deliveryAddress);
192
+ const callUrl = phoneHref(stop.customerPhone);
193
+ return (
194
+ <div className="space-y-4">
195
+ <Button type="button" variant="ghost" size="sm" onClick={onBack}>
196
+ <ArrowLeft size={16} /> All stops
197
+ </Button>
198
+ <Card>
199
+ <CardContent className="space-y-4 py-5">
200
+ <div className="flex flex-wrap items-center gap-2">
201
+ <SequenceMarker stop={stop} />
202
+ <h2 className="text-lg font-semibold">Stop {stop.sequence}</h2>
203
+ <StopStateBadge state={stop.state} />
204
+ <PriorityBadge priority={mapOrderPriority(stop.priority)} size="sm" />
205
+ {stop.overdue && <Badge variant="destructive">Overdue</Badge>}
206
+ </div>
207
+
208
+ <dl className="grid gap-3 text-sm">
209
+ <div>
210
+ <dt className="text-text-secondary">Deliver to</dt>
211
+ <dd className="font-medium">
212
+ {stop.deliveryAddress ? formatAddress(stop.deliveryAddress) : 'No address on file'}
213
+ </dd>
214
+ </div>
215
+ {stop.customerName && (
216
+ <div>
217
+ <dt className="text-text-secondary">Recipient</dt>
218
+ <dd className="font-medium">{stop.customerName}</dd>
219
+ </div>
220
+ )}
221
+ <div>
222
+ <dt className="text-text-secondary">Order</dt>
223
+ <dd className="font-medium">{stop.deliveryJobNumber}</dd>
224
+ </div>
225
+ {stop.scheduledDelivery && (
226
+ <div>
227
+ <dt className="text-text-secondary">Scheduled</dt>
228
+ <dd className="font-medium">{formatDate(stop.scheduledDelivery, 'full')}</dd>
229
+ </div>
230
+ )}
231
+ {stop.routeName && (
232
+ <div>
233
+ <dt className="text-text-secondary">Route</dt>
234
+ <dd className="font-medium">{stop.routeName}</dd>
235
+ </div>
236
+ )}
237
+ {stop.specialInstructions && (
238
+ <div>
239
+ <dt className="text-text-secondary">Delivery instructions</dt>
240
+ <dd className="whitespace-pre-line">{stop.specialInstructions}</dd>
241
+ </div>
242
+ )}
243
+ {stop.deliveredAt && (
244
+ <div>
245
+ <dt className="text-text-secondary">Proof of delivery captured</dt>
246
+ <dd className="font-medium">{formatDate(stop.deliveredAt, 'full')}</dd>
247
+ </div>
248
+ )}
249
+ </dl>
258
250
 
259
- <div className="space-y-1.5">
260
- <Label>Signature</Label>
261
- <div className="flex gap-2">
251
+ <div className="grid gap-2 sm:grid-cols-2">
262
252
  <Button
263
253
  type="button"
264
- variant={signatureType === 'drawn' ? 'default' : 'outline'}
265
- size="sm"
266
- onClick={() => setSignatureType('drawn')}
254
+ variant="outline"
255
+ disabled={!navigateUrl}
256
+ onClick={() => openExternal(navigateUrl)}
267
257
  >
268
- <PenLine size={14} /> Draw
258
+ <Navigation size={16} /> Navigate
269
259
  </Button>
270
260
  <Button
271
261
  type="button"
272
- variant={signatureType === 'typed' ? 'default' : 'outline'}
273
- size="sm"
274
- onClick={() => setSignatureType('typed')}
262
+ variant="outline"
263
+ disabled={!callUrl}
264
+ onClick={() => {
265
+ if (callUrl) window.location.href = callUrl;
266
+ }}
275
267
  >
276
- <TypeIcon size={14} /> Type name instead
268
+ <Phone size={16} /> Call recipient
277
269
  </Button>
278
270
  </div>
279
- {signatureType === 'drawn' ? (
280
- <SignaturePad ref={signaturePadRef} />
281
- ) : (
282
- <Input
283
- value={typedSignature}
284
- onChange={(event) => setTypedSignature(event.target.value)}
285
- placeholder="Type full name as signature"
286
- />
287
- )}
288
- </div>
289
-
290
- <div className="space-y-1.5">
291
- <Label htmlFor="epod-photo">Delivery photo (optional)</Label>
292
- <div className="flex items-center gap-2">
293
- <input
294
- id="epod-photo"
295
- type="file"
296
- accept="image/*"
297
- capture="environment"
298
- onChange={(event) => setPhotoFile(event.target.files?.[0] ?? null)}
299
- className="text-sm"
300
- />
301
- {photoFile && <Upload size={14} className="text-text-secondary" />}
302
- </div>
303
- {photoFile && <p className="text-xs text-text-secondary">{photoFile.name}</p>}
304
- </div>
305
-
306
- <div className="space-y-1.5">
307
- <Label htmlFor="epod-notes">Notes (optional)</Label>
308
- <Textarea
309
- id="epod-notes"
310
- value={notes}
311
- onChange={(event) => setNotes(event.target.value)}
312
- placeholder="e.g. Left with front desk, gate code used, etc."
313
- rows={2}
314
- />
315
- </div>
316
-
317
- <p className="flex items-center gap-1.5 text-xs text-text-secondary">
318
- <MapPin size={12} /> Device GPS is captured automatically when permitted by the browser.
319
- </p>
320
271
 
321
- {validationError && <FormError message={validationError} />}
322
- {captureError && <FormError message={captureError.message} />}
323
- {uploadError && <FormError message={uploadError.message} />}
324
-
325
- <div className="flex gap-2 justify-end">
326
- <Button type="button" variant="outline" onClick={onCancel} disabled={submitting}>
327
- Cancel
328
- </Button>
329
- <Button
330
- type="button"
331
- onClick={() => void handleSubmit()}
332
- disabled={
333
- submitting ||
334
- ownedStatus.loading ||
335
- !!ownedStatus.error ||
336
- !ownedStatus.data ||
337
- statusRefresh < requiredStatusRefresh ||
338
- !completionAttestation ||
339
- captureFeedback?.kind === 'UNKNOWN'
340
- }
341
- >
342
- {submitting ? (
343
- <>
344
- <Loader2 size={14} className="animate-spin" /> Submitting…
345
- </>
346
- ) : (
347
- <>
348
- <CheckCircle2 size={14} /> Confirm delivery
349
- </>
350
- )}
351
- </Button>
352
- </div>
353
- </CardContent>
354
- </Card>
272
+ {stop.awaitingCapture ? (
273
+ <Button type="button" className="w-full" onClick={onCapture} disabled={offline}>
274
+ <CheckCircle2 size={16} /> Capture proof of delivery
275
+ </Button>
276
+ ) : stop.state === 'UPCOMING' ? (
277
+ <p className="text-sm text-text-secondary">
278
+ Proof of delivery opens once dispatch marks this stop out for delivery.
279
+ </p>
280
+ ) : null}
281
+ </CardContent>
282
+ </Card>
283
+ </div>
355
284
  );
356
285
  }
357
286
 
358
287
  export default function DeliveryCapturePage() {
359
288
  const { workspaceId, tenantId, currentUser, apiGatewayUrl } = useMoveTheWheels();
360
- const [pageIndex, setPageIndex] = useState(0);
361
- const pageSize = 20;
362
- const { jobs, hasMore, isLoading, error, refetch, retireAcknowledgedJob } =
363
- useMyPendingEpodDeliveryJobs({
364
- limit: pageSize,
365
- offset: pageIndex * pageSize,
366
- });
367
- const [selectedJob, setSelectedJob] = useState<PendingEpodDeliveryJob | null>(null);
289
+ const online = useOnlineStatus();
290
+ const offline = !online;
291
+ const [date, setDate] = useState(() => localDateString(new Date()));
292
+ const [filter, setFilter] = useState<StopFilter>('all');
293
+ const [view, setView] = useState<View>({ kind: 'list' });
294
+ const { day, isLoading, error, refetch, markCaptured } = useMyDeliveryDay(date);
368
295
  const { message, notify } = useNotice();
296
+ const today = localDateString(new Date());
297
+
298
+ // Coming back online: refresh so the list reflects anything dispatch changed.
299
+ // Only an offline -> online transition refetches; the hook already loads on
300
+ // mount and whenever the date or scope changes.
301
+ const wasOffline = useRef(false);
302
+ useEffect(() => {
303
+ if (!online) {
304
+ wasOffline.current = true;
305
+ } else if (wasOffline.current) {
306
+ wasOffline.current = false;
307
+ void refetch();
308
+ }
309
+ }, [online, refetch]);
310
+
311
+ const stops = useMemo(() => day?.stops ?? [], [day]);
312
+ const visibleStops = useMemo(
313
+ () =>
314
+ stops.filter((stop) =>
315
+ filter === 'all' ? true : filter === 'completed' ? isDone(stop) : !isDone(stop)
316
+ ),
317
+ [stops, filter]
318
+ );
319
+ const remainingRouteUrl = useMemo(
320
+ () =>
321
+ routeNavigationUrl(stops.filter((stop) => !isDone(stop)).map((stop) => stop.deliveryAddress)),
322
+ [stops]
323
+ );
324
+ const selected =
325
+ view.kind === 'list' ? null : (stops.find((stop) => stop.jobId === view.jobId) ?? null);
369
326
 
370
327
  const handleCaptured = (deliveryJobId: string) => {
371
- retireAcknowledgedJob(deliveryJobId);
328
+ markCaptured(deliveryJobId);
372
329
  notify('Proof of delivery captured — delivery marked complete.');
373
- setSelectedJob(null);
374
- setPageIndex(0);
375
- refetch();
330
+ setView({ kind: 'list' });
331
+ void refetch();
376
332
  };
377
333
 
334
+ const changeDate = (next: string) => {
335
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(next)) return;
336
+ setDate(next);
337
+ setView({ kind: 'list' });
338
+ };
339
+
340
+ const progress = day && day.totalStops > 0 ? (day.completedStops / day.totalStops) * 100 : 0;
341
+
378
342
  return (
379
343
  <PageLayout
380
344
  title="My Deliveries"
381
- subtitle="Capture proof of delivery for your assigned stops"
345
+ subtitle="Your stops for the day, in order — navigate, then capture proof of delivery"
382
346
  icon={<Truck size={24} />}
347
+ maxWidth="2xl"
383
348
  >
384
349
  <div className="space-y-4">
385
350
  <Notice message={message} />
386
351
 
387
- {selectedJob ? (
388
- <CaptureForm
389
- key={`${workspaceId}:${tenantId}:${currentUser?.id}:${apiGatewayUrl}:${selectedJob.id}`}
390
- job={selectedJob}
352
+ {offline && (
353
+ <div
354
+ role="status"
355
+ className="flex items-start gap-2 rounded-md border border-border bg-surface-secondary p-3 text-sm"
356
+ >
357
+ <WifiOff size={16} className="mt-0.5 shrink-0" />
358
+ <span>
359
+ You are offline. Your last loaded stops stay available; reconnect to capture proof of
360
+ delivery.
361
+ </span>
362
+ </div>
363
+ )}
364
+
365
+ {selected && view.kind === 'capture' && selected.awaitingCapture ? (
366
+ <EpodCaptureForm
367
+ key={`${workspaceId}:${tenantId}:${currentUser?.id}:${apiGatewayUrl}:${selected.jobId}`}
368
+ job={toCaptureJob(selected)}
369
+ offline={offline}
391
370
  onCaptured={handleCaptured}
392
- onCancel={() => setSelectedJob(null)}
371
+ onCancel={() => setView({ kind: 'stop', jobId: selected.jobId })}
393
372
  />
394
- ) : isLoading ? (
395
- <p className="text-text-secondary text-center py-8">Loading your deliveries…</p>
396
- ) : error ? (
397
- <FormError message={error.message} />
398
- ) : jobs.length > 0 ? (
399
- <div className="space-y-3">
400
- {jobs.map((job) => (
401
- <Card key={job.id}>
402
- <CardContent className="flex items-center justify-between gap-3 py-4">
403
- <div className="min-w-0">
404
- <p className="font-medium flex items-center gap-2">
405
- <Package size={16} /> {job.deliveryJobNumber}
406
- </p>
407
- {/* Stop state + urgency, straight off the job record — a driver
408
- needs to know which stop is already out for delivery. */}
409
- <div className="flex flex-wrap items-center gap-1.5 py-1">
410
- <StatusBadge status={mapOrderStatus(job.status)} type="order" size="sm" />
411
- <PriorityBadge priority={mapOrderPriority(job.priority)} size="sm" />
412
- </div>
413
- {job.deliveryAddress && (
414
- <p className="text-sm text-text-secondary truncate">
415
- {formatAddress(job.deliveryAddress)}
416
- </p>
417
- )}
418
- {job.scheduledDelivery && (
419
- <p className="text-xs text-text-secondary">
420
- Scheduled {formatDate(job.scheduledDelivery, 'short')}
373
+ ) : selected ? (
374
+ <StopDetail
375
+ stop={selected}
376
+ offline={offline}
377
+ onBack={() => setView({ kind: 'list' })}
378
+ onCapture={() => setView({ kind: 'capture', jobId: selected.jobId })}
379
+ />
380
+ ) : (
381
+ <>
382
+ <div className="flex flex-wrap items-center gap-2">
383
+ <Button
384
+ type="button"
385
+ variant="outline"
386
+ size="sm"
387
+ aria-label="Previous day"
388
+ onClick={() => changeDate(shiftLocalDate(date, -1))}
389
+ >
390
+ <ChevronLeft size={16} />
391
+ </Button>
392
+ <Button
393
+ type="button"
394
+ variant={date === today ? 'default' : 'outline'}
395
+ size="sm"
396
+ onClick={() => changeDate(today)}
397
+ >
398
+ <CalendarDays size={16} /> Today
399
+ </Button>
400
+ <Button
401
+ type="button"
402
+ variant="outline"
403
+ size="sm"
404
+ aria-label="Next day"
405
+ onClick={() => changeDate(shiftLocalDate(date, 1))}
406
+ >
407
+ <ChevronRight size={16} />
408
+ </Button>
409
+ <Input
410
+ type="date"
411
+ aria-label="Delivery date"
412
+ value={date}
413
+ onChange={(event) => changeDate(event.target.value)}
414
+ className="w-auto"
415
+ />
416
+ <Button
417
+ type="button"
418
+ variant="ghost"
419
+ size="sm"
420
+ aria-label="Refresh stops"
421
+ disabled={isLoading || offline}
422
+ onClick={() => void refetch()}
423
+ >
424
+ <RefreshCw size={16} className={isLoading ? 'animate-spin' : undefined} />
425
+ </Button>
426
+ </div>
427
+
428
+ {error && <FormError message={error.message} />}
429
+
430
+ {isLoading && !day ? (
431
+ <p className="py-8 text-center text-text-secondary">Loading your deliveries…</p>
432
+ ) : day && day.driverId === null ? (
433
+ <div className="py-12 text-center">
434
+ <AlertTriangle size={40} className="mx-auto mb-3 text-text-secondary opacity-50" />
435
+ <p className="text-text-secondary">
436
+ Your account is not linked to a driver in this workspace. Ask your dispatcher to
437
+ link your user on the driver profile.
438
+ </p>
439
+ </div>
440
+ ) : day ? (
441
+ <>
442
+ <Card>
443
+ <CardContent className="space-y-3 py-4">
444
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
445
+ <p className="font-medium">
446
+ {day.completedStops} of {day.totalStops} stops done
447
+ {day.driverName ? ` · ${day.driverName}` : ''}
421
448
  </p>
449
+ <p className="text-sm text-text-secondary">{formatLocalDay(date)}</p>
450
+ </div>
451
+ <Progress value={progress} aria-label="Stops completed" />
452
+ {day.nextStop && (
453
+ <div className="rounded-md border border-border p-3">
454
+ <p className="text-xs uppercase tracking-wide text-text-secondary">
455
+ Next stop · Stop {day.nextStop.sequence}
456
+ </p>
457
+ <p className="mt-1 font-medium">
458
+ {day.nextStop.deliveryAddress
459
+ ? formatAddress(day.nextStop.deliveryAddress)
460
+ : day.nextStop.deliveryJobNumber}
461
+ </p>
462
+ {day.nextStop.customerName && (
463
+ <p className="text-sm text-text-secondary">
464
+ Recipient: {day.nextStop.customerName}
465
+ </p>
466
+ )}
467
+ <div className="mt-3 grid gap-2 sm:grid-cols-2">
468
+ <Button
469
+ type="button"
470
+ onClick={() => openExternal(remainingRouteUrl)}
471
+ disabled={!remainingRouteUrl}
472
+ >
473
+ <RouteIcon size={16} /> Start route
474
+ </Button>
475
+ <Button
476
+ type="button"
477
+ variant="outline"
478
+ onClick={() => {
479
+ const next = day.nextStop;
480
+ if (next) setView({ kind: 'stop', jobId: next.jobId });
481
+ }}
482
+ >
483
+ Stop details <ChevronRight size={16} />
484
+ </Button>
485
+ </div>
486
+ </div>
422
487
  )}
488
+ </CardContent>
489
+ </Card>
490
+
491
+ <div role="tablist" aria-label="Filter stops" className="flex gap-2">
492
+ {(
493
+ [
494
+ ['all', `All stops (${day.totalStops})`],
495
+ ['remaining', `Remaining (${day.remainingStops})`],
496
+ ['completed', `Done (${day.completedStops})`],
497
+ ] as const
498
+ ).map(([value, label]) => (
499
+ <Button
500
+ key={value}
501
+ type="button"
502
+ role="tab"
503
+ aria-selected={filter === value}
504
+ size="sm"
505
+ variant={filter === value ? 'default' : 'outline'}
506
+ onClick={() => setFilter(value)}
507
+ >
508
+ {label}
509
+ </Button>
510
+ ))}
511
+ </div>
512
+
513
+ {visibleStops.length > 0 ? (
514
+ <div className="space-y-3">
515
+ {visibleStops.map((stop) => (
516
+ <StopCard
517
+ key={stop.jobId}
518
+ stop={stop}
519
+ offline={offline}
520
+ onOpen={() => setView({ kind: 'stop', jobId: stop.jobId })}
521
+ onCapture={() => setView({ kind: 'capture', jobId: stop.jobId })}
522
+ />
523
+ ))}
423
524
  </div>
424
- <Button type="button" size="sm" onClick={() => setSelectedJob(job)}>
425
- Capture
426
- </Button>
427
- </CardContent>
428
- </Card>
429
- ))}
430
- {(pageIndex > 0 || hasMore) && (
431
- <div className="flex justify-end gap-2 pt-2">
432
- <Button
433
- type="button"
434
- variant="outline"
435
- size="sm"
436
- disabled={pageIndex === 0 || isLoading}
437
- onClick={() => setPageIndex((previous) => Math.max(0, previous - 1))}
438
- >
439
- <ChevronLeft size={16} /> Previous
440
- </Button>
441
- <Button
442
- type="button"
443
- variant="outline"
444
- size="sm"
445
- disabled={!hasMore || isLoading}
446
- onClick={() => setPageIndex((previous) => previous + 1)}
447
- >
448
- Next <ChevronRight size={16} />
449
- </Button>
450
- </div>
451
- )}
452
- </div>
453
- ) : (
454
- <div className="text-center py-12">
455
- <CheckCircle2 size={40} className="mx-auto mb-3 text-text-secondary opacity-50" />
456
- <p className="text-text-secondary">No deliveries awaiting proof of delivery.</p>
457
- </div>
525
+ ) : (
526
+ <div className="py-12 text-center">
527
+ <CheckCircle2
528
+ size={40}
529
+ className="mx-auto mb-3 text-text-secondary opacity-50"
530
+ />
531
+ <p className="text-text-secondary">
532
+ {day.totalStops === 0
533
+ ? 'No deliveries scheduled for this day.'
534
+ : filter === 'completed'
535
+ ? 'No stops completed yet.'
536
+ : 'All stops done for this day.'}
537
+ </p>
538
+ </div>
539
+ )}
540
+ </>
541
+ ) : null}
542
+ </>
458
543
  )}
459
544
  </div>
460
545
  </PageLayout>