Seth commited on
Commit
8aefeb2
·
1 Parent(s): edb8309
frontend/src/components/ExportButtons.jsx CHANGED
@@ -175,1209 +175,3 @@ function objectToXML(obj, rootName = "extraction") {
175
  }
176
 
177
  export default function ExportButtons({ isComplete, extractionResult }) {
178
- const [downloading, setDownloading] = useState(null);
179
- const [copied, setCopied] = useState(false);
180
- const [isShareModalOpen, setIsShareModalOpen] = useState(false);
181
- const [isShareLinkModalOpen, setIsShareLinkModalOpen] = useState(false);
182
- const [shareLink, setShareLink] = useState("");
183
- const [isGeneratingLink, setIsGeneratingLink] = useState(false);
184
-
185
- // Helper function to extract text from fields (same as in ExtractionOutput)
186
- const extractTextFromFields = (fields) => {
187
- if (!fields || typeof fields !== "object") {
188
- return "";
189
- }
190
-
191
- // Check for page_X structure first (preferred format)
192
- const pageKeys = Object.keys(fields).filter(key => key.startsWith("page_"));
193
- if (pageKeys.length > 0) {
194
- // Get text from first page (or combine all pages)
195
- const pageTexts = pageKeys.map(key => {
196
- const page = fields[key];
197
- if (page && page.text) {
198
- return page.text;
199
- }
200
- return "";
201
- }).filter(text => text);
202
-
203
- if (pageTexts.length > 0) {
204
- return pageTexts.join("\n\n");
205
- }
206
- }
207
-
208
- // Fallback to full_text
209
- if (fields.full_text) {
210
- return fields.full_text;
211
- }
212
-
213
- return "";
214
- };
215
-
216
- // Helper function to escape HTML
217
- const escapeHtml = (text) => {
218
- if (!text) return '';
219
- const div = document.createElement('div');
220
- div.textContent = text;
221
- return div.innerHTML;
222
- };
223
-
224
- // Helper function to convert pipe-separated tables to HTML tables
225
- const convertPipeTablesToHTML = (text) => {
226
- if (!text) return text;
227
-
228
- const lines = text.split('\n');
229
- const result = [];
230
- let i = 0;
231
-
232
- while (i < lines.length) {
233
- const line = lines[i];
234
-
235
- // Check if this line looks like a table row (has multiple pipes)
236
- if (line.includes('|') && line.split('|').length >= 3) {
237
- // Check if it's a separator line (only |, -, :, spaces)
238
- const isSeparator = /^[\s|\-:]+$/.test(line.trim());
239
-
240
- if (!isSeparator) {
241
- // Start of a table - collect all table rows
242
- const tableRows = [];
243
- let j = i;
244
-
245
- // Collect header row
246
- const headerLine = lines[j];
247
- const headerCells = headerLine.split('|').map(cell => cell.trim()).filter(cell => cell || cell === '');
248
- // Remove empty cells at start/end
249
- if (headerCells.length > 0 && !headerCells[0]) headerCells.shift();
250
- if (headerCells.length > 0 && !headerCells[headerCells.length - 1]) headerCells.pop();
251
-
252
- if (headerCells.length >= 2) {
253
- tableRows.push(headerCells);
254
- j++;
255
-
256
- // Skip separator line if present
257
- if (j < lines.length && /^[\s|\-:]+$/.test(lines[j].trim())) {
258
- j++;
259
- }
260
-
261
- // Collect data rows
262
- while (j < lines.length) {
263
- const rowLine = lines[j];
264
- if (!rowLine.trim()) break; // Empty line ends table
265
-
266
- // Check if it's still a table row
267
- if (rowLine.includes('|') && rowLine.split('|').length >= 2) {
268
- const isRowSeparator = /^[\s|\-:]+$/.test(rowLine.trim());
269
- if (!isRowSeparator) {
270
- const rowCells = rowLine.split('|').map(cell => cell.trim());
271
- // Remove empty cells at start/end
272
- if (rowCells.length > 0 && !rowCells[0]) rowCells.shift();
273
- if (rowCells.length > 0 && !rowCells[rowCells.length - 1]) rowCells.pop();
274
- tableRows.push(rowCells);
275
- j++;
276
- } else {
277
- j++;
278
- }
279
- } else {
280
- break; // Not a table row anymore
281
- }
282
- }
283
-
284
- // Convert to HTML table
285
- if (tableRows.length > 0) {
286
- let htmlTable = '<table class="border-collapse border border-gray-300 w-full my-4">\n<thead>\n<tr>';
287
-
288
- // Header row
289
- tableRows[0].forEach(cell => {
290
- htmlTable += `<th class="border border-gray-300 px-4 py-2 bg-gray-100 font-semibold text-left">${escapeHtml(cell)}</th>`;
291
- });
292
- htmlTable += '</tr>\n</thead>\n<tbody>\n';
293
-
294
- // Data rows
295
- for (let rowIdx = 1; rowIdx < tableRows.length; rowIdx++) {
296
- htmlTable += '<tr>';
297
- tableRows[rowIdx].forEach((cell, colIdx) => {
298
- // Use header cell count to ensure alignment
299
- const cellContent = cell || '';
300
- htmlTable += `<td class="border border-gray-300 px-4 py-2">${escapeHtml(cellContent)}</td>`;
301
- });
302
- htmlTable += '</tr>\n';
303
- }
304
-
305
- htmlTable += '</tbody>\n</table>';
306
- result.push(htmlTable);
307
- i = j;
308
- continue;
309
- }
310
- }
311
- }
312
- }
313
-
314
- // Not a table row, add as-is
315
- result.push(line);
316
- i++;
317
- }
318
-
319
- return result.join('\n');
320
- };
321
-
322
- // Helper function to render markdown to HTML (same as in ExtractionOutput)
323
- const renderMarkdownToHTML = (text) => {
324
- if (!text) return "";
325
-
326
- let html = text;
327
-
328
- // FIRST: Convert pipe-separated tables to HTML tables
329
- html = convertPipeTablesToHTML(html);
330
-
331
- // Convert LaTeX-style superscripts/subscripts FIRST
332
- html = html.replace(/\$\s*\^\s*\{([^}]+)\}\s*\$/g, '<sup>$1</sup>');
333
- html = html.replace(/\$\s*\^\s*([^\s$<>]+)\s*\$/g, '<sup>$1</sup>');
334
- html = html.replace(/\$\s*_\s*\{([^}]+)\}\s*\$/g, '<sub>$1</sub>');
335
- html = html.replace(/\$\s*_\s*([^\s$<>]+)\s*\$/g, '<sub>$1</sub>');
336
-
337
- // Protect HTML table blocks
338
- const htmlBlocks = [];
339
- let htmlBlockIndex = 0;
340
-
341
- html = html.replace(/<table[\s\S]*?<\/table>/gi, (match) => {
342
- const placeholder = `__HTML_BLOCK_${htmlBlockIndex}__`;
343
- htmlBlocks[htmlBlockIndex] = match;
344
- htmlBlockIndex++;
345
- return placeholder;
346
- });
347
-
348
- // Convert markdown headers
349
- html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>');
350
- html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>');
351
- html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>');
352
-
353
- // Convert markdown bold/italic
354
- html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
355
- html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
356
-
357
- // Convert markdown links
358
- html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
359
-
360
- // Process line breaks
361
- const parts = html.split(/(__HTML_BLOCK_\d+__)/);
362
- const processedParts = parts.map((part) => {
363
- if (part.match(/^__HTML_BLOCK_\d+__$/)) {
364
- const blockIndex = parseInt(part.match(/\d+/)[0]);
365
- return htmlBlocks[blockIndex];
366
- } else {
367
- let processed = part;
368
- processed = processed.replace(/\n\n+/g, '</p><p>');
369
- processed = processed.replace(/([^\n>])\n([^\n<])/g, '$1<br>$2');
370
- if (processed.trim() && !processed.trim().startsWith('<')) {
371
- processed = '<p>' + processed + '</p>';
372
- }
373
- return processed;
374
- }
375
- });
376
-
377
- html = processedParts.join('');
378
- html = html.replace(/<p><\/p>/g, '');
379
- html = html.replace(/<p>\s*<br>\s*<\/p>/g, '');
380
- html = html.replace(/<p>\s*<\/p>/g, '');
381
-
382
- return html;
383
- };
384
-
385
- const handleDownload = async (format) => {
386
- if (!extractionResult || !extractionResult.fields) {
387
- console.error("No extraction data available");
388
- return;
389
- }
390
-
391
- setDownloading(format);
392
-
393
- try {
394
- const fields = extractionResult.fields;
395
- let content = "";
396
- let filename = "";
397
- let mimeType = "";
398
-
399
- if (format === "json") {
400
- const preparedFields = prepareFieldsForOutput(fields, "json");
401
- content = JSON.stringify(preparedFields, null, 2);
402
- filename = `extraction_${new Date().toISOString().split('T')[0]}.json`;
403
- mimeType = "application/json";
404
- } else if (format === "xml") {
405
- content = objectToXML(fields);
406
- filename = `extraction_${new Date().toISOString().split('T')[0]}.xml`;
407
- mimeType = "application/xml";
408
- } else if (format === "docx") {
409
- // For DOCX, create a Word-compatible HTML document that preserves layout
410
- // Extract text and convert to HTML (same as text viewer)
411
- const textContent = extractTextFromFields(fields);
412
- const htmlContent = renderMarkdownToHTML(textContent);
413
-
414
- // Create a Word-compatible HTML document with proper MIME type
415
- // Word can open HTML files with .docx extension if we use the right MIME type
416
- const wordHTML = `<!DOCTYPE html>
417
- <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">
418
- <head>
419
- <meta charset="UTF-8">
420
- <meta name="ProgId" content="Word.Document">
421
- <meta name="Generator" content="Microsoft Word">
422
- <meta name="Originator" content="Microsoft Word">
423
- <!--[if gte mso 9]><xml>
424
- <w:WordDocument>
425
- <w:View>Print</w:View>
426
- <w:Zoom>100</w:Zoom>
427
- <w:DoNotOptimizeForBrowser/>
428
- </w:WordDocument>
429
- </xml><![endif]-->
430
- <title>Document Extraction</title>
431
- <style>
432
- @page {
433
- size: 8.5in 11in;
434
- margin: 1in;
435
- }
436
- body {
437
- font-family: 'Calibri', 'Arial', sans-serif;
438
- font-size: 11pt;
439
- line-height: 1.6;
440
- margin: 0;
441
- color: #333;
442
- }
443
- h1 {
444
- font-size: 18pt;
445
- font-weight: bold;
446
- color: #0f172a;
447
- margin-top: 24pt;
448
- margin-bottom: 12pt;
449
- page-break-after: avoid;
450
- }
451
- h2 {
452
- font-size: 16pt;
453
- font-weight: 600;
454
- color: #0f172a;
455
- margin-top: 20pt;
456
- margin-bottom: 10pt;
457
- page-break-after: avoid;
458
- }
459
- h3 {
460
- font-size: 14pt;
461
- font-weight: 600;
462
- color: #1e293b;
463
- margin-top: 16pt;
464
- margin-bottom: 8pt;
465
- page-break-after: avoid;
466
- }
467
- p {
468
- margin-top: 6pt;
469
- margin-bottom: 6pt;
470
- }
471
- table {
472
- width: 100%;
473
- border-collapse: collapse;
474
- margin: 12pt 0;
475
- font-size: 10pt;
476
- page-break-inside: avoid;
477
- }
478
- table th {
479
- background-color: #f8fafc;
480
- border: 1pt solid #cbd5e1;
481
- padding: 6pt;
482
- text-align: left;
483
- font-weight: 600;
484
- color: #0f172a;
485
- }
486
- table td {
487
- border: 1pt solid #cbd5e1;
488
- padding: 6pt;
489
- color: #334155;
490
- }
491
- table tr:nth-child(even) {
492
- background-color: #f8fafc;
493
- }
494
- sup {
495
- font-size: 0.75em;
496
- vertical-align: super;
497
- line-height: 0;
498
- }
499
- sub {
500
- font-size: 0.75em;
501
- vertical-align: sub;
502
- line-height: 0;
503
- }
504
- strong {
505
- font-weight: 600;
506
- }
507
- em {
508
- font-style: italic;
509
- }
510
- a {
511
- color: #4f46e5;
512
- text-decoration: underline;
513
- }
514
- </style>
515
- </head>
516
- <body>
517
- ${htmlContent}
518
- </body>
519
- </html>`;
520
-
521
- content = wordHTML;
522
- filename = `extraction_${new Date().toISOString().split('T')[0]}.doc`;
523
- mimeType = "application/msword";
524
- }
525
-
526
- // Create blob and download
527
- const blob = new Blob([content], { type: mimeType });
528
- const url = URL.createObjectURL(blob);
529
- const link = document.createElement("a");
530
- link.href = url;
531
- link.download = filename;
532
- document.body.appendChild(link);
533
- link.click();
534
- document.body.removeChild(link);
535
- URL.revokeObjectURL(url);
536
-
537
- setDownloading(null);
538
- } catch (error) {
539
- console.error("Download error:", error);
540
- setDownloading(null);
541
- }
542
- };
543
-
544
- const handleCopyLink = async () => {
545
- if (!extractionResult?.id) return;
546
-
547
- setIsGeneratingLink(true);
548
- setIsShareLinkModalOpen(true);
549
- setShareLink("");
550
-
551
- try {
552
- const result = await createShareLink(extractionResult.id);
553
- if (result.success && result.share_link) {
554
- setShareLink(result.share_link);
555
- } else {
556
- throw new Error("Failed to generate share link");
557
- }
558
- } catch (err) {
559
- console.error("Failed to create share link:", err);
560
- setShareLink("");
561
- // Still show modal but with error state
562
- } finally {
563
- setIsGeneratingLink(false);
564
- }
565
- };
566
-
567
- const handleShare = async (extractionId, recipientEmail) => {
568
- await shareExtraction(extractionId, recipientEmail);
569
- };
570
-
571
- if (!isComplete) return null;
572
-
573
- return (
574
- <motion.div
575
- initial={{ opacity: 0, y: 20 }}
576
- animate={{ opacity: 1, y: 0 }}
577
- className="flex items-center gap-3"
578
- >
579
- {/* Export Options Dropdown */}
580
- <DropdownMenu>
581
- <DropdownMenuTrigger asChild>
582
- <Button
583
- variant="ghost"
584
- className="h-11 w-11 rounded-xl hover:bg-slate-100"
585
- disabled={downloading !== null}
586
- >
587
- {downloading ? (
588
- <motion.div
589
- animate={{ rotate: 360 }}
590
- transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
591
- >
592
- <Download className="h-4 w-4" />
593
- </motion.div>
594
- ) : (
595
- <Share2 className="h-4 w-4" />
596
- )}
597
- </Button>
598
- </DropdownMenuTrigger>
599
- <DropdownMenuContent align="end" className="w-56 rounded-xl p-2">
600
- <DropdownMenuItem
601
- className="rounded-lg cursor-pointer"
602
- onClick={() => setIsShareModalOpen(true)}
603
- >
604
- <Mail className="h-4 w-4 mr-2 text-indigo-600" />
605
- Share output
606
- </DropdownMenuItem>
607
- <DropdownMenuItem
608
- className="rounded-lg cursor-pointer"
609
- onClick={handleCopyLink}
610
- >
611
- <Link2 className="h-4 w-4 mr-2 text-indigo-600" />
612
- Copy share link
613
- </DropdownMenuItem>
614
- <DropdownMenuSeparator />
615
- <DropdownMenuItem
616
- className="rounded-lg cursor-pointer"
617
- onClick={() => handleDownload("docx")}
618
- disabled={downloading === "docx"}
619
- >
620
- {downloading === "docx" ? (
621
- <motion.div
622
- animate={{ rotate: 360 }}
623
- transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
624
- className="h-4 w-4 mr-2"
625
- >
626
- <Download className="h-4 w-4" />
627
- </motion.div>
628
- ) : (
629
- <FileText className="h-4 w-4 mr-2 text-blue-600" />
630
- )}
631
- Download Docx
632
- </DropdownMenuItem>
633
- <DropdownMenuItem
634
- className="rounded-lg cursor-pointer"
635
- onClick={() => handleDownload("json")}
636
- disabled={downloading === "json"}
637
- >
638
- {downloading === "json" ? (
639
- <motion.div
640
- animate={{ rotate: 360 }}
641
- transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
642
- className="h-4 w-4 mr-2"
643
- >
644
- <Download className="h-4 w-4" />
645
- </motion.div>
646
- ) : (
647
- <Braces className="h-4 w-4 mr-2 text-indigo-600" />
648
- )}
649
- Download JSON
650
- </DropdownMenuItem>
651
- <DropdownMenuItem
652
- className="rounded-lg cursor-pointer"
653
- onClick={() => handleDownload("xml")}
654
- disabled={downloading === "xml"}
655
- >
656
- {downloading === "xml" ? (
657
- <motion.div
658
- animate={{ rotate: 360 }}
659
- transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
660
- className="h-4 w-4 mr-2"
661
- >
662
- <Download className="h-4 w-4" />
663
- </motion.div>
664
- ) : (
665
- <FileCode2 className="h-4 w-4 mr-2 text-slate-600" />
666
- )}
667
- Download XML
668
- </DropdownMenuItem>
669
- </DropdownMenuContent>
670
- </DropdownMenu>
671
-
672
- {/* Share Modal */}
673
- <ShareModal
674
- isOpen={isShareModalOpen}
675
- onClose={() => setIsShareModalOpen(false)}
676
- onShare={handleShare}
677
- extractionId={extractionResult?.id}
678
- />
679
-
680
- {/* Share Link Modal */}
681
- <ShareLinkModal
682
- isOpen={isShareLinkModalOpen}
683
- onClose={() => {
684
- setIsShareLinkModalOpen(false);
685
- setShareLink("");
686
- }}
687
- shareLink={shareLink}
688
- isLoading={isGeneratingLink}
689
- />
690
- </motion.div>
691
- );
692
- }
693
- import { motion, AnimatePresence } from "framer-motion";
694
- import {
695
- Download,
696
- Braces,
697
- FileCode2,
698
- Check,
699
- Share2,
700
- FileText,
701
- Link2,
702
- Mail,
703
- } from "lucide-react";
704
- import { Button } from "@/components/ui/button";
705
- import {
706
- DropdownMenu,
707
- DropdownMenuContent,
708
- DropdownMenuItem,
709
- DropdownMenuSeparator,
710
- DropdownMenuTrigger,
711
- } from "@/components/ui/dropdown-menu";
712
- import { cn } from "@/lib/utils";
713
- import ShareModal from "@/components/ShareModal";
714
- import ShareLinkModal from "@/components/ShareLinkModal";
715
- import { shareExtraction, createShareLink } from "@/services/api";
716
-
717
- // Helper functions from ExtractionOutput
718
- function prepareFieldsForOutput(fields, format = "json") {
719
- if (!fields || typeof fields !== "object") {
720
- return fields;
721
- }
722
-
723
- const output = { ...fields };
724
-
725
- // Extract Fields from root level if it exists
726
- const rootFields = output.Fields;
727
- // Remove Fields from output temporarily (will be added back at top)
728
- delete output.Fields;
729
-
730
- // Remove full_text from top-level if pages array exists (to avoid duplication)
731
- if (output.pages && Array.isArray(output.pages) && output.pages.length > 0) {
732
- delete output.full_text;
733
-
734
- // Clean up each page: remove full_text from page.fields (it duplicates page.text)
735
- output.pages = output.pages.map(page => {
736
- const cleanedPage = { ...page };
737
- if (cleanedPage.fields && typeof cleanedPage.fields === "object") {
738
- const cleanedFields = { ...cleanedPage.fields };
739
- // Remove full_text from page fields (duplicates page.text)
740
- delete cleanedFields.full_text;
741
- cleanedPage.fields = cleanedFields;
742
- }
743
- return cleanedPage;
744
- });
745
- }
746
-
747
- // For JSON and XML: restructure pages into separate top-level fields (page_1, page_2, etc.)
748
- if ((format === "json" || format === "xml") && output.pages && Array.isArray(output.pages)) {
749
- // Get top-level field keys (these are merged from all pages - avoid duplicating in page fields)
750
- const topLevelKeys = new Set(Object.keys(output).filter(k => k !== "pages" && k !== "full_text" && k !== "Fields"));
751
-
752
- output.pages.forEach((page, idx) => {
753
- const pageNum = page.page_number || idx + 1;
754
- const pageFields = page.fields || {};
755
-
756
- // Remove duplicate fields from page.fields:
757
- // 1. Remove full_text (duplicates page.text)
758
- // 2. Remove fields that match top-level fields (already shown at root)
759
- const cleanedPageFields = {};
760
- for (const [key, value] of Object.entries(pageFields)) {
761
- // Skip full_text and fields that match top-level exactly
762
- if (key !== "full_text" && (!topLevelKeys.has(key) || (value !== output[key]))) {
763
- cleanedPageFields[key] = value;
764
- }
765
- }
766
-
767
- const pageObj = {
768
- text: page.text || "",
769
- confidence: page.confidence || 0,
770
- doc_type: page.doc_type || "other"
771
- };
772
-
773
- // Add table and footer_notes if they exist
774
- if (page.table && Array.isArray(page.table) && page.table.length > 0) {
775
- pageObj.table = page.table;
776
- }
777
- if (page.footer_notes && Array.isArray(page.footer_notes) && page.footer_notes.length > 0) {
778
- pageObj.footer_notes = page.footer_notes;
779
- }
780
-
781
- // Only add fields if there are unique page-specific fields
782
- if (Object.keys(cleanedPageFields).length > 0) {
783
- pageObj.fields = cleanedPageFields;
784
- }
785
-
786
- output[`page_${pageNum}`] = pageObj;
787
- });
788
- // Remove pages array - we now have page_1, page_2, etc. as separate fields
789
- delete output.pages;
790
- }
791
-
792
- // Handle page_X structure (from backend) - remove Fields from page objects if they exist
793
- if (output && typeof output === "object") {
794
- const pageKeys = Object.keys(output).filter(k => k.startsWith("page_"));
795
- for (const pageKey of pageKeys) {
796
- const pageData = output[pageKey];
797
- if (pageData && typeof pageData === "object") {
798
- // Remove Fields from page objects (it's now at root level)
799
- delete pageData.Fields;
800
- delete pageData.metadata;
801
- }
802
- }
803
- }
804
-
805
- // Rebuild output with Fields at the top (only if it exists and is not empty)
806
- const finalOutput = {};
807
- if (rootFields && typeof rootFields === "object" && Object.keys(rootFields).length > 0) {
808
- finalOutput.Fields = rootFields;
809
- }
810
-
811
- // Add all other keys
812
- Object.keys(output).forEach(key => {
813
- finalOutput[key] = output[key];
814
- });
815
-
816
- return finalOutput;
817
- }
818
-
819
- function escapeXML(str) {
820
- return str
821
- .replace(/&/g, "&amp;")
822
- .replace(/</g, "&lt;")
823
- .replace(/>/g, "&gt;")
824
- .replace(/"/g, "&quot;")
825
- .replace(/'/g, "&apos;");
826
- }
827
-
828
- function objectToXML(obj, rootName = "extraction") {
829
- // Prepare fields - remove full_text if pages exist
830
- const preparedObj = prepareFieldsForOutput(obj, "xml");
831
-
832
- let xml = `<?xml version="1.0" encoding="UTF-8"?>\n<${rootName}>\n`;
833
-
834
- const convert = (obj, indent = " ") => {
835
- for (const [key, value] of Object.entries(obj)) {
836
- if (value === null || value === undefined) continue;
837
-
838
- // Skip full_text if pages exist (already handled in prepareFieldsForOutput)
839
- if (key === "full_text" && obj.pages && Array.isArray(obj.pages) && obj.pages.length > 0) {
840
- continue;
841
- }
842
-
843
- if (Array.isArray(value)) {
844
- value.forEach((item) => {
845
- xml += `${indent}<${key}>\n`;
846
- if (typeof item === "object") {
847
- convert(item, indent + " ");
848
- } else {
849
- xml += `${indent} ${escapeXML(String(item))}\n`;
850
- }
851
- xml += `${indent}</${key}>\n`;
852
- });
853
- } else if (typeof value === "object") {
854
- xml += `${indent}<${key}>\n`;
855
- convert(value, indent + " ");
856
- xml += `${indent}</${key}>\n`;
857
- } else {
858
- xml += `${indent}<${key}>${escapeXML(String(value))}</${key}>\n`;
859
- }
860
- }
861
- };
862
-
863
- convert(preparedObj);
864
- xml += `</${rootName}>`;
865
- return xml;
866
- }
867
-
868
- export default function ExportButtons({ isComplete, extractionResult }) {
869
- const [downloading, setDownloading] = useState(null);
870
- const [copied, setCopied] = useState(false);
871
- const [isShareModalOpen, setIsShareModalOpen] = useState(false);
872
- const [isShareLinkModalOpen, setIsShareLinkModalOpen] = useState(false);
873
- const [shareLink, setShareLink] = useState("");
874
- const [isGeneratingLink, setIsGeneratingLink] = useState(false);
875
-
876
- // Helper function to extract text from fields (same as in ExtractionOutput)
877
- const extractTextFromFields = (fields) => {
878
- if (!fields || typeof fields !== "object") {
879
- return "";
880
- }
881
-
882
- // Check for page_X structure first (preferred format)
883
- const pageKeys = Object.keys(fields).filter(key => key.startsWith("page_"));
884
- if (pageKeys.length > 0) {
885
- // Get text from first page (or combine all pages)
886
- const pageTexts = pageKeys.map(key => {
887
- const page = fields[key];
888
- if (page && page.text) {
889
- return page.text;
890
- }
891
- return "";
892
- }).filter(text => text);
893
-
894
- if (pageTexts.length > 0) {
895
- return pageTexts.join("\n\n");
896
- }
897
- }
898
-
899
- // Fallback to full_text
900
- if (fields.full_text) {
901
- return fields.full_text;
902
- }
903
-
904
- return "";
905
- };
906
-
907
- // Helper function to escape HTML
908
- const escapeHtml = (text) => {
909
- if (!text) return '';
910
- const div = document.createElement('div');
911
- div.textContent = text;
912
- return div.innerHTML;
913
- };
914
-
915
- // Helper function to convert pipe-separated tables to HTML tables
916
- const convertPipeTablesToHTML = (text) => {
917
- if (!text) return text;
918
-
919
- const lines = text.split('\n');
920
- const result = [];
921
- let i = 0;
922
-
923
- while (i < lines.length) {
924
- const line = lines[i];
925
-
926
- // Check if this line looks like a table row (has multiple pipes)
927
- if (line.includes('|') && line.split('|').length >= 3) {
928
- // Check if it's a separator line (only |, -, :, spaces)
929
- const isSeparator = /^[\s|\-:]+$/.test(line.trim());
930
-
931
- if (!isSeparator) {
932
- // Start of a table - collect all table rows
933
- const tableRows = [];
934
- let j = i;
935
-
936
- // Collect header row
937
- const headerLine = lines[j];
938
- const headerCells = headerLine.split('|').map(cell => cell.trim()).filter(cell => cell || cell === '');
939
- // Remove empty cells at start/end
940
- if (headerCells.length > 0 && !headerCells[0]) headerCells.shift();
941
- if (headerCells.length > 0 && !headerCells[headerCells.length - 1]) headerCells.pop();
942
-
943
- if (headerCells.length >= 2) {
944
- tableRows.push(headerCells);
945
- j++;
946
-
947
- // Skip separator line if present
948
- if (j < lines.length && /^[\s|\-:]+$/.test(lines[j].trim())) {
949
- j++;
950
- }
951
-
952
- // Collect data rows
953
- while (j < lines.length) {
954
- const rowLine = lines[j];
955
- if (!rowLine.trim()) break; // Empty line ends table
956
-
957
- // Check if it's still a table row
958
- if (rowLine.includes('|') && rowLine.split('|').length >= 2) {
959
- const isRowSeparator = /^[\s|\-:]+$/.test(rowLine.trim());
960
- if (!isRowSeparator) {
961
- const rowCells = rowLine.split('|').map(cell => cell.trim());
962
- // Remove empty cells at start/end
963
- if (rowCells.length > 0 && !rowCells[0]) rowCells.shift();
964
- if (rowCells.length > 0 && !rowCells[rowCells.length - 1]) rowCells.pop();
965
- tableRows.push(rowCells);
966
- j++;
967
- } else {
968
- j++;
969
- }
970
- } else {
971
- break; // Not a table row anymore
972
- }
973
- }
974
-
975
- // Convert to HTML table
976
- if (tableRows.length > 0) {
977
- let htmlTable = '<table class="border-collapse border border-gray-300 w-full my-4">\n<thead>\n<tr>';
978
-
979
- // Header row
980
- tableRows[0].forEach(cell => {
981
- htmlTable += `<th class="border border-gray-300 px-4 py-2 bg-gray-100 font-semibold text-left">${escapeHtml(cell)}</th>`;
982
- });
983
- htmlTable += '</tr>\n</thead>\n<tbody>\n';
984
-
985
- // Data rows
986
- for (let rowIdx = 1; rowIdx < tableRows.length; rowIdx++) {
987
- htmlTable += '<tr>';
988
- tableRows[rowIdx].forEach((cell, colIdx) => {
989
- // Use header cell count to ensure alignment
990
- const cellContent = cell || '';
991
- htmlTable += `<td class="border border-gray-300 px-4 py-2">${escapeHtml(cellContent)}</td>`;
992
- });
993
- htmlTable += '</tr>\n';
994
- }
995
-
996
- htmlTable += '</tbody>\n</table>';
997
- result.push(htmlTable);
998
- i = j;
999
- continue;
1000
- }
1001
- }
1002
- }
1003
- }
1004
-
1005
- // Not a table row, add as-is
1006
- result.push(line);
1007
- i++;
1008
- }
1009
-
1010
- return result.join('\n');
1011
- };
1012
-
1013
- // Helper function to render markdown to HTML (same as in ExtractionOutput)
1014
- const renderMarkdownToHTML = (text) => {
1015
- if (!text) return "";
1016
-
1017
- let html = text;
1018
-
1019
- // FIRST: Convert pipe-separated tables to HTML tables
1020
- html = convertPipeTablesToHTML(html);
1021
-
1022
- // Convert LaTeX-style superscripts/subscripts FIRST
1023
- html = html.replace(/\$\s*\^\s*\{([^}]+)\}\s*\$/g, '<sup>$1</sup>');
1024
- html = html.replace(/\$\s*\^\s*([^\s$<>]+)\s*\$/g, '<sup>$1</sup>');
1025
- html = html.replace(/\$\s*_\s*\{([^}]+)\}\s*\$/g, '<sub>$1</sub>');
1026
- html = html.replace(/\$\s*_\s*([^\s$<>]+)\s*\$/g, '<sub>$1</sub>');
1027
-
1028
- // Protect HTML table blocks
1029
- const htmlBlocks = [];
1030
- let htmlBlockIndex = 0;
1031
-
1032
- html = html.replace(/<table[\s\S]*?<\/table>/gi, (match) => {
1033
- const placeholder = `__HTML_BLOCK_${htmlBlockIndex}__`;
1034
- htmlBlocks[htmlBlockIndex] = match;
1035
- htmlBlockIndex++;
1036
- return placeholder;
1037
- });
1038
-
1039
- // Convert markdown headers
1040
- html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>');
1041
- html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>');
1042
- html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>');
1043
-
1044
- // Convert markdown bold/italic
1045
- html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
1046
- html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
1047
-
1048
- // Convert markdown links
1049
- html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
1050
-
1051
- // Process line breaks
1052
- const parts = html.split(/(__HTML_BLOCK_\d+__)/);
1053
- const processedParts = parts.map((part) => {
1054
- if (part.match(/^__HTML_BLOCK_\d+__$/)) {
1055
- const blockIndex = parseInt(part.match(/\d+/)[0]);
1056
- return htmlBlocks[blockIndex];
1057
- } else {
1058
- let processed = part;
1059
- processed = processed.replace(/\n\n+/g, '</p><p>');
1060
- processed = processed.replace(/([^\n>])\n([^\n<])/g, '$1<br>$2');
1061
- if (processed.trim() && !processed.trim().startsWith('<')) {
1062
- processed = '<p>' + processed + '</p>';
1063
- }
1064
- return processed;
1065
- }
1066
- });
1067
-
1068
- html = processedParts.join('');
1069
- html = html.replace(/<p><\/p>/g, '');
1070
- html = html.replace(/<p>\s*<br>\s*<\/p>/g, '');
1071
- html = html.replace(/<p>\s*<\/p>/g, '');
1072
-
1073
- return html;
1074
- };
1075
-
1076
- const handleDownload = async (format) => {
1077
- if (!extractionResult || !extractionResult.fields) {
1078
- console.error("No extraction data available");
1079
- return;
1080
- }
1081
-
1082
- setDownloading(format);
1083
-
1084
- try {
1085
- const fields = extractionResult.fields;
1086
- let content = "";
1087
- let filename = "";
1088
- let mimeType = "";
1089
-
1090
- if (format === "json") {
1091
- const preparedFields = prepareFieldsForOutput(fields, "json");
1092
- content = JSON.stringify(preparedFields, null, 2);
1093
- filename = `extraction_${new Date().toISOString().split('T')[0]}.json`;
1094
- mimeType = "application/json";
1095
- } else if (format === "xml") {
1096
- content = objectToXML(fields);
1097
- filename = `extraction_${new Date().toISOString().split('T')[0]}.xml`;
1098
- mimeType = "application/xml";
1099
- } else if (format === "docx") {
1100
- // For DOCX, create a Word-compatible HTML document that preserves layout
1101
- // Extract text and convert to HTML (same as text viewer)
1102
- const textContent = extractTextFromFields(fields);
1103
- const htmlContent = renderMarkdownToHTML(textContent);
1104
-
1105
- // Create a Word-compatible HTML document with proper MIME type
1106
- // Word can open HTML files with .docx extension if we use the right MIME type
1107
- const wordHTML = `<!DOCTYPE html>
1108
- <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">
1109
- <head>
1110
- <meta charset="UTF-8">
1111
- <meta name="ProgId" content="Word.Document">
1112
- <meta name="Generator" content="Microsoft Word">
1113
- <meta name="Originator" content="Microsoft Word">
1114
- <!--[if gte mso 9]><xml>
1115
- <w:WordDocument>
1116
- <w:View>Print</w:View>
1117
- <w:Zoom>100</w:Zoom>
1118
- <w:DoNotOptimizeForBrowser/>
1119
- </w:WordDocument>
1120
- </xml><![endif]-->
1121
- <title>Document Extraction</title>
1122
- <style>
1123
- @page {
1124
- size: 8.5in 11in;
1125
- margin: 1in;
1126
- }
1127
- body {
1128
- font-family: 'Calibri', 'Arial', sans-serif;
1129
- font-size: 11pt;
1130
- line-height: 1.6;
1131
- margin: 0;
1132
- color: #333;
1133
- }
1134
- h1 {
1135
- font-size: 18pt;
1136
- font-weight: bold;
1137
- color: #0f172a;
1138
- margin-top: 24pt;
1139
- margin-bottom: 12pt;
1140
- page-break-after: avoid;
1141
- }
1142
- h2 {
1143
- font-size: 16pt;
1144
- font-weight: 600;
1145
- color: #0f172a;
1146
- margin-top: 20pt;
1147
- margin-bottom: 10pt;
1148
- page-break-after: avoid;
1149
- }
1150
- h3 {
1151
- font-size: 14pt;
1152
- font-weight: 600;
1153
- color: #1e293b;
1154
- margin-top: 16pt;
1155
- margin-bottom: 8pt;
1156
- page-break-after: avoid;
1157
- }
1158
- p {
1159
- margin-top: 6pt;
1160
- margin-bottom: 6pt;
1161
- }
1162
- table {
1163
- width: 100%;
1164
- border-collapse: collapse;
1165
- margin: 12pt 0;
1166
- font-size: 10pt;
1167
- page-break-inside: avoid;
1168
- }
1169
- table th {
1170
- background-color: #f8fafc;
1171
- border: 1pt solid #cbd5e1;
1172
- padding: 6pt;
1173
- text-align: left;
1174
- font-weight: 600;
1175
- color: #0f172a;
1176
- }
1177
- table td {
1178
- border: 1pt solid #cbd5e1;
1179
- padding: 6pt;
1180
- color: #334155;
1181
- }
1182
- table tr:nth-child(even) {
1183
- background-color: #f8fafc;
1184
- }
1185
- sup {
1186
- font-size: 0.75em;
1187
- vertical-align: super;
1188
- line-height: 0;
1189
- }
1190
- sub {
1191
- font-size: 0.75em;
1192
- vertical-align: sub;
1193
- line-height: 0;
1194
- }
1195
- strong {
1196
- font-weight: 600;
1197
- }
1198
- em {
1199
- font-style: italic;
1200
- }
1201
- a {
1202
- color: #4f46e5;
1203
- text-decoration: underline;
1204
- }
1205
- </style>
1206
- </head>
1207
- <body>
1208
- ${htmlContent}
1209
- </body>
1210
- </html>`;
1211
-
1212
- content = wordHTML;
1213
- filename = `extraction_${new Date().toISOString().split('T')[0]}.doc`;
1214
- mimeType = "application/msword";
1215
- }
1216
-
1217
- // Create blob and download
1218
- const blob = new Blob([content], { type: mimeType });
1219
- const url = URL.createObjectURL(blob);
1220
- const link = document.createElement("a");
1221
- link.href = url;
1222
- link.download = filename;
1223
- document.body.appendChild(link);
1224
- link.click();
1225
- document.body.removeChild(link);
1226
- URL.revokeObjectURL(url);
1227
-
1228
- setDownloading(null);
1229
- } catch (error) {
1230
- console.error("Download error:", error);
1231
- setDownloading(null);
1232
- }
1233
- };
1234
-
1235
- const handleCopyLink = async () => {
1236
- if (!extractionResult?.id) return;
1237
-
1238
- setIsGeneratingLink(true);
1239
- setIsShareLinkModalOpen(true);
1240
- setShareLink("");
1241
-
1242
- try {
1243
- const result = await createShareLink(extractionResult.id);
1244
- if (result.success && result.share_link) {
1245
- setShareLink(result.share_link);
1246
- } else {
1247
- throw new Error("Failed to generate share link");
1248
- }
1249
- } catch (err) {
1250
- console.error("Failed to create share link:", err);
1251
- setShareLink("");
1252
- // Still show modal but with error state
1253
- } finally {
1254
- setIsGeneratingLink(false);
1255
- }
1256
- };
1257
-
1258
- const handleShare = async (extractionId, recipientEmail) => {
1259
- await shareExtraction(extractionId, recipientEmail);
1260
- };
1261
-
1262
- if (!isComplete) return null;
1263
-
1264
- return (
1265
- <motion.div
1266
- initial={{ opacity: 0, y: 20 }}
1267
- animate={{ opacity: 1, y: 0 }}
1268
- className="flex items-center gap-3"
1269
- >
1270
- {/* Export Options Dropdown */}
1271
- <DropdownMenu>
1272
- <DropdownMenuTrigger asChild>
1273
- <Button
1274
- variant="ghost"
1275
- className="h-11 w-11 rounded-xl hover:bg-slate-100"
1276
- disabled={downloading !== null}
1277
- >
1278
- {downloading ? (
1279
- <motion.div
1280
- animate={{ rotate: 360 }}
1281
- transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
1282
- >
1283
- <Download className="h-4 w-4" />
1284
- </motion.div>
1285
- ) : (
1286
- <Share2 className="h-4 w-4" />
1287
- )}
1288
- </Button>
1289
- </DropdownMenuTrigger>
1290
- <DropdownMenuContent align="end" className="w-56 rounded-xl p-2">
1291
- <DropdownMenuItem
1292
- className="rounded-lg cursor-pointer"
1293
- onClick={() => setIsShareModalOpen(true)}
1294
- >
1295
- <Mail className="h-4 w-4 mr-2 text-indigo-600" />
1296
- Share output
1297
- </DropdownMenuItem>
1298
- <DropdownMenuItem
1299
- className="rounded-lg cursor-pointer"
1300
- onClick={handleCopyLink}
1301
- >
1302
- <Link2 className="h-4 w-4 mr-2 text-indigo-600" />
1303
- Copy share link
1304
- </DropdownMenuItem>
1305
- <DropdownMenuSeparator />
1306
- <DropdownMenuItem
1307
- className="rounded-lg cursor-pointer"
1308
- onClick={() => handleDownload("docx")}
1309
- disabled={downloading === "docx"}
1310
- >
1311
- {downloading === "docx" ? (
1312
- <motion.div
1313
- animate={{ rotate: 360 }}
1314
- transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
1315
- className="h-4 w-4 mr-2"
1316
- >
1317
- <Download className="h-4 w-4" />
1318
- </motion.div>
1319
- ) : (
1320
- <FileText className="h-4 w-4 mr-2 text-blue-600" />
1321
- )}
1322
- Download Docx
1323
- </DropdownMenuItem>
1324
- <DropdownMenuItem
1325
- className="rounded-lg cursor-pointer"
1326
- onClick={() => handleDownload("json")}
1327
- disabled={downloading === "json"}
1328
- >
1329
- {downloading === "json" ? (
1330
- <motion.div
1331
- animate={{ rotate: 360 }}
1332
- transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
1333
- className="h-4 w-4 mr-2"
1334
- >
1335
- <Download className="h-4 w-4" />
1336
- </motion.div>
1337
- ) : (
1338
- <Braces className="h-4 w-4 mr-2 text-indigo-600" />
1339
- )}
1340
- Download JSON
1341
- </DropdownMenuItem>
1342
- <DropdownMenuItem
1343
- className="rounded-lg cursor-pointer"
1344
- onClick={() => handleDownload("xml")}
1345
- disabled={downloading === "xml"}
1346
- >
1347
- {downloading === "xml" ? (
1348
- <motion.div
1349
- animate={{ rotate: 360 }}
1350
- transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
1351
- className="h-4 w-4 mr-2"
1352
- >
1353
- <Download className="h-4 w-4" />
1354
- </motion.div>
1355
- ) : (
1356
- <FileCode2 className="h-4 w-4 mr-2 text-slate-600" />
1357
- )}
1358
- Download XML
1359
- </DropdownMenuItem>
1360
- </DropdownMenuContent>
1361
- </DropdownMenu>
1362
-
1363
- {/* Share Modal */}
1364
- <ShareModal
1365
- isOpen={isShareModalOpen}
1366
- onClose={() => setIsShareModalOpen(false)}
1367
- onShare={handleShare}
1368
- extractionId={extractionResult?.id}
1369
- />
1370
-
1371
- {/* Share Link Modal */}
1372
- <ShareLinkModal
1373
- isOpen={isShareLinkModalOpen}
1374
- onClose={() => {
1375
- setIsShareLinkModalOpen(false);
1376
- setShareLink("");
1377
- }}
1378
- shareLink={shareLink}
1379
- isLoading={isGeneratingLink}
1380
- />
1381
- </motion.div>
1382
- );
1383
- }
 
