Spaces:
Sleeping

raahinaez commited on
Commit
a3564f2
·
verified ·
1 Parent(s): f17ec51

Update frontend/src/pages/Repository.jsx

Browse files
Files changed (1) hide show
  1. frontend/src/pages/Repository.jsx +1 -1235
frontend/src/pages/Repository.jsx CHANGED
@@ -1,1235 +1 @@
1
- import React, { useState, useRef, useEffect } from 'react';
2
- import { motion, AnimatePresence } from 'framer-motion';
3
- import {
4
- Upload,
5
- FolderOpen,
6
- Image,
7
- FileText,
8
- Video,
9
- Search,
10
- Filter,
11
- Grid3X3,
12
- List,
13
- MoreVertical,
14
- Download,
15
- Trash2,
16
- Eye,
17
- ChevronDown,
18
- ChevronRight,
19
- Plus,
20
- X,
21
- Check,
22
- File,
23
- Copy
24
- } from 'lucide-react';
25
- import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
26
- import { Button } from '@/components/ui/button';
27
- import { Input } from '@/components/ui/input';
28
- import { Badge } from '@/components/ui/badge';
29
- import { Label } from '@/components/ui/label';
30
- import { Progress } from '@/components/ui/progress';
31
- import {
32
- Select,
33
- SelectContent,
34
- SelectItem,
35
- SelectTrigger,
36
- SelectValue,
37
- } from '@/components/ui/select';
38
- import {
39
- DropdownMenu,
40
- DropdownMenuContent,
41
- DropdownMenuItem,
42
- DropdownMenuTrigger,
43
- } from '@/components/ui/dropdown-menu';
44
- import {
45
- Dialog,
46
- DialogContent,
47
- DialogHeader,
48
- DialogTitle,
49
- DialogTrigger,
50
- } from '@/components/ui/dialog';
51
- import { Checkbox } from '@/components/ui/checkbox';
52
-
53
- const products = [
54
- {
55
- id: 'ocr',
56
- name: 'Intelligent Document Parsing (OCR)',
57
- shortName: 'OCR',
58
- color: 'blue',
59
- subCategories: []
60
- },
61
- {
62
- id: 'p2p',
63
- name: 'Purchase To Pay (P2P)',
64
- shortName: 'P2P',
65
- color: 'emerald',
66
- subCategories: [
67
- 'Budget Approval Workflow',
68
- 'Purchase Request Workflow',
69
- 'Accounts Payable Workflow'
70
- ]
71
- },
72
- {
73
- id: 'o2c',
74
- name: 'Order to Cash (O2C)',
75
- shortName: 'O2C',
76
- color: 'violet',
77
- subCategories: [
78
- 'Quotation Workflow',
79
- 'Sales Order Workflow',
80
- 'PickSlip Delivery Workflow',
81
- 'Accounts Receivable Workflow'
82
- ]
83
- }
84
- ];
85
-
86
- const mockAssets = [
87
- { id: '1', name: 'OCR_Demo_Screenshot.png', type: 'image', product: 'ocr', subCategory: null, size: '2.4 MB', date: '2024-12-20' },
88
- { id: '2', name: 'P2P_Workflow_Diagram.pdf', type: 'document', product: 'p2p', subCategory: 'Budget Approval Workflow', size: '1.8 MB', date: '2024-12-19' },
89
- { id: '3', name: 'Invoice_Processing_Video.mp4', type: 'video', product: 'ocr', subCategory: null, size: '45.2 MB', date: '2024-12-18' },
90
- { id: '4', name: 'Sales_Order_Infographic.png', type: 'image', product: 'o2c', subCategory: 'Sales Order Workflow', size: '3.1 MB', date: '2024-12-17' },
91
- { id: '5', name: 'AP_Automation_Brochure.pdf', type: 'document', product: 'p2p', subCategory: 'Accounts Payable Workflow', size: '5.6 MB', date: '2024-12-16' },
92
- { id: '6', name: 'O2C_Product_Banner.png', type: 'image', product: 'o2c', subCategory: 'Quotation Workflow', size: '1.2 MB', date: '2024-12-15' },
93
- { id: '7', name: 'Document_Parsing_Demo.png', type: 'image', product: 'ocr', subCategory: null, size: '890 KB', date: '2024-12-14' },
94
- { id: '8', name: 'PR_Workflow_Guide.pdf', type: 'document', product: 'p2p', subCategory: 'Purchase Request Workflow', size: '2.3 MB', date: '2024-12-13' },
95
- ];
96
-
97
- export default function Repository() {
98
- const [viewMode, setViewMode] = useState('grid');
99
- const [searchQuery, setSearchQuery] = useState('');
100
- const [selectedProduct, setSelectedProduct] = useState('all');
101
- const [expandedProducts, setExpandedProducts] = useState(['ocr', 'p2p', 'o2c']);
102
- const [selectedAssets, setSelectedAssets] = useState([]);
103
- const [uploadDialogOpen, setUploadDialogOpen] = useState(false);
104
- const [dragOver, setDragOver] = useState(false);
105
- const [selectedFiles, setSelectedFiles] = useState([]);
106
- const [uploadProductCategory, setUploadProductCategory] = useState('');
107
- const [uploadSubCategory, setUploadSubCategory] = useState('');
108
- const [isUploading, setIsUploading] = useState(false);
109
- const [assets, setAssets] = useState(mockAssets);
110
- const [isLoadingAssets, setIsLoadingAssets] = useState(false);
111
- const [previewAsset, setPreviewAsset] = useState(null);
112
- const [previewDialogOpen, setPreviewDialogOpen] = useState(false);
113
- const [uploadProgress, setUploadProgress] = useState({});
114
- const [pdfPages, setPdfPages] = useState(null);
115
- const [isLoadingPdf, setIsLoadingPdf] = useState(false);
116
- const [isDeleting, setIsDeleting] = useState(false);
117
- const fileInputRef = useRef(null);
118
-
119
- const toggleProduct = (productId) => {
120
- setExpandedProducts(prev =>
121
- prev.includes(productId)
122
- ? prev.filter(id => id !== productId)
123
- : [...prev, productId]
124
- );
125
- };
126
-
127
- const filteredAssets = assets.filter(asset => {
128
- const matchesSearch = asset.name.toLowerCase().includes(searchQuery.toLowerCase());
129
- const matchesProduct = selectedProduct === 'all' || asset.product === selectedProduct;
130
- return matchesSearch && matchesProduct;
131
- });
132
-
133
- const getAssetsByProduct = (productId) => {
134
- return assets.filter(asset => asset.product === productId);
135
- };
136
-
137
- const getTypeIcon = (type) => {
138
- switch(type) {
139
- case 'image': return <Image className="w-5 h-5 text-pink-500" />;
140
- case 'video': return <Video className="w-5 h-5 text-red-500" />;
141
- case 'document': return <FileText className="w-5 h-5 text-blue-500" />;
142
- default: return <File className="w-5 h-5 text-slate-500" />;
143
- }
144
- };
145
-
146
- const getProductColor = (productId) => {
147
- const product = products.find(p => p.id === productId);
148
- return product?.color || 'slate';
149
- };
150
-
151
- // Fetch assets from API
152
- const fetchAssets = async () => {
153
- setIsLoadingAssets(true);
154
- try {
155
- const response = await fetch('/api/assets');
156
- if (response.ok) {
157
- const data = await response.json();
158
- console.log('Fetched assets from API:', data); // Debug log
159
-
160
- // Convert API response to match mockAssets format
161
- // IMPORTANT: Keep IDs as strings to preserve precision for large CockroachDB IDs
162
- const formattedAssets = data.map(asset => {
163
- // Handle date formatting more robustly
164
- let dateStr = new Date().toISOString().split('T')[0]; // Default to today
165
- if (asset.created_at) {
166
- try {
167
- // Handle both string and datetime object
168
- let date;
169
- if (asset.created_at instanceof Date) {
170
- date = asset.created_at;
171
- } else if (typeof asset.created_at === 'string') {
172
- date = new Date(asset.created_at);
173
- } else {
174
- // Handle datetime object from backend
175
- date = new Date(asset.created_at);
176
- }
177
-
178
- if (!isNaN(date.getTime())) {
179
- dateStr = date.toISOString().split('T')[0];
180
- } else {
181
- console.warn('Invalid date:', asset.created_at);
182
- }
183
- } catch (e) {
184
- console.warn('Date parsing error:', e, asset.created_at);
185
- }
186
- }
187
-
188
- return {
189
- id: String(asset.id), // Explicitly convert to string to preserve precision
190
- name: asset.name || 'Unknown',
191
- type: asset.file_type || 'unknown',
192
- product: asset.product_category || 'ocr',
193
- subCategory: asset.sub_category || null,
194
- size: formatFileSize(asset.size || 0),
195
- date: dateStr
196
- };
197
- });
198
-
199
- console.log('Formatted assets:', formattedAssets); // Debug log
200
- setAssets(formattedAssets);
201
- } else {
202
- const errorText = await response.text();
203
- console.error('Failed to fetch assets:', response.status, errorText);
204
- // Don't reset to mockAssets - keep what we have
205
- }
206
- } catch (error) {
207
- console.error('Error fetching assets:', error);
208
- // Don't reset to mockAssets - keep what we have
209
- } finally {
210
- setIsLoadingAssets(false);
211
- }
212
- };
213
-
214
- // Format file size
215
- const formatFileSize = (bytes) => {
216
- if (!bytes) return '0 B';
217
- const k = 1024;
218
- const sizes = ['B', 'KB', 'MB', 'GB'];
219
- const i = Math.floor(Math.log(bytes) / Math.log(k));
220
- return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
221
- };
222
-
223
- // Handle delete asset
224
- const handleDeleteAsset = async (assetId) => {
225
- setIsDeleting(true);
226
- try {
227
- // Ensure assetId is a string to preserve precision
228
- const assetIdStr = String(assetId);
229
- const response = await fetch(`/api/assets/${assetIdStr}`, {
230
- method: 'DELETE',
231
- });
232
-
233
- if (!response.ok) {
234
- const errorData = await response.json().catch(() => ({ detail: 'Delete failed' }));
235
- throw new Error(errorData.detail || 'Delete failed');
236
- }
237
-
238
- const result = await response.json();
239
- console.log('Delete result:', result);
240
-
241
- // Refresh assets list
242
- await fetchAssets();
243
-
244
- // Close preview if deleted asset was being previewed
245
- if (previewAsset && previewAsset.id === assetId) {
246
- setPreviewDialogOpen(false);
247
- setPreviewAsset(null);
248
- setPdfPages(null);
249
- }
250
-
251
- alert('Asset deleted successfully');
252
- } catch (error) {
253
- console.error('Delete error:', error);
254
- alert(`Delete failed: ${error.message}`);
255
- } finally {
256
- setIsDeleting(false);
257
- }
258
- };
259
-
260
- // Load PDF pages when previewing a PDF
261
- const loadPdfPages = async (assetId) => {
262
- setIsLoadingPdf(true);
263
- setPdfPages(null);
264
- try {
265
- // Ensure assetId is a string to preserve precision
266
- const assetIdStr = String(assetId);
267
- const response = await fetch(`/api/assets/${assetIdStr}/pdf-pages`);
268
-
269
- if (response.ok) {
270
- const data = await response.json();
271
- setPdfPages(data);
272
- } else {
273
- const errorData = await response.json().catch(() => ({
274
- detail: response.status === 503
275
- ? 'PDF preview requires poppler-utils to be installed on the server'
276
- : 'Failed to load PDF preview'
277
- }));
278
- console.error('Failed to load PDF pages:', errorData);
279
- setPdfPages({ error: errorData.detail || 'Failed to load PDF preview' });
280
- }
281
- } catch (error) {
282
- console.error('Error loading PDF pages:', error);
283
- setPdfPages({
284
- error: error.message || 'Failed to load PDF preview. Make sure poppler-utils is installed.'
285
- });
286
- } finally {
287
- setIsLoadingPdf(false);
288
- }
289
- };
290
-
291
- // Fetch assets on component mount and when upload dialog closes
292
- useEffect(() => {
293
- fetchAssets();
294
- }, []);
295
-
296
- // Refresh assets after successful upload
297
- useEffect(() => {
298
- if (!uploadDialogOpen && !isUploading) {
299
- console.log('useEffect: Refreshing assets (dialog closed, not uploading)');
300
- fetchAssets();
301
- }
302
- }, [uploadDialogOpen, isUploading]);
303
-
304
- // Auto-load PDF pages when preview opens for PDF files
305
- useEffect(() => {
306
- if (previewAsset && previewDialogOpen) {
307
- // Load PDF pages if it's a PDF
308
- if (previewAsset.type === 'document' && previewAsset.name.toLowerCase().endsWith('.pdf')) {
309
- console.log('Auto-loading PDF pages for:', previewAsset.id);
310
- loadPdfPages(String(previewAsset.id));
311
- } else {
312
- setPdfPages(null);
313
- }
314
- }
315
- }, [previewAsset, previewDialogOpen]);
316
-
317
- const handleFileSelect = (files) => {
318
- const fileArray = Array.from(files);
319
- setSelectedFiles(fileArray);
320
- };
321
-
322
- const handleDragDrop = (e) => {
323
- e.preventDefault();
324
- setDragOver(false);
325
- if (e.dataTransfer.files) {
326
- handleFileSelect(e.dataTransfer.files);
327
- }
328
- };
329
-
330
- const handleFileInputChange = (e) => {
331
- if (e.target.files) {
332
- handleFileSelect(e.target.files);
333
- }
334
- };
335
-
336
- const pollAssetStatus = async (assetId, fileName) => {
337
- const maxAttempts = 60; // Poll for up to 60 seconds
338
- let attempts = 0;
339
- let consecutive404s = 0;
340
- const max404s = 5; // Allow up to 5 consecutive 404s (asset might not be visible yet)
341
-
342
- // Small delay before first poll to allow database commit
343
- await new Promise(resolve => setTimeout(resolve, 500));
344
-
345
- while (attempts < maxAttempts) {
346
- try {
347
- const response = await fetch(`/api/assets/${assetId}/status`);
348
- if (response.ok) {
349
- const status = await response.json();
350
- consecutive404s = 0; // Reset 404 counter on success
351
- setUploadProgress(prev => ({
352
- ...prev,
353
- [fileName]: {
354
- status: status.status,
355
- message: getStatusMessage(status.status),
356
- extractedContent: status.extracted_content || null // Store extracted JSON
357
- }
358
- }));
359
-
360
- if (status.status === 'completed' || status.status === 'failed') {
361
- break;
362
- }
363
- } else if (response.status === 404) {
364
- consecutive404s++;
365
- // If we get too many 404s, stop polling (asset might not exist)
366
- if (consecutive404s >= max404s) {
367
- console.warn(`Asset ${assetId} not found after ${max404s} attempts`);
368
- setUploadProgress(prev => ({
369
- ...prev,
370
- [fileName]: {
371
- status: 'pending',
372
- message: 'Asset status unavailable'
373
- }
374
- }));
375
- break;
376
- }
377
- // For first few 404s, keep trying (might be replication lag)
378
- } else {
379
- // Other errors - log but keep trying
380
- console.error(`Status check failed: ${response.status}`);
381
- }
382
- } catch (error) {
383
- console.error('Error polling status:', error);
384
- // On network errors, keep trying
385
- }
386
-
387
- await new Promise(resolve => setTimeout(resolve, 1000)); // Poll every second
388
- attempts++;
389
- }
390
- };
391
-
392
- const getStatusMessage = (status) => {
393
- switch(status) {
394
- case 'pending': return 'Uploading file...';
395
- case 'processing': return 'Extracting content with OCR...';
396
- case 'completed': return 'Content extracted and indexed by AI agent ✓';
397
- case 'failed': return 'Analysis failed';
398
- default: return 'Processing...';
399
- }
400
- };
401
-
402
- const handleUpload = async () => {
403
- if (selectedFiles.length === 0) {
404
- alert('Please select at least one file to upload');
405
- return;
406
- }
407
- if (!uploadProductCategory) {
408
- alert('Please select a product category');
409
- return;
410
- }
411
-
412
- setIsUploading(true);
413
- setUploadProgress({});
414
-
415
- try {
416
- // Initialize progress for all files
417
- const initialProgress = {};
418
- selectedFiles.forEach(file => {
419
- initialProgress[file.name] = {
420
- status: 'pending',
421
- message: 'Uploading file...'
422
- };
423
- });
424
- setUploadProgress(initialProgress);
425
-
426
- // Upload files sequentially to show progress
427
- const results = [];
428
- for (const file of selectedFiles) {
429
- try {
430
- setUploadProgress(prev => ({
431
- ...prev,
432
- [file.name]: {
433
- status: 'pending',
434
- message: 'Uploading file...'
435
- }
436
- }));
437
-
438
- const formData = new FormData();
439
- formData.append('file', file);
440
- formData.append('product_category', uploadProductCategory);
441
- if (uploadSubCategory && uploadSubCategory !== 'none') {
442
- formData.append('sub_category', uploadSubCategory);
443
- }
444
-
445
- const response = await fetch('/api/assets/upload', {
446
- method: 'POST',
447
- body: formData,
448
- });
449
-
450
- if (!response.ok) {
451
- const errorData = await response.json().catch(() => ({ detail: 'Upload failed' }));
452
- throw new Error(errorData.detail || `Upload failed for ${file.name}`);
453
- }
454
-
455
- const result = await response.json();
456
- results.push(result);
457
-
458
- // Ensure ID is kept as string to preserve precision
459
- const assetId = String(result.id);
460
-
461
- // Update progress - file uploaded, now analyzing
462
- setUploadProgress(prev => ({
463
- ...prev,
464
- [file.name]: {
465
- status: result.analysis_status || 'processing',
466
- message: result.analysis_status === 'processing'
467
- ? 'Extracting content with OCR...'
468
- : 'Upload complete, analyzing...'
469
- }
470
- }));
471
-
472
- // Start polling for analysis status if it's a document/image
473
- if (result.file_type === 'document' || result.file_type === 'image') {
474
- pollAssetStatus(assetId, file.name);
475
- } else {
476
- setUploadProgress(prev => ({
477
- ...prev,
478
- [file.name]: {
479
- status: 'completed',
480
- message: 'Upload complete ✓'
481
- }
482
- }));
483
- }
484
- } catch (error) {
485
- console.error(`Upload error for ${file.name}:`, error);
486
- setUploadProgress(prev => ({
487
- ...prev,
488
- [file.name]: {
489
- status: 'failed',
490
- message: `Upload failed: ${error.message}`
491
- }
492
- }));
493
- }
494
- }
495
-
496
- console.log('Upload results:', results);
497
-
498
- // Refresh assets immediately after upload
499
- console.log('Refreshing assets after upload...');
500
- await fetchAssets();
501
-
502
- // Wait a bit more for database to commit, then refresh again
503
- setTimeout(async () => {
504
- console.log('Refreshing assets again after delay...');
505
- await fetchAssets();
506
- }, 1500);
507
-
508
- // Don't close dialog immediately - let user see the progress
509
- // Reset form after a delay
510
- setTimeout(() => {
511
- setSelectedFiles([]);
512
- setUploadProductCategory('');
513
- setUploadSubCategory('');
514
- setUploadProgress({});
515
- setUploadDialogOpen(false);
516
- // Refresh again after dialog closes to ensure latest data
517
- console.log('Refreshing assets after dialog closes...');
518
- fetchAssets();
519
- }, 3000);
520
-
521
- } catch (error) {
522
- console.error('Upload error:', error);
523
- alert(`Upload failed: ${error.message}`);
524
- } finally {
525
- setIsUploading(false);
526
- }
527
- };
528
-
529
- return (
530
- <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30">
531
- <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
532
- {/* Header */}
533
- <motion.div
534
- initial={{ opacity: 0, y: -20 }}
535
- animate={{ opacity: 1, y: 0 }}
536
- className="mb-8"
537
- >
538
- <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
539
- <div>
540
- <h1 className="text-3xl font-bold text-slate-900 tracking-tight">
541
- Asset Repository
542
- </h1>
543
- <p className="text-slate-500 mt-1">
544
- Manage your marketing materials, screenshots, and documents
545
- </p>
546
- </div>
547
- <Dialog open={uploadDialogOpen} onOpenChange={setUploadDialogOpen}>
548
- <DialogTrigger asChild>
549
- <Button className="gap-2 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 shadow-lg shadow-blue-500/25">
550
- <Upload className="w-4 h-4" />
551
- Upload Assets
552
- </Button>
553
- </DialogTrigger>
554
- <DialogContent className="sm:max-w-lg">
555
- <DialogHeader>
556
- <DialogTitle>Upload Assets</DialogTitle>
557
- </DialogHeader>
558
- <div className="space-y-4 pt-4">
559
- <input
560
- type="file"
561
- ref={fileInputRef}
562
- onChange={handleFileInputChange}
563
- multiple
564
- className="hidden"
565
- accept="image/*,video/*,.pdf,.doc,.docx"
566
- />
567
- <div
568
- className={`border-2 border-dashed rounded-xl p-8 text-center transition-colors ${
569
- dragOver ? 'border-blue-500 bg-blue-50' : 'border-slate-200 hover:border-slate-300'
570
- }`}
571
- onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
572
- onDragLeave={() => setDragOver(false)}
573
- onDrop={handleDragDrop}
574
- onClick={() => fileInputRef.current?.click()}
575
- >
576
- <Upload className="w-10 h-10 text-slate-400 mx-auto mb-3" />
577
- <p className="text-sm font-medium text-slate-700">
578
- Drag and drop files here
579
- </p>
580
- <p className="text-xs text-slate-500 mt-1">
581
- or click to browse
582
- </p>
583
- <Button
584
- variant="outline"
585
- size="sm"
586
- className="mt-4"
587
- type="button"
588
- onClick={(e) => { e.stopPropagation(); fileInputRef.current?.click(); }}
589
- >
590
- Browse Files
591
- </Button>
592
- {selectedFiles.length > 0 && (
593
- <div className="mt-4 space-y-3">
594
- <p className="text-xs font-medium text-slate-600">Selected files:</p>
595
- {selectedFiles.map((file, index) => {
596
- const progress = uploadProgress[file.name];
597
- const getProgressValue = () => {
598
- if (!progress) return 0;
599
- switch(progress.status) {
600
- case 'pending': return 25;
601
- case 'processing': return 60;
602
- case 'completed': return 100;
603
- case 'failed': return 0;
604
- default: return 0;
605
- }
606
- };
607
- const getProgressColor = () => {
608
- if (!progress) return 'bg-blue-500';
609
- switch(progress.status) {
610
- case 'pending': return 'bg-blue-500';
611
- case 'processing': return 'bg-yellow-500';
612
- case 'completed': return 'bg-green-500';
613
- case 'failed': return 'bg-red-500';
614
- default: return 'bg-blue-500';
615
- }
616
- };
617
- return (
618
- <div key={index} className="space-y-2">
619
- <div className="flex items-center justify-between text-xs bg-slate-50 p-2 rounded">
620
- <span className="text-slate-700 truncate flex-1 mr-2">{file.name}</span>
621
- <span className="text-slate-500 whitespace-nowrap">{(file.size / 1024 / 1024).toFixed(2)} MB</span>
622
- </div>
623
- {isUploading && (
624
- <div className="space-y-1">
625
- <div className="flex items-center justify-between text-xs">
626
- <span className={`font-medium ${
627
- progress?.status === 'completed' ? 'text-green-600' :
628
- progress?.status === 'failed' ? 'text-red-600' :
629
- progress?.status === 'processing' ? 'text-yellow-600' :
630
- 'text-blue-600'
631
- }`}>
632
- {progress?.message || 'Uploading...'}
633
- </span>
634
- {progress?.status === 'completed' && <Check className="w-3 h-3 text-green-600" />}
635
- {progress?.status === 'failed' && <X className="w-3 h-3 text-red-600" />}
636
- </div>
637
- <div className="relative h-1.5 w-full overflow-hidden rounded-full bg-slate-200">
638
- <div
639
- className={`h-full transition-all ${getProgressColor()}`}
640
- style={{ width: `${getProgressValue()}%` }}
641
- />
642
- </div>
643
- {/* JSON Output Display */}
644
- {progress?.status === 'completed' && progress?.extractedContent && (
645
- <div className="mt-3 p-3 bg-slate-50 rounded-lg border border-slate-200">
646
- <div className="flex items-center justify-between mb-2">
647
- <p className="text-xs font-medium text-slate-700">Extracted JSON Output:</p>
648
- <Button
649
- variant="ghost"
650
- size="sm"
651
- className="h-6 px-2 text-xs"
652
- onClick={() => {
653
- const jsonStr = JSON.stringify(progress.extractedContent, null, 2);
654
- navigator.clipboard.writeText(jsonStr).then(() => {
655
- alert('JSON copied to clipboard!');
656
- }).catch(() => {
657
- alert('Failed to copy JSON');
658
- });
659
- }}
660
- >
661
- <Copy className="w-3 h-3 mr-1" />
662
- Copy
663
- </Button>
664
- </div>
665
- <pre className="text-xs text-slate-600 bg-white p-2 rounded border border-slate-200 max-h-40 overflow-auto font-mono">
666
- {JSON.stringify(progress.extractedContent, null, 2)}
667
- </pre>
668
- </div>
669
- )}
670
- </div>
671
- )}
672
- </div>
673
- );
674
- })}
675
- </div>
676
- )}
677
- </div>
678
-
679
- <div className="space-y-3">
680
- <div>
681
- <Label>Product Category</Label>
682
- <Select value={uploadProductCategory} onValueChange={setUploadProductCategory}>
683
- <SelectTrigger className="mt-1.5">
684
- <SelectValue placeholder="Select a product" />
685
- </SelectTrigger>
686
- <SelectContent>
687
- {products.map(product => (
688
- <SelectItem key={product.id} value={product.id}>
689
- {product.name}
690
- </SelectItem>
691
- ))}
692
- </SelectContent>
693
- </Select>
694
- </div>
695
-
696
- <div>
697
- <Label>Sub-Category (Optional)</Label>
698
- <Select
699
- value={uploadSubCategory}
700
- onValueChange={setUploadSubCategory}
701
- disabled={!uploadProductCategory || products.find(p => p.id === uploadProductCategory)?.subCategories?.length === 0}
702
- >
703
- <SelectTrigger className="mt-1.5">
704
- <SelectValue placeholder="Select sub-category" />
705
- </SelectTrigger>
706
- <SelectContent>
707
- <SelectItem value="none">None</SelectItem>
708
- {uploadProductCategory && products.find(p => p.id === uploadProductCategory)?.subCategories?.map((sub, idx) => (
709
- <SelectItem key={idx} value={sub}>{sub}</SelectItem>
710
- ))}
711
- </SelectContent>
712
- </Select>
713
- </div>
714
- </div>
715
-
716
- <div className="flex justify-end gap-2 pt-4">
717
- <Button
718
- variant="outline"
719
- onClick={() => {
720
- setUploadDialogOpen(false);
721
- setSelectedFiles([]);
722
- setUploadProductCategory('');
723
- setUploadSubCategory('');
724
- }}
725
- disabled={isUploading}
726
- >
727
- Cancel
728
- </Button>
729
- <Button
730
- className="bg-blue-600 hover:bg-blue-700"
731
- onClick={handleUpload}
732
- disabled={isUploading || selectedFiles.length === 0 || !uploadProductCategory}
733
- >
734
- {isUploading ? 'Uploading...' : 'Upload'}
735
- </Button>
736
- </div>
737
- </div>
738
- </DialogContent>
739
- </Dialog>
740
- </div>
741
- </motion.div>
742
-
743
- <div className="grid lg:grid-cols-4 gap-6">
744
- {/* Sidebar - Product Categories */}
745
- <motion.div
746
- initial={{ opacity: 0, x: -20 }}
747
- animate={{ opacity: 1, x: 0 }}
748
- className="lg:col-span-1"
749
- >
750
- <Card className="border-0 shadow-lg shadow-slate-200/50 sticky top-8">
751
- <CardHeader className="pb-3">
752
- <CardTitle className="text-sm font-semibold text-slate-600 uppercase tracking-wider">
753
- Product Categories
754
- </CardTitle>
755
- </CardHeader>
756
- <CardContent className="pt-0">
757
- <div className="space-y-1">
758
- <button
759
- onClick={() => setSelectedProduct('all')}
760
- className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-colors ${
761
- selectedProduct === 'all'
762
- ? 'bg-blue-50 text-blue-700'
763
- : 'hover:bg-slate-50 text-slate-700'
764
- }`}
765
- >
766
- <FolderOpen className="w-4 h-4" />
767
- <span className="font-medium text-sm">All Assets</span>
768
- <Badge variant="secondary" className="ml-auto text-xs">
769
- {assets.length}
770
- </Badge>
771
- </button>
772
-
773
- {products.map(product => (
774
- <div key={product.id}>
775
- <button
776
- onClick={() => {
777
- setSelectedProduct(product.id);
778
- if (product.subCategories.length > 0) {
779
- toggleProduct(product.id);
780
- }
781
- }}
782
- className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-colors ${
783
- selectedProduct === product.id
784
- ? `bg-${product.color}-50 text-${product.color}-700`
785
- : 'hover:bg-slate-50 text-slate-700'
786
- }`}
787
- >
788
- {product.subCategories.length > 0 && (
789
- <ChevronRight className={`w-4 h-4 transition-transform ${
790
- expandedProducts.includes(product.id) ? 'rotate-90' : ''
791
- }`} />
792
- )}
793
- {product.subCategories.length === 0 && <div className="w-4" />}
794
- <span className="font-medium text-sm truncate">{product.shortName}</span>
795
- <Badge variant="secondary" className="ml-auto text-xs">
796
- {getAssetsByProduct(product.id).length}
797
- </Badge>
798
- </button>
799
-
800
- <AnimatePresence>
801
- {expandedProducts.includes(product.id) && product.subCategories.length > 0 && (
802
- <motion.div
803
- initial={{ height: 0, opacity: 0 }}
804
- animate={{ height: 'auto', opacity: 1 }}
805
- exit={{ height: 0, opacity: 0 }}
806
- className="overflow-hidden"
807
- >
808
- <div className="ml-7 pl-3 border-l border-slate-200 mt-1 space-y-1">
809
- {product.subCategories.map((sub, idx) => (
810
- <button
811
- key={idx}
812
- className="w-full text-left px-3 py-2 text-sm text-slate-600 hover:text-slate-900 hover:bg-slate-50 rounded-lg transition-colors"
813
- >
814
- {sub}
815
- </button>
816
- ))}
817
- </div>
818
- </motion.div>
819
- )}
820
- </AnimatePresence>
821
- </div>
822
- ))}
823
- </div>
824
- </CardContent>
825
- </Card>
826
- </motion.div>
827
-
828
- {/* Main Content */}
829
- <motion.div
830
- initial={{ opacity: 0, y: 20 }}
831
- animate={{ opacity: 1, y: 0 }}
832
- className="lg:col-span-3"
833
- >
834
- {/* Search and Filters */}
835
- <Card className="border-0 shadow-lg shadow-slate-200/50 mb-6">
836
- <CardContent className="p-4">
837
- <div className="flex flex-col sm:flex-row gap-3">
838
- <div className="relative flex-1">
839
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
840
- <Input
841
- placeholder="Search assets..."
842
- value={searchQuery}
843
- onChange={(e) => setSearchQuery(e.target.value)}
844
- className="pl-10 border-slate-200"
845
- />
846
- </div>
847
- <div className="flex gap-2">
848
- <Select defaultValue="all">
849
- <SelectTrigger className="w-32 border-slate-200">
850
- <Filter className="w-4 h-4 mr-2" />
851
- <SelectValue placeholder="Type" />
852
- </SelectTrigger>
853
- <SelectContent>
854
- <SelectItem value="all">All Types</SelectItem>
855
- <SelectItem value="image">Images</SelectItem>
856
- <SelectItem value="document">Documents</SelectItem>
857
- <SelectItem value="video">Videos</SelectItem>
858
- </SelectContent>
859
- </Select>
860
- <div className="flex border border-slate-200 rounded-lg overflow-hidden">
861
- <Button
862
- variant={viewMode === 'grid' ? 'secondary' : 'ghost'}
863
- size="icon"
864
- onClick={() => setViewMode('grid')}
865
- className="rounded-none"
866
- >
867
- <Grid3X3 className="w-4 h-4" />
868
- </Button>
869
- <Button
870
- variant={viewMode === 'list' ? 'secondary' : 'ghost'}
871
- size="icon"
872
- onClick={() => setViewMode('list')}
873
- className="rounded-none"
874
- >
875
- <List className="w-4 h-4" />
876
- </Button>
877
- </div>
878
- </div>
879
- </div>
880
- </CardContent>
881
- </Card>
882
-
883
- {/* Assets Grid/List */}
884
- {viewMode === 'grid' ? (
885
- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
886
- {filteredAssets.map((asset, index) => (
887
- <motion.div
888
- key={asset.id}
889
- initial={{ opacity: 0, scale: 0.95 }}
890
- animate={{ opacity: 1, scale: 1 }}
891
- transition={{ delay: index * 0.05 }}
892
- >
893
- <Card className="border-0 shadow-md hover:shadow-lg transition-all duration-300 group overflow-hidden">
894
- <div className={`h-40 bg-gradient-to-br from-${getProductColor(asset.product)}-100 to-${getProductColor(asset.product)}-50 flex items-center justify-center relative`}>
895
- {asset.type === 'image' ? (
896
- <Image className={`w-12 h-12 text-${getProductColor(asset.product)}-400`} />
897
- ) : asset.type === 'video' ? (
898
- <Video className={`w-12 h-12 text-${getProductColor(asset.product)}-400`} />
899
- ) : (
900
- <FileText className={`w-12 h-12 text-${getProductColor(asset.product)}-400`} />
901
- )}
902
- <div className="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors flex items-center justify-center opacity-0 group-hover:opacity-100">
903
- <div className="flex gap-2">
904
- <Button
905
- size="icon"
906
- variant="secondary"
907
- className="h-9 w-9"
908
- onClick={async (e) => {
909
- e.stopPropagation();
910
- setPreviewAsset(asset);
911
- setPreviewDialogOpen(true);
912
- // Load PDF pages if it's a PDF
913
- if (asset.type === 'document' && asset.name.toLowerCase().endsWith('.pdf')) {
914
- await loadPdfPages(String(asset.id));
915
- } else {
916
- setPdfPages(null);
917
- }
918
- }}
919
- >
920
- <Eye className="w-4 h-4" />
921
- </Button>
922
- <Button
923
- size="icon"
924
- variant="secondary"
925
- className="h-9 w-9"
926
- onClick={(e) => {
927
- e.stopPropagation();
928
- window.open(`/api/assets/${String(asset.id)}/download`, '_blank');
929
- }}
930
- >
931
- <Download className="w-4 h-4" />
932
- </Button>
933
- </div>
934
- </div>
935
- <div className="absolute top-2 right-2">
936
- <Checkbox className="bg-white border-slate-300" />
937
- </div>
938
- </div>
939
- <CardContent className="p-4">
940
- <div className="flex items-start justify-between gap-2">
941
- <div className="min-w-0">
942
- <h3 className="font-medium text-slate-900 text-sm truncate">
943
- {asset.name}
944
- </h3>
945
- <p className="text-xs text-slate-500 mt-1">
946
- {asset.size} • {asset.date}
947
- </p>
948
- </div>
949
- <DropdownMenu>
950
- <DropdownMenuTrigger asChild>
951
- <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0">
952
- <MoreVertical className="w-4 h-4" />
953
- </Button>
954
- </DropdownMenuTrigger>
955
- <DropdownMenuContent align="end">
956
- <DropdownMenuItem onClick={async () => {
957
- setPreviewAsset(asset);
958
- setPreviewDialogOpen(true);
959
- // Load PDF pages if it's a PDF
960
- if (asset.type === 'document' && asset.name.toLowerCase().endsWith('.pdf')) {
961
- await loadPdfPages(String(asset.id));
962
- } else {
963
- setPdfPages(null);
964
- }
965
- }}>
966
- <Eye className="w-4 h-4 mr-2" /> Preview
967
- </DropdownMenuItem>
968
- <DropdownMenuItem onClick={() => {
969
- window.open(`/api/assets/${String(asset.id)}/download`, '_blank');
970
- }}>
971
- <Download className="w-4 h-4 mr-2" /> Download
972
- </DropdownMenuItem>
973
- <DropdownMenuItem
974
- className="text-red-600"
975
- onClick={async () => {
976
- if (confirm(`Are you sure you want to delete "${asset.name}"?`)) {
977
- await handleDeleteAsset(String(asset.id));
978
- }
979
- }}
980
- >
981
- <Trash2 className="w-4 h-4 mr-2" /> Delete
982
- </DropdownMenuItem>
983
- </DropdownMenuContent>
984
- </DropdownMenu>
985
- </div>
986
- <div className="flex gap-2 mt-3">
987
- <Badge variant="outline" className={`text-xs border-${getProductColor(asset.product)}-200 text-${getProductColor(asset.product)}-700 bg-${getProductColor(asset.product)}-50`}>
988
- {products.find(p => p.id === asset.product)?.shortName}
989
- </Badge>
990
- {asset.subCategory && (
991
- <Badge variant="outline" className="text-xs border-slate-200 text-slate-600 truncate max-w-[120px]">
992
- {asset.subCategory}
993
- </Badge>
994
- )}
995
- </div>
996
- </CardContent>
997
- </Card>
998
- </motion.div>
999
- ))}
1000
- </div>
1001
- ) : (
1002
- <Card className="border-0 shadow-lg shadow-slate-200/50">
1003
- <CardContent className="p-0">
1004
- <div className="divide-y divide-slate-100">
1005
- {filteredAssets.map((asset, index) => (
1006
- <motion.div
1007
- key={asset.id}
1008
- initial={{ opacity: 0, x: -10 }}
1009
- animate={{ opacity: 1, x: 0 }}
1010
- transition={{ delay: index * 0.03 }}
1011
- className="flex items-center gap-4 p-4 hover:bg-slate-50 transition-colors"
1012
- >
1013
- <Checkbox />
1014
- <div className={`w-10 h-10 rounded-lg bg-${getProductColor(asset.product)}-100 flex items-center justify-center`}>
1015
- {getTypeIcon(asset.type)}
1016
- </div>
1017
- <div className="flex-1 min-w-0">
1018
- <h3 className="font-medium text-slate-900 text-sm truncate">
1019
- {asset.name}
1020
- </h3>
1021
- <p className="text-xs text-slate-500 mt-0.5">
1022
- {asset.subCategory || products.find(p => p.id === asset.product)?.name}
1023
- </p>
1024
- </div>
1025
- <div className="hidden sm:block text-sm text-slate-500">
1026
- {asset.size}
1027
- </div>
1028
- <div className="hidden md:block text-sm text-slate-500">
1029
- {asset.date}
1030
- </div>
1031
- <Badge variant="outline" className={`text-xs border-${getProductColor(asset.product)}-200 text-${getProductColor(asset.product)}-700`}>
1032
- {products.find(p => p.id === asset.product)?.shortName}
1033
- </Badge>
1034
- <DropdownMenu>
1035
- <DropdownMenuTrigger asChild>
1036
- <Button variant="ghost" size="icon" className="h-8 w-8">
1037
- <MoreVertical className="w-4 h-4" />
1038
- </Button>
1039
- </DropdownMenuTrigger>
1040
- <DropdownMenuContent align="end">
1041
- <DropdownMenuItem onClick={async () => {
1042
- setPreviewAsset(asset);
1043
- setPreviewDialogOpen(true);
1044
- // Load PDF pages if it's a PDF
1045
- if (asset.type === 'document' && asset.name.toLowerCase().endsWith('.pdf')) {
1046
- await loadPdfPages(String(asset.id));
1047
- } else {
1048
- setPdfPages(null);
1049
- }
1050
- }}>
1051
- <Eye className="w-4 h-4 mr-2" /> Preview
1052
- </DropdownMenuItem>
1053
- <DropdownMenuItem onClick={() => {
1054
- window.open(`/api/assets/${String(asset.id)}/download`, '_blank');
1055
- }}>
1056
- <Download className="w-4 h-4 mr-2" /> Download
1057
- </DropdownMenuItem>
1058
- <DropdownMenuItem
1059
- className="text-red-600"
1060
- onClick={async () => {
1061
- if (confirm(`Are you sure you want to delete "${asset.name}"?`)) {
1062
- await handleDeleteAsset(String(asset.id));
1063
- }
1064
- }}
1065
- >
1066
- <Trash2 className="w-4 h-4 mr-2" /> Delete
1067
- </DropdownMenuItem>
1068
- </DropdownMenuContent>
1069
- </DropdownMenu>
1070
- </motion.div>
1071
- ))}
1072
- </div>
1073
- </CardContent>
1074
- </Card>
1075
- )}
1076
- </motion.div>
1077
- </div>
1078
- </div>
1079
-
1080
- {/* Preview Dialog */}
1081
- <Dialog open={previewDialogOpen} onOpenChange={(open) => {
1082
- setPreviewDialogOpen(open);
1083
- if (!open) {
1084
- setPreviewAsset(null);
1085
- setPdfPages(null);
1086
- }
1087
- }}>
1088
- <DialogContent className="max-w-6xl max-h-[90vh] flex flex-col">
1089
- <DialogHeader>
1090
- <DialogTitle className="flex items-center justify-between">
1091
- <span>{previewAsset?.name || 'Preview'}</span>
1092
- {previewAsset && (
1093
- <Button
1094
- variant="ghost"
1095
- size="icon"
1096
- className="h-8 w-8 text-red-600 hover:text-red-700 hover:bg-red-50"
1097
- onClick={async () => {
1098
- if (confirm(`Are you sure you want to delete "${previewAsset.name}"?`)) {
1099
- await handleDeleteAsset(String(previewAsset.id));
1100
- }
1101
- }}
1102
- disabled={isDeleting}
1103
- >
1104
- <Trash2 className="w-4 h-4" />
1105
- </Button>
1106
- )}
1107
- </DialogTitle>
1108
- </DialogHeader>
1109
- <div className="mt-4 flex-1 overflow-auto">
1110
- {previewAsset && (
1111
- <div className="space-y-4">
1112
- {previewAsset.type === 'image' ? (
1113
- <img
1114
- src={`/api/assets/${String(previewAsset.id)}/download`}
1115
- alt={previewAsset.name}
1116
- className="max-w-full h-auto rounded-lg mx-auto"
1117
- />
1118
- ) : previewAsset.type === 'video' ? (
1119
- <video
1120
- src={`/api/assets/${String(previewAsset.id)}/download`}
1121
- controls
1122
- className="max-w-full rounded-lg mx-auto"
1123
- >
1124
- Your browser does not support the video tag.
1125
- </video>
1126
- ) : previewAsset.type === 'document' && previewAsset.name.toLowerCase().endsWith('.pdf') ? (
1127
- <div className="space-y-4">
1128
- {isLoadingPdf ? (
1129
- <div className="flex flex-col items-center justify-center p-12 bg-slate-50 rounded-lg">
1130
- <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mb-4"></div>
1131
- <p className="text-slate-600">Converting PDF pages to images...</p>
1132
- </div>
1133
- ) : pdfPages && pdfPages.error ? (
1134
- <div className="flex flex-col items-center justify-center p-12 bg-red-50 rounded-lg border border-red-200">
1135
- <FileText className="w-16 h-16 text-red-400 mb-4" />
1136
- <p className="text-red-600 font-medium mb-2">Failed to load PDF preview</p>
1137
- <p className="text-red-500 text-sm mb-4 text-center max-w-md">{pdfPages.error}</p>
1138
- <p className="text-slate-600 text-xs mb-4 text-center max-w-md">
1139
- This might be because poppler-utils is not installed. PDFs can still be downloaded.
1140
- </p>
1141
- <Button
1142
- onClick={() => window.open(`/api/assets/${String(previewAsset.id)}/download`, '_blank')}
1143
- variant="outline"
1144
- className="border-red-200 text-red-600 hover:bg-red-100"
1145
- >
1146
- <Download className="w-4 h-4 mr-2" />
1147
- Download PDF
1148
- </Button>
1149
- </div>
1150
- ) : pdfPages && pdfPages.pages ? (
1151
- <div className="space-y-6">
1152
- <div className="text-sm text-slate-600 bg-blue-50 p-3 rounded-lg">
1153
- <strong>PDF Viewer:</strong> {pdfPages.total_pages} page{pdfPages.total_pages !== 1 ? 's' : ''}
1154
- </div>
1155
- <div className="space-y-4 max-h-[70vh] overflow-y-auto pr-2">
1156
- {pdfPages.pages.map((page, index) => (
1157
- <div key={index} className="border border-slate-200 rounded-lg p-4 bg-white shadow-sm">
1158
- <div className="text-xs text-slate-500 mb-2 font-medium">
1159
- Page {page.page_number} of {pdfPages.total_pages}
1160
- </div>
1161
- <img
1162
- src={page.image_data}
1163
- alt={`Page ${page.page_number}`}
1164
- className="max-w-full h-auto rounded border border-slate-100 shadow-sm"
1165
- style={{ maxHeight: '800px' }}
1166
- />
1167
- </div>
1168
- ))}
1169
- </div>
1170
- </div>
1171
- ) : (
1172
- <div className="flex flex-col items-center justify-center p-12 bg-slate-50 rounded-lg">
1173
- <FileText className="w-16 h-16 text-slate-400 mb-4" />
1174
- <p className="text-slate-600 mb-4">Failed to load PDF preview</p>
1175
- <Button
1176
- onClick={() => window.open(`/api/assets/${String(previewAsset.id)}/download`, '_blank')}
1177
- variant="outline"
1178
- >
1179
- <Download className="w-4 h-4 mr-2" />
1180
- Download to view
1181
- </Button>
1182
- </div>
1183
- )}
1184
- </div>
1185
- ) : (
1186
- <div className="flex flex-col items-center justify-center p-12 bg-slate-50 rounded-lg">
1187
- <FileText className="w-16 h-16 text-slate-400 mb-4" />
1188
- <p className="text-slate-600 mb-4">Preview not available for this file type</p>
1189
- <Button
1190
- onClick={() => window.open(`/api/assets/${String(previewAsset.id)}/download`, '_blank')}
1191
- variant="outline"
1192
- >
1193
- <Download className="w-4 h-4 mr-2" />
1194
- Download to view
1195
- </Button>
1196
- </div>
1197
- )}
1198
- <div className="flex items-center justify-between pt-4 border-t sticky bottom-0 bg-white">
1199
- <div className="text-sm text-slate-600">
1200
- <p><strong>Type:</strong> {previewAsset.type}</p>
1201
- <p><strong>Size:</strong> {previewAsset.size}</p>
1202
- <p><strong>Date:</strong> {previewAsset.date}</p>
1203
- </div>
1204
- <div className="flex gap-2">
1205
- <Button
1206
- onClick={() => window.open(`/api/assets/${String(previewAsset.id)}/download`, '_blank')}
1207
- variant="outline"
1208
- >
1209
- <Download className="w-4 h-4 mr-2" />
1210
- Download
1211
- </Button>
1212
- <Button
1213
- variant="outline"
1214
- className="text-red-600 border-red-200 hover:bg-red-50"
1215
- onClick={async () => {
1216
- if (confirm(`Are you sure you want to delete "${previewAsset.name}"?`)) {
1217
- await handleDeleteAsset(String(previewAsset.id));
1218
- }
1219
- }}
1220
- disabled={isDeleting}
1221
- >
1222
- <Trash2 className="w-4 h-4 mr-2" />
1223
- {isDeleting ? 'Deleting...' : 'Delete'}
1224
- </Button>
1225
- </div>
1226
- </div>
1227
- </div>
1228
- )}
1229
- </div>
1230
- </DialogContent>
1231
- </Dialog>
1232
- </div>
1233
- );
1234
- }
1235
-
 
1
+ md