-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics.html
More file actions
3076 lines (2619 loc) · 117 KB
/
analytics.html
File metadata and controls
3076 lines (2619 loc) · 117 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" />
<title>Analytics — Student Progress Analyzer</title>
<script>
window.MathJax = {
tex: {
inlineMath: [['\\(', '\\)']],
displayMath: [['$$', '$$']],
processEscapes: true
},
svg: { fontCache: 'global' }
};
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" async></script>
<!-- PyScript core -->
<link rel="stylesheet" href="https://pyscript.net/releases/2024.1.1/core.css" />
<script type="module" src="https://pyscript.net/releases/2024.1.1/core.js"></script>
<style>
/* =========================================
GLOBAL RESET
========================================= */
/* =========================================
STARTUP MODAL
========================================= */
.startup-modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.6);
z-index: 10000;
display: flex;
justify-content: center;
align-items: center;
font-family: sans-serif;
}
.startup-modal {
background: white;
padding: 30px;
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
max-width: 600px;
width: 90%;
max-height: 80vh;
overflow-y: auto;
}
.startup-modal h2 {
margin: 0 0 20px 0;
color: #0f172a;
font-size: 24px;
}
.startup-modal p {
margin: 0 0 20px 0;
color: #64748b;
font-size: 14px;
}
.saved-sessions-list {
margin: 20px 0;
max-height: 400px;
overflow-y: auto;
}
.session-item {
padding: 16px;
border: 2px solid #e2e8f0;
border-radius: 8px;
margin-bottom: 12px;
cursor: pointer;
transition: all 0.2s ease;
background: #f8fafc;
}
.session-item:hover {
border-color: #3b82f6;
background: #eff6ff;
transform: translateX(4px);
}
.session-item.selected {
border-color: #3b82f6;
background: #dbeafe;
}
.session-name {
font-weight: 600;
font-size: 16px;
color: #0f172a;
margin-bottom: 4px;
}
.session-info {
font-size: 13px;
color: #64748b;
}
.modal-actions {
display: flex;
gap: 12px;
margin-top: 24px;
}
.modal-btn {
flex: 1;
padding: 12px 24px;
border-radius: 8px;
border: none;
cursor: pointer;
font-size: 15px;
font-weight: 600;
transition: all 0.2s ease;
}
.modal-btn-primary {
background: #3b82f6;
color: white;
}
.modal-btn-primary:hover {
background: #2563eb;
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}
.modal-btn-primary:disabled {
background: #cbd5e1;
cursor: not-allowed;
transform: none;
}
.modal-btn-secondary {
background: #f1f5f9;
color: #475569;
}
.modal-btn-secondary:hover {
background: #e2e8f0;
}
.empty-state {
text-align: center;
padding: 40px 20px;
color: #94a3b8;
}
.empty-state-icon {
font-size: 48px;
margin-bottom: 16px;
}
.empty-state-text {
font-size: 16px;
margin-bottom: 8px;
color: #64748b;
}
.empty-state-subtext {
font-size: 13px;
color: #94a3b8;
}
body {
font-family: "Inter", "Segoe UI", Arial, sans-serif;
background: #f3f4f6;
color: #111827;
margin: 0;
padding: 0;
}
#analyticsResults {
padding: 16px;
max-width: 1200px;
margin: auto;
}
/* =========================================
PANEL STYLING
========================================= */
.panel {
background: #ffffff;
border-radius: 10px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
padding: 16px 20px;
margin-bottom: 18px;
transition: box-shadow 0.2s ease;
}
.panel:hover {
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
}
/* =========================================
STATISTIC CARDS
========================================= */
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
gap: 10px;
margin-top: 8px;
}
.stats-card {
text-align: center;
border-radius: 10px;
padding: 10px 6px;
}
.stats-number {
font-size: 1.3em;
font-weight: bold;
color: #111827;
}
.stats-label {
font-size: 0.8em;
color: #6b7280;
}
/* =========================================
SCORE BADGES
========================================= */
.score-badge {
display: inline-block;
padding: 4px 8px;
border-radius: 8px;
font-weight: 600;
font-size: 12px;
color: #fff;
}
.score-high { background-color: #16a34a; } /* green */
.score-medium { background-color: #facc15; color:#111827; } /* yellow */
.score-low { background-color: #dc2626; } /* red */
/* =========================================
TABLE STYLING
========================================= */
table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
th, td {
border-bottom: 1px solid #e5e7eb;
padding: 8px;
vertical-align: middle;
}
th {
background: #f3f4f6;
text-align: left;
font-weight: 600;
}
tr.detail-row td {
background: #f9fafb;
}
/* zebra stripes for readability */
tbody tr:nth-child(even):not(.detail-row) {
background: #fcfcfc;
}
/* =========================================
BUTTONS (Details Toggle)
========================================= */
button.detail-toggle {
background: #e0f2fe;
border: 1px solid #bae6fd;
border-radius: 6px;
color: #0369a1;
cursor: pointer;
font-size: 12px;
padding: 4px 8px;
transition: background 0.2s ease, color 0.2s ease;
}
button.detail-toggle:hover {
background: #0369a1;
color: #ffffff;
}
/* =========================================
PROBLEM CARD STYLING
========================================= */
.problem-card {
background: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 8px;
margin-bottom: 12px;
overflow: hidden;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
}
.problem-header {
background: #f9fafb;
cursor: pointer;
font-weight: 600;
padding: 10px 12px;
border-bottom: 1px solid #e5e7eb;
display: flex;
justify-content: space-between;
align-items: center;
transition: background 0.2s ease;
}
.problem-header:hover {
background: #f3f4f6;
}
.problem-body {
padding: 10px 12px;
background: #fcfcfc;
}
.badge {
background: #e0f2fe;
color: #0369a1;
border-radius: 8px;
padding: 2px 6px;
font-size: 11px;
font-weight: 500;
}
/* =========================================
ATTEMPTS DISPLAY (Horizontal Layout)
========================================= */
.problem-body .attempts-container {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: flex-start;
justify-content: flex-start;
}
.problem-body .attempt-box {
border: 1px solid #e5e7eb;
background: #ffffff;
border-radius: 6px;
padding: 8px 10px;
min-width: 120px;
text-align: center;
transition: box-shadow 0.2s ease;
}
.problem-body .attempt-box:hover {
box-shadow: 0 0 6px rgba(0, 0, 0, 0.08);
}
/* flag labels */
.attempt-flag {
font-size: 12px;
margin-bottom: 4px;
font-weight: 500;
}
.flag-correct { color: #15803d; } /* ✅ Correct */
.flag-finalized { color: #166534; } /* 🔒 Finalized */
.flag-false { color: #991b1b; } /* ❌ False */
.flag-false-finalized { color: #b45309; } /* ⚠️ False Finalized */
/* =========================================
MATHJAX OUTPUT AREA
========================================= */
.mathjax-latex {
display: block;
font-size: 14px;
margin: 4px 0;
color: #111827;
line-height: 1.4;
}
.mathjax-latex mjx-container {
overflow-x: auto;
overflow-y: hidden;
}
/* =========================================
RESPONSIVE TABLE
========================================= */
@media (max-width: 768px) {
th, td {
padding: 6px;
font-size: 12px;
}
.problem-body .attempt-box {
min-width: 90px;
padding: 6px;
}
.stats-grid {
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
}
</style>
</head>
<body>
<div id="loadingOverlay">
<div class="spinner"></div>
<div class="loading-text">Initializing Analytics...</div>
<div id="loadingStatus"><div>⏳ Starting up...</div></div>
</div>
<header>
<h1>📊 Analytics Dashboard (IndexedDB)</h1>
</header>
<div class="panel">
<label>Student Roster Setup</label>
<div class="small" style="margin-bottom:8px;">
Paste WhatsApp messages containing student info. Format: <code>+62...</code> followed by name and registration number.
</div>
<textarea id="pasteRosterData" style="width:100%; min-height:120px; padding:8px; border-radius:8px; border:1px solid #e6eef8; font-family:monospace; font-size:12px;" placeholder="Example: +628123456789: John Doe 12345 [4/10 19.16] +62 858-9375-4880: Abima Ardiansah 41524110006"></textarea>
<div style="margin-top:8px; display:flex; gap:8px; flex-wrap:wrap;">
<button id="parseRosterReplaceBtn" class="btn danger">Parse & Replace</button>
<button id="parseRosterMergeBtn" class="btn success">Parse & Merge</button>
<button id="clearRosterBtn" class="btn ghost">Clear Roster</button>
<button id="viewRosterBtn" class="btn ghost">View Roster</button>
</div>
<div id="rosterStatus" class="small" style="margin-top:8px; color:#059669;"></div>
</div>
<div class="panel">
<label>Paste Student Progress Data</label>
<div class="small" style="margin-bottom:8px;">
Paste one or multiple base64-encoded progress exports. <strong>✈️ Telegram multi-part messages supported!</strong>
</div>
<textarea id="pasteProgressData" style="width:100%; min-height:200px; padding:8px; border-radius:8px; border:1px solid #e6eef8; font-family:monospace; font-size:12px;"></textarea>
<div style="margin-top:8px; display:flex; gap:8px; flex-wrap:wrap;">
<button id="analyzeBtn" class="btn">Analyze & Add Submissions</button>
<button id="clearAnalyticsBtn" class="btn ghost">Clear All</button>
<button id="exportAnalyticsBtn" class="btn" style="background:#8b5cf6;">Export Analytics</button>
</div>
</div>
<div id="analyticsResults"></div>
<py-config>
packages = ["brotli"]
</py-config>
<script type="py">
from pyscript import document, window
from pyodide.ffi import create_proxy
import re, json, base64, brotli, html, hashlib
from collections import defaultdict
# ================================================================
# INDEXEDDB MANAGER
# ================================================================
from js import Function, window
class IndexedDBManager:
"""Hybrid IndexedDB manager with automatic localStorage fallback and progress pop-up — fully Pyodide-safe"""
def __init__(self):
self.db_name = "AnalyticsDB"
self.db_version = 1
self.initialized = False
self.fallback_mode = False # Enabled automatically if IndexedDB fails
# --- Progress Pop-up Elements ---
self.progress_popup = None
self.progress_status = None
self.progress_container_id = "pyodide-progress-container"
# ============================================================
# PROGRESS POP-UP HELPERS
# ============================================================
def _create_progress_elements(self):
"""Create the progress pop-up elements and add them to the DOM."""
from js import document
container = document.createElement("div")
container.id = self.progress_container_id
popup = document.createElement("div")
popup.id = "progress-popup"
popup.style.display = "none"
content = document.createElement("div")
content.className = "progress-content"
spinner = document.createElement("div")
spinner.className = "spinner"
status = document.createElement("p")
status.id = "progress-status"
status.textContent = "Processing..."
content.appendChild(spinner)
content.appendChild(status)
popup.appendChild(content)
container.appendChild(popup)
style = document.createElement("style")
style.textContent = """
#pyodide-progress-container #progress-popup {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1000;
display: flex;
justify-content: center;
align-items: center;
font-family: sans-serif;
}
#pyodide-progress-container .progress-content {
background-color: white;
padding: 20px 30px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
display: flex;
align-items: center;
gap: 15px;
}
#pyodide-progress-container .spinner {
width: 24px;
height: 24px;
border: 3px solid #f3f3f3;
border-top: 3px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
#pyodide-progress-container #progress-status {
margin: 0;
font-size: 16px;
color: #333;
}
"""
container.appendChild(style)
document.body.appendChild(container)
self.progress_popup = popup
self.progress_status = status
def _find_progress_elements(self):
"""Find or create the DOM elements for the progress pop-up."""
from js import window
if not self.progress_popup:
self.progress_popup = window.document.querySelector("#progress-popup")
self.progress_status = window.document.querySelector("#progress-status")
if not self.progress_popup or not self.progress_status:
window.console.log("Creating progress pop-up elements...")
self._create_progress_elements()
def _show_progress(self, message):
"""Display the progress pop-up with a custom message."""
self._find_progress_elements()
if self.progress_popup and self.progress_status:
self.progress_status.textContent = message
self.progress_popup.style.display = "flex"
def _hide_progress(self):
"""Hide the progress pop-up."""
if self.progress_popup:
self.progress_popup.style.display = "none"
# ============================================================
# INITIALIZE
# ============================================================
async def initialize(self):
from js import window, Function
if self.initialized:
return True
self._show_progress("Initializing database...")
try:
if not hasattr(window, "indexedDB"):
window.console.warn("⚠️ IndexedDB not supported, switching to localStorage")
self.fallback_mode = True
self.initialized = True
return True
create_bridge = Function(
"""
return (function() {
const delayClose = db => setTimeout(() => db.close(), 0);
const bridge = {
openDB: function(name, version) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(name, version);
request.onupgradeneeded = e => {
const db = e.target.result;
if (!db.objectStoreNames.contains("analytics")) {
db.createObjectStore("analytics", { keyPath: "id" });
}
if (!db.objectStoreNames.contains("hashes")) {
db.createObjectStore("hashes", { keyPath: "id" });
}
};
request.onsuccess = e => resolve(e.target.result);
request.onerror = e => reject(e.target.error);
});
},
async save(dbName, version, store, key, jsonString) {
const db = await bridge.openDB(dbName, version);
return new Promise((resolve, reject) => {
try {
const tx = db.transaction(store, "readwrite");
const st = tx.objectStore(store);
const keyStr = String(key);
const dataStr = String(jsonString);
const record = { id: keyStr, data: dataStr };
const req = st.put(record); // ✅ no key argument (keyPath used)
req.onsuccess = () => { delayClose(db); resolve(true); };
req.onerror = e => { delayClose(db); reject(e.target.error); };
} catch (err) {
delayClose(db);
reject(err);
}
});
},
async load(dbName, version, store, key) {
const db = await bridge.openDB(dbName, version);
return new Promise((resolve, reject) => {
try {
const tx = db.transaction(store, "readonly");
const st = tx.objectStore(store);
const req = st.get(String(key));
req.onsuccess = () => {
const val = req.result ? String(req.result.data) : null;
delayClose(db);
resolve(val);
};
req.onerror = e => { delayClose(db); reject(e.target.error); };
} catch (err) {
delayClose(db);
reject(err);
}
});
},
async delete(dbName, version, store, key) {
const db = await bridge.openDB(dbName, version);
return new Promise((resolve, reject) => {
try {
const tx = db.transaction(store, "readwrite");
const st = tx.objectStore(store);
const req = st.delete(String(key));
req.onsuccess = () => { delayClose(db); resolve(true); };
req.onerror = e => { delayClose(db); reject(e.target.error); };
} catch (err) {
delayClose(db);
reject(err);
}
});
}
};
return bridge;
})();
"""
)
window.PyIndexedDBBridge = create_bridge()
self.initialized = True
window.console.log("✅ IndexedDB Bridge initialized successfully")
except Exception as e:
window.console.warn(f"⚠️ IndexedDB initialization failed ({e}), using localStorage fallback")
self.fallback_mode = True
self.initialized = True
finally:
self._hide_progress()
return True
# ============================================================
# SAVE
# ============================================================
async def save_data(self, store_name, key, data):
from js import window, JSON
from pyodide.ffi import to_js
import json
if not self.initialized:
await self.initialize()
self._show_progress("Saving data...")
try:
if not isinstance(data, (dict, list, str, int, float, bool, type(None))):
data = str(data)
json_text = json.dumps(data)
if self.fallback_mode:
window.localStorage.setItem(f"{store_name}_{key}", json_text)
window.console.log("💾 Saved to localStorage (fallback mode)")
self._hide_progress()
return True
js_db_name = to_js(self.db_name)
js_version = to_js(self.db_version)
js_store = to_js(store_name)
js_key = to_js(key)
js_json = to_js(json_text)
result = await window.PyIndexedDBBridge.save(js_db_name, js_version, js_store, js_key, js_json)
window.console.log("✅ Saved to IndexedDB successfully")
return result
except Exception as e:
window.console.error(f"❌ Error saving data: {e}")
try:
window.localStorage.setItem(f"{store_name}_{key}", json.dumps(data))
window.console.warn("⚠️ Saved to localStorage (fallback after error)")
return True
except Exception as e2:
window.console.error(f"❌ Fallback save failed: {e2}")
return False
finally:
self._hide_progress()
# ============================================================
# LOAD
# ============================================================
async def load_data(self, store_name, key):
from js import window
from pyodide.ffi import to_js
import json
if not self.initialized:
await self.initialize()
self._show_progress("Loading data...")
try:
if self.fallback_mode:
raw = window.localStorage.getItem(f"{store_name}_{key}")
return json.loads(raw) if raw else None
js_db_name = to_js(self.db_name)
js_version = to_js(self.db_version)
js_store = to_js(store_name)
js_key = to_js(key)
result = await window.PyIndexedDBBridge.load(js_db_name, js_version, js_store, js_key)
if result is None:
return None
result = result.to_py() if hasattr(result, "to_py") else str(result)
return json.loads(result)
except Exception as e:
window.console.error(f"❌ Error loading data: {e}")
try:
raw = window.localStorage.getItem(f"{store_name}_{key}")
return json.loads(raw) if raw else None
except Exception as e2:
window.console.error(f"❌ Fallback load failed: {e2}")
return None
finally:
self._hide_progress()
# ============================================================
# DELETE
# ============================================================
async def delete_data(self, store_name, key):
from js import window
from pyodide.ffi import to_js
if not self.initialized:
await self.initialize()
self._show_progress("Deleting data...")
try:
if self.fallback_mode:
window.localStorage.removeItem(f"{store_name}_{key}")
return True
js_db_name = to_js(self.db_name)
js_version = to_js(self.db_version)
js_store = to_js(store_name)
js_key = to_js(key)
result = await window.PyIndexedDBBridge.delete(js_db_name, js_version, js_store, js_key)
return result
except Exception as e:
window.console.error(f"❌ Error deleting data: {e}")
try:
window.localStorage.removeItem(f"{store_name}_{key}")
window.console.warn("⚠️ Deleted from localStorage (fallback after error)")
return True
except:
return False
finally:
self._hide_progress()
class RosterManager:
"""Manages student roster operations"""
def __init__(self):
self.app = None
self.student_roster = {}
def initialize(self):
"""Initialize roster management"""
self.bind_events()
def bind_events(self):
"""Bind roster-related events"""
bindings = [
("#parseRosterReplaceBtn", self.parse_and_replace),
("#parseRosterMergeBtn", self.parse_and_merge),
("#clearRosterBtn", self.clear_roster),
("#viewRosterBtn", self.view_roster),
]
for selector, handler in bindings:
element = document.querySelector(selector)
if element:
element.addEventListener("click", create_proxy(handler))
else:
window.console.warn(f"⚠️ Missing element: {selector}")
def normalize_phone(self, p):
"""Normalize Indonesian phone numbers"""
if not p:
return ""
p = re.sub(r"[^\d+]", "", p)
if p.startswith("0"):
p = "+62" + p[1:]
elif p.startswith("62") and not p.startswith("+"):
p = "+" + p
elif not p.startswith("+") and len(p) > 8:
p = "+" + p
return p
def parse_entry(self, entry):
"""Parse a single roster entry"""
entry = entry.replace("\n", " ")
m = re.search(r"(\+?\d[\d\s\-]+)\s*:\s*([A-Za-z\s.'()\-]+)\s*(\d{8,15})", entry)
return m.groups() if m else None
def combine_multiline_entries(self, text):
"""Combine multi-line roster entries"""
lines = text.splitlines()
combined, buf = [], ""
for line in lines:
line = line.strip()
if not line:
continue
if re.match(r"^\[\d{1,2}", line):
if buf:
combined.append(buf.strip())
buf = line
else:
buf += " " + line
if buf:
combined.append(buf.strip())
return combined
def parse_and_replace(self, e=None):
"""Parse and replace roster"""
text = document.querySelector("#pasteRosterData").value.strip()
if not text:
window.alert("Paste roster data first.")
return
combined = self.combine_multiline_entries(text)
parsed = {}
for entry in combined:
parts = self.parse_entry(entry)
if not parts:
continue
phone, name, reg = parts
phone = self.normalize_phone(phone)
parsed[phone] = {
"phone": phone,
"name": name.title().strip(),
"registration_number": reg.strip()
}
if not parsed:
window.alert("❌ No valid entries found.")
return
self.student_roster = parsed
self.app.student_roster = parsed # Update global reference
document.querySelector("#rosterStatus").innerHTML = (
f"✅ Replace complete — Total: {len(parsed)}"
)
window.alert(f"✅ Roster replaced!\nTotal: {len(parsed)}")
# CRITICAL: Refresh analytics display with new roster data
if self.app.analytics_data:
self.app.progress_analyzer.refresh_analytics_with_roster()
def parse_and_merge(self, e=None):
"""Parse and merge roster"""
text = document.querySelector("#pasteRosterData").value.strip()
if not text:
window.alert("Paste roster data first.")
return
combined = self.combine_multiline_entries(text)
added, updated = 0, 0
for entry in combined:
parts = self.parse_entry(entry)
if not parts:
continue
phone, name, reg = parts
phone = self.normalize_phone(phone)
if phone not in self.student_roster:
self.student_roster[phone] = {
"phone": phone,
"name": name.title().strip(),
"registration_number": reg.strip()
}
added += 1
else:
prev = self.student_roster[phone]
if name != prev["name"] or reg != prev["registration_number"]:
self.student_roster[phone].update({
"name": name.title().strip(),
"registration_number": reg.strip()
})
updated += 1
self.app.student_roster = self.student_roster # Update global reference
document.querySelector("#rosterStatus").innerHTML = (
f"✅ Merge complete — Total: {len(self.student_roster)} • Added: {added} • Updated: {updated}"
)
window.alert(f"✅ Roster merged!\nTotal: {len(self.student_roster)}\nAdded: {added}\nUpdated: {updated}")
# CRITICAL: Refresh analytics display with new roster data
if self.app.analytics_data:
self.app.progress_analyzer.refresh_analytics_with_roster()
def clear_roster(self, e=None):
"""Clear the roster"""
self.student_roster = {}
self.app.student_roster = {} # Update global reference
document.querySelector("#pasteRosterData").value = ""
document.querySelector("#rosterStatus").innerHTML = ""
window.alert("Roster cleared.")
# Refresh analytics display
if self.app.analytics_data:
self.app.display_manager.display_analytics(self.app.analytics_data, [])
def view_roster(self, e=None):
"""Display roster in a modal"""
if not self.student_roster:
window.alert("No roster loaded.")
return
# Sort by registration number, then name
def sort_key(item):
reg = item[1].get("registration_number", "")
try:
return int(re.sub(r"\D", "", reg) or 0)
except:
return 0
sorted_roster = sorted(
self.student_roster.items(),
key=lambda x: (sort_key(x), x[1]["name"].lower())
)
html_content = """
<table style='width:100%;font-size:13px;border-collapse:collapse;'>