175
  }
176
 
177
  export default function ExportButtons({ isComplete, extractionResult }) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/src/components/ShareLinkModal.jsx CHANGED
@@ -5,275 +5,3 @@ import { Button } from "@/components/ui/button";
5
  import { Input } from "@/components/ui/input";
6
 
7
  export default function ShareLinkModal({ isOpen, onClose, shareLink, isLoading }) {
8
- const [copied, setCopied] = useState(false);
9
-
10
- useEffect(() => {
11
- if (!isOpen) {
12
- setCopied(false);
13
- }
14
- }, [isOpen]);
15
-
16
- const handleCopy = async () => {
17
- if (!shareLink) return;
18
-
19
- try {
20
- await navigator.clipboard.writeText(shareLink);
21
- setCopied(true);
22
- setTimeout(() => setCopied(false), 2000);
23
- } catch (err) {
24
- // Fallback for older browsers
25
- const textArea = document.createElement("textarea");
26
- textArea.value = shareLink;
27
- textArea.style.position = "fixed";
28
- textArea.style.opacity = "0";
29
- document.body.appendChild(textArea);
30
- textArea.select();
31
- try {
32
- document.execCommand("copy");
33
- setCopied(true);
34
- setTimeout(() => setCopied(false), 2000);
35
- } catch (fallbackErr) {
36
- console.error("Failed to copy:", fallbackErr);
37
- }
38
- document.body.removeChild(textArea);
39
- }
40
- };
41
-
42
- if (!isOpen) return null;
43
-
44
- return (
45
- <AnimatePresence>
46
- <div className="fixed inset-0 z-50 flex items-center justify-center">
47
- {/* Backdrop */}
48
- <motion.div
49
- initial={{ opacity: 0 }}
50
- animate={{ opacity: 1 }}
51
- exit={{ opacity: 0 }}
52
- className="absolute inset-0 bg-black/50 backdrop-blur-sm"
53
- onClick={onClose}
54
- />
55
-
56
- {/* Modal */}
57
- <motion.div
58
- initial={{ opacity: 0, scale: 0.95, y: 20 }}
59
- animate={{ opacity: 1, scale: 1, y: 0 }}
60
- exit={{ opacity: 0, scale: 0.95, y: 20 }}
61
- className="relative z-10 w-full max-w-md mx-4 bg-white rounded-2xl shadow-2xl overflow-hidden"
62
- onClick={(e) => e.stopPropagation()}
63
- >
64
- {/* Header */}
65
- <div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
66
- <h2 className="text-xl font-semibold text-slate-900">Copy Share Link</h2>
67
- <button
68
- onClick={onClose}
69
- disabled={isLoading}
70
- className="p-2 rounded-lg hover:bg-slate-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
71
- >
72
- <X className="h-5 w-5 text-slate-500" />
73
- </button>
74
- </div>
75
-
76
- {/* Content */}
77
- <div className="px-6 py-6">
78
- {isLoading ? (
79
- <div className="text-center py-8">
80
- <Loader2 className="h-8 w-8 mx-auto mb-4 text-indigo-600 animate-spin" />
81
- <p className="text-sm text-slate-600">Generating share link...</p>
82
- </div>
83
- ) : shareLink ? (
84
- <div className="space-y-4">
85
- <div>
86
- <label className="block text-sm font-medium text-slate-700 mb-2">
87
- Share Link
88
- </label>
89
- <div className="flex gap-2">
90
- <Input
91
- type="text"
92
- value={shareLink}
93
- readOnly
94
- className="flex-1 h-12 rounded-xl border-slate-200 bg-slate-50 text-sm font-mono"
95
- />
96
- <Button
97
- onClick={handleCopy}
98
- className="h-12 px-4 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-700 hover:to-violet-700"
99
- >
100
- {copied ? (
101
- <>
102
- <Check className="h-4 w-4 mr-2" />
103
- Copied!
104
- </>
105
- ) : (
106
- <>
107
- <Copy className="h-4 w-4 mr-2" />
108
- Copy
109
- </>
110
- )}
111
- </Button>
112
- </div>
113
- </div>
114
- <p className="text-xs text-slate-500">
115
- Share this link with anyone you want to give access to this extraction. They'll need to sign in to view it.
116
- </p>
117
- </div>
118
- ) : (
119
- <div className="text-center py-8">
120
- <p className="text-sm text-slate-600">No share link available</p>
121
- </div>
122
- )}
123
-
124
- <div className="pt-4 mt-6 border-t border-slate-200">
125
- <Button
126
- type="button"
127
- variant="outline"
128
- onClick={onClose}
129
- disabled={isLoading}
130
- className="w-full h-11 rounded-xl"
131
- >
132
- Close
133
- </Button>
134
- </div>
135
- </div>
136
- </motion.div>
137
- </div>
138
- </AnimatePresence>
139
- );
140
- }
141
- import { motion, AnimatePresence } from "framer-motion";
142
- import { X, Copy, Check, Loader2 } from "lucide-react";
143
- import { Button } from "@/components/ui/button";
144
- import { Input } from "@/components/ui/input";
145
-
146
- export default function ShareLinkModal({ isOpen, onClose, shareLink, isLoading }) {
147
- const [copied, setCopied] = useState(false);
148
-
149
- useEffect(() => {
150
- if (!isOpen) {
151
- setCopied(false);
152
- }
153
- }, [isOpen]);
154
-
155
- const handleCopy = async () => {
156
- if (!shareLink) return;
157
-
158
- try {
159
- await navigator.clipboard.writeText(shareLink);
160
- setCopied(true);
161
- setTimeout(() => setCopied(false), 2000);
162
- } catch (err) {
163
- // Fallback for older browsers
164
- const textArea = document.createElement("textarea");
165
- textArea.value = shareLink;
166
- textArea.style.position = "fixed";
167
- textArea.style.opacity = "0";
168
- document.body.appendChild(textArea);
169
- textArea.select();
170
- try {
171
- document.execCommand("copy");
172
- setCopied(true);
173
- setTimeout(() => setCopied(false), 2000);
174
- } catch (fallbackErr) {
175
- console.error("Failed to copy:", fallbackErr);
176
- }
177
- document.body.removeChild(textArea);
178
- }
179
- };
180
-
181
- if (!isOpen) return null;
182
-
183
- return (
184
- <AnimatePresence>
185
- <div className="fixed inset-0 z-50 flex items-center justify-center">
186
- {/* Backdrop */}
187
- <motion.div
188
- initial={{ opacity: 0 }}
189
- animate={{ opacity: 1 }}
190
- exit={{ opacity: 0 }}
191
- className="absolute inset-0 bg-black/50 backdrop-blur-sm"
192
- onClick={onClose}
193
- />
194
-
195
- {/* Modal */}
196
- <motion.div
197
- initial={{ opacity: 0, scale: 0.95, y: 20 }}
198
- animate={{ opacity: 1, scale: 1, y: 0 }}
199
- exit={{ opacity: 0, scale: 0.95, y: 20 }}
200
- className="relative z-10 w-full max-w-md mx-4 bg-white rounded-2xl shadow-2xl overflow-hidden"
201
- onClick={(e) => e.stopPropagation()}
202
- >
203
- {/* Header */}
204
- <div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
205
- <h2 className="text-xl font-semibold text-slate-900">Copy Share Link</h2>
206
- <button
207
- onClick={onClose}
208
- disabled={isLoading}
209
- className="p-2 rounded-lg hover:bg-slate-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
210
- >
211
- <X className="h-5 w-5 text-slate-500" />
212
- </button>
213
- </div>
214
-
215
- {/* Content */}
216
- <div className="px-6 py-6">
217
- {isLoading ? (
218
- <div className="text-center py-8">
219
- <Loader2 className="h-8 w-8 mx-auto mb-4 text-indigo-600 animate-spin" />
220
- <p className="text-sm text-slate-600">Generating share link...</p>
221
- </div>
222
- ) : shareLink ? (
223
- <div className="space-y-4">
224
- <div>
225
- <label className="block text-sm font-medium text-slate-700 mb-2">
226
- Share Link
227
- </label>
228
- <div className="flex gap-2">
229
- <Input
230
- type="text"
231
- value={shareLink}
232
- readOnly
233
- className="flex-1 h-12 rounded-xl border-slate-200 bg-slate-50 text-sm font-mono"
234
- />
235
- <Button
236
- onClick={handleCopy}
237
- className="h-12 px-4 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-700 hover:to-violet-700"
238
- >
239
- {copied ? (
240
- <>
241
- <Check className="h-4 w-4 mr-2" />
242
- Copied!
243
- </>
244
- ) : (
245
- <>
246
- <Copy className="h-4 w-4 mr-2" />
247
- Copy
248
- </>
249
- )}
250
- </Button>
251
- </div>
252
- </div>
253
- <p className="text-xs text-slate-500">
254
- Share this link with anyone you want to give access to this extraction. They'll need to sign in to view it.
255
- </p>
256
- </div>
257
- ) : (
258
- <div className="text-center py-8">
259
- <p className="text-sm text-slate-600">No share link available</p>
260
- </div>
261
- )}
262
-
263
- <div className="pt-4 mt-6 border-t border-slate-200">
264
- <Button
265
- type="button"
266
- variant="outline"
267
- onClick={onClose}
268
- disabled={isLoading}
269
- className="w-full h-11 rounded-xl"
270
- >
271
- Close
272
- </Button>
273
- </div>
274
- </div>
275
- </motion.div>
276
- </div>
277
- </AnimatePresence>
278
- );
279
- }
 
5
  import { Input } from "@/components/ui/input";
6
 
7
  export default function ShareLinkModal({ isOpen, onClose, shareLink, isLoading }) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/src/components/ShareModal.jsx CHANGED
@@ -5,387 +5,3 @@ import { Button } from "@/components/ui/button";
5
  import { Input } from "@/components/ui/input";
6
 
