forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReceiptCaptureFlow.tsx
More file actions
612 lines (562 loc) · 20 KB
/
Copy pathReceiptCaptureFlow.tsx
File metadata and controls
612 lines (562 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
import { useEffect, useMemo, useState } from 'react';
import {
Camera,
CheckCircle2,
FileScan,
PencilLine,
RefreshCcw,
Trash2,
Upload,
} from 'lucide-react';
import { CameraCapture } from '../CameraCapture';
import {
ManualEntryFallback,
ReceiptUpload,
type ManualEntryData,
} from '../ReceiptUpload';
import { ReceiptParserResults } from './ReceiptParserResults';
import type { ParsedItem } from './ParsedItemEditor';
import {
createReceiptOcrProvider,
receiptOcrStrategyFromEnv,
type ReceiptOcrProvider,
} from '../../services/receiptOcrProvider';
import * as api from '../../utils/api-client';
import { draftRegistry } from '../../services/draftRegistry';
const defaultReceiptOcrProvider = createReceiptOcrProvider({
strategy: receiptOcrStrategyFromEnv,
deps: {
uploadReceiptForSplit: api.uploadReceiptForSplit,
fetchReceiptOcrData: api.fetchReceiptOcrData,
fetchReceiptSignedUrl: api.fetchReceiptSignedUrl,
},
});
type FlowStep =
| 'choose'
| 'camera'
| 'upload'
| 'manual'
| 'processing'
| 'review'
| 'complete';
type CaptureMethod = 'camera' | 'upload' | 'manual';
interface ReceiptFlowDraft {
receiptId?: string;
step: FlowStep;
method: CaptureMethod;
imageUrl?: string;
imageName?: string;
merchant?: string;
receiptTotal: number;
items: ParsedItem[];
manualEntry?: ManualEntryData;
progress: number;
progressLabel?: string;
error?: string;
updatedAt: string;
}
export interface ReceiptCaptureFlowResult {
imageUrl?: string;
items: ParsedItem[];
receiptTotal: number;
merchant?: string;
manualEntry?: ManualEntryData;
}
interface ReceiptCaptureFlowProps {
splitId: string;
currency: string;
onApply: (result: ReceiptCaptureFlowResult) => void;
/** Injected OCR boundary (defaults to env-driven transport or simulate strategy). */
ocrProvider?: ReceiptOcrProvider;
}
const createEmptyDraft = (): ReceiptFlowDraft => ({
step: 'choose',
method: 'camera',
receiptTotal: 0,
items: [],
progress: 0,
updatedAt: new Date().toISOString(),
});
const readFileAsDataUrl = (file: File) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
if (typeof reader.result === 'string') {
resolve(reader.result);
return;
}
reject(new Error('Unable to preview the selected receipt'));
};
reader.onerror = () => reject(new Error('Unable to preview the selected receipt'));
reader.readAsDataURL(file);
});
const loadDraft = (storageKey: string): ReceiptFlowDraft => {
const emptyDraft = createEmptyDraft();
draftRegistry.migrateReceiptDraft(storageKey.replace('receipt:', ''));
const data = draftRegistry.load(storageKey);
if (!data) {
return emptyDraft;
}
const parsed = data as Partial<ReceiptFlowDraft>;
return {
...emptyDraft,
...parsed,
items: Array.isArray(parsed.items) ? parsed.items : [],
progress:
typeof parsed.progress === 'number' ? Math.max(0, parsed.progress) : 0,
updatedAt: parsed.updatedAt ?? emptyDraft.updatedAt,
};
};
const methodLabel: Record<CaptureMethod, string> = {
camera: 'Camera',
upload: 'Upload',
manual: 'Manual',
};
export const ReceiptCaptureFlow = ({
splitId,
currency,
onApply,
ocrProvider = defaultReceiptOcrProvider,
}: ReceiptCaptureFlowProps) => {
const storageKey = useMemo(
() => `receipt:${splitId}`,
[splitId]
);
const [draft, setDraft] = useState<ReceiptFlowDraft>(() => loadDraft(storageKey));
const [isApplying, setIsApplying] = useState(false);
useEffect(() => {
const title = draft.imageName || draft.manualEntry?.merchant || `Receipt Draft ${splitId}`;
draftRegistry.save(storageKey, draft, 'receipt', title);
}, [draft, storageKey, splitId]);
const parsedTotal = useMemo(
() =>
draft.items.reduce((sum, item) => sum + item.quantity * item.price, 0),
[draft.items]
);
const updateDraft = (updater: (current: ReceiptFlowDraft) => ReceiptFlowDraft) => {
setDraft((current) => ({
...updater(current),
updatedAt: new Date().toISOString(),
}));
};
const clearDraft = () => {
const emptyDraft = createEmptyDraft();
draftRegistry.delete(storageKey);
setDraft(emptyDraft);
};
const startMethod = (step: Extract<FlowStep, 'camera' | 'upload' | 'manual'>) => {
updateDraft((current) => ({
...current,
step,
method: step,
error: undefined,
progress: 0,
progressLabel: undefined,
}));
};
const beginProcessing = async ({
method,
file,
}: {
method: CaptureMethod;
file: File;
}) => {
try {
const localPreviewUrl =
file.type.startsWith('image/')
? await readFileAsDataUrl(file)
: undefined;
updateDraft((current) => ({
...current,
step: 'processing',
method,
imageUrl: localPreviewUrl ?? current.imageUrl,
imageName: file.name,
progress: 5,
progressLabel: 'Preparing receipt',
error: undefined,
}));
const processed = await ocrProvider.processUploadedReceiptFile({
splitId,
file,
localPreviewUrl,
onProgress: (progress) => {
updateDraft((current) => ({
...current,
progress: progress.progress,
progressLabel: progress.label,
}));
},
});
updateDraft((current) => ({
...current,
receiptId: processed.receiptId ?? current.receiptId,
step: 'review',
method,
imageUrl: processed.signedPreviewUrl ?? current.imageUrl,
imageName: file.name,
merchant: processed.merchant,
receiptTotal: processed.receiptTotal,
items: processed.items,
progress: 100,
progressLabel: undefined,
error: undefined,
}));
} catch (error) {
updateDraft((current) => ({
...current,
step: method,
method,
error:
api.getApiErrorMessage(error) ||
(error instanceof Error
? error.message
: 'We could not prepare this receipt. Please try again.'),
progress: 0,
progressLabel: undefined,
}));
}
};
const handleCapture = (file: File) => {
void beginProcessing({ method: 'camera', file });
};
const handleFilesChange = (files: File[]) => {
const file = files[0];
if (!file) {
return;
}
void beginProcessing({ method: 'upload', file });
};
const handleManualSubmit = (manualEntry: ManualEntryData) => {
updateDraft((current) => {
const built = ocrProvider.applyManualEntry(manualEntry, {
previousMerchant: current.merchant,
});
return {
...current,
step: 'review',
method: 'manual',
items: built.items,
receiptTotal: built.receiptTotal,
merchant: built.merchant,
manualEntry: built.manualEntry,
progress: 100,
progressLabel: undefined,
error: undefined,
};
});
};
const handleApply = (items: ParsedItem[]) => {
setIsApplying(true);
const normalizedItems = items.filter(
(item) => item.name.trim().length > 0 && item.quantity > 0
);
const receiptTotal =
draft.receiptTotal > 0
? draft.receiptTotal
: normalizedItems.reduce(
(sum, item) => sum + item.quantity * item.price,
0
);
updateDraft((current) => ({
...current,
step: 'complete',
items: normalizedItems,
receiptTotal,
error: undefined,
}));
onApply({
imageUrl: draft.imageUrl,
items: normalizedItems,
receiptTotal,
merchant: draft.merchant,
manualEntry: draft.manualEntry,
});
setIsApplying(false);
};
const canResumeReview = draft.items.length > 0;
const hasDraftContent =
canResumeReview ||
Boolean(draft.imageUrl) ||
Boolean(draft.manualEntry?.amount) ||
Boolean(draft.merchant);
return (
<div className="rounded-3xl border border-gray-200 bg-white shadow-sm overflow-hidden">
<div className="border-b border-gray-100 bg-gradient-to-br from-purple-50 via-white to-blue-50 p-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-purple-600">
Receipt Review Flow
</p>
<h3 className="mt-1 text-xl font-bold text-gray-900">
Capture, scan, correct, and continue
</h3>
<p className="mt-1 text-sm text-gray-600">
Camera capture, upload fallback, OCR review, and manual fixes all live
in one draft-aware flow.
</p>
</div>
<div className="rounded-full border border-purple-100 bg-white px-3 py-1 text-xs font-medium text-gray-600">
{methodLabel[draft.method]} draft
</div>
</div>
{hasDraftContent && draft.step === 'choose' && (
<div className="mt-4 rounded-2xl border border-purple-100 bg-white/90 p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<p className="font-semibold text-gray-900">Draft saved on this device</p>
<p className="text-sm text-gray-600">
Resume where you left off or clear it and start fresh.
</p>
</div>
<div className="flex flex-wrap gap-2">
{canResumeReview && (
<button
type="button"
onClick={() =>
updateDraft((current) => ({
...current,
step: current.step === 'complete' ? 'complete' : 'review',
error: undefined,
}))
}
className="inline-flex min-h-[44px] items-center gap-2 rounded-xl bg-purple-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-purple-700"
>
<RefreshCcw size={16} />
Resume review
</button>
)}
<button
type="button"
onClick={clearDraft}
className="inline-flex min-h-[44px] items-center gap-2 rounded-xl border border-gray-200 px-4 py-2 text-sm font-semibold text-gray-700 transition hover:bg-gray-50"
>
<Trash2 size={16} />
Start over
</button>
</div>
</div>
</div>
)}
</div>
{draft.error && (
<div className="border-b border-red-100 bg-red-50 px-5 py-3 text-sm text-red-700">
{draft.error}
</div>
)}
{draft.step === 'choose' && (
<div className="grid gap-4 p-5 md:grid-cols-3">
<button
type="button"
onClick={() => startMethod('camera')}
className="flex min-h-[180px] flex-col items-start rounded-2xl border border-gray-200 bg-white p-5 text-left transition hover:border-purple-300 hover:bg-purple-50/40"
>
<span className="rounded-2xl bg-purple-100 p-3 text-purple-700">
<Camera size={22} />
</span>
<span className="mt-4 text-lg font-semibold text-gray-900">Use camera</span>
<span className="mt-2 text-sm text-gray-600">
Launch the rear camera, request permission, and compress the photo
before OCR.
</span>
</button>
<button
type="button"
onClick={() => startMethod('upload')}
className="flex min-h-[180px] flex-col items-start rounded-2xl border border-gray-200 bg-white p-5 text-left transition hover:border-purple-300 hover:bg-purple-50/40"
>
<span className="rounded-2xl bg-blue-100 p-3 text-blue-700">
<Upload size={22} />
</span>
<span className="mt-4 text-lg font-semibold text-gray-900">Upload receipt</span>
<span className="mt-2 text-sm text-gray-600">
Fall back to the file picker for an existing receipt image or PDF.
</span>
</button>
<button
type="button"
onClick={() => startMethod('manual')}
className="flex min-h-[180px] flex-col items-start rounded-2xl border border-gray-200 bg-white p-5 text-left transition hover:border-purple-300 hover:bg-purple-50/40"
>
<span className="rounded-2xl bg-amber-100 p-3 text-amber-700">
<PencilLine size={22} />
</span>
<span className="mt-4 text-lg font-semibold text-gray-900">Enter manually</span>
<span className="mt-2 text-sm text-gray-600">
Start from the total and merchant, then refine the parsed items yourself.
</span>
</button>
</div>
)}
{draft.step === 'camera' && (
<div className="space-y-4 p-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<p className="text-lg font-semibold text-gray-900">Capture your receipt</p>
<p className="text-sm text-gray-600">
The camera view requests permission when it opens and compresses the
photo before review.
</p>
</div>
<button
type="button"
onClick={() => updateDraft((current) => ({ ...current, step: 'choose' }))}
className="rounded-xl border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 transition hover:bg-gray-50"
>
Back
</button>
</div>
<CameraCapture onCapture={handleCapture} onError={(error) => {
updateDraft((current) => ({
...current,
error: error.message,
}));
}} />
</div>
)}
{draft.step === 'upload' && (
<div className="space-y-4 p-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<p className="text-lg font-semibold text-gray-900">Upload a receipt</p>
<p className="text-sm text-gray-600">
Use an existing image or PDF if taking a photo is not convenient right now.
</p>
</div>
<button
type="button"
onClick={() => updateDraft((current) => ({ ...current, step: 'choose' }))}
className="rounded-xl border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 transition hover:bg-gray-50"
>
Back
</button>
</div>
<ReceiptUpload
maxFiles={1}
onFilesChange={handleFilesChange}
onManualEntry={handleManualSubmit}
onError={(error) => {
updateDraft((current) => ({
...current,
error: error.message,
}));
}}
/>
</div>
)}
{draft.step === 'manual' && (
<div className="space-y-4 p-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<p className="text-lg font-semibold text-gray-900">Manual receipt details</p>
<p className="text-sm text-gray-600">
We will seed the review with one line item so you can break it down by hand.
</p>
</div>
<button
type="button"
onClick={() => updateDraft((current) => ({ ...current, step: 'choose' }))}
className="rounded-xl border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 transition hover:bg-gray-50"
>
Back
</button>
</div>
<ManualEntryFallback
defaultValues={draft.manualEntry}
onSubmit={handleManualSubmit}
onCancel={() => updateDraft((current) => ({ ...current, step: 'choose' }))}
/>
</div>
)}
{draft.step === 'processing' && (
<div className="space-y-5 p-5">
<div className="flex items-start gap-4 rounded-2xl border border-purple-100 bg-purple-50/70 p-4">
<span className="rounded-2xl bg-white p-3 text-purple-700 shadow-sm">
<FileScan size={20} />
</span>
<div className="min-w-0 flex-1">
<p className="font-semibold text-gray-900">Running OCR review</p>
<p className="mt-1 text-sm text-gray-600">
{draft.progressLabel ?? 'Extracting items from your receipt'}
</p>
<div className="mt-4 h-2 overflow-hidden rounded-full bg-purple-100">
<div
className="h-full rounded-full bg-purple-600 transition-all duration-300"
style={{ width: `${draft.progress}%` }}
/>
</div>
<p className="mt-2 text-sm font-medium text-purple-700">
{draft.progress}% complete
</p>
</div>
</div>
<div className="rounded-2xl border border-gray-200 bg-gray-50 p-4">
<p className="text-sm font-medium text-gray-700">Current source</p>
<p className="mt-1 text-sm text-gray-600">
{draft.imageName ?? draft.manualEntry?.merchant ?? 'Receipt draft'}
</p>
</div>
{draft.imageUrl && (
<img
src={draft.imageUrl}
alt="Receipt preview while OCR is running"
className="max-h-[340px] w-full rounded-2xl border border-gray-200 object-cover"
/>
)}
</div>
)}
{(draft.step === 'review' || draft.step === 'complete') && (
<div className="space-y-4 p-5">
<div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-gray-200 bg-gray-50 px-4 py-3">
<div className="min-w-0">
<p className="font-semibold text-gray-900">
{draft.merchant || 'Receipt review'}
</p>
<p className="text-sm text-gray-600">
{draft.imageName ?? 'Manual entry'} · Parsed subtotal {parsedTotal.toFixed(2)}{' '}
{currency}
</p>
</div>
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={() => updateDraft((current) => ({ ...current, step: 'choose' }))}
className="rounded-xl border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 transition hover:bg-white"
>
Replace receipt
</button>
<button
type="button"
onClick={clearDraft}
className="rounded-xl border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 transition hover:bg-white"
>
Clear draft
</button>
</div>
</div>
{draft.step === 'complete' && (
<div className="flex items-start gap-3 rounded-2xl border border-green-200 bg-green-50 px-4 py-3 text-green-800">
<CheckCircle2 size={20} className="mt-0.5 flex-shrink-0" />
<div>
<p className="font-semibold">Receipt applied to this split</p>
<p className="text-sm">
The reviewed items are now reflected below, and this draft stays here
if you want to reopen it.
</p>
</div>
</div>
)}
<ReceiptParserResults
imageUrl={draft.imageUrl}
items={draft.items}
receiptTotal={draft.receiptTotal || parsedTotal}
currency={currency}
onAccept={handleApply}
onReject={() => updateDraft((current) => ({ ...current, step: 'choose' }))}
isLoading={isApplying}
/>
</div>
)}
</div>
);
};