@burdenoff/microfe-movethewheels 2026.1108.2 → 2026.1108.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.
@@ -2,16 +2,44 @@
2
2
  * DocumentsCard — reuse of the platform Files module (wspace-files-svc).
3
3
  *
4
4
  * Lists the real files tagged for a MoveTheWheels entity (vehicle / driver /
5
- * order) and deep-links to the Files module for uploading and managing them.
6
- * MoveTheWheels does not store documents itself — this is honest cross-module
7
- * reuse. When there are no files (or the query errors), we show an honest empty
8
- * state with a working link to Files rather than any fabricated rows.
5
+ * order / shipment / route) and deep-links to the Files module for uploading
6
+ * and managing them. MoveTheWheels does not store documents itself — this is
7
+ * honest cross-module reuse.
8
+ *
9
+ * Freight document intelligence (BOFF-3892): each document can be read by the
10
+ * shared vision model, which PROPOSES typed fields with per-field confidence.
11
+ * Nothing is written until a human accepts a field — extraction proposes, the
12
+ * human disposes. Accepting a POD field advances the shipment through the
13
+ * normal ShipmentService path; accepting invoice fields records a
14
+ * variance comparison on the Finance page; accepting a BOL tracking number
15
+ * updates the shipment. Everything else records human confirmation for the
16
+ * audit trail.
9
17
  */
10
18
 
11
- import { FileText, ExternalLink, Download, Upload } from 'lucide-react';
12
- import { Card, CardContent, CardHeader, CardTitle, Button } from './ui';
19
+ import { useState } from 'react';
20
+ import { Check, FileSearch, FileText, ExternalLink, Download, Upload } from 'lucide-react';
21
+ import {
22
+ Badge,
23
+ Button,
24
+ Card,
25
+ CardContent,
26
+ CardHeader,
27
+ CardTitle,
28
+ Input,
29
+ Select,
30
+ SelectContent,
31
+ SelectItem,
32
+ SelectTrigger,
33
+ SelectValue,
34
+ } from './ui';
13
35
  import { useMoveTheWheels } from '../providers/MoveTheWheelsProvider';
14
36
  import { useEntityDocuments, type EntityDocumentType } from '../hooks/useEntityDocuments';
37
+ import {
38
+ DOCUMENT_TYPE_OPTIONS,
39
+ useDocumentExtractions,
40
+ type DocumentExtraction,
41
+ type DocumentType,
42
+ } from '../hooks/useDocumentExtractions';
15
43
  import { formatDate } from '../utils/formatters';
16
44
 