7
  export default function ShareModal({ isOpen, onClose, onShare, extractionId }) {
8
- const [email, setEmail] = useState("");
9
- const [isLoading, setIsLoading] = useState(false);
10
- const [error, setError] = useState("");
11
- const [success, setSuccess] = useState(false);
12
- const [successMessage, setSuccessMessage] = useState("");
13
-
14
- const handleSubmit = async (e) => {
15
- e.preventDefault();
16
- setError("");
17
- setSuccess(false);
18
-
19
- // Parse and validate multiple emails (comma or semicolon separated)
20
- if (!email.trim()) {
21
- setError("Please enter at least one recipient email address");
22
- return;
23
- }
24
-
25
- // Split by comma or semicolon, trim each email, and filter out empty strings
26
- const emailList = email
27
- .split(/[,;]/)
28
- .map((e) => e.trim())
29
- .filter((e) => e.length > 0);
30
-
31
- if (emailList.length === 0) {
32
- setError("Please enter at least one recipient email address");
33
- return;
34
- }
35
-
36
- // Validate each email
37
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
38
- const invalidEmails = emailList.filter((e) => !emailRegex.test(e));
39
-
40
- if (invalidEmails.length > 0) {
41
- setError(`Invalid email address(es): ${invalidEmails.join(", ")}`);
42
- return;
43
- }
44
-
45
- setIsLoading(true);
46
- try {
47
- const result = await onShare(extractionId, emailList);
48
- setSuccessMessage(result?.message || `Successfully shared with ${emailList.length} recipient(s)`);
49
- setSuccess(true);
50
- setEmail("");
51
- // Close modal after 2 seconds
52
- setTimeout(() => {
53
- setSuccess(false);
54
- setSuccessMessage("");
55
- onClose();
56
- }, 2000);
57
- } catch (err) {
58
- setError(err.message || "Failed to share extraction. Please try again.");
59
- } finally {
60
- setIsLoading(false);
61
- }
62
- };
63
-
64
- const handleClose = () => {
65
- if (!isLoading) {
66
- setEmail("");
67
- setError("");
68
- setSuccess(false);
69
- onClose();
70
- }
71
- };
72
-
73
- if (!isOpen) return null;
74
-
75
- return (
76
- <AnimatePresence>
77
- <div className="fixed inset-0 z-50 flex items-center justify-center">
78
- {/* Backdrop */}
79
- <motion.div
80
- initial={{ opacity: 0 }}
81
- animate={{ opacity: 1 }}
82
- exit={{ opacity: 0 }}
83
- className="absolute inset-0 bg-black/50 backdrop-blur-sm"
84
- onClick={handleClose}
85
- />
86
-
87
- {/* Modal */}
88
- <motion.div
89
- initial={{ opacity: 0, scale: 0.95, y: 20 }}
90
- animate={{ opacity: 1, scale: 1, y: 0 }}
91
- exit={{ opacity: 0, scale: 0.95, y: 20 }}
92
- className="relative z-10 w-full max-w-md mx-4 bg-white rounded-2xl shadow-2xl overflow-hidden"
93
- onClick={(e) => e.stopPropagation()}
94
- >
95
- {/* Header */}
96
- <div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
97
- <h2 className="text-xl font-semibold text-slate-900">Share Output</h2>
98
- <button
99
- onClick={handleClose}
100
- disabled={isLoading}
101
- className="p-2 rounded-lg hover:bg-slate-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
102
- >
103
- <X className="h-5 w-5 text-slate-500" />
104
- </button>
105
- </div>
106
-
107
- {/* Content */}
108
- <div className="px-6 py-6">
109
- {success ? (
110
- <motion.div
111
- initial={{ opacity: 0, scale: 0.9 }}
112
- animate={{ opacity: 1, scale: 1 }}
113
- className="text-center py-8"
114
- >
115
- <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-emerald-100 flex items-center justify-center">
116
- <Send className="h-8 w-8 text-emerald-600" />
117
- </div>
118
- <h3 className="text-lg font-semibold text-slate-900 mb-2">
119
- Share Sent Successfully!
120
- </h3>
121
- <p className="text-sm text-slate-600">
122
- {successMessage || "The recipient(s) will receive an email with a link to view the extraction."}
123
- </p>
124
- </motion.div>
125
- ) : (
126
- <form onSubmit={handleSubmit} className="space-y-4">
127
- <div>
128
- <label
129
- htmlFor="recipient-email"
130
- className="block text-sm font-medium text-slate-700 mb-2"
131
- >
132
- Recipient Email(s)
133
- </label>
134
- <p className="text-xs text-slate-500 mb-2">
135
- Separate multiple emails with commas or semicolons
136
- </p>
137
- <div className="relative">
138
- <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-slate-400" />
139
- <Input
140
- id="recipient-email"
141
- type="text"
142
- value={email}
143
- onChange={(e) => setEmail(e.target.value)}
144
- placeholder="Enter email addresses (comma or semicolon separated)"
145
- className="pl-10 h-12 rounded-xl border-slate-200 focus:border-indigo-500 focus:ring-indigo-500"
146
- disabled={isLoading}
147
- autoFocus
148
- />
149
- </div>
150
- {error && (
151
- <motion.p
152
- initial={{ opacity: 0, y: -10 }}
153
- animate={{ opacity: 1, y: 0 }}
154
- className="mt-2 text-sm text-red-600"
155
- >
156
- {error}
157
- </motion.p>
158
- )}
159
- </div>
160
-
161
- <div className="pt-4 flex gap-3">
162
- <Button
163
- type="button"
164
- variant="outline"
165
- onClick={handleClose}
166
- disabled={isLoading}
167
- className="flex-1 h-11 rounded-xl"
168
- >
169
- Cancel
170
- </Button>
171
- <Button
172
- type="submit"
173
- disabled={isLoading || !email.trim()}
174
- className="flex-1 h-11 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-700 hover:to-violet-700"
175
- >
176
- {isLoading ? (
177
- <>
178
- <Loader2 className="h-4 w-4 mr-2 animate-spin" />
179
- Sending...
180
- </>
181
- ) : (
182
- <>
183
- <Send className="h-4 w-4 mr-2" />
184
- Send
185
- </>
186
- )}
187
- </Button>
188
- </div>
189
- </form>
190
- )}
191
- </div>
192
- </motion.div>
193
- </div>
194
- </AnimatePresence>
195
- );
196
- }
197
- import { motion, AnimatePresence } from "framer-motion";
198
- import { X, Mail, Send, Loader2 } from "lucide-react";
199
- import { Button } from "@/components/ui/button";
200
- import { Input } from "@/components/ui/input";
201
-
202
- export default function ShareModal({ isOpen, onClose, onShare, extractionId }) {
203
- const [email, setEmail] = useState("");
204
- const [isLoading, setIsLoading] = useState(false);
205
- const [error, setError] = useState("");
206
- const [success, setSuccess] = useState(false);
207
- const [successMessage, setSuccessMessage] = useState("");
208
-
209
- const handleSubmit = async (e) => {
210
- e.preventDefault();
211
- setError("");
212
- setSuccess(false);
213
-
214
- // Parse and validate multiple emails (comma or semicolon separated)
215
- if (!email.trim()) {
216
- setError("Please enter at least one recipient email address");
217
- return;
218
- }
219
-
220
- // Split by comma or semicolon, trim each email, and filter out empty strings
221
- const emailList = email
222
- .split(/[,;]/)
223
- .map((e) => e.trim())
224
- .filter((e) => e.length > 0);
225
-
226
- if (emailList.length === 0) {
227
- setError("Please enter at least one recipient email address");
228
- return;
229
- }
230
-
231
- // Validate each email
232
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
233
- const invalidEmails = emailList.filter((e) => !emailRegex.test(e));
234
-
235
- if (invalidEmails.length > 0) {
236
- setError(`Invalid email address(es): ${invalidEmails.join(", ")}`);
237
- return;
238
- }
239
-
240
- setIsLoading(true);
241
- try {
242
- const result = await onShare(extractionId, emailList);
243
- setSuccessMessage(result?.message || `Successfully shared with ${emailList.length} recipient(s)`);
244
- setSuccess(true);
245
- setEmail("");
246
- // Close modal after 2 seconds
247
- setTimeout(() => {
248
- setSuccess(false);
249
- setSuccessMessage("");
250
- onClose();
251
- }, 2000);
252
- } catch (err) {
253
- setError(err.message || "Failed to share extraction. Please try again.");
254
- } finally {
255
- setIsLoading(false);
256
- }
257
- };
258
-
259
- const handleClose = () => {
260
- if (!isLoading) {
261
- setEmail("");
262
- setError("");
263
- setSuccess(false);
264
- onClose();
265
- }
266
- };
267
-
268
- if (!isOpen) return null;
269
-
270
- return (
271
- <AnimatePresence>
272
- <div className="fixed inset-0 z-50 flex items-center justify-center">
273
- {/* Backdrop */}
274
- <motion.div
275
- initial={{ opacity: 0 }}
276
- animate={{ opacity: 1 }}
277
- exit={{ opacity: 0 }}
278
- className="absolute inset-0 bg-black/50 backdrop-blur-sm"
279
- onClick={handleClose}
280
- />
281
-
282
- {/* Modal */}
283
- <motion.div
284
- initial={{ opacity: 0, scale: 0.95, y: 20 }}
285
- animate={{ opacity: 1, scale: 1, y: 0 }}
286
- exit={{ opacity: 0, scale: 0.95, y: 20 }}
287
- className="relative z-10 w-full max-w-md mx-4 bg-white rounded-2xl shadow-2xl overflow-hidden"
288
- onClick={(e) => e.stopPropagation()}
289
- >
290
- {/* Header */}
291
- <div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
292
- <h2 className="text-xl font-semibold text-slate-900">Share Output</h2>
293
- <button
294
- onClick={handleClose}
295
- disabled={isLoading}
296
- className="p-2 rounded-lg hover:bg-slate-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
297
- >
298
- <X className="h-5 w-5 text-slate-500" />
299
- </button>
300
- </div>
301
-
302
- {/* Content */}
303
- <div className="px-6 py-6">
304
- {success ? (
305
- <motion.div
306
- initial={{ opacity: 0, scale: 0.9 }}
307
- animate={{ opacity: 1, scale: 1 }}
308
- className="text-center py-8"
309
- >
310
- <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-emerald-100 flex items-center justify-center">
311
- <Send className="h-8 w-8 text-emerald-600" />
312
- </div>
313
- <h3 className="text-lg font-semibold text-slate-900 mb-2">
314
- Share Sent Successfully!
315
- </h3>
316
- <p className="text-sm text-slate-600">
317
- {successMessage || "The recipient(s) will receive an email with a link to view the extraction."}
318
- </p>
319
- </motion.div>
320
- ) : (
321
- <form onSubmit={handleSubmit} className="space-y-4">
322
- <div>
323
- <label
324
- htmlFor="recipient-email"
325
- className="block text-sm font-medium text-slate-700 mb-2"
326
- >
327
- Recipient Email(s)
328
- </label>
329
- <p className="text-xs text-slate-500 mb-2">
330
- Separate multiple emails with commas or semicolons
331
- </p>
332
- <div className="relative">
333
- <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-slate-400" />
334
- <Input
335
- id="recipient-email"
336
- type="text"
337
- value={email}
338
- onChange={(e) => setEmail(e.target.value)}
339
- placeholder="Enter email addresses (comma or semicolon separated)"
340
- className="pl-10 h-12 rounded-xl border-slate-200 focus:border-indigo-500 focus:ring-indigo-500"
341
- disabled={isLoading}
342
- autoFocus
343
- />
344
- </div>
345
- {error && (
346
- <motion.p
347
- initial={{ opacity: 0, y: -10 }}
348
- animate={{ opacity: 1, y: 0 }}
349
- className="mt-2 text-sm text-red-600"
350
- >
351
- {error}
352
- </motion.p>
353
- )}
354
- </div>
355
-
356
- <div className="pt-4 flex gap-3">
357
- <Button
358
- type="button"
359
- variant="outline"
360
- onClick={handleClose}
361
- disabled={isLoading}
362
- className="flex-1 h-11 rounded-xl"
363
- >
364
- Cancel
365
- </Button>
366
- <Button
367
- type="submit"
368
- disabled={isLoading || !email.trim()}
369
- className="flex-1 h-11 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-700 hover:to-violet-700"
370
- >
371
- {isLoading ? (
372
- <>
373
- <Loader2 className="h-4 w-4 mr-2 animate-spin" />
374
- Sending...
375
- </>
376
- ) : (
377
- <>
378
- <Send className="h-4 w-4 mr-2" />
379
- Send
380
- </>
381
- )}
382
- </Button>
383
- </div>
384
- </form>
385
- )}
386
- </div>
387
- </motion.div>
388
- </div>
389
- </AnimatePresence>
390
- );
391
- }
 
5
  import { Input } from "@/components/ui/input";
6
 
7
  export default function ShareModal({ isOpen, onClose, onShare, extractionId }) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/src/components/ocr/DocumentPreview.jsx CHANGED
@@ -4,454 +4,3 @@ import { FileText, ZoomIn, ZoomOut, RotateCw } from "lucide-react";
4
  import { Button } from "@/components/ui/button";
5
 
6
  export default function DocumentPreview({ file, isProcessing, isFromHistory = false }) {
7
- const [previewUrls, setPreviewUrls] = useState([]);
8
- const [zoom, setZoom] = useState(100);
9
- const [rotation, setRotation] = useState(0);
10
- const objectUrlsRef = useRef([]);
11
-
12
- useEffect(() => {
13
- if (!file) {
14
- // Cleanup previous URLs
15
- objectUrlsRef.current.forEach((url) => {
16
- if (url && url.startsWith("blob:")) {
17
- URL.revokeObjectURL(url);
18
- }
19
- });
20
- objectUrlsRef.current = [];
21
- setPreviewUrls([]);
22
- return;
23
- }
24
-
25
- const loadPreview = async () => {
26
- const urls = [];
27
- const newObjectUrls = [];
28
-
29
- // Check if it's a PDF
30
- if (file.type === "application/pdf" || file.name?.toLowerCase().endsWith(".pdf")) {
31
- try {
32
- // Use pdf.js to render PDF pages
33
- const pdfjsLib = await import("pdfjs-dist");
34
-
35
- // Configure worker - use jsdelivr CDN which is more reliable
36
- // This will use the same version as the installed package
37
- const version = pdfjsLib.version || "4.0.379";
38
- pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdn.jsdelivr.net/npm/pdfjs-dist@${version}/build/pdf.worker.min.mjs`;
39
-
40
- const arrayBuffer = await file.arrayBuffer();
41
- const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
42
- const numPages = pdf.numPages;
43
-
44
- for (let pageNum = 1; pageNum <= numPages; pageNum++) {
45
- const page = await pdf.getPage(pageNum);
46
- const viewport = page.getViewport({ scale: 2.0 });
47
-
48
- const canvas = document.createElement("canvas");
49
- const context = canvas.getContext("2d");
50
- canvas.height = viewport.height;
51
- canvas.width = viewport.width;
52
-
53
- await page.render({
54
- canvasContext: context,
55
- viewport: viewport,
56
- }).promise;
57
-
58
- urls.push(canvas.toDataURL("image/jpeg", 0.95));
59
- }
60
- } catch (error) {
61
- console.error("Error loading PDF:", error);
62
- // Fallback: show error message
63
- urls.push(null);
64
- }
65
- } else {
66
- // For images, create object URL
67
- const url = URL.createObjectURL(file);
68
- urls.push(url);
69
- newObjectUrls.push(url);
70
- }
71
-
72
- // Cleanup old object URLs
73
- objectUrlsRef.current.forEach((url) => {
74
- if (url && url.startsWith("blob:")) {
75
- URL.revokeObjectURL(url);
76
- }
77
- });
78
- objectUrlsRef.current = newObjectUrls;
79
- setPreviewUrls(urls);
80
- };
81
-
82
- loadPreview();
83
-
84
- // Cleanup function - revoke object URLs when component unmounts or file changes
85
- return () => {
86
- objectUrlsRef.current.forEach((url) => {
87
- if (url && url.startsWith("blob:")) {
88
- URL.revokeObjectURL(url);
89
- }
90
- });
91
- objectUrlsRef.current = [];
92
- };
93
- }, [file]);
94
-
95
- return (
96
- <div className="h-full flex flex-col bg-white rounded-2xl border border-slate-200 overflow-hidden">
97
- {/* Header */}
98
- <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
99
- <div className="flex items-center gap-3">
100
- <div className="h-8 w-8 rounded-lg bg-indigo-50 flex items-center justify-center">
101
- <FileText className="h-4 w-4 text-indigo-600" />
102
- </div>
103
- <div>
104
- <h3 className="font-semibold text-slate-800 text-sm">Document Preview</h3>
105
- <p className="text-xs text-slate-400">{file?.name || "No file selected"}</p>
106
- </div>
107
- </div>
108
-
109
- {file && (
110
- <div className="flex items-center gap-1">
111
- <Button
112
- variant="ghost"
113
- size="icon"
114
- className="h-8 w-8 text-slate-400 hover:text-slate-600"
115
- onClick={() => setZoom(Math.max(50, zoom - 25))}
116
- >
117
- <ZoomOut className="h-4 w-4" />
118
- </Button>
119
- <span className="text-xs text-slate-500 w-12 text-center">{zoom}%</span>
120
- <Button
121
- variant="ghost"
122
- size="icon"
123
- className="h-8 w-8 text-slate-400 hover:text-slate-600"
124
- onClick={() => setZoom(Math.min(200, zoom + 25))}
125
- >
126
- <ZoomIn className="h-4 w-4" />
127
- </Button>
128
- <div className="w-px h-4 bg-slate-200 mx-2" />
129
- <Button
130
- variant="ghost"
131
- size="icon"
132
- className="h-8 w-8 text-slate-400 hover:text-slate-600"
133
- onClick={() => setRotation((rotation + 90) % 360)}
134
- >
135
- <RotateCw className="h-4 w-4" />
136
- </Button>
137
- </div>
138
- )}
139
- </div>
140
-
141
- {/* Preview Area */}
142
- <div className="flex-1 p-6 bg-slate-50/50 overflow-auto">
143
- {!file ? (
144
- <div className="h-full flex items-center justify-center">
145
- <div className="text-center">
146
- <div className="h-20 w-20 mx-auto rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
147
- <FileText className="h-10 w-10 text-slate-300" />
148
- </div>
149
- <p className="text-slate-400 text-sm">Upload a document to preview</p>
150
- </div>
151
- </div>
152
- ) : previewUrls.length === 0 ? (
153
- <div className="h-full flex items-center justify-center">
154
- <div className="text-center">
155
- <div className="h-20 w-20 mx-auto rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
156
- <FileText className="h-10 w-10 text-slate-300" />
157
- </div>
158
- <p className="text-slate-400 text-sm">Loading preview...</p>
159
- </div>
160
- </div>
161
- ) : (
162
- <div className="space-y-4">
163
- {previewUrls.map((url, index) => (
164
- <motion.div
165
- key={index}
166
- initial={{ opacity: 0, y: 20 }}
167
- animate={{ opacity: 1, y: 0 }}
168
- transition={{ delay: index * 0.1 }}
169
- className="relative bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden flex items-center justify-center"
170
- style={{
171
- minHeight: "400px",
172
- }}
173
- >
174
- {url ? (
175
- <img
176
- src={url}
177
- alt={`Page ${index + 1}`}
178
- className="w-full h-auto"
179
- style={{
180
- transform: `scale(${zoom / 100}) rotate(${rotation}deg)`,
181
- maxWidth: "100%",
182
- objectFit: "contain",
183
- transition: "transform 0.2s ease",
184
- }}
185
- />
186
- ) : (
187
- <div className="p-8 text-center">
188
- <p className="text-slate-400 text-sm">
189
- {isFromHistory
190
- ? "Original document not available for historical extractions"
191
- : "Unable to load preview"}
192
- </p>
193
- </div>
194
- )}
195
-
196
- {/* Processing overlay */}
197
- {isProcessing && (
198
- <motion.div
199
- initial={{ opacity: 0 }}
200
- animate={{ opacity: 1 }}
201
- className="absolute inset-0 bg-indigo-600/5 backdrop-blur-[1px] pointer-events-none"
202
- >
203
- <motion.div
204
- initial={{ top: 0 }}
205
- animate={{ top: "100%" }}
206
- transition={{
207
- duration: 2,
208
- repeat: Infinity,
209
- ease: "linear",
210
- }}
211
- className="absolute left-0 right-0 h-1 bg-gradient-to-r from-transparent via-indigo-500 to-transparent"
212
- />
213
- </motion.div>
214
- )}
215
-
216
- {/* Page number */}
217
- {previewUrls.length > 1 && (
218
- <div className="absolute bottom-3 right-3 text-xs text-slate-400 bg-white/90 px-2 py-1 rounded">
219
- Page {index + 1}
220
- </div>
221
- )}
222
- </motion.div>
223
- ))}
224
- </div>
225
- )}
226
- </div>
227
- </div>
228
- );
229
- }
230
- import { motion } from "framer-motion";
231
- import { FileText, ZoomIn, ZoomOut, RotateCw } from "lucide-react";
232
- import { Button } from "@/components/ui/button";
233
-
234
- export default function DocumentPreview({ file, isProcessing, isFromHistory = false }) {
235
- const [previewUrls, setPreviewUrls] = useState([]);
236
- const [zoom, setZoom] = useState(100);
237
- const [rotation, setRotation] = useState(0);
238
- const objectUrlsRef = useRef([]);
239
-
240
- useEffect(() => {
241
- if (!file) {
242
- // Cleanup previous URLs
243
- objectUrlsRef.current.forEach((url) => {
244
- if (url && url.startsWith("blob:")) {
245
- URL.revokeObjectURL(url);
246
- }
247
- });
248
- objectUrlsRef.current = [];
249
- setPreviewUrls([]);
250
- return;
251
- }
252
-
253
- const loadPreview = async () => {
254
- const urls = [];
255
- const newObjectUrls = [];
256
-
257
- // Check if it's a PDF
258
- if (file.type === "application/pdf" || file.name?.toLowerCase().endsWith(".pdf")) {
259
- try {
260
- // Use pdf.js to render PDF pages
261
- const pdfjsLib = await import("pdfjs-dist");
262
-
263
- // Configure worker - use jsdelivr CDN which is more reliable
264
- // This will use the same version as the installed package
265
- const version = pdfjsLib.version || "4.0.379";
266
- pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdn.jsdelivr.net/npm/pdfjs-dist@${version}/build/pdf.worker.min.mjs`;
267
-
268
- const arrayBuffer = await file.arrayBuffer();
269
- const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
270
- const numPages = pdf.numPages;
271
-
272
- for (let pageNum = 1; pageNum <= numPages; pageNum++) {
273
- const page = await pdf.getPage(pageNum);
274
- const viewport = page.getViewport({ scale: 2.0 });
275
-
276
- const canvas = document.createElement("canvas");
277
- const context = canvas.getContext("2d");
278
- canvas.height = viewport.height;
279
- canvas.width = viewport.width;
280
-
281
- await page.render({
282
- canvasContext: context,
283
- viewport: viewport,
284
- }).promise;
285
-
286
- urls.push(canvas.toDataURL("image/jpeg", 0.95));
287
- }
288
- } catch (error) {
289
- console.error("Error loading PDF:", error);
290
- // Fallback: show error message
291
- urls.push(null);
292
- }
293
- } else {
294
- // For images, create object URL
295
- const url = URL.createObjectURL(file);
296
- urls.push(url);
297
- newObjectUrls.push(url);
298
- }
299
-
300
- // Cleanup old object URLs
301
- objectUrlsRef.current.forEach((url) => {
302
- if (url && url.startsWith("blob:")) {
303
- URL.revokeObjectURL(url);
304
- }
305
- });
306
- objectUrlsRef.current = newObjectUrls;
307
- setPreviewUrls(urls);
308
- };
309
-
310
- loadPreview();
311
-
312
- // Cleanup function - revoke object URLs when component unmounts or file changes
313
- return () => {
314
- objectUrlsRef.current.forEach((url) => {
315
- if (url && url.startsWith("blob:")) {
316
- URL.revokeObjectURL(url);
317
- }
318
- });
319
- objectUrlsRef.current = [];
320
- };
321
- }, [file]);
322
-
323
- return (
324
- <div className="h-full flex flex-col bg-white rounded-2xl border border-slate-200 overflow-hidden">
325
- {/* Header */}
326
- <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
327
- <div className="flex items-center gap-3">
328
- <div className="h-8 w-8 rounded-lg bg-indigo-50 flex items-center justify-center">
329
- <FileText className="h-4 w-4 text-indigo-600" />
330
- </div>
331
- <div>
332
- <h3 className="font-semibold text-slate-800 text-sm">Document Preview</h3>
333
- <p className="text-xs text-slate-400">{file?.name || "No file selected"}</p>
334
- </div>
335
- </div>
336
-
337
- {file && (
338
- <div className="flex items-center gap-1">
339
- <Button
340
- variant="ghost"
341
- size="icon"
342
- className="h-8 w-8 text-slate-400 hover:text-slate-600"
343
- onClick={() => setZoom(Math.max(50, zoom - 25))}
344
- >
345
- <ZoomOut className="h-4 w-4" />
346
- </Button>
347
- <span className="text-xs text-slate-500 w-12 text-center">{zoom}%</span>
348
- <Button
349
- variant="ghost"
350
- size="icon"
351
- className="h-8 w-8 text-slate-400 hover:text-slate-600"
352
- onClick={() => setZoom(Math.min(200, zoom + 25))}
353
- >
354
- <ZoomIn className="h-4 w-4" />
355
- </Button>
356
- <div className="w-px h-4 bg-slate-200 mx-2" />
357
- <Button
358
- variant="ghost"
359
- size="icon"
360
- className="h-8 w-8 text-slate-400 hover:text-slate-600"
361
- onClick={() => setRotation((rotation + 90) % 360)}
362
- >
363
- <RotateCw className="h-4 w-4" />
364
- </Button>
365
- </div>
366
- )}
367
- </div>
368
-
369
- {/* Preview Area */}
370
- <div className="flex-1 p-6 bg-slate-50/50 overflow-auto">
371
- {!file ? (
372
- <div className="h-full flex items-center justify-center">
373
- <div className="text-center">
374
- <div className="h-20 w-20 mx-auto rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
375
- <FileText className="h-10 w-10 text-slate-300" />
376
- </div>
377
- <p className="text-slate-400 text-sm">Upload a document to preview</p>
378
- </div>
379
- </div>
380
- ) : previewUrls.length === 0 ? (
381
- <div className="h-full flex items-center justify-center">
382
- <div className="text-center">
383
- <div className="h-20 w-20 mx-auto rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
384
- <FileText className="h-10 w-10 text-slate-300" />
385
- </div>
386
- <p className="text-slate-400 text-sm">Loading preview...</p>
387
- </div>
388
- </div>
389
- ) : (
390
- <div className="space-y-4">
391
- {previewUrls.map((url, index) => (
392
- <motion.div
393
- key={index}
394
- initial={{ opacity: 0, y: 20 }}
395
- animate={{ opacity: 1, y: 0 }}
396
- transition={{ delay: index * 0.1 }}
397
- className="relative bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden flex items-center justify-center"
398
- style={{
399
- minHeight: "400px",
400
- }}
401
- >
402
- {url ? (
403
- <img
404
- src={url}
405
- alt={`Page ${index + 1}`}
406
- className="w-full h-auto"
407
- style={{
408
- transform: `scale(${zoom / 100}) rotate(${rotation}deg)`,
409
- maxWidth: "100%",
410
- objectFit: "contain",
411
- transition: "transform 0.2s ease",
412
- }}
413
- />
414
- ) : (
415
- <div className="p-8 text-center">
416
- <p className="text-slate-400 text-sm">
417
- {isFromHistory
418
- ? "Original document not available for historical extractions"
419
- : "Unable to load preview"}
420
- </p>
421
- </div>
422
- )}
423
-
424
- {/* Processing overlay */}
425
- {isProcessing && (
426
- <motion.div
427
- initial={{ opacity: 0 }}
428
- animate={{ opacity: 1 }}
429
- className="absolute inset-0 bg-indigo-600/5 backdrop-blur-[1px] pointer-events-none"
430
- >
431
- <motion.div
432
- initial={{ top: 0 }}
433
- animate={{ top: "100%" }}
434
- transition={{
435
- duration: 2,
436
- repeat: Infinity,
437
- ease: "linear",
438
- }}
439
- className="absolute left-0 right-0 h-1 bg-gradient-to-r from-transparent via-indigo-500 to-transparent"
440
- />
441
- </motion.div>
442
- )}
443
-
444
- {/* Page number */}
445
- {previewUrls.length > 1 && (
446
- <div className="absolute bottom-3 right-3 text-xs text-slate-400 bg-white/90 px-2 py-1 rounded">
447
- Page {index + 1}
448
- </div>
449
- )}
450
- </motion.div>
451
- ))}
452
- </div>
453
- )}
454
- </div>
455
- </div>
456
- );
457
- }
 
