-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.html
More file actions
1449 lines (1242 loc) · 68.4 KB
/
Copy pathupload.html
File metadata and controls
1449 lines (1242 loc) · 68.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload - 4Set Pipeline</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="assets/js/tailwind.config.js"></script>
<link rel="stylesheet" href="assets/css/theme_pantone_light_1.css" />
<link rel="stylesheet" href="assets/css/index.css" />
<link rel="stylesheet" href="assets/css/global.css" />
<link rel="stylesheet" href="assets/css/upload.css" />
<link rel="stylesheet" href="assets/css/spotlight-system.css" />
<link rel="stylesheet" href="assets/css/tooltip-styles.css" />
<link rel="icon" type="image/x-icon" href="assets/favicon.ico" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono&display=swap" rel="stylesheet">
<script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
</head>
<body class="min-h-screen hero-background">
<!-- Spotlight Overlay -->
<div id="uploadPageOverlay" style="position: fixed; inset: 0; pointer-events: none; z-index: 10000;"></div>
<div class="relative overflow-hidden">
<!-- Decorative Background Elements (matching index.html) -->
<div class="absolute inset-x-0 top-0 h-32 bg-gradient-to-b from-white/70 to-transparent"></div>
<div class="absolute inset-0 pointer-events-none">
<div class="absolute -left-24 top-24 w-48 h-48 rounded-full border border-primary/20 glow-ring"></div>
<div class="absolute right-12 bottom-20 w-40 h-40 rounded-full border border-secondary/30 glow-ring-secondary"></div>
<div class="absolute left-1/3 top-1/2 w-20 h-20 rounded-full bg-secondary/20 blur-3xl"></div>
<div class="absolute right-1/4 top-1/3 w-24 h-24 rounded-full bg-primary/20 blur-3xl"></div>
</div>
<main class="relative z-10 mx-auto min-h-screen w-full max-w-6xl px-6 py-12 lg:py-16">
<!-- Header Section -->
<div class="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<span class="hero-badge inline-flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-wide mb-3">
<i data-lucide="upload-cloud" class="w-4 h-4"></i>
File Upload Station
</span>
<h1 class="upload-title text-3xl font-bold text-[color:var(--primary)] sm:text-4xl lg:text-5xl">
Assessment Uploader
</h1>
<p class="upload-subtitle mt-2 text-base text-[color:var(--muted-foreground)] lg:text-lg">
Drag and drop PDF or E-Prime (.edat3) files to add them to the processing queue
</p>
</div>
<div class="flex items-center gap-3">
<a href="log.html" class="hero-button secondary-button flex items-center gap-2 px-6 py-3 text-sm font-semibold" title="View Processing Logs">
<i data-lucide="file-text" class="w-4 h-4"></i>
<span>View Processing Logs</span>
</a>
<a href="index.html" class="hero-button secondary-button flex items-center gap-2 px-6 py-3 text-sm font-semibold">
<i data-lucide="arrow-left" class="w-4 h-4"></i>
<span>Go Back Home</span>
</a>
</div>
</div>
<!-- System Status Card -->
<div class="entry-card mb-6 p-4 lg:p-6">
<div class="flex flex-col gap-4 sm:gap-3">
<div class="flex flex-wrap items-center gap-3">
<div class="flex items-center gap-3 flex-shrink-0">
<div id="system-status-badge" class="badge-success flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-medium min-h-[40px] min-w-[120px]">
<span id="status-indicator" class="inline-block h-2 w-2 rounded-full bg-[color:var(--success)] animate-pulse flex-shrink-0"></span>
<div class="flex flex-col items-start flex-1">
<span class="text-[color:var(--foreground)] font-semibold leading-tight whitespace-nowrap">System</span>
<span id="status-text" class="status-value text-[10px] text-[color:var(--muted-foreground)] leading-tight whitespace-nowrap">Ready</span>
</div>
</div>
<div class="interactive-btn-wrapper" style="position: relative;">
<button data-spotlight="button" onclick="showPCNumberDialog(); event.stopPropagation();" id="pc-number-badge" class="flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-medium border hover:opacity-80 transition-all cursor-pointer min-h-[40px] min-w-[120px]" title="Click to set PC number">
<i data-lucide="monitor" class="w-3 h-3 flex-shrink-0"></i>
<div class="flex flex-col items-start flex-1">
<span class="text-[color:var(--foreground)] font-semibold leading-tight whitespace-nowrap">PC Number</span>
<span id="pc-number" class="status-value font-mono text-[10px] leading-tight whitespace-nowrap">—</span>
</div>
</button>
<div id="tooltip-pc-number" class="feature-tooltip" style="display: none;">
<div style="font-weight: 600; margin-bottom: 4px;">💻 PC Number</div>
<div style="font-size: 13px; opacity: 0.9;">Set your workstation identifier for tracking uploads</div>
<div style="position: absolute; top: -6px; left: 50%; transform: translateX(-50%); width: 0; height: 0; border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 6px solid #1f2937;"></div>
</div>
</div>
<div class="interactive-btn-wrapper" style="position: relative;">
<button data-spotlight="button" onclick="showUploadDestinationDialog(); event.stopPropagation();" id="upload-destination-badge" class="flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-medium border hover:opacity-80 transition-all cursor-pointer min-h-[40px] min-w-[120px]" title="Click to set upload destination">
<i data-lucide="folder-open" class="w-3 h-3 flex-shrink-0"></i>
<div class="flex flex-col items-start flex-1">
<span class="text-[color:var(--foreground)] font-semibold leading-tight whitespace-nowrap">Upload Destination</span>
<span id="destination-status" class="status-value text-[10px] leading-tight whitespace-nowrap">Not Set</span>
</div>
</button>
<div id="tooltip-upload-destination" class="feature-tooltip" style="display: none;">
<div style="font-weight: 600; margin-bottom: 4px;">📁 Upload Destination</div>
<div style="font-size: 13px; opacity: 0.9;">Select the folder where files will be saved for processing</div>
<div style="position: absolute; top: -6px; left: 50%; transform: translateX(-50%); width: 0; height: 0; border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 6px solid #1f2937;"></div>
</div>
</div>
</div>
<div class="flex items-start gap-2 text-xs text-[color:var(--muted-foreground)] bg-[color:var(--muted)]/20 px-3 py-2 rounded-lg border border-[color:var(--border)] max-w-2xl flex-1 min-w-[300px]">
<i data-lucide="info" class="w-3.5 h-3.5 flex-shrink-0 mt-0.5 text-[color:var(--primary)]"></i>
<p class="leading-relaxed">
<span class="font-semibold text-[color:var(--foreground)]">One-time setup required.</span>
Please configure your PC number and upload destination folder once per workstation. Browser permissions will be saved for future use.
</p>
</div>
</div>
</div>
</div>
<div class="grid gap-6 lg:grid-cols-2">
<!-- Upload Zone -->
<div class="lg:col-span-2">
<div class="interactive-btn-wrapper" style="position: relative;">
<div class="upload-zone entry-card p-8 sm:p-12 lg:p-16 text-center cursor-pointer" id="upload-zone">
<input type="file" id="file-input" accept=".pdf,.edat3" multiple class="hidden" aria-label="Select PDF or E-Prime files to upload">
<div class="flex flex-col items-center gap-4">
<div class="p-6 rounded-full bg-[color:var(--primary)]/10">
<i data-lucide="file-plus" class="w-12 h-12 sm:w-16 sm:h-16 text-[color:var(--primary)]"></i>
</div>
<div>
<h2 class="text-xl sm:text-2xl lg:text-3xl font-bold text-[color:var(--foreground)] mb-2">Drop Files Here</h2>
<p class="text-sm sm:text-base text-[color:var(--muted-foreground)] mb-4">or click anywhere to browse your computer</p>
</div>
<button class="hero-button btn-primary flex items-center gap-2 px-6 sm:px-8 py-3 text-sm sm:text-base font-semibold" id="browse-btn">
<i data-lucide="folder-open" class="w-4 h-4 sm:w-5 sm:h-5"></i>
Browse Files
</button>
<div class="mt-4 space-y-1.5 text-[color:var(--muted-foreground)]">
<p class="flex items-center gap-2 justify-center text-xs sm:text-sm">
<i data-lucide="info" class="w-3 h-3 sm:w-4 sm:h-4"></i>
PDF and E-Prime (.edat3) files are supported
</p>
<p class="flex items-center gap-2 justify-center text-[10px] sm:text-xs">
<i data-lucide="shield-alert" class="w-3 h-3"></i>
<span>For security, system folders (e.g., <code class="font-mono">C:\Windows</code>, <code class="font-mono">Program Files</code>) cannot be selected</span>
</p>
</div>
</div>
</div>
<div id="tooltip-upload-zone" class="feature-tooltip" style="display: none;">
<div style="font-weight: 600; margin-bottom: 4px;">📤 Upload Zone</div>
<div style="font-size: 13px; opacity: 0.9;">Drag and drop PDF or E-Prime (.edat3) files here or click to browse. Files are saved directly to your selected destination folder.</div>
<div style="position: absolute; top: -6px; left: 50%; transform: translateX(-50%); width: 0; height: 0; border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 6px solid #1f2937;"></div>
</div>
</div>
<div class="mt-3 flex justify-end">
<button
id="upload-panel-trigger"
type="button"
onclick="showUploadPanel()"
class="hidden text-xs sm:text-sm text-[color:var(--primary)] hover:text-[color:var(--primary)]/80 font-medium flex items-center gap-1"
>
<i data-lucide="panel-top-open" class="w-4 h-4"></i>
View upload status
</button>
</div>
</div>
<!-- Upload Summary -->
<div id="upload-summary" class="lg:col-span-2 hidden">
<div class="entry-card border-[color:var(--success)]/30 p-4 sm:p-6">
<div class="flex items-start gap-3">
<i data-lucide="check-circle" class="w-5 h-5 sm:w-6 sm:h-6 text-[color:var(--success)] mt-0.5 flex-shrink-0"></i>
<div class="flex-1 min-w-0">
<h4 class="font-semibold text-[color:var(--foreground)] mb-1 text-sm sm:text-base">Upload Complete</h4>
<p class="text-xs sm:text-sm text-[color:var(--muted-foreground)]">
<span id="success-count">0</span> file(s) uploaded successfully to the incoming folder.
The processor agent will pick them up automatically.
</p>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
<script>
// State
const state = {
pcNumber: null,
uploadQueue: [],
isUploading: false,
directoryHandle: null // File System Access API handle (user-selected folder)
};
// DOM References
const uploadZone = document.getElementById('upload-zone');
const fileInput = document.getElementById('file-input');
const browseBtn = document.getElementById('browse-btn');
const fileList = document.getElementById('file-list');
const uploadQueue = document.getElementById('upload-queue');
const uploadSummary = document.getElementById('upload-summary');
// Initialize
async function init() {
await detectSystemPaths();
await restoreDirectoryHandle(); // Restore folder access if previously granted
updateDestinationDisplay(); // Update upload destination badge
updateSystemStatus(); // Update system status badge
setupEventListeners();
lucide.createIcons();
}
// Detect PC number only (OneDrive detection removed - using File System Access API)
async function detectSystemPaths() {
try {
// Detect PC number from localStorage only
const manualPC = localStorage.getItem('pc_number');
const detectedPCNumber = (manualPC && manualPC !== '000') ? manualPC : null;
state.pcNumber = detectedPCNumber;
// Update UI
updatePCNumberDisplay(state.pcNumber);
lucide.createIcons();
} catch (error) {
console.error('[PC Detection] Failed:', error);
state.pcNumber = null;
updatePCNumberDisplay(state.pcNumber);
lucide.createIcons();
}
}
// Legacy function - now no-op (OneDrive badge removed, using Upload Destination)
function updateOneDriveStatus() {
// No-op: OneDrive badge replaced with Upload Destination badge
return;
// Check if path is valid (comprehensive validation)
const basePath = state.oneDrivePath;
const cached = localStorage.getItem('onedrive_base_path');
let isValid = false;
let statusText = '';
let tooltipText = '';
// Remove all state classes first
badge.classList.remove('badge-valid', 'badge-error');
if (!basePath || basePath === '') {
// No path
statusText = 'Not Detected';
tooltipText = 'Path not detected - Click to configure';
} else if (basePath.includes('KeySteps') && !cached) {
// Fallback path (only if NOT manually saved)
statusText = 'Using Fallback';
tooltipText = 'Using fallback path from config - Click to set correct path';
} else if (!basePath.match(/^[A-Z]:\\/i)) {
// Invalid drive letter
statusText = 'Invalid Path';
tooltipText = 'Path must start with drive letter (e.g., C:\\)';
} else if (basePath.length < 5) {
// Too short
statusText = 'Invalid Path';
tooltipText = 'Path is too short to be valid';
} else if (basePath.match(/[<>"|?*]/)) {
// Invalid characters
statusText = 'Invalid Path';
tooltipText = 'Path contains invalid characters';
} else {
// Valid path
isValid = true;
// Determine detection method
if (window.location.protocol === 'file:') {
statusText = 'File Path';
tooltipText = 'Detected from file:// URL';
} else if (cached) {
statusText = 'Cached Path';
tooltipText = 'Using saved path from localStorage';
} else {
statusText = 'Auto-Detected';
tooltipText = 'Automatically detected path';
}
}
// Apply state
if (isValid) {
badge.classList.add('badge-valid');
} else {
badge.classList.add('badge-error');
}
statusSpan.textContent = statusText;
// Build tooltip with actual paths
let fullTooltip = tooltipText + '\n\nClick to change path';
if (basePath) {
fullTooltip += '\n\nBase: ' + basePath;
if (state.watchPath) {
fullTooltip += '\nWatch: ' + state.watchPath;
}
} else {
fullTooltip += '\n\nNo path configured';
}
badge.title = fullTooltip;
// Update system status
updateSystemStatus();
}
// Detect PC number from multiple sources
async function detectPCNumber() {
// Strategy 1: Check manually configured PC number
const savedPCNumber = localStorage.getItem('pc_number');
if (savedPCNumber) {
return savedPCNumber;
}
// Strategy 2: Check cached OneDrive path
const cachedPath = localStorage.getItem('onedrive_base_path');
if (cachedPath) {
// Look for computer name patterns
const pathMatch = cachedPath.match(/(?:KS|LAPTOP|PC|WORKSTATION)(\d+)/i);
if (pathMatch) {
const pcNum = pathMatch[1].padStart(3, '0');
localStorage.setItem('pc_number', pcNum);
return pcNum;
}
// Extract from username in cached path
const userMatch = cachedPath.match(/Users[\\\/]([^\\\/]+)/i);
if (userMatch) {
const username = userMatch[1];
const numMatch = username.match(/(\d+)/);
if (numMatch) {
const pcNum = numMatch[1].padStart(3, '0');
localStorage.setItem('pc_number', pcNum);
return pcNum;
}
}
}
// Strategy 3: Try to extract from current URL path
const path = window.location.pathname;
const pathMatch = path.match(/(?:KS|LAPTOP|PC|WORKSTATION)(\d+)/i);
if (pathMatch) {
const pcNum = pathMatch[1].padStart(3, '0');
localStorage.setItem('pc_number', pcNum);
return pcNum;
}
// Strategy 4: Auto-detection failed
console.warn('[PC Detection] Could not auto-detect PC number - user needs to set manually');
return '000'; // Will show as red badge
}
// OneDrive path detection (browser-compatible only)
async function detectOneDrivePath(config) {
// Strategy 1: Check localStorage cache (primary for HTTP deployments)
const savedPath = localStorage.getItem('onedrive_base_path');
if (savedPath) {
return savedPath;
return savedPath;
}
// Strategy 2: Parse from file:// protocol (only works when opened directly)
if (window.location.protocol === 'file:') {
let fullPath = window.location.href;
fullPath = fullPath.replace('file:///', '');
fullPath = decodeURIComponent(fullPath);
const serverIndex = fullPath.indexOf('4Set-Server');
if (serverIndex > 0) {
let basePath = fullPath.substring(0, serverIndex + '4Set-Server'.length);
basePath = basePath.replace(/\//g, '\\');
// Ensure drive letter format
if (basePath.match(/^[A-Z]\\/i) && !basePath.match(/^[A-Z]:/i)) {
basePath = basePath.charAt(0) + ':' + basePath.substring(1);
}
localStorage.setItem('onedrive_base_path', basePath);
return basePath;
}
}
// Strategy 3: Use config fallback (for HTTP deployments or when file:// fails)
if (config.oneDrive?.fallbackRoot && config.oneDrive?.relativePath) {
const fallbackPath = config.oneDrive.fallbackRoot + config.oneDrive.relativePath;
// Don't save to localStorage - let first-run setup handle it
return fallbackPath;
}
// Final fallback
const hardcodedFallback = 'C:\\Users\\KeySteps\\The Education University of Hong Kong\\o365grp_KeySteps@JC - General\\98 - IT Support\\04 - Homemade Apps\\4Set-Server';
console.warn('[OneDrive Detection] Using hardcoded fallback');
return hardcodedFallback;
}
// Show PC Number Configuration Modal
function showPCNumberDialog() {
const modal = document.getElementById('pc-number-modal');
const input = document.getElementById('pc-number-input');
const currentPC = state.pcNumber || localStorage.getItem('pc_number') || '';
input.value = currentPC && currentPC !== '000' ? currentPC : '';
document.getElementById('pc-modal-error').textContent = '';
modal.classList.remove('hidden');
setTimeout(() => {
input.focus();
input.select();
lucide.createIcons();
}, 100);
}
// Close PC Number Modal
function closePCNumberModal() {
document.getElementById('pc-number-modal').classList.add('hidden');
}
// Clear PC Number Cache
function clearPCNumberCache() {
if (confirm('Clear cached PC number and reload?\n\nYou will need to set it again.')) {
localStorage.removeItem('pc_number');
location.reload();
}
}
// Save PC Number from Modal
function savePCNumber() {
const input = document.getElementById('pc-number-input');
const errorDiv = document.getElementById('pc-modal-error');
const value = input.value.trim();
// Validation
if (!value) {
errorDiv.textContent = 'Please enter a PC number';
input.focus();
return;
}
if (!/^\d+$/.test(value)) {
errorDiv.textContent = 'PC number must contain only digits';
input.focus();
return;
}
if (parseInt(value) === 0) {
errorDiv.textContent = 'PC number cannot be 0';
input.focus();
return;
}
// Format and save
const formatted = value.padStart(3, '0');
localStorage.setItem('pc_number', formatted);
state.pcNumber = formatted;
// Update UI
updatePCNumberDisplay(formatted);
closePCNumberModal();
}
// Update PC Number Display
function updatePCNumberDisplay(pcNumber) {
const pcNumberSpan = document.getElementById('pc-number');
const pcBadge = document.getElementById('pc-number-badge');
if (!pcNumberSpan || !pcBadge) {
console.error('[UI] PC number elements not found');
return;
}
// Display "Not Set" if no PC number configured
pcNumberSpan.textContent = pcNumber || 'Not Set';
// Remove all state classes first
pcBadge.classList.remove('badge-valid', 'badge-error', 'pc-number-not-set');
if (!pcNumber || pcNumber === '000') {
// PC number NOT set - error state
pcBadge.classList.add('badge-error');
pcBadge.title = 'PC number not set - Click to configure';
} else {
// PC number IS set - success state (green)
pcBadge.classList.add('badge-valid');
pcBadge.title = 'PC ' + pcNumber + ' - Click to change';
}
// Update system status based on both PC and OneDrive
updateSystemStatus();
lucide.createIcons();
}
// Update System Status Badge
function updateSystemStatus() {
const statusBadge = document.getElementById('system-status-badge');
const statusText = document.getElementById('status-text');
const statusIndicator = document.getElementById('status-indicator');
// Clear previous states
statusBadge.classList.remove('badge-success', 'badge-error', 'badge-warning');
const hasPCNumber = state.pcNumber && state.pcNumber !== '000';
const hasDestination = state.directoryHandle !== null;
if (hasPCNumber && hasDestination) {
// Both configured - success (green)
statusBadge.classList.add('badge-success');
statusText.textContent = 'Ready';
statusIndicator.classList.remove('animate-pulse');
} else if (!hasPCNumber && !hasDestination) {
// Neither configured - error (red)
statusBadge.classList.add('badge-error');
statusText.textContent = 'Setup Required';
statusIndicator.classList.remove('animate-pulse');
} else {
// Partial configuration - warning (orange)
statusBadge.classList.add('badge-warning');
statusText.textContent = 'Partial Setup';
statusIndicator.classList.remove('animate-pulse');
}
}
// Show Upload Destination Modal
function showUploadDestinationDialog() {
const modal = document.getElementById('destination-modal');
// Update current destination display
if (state.directoryHandle) {
document.getElementById('current-destination').textContent = state.directoryHandle.name;
document.getElementById('destination-subpath').textContent = state.directoryHandle.name;
} else {
document.getElementById('current-destination').textContent = 'Not set';
document.getElementById('destination-subpath').textContent = '—';
}
modal.classList.remove('hidden');
lucide.createIcons();
}
// Close Upload Destination Modal
function closeDestinationModal() {
document.getElementById('destination-modal').classList.add('hidden');
}
// Select Upload Destination (trigger folder picker)
async function selectUploadDestination() {
closeDestinationModal();
try {
await requestDirectoryAccess(true); // Show permission info modal first
} catch (error) {
console.error('[Detection] Failed to detect system paths:', error);
}
// Final update to UI
updatePCNumberDisplay(state.pcNumber);
updateDestinationDisplay();
}
// Update destination badge display
function updateDestinationDisplay() {
const badge = document.getElementById('upload-destination-badge');
const statusSpan = document.getElementById('destination-status');
// Remove all state classes
badge.classList.remove('badge-valid', 'badge-error');
if (state.directoryHandle) {
badge.classList.add('badge-valid');
statusSpan.textContent = state.directoryHandle.name;
badge.title = `Upload destination: ${state.directoryHandle.name}\nClick to change`;
} else {
badge.classList.add('badge-error');
statusSpan.textContent = 'Not Set';
badge.title = 'Click to set upload destination folder';
}
}
// Legacy function kept for compatibility
async function showPathOverrideDialog() {
showUploadDestinationDialog();
}
// Legacy functions (now no-ops)
function closePathModal() {
closeDestinationModal();
}
// No-op - legacy functions removed (now using File System Access API)
// Show configuration warning modal (clean modal like checking_system_home.html)
function showConfigWarningModal(needsPCNumber, needsDestination) {
const modal = document.getElementById('config-warning-modal');
const messageDiv = document.getElementById('config-warning-message');
// Build warning message
let message = '<p class="mb-4">Before uploading files, you need to configure:</p><ul class="space-y-2 ml-6 list-disc">';
if (needsPCNumber) {
message += '<li><strong>PC Number:</strong> Set your workstation identifier for tracking uploads</li>';
}
if (needsDestination) {
message += '<li><strong>Upload Destination:</strong> Select the folder where files will be saved</li>';
}
message += '</ul>';
messageDiv.innerHTML = message;
// Show modal (no spotlight - clean modal approach)
modal.classList.remove('hidden');
// Refresh icons (if lucide is loaded)
if (typeof lucide !== 'undefined') {
lucide.createIcons();
}
}
// Close configuration warning modal
function closeConfigWarningModal() {
const modal = document.getElementById('config-warning-modal');
modal.classList.add('hidden');
}
// Setup event listeners
function setupEventListeners() {
// Browse button
browseBtn.addEventListener('click', (e) => {
e.stopPropagation();
// Check configuration before opening file dialog
const hasPCNumber = state.pcNumber && state.pcNumber !== '000';
const hasDestination = state.directoryHandle !== null;
if (!hasPCNumber || !hasDestination) {
showConfigWarningModal(!hasPCNumber, !hasDestination);
return;
}
fileInput.click();
});
// Click on upload zone
uploadZone.addEventListener('click', () => {
// Check configuration before opening file dialog
const hasPCNumber = state.pcNumber && state.pcNumber !== '000';
const hasDestination = state.directoryHandle !== null;
if (!hasPCNumber || !hasDestination) {
showConfigWarningModal(!hasPCNumber, !hasDestination);
return;
}
fileInput.click();
});
// File input change
fileInput.addEventListener('change', (e) => {
handleFiles(Array.from(e.target.files));
e.target.value = ''; // Reset input
});
// Drag and drop
uploadZone.addEventListener('dragover', (e) => {
e.preventDefault();
uploadZone.classList.add('drag-over');
});
uploadZone.addEventListener('dragleave', () => {
uploadZone.classList.remove('drag-over');
});
uploadZone.addEventListener('drop', (e) => {
e.preventDefault();
uploadZone.classList.remove('drag-over');
// Check configuration before processing dropped files
const hasPCNumber = state.pcNumber && state.pcNumber !== '000';
const hasDestination = state.directoryHandle !== null;
if (!hasPCNumber || !hasDestination) {
showConfigWarningModal(!hasPCNumber, !hasDestination);
return;
}
const files = Array.from(e.dataTransfer.files).filter(f => {
const name = f.name.toLowerCase();
return name.endsWith('.pdf') || name.endsWith('.edat3');
});
if (files.length > 0) {
handleFiles(files);
} else {
alert('Please drop only PDF or E-Prime (.edat3) files.');
}
});
}
// Handle dropped/selected files
function handleFiles(files) {
if (files.length === 0) return;
const hasPCNumber = state.pcNumber && state.pcNumber !== '000';
const hasDestination = state.directoryHandle !== null;
// Check if PC number and destination are set (BOTH REQUIRED for web uploader)
if (!hasPCNumber || !hasDestination) {
// Show configuration warning modal with spotlight
showConfigWarningModal(!hasPCNumber, !hasDestination);
return;
}
// Filter supported files (PDF and EDAT3)
const supportedFiles = Array.from(files).filter(file => {
const name = file.name.toLowerCase();
return file.type === 'application/pdf' || name.endsWith('.pdf') || name.endsWith('.edat3');
});
if (supportedFiles.length === 0) {
alert('Please select PDF or E-Prime (.edat3) files only.');
return;
}
// Add to queue
supportedFiles.forEach(file => {
const id = Date.now() + Math.random();
state.uploadQueue.push({ id, file, status: 'pending' });
addUploadItemToPanel(id, file);
});
// Start processing
if (!state.isUploading) {
state.isUploading = true;
processUploadQueue();
}
}
// Add file to UI
function addFileToUI(id, file) {
const fileItem = document.createElement('div');
fileItem.id = `file-${id}`;
fileItem.className = 'file-item entry-card p-4 flex flex-col sm:flex-row items-start sm:items-center gap-3 sm:gap-4';
fileItem.innerHTML = `
<div class="p-2 rounded bg-[color:var(--accent)]/10 flex-shrink-0">
<i data-lucide="file-text" class="w-5 h-5 sm:w-6 sm:h-6 text-[color:var(--accent)]"></i>
</div>
<div class="flex-1 min-w-0">
<p class="font-medium text-[color:var(--foreground)] truncate text-sm sm:text-base">${file.name}</p>
<p class="text-xs sm:text-sm text-[color:var(--muted-foreground)] mt-0.5">${formatFileSize(file.size)}</p>
</div>
<div class="status flex items-center gap-2 self-end sm:self-auto">
<div class="w-4 h-4 sm:w-5 sm:h-5 border-2 border-[color:var(--muted-foreground)]/30 border-t-[color:var(--primary)] rounded-full animate-spin"></div>
<span class="text-xs sm:text-sm text-[color:var(--muted-foreground)]">Uploading...</span>
</div>
`;
fileList.appendChild(fileItem);
lucide.createIcons();
}
// Process upload queue
async function processUploadQueue() {
let successCount = 0;
for (const item of state.uploadQueue) {
if (item.status !== 'pending') continue;
try {
await uploadFile(item.id, item.file);
updateUploadItemStatus(item.id, 'success');
item.status = 'success';
successCount++;
} catch (error) {
updateUploadItemStatus(item.id, 'error', error.message);
item.status = 'error';
}
}
state.isUploading = false;
// Update panel title
document.getElementById('panel-title').textContent = `${successCount} Uploaded`;
}
// Show folder permission info modal
function showFolderPermissionModal() {
const modal = document.getElementById('folder-permission-modal');
modal.classList.remove('hidden');
lucide.createIcons();
}
// Close folder permission modal
function closeFolderPermissionModal() {
const modal = document.getElementById('folder-permission-modal');
modal.classList.add('hidden');
}
// Proceed with folder selection after user reads info
async function proceedWithFolderSelection() {
closeFolderPermissionModal();
try {
await requestDirectoryAccess();
} catch (error) {
// User cancelled or error occurred
}
}
// Request directory access (File System Access API)
async function requestDirectoryAccess(showModal = false) {
try {
// Check if API is supported
if (!('showDirectoryPicker' in window)) {
throw new Error('File System Access API not supported. Please use Chrome or Edge.');
}
// Show info modal on first access if requested
if (showModal) {
showFolderPermissionModal();
return; // Modal will call this function again without showModal
}
// Build picker options. Reuse previous handle if available so user lands in the same folder.
const pickerOptions = { mode: 'readwrite' };
if (state.directoryHandle) {
pickerOptions.startIn = state.directoryHandle;
} else {
pickerOptions.startIn = 'documents';
}
// Request directory picker (for parent folder - 4Set-Server)
const dirHandle = await window.showDirectoryPicker(pickerOptions);
// Verify write permission
const permission = await dirHandle.queryPermission({ mode: 'readwrite' });
if (permission !== 'granted') {
const request = await dirHandle.requestPermission({ mode: 'readwrite' });
if (request !== 'granted') {
throw new Error('Write permission denied');
}
}
// Store parent folder handle
state.directoryHandle = dirHandle;
// Store in IndexedDB for future use
await storeDirectoryHandle(dirHandle);
// Update UI
updateDestinationDisplay();
updateSystemStatus();
return dirHandle;
} catch (error) {
console.error('[File Access] Error:', error);
throw error;
}
}
// Store directory handle in IndexedDB
async function storeDirectoryHandle(handle) {
try {
const database = await openDB();
// Verify object store exists before creating transaction
if (!database.objectStoreNames.contains('handles')) {
console.error('[IndexedDB] handles object store not found in database');
return; // Graceful degradation - continue without persistence
}
const tx = database.transaction('handles', 'readwrite');
const store = tx.objectStore('handles');
const request = store.put(handle, 'incomingFolder');
return new Promise((resolve, reject) => {
request.onsuccess = () => {
resolve();
};
request.onerror = () => reject(request.error);
});
} catch (error) {
console.error('[IndexedDB] Error storing handle:', error);
// Don't throw - allow app to continue without persistence
console.warn('[IndexedDB] Continuing without handle persistence');
}
}
// Restore directory handle from IndexedDB
async function restoreDirectoryHandle() {
try {
const database = await openDB();
// Verify object store exists before creating transaction
if (!database.objectStoreNames.contains('handles')) {
return null;
}
const tx = database.transaction('handles', 'readonly');
const store = tx.objectStore('handles');
const getRequest = store.get('incomingFolder');
return new Promise((resolve) => {
getRequest.onsuccess = async () => {
const handle = getRequest.result;
if (handle) {
try {
// Verify permission still valid
const permission = await handle.queryPermission({ mode: 'readwrite' });
if (permission === 'granted') {
state.directoryHandle = handle;
resolve(handle);
return;
}
} catch (error) {
}
}
resolve(null);
};
getRequest.onerror = () => {
resolve(null);
};
});
} catch (error) {
return null;
}
}
// Open IndexedDB
function openDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open('4SetUploader', 2);
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create handles object store if it doesn't exist
if (!db.objectStoreNames.contains('handles')) {
db.createObjectStore('handles');
}
};
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = () => {
console.error('[IndexedDB] Failed to open database:', request.error);
reject(request.error);
};
request.onblocked = () => {
console.warn('[IndexedDB] Database upgrade blocked - please close other tabs');
};
});
}
// Upload file (File System Access API)
async function uploadFile(id, file) {
try {
// Ensure we have directory access (parent folder)
if (!state.directoryHandle) {
showUploadDestinationDialog(); // Show destination modal first
throw new Error('Please set upload destination first');
}
// Write directly to the selected folder (don't navigate to subfolder)
const targetHandle = state.directoryHandle;
// Create metadata (PC number is guaranteed to be set by handleFiles() validation)
const metadata = {
uploadedFrom: state.pcNumber
};
// Write file
const fileHandle = await targetHandle.getFileHandle(file.name, { create: true });
const fileWritable = await fileHandle.createWritable();
await fileWritable.write(file);
await fileWritable.close();
const isEdat3 = file.name.toLowerCase().endsWith('.edat3');
// Write metadata JSON file (only for PDFs - EDAT3 has PC number in filename)
if (!isEdat3) {
const metaFilename = file.name.replace('.pdf', '.meta.json');
const metaHandle = await targetHandle.getFileHandle(metaFilename, { create: true });
const metaWritable = await metaHandle.createWritable();
await metaWritable.write(JSON.stringify(metadata, null, 2));
await metaWritable.close();
}
return true;