17
45
  interface DocumentsCardProps {
@@ -31,6 +59,123 @@ function formatFileSize(bytes: number): string {
31
59
  return `${value.toFixed(value >= 10 || unit === 0 ? 0 : 1)} ${units[unit]}`;
32
60
  }
33
61
 
62
+ function statusLabel(status: DocumentExtraction['status']): string {
63
+ if (status === 'APPLIED') return 'Applied';
64
+ if (status === 'PARTIALLY_APPLIED') return 'Partially applied';
65
+ return 'Proposed';
66
+ }
67
+
68
+ function ExtractionPanel({ fileId }: { fileId: string }) {
69
+ const { extractions, isLoading, error, extracting, extractError, extract, apply } =
70
+ useDocumentExtractions(fileId);
71
+ const [docType, setDocType] = useState<DocumentType>('BILL_OF_LADING');
72
+ const [corrections, setCorrections] = useState<Record<string, string>>({});
73
+ const [applyError, setApplyError] = useState<string | null>(null);
74
+ const latest = extractions[0] ?? null;
75
+
76
+ const acceptField = async (extraction: DocumentExtraction, key: string) => {
77
+ setApplyError(null);
78
+ const corrected = corrections[key]?.trim();
79
+ const correction = corrected ? [{ key, value: corrected }] : null;
80
+ const ok = await apply(extraction.id, [key], correction);
81
+ if (!ok) setApplyError(`Accepting "${key}" failed — refresh and try again`);
82
+ };
83
+
84
+ return (
85
+ <div className="mt-2 space-y-2 border-t border-border-seam pt-2">
86
+ <div className="flex items-center gap-2">
87
+ <Select value={docType} onValueChange={(value) => setDocType(value as DocumentType)}>
88
+ <SelectTrigger className="w-40" aria-label="Document type">
89
+ <SelectValue />
90
+ </SelectTrigger>
91
+ <SelectContent>
92
+ {DOCUMENT_TYPE_OPTIONS.map((option) => (
93
+ <SelectItem key={option.value} value={option.value}>
94
+ {option.label}
95
+ </SelectItem>
96
+ ))}
97
+ </SelectContent>
98
+ </Select>
99
+ <Button
100
+ variant="outline"
101
+ size="sm"
102
+ disabled={extracting}
103
+ onClick={() => void extract(fileId, docType)}
104
+ >
105
+ <FileSearch size={14} /> {extracting ? 'Reading…' : 'Extract fields'}
106
+ </Button>
107
+ </div>
108
+ {(extractError ?? applyError) && (
109
+ <p className="text-sm text-text-danger">{extractError ?? applyError}</p>
110
+ )}
111
+ {isLoading ? (
112
+ <p className="text-sm text-text-secondary">Loading extraction…</p>
113
+ ) : latest ? (
114
+ <div className="space-y-2">
115
+ <div className="flex items-center gap-2 text-sm">
116
+ <Badge variant={latest.status === 'APPLIED' ? 'default' : 'secondary'}>
117
+ {statusLabel(latest.status)}
118
+ </Badge>
119
+ <span className="text-text-secondary">
120
+ {DOCUMENT_TYPE_OPTIONS.find((option) => option.value === latest.docType)?.label} ·{' '}
121
+ {formatDate(latest.createdAt, 'relative')} · {latest.model}
122
+ {latest.costMicroUsd
123
+ ? ` · ${(Number(latest.costMicroUsd) / 1_000_000).toFixed(4)} USD`
124
+ : ''}
125
+ </span>
126
+ </div>
127
+ {error && <p className="text-sm text-text-danger">{error}</p>}
128
+ <ul className="space-y-1" key={latest.id}>
129
+ {latest.fields.map((field) => {
130
+ const accepted = latest.acceptedFields.includes(field.key);
131
+ const corrected = corrections[field.key];
132
+ return (
133
+ <li key={field.key} className="flex items-center gap-2 text-sm">
134
+ <span className="w-40 shrink-0 truncate text-text-secondary" title={field.label}>
135
+ {field.label}
136
+ </span>
137
+ <Input
138
+ className="h-7 flex-1"
139
+ defaultValue={corrected ?? field.value ?? ''}
140
+ placeholder="Not shown on document"
141
+ disabled={accepted}
142
+ onChange={(event) =>
143
+ setCorrections((previous) => ({
144
+ ...previous,
145
+ [field.key]: event.target.value,
146
+ }))
147
+ }
148
+ />
149
+ <span className="w-12 shrink-0 text-right text-text-secondary">
150
+ {Math.round(field.confidence * 100)}%
151
+ </span>
152
+ {accepted ? (
153
+ <Badge variant="outline" className="flex items-center gap-1">
154
+ <Check size={12} /> Accepted
155
+ </Badge>
156
+ ) : (
157
+ <Button
158
+ variant="ghost"
159
+ size="sm"
160
+ onClick={() => void acceptField(latest, field.key)}
161
+ >
162
+ <Check size={14} /> Accept
163
+ </Button>
164
+ )}
165
+ </li>
166
+ );
167
+ })}
168
+ </ul>
169
+ <p className="text-xs text-text-secondary">
170
+ Accepting writes only what that field maps to — a delivery time closes the shipment,
171
+ invoice lines reconcile on Finance. Editing a value first corrects it on acceptance.
172
+ </p>
173
+ </div>
174
+ ) : null}
175
+ </div>
176
+ );
177
+ }
178
+
34
179
  export function DocumentsCard({ entityType, entityId }: DocumentsCardProps) {
35
180
  const { navigate } = useMoveTheWheels();
36
181
  const { documents, hasMore, isLoading, loadMore } = useEntityDocuments(entityType, entityId);
@@ -56,30 +201,30 @@ export function DocumentsCard({ entityType, entityId }: DocumentsCardProps) {
56
201
  ) : documents.length > 0 ? (
57
202
  <div className="space-y-3">
58
203
  {documents.map((doc) => (
59
- <div
60
- key={doc.id}
61
- className="flex items-center justify-between gap-3 p-3 border rounded-lg"
62
- >
63
- <div className="min-w-0">
64
- <p className="font-medium truncate">{doc.name}</p>
65
- <p className="text-sm text-text-secondary">
66
- {formatFileSize(doc.size)} · {formatDate(doc.createdAt, 'relative')}
67
- </p>
204
+ <div key={doc.id} className="p-3 border rounded-lg">
205
+ <div className="flex items-center justify-between gap-3">
206
+ <div className="min-w-0">
207
+ <p className="font-medium truncate">{doc.name}</p>
208
+ <p className="text-sm text-text-secondary">
209
+ {formatFileSize(doc.size)} · {formatDate(doc.createdAt, 'relative')}
210
+ </p>
211
+ </div>
212
+ {doc.downloadUrl ? (
213
+ <a
214
+ href={doc.downloadUrl}
215
+ target="_blank"
216
+ rel="noopener noreferrer"
217
+ className="shrink-0 inline-flex items-center gap-1 text-sm text-primary hover:underline"
218
+ >
219
+ <Download size={14} /> Open
220
+ </a>
221
+ ) : (
222
+ <Button variant="ghost" size="sm" onClick={openFiles}>
223
+ <ExternalLink size={14} /> View
224
+ </Button>
225
+ )}
68
226
  </div>
69
- {doc.downloadUrl ? (
70
- <a
71
- href={doc.downloadUrl}
72
- target="_blank"
73
- rel="noopener noreferrer"
74
- className="shrink-0 inline-flex items-center gap-1 text-sm text-primary hover:underline"
75
- >
76
- <Download size={14} /> Open
77
- </a>
78
- ) : (
79
- <Button variant="ghost" size="sm" onClick={openFiles}>
80
- <ExternalLink size={14} /> View
81
- </Button>
82
- )}
227
+ <ExtractionPanel fileId={doc.id} />
83
228
  </div>
84
229
  ))}
85
230
  {hasMore && (
@@ -0,0 +1,246 @@
1
+ /**
2
+ * useDocumentExtractions — freight document intelligence (BOFF-3892).
3
+ *
4
+ * Lists the extraction runs a platform File has been through and drives the
5
+ * two mutations: mtwExtractDocument (vision model proposes typed fields with
6
+ * per-field confidence, metered on the shared AI runtime) and
7
+ * mtwApplyDocumentExtraction (a human accepts fields per-field; the mapped
8
+ * writes — POD delivery event, invoice comparison, BOL tracking number —
9
+ * happen only then, once each).
10
+ */
11
+
12
+ import { useCallback, useEffect, useMemo, useState } from 'react';
13
+ import { useMoveTheWheels } from '../providers/MoveTheWheelsProvider';
14
+ import { executeGraphQL } from '../utils/graphqlClient';
15
+
16
+ export type DocumentType =
17
+ 'BILL_OF_LADING' | 'PROOF_OF_DELIVERY' | 'CARRIER_INVOICE' | 'PACKING_LIST';
18
+
19
+ export const DOCUMENT_TYPE_OPTIONS: ReadonlyArray<{ value: DocumentType; label: string }> = [
20
+ { value: 'BILL_OF_LADING', label: 'Bill of lading' },
21
+ { value: 'PROOF_OF_DELIVERY', label: 'Proof of delivery' },
22
+ { value: 'CARRIER_INVOICE', label: 'Carrier invoice' },
23
+ { value: 'PACKING_LIST', label: 'Packing list' },
24
+ ];
25
+
26
+ export interface ExtractionField {
27
+ key: string;
28
+ label: string;
29
+ value: string | null;
30
+ confidence: number;
31
+ }
32
+
33
+ export interface DocumentExtraction {
34
+ id: string;
35
+ fileId: string;
36
+ docType: DocumentType;
37
+ status: 'PROPOSED' | 'PARTIALLY_APPLIED' | 'APPLIED';
38
+ fields: ExtractionField[];
39
+ acceptedFields: string[];
40
+ shipmentId: string | null;
41
+ model: string;
42
+ costMicroUsd: string | null;
43
+ createdAt: Date;
44
+ appliedAt: Date | null;
45
+ appliedBy: string | null;
46
+ }
47
+
48
+ interface ApiExtraction {
49
+ id: string;
50
+ fileId: string;
51
+ docType: DocumentType;
52
+ status: DocumentExtraction['status'];
53
+ fields: ExtractionField[];
54
+ acceptedFields: string[];
55
+ shipmentId: string | null;
56
+ model: string;
57
+ costMicroUsd: string | null;
58
+ createdAt: string;
59
+ appliedAt: string | null;
60
+ appliedBy: string | null;
61
+ }
62
+
63
+ const LIST_QUERY = `
64
+ query MtwDocumentExtractions($fileId: ID!) {
65
+ mtwDocumentExtractions(fileId: $fileId) {
66
+ id
67
+ fileId
68
+ docType
69
+ status
70
+ fields { key label value confidence }
71
+ acceptedFields
72
+ shipmentId
73
+ model
74
+ costMicroUsd
75
+ createdAt
76
+ appliedAt
77
+ appliedBy
78
+ }
79
+ }
80
+ `;
81
+
82
+ const EXTRACT_MUTATION = `
83
+ mutation MtwExtractDocument($fileId: ID!, $docType: MtwDocumentType!) {
84
+ mtwExtractDocument(fileId: $fileId, docType: $docType) {
85
+ id
86
+ fileId
87
+ docType
88
+ status
89
+ fields { key label value confidence }
90
+ acceptedFields
91
+ shipmentId
92
+ model
93
+ costMicroUsd
94
+ createdAt
95
+ appliedAt
96
+ appliedBy
97
+ }
98
+ }
99
+ `;
100
+
101
+ const APPLY_MUTATION = `
102
+ mutation MtwApplyDocumentExtraction($extractionId: ID!, $accept: [String!]!, $corrections: [MtwExtractionCorrectionInput!]) {
103
+ mtwApplyDocumentExtraction(extractionId: $extractionId, accept: $accept, corrections: $corrections) {
104
+ id
105
+ status
106
+ fields { key label value confidence }
107
+ acceptedFields
108
+ appliedAt
109
+ appliedBy
110
+ }
111
+ }
112
+ `;
113
+
114
+ function mapExtraction(raw: ApiExtraction): DocumentExtraction {
115
+ return {
116
+ ...raw,
117
+ createdAt: new Date(raw.createdAt),
118
+ appliedAt: raw.appliedAt ? new Date(raw.appliedAt) : null,
119
+ };
120
+ }
121
+
122
+ export interface UseDocumentExtractionsResult {
123
+ extractions: DocumentExtraction[];
124
+ isLoading: boolean;
125
+ error: string | null;
126
+ extracting: boolean;
127
+ extractError: string | null;
128
+ extract: (fileId: string, docType: DocumentType) => Promise<DocumentExtraction | null>;
129
+ apply: (
130
+ extractionId: string,
131
+ accept: string[],
132
+ corrections: Array<{ key: string; value: string }> | null
133
+ ) => Promise<boolean>;
134
+ refetch: () => void;
135
+ }
136
+
137
+ export function useDocumentExtractions(fileId: string | undefined): UseDocumentExtractionsResult {
138
+ const { apiGatewayUrl, authToken, workspaceToken, workspaceId, tenantId, currentUser } =
139
+ useMoveTheWheels();
140
+ const [extractions, setExtractions] = useState<DocumentExtraction[]>([]);
141
+ const [isLoading, setIsLoading] = useState(false);
142
+ const [error, setError] = useState<string | null>(null);
143
+ const [extracting, setExtracting] = useState(false);
144
+ const [extractError, setExtractError] = useState<string | null>(null);
145
+
146
+ const graphQLOptions = useMemo(
147
+ () => ({
148
+ apiGatewayUrl,
149
+ authToken,
150
+ workspaceToken,
151
+ workspaceId,
152
+ tenantId,
153
+ actorId: currentUser?.id,
154
+ }),
155
+ [apiGatewayUrl, authToken, workspaceToken, workspaceId, tenantId, currentUser?.id]
156
+ );
157
+
158
+ const load = useCallback(async () => {
159
+ if (!fileId) {
160
+ setExtractions([]);
161
+ return;
162
+ }
163
+ setIsLoading(true);
164
+ setError(null);
165
+ try {
166
+ const data = await executeGraphQL<{ mtwDocumentExtractions: ApiExtraction[] }>(
167
+ graphQLOptions,
168
+ LIST_QUERY,
169
+ { fileId }
170
+ );
171
+ setExtractions((data.mtwDocumentExtractions ?? []).map(mapExtraction));
172
+ } catch (loadError) {
173
+ setError(loadError instanceof Error ? loadError.message : 'Failed to load extractions');
174
+ setExtractions([]);
175
+ } finally {
176
+ setIsLoading(false);
177
+ }
178
+ }, [fileId, graphQLOptions]);
179
+
180
+ useEffect(() => {
181
+ void load();
182
+ }, [load]);
183
+
184
+ const extract = useCallback(
185
+ async (targetFileId: string, docType: DocumentType): Promise<DocumentExtraction | null> => {
186
+ setExtracting(true);
187
+ setExtractError(null);
188
+ try {
189
+ const data = await executeGraphQL<{ mtwExtractDocument: ApiExtraction }>(
190
+ graphQLOptions,
191
+ EXTRACT_MUTATION,
192
+ { fileId: targetFileId, docType }
193
+ );
194
+ const created = mapExtraction(data.mtwExtractDocument);
195
+ setExtractions((previous) => [
196
+ created,
197
+ ...previous.filter((item) => item.id !== created.id),
198
+ ]);
199
+ return created;
200
+ } catch (extractFailure) {
201
+ setExtractError(
202
+ extractFailure instanceof Error ? extractFailure.message : 'Extraction failed'
203
+ );
204
+ return null;
205
+ } finally {
206
+ setExtracting(false);
207
+ }
208
+ },
209
+ [graphQLOptions]
210
+ );
211
+
212
+ const apply = useCallback(
213
+ async (
214
+ extractionId: string,
215
+ accept: string[],
216
+ corrections: Array<{ key: string; value: string }> | null
217
+ ): Promise<boolean> => {
218
+ try {
219
+ const data = await executeGraphQL<{ mtwApplyDocumentExtraction: ApiExtraction }>(
220
+ graphQLOptions,
221
+ APPLY_MUTATION,
222
+ { extractionId, accept, corrections }
223
+ );
224
+ const updated = mapExtraction(data.mtwApplyDocumentExtraction);
225
+ setExtractions((previous) =>
226
+ previous.map((item) => (item.id === updated.id ? { ...item, ...updated } : item))
227
+ );
228
+ return true;
229
+ } catch {
230
+ return false;
231
+ }
232
+ },
233
+ [graphQLOptions]
234
+ );
235
+
236
+ return {
237
+ extractions,
238
+ isLoading,
239
+ error,
240
+ extracting,
241
+ extractError,
242
+ extract,
243
+ apply,
244
+ refetch: () => void load(),
245
+ };
246
+ }
@@ -2,10 +2,10 @@
2
2
  * useEntityDocuments — real document listing via wspace-files-svc.
3
3
  *
4
4
  * MoveTheWheels does NOT own a Document model. Documents attached to a vehicle,
5
- * driver or order live in the platform Files module (wspace-files-svc), which
6
- * federates into the same workspace gateway. We tag each uploaded file with two
7
- * marqueue entity tags — `mtwEntityType` and `mtwEntityId` — and list them back
8
- * here through `getFiles(filter:{ tags:[...] })`.
5
+ * driver, order, shipment or route live in the platform Files module
6
+ * (wspace-files-svc), which federates into the same workspace gateway. We tag
7
+ * each uploaded file with two marqueue entity tags — `mtwEntityType` and
8
+ * `mtwEntityId` — and list them back here through `getFiles(filter:{ tags:[...] })`.
9
9
  *
10
10
  * There is no upload UI here (out of scope): uploading/managing happens in the
11
11
  * Files module, deep-linked from DocumentsCard. This hook is read-only.
@@ -31,7 +31,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
31
31
  import { useMoveTheWheels } from '../providers/MoveTheWheelsProvider';
32
32
  import { executeGraphQL } from '../utils/graphqlClient';
33
33
 
34
- export type EntityDocumentType = 'vehicle' | 'driver' | 'order';
34
+ export type EntityDocumentType = 'vehicle' | 'driver' | 'order' | 'shipment' | 'route';
35
35
 
36
36
  export interface EntityDocument {
37
37
  id: string;
@@ -20,6 +20,7 @@ import {
20
20
  } from 'lucide-react';
21
21
  import { PageLayout, PageSection, EmptyState, LoadingState } from '../components/PageLayout';
22
22
  import { FormError } from '../components/FormError';
23
+ import { DocumentsCard } from '../components/DocumentsCard';
23
24
  import {
24
25
  Card,
25
26
  CardContent,
@@ -578,6 +579,7 @@ export default function MultiModalShipmentPage() {
578
579
  );
579
580
  })}
580
581
  </div>
582
+ <DocumentsCard entityType="shipment" entityId={shipment.id} />
581
583
  </CardContent>
582
584
  </Card>
583
585
  ))}
@@ -51,6 +51,7 @@ import { RouteMap, type RouteStop as MapRouteStop } from '../components/maps';
51
51
  import { firstRealLatLng } from '../utils/mapMarkers';
52
52
  import { EntityCombobox } from '../components/EntityCombobox';
53
53
  import { useRoute, useRoutes } from '../hooks/useRoutes';
54
+ import { DocumentsCard } from '../components/DocumentsCard';
54
55
  import { useVehicles, useVehicle, useDrivers, useDriver } from '../hooks/useFleet';
55
56
  import { useAssignmentSuggestions } from '../hooks/useFleetIntelligence';
56
57
  import { useRefetchOnLeaveEdit } from '../hooks/useRefetchOnLeaveEdit';
@@ -702,6 +703,7 @@ export default function RouteDetailsPage() {
702
703
  </div>
703
704
 
704
705
  <div className="space-y-6">
706
+ <DocumentsCard entityType="route" entityId={route.id} />
705
707
  {(route.status === 'planned' || route.status === 'in_progress') && (
706
708
  <AssignmentSuggestions
707
709
  suggestions={suggestions.data}