4
  import { Button } from "@/components/ui/button";
5
 
6
  export default function DocumentPreview({ file, isProcessing, isFromHistory = false }) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/src/components/ocr/ExtractionOutput.jsx CHANGED
@@ -1199,1203 +1199,3 @@ export default function ExtractionOutput({ hasFile, isProcessing, isComplete, ex
1199
  </div>
1200
  );
1201
  }
1202
- import { motion, AnimatePresence } from "framer-motion";
1203
- import {
1204
- Code2,
1205
- Copy,
1206
- Check,
1207
- Braces,
1208
- FileCode2,
1209
- FileText,
1210
- Sparkles,
1211
- ChevronDown,
1212
- Upload,
1213
- } from "lucide-react";
1214
- import { Button } from "@/components/ui/button";
1215
- import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
1216
- import { cn } from "@/lib/utils";
1217
-
1218
- // Helper function to convert pipe-separated tables to HTML tables
1219
- function convertPipeTablesToHTML(text) {
1220
- if (!text) return text;
1221
-
1222
- const lines = text.split('\n');
1223
- const result = [];
1224
- let i = 0;
1225
-
1226
- while (i < lines.length) {
1227
- const line = lines[i];
1228
-
1229
- // Check if this line looks like a table row (has multiple pipes)
1230
- if (line.includes('|') && line.split('|').length >= 3) {
1231
- // Check if it's a separator line (only |, -, :, spaces)
1232
- const isSeparator = /^[\s|\-:]+$/.test(line.trim());
1233
-
1234
- if (!isSeparator) {
1235
- // Start of a table - collect all table rows
1236
- const tableRows = [];
1237
- let j = i;
1238
-
1239
- // Collect header row
1240
- const headerLine = lines[j];
1241
- const headerCells = headerLine.split('|').map(cell => cell.trim()).filter(cell => cell || cell === '');
1242
- // Remove empty cells at start/end
1243
- if (headerCells.length > 0 && !headerCells[0]) headerCells.shift();
1244
- if (headerCells.length > 0 && !headerCells[headerCells.length - 1]) headerCells.pop();
1245
-
1246
- if (headerCells.length >= 2) {
1247
- tableRows.push(headerCells);
1248
- j++;
1249
-
1250
- // Skip separator line if present
1251
- if (j < lines.length && /^[\s|\-:]+$/.test(lines[j].trim())) {
1252
- j++;
1253
- }
1254
-
1255
- // Collect data rows
1256
- while (j < lines.length) {
1257
- const rowLine = lines[j];
1258
- if (!rowLine.trim()) break; // Empty line ends table
1259
-
1260
- // Check if it's still a table row
1261
- if (rowLine.includes('|') && rowLine.split('|').length >= 2) {
1262
- const isRowSeparator = /^[\s|\-:]+$/.test(rowLine.trim());
1263
- if (!isRowSeparator) {
1264
- const rowCells = rowLine.split('|').map(cell => cell.trim());
1265
- // Remove empty cells at start/end
1266
- if (rowCells.length > 0 && !rowCells[0]) rowCells.shift();
1267
- if (rowCells.length > 0 && !rowCells[rowCells.length - 1]) rowCells.pop();
1268
- tableRows.push(rowCells);
1269
- j++;
1270
- } else {
1271
- j++;
1272
- }
1273
- } else {
1274
- break; // Not a table row anymore
1275
- }
1276
- }
1277
-
1278
- // Convert to HTML table
1279
- if (tableRows.length > 0) {
1280
- let htmlTable = '<table class="border-collapse border border-gray-300 w-full my-4">\n<thead>\n<tr>';
1281
-
1282
- // Header row
1283
- tableRows[0].forEach(cell => {
1284
- htmlTable += `<th class="border border-gray-300 px-4 py-2 bg-gray-100 font-semibold text-left">${escapeHtml(cell)}</th>`;
1285
- });
1286
- htmlTable += '</tr>\n</thead>\n<tbody>\n';
1287
-
1288
- // Data rows
1289
- for (let rowIdx = 1; rowIdx < tableRows.length; rowIdx++) {
1290
- htmlTable += '<tr>';
1291
- tableRows[rowIdx].forEach((cell, colIdx) => {
1292
- // Use header cell count to ensure alignment
1293
- const cellContent = cell || '';
1294
- htmlTable += `<td class="border border-gray-300 px-4 py-2">${escapeHtml(cellContent)}</td>`;
1295
- });
1296
- htmlTable += '</tr>\n';
1297
- }
1298
-
1299
- htmlTable += '</tbody>\n</table>';
1300
- result.push(htmlTable);
1301
- i = j;
1302
- continue;
1303
- }
1304
- }
1305
- }
1306
- }
1307
-
1308
- // Not a table row, add as-is
1309
- result.push(line);
1310
- i++;
1311
- }
1312
-
1313
- return result.join('\n');
1314
- }
1315
-
1316
- // Helper function to escape HTML
1317
- function escapeHtml(text) {
1318
- if (!text) return '';
1319
- const div = document.createElement('div');
1320
- div.textContent = text;
1321
- return div.innerHTML;
1322
- }
1323
-
1324
- // Helper function to convert markdown/HTML text to safe HTML
1325
- function renderMarkdownToHTML(text) {
1326
- if (!text) return "";
1327
-
1328
- let html = text;
1329
-
1330
- // FIRST: Convert pipe-separated tables to HTML tables
1331
- html = convertPipeTablesToHTML(html);
1332
-
1333
- // Convert LaTeX-style superscripts/subscripts FIRST (before protecting tables)
1334
- // This ensures they're converted everywhere, including inside tables
1335
-
1336
- // Convert LaTeX-style superscripts: $^{text}$ or $^text$ to <sup>text</sup>
1337
- html = html.replace(/\$\s*\^\s*\{([^}]+)\}\s*\$/g, '<sup>$1</sup>');
1338
- html = html.replace(/\$\s*\^\s*([^\s$<>]+)\s*\$/g, '<sup>$1</sup>');
1339
-
1340
- // Convert LaTeX-style subscripts: $_{text}$ or $_text$ to <sub>text</sub>
1341
- html = html.replace(/\$\s*_\s*\{([^}]+)\}\s*\$/g, '<sub>$1</sub>');
1342
- html = html.replace(/\$\s*_\s*([^\s$<>]+)\s*\$/g, '<sub>$1</sub>');
1343
-
1344
- // Split by HTML tags to preserve existing HTML (like tables)
1345
- // Process markdown only in non-HTML sections
1346
-
1347
- // First, protect existing HTML blocks (tables, etc.)
1348
- const htmlBlocks = [];
1349
- let htmlBlockIndex = 0;
1350
-
1351
- // Extract and protect HTML table blocks
1352
- html = html.replace(/<table[\s\S]*?<\/table>/gi, (match) => {
1353
- const placeholder = `__HTML_BLOCK_${htmlBlockIndex}__`;
1354
- htmlBlocks[htmlBlockIndex] = match;
1355
- htmlBlockIndex++;
1356
- return placeholder;
1357
- });
1358
-
1359
- // Convert markdown headers (only if not inside HTML)
1360
- html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>');
1361
- html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>');
1362
- html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>');
1363
-
1364
- // Convert markdown bold/italic (but not inside HTML tags)
1365
- html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
1366
- html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
1367
-
1368
- // Convert markdown links
1369
- html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
1370
-
1371
- // Convert line breaks to paragraphs (but preserve structure around HTML blocks)
1372
- const parts = html.split(/(__HTML_BLOCK_\d+__)/);
1373
- const processedParts = parts.map((part, index) => {
1374
- if (part.match(/^__HTML_BLOCK_\d+__$/)) {
1375
- // Restore HTML block
1376
- const blockIndex = parseInt(part.match(/\d+/)[0]);
1377
- return htmlBlocks[blockIndex];
1378
- } else {
1379
- // Process markdown in this part
1380
- let processed = part;
1381
-
1382
- // Convert double line breaks to paragraph breaks
1383
- processed = processed.replace(/\n\n+/g, '</p><p>');
1384
- // Convert single line breaks to <br> (but not if already in a tag)
1385
- processed = processed.replace(/([^\n>])\n([^\n<])/g, '$1<br>$2');
1386
-
1387
- // Wrap in paragraph if there's content
1388
- if (processed.trim() && !processed.trim().startsWith('<')) {
1389
- processed = '<p>' + processed + '</p>';
1390
- }
1391
-
1392
- return processed;
1393
- }
1394
- });
1395
-
1396
- html = processedParts.join('');
1397
-
1398
- // Process LaTeX notation in restored HTML blocks (tables) as well
1399
- // This handles any LaTeX that might be in table cells
1400
- html = html.replace(/(<td[^>]*>|<th[^>]*>)([^<]*)\$\s*\^\s*\{([^}]+)\}\s*\$([^<]*)(<\/td>|<\/th>)/gi,
1401
- (match, openTag, before, supText, after, closeTag) => {
1402
- return openTag + before + '<sup>' + supText + '</sup>' + after + closeTag;
1403
- });
1404
- html = html.replace(/(<td[^>]*>|<th[^>]*>)([^<]*)\$\s*\^\s*([^\s$<>]+)\s*\$([^<]*)(<\/td>|<\/th>)/gi,
1405
- (match, openTag, before, supText, after, closeTag) => {
1406
- return openTag + before + '<sup>' + supText + '</sup>' + after + closeTag;
1407
- });
1408
- html = html.replace(/(<td[^>]*>|<th[^>]*>)([^<]*)\$\s*_\s*\{([^}]+)\}\s*\$([^<]*)(<\/td>|<\/th>)/gi,
1409
- (match, openTag, before, subText, after, closeTag) => {
1410
- return openTag + before + '<sub>' + subText + '</sub>' + after + closeTag;
1411
- });
1412
- html = html.replace(/(<td[^>]*>|<th[^>]*>)([^<]*)\$\s*_\s*([^\s$<>]+)\s*\$([^<]*)(<\/td>|<\/th>)/gi,
1413
- (match, openTag, before, subText, after, closeTag) => {
1414
- return openTag + before + '<sub>' + subText + '</sub>' + after + closeTag;
1415
- });
1416
-
1417
- // Clean up empty paragraphs and fix paragraph structure
1418
- html = html.replace(/<p><\/p>/g, '');
1419
- html = html.replace(/<p>\s*<br>\s*<\/p>/g, '');
1420
- html = html.replace(/<p>\s*<\/p>/g, '');
1421
-
1422
- // Ensure proper spacing around HTML blocks
1423
- html = html.replace(/(<\/table>)\s*(<h[1-3])/g, '$1</p><p>$2');
1424
- html = html.replace(/(<\/h[1-3]>)\s*(<table)/g, '$1<p>$2');
1425
- html = html.replace(/(<\/table>)\s*(<p>)/g, '$1$2');
1426
-
1427
- return html;
1428
- }
1429
-
1430
- // Mock extracted data
1431
- const mockData = {
1432
- document: {
1433
- type: "Invoice",
1434
- confidence: 0.98,
1435
- },
1436
- vendor: {
1437
- name: "Acme Corporation",
1438
- address: "123 Business Ave, Suite 400",
1439
- city: "San Francisco",
1440
- state: "CA",
1441
- zip: "94102",
1442
- phone: "+1 (555) 123-4567",
1443
- },
1444
- invoice: {
1445
- number: "INV-2024-0847",
1446
- date: "2024-01-15",
1447
- due_date: "2024-02-14",
1448
- po_number: "PO-9823",
1449
- },
1450
- items: [
1451
- { description: "Professional Services", quantity: 40, unit_price: 150.0, total: 6000.0 },
1452
- { description: "Software License", quantity: 5, unit_price: 299.99, total: 1499.95 },
1453
- { description: "Support Package", quantity: 1, unit_price: 500.0, total: 500.0 },
1454
- ],
1455
- totals: {
1456
- subtotal: 7999.95,
1457
- tax_rate: 0.0875,
1458
- tax_amount: 699.99,
1459
- total: 8699.94,
1460
- },
1461
- };
1462
-
1463
- const mockXML = `<?xml version="1.0" encoding="UTF-8"?>
1464
- <extraction>
1465
- <document type="Invoice" confidence="0.98"/>
1466
- <vendor>
1467
- <name>Acme Corporation</name>
1468
- <address>123 Business Ave, Suite 400</address>
1469
- <city>San Francisco</city>
1470
- <state>CA</state>
1471
- <zip>94102</zip>
1472
- </vendor>
1473
- <invoice>
1474
- <number>INV-2024-0847</number>
1475
- <date>2024-01-15</date>
1476
- <due_date>2024-02-14</due_date>
1477
- </invoice>
1478
- <items>
1479
- <item>
1480
- <description>Professional Services</description>
1481
- <quantity>40</quantity>
1482
- <total>6000.00</total>
1483
- </item>
1484
- </items>
1485
- <totals>
1486
- <subtotal>7999.95</subtotal>
1487
- <tax>699.99</tax>
1488
- <total>8699.94</total>
1489
- </totals>
1490
- </extraction>`;
1491
-
1492
- const mockText = `INVOICE
1493
-
1494
- ACME CORPORATION
1495
- 123 Business Ave, Suite 400
1496
- San Francisco, CA 94102
1497
- Phone: +1 (555) 123-4567
1498
-
1499
- Invoice Number: INV-2024-0847
1500
- Invoice Date: January 15, 2024
1501
- Due Date: February 14, 2024
1502
- PO Number: PO-9823
1503
-
1504
- BILL TO:
1505
- Customer Name
1506
- 456 Client Street
1507
- New York, NY 10001
1508
-
1509
- ITEMS:
1510
- ─────────────────────────────────────────────────────────
1511
- Description Qty Unit Price Total
1512
- ─────────────────────────────────────────────────────────
1513
- Professional Services 40 $150.00 $6,000.00
1514
- Software License 5 $299.99 $1,499.95
1515
- Support Package 1 $500.00 $500.00
1516
- ─────────────────────────────────────────────────────────
1517
-
1518
- Subtotal: $7,999.95
1519
- Tax (8.75%): $699.99
1520
- ─────────────────────────
1521
- TOTAL: $8,699.94
1522
-
1523
- Payment Terms: Net 30
1524
- Thank you for your business!`;
1525
-
1526
- // Helper function to convert object to XML
1527
- // Prepare fields for JSON/XML output - remove duplicates and restructure
1528
- function prepareFieldsForOutput(fields, format = "json") {
1529
- if (!fields || typeof fields !== "object") {
1530
- return fields;
1531
- }
1532
-
1533
- const output = { ...fields };
1534
-
1535
- // Extract Fields from root level if it exists
1536
- const rootFields = output.Fields;
1537
- // Remove Fields from output temporarily (will be added back at top)
1538
- delete output.Fields;
1539
-
1540
- // Remove full_text from top-level if pages array exists (to avoid duplication)
1541
- if (output.pages && Array.isArray(output.pages) && output.pages.length > 0) {
1542
- delete output.full_text;
1543
-
1544
- // Clean up each page: remove full_text from page.fields (it duplicates page.text)
1545
- output.pages = output.pages.map(page => {
1546
- const cleanedPage = { ...page };
1547
- if (cleanedPage.fields && typeof cleanedPage.fields === "object") {
1548
- const cleanedFields = { ...cleanedPage.fields };
1549
- // Remove full_text from page fields (duplicates page.text)
1550
- delete cleanedFields.full_text;
1551
- cleanedPage.fields = cleanedFields;
1552
- }
1553
- return cleanedPage;
1554
- });
1555
- }
1556
-
1557
- // For JSON and XML: restructure pages into separate top-level fields (page_1, page_2, etc.)
1558
- if ((format === "json" || format === "xml") && output.pages && Array.isArray(output.pages)) {
1559
- // Get top-level field keys (these are merged from all pages - avoid duplicating in page fields)
1560
- const topLevelKeys = new Set(Object.keys(output).filter(k => k !== "pages" && k !== "full_text" && k !== "Fields"));
1561
-
1562
- output.pages.forEach((page, idx) => {
1563
- const pageNum = page.page_number || idx + 1;
1564
- const pageFields = page.fields || {};
1565
-
1566
- // Remove duplicate fields from page.fields:
1567
- // 1. Remove full_text (duplicates page.text)
1568
- // 2. Remove fields that match top-level fields (already shown at root)
1569
- const cleanedPageFields = {};
1570
- for (const [key, value] of Object.entries(pageFields)) {
1571
- // Skip full_text and fields that match top-level exactly
1572
- if (key !== "full_text" && (!topLevelKeys.has(key) || (value !== output[key]))) {
1573
- cleanedPageFields[key] = value;
1574
- }
1575
- }
1576
-
1577
- const pageObj = {
1578
- text: page.text || "",
1579
- confidence: page.confidence || 0,
1580
- doc_type: page.doc_type || "other"
1581
- };
1582
-
1583
- // Add table and footer_notes if they exist
1584
- if (page.table && Array.isArray(page.table) && page.table.length > 0) {
1585
- pageObj.table = page.table;
1586
- }
1587
- if (page.footer_notes && Array.isArray(page.footer_notes) && page.footer_notes.length > 0) {
1588
- pageObj.footer_notes = page.footer_notes;
1589
- }
1590
-
1591
- // Only add fields if there are unique page-specific fields
1592
- if (Object.keys(cleanedPageFields).length > 0) {
1593
- pageObj.fields = cleanedPageFields;
1594
- }
1595
-
1596
- output[`page_${pageNum}`] = pageObj;
1597
- });
1598
- // Remove pages array - we now have page_1, page_2, etc. as separate fields
1599
- delete output.pages;
1600
- }
1601
-
1602
- // Handle page_X structure (from backend) - remove Fields from page objects if they exist
1603
- if (output && typeof output === "object") {
1604
- const pageKeys = Object.keys(output).filter(k => k.startsWith("page_"));
1605
- for (const pageKey of pageKeys) {
1606
- const pageData = output[pageKey];
1607
- if (pageData && typeof pageData === "object") {
1608
- // Remove Fields from page objects (it's now at root level)
1609
- delete pageData.Fields;
1610
- delete pageData.metadata;
1611
- }
1612
- }
1613
- }
1614
-
1615
- // Rebuild output with Fields at the top (only if it exists and is not empty)
1616
- const finalOutput = {};
1617
- if (rootFields && typeof rootFields === "object" && Object.keys(rootFields).length > 0) {
1618
- finalOutput.Fields = rootFields;
1619
- }
1620
-
1621
- // Add all other keys
1622
- Object.keys(output).forEach(key => {
1623
- finalOutput[key] = output[key];
1624
- });
1625
-
1626
- return finalOutput;
1627
- }
1628
-
1629
- function objectToXML(obj, rootName = "extraction") {
1630
- // Prepare fields - remove full_text if pages exist
1631
- const preparedObj = prepareFieldsForOutput(obj, "xml");
1632
-
1633
- let xml = `<?xml version="1.0" encoding="UTF-8"?>\n<${rootName}>\n`;
1634
-
1635
- const convert = (obj, indent = " ") => {
1636
- for (const [key, value] of Object.entries(obj)) {
1637
- if (value === null || value === undefined) continue;
1638
-
1639
- // Skip full_text if pages exist (already handled in prepareFieldsForOutput)
1640
- if (key === "full_text" && obj.pages && Array.isArray(obj.pages) && obj.pages.length > 0) {
1641
- continue;
1642
- }
1643
-
1644
- if (Array.isArray(value)) {
1645
- value.forEach((item) => {
1646
- xml += `${indent}<${key}>\n`;
1647
- if (typeof item === "object") {
1648
- convert(item, indent + " ");
1649
- } else {
1650
- xml += `${indent} ${escapeXML(String(item))}\n`;
1651
- }
1652
- xml += `${indent}</${key}>\n`;
1653
- });
1654
- } else if (typeof value === "object") {
1655
- xml += `${indent}<${key}>\n`;
1656
- convert(value, indent + " ");
1657
- xml += `${indent}</${key}>\n`;
1658
- } else {
1659
- xml += `${indent}<${key}>${escapeXML(String(value))}</${key}>\n`;
1660
- }
1661
- }
1662
- };
1663
-
1664
- convert(preparedObj);
1665
- xml += `</${rootName}>`;
1666
- return xml;
1667
- }
1668
-
1669
- function escapeXML(str) {
1670
- return str
1671
- .replace(/&/g, "&amp;")
1672
- .replace(/</g, "&lt;")
1673
- .replace(/>/g, "&gt;")
1674
- .replace(/"/g, "&quot;")
1675
- .replace(/'/g, "&apos;");
1676
- }
1677
-
1678
- // Helper function to extract text from page structure
1679
- function extractTextFromFields(fields) {
1680
- if (!fields || typeof fields !== "object") {
1681
- return "";
1682
- }
1683
-
1684
- // Check for page_X structure first (preferred format)
1685
- const pageKeys = Object.keys(fields).filter(key => key.startsWith("page_"));
1686
- if (pageKeys.length > 0) {
1687
- // Get text from first page (or combine all pages)
1688
- const pageTexts = pageKeys.map(key => {
1689
- const page = fields[key];
1690
- if (page && page.text) {
1691
- return page.text;
1692
- }
1693
- return "";
1694
- }).filter(text => text);
1695
-
1696
- if (pageTexts.length > 0) {
1697
- return pageTexts.join("\n\n");
1698
- }
1699
- }
1700
-
1701
- // Fallback to full_text
1702
- if (fields.full_text) {
1703
- return fields.full_text;
1704
- }
1705
-
1706
- return "";
1707
- }
1708
-
1709
- // Helper function to format fields as readable text
1710
- function fieldsToText(fields) {
1711
- if (!fields || typeof fields !== "object") {
1712
- return "No data extracted.";
1713
- }
1714
-
1715
- // Extract text from page structure or full_text
1716
- const extractedText = extractTextFromFields(fields);
1717
-
1718
- if (extractedText) {
1719
- return extractedText;
1720
-
1721
- // Don't show pages array separately if full_text already contains page markers
1722
- // (full_text from backend already includes "=== PAGE 1 ===" etc.)
1723
- const hasPageMarkers = fields.full_text.includes("=== PAGE") || fields.full_text.includes("--- Page");
1724
-
1725
- // Only show pages array if full_text doesn't already have page breakdown
1726
- if (!hasPageMarkers && fields.pages && Array.isArray(fields.pages)) {
1727
- text += "\n\n=== TEXT BY PAGE ===\n\n";
1728
- fields.pages.forEach((page, idx) => {
1729
- text += `--- Page ${page.page_number || idx + 1} ---\n`;
1730
- text += page.text || "";
1731
- text += "\n\n";
1732
- });
1733
- }
1734
-
1735
- // Then show other structured fields
1736
- const otherFields = { ...fields };
1737
- delete otherFields.full_text;
1738
- delete otherFields.pages;
1739
-
1740
- if (Object.keys(otherFields).length > 0) {
1741
- text += "\n\n=== STRUCTURED FIELDS ===\n\n";
1742
- const formatValue = (key, value, indent = "") => {
1743
- if (Array.isArray(value)) {
1744
- text += `${indent}${key}:\n`;
1745
- value.forEach((item, idx) => {
1746
- if (typeof item === "object") {
1747
- text += `${indent} Item ${idx + 1}:\n`;
1748
- Object.entries(item).forEach(([k, v]) => formatValue(k, v, indent + " "));
1749
- } else {
1750
- text += `${indent} - ${item}\n`;
1751
- }
1752
- });
1753
- } else if (typeof value === "object" && value !== null) {
1754
- text += `${indent}${key}:\n`;
1755
- Object.entries(value).forEach(([k, v]) => formatValue(k, v, indent + " "));
1756
- } else {
1757
- text += `${indent}${key}: ${value}\n`;
1758
- }
1759
- };
1760
-
1761
- Object.entries(otherFields).forEach(([key, value]) => {
1762
- formatValue(key, value);
1763
- text += "\n";
1764
- });
1765
- }
1766
-
1767
- return text.trim();
1768
- }
1769
-
1770
- // Fallback: format all fields normally
1771
- let text = "";
1772
- const formatValue = (key, value, indent = "") => {
1773
- if (Array.isArray(value)) {
1774
- text += `${indent}${key}:\n`;
1775
- value.forEach((item, idx) => {
1776
- if (typeof item === "object") {
1777
- text += `${indent} Item ${idx + 1}:\n`;
1778
- Object.entries(item).forEach(([k, v]) => formatValue(k, v, indent + " "));
1779
- } else {
1780
- text += `${indent} - ${item}\n`;
1781
- }
1782
- });
1783
- } else if (typeof value === "object" && value !== null) {
1784
- text += `${indent}${key}:\n`;
1785
- Object.entries(value).forEach(([k, v]) => formatValue(k, v, indent + " "));
1786
- } else {
1787
- text += `${indent}${key}: ${value}\n`;
1788
- }
1789
- };
1790
-
1791
- Object.entries(fields).forEach(([key, value]) => {
1792
- formatValue(key, value);
1793
- text += "\n";
1794
- });
1795
-
1796
- return text.trim() || "No data extracted.";
1797
- }
1798
-
1799
- export default function ExtractionOutput({ hasFile, isProcessing, isComplete, extractionResult, onNewUpload }) {
1800
- const [activeTab, setActiveTab] = useState("json");
1801
- const [copied, setCopied] = useState(false);
1802
- const [statusMessage, setStatusMessage] = useState("Preparing document...");
1803
-
1804
- // Get fields from extraction result, default to empty object
1805
- const fields = extractionResult?.fields || {};
1806
- const confidence = extractionResult?.confidence || 0;
1807
- const fieldsExtracted = extractionResult?.fieldsExtracted || 0;
1808
- const totalTime = extractionResult?.totalTime || 0;
1809
-
1810
- // Dynamic status messages that rotate during processing
1811
- const statusMessages = [
1812
- "Preparing document...",
1813
- "Converting pages to images...",
1814
- "Visual Reasoning...",
1815
- "Reading text from document...",
1816
- "Identifying document structure...",
1817
- "Extracting tables and data...",
1818
- "Analyzing content...",
1819
- "Processing pages...",
1820
- "Organizing extracted information...",
1821
- "Finalizing results...",
1822
- ];
1823
-
1824
- // Rotate status messages during processing
1825
- const messageIndexRef = useRef(0);
1826
-
1827
- useEffect(() => {
1828
- if (!isProcessing) {
1829
- setStatusMessage("Analyzing document structure");
1830
- messageIndexRef.current = 0;
1831
- return;
1832
- }
1833
-
1834
- setStatusMessage(statusMessages[0]);
1835
- messageIndexRef.current = 0;
1836
-
1837
- const interval = setInterval(() => {
1838
- messageIndexRef.current = (messageIndexRef.current + 1) % statusMessages.length;
1839
- setStatusMessage(statusMessages[messageIndexRef.current]);
1840
- }, 2500); // Change message every 2.5 seconds
1841
-
1842
- return () => clearInterval(interval);
1843
- }, [isProcessing]);
1844
-
1845
- // Initialize expanded sections based on available fields
1846
- const [expandedSections, setExpandedSections] = useState(() =>
1847
- Object.keys(fields).slice(0, 5) // Expand first 5 sections by default
1848
- );
1849
-
1850
- // Helper function to convert HTML to formatted plain text with layout preserved
1851
- const htmlToFormattedText = (html) => {
1852
- if (!html) return "";
1853
-
1854
- // Create a temporary div to parse HTML
1855
- const tempDiv = document.createElement("div");
1856
- tempDiv.innerHTML = html;
1857
-
1858
- let text = "";
1859
-
1860
- // Process each element
1861
- const processNode = (node) => {
1862
- if (node.nodeType === Node.TEXT_NODE) {
1863
- return node.textContent;
1864
- }
1865
-
1866
- if (node.nodeType !== Node.ELEMENT_NODE) {
1867
- return "";
1868
- }
1869
-
1870
- const tagName = node.tagName?.toLowerCase();
1871
- const children = Array.from(node.childNodes);
1872
-
1873
- switch (tagName) {
1874
- case "h1":
1875
- return "\n\n" + processChildren(children).trim() + "\n\n";
1876
- case "h2":
1877
- return "\n\n" + processChildren(children).trim() + "\n\n";
1878
- case "h3":
1879
- return "\n" + processChildren(children).trim() + "\n";
1880
- case "p":
1881
- return processChildren(children) + "\n\n";
1882
- case "br":
1883
- return "\n";
1884
- case "strong":
1885
- case "b":
1886
- return processChildren(children);
1887
- case "em":
1888
- case "i":
1889
- return processChildren(children);
1890
- case "sup":
1891
- return processChildren(children);
1892
- case "sub":
1893
- return processChildren(children);
1894
- case "table":
1895
- return "\n" + processTable(node) + "\n\n";
1896
- case "ul":
1897
- case "ol":
1898
- return "\n" + processList(node) + "\n\n";
1899
- case "li":
1900
- return " • " + processChildren(children).trim() + "\n";
1901
- default:
1902
- return processChildren(children);
1903
- }
1904
- };
1905
-
1906
- const processChildren = (children) => {
1907
- return children.map(processNode).join("");
1908
- };
1909
-
1910
- const processTable = (table) => {
1911
- let tableText = "";
1912
- const rows = table.querySelectorAll("tr");
1913
-
1914
- if (rows.length === 0) return "";
1915
-
1916
- // First pass: calculate column widths
1917
- const allRows = Array.from(rows);
1918
- const columnCount = Math.max(...allRows.map(row => row.querySelectorAll("td, th").length));
1919
- const columnWidths = new Array(columnCount).fill(0);
1920
-
1921
- allRows.forEach(row => {
1922
- const cells = row.querySelectorAll("td, th");
1923
- cells.forEach((cell, colIndex) => {
1924
- const cellText = processChildren(Array.from(cell.childNodes)).trim().replace(/\s+/g, " ");
1925
- columnWidths[colIndex] = Math.max(columnWidths[colIndex] || 0, cellText.length, 10);
1926
- });
1927
- });
1928
-
1929
- // Second pass: format rows
1930
- allRows.forEach((row, rowIndex) => {
1931
- const cells = row.querySelectorAll("td, th");
1932
- const cellTexts = Array.from(cells).map(cell => {
1933
- let cellContent = processChildren(Array.from(cell.childNodes)).trim();
1934
- cellContent = cellContent.replace(/\s+/g, " ");
1935
- return cellContent;
1936
- });
1937
-
1938
- // Pad cells to column widths
1939
- const paddedCells = cellTexts.map((text, i) => {
1940
- const width = columnWidths[i] || 10;
1941
- return text.padEnd(width);
1942
- });
1943
-
1944
- tableText += paddedCells.join(" | ") + "\n";
1945
-
1946
- // Add separator after header row
1947
- if (rowIndex === 0 && row.querySelector("th")) {
1948
- tableText += columnWidths.map(w => "-".repeat(w)).join("-|-") + "\n";
1949
- }
1950
- });
1951
-
1952
- return tableText;
1953
- };
1954
-
1955
- const processList = (list) => {
1956
- const items = list.querySelectorAll("li");
1957
- return Array.from(items).map(item => {
1958
- return " • " + processChildren(Array.from(item.childNodes)).trim();
1959
- }).join("\n");
1960
- };
1961
-
1962
- text = processChildren(Array.from(tempDiv.childNodes));
1963
-
1964
- // Clean up extra newlines
1965
- text = text.replace(/\n{3,}/g, "\n\n");
1966
- text = text.trim();
1967
-
1968
- return text;
1969
- };
1970
-
1971
- const handleCopy = () => {
1972
- let content = "";
1973
- if (activeTab === "json") {
1974
- const preparedFields = prepareFieldsForOutput(fields, "json");
1975
- content = JSON.stringify(preparedFields, null, 2);
1976
- } else if (activeTab === "xml") {
1977
- content = objectToXML(fields);
1978
- } else {
1979
- // For text tab, get the formatted HTML and convert to plain text with layout
1980
- const textContent = extractTextFromFields(fields);
1981
- const htmlContent = renderMarkdownToHTML(textContent);
1982
- content = htmlToFormattedText(htmlContent);
1983
- }
1984
-
1985
- navigator.clipboard.writeText(content);
1986
- setCopied(true);
1987
- setTimeout(() => setCopied(false), 2000);
1988
- };
1989
-
1990
- // Get prepared fields for display
1991
- const preparedFields = React.useMemo(() => {
1992
- return prepareFieldsForOutput(fields, "json");
1993
- }, [fields]);
1994
-
1995
- // Update expanded sections when fields change
1996
- React.useEffect(() => {
1997
- if (extractionResult?.fields) {
1998
- setExpandedSections(Object.keys(extractionResult.fields).slice(0, 5));
1999
- }
2000
- }, [extractionResult]);
2001
-
2002
- const toggleSection = (section) => {
2003
- setExpandedSections((prev) =>
2004
- prev.includes(section) ? prev.filter((s) => s !== section) : [...prev, section]
2005
- );
2006
- };
2007
-
2008
- const renderValue = (value) => {
2009
- if (typeof value === "number") {
2010
- return <span className="text-amber-600">{value}</span>;
2011
- }
2012
- if (typeof value === "string") {
2013
- return <span className="text-emerald-600">"{value}"</span>;
2014
- }
2015
- return String(value);
2016
- };
2017
-
2018
- const renderSection = (key, value, level = 0) => {
2019
- const isExpanded = expandedSections.includes(key);
2020
- const isObject = typeof value === "object" && value !== null;
2021
- const isArray = Array.isArray(value);
2022
-
2023
- if (!isObject) {
2024
- return (
2025
- <div
2026
- key={key}
2027
- className="flex items-start gap-2 py-1"
2028
- style={{ paddingLeft: level * 16 }}
2029
- >
2030
- <span className="text-violet-500">"{key}"</span>
2031
- <span className="text-slate-400">:</span>
2032
- {renderValue(value)}
2033
- </div>
2034
- );
2035
- }
2036
-
2037
- return (
2038
- <div key={key}>
2039
- <button
2040
- onClick={() => toggleSection(key)}
2041
- className="flex items-center gap-2 py-1 hover:bg-slate-50 w-full text-left rounded"
2042
- style={{ paddingLeft: level * 16 }}
2043
- >
2044
- <ChevronDown
2045
- className={cn(
2046
- "h-3 w-3 text-slate-400 transition-transform",
2047
- !isExpanded && "-rotate-90"
2048
- )}
2049
- />
2050
- <span className="text-violet-500">"{key}"</span>
2051
- <span className="text-slate-400">:</span>
2052
- <span className="text-slate-400">{isArray ? "[" : "{"}</span>
2053
- {!isExpanded && (
2054
- <span className="text-slate-300 text-xs">
2055
- {isArray ? `${value.length} items` : `${Object.keys(value).length} fields`}
2056
- </span>
2057
- )}
2058
- </button>
2059
- <AnimatePresence>
2060
- {isExpanded && (
2061
- <motion.div
2062
- initial={{ height: 0, opacity: 0 }}
2063
- animate={{ height: "auto", opacity: 1 }}
2064
- exit={{ height: 0, opacity: 0 }}
2065
- transition={{ duration: 0.2 }}
2066
- className="overflow-hidden"
2067
- >
2068
- {isArray ? (
2069
- value.map((item, idx) => (
2070
- <div key={idx} className="border-l border-slate-100 ml-4">
2071
- {Object.entries(item).map(([k, v]) => renderSection(k, v, level + 2))}
2072
- {idx < value.length - 1 && <div className="h-2" />}
2073
- </div>
2074
- ))
2075
- ) : (
2076
- Object.entries(value).map(([k, v]) => renderSection(k, v, level + 1))
2077
- )}
2078
- <div style={{ paddingLeft: level * 16 }} className="text-slate-400">
2079
- {isArray ? "]" : "}"}
2080
- </div>
2081
- </motion.div>
2082
- )}
2083
- </AnimatePresence>
2084
- </div>
2085
- );
2086
- };
2087
-
2088
- return (
2089
- <div className="h-full flex flex-col bg-white rounded-2xl border border-slate-200 overflow-hidden">
2090
- {/* Header */}
2091
- <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
2092
- <div className="flex items-center gap-3">
2093
- <div className="h-8 w-8 rounded-lg bg-emerald-50 flex items-center justify-center">
2094
- <Code2 className="h-4 w-4 text-emerald-600" />
2095
- </div>
2096
- <div>
2097
- <h3 className="font-semibold text-slate-800 text-sm">Extracted Data</h3>
2098
- <p className="text-xs text-slate-400">
2099
- {isComplete
2100
- ? `${fieldsExtracted} field${fieldsExtracted !== 1 ? 's' : ''} extracted`
2101
- : "Waiting for extraction"}
2102
- </p>
2103
- </div>
2104
- {isComplete && onNewUpload && (
2105
- <Button
2106
- variant="ghost"
2107
- size="sm"
2108
- onClick={onNewUpload}
2109
- className="h-8 ml-auto text-xs gap-1.5 text-indigo-600 hover:text-indigo-700 hover:bg-indigo-50"
2110
- title="Upload new document"
2111
- >
2112
- <Upload className="h-3.5 w-3.5" />
2113
- New
2114
- </Button>
2115
- )}
2116
- </div>
2117
-
2118
- {isComplete && (
2119
- <div className="flex items-center gap-2">
2120
- <Tabs value={activeTab} onValueChange={setActiveTab}>
2121
- <TabsList className="h-8 bg-slate-100 p-0.5">
2122
- <TabsTrigger value="text" className="h-7 text-xs gap-1.5">
2123
- <FileText className="h-3 w-3" />
2124
- Text
2125
- </TabsTrigger>
2126
- <TabsTrigger value="json" className="h-7 text-xs gap-1.5">
2127
- <Braces className="h-3 w-3" />
2128
- JSON
2129
- </TabsTrigger>
2130
- <TabsTrigger value="xml" className="h-7 text-xs gap-1.5">
2131
- <FileCode2 className="h-3 w-3" />
2132
- XML
2133
- </TabsTrigger>
2134
- </TabsList>
2135
- </Tabs>
2136
- <Button
2137
- variant="ghost"
2138
- size="sm"
2139
- onClick={handleCopy}
2140
- className="h-8 text-xs gap-1.5"
2141
- >
2142
- {copied ? (
2143
- <>
2144
- <Check className="h-3 w-3 text-emerald-500" />
2145
- Copied
2146
- </>
2147
- ) : (
2148
- <>
2149
- <Copy className="h-3 w-3" />
2150
- Copy
2151
- </>
2152
- )}
2153
- </Button>
2154
- </div>
2155
- )}
2156
- </div>
2157
-
2158
- {/* Output Area */}
2159
- <div className="flex-1 overflow-auto">
2160
- {!hasFile ? (
2161
- <div className="h-full flex items-center justify-center p-6">
2162
- <div className="text-center">
2163
- <div className="h-20 w-20 mx-auto rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
2164
- <Code2 className="h-10 w-10 text-slate-300" />
2165
- </div>
2166
- <p className="text-slate-400 text-sm">Extracted data will appear here</p>
2167
- </div>
2168
- </div>
2169
- ) : isProcessing ? (
2170
- <div className="h-full flex items-center justify-center p-6">
2171
- <div className="text-center">
2172
- <motion.div
2173
- animate={{ rotate: 360 }}
2174
- transition={{ duration: 2, repeat: Infinity, ease: "linear" }}
2175
- className="h-16 w-16 mx-auto rounded-2xl bg-gradient-to-br from-indigo-100 to-violet-100 flex items-center justify-center mb-4"
2176
- >
2177
- <Sparkles className="h-8 w-8 text-indigo-500" />
2178
- </motion.div>
2179
- <p className="text-slate-700 font-medium mb-1">Extracting data...</p>
2180
- <p className="text-slate-400 text-sm">{statusMessage}</p>
2181
-
2182
- <div className="mt-6 flex items-center justify-center gap-1">
2183
- {[0, 1, 2].map((i) => (
2184
- <motion.div
2185
- key={i}
2186
- animate={{ scale: [1, 1.2, 1] }}
2187
- transition={{
2188
- duration: 0.6,
2189
- repeat: Infinity,
2190
- delay: i * 0.2,
2191
- }}
2192
- className="h-2 w-2 rounded-full bg-indigo-400"
2193
- />
2194
- ))}
2195
- </div>
2196
- </div>
2197
- </div>
2198
- ) : isComplete && Object.keys(fields).length === 0 ? (
2199
- <div className="h-full flex items-center justify-center p-6">
2200
- <div className="text-center">
2201
- <div className="h-20 w-20 mx-auto rounded-2xl bg-amber-100 flex items-center justify-center mb-4">
2202
- <Code2 className="h-10 w-10 text-amber-600" />
2203
- </div>
2204
- <p className="text-slate-600 font-medium mb-1">No data extracted</p>
2205
- <p className="text-slate-400 text-sm">The document may not contain extractable fields</p>
2206
- </div>
2207
- </div>
2208
- ) : (
2209
- <div className="p-4 font-mono text-sm">
2210
- {activeTab === "text" ? (
2211
- <div
2212
- className="text-sm text-slate-700 leading-relaxed"
2213
- style={{
2214
- fontFamily: 'system-ui, -apple-system, sans-serif'
2215
- }}
2216
- >
2217
- <div
2218
- className="markdown-content"
2219
- dangerouslySetInnerHTML={{ __html: renderMarkdownToHTML(fieldsToText(fields)) }}
2220
- style={{
2221
- lineHeight: '1.6'
2222
- }}
2223
- />
2224
- <style>{`
2225
- .markdown-content h1 {
2226
- font-size: 1.5rem;
2227
- font-weight: 700;
2228
- color: #0f172a;
2229
- margin-top: 1.5rem;
2230
- margin-bottom: 1rem;
2231
- line-height: 1.3;
2232
- }
2233
- .markdown-content h2 {
2234
- font-size: 1.25rem;
2235
- font-weight: 600;
2236
- color: #0f172a;
2237
- margin-top: 1.25rem;
2238
- margin-bottom: 0.75rem;
2239
- line-height: 1.3;
2240
- }
2241
- .markdown-content h3 {
2242
- font-size: 1.125rem;
2243
- font-weight: 600;
2244
- color: #1e293b;
2245
- margin-top: 1rem;
2246
- margin-bottom: 0.5rem;
2247
- line-height: 1.3;
2248
- }
2249
- .markdown-content p {
2250
- margin-top: 0.75rem;
2251
- margin-bottom: 0.75rem;
2252
- color: #334155;
2253
- }
2254
- .markdown-content table {
2255
- width: 100%;
2256
- border-collapse: collapse;
2257
- margin: 1.5rem 0;
2258
- font-size: 0.875rem;
2259
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
2260
- }
2261
- .markdown-content table caption {
2262
- font-weight: 600;
2263
- margin-bottom: 0.5rem;
2264
- text-align: left;
2265
- }
2266
- .markdown-content table th {
2267
- background-color: #f8fafc;
2268
- border: 1px solid #cbd5e1;
2269
- padding: 0.75rem;
2270
- text-align: left;
2271
- font-weight: 600;
2272
- color: #0f172a;
2273
- }
2274
- .markdown-content table td {
2275
- border: 1px solid #cbd5e1;
2276
- padding: 0.75rem;
2277
- color: #334155;
2278
- }
2279
- .markdown-content table tr:nth-child(even) {
2280
- background-color: #f8fafc;
2281
- }
2282
- .markdown-content table tr:hover {
2283
- background-color: #f1f5f9;
2284
- }
2285
- .markdown-content strong {
2286
- font-weight: 600;
2287
- color: #0f172a;
2288
- }
2289
- .markdown-content em {
2290
- font-style: italic;
2291
- }
2292
- .markdown-content a {
2293
- color: #4f46e5;
2294
- text-decoration: underline;
2295
- }
2296
- .markdown-content a:hover {
2297
- color: #4338ca;
2298
- }
2299
- .markdown-content sup {
2300
- font-size: 0.75em;
2301
- vertical-align: super;
2302
- line-height: 0;
2303
- position: relative;
2304
- top: -0.5em;
2305
- }
2306
- .markdown-content sub {
2307
- font-size: 0.75em;
2308
- vertical-align: sub;
2309
- line-height: 0;
2310
- position: relative;
2311
- bottom: -0.25em;
2312
- }
2313
- .markdown-content ul, .markdown-content ol {
2314
- margin: 0.75rem 0;
2315
- padding-left: 1.5rem;
2316
- }
2317
- .markdown-content li {
2318
- margin: 0.25rem 0;
2319
- }
2320
- `}</style>
2321
- </div>
2322
- ) : activeTab === "json" ? (
2323
- <div className="space-y-1">
2324
- <span className="text-slate-400">{"{"}</span>
2325
- {Object.keys(preparedFields).length > 0 ? (
2326
- Object.entries(preparedFields).map(([key, value]) =>
2327
- renderSection(key, value, 1)
2328
- )
2329
- ) : (
2330
- <div className="pl-4 text-slate-400 italic">No fields extracted</div>
2331
- )}
2332
- <span className="text-slate-400">{"}"}</span>
2333
- </div>
2334
- ) : (
2335
- <pre className="text-sm text-slate-600 whitespace-pre-wrap">
2336
- {objectToXML(fields).split("\n").map((line, i) => (
2337
- <div key={i} className="hover:bg-slate-50 px-2 -mx-2 rounded">
2338
- {line.includes("<") ? (
2339
- <>
2340
- {line.split(/(<\/?[\w\s=".-]+>)/g).map((part, j) => {
2341
- if (part.startsWith("</")) {
2342
- return (
2343
- <span key={j} className="text-rose-500">
2344
- {part}
2345
- </span>
2346
- );
2347
- }
2348
- if (part.startsWith("<")) {
2349
- return (
2350
- <span key={j} className="text-indigo-500">
2351
- {part}
2352
- </span>
2353
- );
2354
- }
2355
- return (
2356
- <span key={j} className="text-slate-700">
2357
- {part}
2358
- </span>
2359
- );
2360
- })}
2361
- </>
2362
- ) : (
2363
- line
2364
- )}
2365
- </div>
2366
- ))}
2367
- </pre>
2368
- )}
2369
- </div>
2370
- )}
2371
- </div>
2372
-
2373
- {/* Confidence Footer */}
2374
- {isComplete && extractionResult && (
2375
- <div className="px-5 py-3 border-t border-slate-100 bg-slate-50/50">
2376
- <div className="flex items-center justify-between text-xs">
2377
- <div className="flex items-center gap-4">
2378
- <div className="flex items-center gap-1.5">
2379
- <div className={cn(
2380
- "h-2 w-2 rounded-full",
2381
- confidence >= 90 ? "bg-emerald-500" : confidence >= 70 ? "bg-amber-500" : "bg-red-500"
2382
- )} />
2383
- <span className="text-slate-500">Confidence:</span>
2384
- <span className="font-semibold text-slate-700">
2385
- {confidence > 0 ? `${confidence.toFixed(1)}%` : "N/A"}
2386
- </span>
2387
- </div>
2388
- <div className="flex items-center gap-1.5">
2389
- <span className="text-slate-500">Fields:</span>
2390
- <span className="font-semibold text-slate-700">{fieldsExtracted}</span>
2391
- </div>
2392
- </div>
2393
- <span className="text-slate-400">
2394
- Processed in {totalTime >= 1000 ? `${(totalTime / 1000).toFixed(1)}s` : `${totalTime}ms`}
2395
- </span>
2396
- </div>
2397
- </div>
2398
- )}
2399
- </div>
2400
- );
2401
- }
 
1199
  </div>
1200
  );
1201
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/src/components/ocr/UpgradeModal.jsx CHANGED
@@ -46,378 +46,3 @@ const features = [
46
  ];
47
 
48
  export default function UpgradeModal({ open, onClose }) {
49
- if (!open) return null;
50
-
51
- return (
52
- <div className="fixed inset-0 z-50 flex items-center justify-center">
53
- {/* Backdrop */}
54
- <motion.div
55
- initial={{ opacity: 0 }}
56
- animate={{ opacity: 1 }}
57
- exit={{ opacity: 0 }}
58
- className="absolute inset-0 bg-black/50 backdrop-blur-sm"
59
- onClick={onClose}
60
- />
61
-
62
- {/* Modal */}
63
- <motion.div
64
- initial={{ opacity: 0, scale: 0.95, y: 20 }}
65
- animate={{ opacity: 1, scale: 1, y: 0 }}
66
- exit={{ opacity: 0, scale: 0.95, y: 20 }}
67
- className="relative z-10 w-full max-w-6xl max-h-[90vh] mx-4 bg-white rounded-2xl shadow-2xl overflow-hidden flex flex-col"
68
- onClick={(e) => e.stopPropagation()}
69
- >
70
- {/* Header */}
71
- <div className="sticky top-0 bg-gradient-to-r from-indigo-600 via-violet-600 to-purple-600 text-white px-8 py-6 z-10">
72
- <button
73
- onClick={onClose}
74
- className="absolute right-6 top-6 h-8 w-8 rounded-lg bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors"
75
- >
76
- <X className="h-4 w-4" />
77
- </button>
78
-
79
- <motion.div
80
- initial={{ opacity: 0, y: 20 }}
81
- animate={{ opacity: 1, y: 0 }}
82
- className="text-center"
83
- >
84
- <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-white/10 backdrop-blur-sm mb-4">
85
- <Sparkles className="h-4 w-4" />
86
- <span className="text-sm font-medium">Trial Limit Reached</span>
87
- </div>
88
- <h2 className="text-3xl font-bold mb-2">You've processed 2 documents</h2>
89
- <p className="text-white/80 text-lg">Continue with production-ready document intelligence</p>
90
- </motion.div>
91
- </div>
92
-
93
- {/* Stats Bar */}
94
- <div className="grid grid-cols-3 gap-6 px-8 py-6 bg-slate-50 border-b border-slate-200">
95
- {[
96
- { label: "Accuracy Rate", value: "99.8%", icon: CheckCircle2 },
97
- { label: "Processing Speed", value: "< 10s", icon: Zap },
98
- { label: "Operational Users", value: "10,000+", icon: Users }
99
- ].map((stat, i) => (
100
- <motion.div
101
- key={stat.label}
102
- initial={{ opacity: 0, y: 20 }}
103
- animate={{ opacity: 1, y: 0 }}
104
- transition={{ delay: i * 0.1 }}
105
- className="text-center"
106
- >
107
- <div className="flex items-center justify-center gap-2 mb-1">
108
- <stat.icon className="h-4 w-4 text-indigo-600" />
109
- <span className="text-2xl font-bold text-slate-900">{stat.value}</span>
110
- </div>
111
- <p className="text-sm text-slate-500">{stat.label}</p>
112
- </motion.div>
113
- ))}
114
- </div>
115
-
116
- {/* Features Grid - Scrollable */}
117
- <div className="flex-1 overflow-auto px-8 py-8">
118
- <div className="text-center mb-8">
119
- <h3 className="text-2xl font-bold text-slate-900 mb-2">
120
- Continue to Production Use
121
- </h3>
122
-
123
- </div>
124
-
125
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
126
- {features.map((feature, index) => (
127
- <motion.div
128
- key={feature.title}
129
- initial={{ opacity: 0, y: 20 }}
130
- animate={{ opacity: 1, y: 0 }}
131
- transition={{ delay: 0.2 + index * 0.1 }}
132
- className="group relative bg-white rounded-2xl border border-slate-200 p-6 hover:shadow-xl hover:shadow-slate-200/50 transition-all duration-300 hover:-translate-y-1 overflow-hidden"
133
- >
134
- {/* Gradient Background on Hover */}
135
- <div className={`absolute inset-0 bg-gradient-to-br ${feature.gradient} opacity-0 group-hover:opacity-5 transition-opacity duration-300`} />
136
-
137
- <div className="relative">
138
- <div className={cn(
139
- "h-12 w-12 rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300",
140
- feature.color === "amber" && "bg-amber-50",
141
- feature.color === "indigo" && "bg-indigo-50",
142
- feature.color === "blue" && "bg-blue-50",
143
- feature.color === "emerald" && "bg-emerald-50",
144
- feature.color === "slate" && "bg-slate-50",
145
- feature.color === "purple" && "bg-purple-50"
146
- )}>
147
- <feature.icon className={cn(
148
- "h-6 w-6",
149
- feature.color === "amber" && "text-amber-600",
150
- feature.color === "indigo" && "text-indigo-600",
151
- feature.color === "blue" && "text-blue-600",
152
- feature.color === "emerald" && "text-emerald-600",
153
- feature.color === "slate" && "text-slate-600",
154
- feature.color === "purple" && "text-purple-600"
155
- )} />
156
- </div>
157
- <h4 className="font-semibold text-slate-900 mb-2">{feature.title}</h4>
158
- <p className="text-sm text-slate-600 mb-4 leading-relaxed">{feature.description}</p>
159
-
160
- <Button
161
- variant="ghost"
162
- size="sm"
163
- className={cn(
164
- "w-full h-9 border transition-all group-hover:shadow-md",
165
- feature.color === "amber" && "text-amber-600 hover:bg-amber-50 border-amber-200 hover:border-amber-300",
166
- feature.color === "indigo" && "text-indigo-600 hover:bg-indigo-50 border-indigo-200 hover:border-indigo-300",
167
- feature.color === "blue" && "text-blue-600 hover:bg-blue-50 border-blue-200 hover:border-blue-300",
168
- feature.color === "emerald" && "text-emerald-600 hover:bg-emerald-50 border-emerald-200 hover:border-emerald-300",
169
- feature.color === "slate" && "text-slate-600 hover:bg-slate-50 border-slate-200 hover:border-slate-300",
170
- feature.color === "purple" && "text-purple-600 hover:bg-purple-50 border-purple-200 hover:border-purple-300"
171
- )}
172
- >
173
- {feature.cta}
174
- <ArrowRight className="h-3.5 w-3.5 ml-2 group-hover:translate-x-1 transition-transform" />
175
- </Button>
176
- </div>
177
- </motion.div>
178
- ))}
179
- </div>
180
- </div>
181
-
182
- {/* CTA Footer */}
183
- <div className="sticky bottom-0 bg-white border-t border-slate-200 px-8 py-6">
184
- <div className="flex items-center justify-between gap-6">
185
- <div className="flex-1">
186
- <h4 className="font-semibold text-slate-900 mb-1">Ready to scale?</h4>
187
- <p className="text-sm text-slate-600">No commitment. We’ll tailor the demo to your documents and workflows.</p>
188
- </div>
189
- <div className="flex items-center gap-3">
190
- <Button
191
- variant="outline"
192
- size="lg"
193
- className="h-11 border-slate-300"
194
- >
195
- <Users className="h-4 w-4 mr-2" />
196
- Talk to Sales
197
- </Button>
198
- <Button
199
- size="lg"
200
- className="h-11 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-700 hover:to-violet-700 shadow-lg shadow-indigo-500/25 hover:shadow-xl hover:shadow-indigo-500/30"
201
- >
202
- <Rocket className="h-4 w-4 mr-2" />
203
- Start a production evaluation
204
- <Sparkles className="h-4 w-4 ml-2" />
205
- </Button>
206
- </div>
207
- </div>
208
- </div>
209
- </motion.div>
210
- </div>
211
- );
212
- }
213
- import { motion } from "framer-motion";
214
- import { cn } from "@/lib/utils";
215
- import {
216
- X,
217
- Sparkles,
218
- Zap,
219
- Shield,
220
- Cloud,
221
- BarChart3,
222
- Bot,
223
- Globe,
224
- Lock,
225
- Rocket,
226
- Users,
227
- CheckCircle2,
228
- ArrowRight
229
- } from "lucide-react";
230
- import { Button } from "@/components/ui/button";
231
-
232
- const features = [
233
- {
234
- icon: Zap,
235
- title: "Production-Scale Processing",
236
- description: "Remove trial limits and run live AP and operations workflows",
237
- color: "amber",
238
- cta: "Explore with a demo",
239
- gradient: "from-amber-500 to-orange-500"
240
- },
241
- {
242
- icon: Bot,
243
- title: "Advanced Agentic Processing",
244
- description: "You can customize your own agentic pipeline with your own data",
245
- color: "indigo",
246
- cta: "Talk to Sales",
247
- gradient: "from-indigo-500 to-violet-500"
248
- },
249
- {
250
- icon: Cloud,
251
- title: "API Access",
252
- description: "Integrate EZOFIS into your workflow with our REST API",
253
- color: "blue",
254
- cta: "Talk to a Techie!",
255
- gradient: "from-blue-500 to-cyan-500"
256
- }
257
- ];
258
-
259
- export default function UpgradeModal({ open, onClose }) {
260
- if (!open) return null;
261
-
262
- return (
263
- <div className="fixed inset-0 z-50 flex items-center justify-center">
264
- {/* Backdrop */}
265
- <motion.div
266
- initial={{ opacity: 0 }}
267
- animate={{ opacity: 1 }}
268
- exit={{ opacity: 0 }}
269
- className="absolute inset-0 bg-black/50 backdrop-blur-sm"
270
- onClick={onClose}
271
- />
272
-
273
- {/* Modal */}
274
- <motion.div
275
- initial={{ opacity: 0, scale: 0.95, y: 20 }}
276
- animate={{ opacity: 1, scale: 1, y: 0 }}
277
- exit={{ opacity: 0, scale: 0.95, y: 20 }}
278
- className="relative z-10 w-full max-w-6xl max-h-[90vh] mx-4 bg-white rounded-2xl shadow-2xl overflow-hidden flex flex-col"
279
- onClick={(e) => e.stopPropagation()}
280
- >
281
- {/* Header */}
282
- <div className="sticky top-0 bg-gradient-to-r from-indigo-600 via-violet-600 to-purple-600 text-white px-8 py-6 z-10">
283
- <button
284
- onClick={onClose}
285
- className="absolute right-6 top-6 h-8 w-8 rounded-lg bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors"
286
- >
287
- <X className="h-4 w-4" />
288
- </button>
289
-
290
- <motion.div
291
- initial={{ opacity: 0, y: 20 }}
292
- animate={{ opacity: 1, y: 0 }}
293
- className="text-center"
294
- >
295
- <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-white/10 backdrop-blur-sm mb-4">
296
- <Sparkles className="h-4 w-4" />
297
- <span className="text-sm font-medium">Trial Limit Reached</span>
298
- </div>
299
- <h2 className="text-3xl font-bold mb-2">You've processed 2 documents</h2>
300
- <p className="text-white/80 text-lg">Continue with production-ready document intelligence</p>
301
- </motion.div>
302
- </div>
303
-
304
- {/* Stats Bar */}
305
- <div className="grid grid-cols-3 gap-6 px-8 py-6 bg-slate-50 border-b border-slate-200">
306
- {[
307
- { label: "Accuracy Rate", value: "99.8%", icon: CheckCircle2 },
308
- { label: "Processing Speed", value: "< 10s", icon: Zap },
309
- { label: "Operational Users", value: "10,000+", icon: Users }
310
- ].map((stat, i) => (
311
- <motion.div
312
- key={stat.label}
313
- initial={{ opacity: 0, y: 20 }}
314
- animate={{ opacity: 1, y: 0 }}
315
- transition={{ delay: i * 0.1 }}
316
- className="text-center"
317
- >
318
- <div className="flex items-center justify-center gap-2 mb-1">
319
- <stat.icon className="h-4 w-4 text-indigo-600" />
320
- <span className="text-2xl font-bold text-slate-900">{stat.value}</span>
321
- </div>
322
- <p className="text-sm text-slate-500">{stat.label}</p>
323
- </motion.div>
324
- ))}
325
- </div>
326
-
327
- {/* Features Grid - Scrollable */}
328
- <div className="flex-1 overflow-auto px-8 py-8">
329
- <div className="text-center mb-8">
330
- <h3 className="text-2xl font-bold text-slate-900 mb-2">
331
- Continue to Production Use
332
- </h3>
333
-
334
- </div>
335
-
336
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
337
- {features.map((feature, index) => (
338
- <motion.div
339
- key={feature.title}
340
- initial={{ opacity: 0, y: 20 }}
341
- animate={{ opacity: 1, y: 0 }}
342
- transition={{ delay: 0.2 + index * 0.1 }}
343
- className="group relative bg-white rounded-2xl border border-slate-200 p-6 hover:shadow-xl hover:shadow-slate-200/50 transition-all duration-300 hover:-translate-y-1 overflow-hidden"
344
- >
345
- {/* Gradient Background on Hover */}
346
- <div className={`absolute inset-0 bg-gradient-to-br ${feature.gradient} opacity-0 group-hover:opacity-5 transition-opacity duration-300`} />
347
-
348
- <div className="relative">
349
- <div className={cn(
350
- "h-12 w-12 rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300",
351
- feature.color === "amber" && "bg-amber-50",
352
- feature.color === "indigo" && "bg-indigo-50",
353
- feature.color === "blue" && "bg-blue-50",
354
- feature.color === "emerald" && "bg-emerald-50",
355
- feature.color === "slate" && "bg-slate-50",
356
- feature.color === "purple" && "bg-purple-50"
357
- )}>
358
- <feature.icon className={cn(
359
- "h-6 w-6",
360
- feature.color === "amber" && "text-amber-600",
361
- feature.color === "indigo" && "text-indigo-600",
362
- feature.color === "blue" && "text-blue-600",
363
- feature.color === "emerald" && "text-emerald-600",
364
- feature.color === "slate" && "text-slate-600",
365
- feature.color === "purple" && "text-purple-600"
366
- )} />
367
- </div>
368
- <h4 className="font-semibold text-slate-900 mb-2">{feature.title}</h4>
369
- <p className="text-sm text-slate-600 mb-4 leading-relaxed">{feature.description}</p>
370
-
371
- <Button
372
- variant="ghost"
373
- size="sm"
374
- className={cn(
375
- "w-full h-9 border transition-all group-hover:shadow-md",
376
- feature.color === "amber" && "text-amber-600 hover:bg-amber-50 border-amber-200 hover:border-amber-300",
377
- feature.color === "indigo" && "text-indigo-600 hover:bg-indigo-50 border-indigo-200 hover:border-indigo-300",
378
- feature.color === "blue" && "text-blue-600 hover:bg-blue-50 border-blue-200 hover:border-blue-300",
379
- feature.color === "emerald" && "text-emerald-600 hover:bg-emerald-50 border-emerald-200 hover:border-emerald-300",
380
- feature.color === "slate" && "text-slate-600 hover:bg-slate-50 border-slate-200 hover:border-slate-300",
381
- feature.color === "purple" && "text-purple-600 hover:bg-purple-50 border-purple-200 hover:border-purple-300"
382
- )}
383
- >
384
- {feature.cta}
385
- <ArrowRight className="h-3.5 w-3.5 ml-2 group-hover:translate-x-1 transition-transform" />
386
- </Button>
387
- </div>
388
- </motion.div>
389
- ))}
390
- </div>
391
- </div>
392
-
393
- {/* CTA Footer */}
394
- <div className="sticky bottom-0 bg-white border-t border-slate-200 px-8 py-6">
395
- <div className="flex items-center justify-between gap-6">
396
- <div className="flex-1">
397
- <h4 className="font-semibold text-slate-900 mb-1">Ready to scale?</h4>
398
- <p className="text-sm text-slate-600">No commitment. We’ll tailor the demo to your documents and workflows.</p>
399
- </div>
400
- <div className="flex items-center gap-3">
401
- <Button
402
- variant="outline"
403
- size="lg"
404
- className="h-11 border-slate-300"
405
- >
406
- <Users className="h-4 w-4 mr-2" />
407
- Talk to Sales
408
- </Button>
409
- <Button
410
- size="lg"
411
- className="h-11 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-700 hover:to-violet-700 shadow-lg shadow-indigo-500/25 hover:shadow-xl hover:shadow-indigo-500/30"
412
- >
413
- <Rocket className="h-4 w-4 mr-2" />
414
- Start a production evaluation
415
- <Sparkles className="h-4 w-4 ml-2" />
416
- </Button>
417
- </div>
418
- </div>
419
- </div>
420
- </motion.div>
421
- </div>
422
- );
423
- }
 
46
  ];
47
 
48
  export default function UpgradeModal({ open, onClose }) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/src/components/ocr/UploadZone.jsx CHANGED
@@ -21,481 +21,3 @@ const ALLOWED_EXTENSIONS = [".pdf", ".png", ".jpg", ".jpeg", ".tiff", ".tif"];
21
  const MAX_FILE_SIZE = 4 * 1024 * 1024; // 4 MB in bytes
22
 
23
  export default function UploadZone({ onFileSelect, selectedFile, onClear, keyFields = "", onKeyFieldsChange = () => {} }) {
24
- const [isDragging, setIsDragging] = useState(false);
25
- const [error, setError] = useState(null);
26
-
27
- const validateFile = (file) => {
28
- // Reset error
29
- setError(null);
30
-
31
- // Check file type
32
- const fileExtension = "." + file.name.split(".").pop().toLowerCase();
33
- const isValidType = ALLOWED_TYPES.includes(file.type) || ALLOWED_EXTENSIONS.includes(fileExtension);
34
-
35
- if (!isValidType) {
36
- setError("Only PDF, PNG, JPG, and TIFF files are allowed.");
37
- return false;
38
- }
39
-
40
- // Check file size
41
- if (file.size > MAX_FILE_SIZE) {
42
- const fileSizeMB = (file.size / 1024 / 1024).toFixed(2);
43
- setError(`File size exceeds 4 MB limit. Your file is ${fileSizeMB} MB.`);
44
- return false;
45
- }
46
-
47
- return true;
48
- };
49
-
50
- const handleFileSelect = (file) => {
51
- if (validateFile(file)) {
52
- setError(null);
53
- onFileSelect(file);
54
- }
55
- };
56
-
57
- const handleDragOver = (e) => {
58
- e.preventDefault();
59
- setIsDragging(true);
60
- };
61
-
62
- const handleDragLeave = () => {
63
- setIsDragging(false);
64
- };
65
-
66
- const handleDrop = (e) => {
67
- e.preventDefault();
68
- setIsDragging(false);
69
- const file = e.dataTransfer.files[0];
70
- if (file) {
71
- handleFileSelect(file);
72
- }
73
- };
74
-
75
- const getFileIcon = (type) => {
76
- if (type?.includes("image")) return Image;
77
- if (type?.includes("spreadsheet") || type?.includes("excel")) return FileSpreadsheet;
78
- return FileText;
79
- };
80
-
81
- const FileIcon = selectedFile ? getFileIcon(selectedFile.type) : FileText;
82
-
83
- // Clear error when file is cleared
84
- useEffect(() => {
85
- if (!selectedFile) {
86
- setError(null);
87
- }
88
- }, [selectedFile]);
89
-
90
- return (
91
- <div className="w-full">
92
- <AnimatePresence mode="wait">
93
- {!selectedFile ? (
94
- <motion.div
95
- key="upload"
96
- initial={{ opacity: 0, y: 10 }}
97
- animate={{ opacity: 1, y: 0 }}
98
- exit={{ opacity: 0, y: -10 }}
99
- transition={{ duration: 0.2 }}
100
- onDragOver={handleDragOver}
101
- onDragLeave={handleDragLeave}
102
- onDrop={handleDrop}
103
- className={cn(
104
- "relative group cursor-pointer",
105
- "border-2 border-dashed rounded-2xl",
106
- "transition-all duration-300 ease-out",
107
- isDragging
108
- ? "border-indigo-400 bg-indigo-50/50"
109
- : "border-slate-200 hover:border-indigo-300 hover:bg-slate-50/50"
110
- )}
111
- >
112
- <label className="flex flex-col items-center justify-center py-16 px-8 cursor-pointer">
113
- <motion.div
114
- animate={isDragging ? { scale: 1.1, y: -5 } : { scale: 1, y: 0 }}
115
- className={cn(
116
- "h-16 w-16 rounded-2xl flex items-center justify-center mb-6 transition-colors duration-300",
117
- isDragging
118
- ? "bg-indigo-100"
119
- : "bg-gradient-to-br from-slate-100 to-slate-50 group-hover:from-indigo-100 group-hover:to-violet-50"
120
- )}
121
- >
122
- <Upload
123
- className={cn(
124
- "h-7 w-7 transition-colors duration-300",
125
- isDragging ? "text-indigo-600" : "text-slate-400 group-hover:text-indigo-500"
126
- )}
127
- />
128
- </motion.div>
129
-
130
- <div className="text-center">
131
- <p className="text-lg font-semibold text-slate-700 mb-1">
132
- {isDragging ? "Drop your file here" : "Drop your file here, or browse"}
133
- </p>
134
- <p className="text-sm text-slate-400">
135
- Supports PDF, PNG, JPG, TIFF up to 4MB
136
- </p>
137
- </div>
138
-
139
- <div className="flex items-center gap-2 mt-6">
140
- <div className="flex -space-x-1">
141
- {[
142
- "bg-red-100 text-red-600",
143
- "bg-blue-100 text-blue-600",
144
- "bg-green-100 text-green-600",
145
- "bg-amber-100 text-amber-600",
146
- ].map((color, i) => (
147
- <div
148
- key={i}
149
- className={`h-8 w-8 rounded-lg ${color.split(" ")[0]} flex items-center justify-center border-2 border-white`}
150
- >
151
- <FileText className={`h-4 w-4 ${color.split(" ")[1]}`} />
152
- </div>
153
- ))}
154
- </div>
155
- <span className="text-xs text-slate-400 ml-2">Multiple formats supported</span>
156
- </div>
157
-
158
- <input
159
- type="file"
160
- className="hidden"
161
- accept=".pdf,.png,.jpg,.jpeg,.tiff,.tif"
162
- onChange={(e) => {
163
- const file = e.target.files[0];
164
- if (file) {
165
- handleFileSelect(file);
166
- }
167
- // Reset input so same file can be selected again after error
168
- e.target.value = "";
169
- }}
170
- />
171
- </label>
172
-
173
- {/* Decorative gradient border on hover */}
174
- <div className="absolute inset-0 -z-10 rounded-2xl bg-gradient-to-r from-indigo-500 via-violet-500 to-purple-500 opacity-0 group-hover:opacity-10 blur-xl transition-opacity duration-500" />
175
- </motion.div>
176
- ) : (
177
- <motion.div
178
- key="selected"
179
- initial={{ opacity: 0, scale: 0.95 }}
180
- animate={{ opacity: 1, scale: 1 }}
181
- exit={{ opacity: 0, scale: 0.95 }}
182
- className="grid grid-cols-1 lg:grid-cols-2 gap-3"
183
- >
184
- {/* File Info Box */}
185
- <div className="relative bg-gradient-to-br from-indigo-50 to-violet-50 rounded-xl p-3 border border-indigo-100">
186
- <div className="flex items-center gap-3">
187
- <div className="h-10 w-10 rounded-lg bg-white shadow-sm flex items-center justify-center flex-shrink-0">
188
- <FileIcon className="h-5 w-5 text-indigo-600" />
189
- </div>
190
- <div className="flex-1 min-w-0">
191
- <p className="font-medium text-slate-800 truncate text-sm">{selectedFile.name}</p>
192
- <div className="flex items-center gap-2 text-xs text-slate-500">
193
- <span>{(selectedFile.size / 1024 / 1024).toFixed(2)} MB</span>
194
- <span className="text-indigo-500">•</span>
195
- <span className="text-indigo-600 flex items-center gap-1">
196
- <Sparkles className="h-3 w-3" />
197
- Ready for extraction
198
- </span>
199
- </div>
200
- </div>
201
- <button
202
- onClick={onClear}
203
- className="h-8 w-8 rounded-lg bg-white hover:bg-red-50 border border-slate-200 hover:border-red-200 flex items-center justify-center text-slate-400 hover:text-red-500 transition-colors"
204
- >
205
- <X className="h-4 w-4" />
206
- </button>
207
- </div>
208
- </div>
209
-
210
- {/* Key Fields Box */}
211
- <div className="relative bg-white rounded-xl p-3 border border-slate-200">
212
- <label className="block text-xs font-medium text-slate-600 mb-1.5">
213
- <span className="font-bold">Key Fields</span> <span className="font-normal">(if required)</span>
214
- </label>
215
- <Input
216
- type="text"
217
- value={keyFields || ""}
218
- onChange={(e) => {
219
- if (onKeyFieldsChange) {
220
- onKeyFieldsChange(e.target.value);
221
- }
222
- }}
223
- placeholder="Invoice Number, Invoice Date, PO Number, Supplier Name, Total Amount, Payment terms, Additional Notes"
224
- className="h-8 text-xs border-slate-200 focus:border-indigo-300 focus:ring-indigo-200"
225
- />
226
- </div>
227
- </motion.div>
228
- )}
229
- </AnimatePresence>
230
-
231
- {/* Error Message */}
232
- {error && (
233
- <motion.div
234
- initial={{ opacity: 0, y: -10 }}
235
- animate={{ opacity: 1, y: 0 }}
236
- exit={{ opacity: 0, y: -10 }}
237
- className="mt-3 p-3 bg-red-50 border border-red-200 rounded-xl flex items-start gap-2"
238
- >
239
- <AlertCircle className="h-4 w-4 text-red-600 flex-shrink-0 mt-0.5" />
240
- <p className="text-sm text-red-700 flex-1">{error}</p>
241
- <button
242
- onClick={() => setError(null)}
243
- className="text-red-600 hover:text-red-800 transition-colors"
244
- >
245
- <X className="h-4 w-4" />
246
- </button>
247
- </motion.div>
248
- )}
249
- </div>
250
- );
251
- }
252
- import { motion, AnimatePresence } from "framer-motion";
253
- import { Upload, FileText, Image, FileSpreadsheet, X, Sparkles, AlertCircle } from "lucide-react";
254
- import { cn } from "@/lib/utils";
255
- import { Input } from "@/components/ui/input";
256
-
257
- // Allowed file types
258
- const ALLOWED_TYPES = [
259
- "application/pdf",
260
- "image/png",
261
- "image/jpeg",
262
- "image/jpg",
263
- "image/tiff",
264
- "image/tif"
265
- ];
266
-
267
- // Allowed file extensions (for fallback validation)
268
- const ALLOWED_EXTENSIONS = [".pdf", ".png", ".jpg", ".jpeg", ".tiff", ".tif"];
269
-
270
- // Maximum file size: 4 MB
271
- const MAX_FILE_SIZE = 4 * 1024 * 1024; // 4 MB in bytes
272
-
273
- export default function UploadZone({ onFileSelect, selectedFile, onClear, keyFields = "", onKeyFieldsChange = () => {} }) {
274
- const [isDragging, setIsDragging] = useState(false);
275
- const [error, setError] = useState(null);
276
-
277
- const validateFile = (file) => {
278
- // Reset error
279
- setError(null);
280
-
281
- // Check file type
282
- const fileExtension = "." + file.name.split(".").pop().toLowerCase();
283
- const isValidType = ALLOWED_TYPES.includes(file.type) || ALLOWED_EXTENSIONS.includes(fileExtension);
284
-
285
- if (!isValidType) {
286
- setError("Only PDF, PNG, JPG, and TIFF files are allowed.");
287
- return false;
288
- }
289
-
290
- // Check file size
291
- if (file.size > MAX_FILE_SIZE) {
292
- const fileSizeMB = (file.size / 1024 / 1024).toFixed(2);
293
- setError(`File size exceeds 4 MB limit. Your file is ${fileSizeMB} MB.`);
294
- return false;
295
- }
296
-
297
- return true;
298
- };
299
-
300
- const handleFileSelect = (file) => {
301
- if (validateFile(file)) {
302
- setError(null);
303
- onFileSelect(file);
304
- }
305
- };
306
-
307
- const handleDragOver = (e) => {
308
- e.preventDefault();
309
- setIsDragging(true);
310
- };
311
-
312
- const handleDragLeave = () => {
313
- setIsDragging(false);
314
- };
315
-
316
- const handleDrop = (e) => {
317
- e.preventDefault();
318
- setIsDragging(false);
319
- const file = e.dataTransfer.files[0];
320
- if (file) {
321
- handleFileSelect(file);
322
- }
323
- };
324
-
325
- const getFileIcon = (type) => {
326
- if (type?.includes("image")) return Image;
327
- if (type?.includes("spreadsheet") || type?.includes("excel")) return FileSpreadsheet;
328
- return FileText;
329
- };
330
-
331
- const FileIcon = selectedFile ? getFileIcon(selectedFile.type) : FileText;
332
-
333
- // Clear error when file is cleared
334
- useEffect(() => {
335
- if (!selectedFile) {
336
- setError(null);
337
- }
338
- }, [selectedFile]);
339
-
340
- return (
341
- <div className="w-full">
342
- <AnimatePresence mode="wait">
343
- {!selectedFile ? (
344
- <motion.div
345
- key="upload"
346
- initial={{ opacity: 0, y: 10 }}
347
- animate={{ opacity: 1, y: 0 }}
348
- exit={{ opacity: 0, y: -10 }}
349
- transition={{ duration: 0.2 }}
350
- onDragOver={handleDragOver}
351
- onDragLeave={handleDragLeave}
352
- onDrop={handleDrop}
353
- className={cn(
354
- "relative group cursor-pointer",
355
- "border-2 border-dashed rounded-2xl",
356
- "transition-all duration-300 ease-out",
357
- isDragging
358
- ? "border-indigo-400 bg-indigo-50/50"
359
- : "border-slate-200 hover:border-indigo-300 hover:bg-slate-50/50"
360
- )}
361
- >
362
- <label className="flex flex-col items-center justify-center py-16 px-8 cursor-pointer">
363
- <motion.div
364
- animate={isDragging ? { scale: 1.1, y: -5 } : { scale: 1, y: 0 }}
365
- className={cn(
366
- "h-16 w-16 rounded-2xl flex items-center justify-center mb-6 transition-colors duration-300",
367
- isDragging
368
- ? "bg-indigo-100"
369
- : "bg-gradient-to-br from-slate-100 to-slate-50 group-hover:from-indigo-100 group-hover:to-violet-50"
370
- )}
371
- >
372
- <Upload
373
- className={cn(
374
- "h-7 w-7 transition-colors duration-300",
375
- isDragging ? "text-indigo-600" : "text-slate-400 group-hover:text-indigo-500"
376
- )}
377
- />
378
- </motion.div>
379
-
380
- <div className="text-center">
381
- <p className="text-lg font-semibold text-slate-700 mb-1">
382
- {isDragging ? "Drop your file here" : "Drop your file here, or browse"}
383
- </p>
384
- <p className="text-sm text-slate-400">
385
- Supports PDF, PNG, JPG, TIFF up to 4MB
386
- </p>
387
- </div>
388
-
389
- <div className="flex items-center gap-2 mt-6">
390
- <div className="flex -space-x-1">
391
- {[
392
- "bg-red-100 text-red-600",
393
- "bg-blue-100 text-blue-600",
394
- "bg-green-100 text-green-600",
395
- "bg-amber-100 text-amber-600",
396
- ].map((color, i) => (
397
- <div
398
- key={i}
399
- className={`h-8 w-8 rounded-lg ${color.split(" ")[0]} flex items-center justify-center border-2 border-white`}
400
- >
401
- <FileText className={`h-4 w-4 ${color.split(" ")[1]}`} />
402
- </div>
403
- ))}
404
- </div>
405
- <span className="text-xs text-slate-400 ml-2">Multiple formats supported</span>
406
- </div>
407
-
408
- <input
409
- type="file"
410
- className="hidden"
411
- accept=".pdf,.png,.jpg,.jpeg,.tiff,.tif"
412
- onChange={(e) => {
413
- const file = e.target.files[0];
414
- if (file) {
415
- handleFileSelect(file);
416
- }
417
- // Reset input so same file can be selected again after error
418
- e.target.value = "";
419
- }}
420
- />
421
- </label>
422
-
423
- {/* Decorative gradient border on hover */}
424
- <div className="absolute inset-0 -z-10 rounded-2xl bg-gradient-to-r from-indigo-500 via-violet-500 to-purple-500 opacity-0 group-hover:opacity-10 blur-xl transition-opacity duration-500" />
425
- </motion.div>
426
- ) : (
427
- <motion.div
428
- key="selected"
429
- initial={{ opacity: 0, scale: 0.95 }}
430
- animate={{ opacity: 1, scale: 1 }}
431
- exit={{ opacity: 0, scale: 0.95 }}
432
- className="grid grid-cols-1 lg:grid-cols-2 gap-3"
433
- >
434
- {/* File Info Box */}
435
- <div className="relative bg-gradient-to-br from-indigo-50 to-violet-50 rounded-xl p-3 border border-indigo-100">
436
- <div className="flex items-center gap-3">
437
- <div className="h-10 w-10 rounded-lg bg-white shadow-sm flex items-center justify-center flex-shrink-0">
438
- <FileIcon className="h-5 w-5 text-indigo-600" />
439
- </div>
440
- <div className="flex-1 min-w-0">
441
- <p className="font-medium text-slate-800 truncate text-sm">{selectedFile.name}</p>
442
- <div className="flex items-center gap-2 text-xs text-slate-500">
443
- <span>{(selectedFile.size / 1024 / 1024).toFixed(2)} MB</span>
444
- <span className="text-indigo-500">•</span>
445
- <span className="text-indigo-600 flex items-center gap-1">
446
- <Sparkles className="h-3 w-3" />
447
- Ready for extraction
448
- </span>
449
- </div>
450
- </div>
451
- <button
452
- onClick={onClear}
453
- className="h-8 w-8 rounded-lg bg-white hover:bg-red-50 border border-slate-200 hover:border-red-200 flex items-center justify-center text-slate-400 hover:text-red-500 transition-colors"
454
- >
455
- <X className="h-4 w-4" />
456
- </button>
457
- </div>
458
- </div>
459
-
460
- {/* Key Fields Box */}
461
- <div className="relative bg-white rounded-xl p-3 border border-slate-200">
462
- <label className="block text-xs font-medium text-slate-600 mb-1.5">
463
- <span className="font-bold">Key Fields</span> <span className="font-normal">(if required)</span>
464
- </label>
465
- <Input
466
- type="text"
467
- value={keyFields || ""}
468
- onChange={(e) => {
469
- if (onKeyFieldsChange) {
470
- onKeyFieldsChange(e.target.value);
471
- }
472
- }}
473
- placeholder="Invoice Number, Invoice Date, PO Number, Supplier Name, Total Amount, Payment terms, Additional Notes"
474
- className="h-8 text-xs border-slate-200 focus:border-indigo-300 focus:ring-indigo-200"
475
- />
476
- </div>
477
- </motion.div>
478
- )}
479
- </AnimatePresence>
480
-
481
- {/* Error Message */}
482
- {error && (
483
- <motion.div
484
- initial={{ opacity: 0, y: -10 }}
485
- animate={{ opacity: 1, y: 0 }}
486
- exit={{ opacity: 0, y: -10 }}
487
- className="mt-3 p-3 bg-red-50 border border-red-200 rounded-xl flex items-start gap-2"
488
- >
489
- <AlertCircle className="h-4 w-4 text-red-600 flex-shrink-0 mt-0.5" />
490
- <p className="text-sm text-red-700 flex-1">{error}</p>
491
- <button
492
- onClick={() => setError(null)}
493
- className="text-red-600 hover:text-red-800 transition-colors"
494
- >
495
- <X className="h-4 w-4" />
496
- </button>
497
- </motion.div>
498
- )}
499
- </div>
500
- );
501
- }
 
21
  const MAX_FILE_SIZE = 4 * 1024 * 1024; // 4 MB in bytes
22
 
23
  export default function UploadZone({ onFileSelect, selectedFile, onClear, keyFields = "", onKeyFieldsChange = () => {} }) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/src/pages/Dashboard.jsx CHANGED
@@ -474,478 +474,3 @@ export default function Dashboard() {
474
  </div>
475
  );
476
  }
