-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.html
More file actions
1768 lines (1524 loc) · 80 KB
/
Copy pathlog.html
File metadata and controls
1768 lines (1524 loc) · 80 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>Processing Agent Logs - 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="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&family=Noto+Sans+TC&display=swap" rel="stylesheet">
<script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
<style>
/* Log Level Pills - Compact */
.log-level-pill {
display: inline-block;
padding: 1px 6px;
border-radius: 10px;
font-size: 0.55rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.log-level-INFO {
background-color: rgba(43, 57, 144, 0.1);
color: var(--primary);
border: 1px solid rgba(43, 57, 144, 0.2);
}
.log-level-DEBUG {
background-color: rgba(70, 82, 117, 0.08);
color: var(--muted-foreground);
border: 1px solid rgba(70, 82, 117, 0.15);
}
.log-level-WARN {
background-color: rgba(244, 208, 54, 0.15);
color: var(--warning);
border: 1px solid rgba(244, 208, 54, 0.3);
}
.log-level-ERROR {
background-color: rgba(240, 78, 105, 0.1);
color: var(--destructive);
border: 1px solid rgba(240, 78, 105, 0.25);
}
.log-level-REJECT {
background-color: rgba(240, 78, 105, 0.15);
color: var(--destructive);
border: 1px solid rgba(240, 78, 105, 0.3);
font-weight: 700;
}
.log-level-UPLOAD {
background-color: rgba(141, 190, 80, 0.15);
color: var(--success);
border: 1px solid rgba(141, 190, 80, 0.3);
}
.log-level-FILED {
background-color: rgba(141, 190, 80, 0.1);
color: var(--success);
border: 1px solid rgba(141, 190, 80, 0.25);
}
.log-level-DATA_OVERWRITE_DIFF {
background-color: rgba(249, 157, 51, 0.15);
color: var(--secondary);
border: 1px solid rgba(249, 157, 51, 0.3);
font-weight: 700;
}
.log-row:hover { background-color: var(--muted); }
/* File Type Badges */
.file-type-badge {
display: inline-flex;
align-items: center;
gap: 2px;
padding: 1px 5px;
border-radius: 4px;
font-size: 0.6rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.file-type-pdf {
background-color: rgba(239, 68, 68, 0.1);
color: #dc2626;
border: 1px solid rgba(239, 68, 68, 0.2);
}
.file-type-edat3 {
background-color: rgba(139, 92, 246, 0.1);
color: #7c3aed;
border: 1px solid rgba(139, 92, 246, 0.2);
}
/* File Type Filter Buttons */
.file-type-filter {
display: inline-flex;
align-items: center;
gap: 3px;
padding: 3px 8px;
border-radius: 6px;
font-size: 0.65rem;
font-weight: 500;
cursor: pointer;
transition: all 0.15s;
border: 1px solid transparent;
}
.file-type-filter.active {
font-weight: 600;
}
.file-type-filter:hover {
opacity: 0.85;
}
.duration-badge {
background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
}
/* Ultra-Compact Calendar Styles */
.calendar-grid {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 1px;
font-size: 0.6rem;
}
.calendar-day {
aspect-ratio: 1;
display: flex;
align-items: center;
justify-content: center;
border-radius: 0.25rem;
cursor: pointer;
transition: all 0.15s;
font-size: 0.6rem;
padding: 1px;
min-height: 20px;
}
.calendar-day.empty {
cursor: default;
color: #e5e7eb;
}
.calendar-day.weekend {
background-color: #fef3e2;
}
.calendar-day.no-log {
background-color: #f9fafb;
color: var(--muted-foreground);
}
.calendar-day.no-log:hover {
background-color: #f3f4f6;
}
.calendar-day.no-log.weekend {
background-color: #fef3e2;
}
.calendar-day.has-log {
background-color: #1e40af;
color: white;
font-weight: 700;
}
.calendar-day.has-log:hover {
background-color: #1e3a8a;
}
.calendar-day.has-log.weekend {
background-color: #c2410c;
color: white;
font-weight: 700;
}
.calendar-day.selected {
background-color: var(--primary);
color: white;
}
.calendar-day.today {
border: 2px solid var(--secondary);
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.spinning {
animation: spin 1s linear infinite;
}
</style>
</head>
<body class="min-h-screen hero-background">
<div class="relative overflow-hidden">
<!-- Decorative Background Elements -->
<div id="background-circles"></div>
<div class="absolute inset-x-0 top-0 h-32 bg-gradient-to-b from-white/70 to-transparent"></div>
<main class="relative z-10 mx-auto min-h-screen w-full max-w-6xl px-4 py-6 lg:py-8">
<!-- Header Section - Compact -->
<div class="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div class="flex items-center gap-3">
<i data-lucide="file-text" class="w-6 h-6 text-[color:var(--primary)]"></i>
<h1 class="text-xl sm:text-2xl font-bold tracking-tight text-[color:var(--foreground)]">Processing Agent Logs</h1>
</div>
<a href="upload.html" class="hero-button secondary-button flex items-center gap-1.5 px-4 py-2 text-xs font-semibold self-start">
<i data-lucide="arrow-left" class="w-3.5 h-3.5"></i>
<span>Back</span>
</a>
</div>
<!-- Two-Column Layout: Date Picker (20%) + Log Viewer (80%) -->
<div class="grid grid-cols-12 gap-4">
<!-- LEFT SIDEBAR: Date Picker (20%) -->
<div class="col-span-12 lg:col-span-3">
<div class="entry-card p-4 sticky top-4">
<h2 class="text-sm font-semibold text-[color:var(--foreground)] mb-3 flex items-center gap-2">
<i data-lucide="calendar" class="w-4 h-4 text-[color:var(--primary)]"></i>
Select Date
</h2>
<!-- Quick Actions -->
<div class="flex flex-col gap-1.5 mb-3">
<button
onclick="loadToday()"
class="w-full px-2 py-1.5 text-xs font-medium rounded-lg transition-all text-left flex items-center gap-1.5"
style="background-color: rgba(249, 157, 51, 0.1); color: var(--secondary); border: 1px solid rgba(249, 157, 51, 0.2);"
>
<i data-lucide="calendar-check" class="w-3 h-3"></i>
Today
</button>
<button
onclick="refreshCurrentLog()"
id="refreshBtn"
class="w-full px-2 py-1.5 text-xs font-medium text-white rounded-lg transition-all flex flex-col items-start gap-0.5"
style="background-color: var(--primary);"
disabled
>
<div class="flex items-center gap-1.5">
<i data-lucide="refresh-cw" class="w-3 h-3"></i>
Resync Online
</div>
<span id="lastRefreshTime" class="text-[0.6rem] opacity-75" style="display: none;"></span>
</button>
<button
onclick="resyncLocal()"
class="w-full px-2 py-1.5 text-xs font-medium rounded-lg transition-all flex items-center gap-1.5"
style="background-color: rgba(70, 82, 117, 0.1); color: var(--muted-foreground); border: 1px solid rgba(70, 82, 117, 0.2);"
>
<i data-lucide="search" class="w-3 h-3"></i>
Resync Local
</button>
</div>
<!-- Calendar Navigation -->
<div class="flex items-center justify-between mb-2">
<button
onclick="changeMonth(-1)"
class="p-1 rounded hover:bg-gray-100"
>
<i data-lucide="chevron-left" class="w-3.5 h-3.5" style="color: var(--primary);"></i>
</button>
<h3 class="text-xs font-semibold" style="color: var(--foreground);" id="calendarTitle">
</h3>
<button
onclick="changeMonth(1)"
class="p-1 rounded hover:bg-gray-100"
>
<i data-lucide="chevron-right" class="w-3.5 h-3.5" style="color: var(--primary);"></i>
</button>
</div>
<!-- Compact Calendar -->
<div class="calendar-grid mb-1">
<div class="text-center text-[0.6rem] font-medium text-[color:var(--muted-foreground)] py-0.5">S</div>
<div class="text-center text-[0.6rem] font-medium text-[color:var(--muted-foreground)] py-0.5">M</div>
<div class="text-center text-[0.6rem] font-medium text-[color:var(--muted-foreground)] py-0.5">T</div>
<div class="text-center text-[0.6rem] font-medium text-[color:var(--muted-foreground)] py-0.5">W</div>
<div class="text-center text-[0.6rem] font-medium text-[color:var(--muted-foreground)] py-0.5">T</div>
<div class="text-center text-[0.6rem] font-medium text-[color:var(--muted-foreground)] py-0.5">F</div>
<div class="text-center text-[0.6rem] font-medium text-[color:var(--muted-foreground)] py-0.5">S</div>
</div>
<div id="calendar" class="calendar-grid"></div>
</div>
</div>
<!-- RIGHT MAIN CONTENT: Filters + Logs (80%) -->
<div class="col-span-12 lg:col-span-9">
<!-- Filters Card - Compact -->
<div class="entry-card p-3 mb-3">
<div class="flex flex-wrap items-center gap-3">
<!-- Session Key Filter -->
<div class="flex items-center gap-1.5">
<label class="text-[0.65rem] font-medium text-[color:var(--muted-foreground)]">File:</label>
<input
type="text"
id="fileFilter"
placeholder="Search..."
class="w-32 px-2 py-1 text-xs border rounded focus:ring-1 focus:ring-[color:var(--primary)]"
style="border-color: var(--border);"
/>
</div>
<!-- Level Filter -->
<div class="flex items-center gap-1.5">
<label class="text-[0.65rem] font-medium text-[color:var(--muted-foreground)]">Level:</label>
<select
id="levelFilter"
class="px-2 py-1 text-xs border rounded focus:ring-1 focus:ring-[color:var(--primary)]"
style="border-color: var(--border);"
>
<option value="">All</option>
<option value="INFO">INFO</option>
<option value="DEBUG">DEBUG</option>
<option value="WARN">WARN</option>
<option value="ERROR">ERROR</option>
<option value="REJECT">REJECT</option>
<option value="UPLOAD">UPLOAD</option>
<option value="FILED">FILED</option>
</select>
</div>
<!-- School ID Filter -->
<div class="flex items-center gap-1.5">
<label class="text-[0.65rem] font-medium text-[color:var(--muted-foreground)]">School:</label>
<select
id="schoolFilter"
class="px-2 py-1 text-xs border rounded focus:ring-1 focus:ring-[color:var(--primary)]"
style="border-color: var(--border);"
>
<option value="">All Schools</option>
</select>
</div>
<!-- Quick Filters -->
<div class="flex gap-1">
<button onclick="showOnlyErrors()" class="px-2 py-1 text-[0.65rem] font-medium rounded transition-all" style="background-color: rgba(240, 78, 105, 0.1); color: var(--destructive);">Errors</button>
<button onclick="showOnlySuccess()" class="px-2 py-1 text-[0.65rem] font-medium rounded transition-all" style="background-color: rgba(141, 190, 80, 0.1); color: var(--success);">Success</button>
<button onclick="clearFilters()" class="px-2 py-1 text-[0.65rem] font-medium rounded transition-all" style="background-color: rgba(70, 82, 117, 0.08); color: var(--muted-foreground);">Clear</button>
</div>
</div>
</div>
<!-- File Processing Summary (separate card) -->
<div class="entry-card mb-3" id="timingsContainer" style="display: none;">
<div class="p-3">
<div class="flex items-center justify-between mb-2">
<h2 class="text-xs font-semibold text-[color:var(--foreground)] flex items-center gap-1.5">
<i data-lucide="clock" class="w-3.5 h-3.5 text-[color:var(--primary)]"></i>
File Summary
</h2>
<!-- Compact Stats -->
<div class="flex items-center gap-2 text-xs" id="statsContainer">
<span class="file-type-badge file-type-pdf" title="PDF files">
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></svg>
<span id="statPdfCount">0</span>
</span>
<span class="file-type-badge file-type-edat3" title="E-Prime files">
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5V19A9 3 0 0 0 21 19V5"/><path d="M3 12A9 3 0 0 0 21 12"/></svg>
<span id="statEdat3Count">0</span>
</span>
<span class="text-[color:var(--muted-foreground)]">Avg:</span>
<span class="font-semibold" style="color: var(--primary);" id="statAvgTime">0s</span>
</div>
</div>
<!-- File Type Filter -->
<div class="mb-2 flex items-center gap-1.5">
<button onclick="setFileTypeFilter('all')" id="filterAll" class="file-type-filter active" style="background-color: rgba(70, 82, 117, 0.1); color: var(--foreground);">All</button>
<button onclick="setFileTypeFilter('pdf')" id="filterPdf" class="file-type-filter" style="background-color: rgba(239, 68, 68, 0.08); color: #dc2626;">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></svg>PDF
</button>
<button onclick="setFileTypeFilter('edat3')" id="filterEdat3" class="file-type-filter" style="background-color: rgba(139, 92, 246, 0.08); color: #7c3aed;">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5V19A9 3 0 0 0 21 19V5"/><path d="M3 12A9 3 0 0 0 21 12"/></svg>E-Prime
</button>
</div>
<div id="timingsTable"></div>
</div>
</div>
<!-- Log Table (separate card) -->
<div class="entry-card">
<div class="p-3">
<!-- Header with Stats -->
<div class="flex items-center justify-between mb-2">
<h2 class="text-xs font-semibold text-[color:var(--foreground)] flex items-center gap-1.5">
<i data-lucide="list" class="w-3.5 h-3.5 text-[color:var(--primary)]"></i>
Log Entries
</h2>
<div class="flex items-center gap-2 text-xs">
<span class="text-[color:var(--muted-foreground)]">Rows:</span>
<span class="font-semibold text-[color:var(--foreground)]" id="statTotal">0</span>
<span class="text-[color:var(--muted-foreground)]">Errors:</span>
<span class="font-semibold" style="color: var(--destructive);" id="statRejects">0</span>
</div>
</div>
<div class="overflow-x-auto">
<table class="min-w-full divide-y" style="border-color: var(--border);">
<thead>
<tr>
<th class="px-2 py-1 text-left text-[0.65rem] font-medium text-[color:var(--muted-foreground)] uppercase">Time</th>
<th class="px-2 py-1 text-left text-[0.65rem] font-medium text-[color:var(--muted-foreground)] uppercase">Level</th>
<th class="px-2 py-1 text-left text-[0.65rem] font-medium text-[color:var(--muted-foreground)] uppercase">File</th>
<th class="px-2 py-1 text-left text-[0.65rem] font-medium text-[color:var(--muted-foreground)] uppercase">Message</th>
</tr>
</thead>
<tbody id="logTableBody" class="divide-y" style="border-color: var(--border);">
<tr>
<td colspan="4" class="px-2 py-4 text-center text-[color:var(--muted-foreground)] text-xs">
Select a log date to view entries
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- End of right column -->
</div>
<!-- End of grid layout -->
</main>
</div>
<script>
let allLogs = [];
let filteredLogs = [];
let currentDate = null;
let availableLogDates = new Set();
let currentMonth = new Date();
let logDirectory = './logs';
let scanDays = 90;
let logsDirectoryHandle = null; // File System Access API handle
let defaultLogSource = 'local';
let activeLogSource = 'local';
let logSource = 'local'; // kept for backwards compatibility / logging
let supabaseConfig = null;
let supabaseDayCache = new Map();
let currentFileTypeFilter = 'all'; // 'all', 'pdf', 'edat3'
let fileToSchoolMap = new Map(); // Maps filename to school ID (e.g., "11751_20251209_09_19.pdf" -> "S075")
// Helper: Extract school ID from log messages for a file
// Looks for patterns like "→ S075/" in FILED messages or "school-id: 75 → S075" in INFO messages
function extractSchoolIdFromLogs(logs, filename) {
for (const log of logs) {
if (log.file !== filename) continue;
// Pattern 1a: PDF FILED messages have "filename → S###/"
if (log.level === 'FILED') {
const pdfMatch = log.message.match(/→\s*(S\d{3})\/?/);
if (pdfMatch) return pdfMatch[1];
// Pattern 1b: E-Prime FILED messages have "Filed EDAT3 to S###/"
const eprimeMatch = log.message.match(/Filed EDAT3 to (S\d{3})\/?/);
if (eprimeMatch) return eprimeMatch[1];
}
// Pattern 2: INFO messages have "Formatted school-id: ## → S###"
if (log.level === 'INFO' && log.message.includes('school-id')) {
const match = log.message.match(/→\s*(S\d{3})/);
if (match) return match[1];
}
// Pattern 3: INFO messages have "Added District: ... (from S###)"
if (log.level === 'INFO' && log.message.includes('Added District')) {
const match = log.message.match(/\(from\s+(S\d{3})\)/);
if (match) return match[1];
}
}
return null;
}
// Build file-to-school mapping from all logs
function buildFileToSchoolMap() {
fileToSchoolMap.clear();
const uniqueFiles = new Set(allLogs.filter(log => log.file).map(log => log.file));
uniqueFiles.forEach(filename => {
const schoolId = extractSchoolIdFromLogs(allLogs, filename);
if (schoolId) {
fileToSchoolMap.set(filename, schoolId);
}
});
}
// Update school filter dropdown with available schools
function updateSchoolFilterOptions() {
const schoolFilter = document.getElementById('schoolFilter');
const currentValue = schoolFilter.value;
// Get unique schools from the map
const schools = new Set(fileToSchoolMap.values());
const sortedSchools = Array.from(schools).sort();
// Rebuild options
schoolFilter.innerHTML = '<option value="">All Schools</option>';
sortedSchools.forEach(schoolId => {
const option = document.createElement('option');
option.value = schoolId;
option.textContent = schoolId;
schoolFilter.appendChild(option);
});
// Restore selection if still valid
if (currentValue && sortedSchools.includes(currentValue)) {
schoolFilter.value = currentValue;
}
}
// Helper: Detect file type from filename
function getFileType(filename) {
if (!filename) return 'unknown';
const lower = filename.toLowerCase();
if (lower.endsWith('.pdf')) return 'pdf';
if (lower.endsWith('.edat3')) return 'edat3';
// Also detect edat3 by pattern: TaskName-SchoolId-CoreId-ComputerNo
if (/^[a-z0-9]+-\d+-\d+-\d+$/i.test(lower.replace('.edat3', ''))) return 'edat3';
return 'unknown';
}
// Helper: Get file type badge HTML - use inline SVG for reliable rendering
function getFileTypeBadge(filename) {
const type = getFileType(filename);
if (type === 'pdf') {
// Lucide file-text icon as inline SVG
return `<span class="file-type-badge file-type-pdf" title="PDF Assessment">
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></svg>
</span>`;
} else if (type === 'edat3') {
// Lucide database icon as inline SVG
return `<span class="file-type-badge file-type-edat3" title="E-Prime Data">
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5V19A9 3 0 0 0 21 19V5"/><path d="M3 12A9 3 0 0 0 21 12"/></svg>
</span>`;
}
return '';
}
// File type filter
function setFileTypeFilter(filter) {
currentFileTypeFilter = filter;
// Clear file search input when clicking "All" to reset the full list
if (filter === 'all') {
document.getElementById('fileFilter').value = '';
}
// Update button states
document.getElementById('filterAll').classList.toggle('active', filter === 'all');
document.getElementById('filterPdf').classList.toggle('active', filter === 'pdf');
document.getElementById('filterEdat3').classList.toggle('active', filter === 'edat3');
applyFilters();
}
// Request access to logs directory using File System Access API
async function requestLogsDirectoryAccess() {
if (!('showDirectoryPicker' in window)) {
console.warn('File System Access API not supported');
return false;
}
// Show instructions before opening picker
const proceed = confirm(
'📁 Select Logs Folder\n\n' +
'Please navigate to and select the "logs" folder:\n\n' +
'Path: OneDrive/.../4Set-Server/logs/\n\n' +
'This folder contains files like:\n' +
'• 20251107_processing_agent.csv\n' +
'• 20251106_processing_agent.csv\n\n' +
'Click OK to open folder picker.'
);
if (!proceed) return false;
try {
logsDirectoryHandle = await window.showDirectoryPicker({
mode: 'read',
startIn: 'documents'
});
// Verify it's the correct folder by checking for expected files
if (logsDirectoryHandle.name !== 'logs') {
const confirmWrong = confirm(
`⚠️ Warning: You selected "${logsDirectoryHandle.name}"\n\n` +
'Expected folder name: "logs"\n\n' +
'Continue anyway?'
);
if (!confirmWrong) {
logsDirectoryHandle = null;
return false;
}
}
return true;
} catch (error) {
if (error.name !== 'AbortError') {
console.error('Failed to get directory access:', error);
}
return false;
}
}
// Switch to local mode and rescan local logs
async function resyncLocal() {
activeLogSource = 'local';
await scanLogFiles('local');
if (currentDate) {
await loadLogFile(currentDate);
}
}
// Read file from File System Access API
async function readFileFromHandle(filename) {
if (!logsDirectoryHandle) return null;
try {
const fileHandle = await logsDirectoryHandle.getFileHandle(filename);
const file = await fileHandle.getFile();
return await file.text();
} catch (error) {
return null;
}
}
// Check if file exists in directory handle
async function fileExistsInHandle(filename) {
if (!logsDirectoryHandle) return false;
try {
await logsDirectoryHandle.getFileHandle(filename);
return true;
} catch {
return false;
}
}
// Load configuration
async function loadConfig() {
try {
const response = await fetch('config/checking_system_config.json');
const config = await response.json();
const agentResponse = await fetch('config/agent.json');
const agentConfig = await agentResponse.json();
logDirectory = agentConfig.logDirectory || './logs';
if (config.logViewer && config.logViewer.scanDays) {
scanDays = config.logViewer.scanDays;
}
try {
const logCheckResponse = await fetch('config/log_check_config.json');
if (logCheckResponse.ok) {
const logCheckConfig = await logCheckResponse.json();
if (logCheckConfig.logSource) {
defaultLogSource = logCheckConfig.logSource;
activeLogSource = defaultLogSource;
logSource = defaultLogSource;
}
if (logCheckConfig.supabase) {
supabaseConfig = logCheckConfig.supabase;
if (logCheckConfig.supabase.scanDays) {
scanDays = logCheckConfig.supabase.scanDays;
}
}
}
} catch (e) {
}
return logDirectory;
} catch (error) {
console.error('Failed to load config:', error);
logDirectory = './logs';
scanDays = 90;
logSource = 'local';
supabaseConfig = null;
return './logs';
}
}
// Scan log files directory or Supabase - Smart scan
async function scanLogFiles(source) {
const refreshBtn = document.getElementById('refreshBtn');
const lastRefreshTime = document.getElementById('lastRefreshTime');
try {
if (refreshBtn && lastRefreshTime) {
refreshBtn.disabled = true;
lastRefreshTime.style.display = 'block';
lastRefreshTime.textContent = 'Syncing...';
}
await loadConfig();
availableLogDates.clear();
const effectiveSource = source || activeLogSource;
if (effectiveSource === 'supabase' && supabaseConfig && supabaseConfig.url && supabaseConfig.uploadLogTable) {
if (lastRefreshTime) {
lastRefreshTime.textContent = 'Syncing online logs...';
}
await scanSupabaseDates();
} else {
if (lastRefreshTime) {
lastRefreshTime.textContent = 'Syncing local logs...';
}
const foundFiles = await fetchLogListFromServer();
if (!foundFiles || foundFiles.length === 0) {
await scanRecentDates();
}
}
renderCalendar();
activeLogSource = effectiveSource;
} finally {
if (refreshBtn) {
refreshBtn.disabled = !currentDate;
}
if (lastRefreshTime && !currentDate) {
lastRefreshTime.style.display = 'none';
}
}
}
async function scanSupabaseDates() {
try {
const today = new Date();
const start = new Date();
start.setDate(today.getDate() - (scanDays - 1));
const baseUrl = supabaseConfig.url.replace(/\/+$/, '');
const table = supabaseConfig.uploadLogTable;
const dateCounts = {};
let totalRows = 0;
let probedDays = 0;
const probeDate = async (date) => {
const from = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
const to = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1, 0, 0, 0);
const fromIso = from.toISOString();
const toIso = to.toISOString();
const queryUrl = `${baseUrl}/rest/v1/${encodeURIComponent(table)}?select=timestamp×tamp=gte.${encodeURIComponent(fromIso)}×tamp=lt.${encodeURIComponent(toIso)}&limit=1`;
const response = await fetch(queryUrl, {
headers: {
apikey: supabaseConfig.anonKey,
Authorization: `Bearer ${supabaseConfig.anonKey}`
}
});
if (!response.ok) {
console.error('Failed to load Supabase dates for', fromIso, '→', toIso, await response.text());
return;
}
const rows = await response.json();
probedDays += 1;
if (!rows || rows.length === 0) {
return;
}
totalRows += rows.length;
const ts = rows[0].timestamp;
if (!ts) {
return;
}
let dateStr = null;
if (typeof ts === 'string') {
// Prefer parsing the date portion directly from the Supabase timestamptz string
// to avoid browser timezone shifts changing the calendar day.
const parts = ts.split('T')[0] || ts.split(' ')[0];
if (parts && /^\d{4}-\d{2}-\d{2}$/.test(parts)) {
const [year, month, day] = parts.split('-');
dateStr = `${year}${month}${day}`;
}
}
if (!dateStr) {
// Fallback to Date parsing if the raw string format is unexpected
const d = new Date(ts);
if (!isNaN(d.getTime())) {
dateStr = formatDateToYYYYMMDD(d);
}
}
if (dateStr) {
availableLogDates.add(dateStr);
dateCounts[dateStr] = (dateCounts[dateStr] || 0) + rows.length;
}
};
for (let d = new Date(start); d <= today; d.setDate(d.getDate() + 1)) {
await probeDate(d);
}
} catch (error) {
console.error('Error scanning Supabase dates:', error);
}
}
// Fetch list of available log files from server API
async function fetchLogListFromServer() {
try {
const response = await fetch('/api/logs/list', {
method: 'GET',
cache: 'no-cache'
});
if (response.ok) {
const dateArray = await response.json();
// Add all dates from server response
dateArray.forEach(dateStr => {
availableLogDates.add(dateStr);
});
return dateArray;
}
} catch (error) {
}
return null;
}
// Scan recent dates (fallback method - may cause 404s in console)
async function scanRecentDates() {
console.warn('[LOG VIEWER] Using fallback scanning method - may see 404 errors in console');
const today = new Date();
const promises = [];
// Only scan last 90 days
for (let i = 0; i < scanDays; i++) {
const date = new Date(today);
date.setDate(date.getDate() - i);
const dateStr = formatDateToYYYYMMDD(date);
promises.push(checkLogExistsQuietly(dateStr));
}
await Promise.all(promises);
return Array.from(availableLogDates);
}
// Quiet version that suppresses 404 errors in console (still may log fetch errors)
async function checkLogExistsQuietly(dateStr) {
const filename = `${dateStr}_processing_agent.csv`;
const filepath = `${logDirectory}/${filename}`;
try {
const response = await fetch(filepath, { cache: 'no-cache' });
if (response.ok) {
const text = await response.text();
const lines = text.trim().split('\n');
// Filter out logs that only contain "Rolled log file" message
if (lines.length > 1) {
let hasRealLogs = false;
for (let i = 1; i < lines.length; i++) {
const line = lines[i].trim();
if (line && !line.includes('Rolled log file to')) {
hasRealLogs = true;
break;
}
}
if (hasRealLogs) {
availableLogDates.add(dateStr);
}
}
}
} catch (error) {
// Silently ignore all errors
// Still try File System Access API if available
if (logsDirectoryHandle) {
try {
const text = await readFileFromHandle(filename);
if (text) {
const lines = text.trim().split('\n');
if (lines.length > 1) {
let hasRealLogs = false;
for (let i = 1; i < lines.length; i++) {
const line = lines[i].trim();
if (line && !line.includes('Rolled log file to')) {
hasRealLogs = true;
break;
}
}
if (hasRealLogs) {
availableLogDates.add(dateStr);
}
}
}
} catch (fsError) {
// Silently ignore
}
}
}
}
// Check if log file exists and has actual data (not just headers or "Rolled" messages)
async function checkLogExists(dateStr) {
const filename = `${dateStr}_processing_agent.csv`;
const filepath = `${logDirectory}/${filename}`;
// Try fetch first (works with proxy server)
try {
const response = await fetch(filepath);
if (response.ok) {
const text = await response.text();
const lines = text.trim().split('\n');
// Only consider it a valid log if it has more than just the header row
// AND has real log entries (not just "Rolled log file" message)
if (lines.length > 1) {
let hasRealLogs = false;
for (let i = 1; i < lines.length; i++) {
const line = lines[i].trim();
// Ignore empty lines and "Rolled log file" messages
if (line && !line.includes('Rolled log file to')) {
hasRealLogs = true;
break;
}
}
if (hasRealLogs) {
availableLogDates.add(dateStr);
}
}
return; // Success via fetch, no need to try File System Access API
}
} catch (error) {
// Fetch failed, try File System Access API if available
}
// Fallback to File System Access API (for GitHub Pages)
if (logsDirectoryHandle) {
try {
const text = await readFileFromHandle(filename);
if (text) {
const lines = text.trim().split('\n');
if (lines.length > 1) {
let hasRealLogs = false;
for (let i = 1; i < lines.length; i++) {
const line = lines[i].trim();
if (line && !line.includes('Rolled log file to')) {
hasRealLogs = true;
break;
}
}
if (hasRealLogs) {
availableLogDates.add(dateStr);
}
}
}
} catch (error) {
// File doesn't exist or can't be read, ignore
}
}
}
// Format date to YYYYMMDD
function formatDateToYYYYMMDD(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}${month}${day}`;
}
// Parse YYYYMMDD to Date
function parseYYYYMMDD(dateStr) {
const year = parseInt(dateStr.substring(0, 4));
const month = parseInt(dateStr.substring(4, 6)) - 1;
const day = parseInt(dateStr.substring(6, 8));
return new Date(year, month, day);