-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1455 lines (1319 loc) · 85.7 KB
/
Copy pathscript.js
File metadata and controls
1455 lines (1319 loc) · 85.7 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
import { _sb, GOOGLE_CLIENT_ID } from './config.js'
// ─── STATE ─────────────────────────────────────────────────
let googleAccessToken = null;
let isAdmin = false;
let currentUser = null;
let students = [];
let assignments = [];
let gradingRows = [];
let attendanceRows = [];
let adminInitialized = false;
let html5QrCode = null, scanning = false, lastScannedText = '', lastScannedAt = 0;
let attendanceQr = null, attendanceScanning = false, lastAttendanceScan = '', lastAttendanceScanAt = 0;
let scorePieChart = null;
// ─── UI HELPERS ────────────────────────────────────────────
function $(id) { return document.getElementById(id); }
function showToast(msg, type = 'info') {
const icons = { success: '✅', error: '❌', info: 'ℹ️', warn: '⚠️' };
const el = document.createElement('div');
el.className = 'toast ' + type;
el.innerHTML = `<span>${icons[type] || 'ℹ️'}</span><span>${msg}</span>`;
$('toasts').appendChild(el);
setTimeout(() => { el.style.transition = 'opacity 0.4s'; el.style.opacity = '0'; }, 3400);
setTimeout(() => el.remove(), 3800);
}
function openModal(id) { $(id).classList.add('open'); }
function closeModal(id) { $(id).classList.remove('open'); }
document.querySelectorAll('.modal-overlay').forEach(el => {
el.addEventListener('click', e => { if (e.target === el && el.id !== 'm-login') closeModal(el.id); });
});
function setSyncProgress(pct, msg) {
const overlay = $('sync-overlay');
if (pct <= 0) { overlay.classList.remove('open'); return; }
overlay.classList.add('open');
$('sync-progress-text').textContent = msg || 'กำลังซิงค์...';
$('sync-progress-bar').style.width = pct + '%';
}
function escapeHtml(str) {
if (str == null) return '';
return String(str)
.replace(/&/g, '&').replace(/</g, '<')
.replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
// ─── NAVIGATION ────────────────────────────────────────────
function showPage(name) {
stopQrScanner(); stopAttendanceScanner();
if (name === 'admin' && !isAdmin) { openModal('m-login'); return; }
document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
$('page-' + name).classList.add('active');
$('nav-' + name).classList.add('active');
if (name === 'admin' && isAdmin) initAdmin();
}
// ─── LOGIN / LOGOUT ────────────────────────────────────────
async function doLogin() {
const email = $('l-user').value.trim();
const pass = $('l-pass').value;
const btn = $('login-btn');
$('l-err').style.display = 'none';
btn.disabled = true; btn.textContent = 'กำลังยืนยันตัวตน...';
try {
const { data, error } = await _sb.auth.signInWithPassword({ email, password: pass });
if (error) throw error;
isAdmin = true; currentUser = data.user; adminInitialized = false;
closeModal('m-login');
showToast('เข้าสู่ระบบสำเร็จ!', 'success');
showPage('admin');
} catch (e) {
$('l-err').textContent = '❌ ' + (e.message === 'Invalid login credentials' ? 'อีเมลหรือรหัสผ่านผิด' : e.message);
$('l-err').style.display = 'block';
} finally {
btn.disabled = false; btn.textContent = 'เข้าสู่ระบบ';
}
}
async function doLogout() {
if (!confirm('คุณต้องการออกจากระบบใช่หรือไม่?')) return;
await _sb.auth.signOut();
isAdmin = false; currentUser = null; adminInitialized = false;
$('nav-logout').style.display = 'none';
$('cfg-dot').className = 'cfg-dot';
showPage('status');
location.reload();
}
// ─── SUPABASE HELPERS ──────────────────────────────────────
const gasCall = async (fnName, ...args) => {
if (fnName === 'getStudents') {
const { data, error } = await _sb.from('students').select('*').order('classroom').order('seat_no');
if (error) throw error; return data || [];
}
if (fnName === 'getStudentById') {
const { data } = await _sb.from('students').select('*').eq('id', args[0]).maybeSingle(); return data;
}
if (fnName === 'upsertStudent') {
const { data, error } = await _sb.from('students').upsert(args[0], { onConflict: 'id' }).select();
if (error) throw error; return data;
}
if (fnName === 'upsertStudents') {
const { data, error } = await _sb.from('students').upsert(args[0], { onConflict: 'id' }).select();
if (error) throw error; return data;
}
if (fnName === 'deleteStudent') {
const { error } = await _sb.from('students').delete().eq('id', args[0]);
if (error) throw error; return true;
}
if (fnName === 'updateBehaviorScore') {
const s = Math.min(15, Math.max(0, args[1]));
const { data, error } = await _sb.from('students').update({ behavior_score: s }).eq('id', args[0]).select();
if (error) throw error; return data;
}
if (fnName === 'getAllAssignments') {
const { data, error } = await _sb.from('assignments').select('*').order('created_at', { ascending: false });
if (error) throw error; return data || [];
}
if (fnName === 'getAssignmentById') {
const { data } = await _sb.from('assignments').select('*').eq('id', args[0]).maybeSingle(); return data;
}
if (fnName === 'createAssignment') {
const d = args[0];
const payload = { name: d.name, subject: d.subject, classroom: d.classroom, category: d.category || 'ก่อนกลางภาค', passing_score: d.passing_score || 0, max_score: d.max_score, type: d.type || 'เดี่ยว', deadline: d.deadline || null };
const { data: newA, error } = await _sb.from('assignments').insert(payload).select().single();
if (error) throw error;
const { data: stList } = await _sb.from('students').select('id').eq('classroom', d.classroom);
if (stList?.length) {
const grPay = stList.map(s => ({ student_id: s.id, assignment_id: newA.id, score: null, max_score: d.max_score, status: 'not_sent' }));
await _sb.from('grades').upsert(grPay, { onConflict: 'student_id,assignment_id' });
}
return newA;
}
if (fnName === 'deleteAssignment') {
const { error } = await _sb.from('assignments').delete().eq('id', args[0]);
if (error) throw error; return true;
}
if (fnName === 'getGradesByStudent') {
const { data, error } = await _sb.from('grades').select('*, assignments(*)').eq('student_id', args[0]);
if (error) throw error; return data || [];
}
if (fnName === 'getGradesByAssignment') {
const { data, error } = await _sb.from('grades').select('*').eq('assignment_id', args[0]);
if (error) throw error; return data || [];
}
if (fnName === 'saveGrades') {
const now = new Date().toISOString();
const payload = args[0].map(r => ({ student_id: r.student_id, assignment_id: r.assignment_id, score: r.score, max_score: r.max_score, status: r.status, submitted_at: r.submitted_at !== undefined ? r.submitted_at : now, updated_at: now }));
const { data, error } = await _sb.from('grades').upsert(payload, { onConflict: 'student_id,assignment_id' }).select();
if (error) throw error; return data;
}
if (fnName === 'getGradesByRoom') {
const [classroom, subject] = args;
const { data: asgns } = await _sb.from('assignments').select('*').eq('classroom', classroom).eq('subject', subject).order('created_at');
const { data: sts } = await _sb.from('students').select('*').eq('classroom', classroom).order('seat_no');
if (!asgns?.length || !sts?.length) return { students: sts || [], assignments: asgns || [], grades: [] };
const { data: grs } = await _sb.from('grades').select('*').in('student_id', sts.map(s => s.id)).in('assignment_id', asgns.map(a => a.id));
return { students: sts, assignments: asgns, grades: grs || [] };
}
if (fnName === 'getAttendanceByStudent') {
const { data, error } = await _sb.from('attendance').select('*').eq('student_id', args[0]).order('attendance_date', { ascending: false });
if (error) throw error; return data || [];
}
if (fnName === 'getAttendanceByDate') {
const [classroom, date] = args;
const { data: sts } = await _sb.from('students').select('id').eq('classroom', classroom);
if (!sts?.length) return [];
const { data } = await _sb.from('attendance').select('*').in('student_id', sts.map(s => s.id)).eq('attendance_date', date);
return data || [];
}
if (fnName === 'saveAttendance') {
const now = new Date().toISOString();
const payload = args[0].map(r => ({ student_id: r.student_id, attendance_date: r.attendance_date, subject: r.subject, status: r.status, remark: r.remark || '', hours: r.hours || 1, updated_at: now }));
const { data, error } = await _sb.from('attendance').upsert(payload, { onConflict: 'student_id,attendance_date,subject' }).select();
if (error) throw error; return data;
}
if (fnName === 'getAttendanceForRoom') {
const { data: sts } = await _sb.from('students').select('id').eq('classroom', args[0]);
if (!sts?.length) return [];
const { data } = await _sb.from('attendance').select('*').in('student_id', sts.map(s => s.id)).order('attendance_date', { ascending: true });
return data || [];
}
if (fnName === 'markStudentAttendance') {
const [studentId, date, status, remark, subject, hours] = args;
const student = await gasCall('getStudentById', studentId);
if (!student) throw new Error('ไม่พบนักเรียน');
const saved = await gasCall('saveAttendance', [{ student_id: studentId, attendance_date: date, subject: subject || '', status, remark: remark || '', hours: hours || 1 }]);
return { success: true, student, attendance_date: date, status, saved };
}
throw new Error('Unknown function: ' + fnName);
};
// ─── LATE SCORE CALCULATION ────────────────────────────────
function calcLateScore(score, maxScore, deadline, submittedAt) {
const floor = Math.ceil(maxScore * 0.2);
if (!deadline || score === null || score === undefined)
return { effectiveScore: score, daysLate: 0, penaltyPts: 0, floor };
const submitDate = new Date(submittedAt ? submittedAt.slice(0, 10) : new Date().toISOString().slice(0, 10));
const deadlineDate = new Date(deadline);
submitDate.setHours(0,0,0,0); deadlineDate.setHours(0,0,0,0);
const daysLate = Math.max(0, Math.floor((submitDate - deadlineDate) / 86400000));
const effectiveScore = daysLate > 0 ? Math.max(floor, score - daysLate) : score;
return { effectiveScore, daysLate, penaltyPts: daysLate, floor };
}
// ─── ADMIN INIT ────────────────────────────────────────────
const TABS = ['grading', 'attendance', 'behavior', 'students', 'asgn', 'export'];
function adminTab(name) {
stopQrScanner(); stopAttendanceScanner();
TABS.forEach(t => {
const tab = $('tab-' + t); if (tab) tab.style.display = t === name ? 'block' : 'none';
const btn = $('t-' + t); if (btn) btn.className = 'tab-btn' + (t === name ? ' active' : '');
});
if (name === 'behavior') renderBehaviorList();
if (name === 'students') renderStudentTable();
}
async function initAdmin() {
if (adminInitialized) return;
adminInitialized = true;
$('nav-logout').style.display = 'flex';
try {
[students, assignments] = await Promise.all([gasCall('getStudents'), gasCall('getAllAssignments')]);
$('cfg-dot').className = 'cfg-dot ok';
} catch (e) {
showToast('โหลดข้อมูลล้มเหลว: ' + e, 'error');
adminInitialized = false; return;
}
populateDropdowns();
if (!$('att-date').value) $('att-date').value = new Date().toISOString().slice(0, 10);
renderStudentTable(); renderAsgnTable(); adminTab('grading');
}
// ─── DROPDOWNS ─────────────────────────────────────────────
function populateDropdowns() {
const rooms = [...new Set(students.map(s => s.classroom))].sort();
const subjs = [...new Set(assignments.map(a => a.subject))].sort();
// เพิ่ม bh-room เข้าไปด้วย
['g-room', 'att-room', 'f-room', 'bh-room', 'exp-room', 'exp-att-room'].forEach(id => {
const el = $(id); if (!el) return;
const cur = el.value;
el.innerHTML = (id === 'f-room' ? '<option value="">เลือกห้อง</option>' : '<option value="">— เลือกห้อง —</option>') +
rooms.map(r => `<option value="${r}">${r}</option>`).join('');
el.value = cur;
});
['g-subj', 'att-subj', 'exp-subj', 'exp-att-subj'].forEach(id => {
const el = $(id); if (!el) return;
const cur = el.value;
el.innerHTML = '<option value="">— เลือกวิชา —</option>' + subjs.map(s => `<option value="${s}">${s}</option>`).join('');
el.value = cur;
});
syncAssignSelect();
}
function syncAssignSelect() {
const subj = $('g-subj').value, room = $('g-room').value, el = $('g-asgn');
const cur = el.value;
el.innerHTML = '<option value="">— เลือกงาน —</option>';
assignments.filter(a => (!subj || a.subject === subj) && (!room || a.classroom === room))
.forEach(a => { el.innerHTML += `<option value="${a.id}">${a.name}</option>`; });
el.value = cur;
}
// ─── STATUS PAGE ───────────────────────────────────────────
async function searchStatus() {
const sid = $('st-id-inp').value.trim();
if (!sid) { showToast('กรุณาใส่รหัสนักเรียน', 'error'); return; }
$('st-results').style.display = $('st-att-card').style.display = $('st-empty').style.display = 'none';
try {
const [grades, attendance, stInfo] = await Promise.all([
gasCall('getGradesByStudent', sid), gasCall('getAttendanceByStudent', sid), gasCall('getStudentById', sid)
]);
if (!stInfo) { $('st-empty').style.display = 'block'; return; }
const fullName = stInfo.first_name + ' ' + stInfo.last_name;
$('st-name').textContent = $('st-name-display').textContent = fullName;
$('st-meta').textContent = 'ชั้น ' + stInfo.classroom + ' เลขที่ ' + stInfo.seat_no + ' | รหัส: ' + sid;
$('st-meta-display').textContent = 'ชั้น ' + stInfo.classroom + ' เลขที่ ' + stInfo.seat_no;
const catStats = {
'ก่อนกลางภาค': { current: 0, max: 0, weight: 20 },
'กลางภาค': { current: 0, max: 0, weight: 25 },
'หลังกลางภาค': { current: 0, max: 0, weight: 20 },
'ปลายภาค': { current: 0, max: 0, weight: 25 }
};
const uniqueMap = {};
grades.forEach(g => {
if (!g.assignments) return;
const sc = parseFloat(g.score || 0);
if (!uniqueMap[g.assignment_id] || sc > parseFloat(uniqueMap[g.assignment_id].score || 0))
uniqueMap[g.assignment_id] = g;
});
const sorted = Object.values(uniqueMap).sort((a, b) => {
const sa = (a.assignments.subject || '').toLowerCase(), sb = (b.assignments.subject || '').toLowerCase();
return sa.localeCompare(sb) || (a.assignments.name || '').toLowerCase().localeCompare((b.assignments.name || '').toLowerCase());
});
let countOk = 0, countWait = 0, countNo = 0;
const tbody = $('st-tbody');
tbody.innerHTML = '';
let lastSubject = null;
if (!sorted.length) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;padding:30px;color:var(--text-secondary)">ยังไม่มีรายการงานในขณะนี้</td></tr>';
}
sorted.forEach(g => {
const a = g.assignments || {};
const cat = a.category || 'ก่อนกลางภาค';
const type = a.type || 'ทั่วไป';
const sc = parseFloat(g.score || 0);
const max = parseFloat(a.max_score || 10);
const pass = parseFloat(a.passing_score || 0);
const deadline = a.deadline ? a.deadline.slice(0, 10) : null;
const { daysLate } = calcLateScore(sc, max, deadline, g.submitted_at || null);
if (catStats[cat]) {
catStats[cat].max += max;
if (g.status === 'checked') catStats[cat].current += sc;
}
const subjectName = a.subject || 'วิชาทั่วไป';
if (subjectName !== lastSubject) {
const tr = document.createElement('tr');
tr.className = 'tr-subject-group';
const td = document.createElement('td');
td.colSpan = 5; td.textContent = '📚 ' + subjectName;
tr.appendChild(td); tbody.appendChild(tr);
lastSubject = subjectName;
}
let badge = '', rowClass = '';
if (g.status === 'checked') {
badge = (sc < pass && pass > 0) ? '<span class="badge badge-red">❌ ไม่ผ่าน</span>' : '<span class="badge badge-green">✅ ส่งแล้ว</span>';
rowClass = (sc < pass && pass > 0) ? 'row-ขาด' : 'row-มา';
countOk++;
} else if (g.status === 'waiting') {
badge = '<span class="badge badge-amber">⏳ รอตรวจ</span>'; rowClass = 'row-สาย'; countWait++;
} else {
badge = '<span class="badge badge-red">🚫 ยังไม่ส่ง</span>'; rowClass = 'row-not-sent'; countNo++;
}
const lateHtml = (daysLate > 0 && g.status === 'checked') ? `<div style="font-size:.72rem;color:var(--red)">🕐 ส่งช้า ${daysLate} วัน</div>` : '';
const scoreHtml = g.status === 'checked'
? `<span class="score-big" style="font-size:1.4rem">${g.score}</span><span class="score-sep"> / </span><span class="score-max">${max}</span>${lateHtml}`
: '<span class="text-muted">—</span>';
const deadlineHtml = deadline
? `<div style="font-size:.72rem;color:${new Date() > new Date(deadline) ? 'var(--red)' : 'var(--text-secondary)'}">📅 ส่งภายใน: ${new Date(deadline).toLocaleDateString('th-TH', { day: 'numeric', month: 'short', year: '2-digit' })}</div>`
: '';
const descHtml = a.description ? `<div style="font-size:0.75rem;color:var(--text-secondary);margin-top:4px;line-height:1.4">📝 ${escapeHtml(a.description)}</div>` : '';
const tr = document.createElement('tr');
tr.className = rowClass;
tr.innerHTML = `
<td><small class="text-muted">${escapeHtml(cat)}</small></td>
<td><strong>${escapeHtml(a.name || '—')}</strong>${descHtml}${deadlineHtml}</td>
<td style="text-align:center"><span class="badge ${type.includes('สอบ') ? 'badge-amber' : 'badge-blue'}">${escapeHtml(type)}</span></td>
<td style="text-align:center">${badge}</td>
<td style="text-align:center">${scoreHtml}</td>`;
tbody.appendChild(tr);
});
let weightedTotal = 0;
const chartPoints = ['ก่อนกลางภาค', 'กลางภาค', 'หลังกลางภาค', 'ปลายภาค'].map(lbl => {
const s = catStats[lbl];
const pt = s.max > 0 ? (s.current / s.max) * s.weight : 0;
weightedTotal += pt; return pt.toFixed(2);
});
const behaviorScore = stInfo.behavior_score != null ? parseFloat(stInfo.behavior_score) : 10;
chartPoints.push(behaviorScore.toFixed(2));
const grandTotal = weightedTotal + behaviorScore;
$('final-weighted-score').textContent = grandTotal.toFixed(1);
$('final-weighted-score').style.color = grandTotal >= 50 ? '#fff' : 'var(--red)';
$('cnt-all').textContent = sorted.length;
$('cnt-ok').textContent = countOk;
$('cnt-wait').textContent = countWait;
$('cnt-no').textContent = countNo;
$('behavior-score-text').textContent = behaviorScore + '/15';
$('behavior-progress-fill').style.width = (behaviorScore / 15 * 100) + '%';
$('behavior-progress-fill').style.background = behaviorScore > 10 ? 'linear-gradient(90deg,var(--purple),#ec4899)' : 'var(--purple)';
const subPct = sorted.length > 0 ? ((countOk + countWait) / sorted.length * 100) : 0;
$('global-progress-fill').style.width = subPct + '%';
$('global-progress-text').textContent = subPct.toFixed(0) + '%';
updatePieChart(chartPoints);
const attContent = $('st-att-content');
attContent.innerHTML = '';
if (attendance?.length) {
const grouped = {};
attendance.forEach(a => { const s = a.subject || 'ไม่ระบุวิชา'; (grouped[s] = grouped[s] || []).push(a); });
Object.entries(grouped).forEach(([subj, data]) => renderAttendanceGrid(subj, data, attContent));
$('st-att-card').style.display = 'block';
}
$('st-results').style.display = 'block';
showToast('ดึงข้อมูลสำเร็จ', 'success');
} catch (e) {
console.error(e); showToast('เกิดข้อผิดพลาด: ' + e.message, 'error');
}
}
function updatePieChart(dataPoints) {
const ctx = $('scoreChart').getContext('2d');
if (scorePieChart) scorePieChart.destroy();
Chart.register(ChartDataLabels);
scorePieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['ก่อนกลางภาค', 'กลางภาค', 'หลังกลางภาค', 'ปลายภาค', 'จิตพิสัย'],
datasets: [{ data: dataPoints, backgroundColor: ['#0ea5e9', '#10b981', '#f59e0b', '#ef4444', '#a855f7'], borderWidth: 2, borderColor: '#050e30', hoverOffset: 15 }]
},
options: {
cutout: '50%', layout: { padding: 10 },
plugins: {
legend: { display: false }, tooltip: { enabled: true },
datalabels: { color: '#ffffff', font: { family: 'Kanit', weight: 'bold', size: 14 }, anchor: 'center', align: 'center', formatter: v => parseFloat(v) > 0 ? parseFloat(v).toFixed(1) : '' }
},
responsive: true, maintainAspectRatio: false
}
});
}
function renderAttendanceGrid(subjectName, attendanceData, container) {
const wrapper = document.createElement('div');
wrapper.className = 'mb-4';
const uniqueDates = [...new Set(attendanceData.map(a => a.attendance_date))].sort();
const attMap = {};
let attendedHours = 0, totalHours = 0;
attendanceData.forEach(a => {
attMap[a.attendance_date] = a;
const h = parseFloat(a.hours) || 1;
totalHours += h;
if (a.status === 'มา') attendedHours += h;
else if (a.status === 'ลา') attendedHours += h * 0.25;
else if (a.status === 'สาย') attendedHours += h * 0.5;
});
const pct = totalHours > 0 ? (attendedHours / totalHours) * 100 : 0;
const pctColor = pct >= 80 ? '#22d3ee' : '#ef4444';
let headHtml = '<tr><th class="att-side-label" style="position:sticky;left:0;z-index:30">รายการ \\ วันที่</th>';
uniqueDates.forEach(date => {
const d = new Date(date), h = attMap[date].hours || 1;
headHtml += `<th style="text-align:center;min-width:80px"><div style="font-size:13px">${d.getDate()}/${d.getMonth()+1}/${(d.getFullYear()+543).toString().slice(-2)}</div><div style="font-size:10px;font-weight:400;opacity:.9">(${h} ชม.)</div></th>`;
});
headHtml += '<th class="att-summary-col" style="text-align:center;min-width:80px">มา/รวม</th><th class="att-summary-col" style="text-align:center;min-width:70px">ร้อยละ</th></tr>';
let bodyHtml = '<tr><td class="att-side-label" style="position:sticky;left:0;z-index:10;padding:15px">สถานะ</td>';
uniqueDates.forEach(date => {
const rec = attMap[date];
const map = { 'มา': ['✅','rgba(16,185,129,0.2)'], 'ขาด': ['❌','rgba(239,68,68,0.2)'], 'ลา': ['📝','rgba(14,165,233,0.2)'], 'สาย': ['⏰','rgba(245,158,11,0.2)'] };
const [symbol, cellBg] = (rec && map[rec.status]) || ['-', 'rgba(255,255,255,0.03)'];
bodyHtml += `<td style="text-align:center;background:${cellBg};font-size:20px">${symbol}</td>`;
});
bodyHtml += `<td class="att-summary-col" style="text-align:center">${attendedHours}/${totalHours}</td><td class="att-summary-col" style="text-align:center;color:${pctColor};font-size:18px">${pct.toFixed(0)}%</td></tr>`;
wrapper.innerHTML = `
<div style="font-weight:bold;margin-bottom:10px;border-left:4px solid var(--matisse);padding-left:10px;color:var(--platinum)">📚 วิชา: ${escapeHtml(subjectName)}</div>
<div class="tbl-wrap"><table><thead>${headHtml}</thead><tbody>${bodyHtml}</tbody></table></div>`;
container.appendChild(wrapper);
}
// ─── GRADING ───────────────────────────────────────────────
async function loadGrading() {
stopQrScanner(); $('scan-sw').checked = false; $('scan-area').style.display = 'none';
const aid = $('g-asgn').value, room = $('g-room').value;
if (!aid || !room) { showToast('กรุณาเลือกห้องและงาน', 'error'); return; }
const asgn = assignments.find(a => a.id === aid);
$('grading-title').textContent = '📋 ' + (asgn?.name || 'รายชื่อนักเรียน') + ' — ห้อง ' + room;
$('grading-wrap').style.display = 'block';
$('grading-tbody').innerHTML = '<tr><td colspan="6"><div class="loading"><div class="spinner"></div>กำลังโหลด...</div></td></tr>';
try {
const classStudents = students.filter(s => s.classroom === room).sort((a, b) => a.seat_no - b.seat_no);
const gradesRaw = await gasCall('getGradesByAssignment', aid);
const gMap = {};
gradesRaw.forEach(g => { gMap[g.student_id] = g; });
gradingRows = classStudents.map(s => {
const g = gMap[s.id] || {};
return { student: s, gradeId: g.id || null, status: g.status || 'not_sent', score: (g.score != null) ? g.score : null, maxScore: g.max_score || asgn?.max_score || 10, submittedAt: g.submitted_at || null, deadline: asgn?.deadline || null };
});
renderGradingTable();
} catch (e) {
showToast('โหลดล้มเหลว: ' + e, 'error'); $('grading-tbody').innerHTML = '';
}
}
function togLabel(s) {
return s === 'checked' ? '✅ ตรวจแล้ว' : s === 'waiting' ? '⏳ รอตรวจ' : '❌ ยังไม่ส่ง';
}
function updateEffectiveDisplay(i) {
const row = gradingRows[i];
const raw = $('sc-' + i).value !== '' ? parseFloat($('sc-' + i).value) : null;
const { effectiveScore, daysLate, penaltyPts } = calcLateScore(raw, row.maxScore, row.deadline, row.submittedAt || new Date().toISOString());
const nameCell = document.querySelector(`#gr-${i} td:nth-child(3)`);
if (!nameCell) return;
nameCell.querySelectorAll('.late-info').forEach(el => el.remove());
if (daysLate > 0 && raw !== null) {
const badge = document.createElement('span');
badge.className = 'badge badge-red late-info';
badge.style.cssText = 'font-size:.7rem;margin-left:4px';
badge.textContent = `🕐 ช้า ${daysLate} วัน (−${penaltyPts}) → ได้ ${effectiveScore}`;
nameCell.appendChild(badge);
}
}
function renderGradingTable() {
const fragment = document.createDocumentFragment();
gradingRows.forEach((row, i) => {
const s = row.student;
const cls = row.status === 'checked' ? 'checked' : row.status === 'waiting' ? 'waiting' : 'not-sent';
const { effectiveScore, daysLate, penaltyPts } = calcLateScore(row.score, row.maxScore, row.deadline, row.submittedAt);
const tr = document.createElement('tr');
tr.id = 'gr-' + i;
const tdSeat = document.createElement('td'); tdSeat.style.textAlign = 'center'; tdSeat.textContent = s.seat_no || '—';
const tdId = document.createElement('td'); tdId.style.cssText = 'font-size:.85rem;color:var(--text-secondary)'; tdId.textContent = s.id;
const tdName = document.createElement('td');
const strong = document.createElement('strong'); strong.textContent = s.first_name + ' ' + s.last_name;
tdName.appendChild(strong);
if (daysLate > 0 && row.score !== null) {
const lb = document.createElement('span'); lb.className = 'badge badge-red'; lb.style.cssText = 'font-size:.7rem;margin-left:4px';
lb.textContent = `🕐 ช้า ${daysLate} วัน (−${penaltyPts})`; tdName.appendChild(lb);
}
if (effectiveScore !== null && effectiveScore !== row.score) {
const eff = document.createElement('span'); eff.style.cssText = 'color:var(--red);font-weight:700;margin-left:6px'; eff.textContent = effectiveScore;
const orig = document.createElement('span'); orig.style.cssText = 'color:var(--text-secondary);font-size:.8rem;text-decoration:line-through;margin-left:4px'; orig.textContent = row.score;
tdName.appendChild(eff); tdName.appendChild(orig);
}
const tdStatus = document.createElement('td'); tdStatus.style.textAlign = 'center';
const togBtn = document.createElement('button'); togBtn.className = 'tog ' + cls; togBtn.id = 'tog-' + i; togBtn.textContent = togLabel(row.status);
togBtn.addEventListener('click', () => toggleRow(i)); tdStatus.appendChild(togBtn);
const tdScore = document.createElement('td'); tdScore.style.textAlign = 'center';
const inp = document.createElement('input'); inp.className = 'score-in'; inp.type = 'number'; inp.id = 'sc-' + i;
inp.value = row.score !== null ? row.score : ''; inp.min = 0; inp.max = row.maxScore; inp.placeholder = row.maxScore;
inp.addEventListener('change', () => updateEffectiveDisplay(i)); tdScore.appendChild(inp);
const tdMax = document.createElement('td'); tdMax.style.cssText = 'text-align:center;font-weight:700;color:var(--text-secondary)'; tdMax.textContent = row.maxScore;
tr.append(tdSeat, tdId, tdName, tdStatus, tdScore, tdMax);
fragment.appendChild(tr);
});
$('grading-tbody').replaceChildren(fragment);
}
function toggleRow(i) {
gradingRows[i].status = gradingRows[i].status === 'checked' ? 'not_sent' : 'checked';
const btn = $('tog-' + i);
btn.className = 'tog ' + (gradingRows[i].status === 'checked' ? 'checked' : 'not-sent');
btn.textContent = togLabel(gradingRows[i].status);
}
function markAllStatus(s) {
gradingRows.forEach((_, i) => {
gradingRows[i].status = s;
const btn = $('tog-' + i);
if (btn) { btn.className = 'tog ' + (s === 'checked' ? 'checked' : 'not-sent'); btn.textContent = togLabel(s); }
});
}
async function saveGradesNow() {
const aid = $('g-asgn').value;
if (!aid) { showToast('กรุณาเลือกงานก่อน', 'error'); return; }
const saveBtn = document.querySelector('[onclick="saveGradesNow()"]');
if (saveBtn) { saveBtn.disabled = true; saveBtn.textContent = '⏳ กำลังบันทึก...'; }
const now = new Date().toISOString();
const rows = gradingRows.map((row, i) => {
const sv = $('sc-' + i).value;
const rawScore = sv !== '' ? parseFloat(sv) : null;
const submittedAt = row.submittedAt || (rawScore !== null ? now : null);
const { effectiveScore } = calcLateScore(rawScore, row.maxScore, row.deadline, submittedAt);
return {
student_id: row.student.id,
assignment_id: aid,
score: effectiveScore,
max_score: row.maxScore,
status: rawScore !== null ? 'checked' : row.status,
submitted_at: submittedAt
};
});
try {
await gasCall('saveGrades', rows);
// อัปเดต in-memory แทนโหลดซ้ำทั้งหมด
rows.forEach((r, i) => {
gradingRows[i].score = r.score;
gradingRows[i].status = r.status;
gradingRows[i].submittedAt = r.submitted_at;
});
showToast('บันทึกคะแนนสำเร็จ! 🎉', 'success');
} catch (e) {
showToast('บันทึกล้มเหลว: ' + e, 'error');
} finally {
if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = '💾 บันทึกคะแนน'; }
}
}
// ─── QR SCAN ───────────────────────────────────────────────
function setScanMode(on) {
$('scan-area').style.display = on ? 'block' : 'none';
if (on) { startQrScanner(); $('scan-inp').focus(); } else stopQrScanner();
}
async function startQrScanner() {
if (scanning) return;
const aid = $('g-asgn').value;
if (!aid) { showToast('กรุณาเลือกงานก่อน', 'warn'); $('scan-sw').checked = false; $('scan-area').style.display = 'none'; return; }
try {
html5QrCode = new Html5Qrcode('reader'); scanning = true;
await html5QrCode.start({ facingMode: 'environment' }, { fps: 10, qrbox: { width: 220, height: 220 } },
async decodedText => {
const now = Date.now();
if (decodedText === lastScannedText && now - lastScannedAt < 2500) return;
lastScannedText = decodedText; lastScannedAt = now; await handleScan(decodedText);
}, () => {});
showToast('เปิดกล้องสแกน QR แล้ว', 'success');
} catch (e) { scanning = false; showToast('เปิดกล้องไม่ได้: ' + e, 'error'); }
}
async function stopQrScanner() {
try { if (html5QrCode && scanning) { await html5QrCode.stop(); await html5QrCode.clear(); } } catch (e) {}
scanning = false;
}
function extractStudentId(raw) {
raw = (raw || '').trim(); if (!raw) return '';
if (raw.startsWith('http://') || raw.startsWith('https://')) {
try { return new URL(raw).searchParams.get('student_id') || raw; } catch (e) { return raw; }
}
return raw;
}
async function handleScan(val) {
const studentId = extractStudentId(val); if (!studentId) return;
const aid = $('g-asgn').value; if (!aid) { showToast('กรุณาเลือกงานก่อนสแกน', 'error'); return; }
const idx = gradingRows.findIndex(r => r.student.id === studentId);
if (idx === -1) { showToast('ไม่พบรหัส: ' + studentId, 'error'); return; }
const asgn = assignments.find(a => a.id === aid);
const rawScore = asgn?.max_score || 10;
const submittedAt = new Date().toISOString();
const { effectiveScore, daysLate } = calcLateScore(rawScore, rawScore, asgn?.deadline, submittedAt);
try {
await gasCall('saveGrades', [{ student_id: studentId, assignment_id: aid, score: effectiveScore, max_score: rawScore, status: 'checked', submitted_at: submittedAt }]);
gradingRows[idx].status = 'checked'; gradingRows[idx].score = effectiveScore; gradingRows[idx].submittedAt = submittedAt;
const btn = $('tog-' + idx); if (btn) { btn.className = 'tog checked'; btn.textContent = togLabel('checked'); }
const sc = $('sc-' + idx); if (sc) sc.value = effectiveScore;
const row = $('gr-' + idx);
if (row) { row.scrollIntoView({ behavior: 'smooth', block: 'center' }); row.style.background = 'rgba(16,185,129,.1)'; setTimeout(() => row.style.background = '', 1200); }
const student = gradingRows[idx].student;
showToast(daysLate > 0 ? `${student.first_name} — ช้า ${daysLate} วัน ได้ ${effectiveScore}/${rawScore}` : student.first_name + ' ' + student.last_name + ' ✅', daysLate > 0 ? 'warn' : 'success');
} catch (e) { showToast('บันทึกไม่สำเร็จ: ' + e, 'error'); }
}
// ─── ATTENDANCE ────────────────────────────────────────────
async function loadAttendance() {
stopAttendanceScanner(); $('att-scan-sw').checked = false; $('att-scan-area').style.display = 'none';
const room = $('att-room').value, date = $('att-date').value;
if (!room || !date) { showToast('กรุณาเลือกห้องและวันที่', 'error'); return; }
$('attendance-title').textContent = '📋 เช็กชื่อ ห้อง ' + room + ' วันที่ ' + date;
$('attendance-wrap').style.display = 'block';
$('attendance-tbody').innerHTML = '<tr><td colspan="5"><div class="loading"><div class="spinner"></div>กำลังโหลด...</div></td></tr>';
try {
const classStudents = students.filter(s => s.classroom === room).sort((a, b) => a.seat_no - b.seat_no);
const raw = await gasCall('getAttendanceByDate', room, date);
const aMap = {};
(raw || []).forEach(a => aMap[a.student_id] = a);
attendanceRows = classStudents.map(s => { const a = aMap[s.id] || {}; return { student: s, status: a.status || 'ขาด', remark: a.remark || '' }; });
renderAttendanceTable();
} catch (e) {
showToast('โหลดการเข้าเรียนล้มเหลว: ' + e, 'error'); $('attendance-tbody').innerHTML = '';
}
}
function renderAttendanceTable() {
const tb = $('attendance-tbody'); if (!tb) return;
const statuses = [
{ val: 'มา', label: 'มา', cls: 'att-radio-มา' },
{ val: 'สาย', label: 'สาย', cls: 'att-radio-สาย' },
{ val: 'ลา', label: 'ลา', cls: 'att-radio-ลา' },
{ val: 'ขาด', label: 'ขาด', cls: 'att-radio-ขาด' },
];
const fragment = document.createDocumentFragment();
attendanceRows.forEach((row, i) => {
const tr = document.createElement('tr');
tr.id = 'att-row-' + i; tr.className = 'row-' + row.status;
const tdSeat = document.createElement('td'); tdSeat.style.cssText = 'text-align:center;font-weight:700'; tdSeat.textContent = row.student.seat_no || '—';
const tdId = document.createElement('td'); tdId.style.cssText = 'color:#cbd5e1;font-size:.85rem'; tdId.textContent = row.student.id;
const tdName = document.createElement('td');
const nameSpan = document.createElement('span'); nameSpan.style.cssText = 'color:#fff;font-size:1.05rem;font-weight:600';
nameSpan.textContent = row.student.first_name + ' ' + row.student.last_name; tdName.appendChild(nameSpan);
const tdStatus = document.createElement('td');
const radioGroup = document.createElement('div'); radioGroup.className = 'att-radio-group'; radioGroup.id = 'att-rg-' + i;
statuses.forEach(s => {
const label = document.createElement('label');
label.className = 'att-radio-label ' + s.cls + (row.status === s.val ? ' checked' : '');
const input = document.createElement('input'); input.type = 'radio'; input.name = 'att-status-' + i; input.value = s.val; input.checked = (row.status === s.val);
input.addEventListener('change', () => updateAttendanceRowVisual(i, s.val));
label.appendChild(input); label.appendChild(document.createTextNode(' ' + s.label)); radioGroup.appendChild(label);
});
tdStatus.appendChild(radioGroup);
const tdRemark = document.createElement('td');
const remarkInp = document.createElement('input'); remarkInp.type = 'text'; remarkInp.id = 'att-remark-' + i;
remarkInp.value = row.remark || ''; remarkInp.placeholder = 'หมายเหตุ';
remarkInp.style.cssText = 'background:rgba(255,255,255,0.92);color:#000;width:100%;padding:8px 10px;border-radius:8px;border:1px solid rgba(180,180,210,0.5)';
tdRemark.appendChild(remarkInp);
tr.append(tdSeat, tdId, tdName, tdStatus, tdRemark);
fragment.appendChild(tr);
});
tb.replaceChildren(fragment);
}
function updateAttendanceRowVisual(index, value) {
attendanceRows[index].status = value;
const tr = $('att-row-' + index); if (tr) tr.className = 'row-' + value;
const rg = $('att-rg-' + index);
if (rg) rg.querySelectorAll('.att-radio-label').forEach(lbl => lbl.classList.toggle('checked', lbl.querySelector('input').value === value));
}
function markAllAttendance(status) {
attendanceRows.forEach((_, i) => {
const radio = document.querySelector(`input[name="att-status-${i}"][value="${status}"]`);
if (radio) radio.checked = true;
updateAttendanceRowVisual(i, status);
});
}
async function saveAttendanceNow() {
const date = $('att-date').value;
const subj = $('att-subj').value;
const room = $('att-room').value;
const hours = parseFloat($('att-hours').value) || 1;
if (!date || !subj || !room) { showToast('กรุณาเลือกวิชา ห้อง และวันที่ให้ครบ', 'error'); return; }
const saveBtn = document.querySelector('[onclick="saveAttendanceNow()"]');
if (saveBtn) { saveBtn.disabled = true; saveBtn.textContent = '⏳ กำลังบันทึก...'; }
const rows = attendanceRows.map((row, i) => {
const checked = document.querySelector(`input[name="att-status-${i}"]:checked`);
const rem = $('att-remark-' + i);
return {
student_id: row.student.id,
attendance_date: date,
subject: subj,
status: checked ? checked.value : row.status,
remark: rem ? rem.value : '',
hours
};
});
try {
await gasCall('saveAttendance', rows);
// อัปเดต in-memory แทนโหลดซ้ำทั้งหมด
rows.forEach(r => {
const idx = attendanceRows.findIndex(a => a.student.id === r.student_id);
if (idx !== -1) {
attendanceRows[idx].status = r.status;
attendanceRows[idx].remark = r.remark;
}
});
showToast('บันทึกการเข้าเรียนวิชา ' + subj + ' สำเร็จ', 'success');
} catch (e) {
showToast('บันทึกไม่สำเร็จ: ' + (e.message || e), 'error');
} finally {
if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = '💾 บันทึกการเช็กชื่อ'; }
}
}
function setAttendanceScanMode(on) {
$('att-scan-area').style.display = on ? 'block' : 'none';
if (on) { startAttendanceScanner(); $('att-scan-inp').focus(); } else stopAttendanceScanner();
}
async function startAttendanceScanner() {
if (attendanceScanning) return;
const room = $('att-room').value, date = $('att-date').value;
if (!room || !date) { showToast('กรุณาเลือกห้องและวันที่ก่อนสแกน', 'warn'); $('att-scan-sw').checked = false; $('att-scan-area').style.display = 'none'; return; }
try {
if (attendanceQr) { try { await attendanceQr.stop(); await attendanceQr.clear(); } catch (e) {} }
attendanceQr = new Html5Qrcode('att-reader'); attendanceScanning = true;
await attendanceQr.start({ facingMode: 'environment' }, { fps: 10, qrbox: { width: 220, height: 220 } },
async decodedText => {
const now = Date.now();
if (decodedText === lastAttendanceScan && now - lastAttendanceScanAt < 2500) return;
lastAttendanceScan = decodedText; lastAttendanceScanAt = now; await handleAttendanceScan(decodedText);
}, () => {});
showToast('เปิดกล้องเช็กชื่อแล้ว', 'success');
} catch (e) { attendanceScanning = false; showToast('เปิดกล้องไม่ได้: ' + e, 'error'); }
}
async function stopAttendanceScanner() {
try { if (attendanceQr && attendanceScanning) { await attendanceQr.stop(); await attendanceQr.clear(); } } catch (e) {}
attendanceScanning = false;
}
async function handleAttendanceScan(val) {
const studentId = extractStudentId(val); if (!studentId) return;
const idx = attendanceRows.findIndex(r => r.student.id === studentId);
if (idx === -1) { showToast('ไม่พบรหัส: ' + studentId, 'error'); return; }
const date = $('att-date').value, subj = $('att-subj').value, hours = parseFloat($('att-hours').value) || 1;
try {
const result = await gasCall('markStudentAttendance', studentId, date, 'มา', '', subj, hours);
const radio = document.querySelector(`input[name="att-status-${idx}"][value="มา"]`);
if (radio) radio.checked = true;
updateAttendanceRowVisual(idx, 'มา');
const row = $('att-row-' + idx); if (row) row.scrollIntoView({ behavior: 'smooth', block: 'center' });
showToast(result.student.first_name + ' ' + result.student.last_name + ' = มา', 'success');
} catch (e) { showToast('เช็กชื่อไม่สำเร็จ: ' + e, 'error'); }
}
// ─── STUDENTS TAB ──────────────────────────────────────────
function renderStudentTable() {
const qInp = $('f-q');
if (qInp && !qInp._bound) { qInp._bound = true; qInp.addEventListener('input', filterStudents); }
filterStudents();
}
function filterStudents() {
const room = $('f-room')?.value || '';
const q = ($('f-q')?.value || '').toLowerCase();
const tb = $('st-tbody-admin'); if (!tb) return;
// ยังไม่เลือกห้อง → แสดง prompt
if (!room) {
const tr = document.createElement('tr'); const td = document.createElement('td'); td.colSpan = 7;
td.innerHTML = '<div class="empty" style="padding:32px"><div class="empty-ico" style="font-size:2.5rem">🏫</div><div class="empty-title" style="margin-top:8px">กรุณาเลือกห้องเรียนก่อน</div></div>';
tr.appendChild(td); tb.replaceChildren(tr); return;
}
const list = students.filter(s =>
s.classroom === room &&
(!q || (s.id || '').toLowerCase().includes(q) || (s.first_name || '').toLowerCase().includes(q) || (s.last_name || '').toLowerCase().includes(q))
);
if (!list.length) {
const tr = document.createElement('tr'); const td = document.createElement('td'); td.colSpan = 7;
td.innerHTML = '<div class="empty" style="padding:24px"><div class="empty-ico" style="font-size:2rem">🔍</div><div class="empty-title">ไม่มีข้อมูล</div></div>';
tr.appendChild(td); tb.replaceChildren(tr); return;
}
const fragment = document.createDocumentFragment();
list.forEach(s => {
const tr = document.createElement('tr');
const tdId = document.createElement('td'); tdId.style.fontSize = '.85rem'; tdId.textContent = s.id;
const tdFn = document.createElement('td'); tdFn.textContent = s.first_name;
const tdLn = document.createElement('td'); tdLn.textContent = s.last_name;
const tdCls = document.createElement('td');
const badge = document.createElement('span'); badge.className = 'badge badge-blue'; badge.textContent = s.classroom; tdCls.appendChild(badge);
const tdSeat = document.createElement('td'); tdSeat.style.textAlign = 'center'; tdSeat.textContent = s.seat_no;
const tdAction = document.createElement('td'); tdAction.style.textAlign = 'center';
const wrap = document.createElement('div'); wrap.className = 'flex gap-2 justify-center';
const btnQr = document.createElement('button'); btnQr.className = 'btn btn-sm btn-outline'; btnQr.textContent = '📷';
btnQr.addEventListener('click', () => showQR(s.id, s.first_name + ' ' + s.last_name, s.classroom));
const btnEdit = document.createElement('button'); btnEdit.className = 'btn btn-sm btn-ghost'; btnEdit.textContent = '✏️';
btnEdit.addEventListener('click', () => editStudent(s));
wrap.append(btnQr, btnEdit); tdAction.appendChild(wrap);
const tdDel = document.createElement('td'); tdDel.style.textAlign = 'center';
const btnDel = document.createElement('button'); btnDel.className = 'btn btn-sm btn-danger'; btnDel.textContent = '🗑️';
btnDel.addEventListener('click', () => delStudent(s.id)); tdDel.appendChild(btnDel);
tr.append(tdId, tdFn, tdLn, tdCls, tdSeat, tdAction, tdDel);
fragment.appendChild(tr);
});
tb.replaceChildren(fragment);
}
function prepareAddStudent() {
const hd = document.querySelector('#m-add-st .modal-hd');
if (hd) hd.innerHTML = `➕ เพิ่มนักเรียน <button class="modal-close" onclick="closeModal('m-add-st')">✕</button>`;
['ns-id','ns-fn','ns-ln','ns-cls','ns-seat','ns-email'].forEach(id => { $(id).value = ''; });
$('ns-id').readOnly = false; $('ns-id').style.opacity = '1';
openModal('m-add-st');
}
async function ensureGradeRowsForStudent(studentId, classroom) {
const roomAsgns = assignments.filter(a => a.classroom === classroom);
if (!roomAsgns.length) return;
const { data: existing } = await _sb.from('grades').select('assignment_id').eq('student_id', studentId).in('assignment_id', roomAsgns.map(a => a.id));
const existingIds = new Set((existing || []).map(g => g.assignment_id));
const newRows = roomAsgns.filter(a => !existingIds.has(a.id)).map(a => ({ student_id: studentId, assignment_id: a.id, score: null, max_score: a.max_score, status: 'not_sent' }));
if (newRows.length) {
const { error } = await _sb.from('grades').upsert(newRows, { onConflict: 'student_id,assignment_id', ignoreDuplicates: true });
if (error) console.error('ensureGradeRowsForStudent error:', error);
}
}
async function saveStudent() {
const d = { id: $('ns-id').value.trim(), first_name: $('ns-fn').value.trim(), last_name: $('ns-ln').value.trim(), classroom: $('ns-cls').value.trim(), seat_no: parseInt($('ns-seat').value) || 0, email: $('ns-email').value.trim() };
if (!d.id || !d.first_name || !d.last_name || !d.classroom) { showToast('กรุณากรอกข้อมูลให้ครบ', 'error'); return; }
try {
await gasCall('upsertStudent', d); await ensureGradeRowsForStudent(d.id, d.classroom);
closeModal('m-add-st'); showToast('บันทึกสำเร็จ', 'success');
[students, assignments] = await Promise.all([gasCall('getStudents'), gasCall('getAllAssignments')]);
populateDropdowns(); renderStudentTable();
} catch (e) { showToast('ผิดพลาด: ' + e, 'error'); }
}
function editStudent(s) {
const hd = document.querySelector('#m-add-st .modal-hd');
if (hd) hd.innerHTML = `✏️ แก้ไขข้อมูลนักเรียน <button class="modal-close" onclick="closeModal('m-add-st')">✕</button>`;
$('ns-id').value = s.id; $('ns-id').readOnly = true; $('ns-id').style.opacity = '0.6';
$('ns-fn').value = s.first_name; $('ns-ln').value = s.last_name; $('ns-cls').value = s.classroom;
$('ns-seat').value = s.seat_no; $('ns-email').value = s.email || '';
openModal('m-add-st');
}
async function delStudent(id) {
if (!confirm('ลบนักเรียนรหัส ' + id + '?')) return;
try {
await gasCall('deleteStudent', id); showToast('ลบแล้ว', 'success');
students = await gasCall('getStudents'); populateDropdowns(); renderStudentTable();
} catch (e) { showToast('ผิดพลาด: ' + e, 'error'); }
}
// ─── TEMPLATE & IMPORT ─────────────────────────────────────
function dlTemplate() {
const ws = XLSX.utils.aoa_to_sheet([['รหัสนักเรียน','ชื่อ','สกุล','ชั้น','เลขที่','อีเมล']]);
ws['!cols'] = [16,16,16,10,8,28].map(wch => ({ wch }));
const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, 'นักเรียน');
XLSX.writeFile(wb, 'template_นักเรียน.xlsx');
}
async function importFile(input) {
const file = input.files[0]; if (!file) return;
const reader = new FileReader();
reader.onload = async e => {
try {
const wb = XLSX.read(e.target.result, { type: 'binary' });
const rows = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
const list = rows.map(r => ({
id: String(r['รหัสนักเรียน'] || r['id'] || ''),
first_name: String(r['ชื่อ'] || r['first_name'] || ''),
last_name: String(r['สกุล'] || r['last_name'] || ''),
classroom: String(r['ชั้น'] || r['classroom'] || ''),
seat_no: parseInt(r['เลขที่'] || r['seat_no'] || 0),
email: String(r['อีเมล'] || r['email'] || '')
})).filter(s => s.id);
await gasCall('upsertStudents', list);
showToast('นำเข้า ' + list.length + ' คนสำเร็จ', 'success');
[students, assignments] = await Promise.all([gasCall('getStudents'), gasCall('getAllAssignments')]);
showToast('กำลังตั้งค่างานค้าง...', 'info');
for (const s of list) await ensureGradeRowsForStudent(s.id, s.classroom);
populateDropdowns(); renderStudentTable();
showToast(`✅ ตั้งค่างานค้างสำเร็จ (${list.length} คน)`, 'success');
} catch (e) { showToast('ผิดพลาด: ' + e, 'error'); }
};
reader.readAsBinaryString(file); input.value = '';
}
// ─── QR CODE ───────────────────────────────────────────────
function showQR(id, name, cls) {
$('qr-wrap').innerHTML = '';
new QRCode($('qr-wrap'), { text: id, width: 192, height: 192, colorDark: '#0f172a', colorLight: '#fff', correctLevel: QRCode.CorrectLevel.H });
$('qr-info').innerHTML = `<strong style="font-size:1.05rem">${escapeHtml(name)}</strong><br><span class="text-muted">${escapeHtml(cls)} | รหัส: ${escapeHtml(id)}</span>`;
openModal('m-qr');
}
function printQR() {
const w = window.open('', '_blank'); if (!w) { showToast('กรุณาอนุญาต Popup', 'warn'); return; }
w.document.write(`<!DOCTYPE html><html><head><title>QR</title><link href="https://fonts.googleapis.com/css2?family=Sarabun:wght@400;600&display=swap" rel="stylesheet"><style>body{font-family:'Sarabun',sans-serif;display:flex;justify-content:center;align-items:center;min-height:100vh;background:#f8fafc}.box{border:2.5px solid #0ea5e9;border-radius:18px;padding:28px 32px;text-align:center;background:#fff;box-shadow:0 4px 24px rgba(14,165,233,.18)}</style></head><body><div class="box">${$('qr-wrap').innerHTML}<div style="margin-top:12px">${$('qr-info').innerHTML}</div></div><script>window.onload=()=>window.print()<\/script></body></html>`);
w.document.close();
}
async function printAllQR() {
const room = $('f-room').value;
if (!room) { showToast('กรุณาเลือกห้องเรียนก่อน', 'warn'); return; }
const list = students.filter(s => s.classroom === room).sort((a, b) => a.seat_no - b.seat_no);
if (!list.length) { showToast('ไม่พบข้อมูลนักเรียน', 'error'); return; }
showToast('กำลังสร้าง QR...', 'info');
const tempArea = document.createElement('div');
tempArea.style.cssText = 'position:fixed;left:-9999px;top:0;visibility:hidden';
document.body.appendChild(tempArea);
let htmlContent = '';