477
-
478
- import React, { useState, useEffect } from "react";
479
- import { useSearchParams } from "react-router-dom";
480
- import { motion } from "framer-motion";
481
- import { Sparkles, Zap, FileText, TrendingUp, Clock, AlertCircle } from "lucide-react";
482
- import { Button } from "@/components/ui/button";
483
- import UploadZone from "@/components/ocr/UploadZone";
484
- import DocumentPreview from "@/components/ocr/DocumentPreview";
485
- import ExtractionOutput from "@/components/ocr/ExtractionOutput";
486
- import ExportButtons from "@/components/ExportButtons";
487
- import ProcessingStatus from "@/components/ocr/ProcessingStatus";
488
- import UpgradeModal from "@/components/ocr/UpgradeModal";
489
- import { extractDocument, getHistory, getExtractionById } from "@/services/api";
490
-
491
- export default function Dashboard() {
492
- const [searchParams, setSearchParams] = useSearchParams();
493
- const [selectedFile, setSelectedFile] = useState(null);
494
- const [keyFields, setKeyFields] = useState("");
495
- const [isProcessing, setIsProcessing] = useState(false);
496
- const [isComplete, setIsComplete] = useState(false);
497
- const [extractionResult, setExtractionResult] = useState(null);
498
- const [error, setError] = useState(null);
499
- const [processingStage, setProcessingStage] = useState("received"); // received, analysis, extraction, done
500
- const [stats, setStats] = useState({ totalExtracted: 0, averageAccuracy: 0 });
501
- const [isLoadingFromHistory, setIsLoadingFromHistory] = useState(false);
502
- const [showUpgradeModal, setShowUpgradeModal] = useState(false);
503
-
504
- const TRIAL_LIMIT = 2; // Maximum number of extractions allowed in trial
505
-
506
- const handleFileSelect = (file) => {
507
- // Check if user has reached trial limit
508
- if (stats.totalExtracted >= TRIAL_LIMIT) {
509
- setShowUpgradeModal(true);
510
- return;
511
- }
512
- setSelectedFile(file);
513
- setIsComplete(false);
514
- setExtractionResult(null);
515
- setError(null);
516
- };
517
-
518
- const handleClear = () => {
519
- setSelectedFile(null);
520
- setKeyFields("");
521
- setIsProcessing(false);
522
- setIsComplete(false);
523
- setExtractionResult(null);
524
- setError(null);
525
- setProcessingStage("received");
526
- };
527
-
528
- // Load extraction from history if extractionId is in URL
529
- useEffect(() => {
530
- const extractionId = searchParams.get("extractionId");
531
- console.log("Dashboard useEffect - extractionId:", extractionId, "isLoadingFromHistory:", isLoadingFromHistory, "extractionResult:", extractionResult);
532
-
533
- if (extractionId && !isLoadingFromHistory) {
534
- // Only load if we don't already have this extraction loaded
535
- const currentExtractionId = extractionResult?.id;
536
- if (currentExtractionId && currentExtractionId === parseInt(extractionId)) {
537
- console.log("Extraction already loaded, skipping");
538
- return;
539
- }
540
-
541
- const loadExtractionFromHistory = async () => {
542
- setIsLoadingFromHistory(true);
543
- setError(null);
544
- try {
545
- console.log("Loading extraction from history, ID:", extractionId);
546
- const extraction = await getExtractionById(parseInt(extractionId));
547
- console.log("Extraction loaded:", extraction);
548
- console.log("Extraction fields:", extraction.fields);
549
- console.log("Fields type:", typeof extraction.fields);
550
- console.log("Fields keys:", extraction.fields ? Object.keys(extraction.fields) : "none");
551
-
552
- if (!extraction) {
553
- throw new Error("No extraction data received");
554
- }
555
-
556
- // Ensure fields is an object, not a string
557
- let fieldsData = extraction.fields || {};
558
- if (typeof fieldsData === 'string') {
559
- try {
560
- fieldsData = JSON.parse(fieldsData);
561
- } catch (e) {
562
- console.error("Failed to parse fields as JSON:", e);
563
- fieldsData = {};
564
- }
565
- }
566
-
567
- console.log("Processed fields:", fieldsData);
568
-
569
- // Create file object from base64 if available, otherwise create empty file
570
- let fileForPreview;
571
- if (extraction.fileBase64) {
572
- // Convert base64 to binary
573
- const binaryString = atob(extraction.fileBase64);
574
- const bytes = new Uint8Array(binaryString.length);
575
- for (let i = 0; i < binaryString.length; i++) {
576
- bytes[i] = binaryString.charCodeAt(i);
577
- }
578
- const fileBlob = new Blob([bytes], { type: extraction.fileType || "application/pdf" });
579
- fileForPreview = new File(
580
- [fileBlob],
581
- extraction.fileName || "document.pdf",
582
- { type: extraction.fileType || "application/pdf" }
583
- );
584
- console.log("Created file from base64:", fileForPreview.name, fileForPreview.size, "bytes");
585
- } else {
586
- // Fallback: create empty file if base64 not available
587
- const fileBlob = new Blob([], { type: extraction.fileType || "application/pdf" });
588
- fileForPreview = new File(
589
- [fileBlob],
590
- extraction.fileName || "document.pdf",
591
- { type: extraction.fileType || "application/pdf" }
592
- );
593
- console.log("No base64 available, created empty file");
594
- }
595
-
596
- // Set the extraction result - match the structure from extractDocument
597
- const result = {
598
- id: extraction.id,
599
- fields: fieldsData,
600
- confidence: extraction.confidence || 0,
601
- fieldsExtracted: extraction.fieldsExtracted || 0,
602
- totalTime: extraction.totalTime || 0,
603
- fileName: extraction.fileName,
604
- fileType: extraction.fileType,
605
- fileSize: extraction.fileSize,
606
- };
607
-
608
- console.log("Setting extraction result:", result);
609
- setExtractionResult(result);
610
- setSelectedFile(fileForPreview);
611
- setIsComplete(true);
612
- setIsProcessing(false);
613
- setProcessingStage("done");
614
-
615
- // Remove the extractionId from URL
616
- setSearchParams({});
617
- } catch (err) {
618
- console.error("Failed to load extraction from history:", err);
619
- const errorMessage = err.message || "Failed to load extraction from history";
620
- setError(errorMessage);
621
- // Don't clear the URL params on error so user can see what went wrong
622
- } finally {
623
- setIsLoadingFromHistory(false);
624
- }
625
- };
626
-
627
- loadExtractionFromHistory();
628
- }
629
- }, [searchParams, isLoadingFromHistory, setSearchParams]);
630
-
631
- // Fetch and calculate stats from history
632
- useEffect(() => {
633
- const fetchStats = async () => {
634
- try {
635
- const history = await getHistory();
636
-
637
- // Calculate total extracted (only completed extractions)
638
- const completedExtractions = history.filter(item => item.status === "completed");
639
- const totalExtracted = completedExtractions.length;
640
-
641
- // Calculate average accuracy from completed extractions
642
- const accuracies = completedExtractions
643
- .map(item => item.confidence || 0)
644
- .filter(acc => acc > 0);
645
-
646
- const averageAccuracy = accuracies.length > 0
647
- ? accuracies.reduce((sum, acc) => sum + acc, 0) / accuracies.length
648
- : 0;
649
-
650
- setStats({
651
- totalExtracted,
652
- averageAccuracy: Math.round(averageAccuracy * 10) / 10 // Round to 1 decimal place
653
- });
654
- } catch (err) {
655
- console.error("Failed to fetch stats:", err);
656
- // Keep default values on error
657
- }
658
- };
659
-
660
- // Fetch stats on mount and when extraction completes
661
- fetchStats();
662
- }, [isComplete]);
663
-
664
- const handleExtract = async () => {
665
- if (!selectedFile) return;
666
-
667
- // Check if user has reached trial limit before processing
668
- if (stats.totalExtracted >= TRIAL_LIMIT) {
669
- setShowUpgradeModal(true);
670
- return;
671
- }
672
-
673
- setIsProcessing(true);
674
- setIsComplete(false);
675
- setError(null);
676
- setExtractionResult(null);
677
- setProcessingStage("received");
678
-
679
- // Move to Analysis stage immediately after starting
680
- setTimeout(() => {
681
- setProcessingStage("analysis");
682
- }, 100);
683
-
684
- // Move to Extraction stage after analysis phase (2.5 seconds)
685
- let extractionTimer = setTimeout(() => {
686
- setProcessingStage("extraction");
687
- }, 2500);
688
-
689
- try {
690
- const result = await extractDocument(selectedFile, keyFields);
691
-
692
- // Clear the extraction timer
693
- clearTimeout(extractionTimer);
694
-
695
- // Move to extraction stage if not already there, then to done
696
- setProcessingStage("extraction");
697
-
698
- // Small delay to show extraction stage, then move to done when results are rendered
699
- setTimeout(() => {
700
- setProcessingStage("done");
701
- setExtractionResult(result);
702
- setIsComplete(true);
703
- setIsProcessing(false);
704
- }, 500); // Give time to see extraction stage
705
- } catch (err) {
706
- clearTimeout(extractionTimer);
707
- console.error("Extraction error:", err);
708
- setError(err.message || "Failed to extract document. Please try again.");
709
- setIsComplete(false);
710
- setProcessingStage("received");
711
- setIsProcessing(false);
712
- }
713
- };
714
-
715
- return (
716
- <div className="min-h-screen bg-[#FAFAFA]">
717
- {/* Header */}
718
- <header className="bg-white border-b border-slate-200/80 sticky top-0 z-40 h-16">
719
- <div className="px-8 h-full flex items-center justify-between">
720
- <div>
721
- <h1 className="text-xl font-bold text-slate-900 tracking-tight leading-tight">
722
- Multi-Lingual Document Extraction
723
- </h1>
724
- <p className="text-sm text-slate-500 leading-tight">
725
- Upload any document and extract structured data with VRP (No LLM)
726
- </p>
727
- </div>
728
- <div className="flex items-center gap-3">
729
- {/* Stats Pills */}
730
- <div className="hidden lg:flex items-center gap-2">
731
- <div className="flex items-center gap-2 px-3 py-1.5 bg-slate-100 rounded-lg">
732
- <FileText className="h-4 w-4 text-slate-500" />
733
- <span className="text-sm font-medium text-slate-700">
734
- {stats.totalExtracted}/{TRIAL_LIMIT} Used
735
- </span>
736
- </div>
737
- <div className="flex items-center gap-2 px-3 py-1.5 bg-emerald-50 rounded-lg">
738
- <TrendingUp className="h-4 w-4 text-emerald-600" />
739
- <span className="text-sm font-medium text-emerald-700">
740
- {stats.averageAccuracy > 0 ? `${stats.averageAccuracy}%` : "0%"} Accuracy
741
- </span>
742
- </div>
743
- </div>
744
-
745
- <ExportButtons isComplete={isComplete} extractionResult={extractionResult} />
746
- </div>
747
- </div>
748
- </header>
749
-
750
- {/* Main Content */}
751
- <div className="p-8">
752
- {/* Upload Section */}
753
- <motion.div
754
- initial={{ opacity: 0, y: 20 }}
755
- animate={{ opacity: 1, y: 0 }}
756
- className="max-w-3xl mx-auto mb-4"
757
- >
758
- <UploadZone
759
- onFileSelect={handleFileSelect}
760
- selectedFile={selectedFile}
761
- onClear={handleClear}
762
- keyFields={keyFields}
763
- onKeyFieldsChange={setKeyFields}
764
- />
765
-
766
- {/* Extract Button */}
767
- {selectedFile && !isProcessing && !isComplete && (
768
- <motion.div
769
- initial={{ opacity: 0, y: 10 }}
770
- animate={{ opacity: 1, y: 0 }}
771
- className="mt-4 flex justify-center"
772
- >
773
- <Button
774
- onClick={handleExtract}
775
- size="lg"
776
- className="h-14 px-8 rounded-2xl font-semibold text-base bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-700 hover:to-violet-700 shadow-xl shadow-indigo-500/25 hover:shadow-2xl hover:shadow-indigo-500/30 transition-all duration-300 hover:-translate-y-0.5"
777
- >
778
- <Sparkles className="h-5 w-5 mr-2" />
779
- Start Extraction
780
- <Zap className="h-4 w-4 ml-2 opacity-70" />
781
- </Button>
782
- </motion.div>
783
- )}
784
- </motion.div>
785
-
786
- {/* Error Message */}
787
- {error && (
788
- <motion.div
789
- initial={{ opacity: 0, y: -10 }}
790
- animate={{ opacity: 1, y: 0 }}
791
- className="max-w-3xl mx-auto mb-6"
792
- >
793
- <div className="bg-red-50 border border-red-200 rounded-2xl p-4 flex items-start gap-3">
794
- <AlertCircle className="h-5 w-5 text-red-600 flex-shrink-0 mt-0.5" />
795
- <div className="flex-1">
796
- <h3 className="font-semibold text-red-900 mb-1">Extraction Failed</h3>
797
- <p className="text-sm text-red-700">{error}</p>
798
- </div>
799
- <button
800
- onClick={() => setError(null)}
801
- className="text-red-400 hover:text-red-600 transition-colors"
802
- >
803
- ×
804
- </button>
805
- </div>
806
- </motion.div>
807
- )}
808
-
809
- {/* Loading from History */}
810
- {isLoadingFromHistory && (
811
- <motion.div
812
- initial={{ opacity: 0, y: -10 }}
813
- animate={{ opacity: 1, y: 0 }}
814
- className="max-w-3xl mx-auto mb-6"
815
- >
816
- <div className="bg-blue-50 border border-blue-200 rounded-2xl p-4 flex items-center gap-3">
817
- <Clock className="h-5 w-5 text-blue-600 animate-spin" />
818
- <div className="flex-1">
819
- <h3 className="font-semibold text-blue-900 mb-1">Loading extraction...</h3>
820
- <p className="text-sm text-blue-700">Retrieving extraction data from history</p>
821
- </div>
822
- </div>
823
- </motion.div>
824
- )}
825
-
826
- {/* Processing Status */}
827
- {(isProcessing || isComplete) && !isLoadingFromHistory && (
828
- <div className="max-w-3xl mx-auto mb-4">
829
- <ProcessingStatus
830
- isProcessing={isProcessing}
831
- isComplete={isComplete}
832
- currentStage={processingStage}
833
- />
834
- </div>
835
- )}
836
-
837
- {/* Split View */}
838
- {selectedFile && (
839
- <motion.div
840
- initial={{ opacity: 0, y: 20 }}
841
- animate={{ opacity: 1, y: 0 }}
842
- transition={{ delay: 0.2 }}
843
- className="grid grid-cols-1 lg:grid-cols-2 gap-4"
844
- style={{ height: "calc(100vh - 320px)", minHeight: "450px" }}
845
- >
846
- <DocumentPreview
847
- file={selectedFile}
848
- isProcessing={isProcessing}
849
- isFromHistory={!!extractionResult?.id}
850
- />
851
- <ExtractionOutput
852
- hasFile={!!selectedFile}
853
- isProcessing={isProcessing}
854
- isComplete={isComplete}
855
- extractionResult={extractionResult}
856
- onNewUpload={handleClear}
857
- />
858
- </motion.div>
859
- )}
860
-
861
- {/* Empty State Features */}
862
- {!selectedFile && (
863
- <motion.div
864
- initial={{ opacity: 0 }}
865
- animate={{ opacity: 1 }}
866
- transition={{ delay: 0.3 }}
867
- className="max-w-5xl mx-auto mt-12"
868
- >
869
- <div className="text-center mb-10">
870
- <h2 className="text-2xl font-bold text-slate-900 mb-2">
871
- Pure Agentic Document Intelligence
872
- </h2>
873
- <p className="text-slate-500">
874
- Extract structured data from any document without LLM using VRP (Visual Resoning Processor)
875
- </p>
876
- </div>
877
-
878
- <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
879
- {[
880
- {
881
- icon: Zap,
882
- title: "Lightning Fast",
883
- description:
884
- "Process documents faster with our agentic pipeline",
885
- color: "amber",
886
- },
887
- {
888
- icon: Sparkles,
889
- title: `${stats.averageAccuracy > 0 ? stats.averageAccuracy : "99.8"}% Accuracy`,
890
- description:
891
- "Industry-leading extraction accuracy",
892
- color: "indigo",
893
- },
894
- {
895
- icon: Clock,
896
- title: "Any Format",
897
- description:
898
- "Support for PDF, images, and scanned documents",
899
- color: "emerald",
900
- },
901
- ].map((feature, index) => (
902
- <motion.div
903
- key={feature.title}
904
- initial={{ opacity: 0, y: 20 }}
905
- animate={{ opacity: 1, y: 0 }}
906
- transition={{ delay: 0.4 + index * 0.1 }}
907
- className="group bg-white rounded-2xl border border-slate-200 p-6 hover:shadow-xl hover:shadow-slate-200/50 transition-all duration-300 hover:-translate-y-1"
908
- >
909
- <div
910
- className={`h-12 w-12 rounded-xl bg-${feature.color}-50 flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300`}
911
- >
912
- <feature.icon
913
- className={`h-6 w-6 text-${feature.color}-600`}
914
- />
915
- </div>
916
- <h3 className="font-semibold text-slate-900 mb-2">
917
- {feature.title}
918
- </h3>
919
- <p className="text-sm text-slate-500 leading-relaxed">
920
- {feature.description}
921
- </p>
922
- </motion.div>
923
- ))}
924
- </div>
925
-
926
- {/* Supported Formats */}
927
- <div className="mt-12 text-center">
928
- <p className="text-xs text-slate-400 uppercase tracking-wider mb-4 font-medium">
929
- Supported Formats
930
- </p>
931
- <div className="flex items-center justify-center gap-6 flex-wrap">
932
- {["PDF", "PNG", "JPG", "TIFF", "JPEG"].map((format) => (
933
- <div
934
- key={format}
935
- className="flex items-center gap-2 text-slate-400"
936
- >
937
- <FileText className="h-4 w-4" />
938
- <span className="text-sm font-medium">{format}</span>
939
- </div>
940
- ))}
941
- </div>
942
- </div>
943
- </motion.div>
944
- )}
945
- </div>
946
-
947
- {/* Upgrade Modal */}
948
- <UpgradeModal open={showUpgradeModal} onClose={() => setShowUpgradeModal(false)} />
949
- </div>
950
- );
951
- }
 
474
  </div>
475
  );
476
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/src/pages/History.jsx CHANGED
@@ -857,859 +857,3 @@ export default function History() {
857
  </div>
858
  );
859
  }
860
- import { useNavigate, useSearchParams } from "react-router-dom";
861
- import { motion, AnimatePresence } from "framer-motion";
862
- import {
863
- FileText,
864
- Clock,
865
- CheckCircle2,
866
- ChevronRight,
867
- Download,
868
- Eye,
869
- Trash2,
870
- Search,
871
- Filter,
872
- Calendar,
873
- Upload,
874
- Cpu,
875
- TableProperties,
876
- MonitorPlay,
877
- TrendingUp,
878
- TrendingDown,
879
- Minus,
880
- AlertCircle,
881
- X,
882
- FileSpreadsheet,
883
- Table2,
884
- } from "lucide-react";
885
- import { Button } from "@/components/ui/button";
886
- import { Input } from "@/components/ui/input";
887
- import { Badge } from "@/components/ui/badge";
888
- import {
889
- Select,
890
- SelectContent,
891
- SelectItem,
892
- SelectTrigger,
893
- SelectValue,
894
- } from "@/components/ui/select";
895
- import {
896
- DropdownMenu,
897
- DropdownMenuContent,
898
- DropdownMenuItem,
899
- DropdownMenuSeparator,
900
- DropdownMenuTrigger,
901
- } from "@/components/ui/dropdown-menu";
902
- import { cn } from "@/lib/utils";
903
- import { getHistory } from "@/services/api";
904
-
905
- // minimal "toast"
906
- const toastSuccess = (msg) => {
907
- console.log(msg);
908
- };
909
-
910
- const stageConfig = {
911
- uploading: { label: "Uploading", icon: Upload, color: "blue" },
912
- aiAnalysis: { label: "AI Analysis", icon: Cpu, color: "violet" },
913
- dataExtraction: { label: "Data Extraction", icon: TableProperties, color: "emerald" },
914
- outputRendering: { label: "Output Rendering", icon: MonitorPlay, color: "amber" },
915
- };
916
-
917
- const variationConfig = {
918
- fast: { icon: TrendingDown, color: "text-emerald-500", label: "Faster than avg" },
919
- normal: { icon: Minus, color: "text-slate-400", label: "Normal" },
920
- slow: { icon: TrendingUp, color: "text-amber-500", label: "Slower than avg" },
921
- error: { icon: AlertCircle, color: "text-red-500", label: "Error" },
922
- skipped: { icon: Minus, color: "text-slate-300", label: "Skipped" },
923
- };
924
-
925
- export default function History() {
926
- const navigate = useNavigate();
927
- const [searchParams, setSearchParams] = useSearchParams();
928
- const [searchQuery, setSearchQuery] = useState("");
929
- const [selectedStatus, setSelectedStatus] = useState("all");
930
- const [expandedReport, setExpandedReport] = useState(null);
931
- const [isExporting, setIsExporting] = useState(false);
932
- const [history, setHistory] = useState([]);
933
- const [isLoading, setIsLoading] = useState(true);
934
- const [error, setError] = useState(null);
935
-
936
- // Fetch history on component mount
937
- useEffect(() => {
938
- const fetchHistory = async () => {
939
- setIsLoading(true);
940
- setError(null);
941
- try {
942
- const data = await getHistory();
943
- setHistory(data);
944
-
945
- // Check if there's an extractionId in URL (from share link)
946
- const extractionId = searchParams.get("extractionId");
947
- if (extractionId) {
948
- // Clear the query param and navigate to dashboard
949
- setSearchParams({});
950
- // Small delay to ensure history is loaded
951
- setTimeout(() => {
952
- navigate(`/?extractionId=${extractionId}`);
953
- }, 100);
954
- }
955
- } catch (err) {
956
- console.error("Failed to fetch history:", err);
957
- setError(err.message || "Failed to load history");
958
- setHistory([]); // Fallback to empty array
959
- } finally {
960
- setIsLoading(false);
961
- }
962
- };
963
-
964
- fetchHistory();
965
- }, [searchParams, setSearchParams, navigate]);
966
-
967
- const filteredHistory = history.filter((item) => {
968
- const matchesSearch = item.fileName?.toLowerCase().includes(searchQuery.toLowerCase()) ?? false;
969
- const matchesStatus = selectedStatus === "all" || item.status === selectedStatus;
970
- return matchesSearch && matchesStatus;
971
- });
972
-
973
- const formatTime = (ms) => {
974
- if (ms >= 1000) {
975
- return `${(ms / 1000).toFixed(2)}s`;
976
- }
977
- return `${ms}ms`;
978
- };
979
-
980
- const formatTimeForExport = (ms) => {
981
- return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${ms}ms`;
982
- };
983
-
984
- const formatDate = (dateString) => {
985
- const date = new Date(dateString);
986
- return date.toLocaleDateString("en-US", {
987
- month: "short",
988
- day: "numeric",
989
- hour: "2-digit",
990
- minute: "2-digit",
991
- });
992
- };
993
-
994
- const formatDateForExport = (dateString) => {
995
- const date = new Date(dateString);
996
- return date.toISOString().replace("T", " ").slice(0, 19);
997
- };
998
-
999
- const generateCSV = (data) => {
1000
- const headers = [
1001
- "File Name",
1002
- "File Type",
1003
- "File Size",
1004
- "Extracted At",
1005
- "Status",
1006
- "Confidence (%)",
1007
- "Fields Extracted",
1008
- "Total Time (ms)",
1009
- "Upload Time (ms)",
1010
- "Upload Status",
1011
- "Upload Variation",
1012
- "AI Analysis Time (ms)",
1013
- "AI Analysis Status",
1014
- "AI Analysis Variation",
1015
- "Data Extraction Time (ms)",
1016
- "Data Extraction Status",
1017
- "Data Extraction Variation",
1018
- "Output Rendering Time (ms)",
1019
- "Output Rendering Status",
1020
- "Output Rendering Variation",
1021
- "Error Message",
1022
- ];
1023
-
1024
- const rows = data.map((item) => [
1025
- item.fileName,
1026
- item.fileType,
1027
- item.fileSize,
1028
- formatDateForExport(item.extractedAt),
1029
- item.status,
1030
- item.confidence,
1031
- item.fieldsExtracted,
1032
- item.totalTime,
1033
- item.stages.uploading.time,
1034
- item.stages.uploading.status,
1035
- item.stages.uploading.variation,
1036
- item.stages.aiAnalysis.time,
1037
- item.stages.aiAnalysis.status,
1038
- item.stages.aiAnalysis.variation,
1039
- item.stages.dataExtraction.time,
1040
- item.stages.dataExtraction.status,
1041
- item.stages.dataExtraction.variation,
1042
- item.stages.outputRendering.time,
1043
- item.stages.outputRendering.status,
1044
- item.stages.outputRendering.variation,
1045
- item.errorMessage || "",
1046
- ]);
1047
-
1048
- const csvContent = [
1049
- headers.join(","),
1050
- ...rows.map((row) => row.map((cell) => `"${cell}"`).join(",")),
1051
- ].join("\n");
1052
-
1053
- return csvContent;
1054
- };
1055
-
1056
- const downloadFile = (content, fileName, mimeType) => {
1057
- const blob = new Blob([content], { type: mimeType });
1058
- const url = URL.createObjectURL(blob);
1059
- const link = document.createElement("a");
1060
- link.href = url;
1061
- link.download = fileName;
1062
- document.body.appendChild(link);
1063
- link.click();
1064
- document.body.removeChild(link);
1065
- URL.revokeObjectURL(url);
1066
- };
1067
-
1068
- const handleExportCSV = () => {
1069
- setIsExporting(true);
1070
- setTimeout(() => {
1071
- const csvContent = generateCSV(filteredHistory);
1072
- downloadFile(
1073
- csvContent,
1074
- `extraction_history_${new Date().toISOString().slice(0, 10)}.csv`,
1075
- "text/csv;charset=utf-8;"
1076
- );
1077
- toastSuccess("CSV exported successfully");
1078
- setIsExporting(false);
1079
- }, 500);
1080
- };
1081
-
1082
- const generateExcelXML = (data) => {
1083
- const headers = [
1084
- "File Name",
1085
- "File Type",
1086
- "File Size",
1087
- "Extracted At",
1088
- "Status",
1089
- "Confidence (%)",
1090
- "Fields Extracted",
1091
- "Total Time (ms)",
1092
- "Upload Time (ms)",
1093
- "Upload Status",
1094
- "Upload Variation",
1095
- "AI Analysis Time (ms)",
1096
- "AI Analysis Status",
1097
- "AI Analysis Variation",
1098
- "Data Extraction Time (ms)",
1099
- "Data Extraction Status",
1100
- "Data Extraction Variation",
1101
- "Output Rendering Time (ms)",
1102
- "Output Rendering Status",
1103
- "Output Rendering Variation",
1104
- "Error Message",
1105
- ];
1106
-
1107
- const rows = data.map((item) => [
1108
- item.fileName,
1109
- item.fileType,
1110
- item.fileSize,
1111
- formatDateForExport(item.extractedAt),
1112
- item.status,
1113
- item.confidence,
1114
- item.fieldsExtracted,
1115
- item.totalTime,
1116
- item.stages.uploading.time,
1117
- item.stages.uploading.status,
1118
- item.stages.uploading.variation,
1119
- item.stages.aiAnalysis.time,
1120
- item.stages.aiAnalysis.status,
1121
- item.stages.aiAnalysis.variation,
1122
- item.stages.dataExtraction.time,
1123
- item.stages.dataExtraction.status,
1124
- item.stages.dataExtraction.variation,
1125
- item.stages.outputRendering.time,
1126
- item.stages.outputRendering.status,
1127
- item.stages.outputRendering.variation,
1128
- item.errorMessage || "",
1129
- ]);
1130
-
1131
- let xml = `<?xml version="1.0" encoding="UTF-8"?>
1132
- <?mso-application progid="Excel.Sheet"?>
1133
- <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
1134
- xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
1135
- <Worksheet ss:Name="Extraction History">
1136
- <Table>
1137
- <Row>`;
1138
-
1139
- headers.forEach((header) => {
1140
- xml += `<Cell><Data ss:Type="String">${header}</Data></Cell>`;
1141
- });
1142
- xml += `</Row>`;
1143
-
1144
- rows.forEach((row) => {
1145
- xml += `<Row>`;
1146
- row.forEach((cell) => {
1147
- const type = typeof cell === "number" ? "Number" : "String";
1148
- xml += `<Cell><Data ss:Type="${type}">${cell}</Data></Cell>`;
1149
- });
1150
- xml += `</Row>`;
1151
- });
1152
-
1153
- xml += `</Table></Worksheet></Workbook>`;
1154
- return xml;
1155
- };
1156
-
1157
- const handleExportExcel = () => {
1158
- setIsExporting(true);
1159
- setTimeout(() => {
1160
- const excelContent = generateExcelXML(filteredHistory);
1161
- downloadFile(
1162
- excelContent,
1163
- `extraction_history_${new Date().toISOString().slice(0, 10)}.xls`,
1164
- "application/vnd.ms-excel"
1165
- );
1166
- toastSuccess("Excel file exported successfully");
1167
- setIsExporting(false);
1168
- }, 500);
1169
- };
1170
-
1171
- const handleExportSingleReport = (item, format) => {
1172
- if (format === "csv") {
1173
- const csvContent = generateCSV([item]);
1174
- downloadFile(
1175
- csvContent,
1176
- `${item.fileName.replace(/\.[^/.]+$/, "")}_report.csv`,
1177
- "text/csv;charset=utf-8;"
1178
- );
1179
- toastSuccess("Report exported as CSV");
1180
- } else {
1181
- const excelContent = generateExcelXML([item]);
1182
- downloadFile(
1183
- excelContent,
1184
- `${item.fileName.replace(/\.[^/.]+$/, "")}_report.xls`,
1185
- "application/vnd.ms-excel"
1186
- );
1187
- toastSuccess("Report exported as Excel");
1188
- }
1189
- };
1190
-
1191
- return (
1192
- <div className="min-h-screen bg-[#FAFAFA]">
1193
- {/* Header */}
1194
- <header className="bg-white border-b border-slate-200/80 sticky top-0 z-40 h-16">
1195
- <div className="px-8 h-full flex items-center">
1196
- <div>
1197
- <h1 className="text-xl font-bold text-slate-900 tracking-tight leading-tight">
1198
- Extraction History
1199
- </h1>
1200
- <p className="text-sm text-slate-500 leading-tight">
1201
- View detailed reports and performance metrics for all extractions
1202
- </p>
1203
- </div>
1204
- </div>
1205
- </header>
1206
-
1207
- {/* Content */}
1208
- <div className="p-8">
1209
- {/* Filters */}
1210
- <div className="flex items-center gap-4 mb-6">
1211
- <div className="relative flex-1 max-w-md">
1212
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
1213
- <Input
1214
- placeholder="Search by file name..."
1215
- value={searchQuery}
1216
- onChange={(e) => setSearchQuery(e.target.value)}
1217
- className="pl-10 h-11 rounded-xl border-slate-200"
1218
- />
1219
- </div>
1220
- <Select
1221
- value={selectedStatus}
1222
- onValueChange={(value) => setSelectedStatus(value)}
1223
- >
1224
- <SelectTrigger className="w-40 h-11 rounded-xl border-slate-200">
1225
- <Filter className="h-4 w-4 mr-2 text-slate-400" />
1226
- <SelectValue placeholder="Status" />
1227
- </SelectTrigger>
1228
- <SelectContent>
1229
- <SelectItem value="all">All Status</SelectItem>
1230
- <SelectItem value="completed">Completed</SelectItem>
1231
- <SelectItem value="failed">Failed</SelectItem>
1232
- </SelectContent>
1233
- </Select>
1234
-
1235
- {/* Export All Button */}
1236
- <DropdownMenu>
1237
- <DropdownMenuTrigger asChild>
1238
- <Button
1239
- className="h-11 px-4 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-700 hover:to-violet-700 shadow-lg shadow-indigo-500/25"
1240
- disabled={isExporting || filteredHistory.length === 0}
1241
- >
1242
- {isExporting ? (
1243
- <motion.div
1244
- animate={{ rotate: 360 }}
1245
- transition={{
1246
- duration: 1,
1247
- repeat: Infinity,
1248
- ease: "linear",
1249
- }}
1250
- className="mr-2"
1251
- >
1252
- <Download className="h-4 w-4" />
1253
- </motion.div>
1254
- ) : (
1255
- <Download className="h-4 w-4 mr-2" />
1256
- )}
1257
- Export All
1258
- </Button>
1259
- </DropdownMenuTrigger>
1260
- <DropdownMenuContent
1261
- align="end"
1262
- className="w-48 rounded-xl p-2"
1263
- >
1264
- <DropdownMenuItem
1265
- className="rounded-lg cursor-pointer"
1266
- onClick={handleExportCSV}
1267
- >
1268
- <Table2 className="h-4 w-4 mr-2 text-emerald-600" />
1269
- Export as CSV
1270
- </DropdownMenuItem>
1271
- <DropdownMenuItem
1272
- className="rounded-lg cursor-pointer"
1273
- onClick={handleExportExcel}
1274
- >
1275
- <FileSpreadsheet className="h-4 w-4 mr-2 text-green-600" />
1276
- Export as Excel
1277
- </DropdownMenuItem>
1278
- <DropdownMenuSeparator />
1279
- <div className="px-2 py-1.5 text-xs text-slate-500">
1280
- {filteredHistory.length} records will be exported
1281
- </div>
1282
- </DropdownMenuContent>
1283
- </DropdownMenu>
1284
- </div>
1285
-
1286
- {/* Stats Overview */}
1287
- <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
1288
- {(() => {
1289
- const total = history.length;
1290
- const completed = history.filter((h) => h.status === "completed").length;
1291
- const successRate = total > 0 ? ((completed / total) * 100).toFixed(1) : 0;
1292
- const avgTime = history.length > 0
1293
- ? history.reduce((sum, h) => sum + (h.totalTime || 0), 0) / history.length
1294
- : 0;
1295
- const totalFields = history.reduce((sum, h) => sum + (h.fieldsExtracted || 0), 0);
1296
-
1297
- return [
1298
- {
1299
- label: "Total Extractions",
1300
- value: total.toString(),
1301
- change: "",
1302
- color: "indigo",
1303
- },
1304
- {
1305
- label: "Success Rate",
1306
- value: `${successRate}%`,
1307
- change: total > 0 ? `${completed}/${total} successful` : "No data",
1308
- color: "emerald",
1309
- },
1310
- {
1311
- label: "Avg. Processing Time",
1312
- value: avgTime >= 1000 ? `${(avgTime / 1000).toFixed(1)}s` : `${Math.round(avgTime)}ms`,
1313
- change: "",
1314
- color: "violet",
1315
- },
1316
- {
1317
- label: "Fields Extracted",
1318
- value: totalFields.toLocaleString(),
1319
- change: "",
1320
- color: "amber",
1321
- },
1322
- ].map((stat, index) => (
1323
- <motion.div
1324
- key={stat.label}
1325
- initial={{ opacity: 0, y: 20 }}
1326
- animate={{ opacity: 1, y: 0 }}
1327
- transition={{ delay: index * 0.1 }}
1328
- className="bg-white rounded-2xl border border-slate-200 p-5"
1329
- >
1330
- <p className="text-sm text-slate-500 mb-1">{stat.label}</p>
1331
- <p className="text-2xl font-bold text-slate-900">{stat.value}</p>
1332
- <p className={`text-xs text-${stat.color}-600 mt-1`}>
1333
- {stat.change}
1334
- </p>
1335
- </motion.div>
1336
- ));
1337
- })()}
1338
- </div>
1339
-
1340
- {/* Loading State */}
1341
- {isLoading && (
1342
- <div className="text-center py-16">
1343
- <motion.div
1344
- animate={{ rotate: 360 }}
1345
- transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
1346
- className="h-16 w-16 mx-auto rounded-2xl bg-indigo-100 flex items-center justify-center mb-4"
1347
- >
1348
- <Cpu className="h-8 w-8 text-indigo-600" />
1349
- </motion.div>
1350
- <p className="text-slate-500">Loading extraction history...</p>
1351
- </div>
1352
- )}
1353
-
1354
- {/* History List */}
1355
- {!isLoading && (
1356
- <div className="space-y-4">
1357
- {filteredHistory.map((item, index) => (
1358
- <motion.div
1359
- key={item.id}
1360
- initial={{ opacity: 0, y: 20 }}
1361
- animate={{ opacity: 1, y: 0 }}
1362
- transition={{ delay: index * 0.05 }}
1363
- className="bg-white rounded-2xl border border-slate-200 overflow-hidden"
1364
- >
1365
- {/* Main Row */}
1366
- <div
1367
- className="p-5 cursor-pointer hover:bg-slate-50/50 transition-colors"
1368
- onClick={() =>
1369
- setExpandedReport(
1370
- expandedReport === item.id ? null : item.id
1371
- )
1372
- }
1373
- >
1374
- <div className="flex items-center gap-4">
1375
- {/* File Icon */}
1376
- <div
1377
- className={cn(
1378
- "h-12 w-12 rounded-xl flex items-center justify-center",
1379
- item.status === "completed" ? "bg-indigo-50" : "bg-red-50"
1380
- )}
1381
- >
1382
- <FileText
1383
- className={cn(
1384
- "h-6 w-6",
1385
- item.status === "completed"
1386
- ? "text-indigo-600"
1387
- : "text-red-500"
1388
- )}
1389
- />
1390
- </div>
1391
-
1392
- {/* File Info */}
1393
- <div className="flex-1 min-w-0">
1394
- <div className="flex items-center gap-2">
1395
- <h3 className="font-semibold text-slate-900 truncate">
1396
- {item.fileName}
1397
- </h3>
1398
- <Badge variant="secondary" className="text-xs">
1399
- {item.fileType}
1400
- </Badge>
1401
- </div>
1402
- <div className="flex items-center gap-4 mt-1 text-sm text-slate-500">
1403
- <span>{item.fileSize}</span>
1404
- <span className="flex items-center gap-1">
1405
- <Calendar className="h-3 w-3" />
1406
- {formatDate(item.extractedAt)}
1407
- </span>
1408
- </div>
1409
- </div>
1410
-
1411
- {/* Stats */}
1412
- <div className="hidden md:flex items-center gap-6">
1413
- <div className="text-center">
1414
- <p className="text-xs text-slate-400">Time</p>
1415
- <p className="font-semibold text-slate-700">
1416
- {formatTime(item.totalTime)}
1417
- </p>
1418
- </div>
1419
- <div className="text-center">
1420
- <p className="text-xs text-slate-400">Fields</p>
1421
- <p className="font-semibold text-slate-700">
1422
- {item.fieldsExtracted}
1423
- </p>
1424
- </div>
1425
- <div className="text-center">
1426
- <p className="text-xs text-slate-400">Confidence</p>
1427
- <p
1428
- className={cn(
1429
- "font-semibold",
1430
- item.confidence >= 95
1431
- ? "text-emerald-600"
1432
- : item.confidence >= 90
1433
- ? "text-amber-600"
1434
- : "text-red-600"
1435
- )}
1436
- >
1437
- {item.confidence > 0 ? `${item.confidence}%` : "-"}
1438
- </p>
1439
- </div>
1440
- </div>
1441
-
1442
- {/* Status & Actions */}
1443
- <div className="flex items-center gap-3">
1444
- <Badge
1445
- className={cn(
1446
- "capitalize",
1447
- item.status === "completed"
1448
- ? "bg-emerald-50 text-emerald-700 border-emerald-200"
1449
- : "bg-red-50 text-red-700 border-red-200"
1450
- )}
1451
- >
1452
- {item.status === "completed" ? (
1453
- <CheckCircle2 className="h-3 w-3 mr-1" />
1454
- ) : (
1455
- <AlertCircle className="h-3 w-3 mr-1" />
1456
- )}
1457
- {item.status}
1458
- </Badge>
1459
- <ChevronRight
1460
- className={cn(
1461
- "h-5 w-5 text-slate-400 transition-transform",
1462
- expandedReport === item.id && "rotate-90"
1463
- )}
1464
- />
1465
- </div>
1466
- </div>
1467
- </div>
1468
-
1469
- {/* Expanded Report */}
1470
- <AnimatePresence>
1471
- {expandedReport === item.id && (
1472
- <motion.div
1473
- initial={{ height: 0, opacity: 0 }}
1474
- animate={{ height: "auto", opacity: 1 }}
1475
- exit={{ height: 0, opacity: 0 }}
1476
- transition={{ duration: 0.2 }}
1477
- className="overflow-hidden"
1478
- >
1479
- <div className="px-5 pb-5 pt-2 border-t border-slate-100">
1480
- {/* Error Message */}
1481
- {item.errorMessage && (
1482
- <div className="mb-4 p-4 bg-red-50 border border-red-100 rounded-xl">
1483
- <div className="flex items-center gap-2 text-red-700">
1484
- <AlertCircle className="h-4 w-4" />
1485
- <span className="font-medium">Error Details</span>
1486
- </div>
1487
- <p className="text-sm text-red-600 mt-1">
1488
- {item.errorMessage}
1489
- </p>
1490
- </div>
1491
- )}
1492
-
1493
- {/* Performance Report Header */}
1494
- <div className="flex items-center justify-between mb-4">
1495
- <h4 className="font-semibold text-slate-800">
1496
- Performance Report
1497
- </h4>
1498
- <div className="flex items-center gap-2">
1499
- <Button
1500
- variant="ghost"
1501
- size="sm"
1502
- className="h-8 text-xs"
1503
- onClick={(e) => {
1504
- e.stopPropagation();
1505
- navigate(`/?extractionId=${item.id}`);
1506
- }}
1507
- >
1508
- <Eye className="h-3 w-3 mr-1" />
1509
- View Output
1510
- </Button>
1511
- <DropdownMenu>
1512
- <DropdownMenuTrigger asChild>
1513
- <Button
1514
- variant="outline"
1515
- size="sm"
1516
- className="h-8 text-xs"
1517
- >
1518
- <Download className="h-3 w-3 mr-1" />
1519
- Export Report
1520
- </Button>
1521
- </DropdownMenuTrigger>
1522
- <DropdownMenuContent
1523
- align="end"
1524
- className="w-44 rounded-xl p-2"
1525
- >
1526
- <DropdownMenuItem
1527
- className="rounded-lg cursor-pointer text-xs"
1528
- onClick={(e) => {
1529
- e.stopPropagation();
1530
- handleExportSingleReport(item, "csv");
1531
- }}
1532
- >
1533
- <Table2 className="h-3 w-3 mr-2 text-emerald-600" />
1534
- Download CSV
1535
- </DropdownMenuItem>
1536
- <DropdownMenuItem
1537
- className="rounded-lg cursor-pointer text-xs"
1538
- onClick={(e) => {
1539
- e.stopPropagation();
1540
- handleExportSingleReport(item, "excel");
1541
- }}
1542
- >
1543
- <FileSpreadsheet className="h-3 w-3 mr-2 text-green-600" />
1544
- Download Excel
1545
- </DropdownMenuItem>
1546
- </DropdownMenuContent>
1547
- </DropdownMenu>
1548
- </div>
1549
- </div>
1550
-
1551
- {/* Stage Timing Cards */}
1552
- <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
1553
- {Object.entries(item.stages).map(
1554
- ([stageKey, stageData]) => {
1555
- const config = stageConfig[stageKey];
1556
- const variationInfo =
1557
- variationConfig[stageData.variation];
1558
- const Icon = config.icon;
1559
- const VariationIcon = variationInfo.icon;
1560
-
1561
- return (
1562
- <div
1563
- key={stageKey}
1564
- className={cn(
1565
- "relative p-4 rounded-xl border",
1566
- stageData.status === "completed"
1567
- ? "bg-slate-50 border-slate-200"
1568
- : stageData.status === "failed"
1569
- ? "bg-red-50 border-red-200"
1570
- : "bg-slate-50/50 border-slate-100"
1571
- )}
1572
- >
1573
- <div className="flex items-center gap-2 mb-3">
1574
- <div
1575
- className={cn(
1576
- "h-8 w-8 rounded-lg flex items-center justify-center",
1577
- `bg-${config.color}-100`
1578
- )}
1579
- >
1580
- <Icon
1581
- className={cn(
1582
- "h-4 w-4",
1583
- `text-${config.color}-600`
1584
- )}
1585
- />
1586
- </div>
1587
- <span className="text-sm font-medium text-slate-700">
1588
- {config.label}
1589
- </span>
1590
- </div>
1591
-
1592
- <div className="flex items-end justify-between">
1593
- <div>
1594
- <p
1595
- className={cn(
1596
- "text-2xl font-bold",
1597
- stageData.status === "skipped"
1598
- ? "text-slate-300"
1599
- : stageData.status === "failed"
1600
- ? "text-red-600"
1601
- : "text-slate-900"
1602
- )}
1603
- >
1604
- {stageData.status === "skipped"
1605
- ? "-"
1606
- : formatTime(stageData.time)}
1607
- </p>
1608
- {stageData.status !== "skipped" && (
1609
- <div className="flex items-center gap-1 mt-1">
1610
- <VariationIcon
1611
- className={cn(
1612
- "h-3 w-3",
1613
- variationInfo.color
1614
- )}
1615
- />
1616
- <span
1617
- className={cn(
1618
- "text-xs",
1619
- variationInfo.color
1620
- )}
1621
- >
1622
- {variationInfo.label}
1623
- </span>
1624
- </div>
1625
- )}
1626
- </div>
1627
-
1628
- {stageData.status === "completed" && (
1629
- <CheckCircle2 className="h-5 w-5 text-emerald-500" />
1630
- )}
1631
- {stageData.status === "failed" && (
1632
- <X className="h-5 w-5 text-red-500" />
1633
- )}
1634
- </div>
1635
-
1636
- {/* Progress bar */}
1637
- <div className="mt-3 h-1.5 bg-slate-200 rounded-full overflow-hidden">
1638
- <motion.div
1639
- initial={{ width: 0 }}
1640
- animate={{
1641
- width:
1642
- stageData.status === "completed"
1643
- ? "100%"
1644
- : stageData.status === "failed"
1645
- ? "60%"
1646
- : "0%",
1647
- }}
1648
- transition={{ duration: 0.5, delay: 0.2 }}
1649
- className={cn(
1650
- "h-full rounded-full",
1651
- stageData.status === "failed"
1652
- ? "bg-red-500"
1653
- : `bg-${config.color}-500`
1654
- )}
1655
- />
1656
- </div>
1657
- </div>
1658
- );
1659
- }
1660
- )}
1661
- </div>
1662
-
1663
- {/* Total Time Summary */}
1664
- <div className="mt-4 flex items-center justify-between p-4 bg-gradient-to-r from-indigo-50 to-violet-50 rounded-xl border border-indigo-100">
1665
- <div className="flex items-center gap-3">
1666
- <Clock className="h-5 w-5 text-indigo-600" />
1667
- <div>
1668
- <p className="text-sm font-medium text-slate-700">
1669
- Total Processing Time
1670
- </p>
1671
- <p className="text-xs text-slate-500">
1672
- From upload to output ready
1673
- </p>
1674
- </div>
1675
- </div>
1676
- <div className="text-right">
1677
- <p className="text-2xl font-bold text-indigo-600">
1678
- {formatTime(item.totalTime)}
1679
- </p>
1680
- <p className="text-xs text-slate-500">
1681
- {item.status === "completed"
1682
- ? "Completed successfully"
1683
- : "Process failed"}
1684
- </p>
1685
- </div>
1686
- </div>
1687
- </div>
1688
- </motion.div>
1689
- )}
1690
- </AnimatePresence>
1691
- </motion.div>
1692
- ))}
1693
- {filteredHistory.length === 0 && !error && (
1694
- <div className="text-center py-16">
1695
- <div className="h-20 w-20 mx-auto rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
1696
- <FileText className="h-10 w-10 text-slate-300" />
1697
- </div>
1698
- <p className="text-slate-500 mb-2">
1699
- {history.length === 0
1700
- ? "No extraction history yet"
1701
- : "No extractions match your filters"}
1702
- </p>
1703
- {history.length === 0 && (
1704
- <p className="text-sm text-slate-400">
1705
- Upload a document to get started
1706
- </p>
1707
- )}
1708
- </div>
1709
- )}
1710
- </div>
1711
- )}
1712
- </div>
1713
- </div>
1714
- );
1715
- }
 
857
  </div>
858
  );
859
  }