-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdashboard.js
More file actions
769 lines (694 loc) · 26.8 KB
/
Copy pathdashboard.js
File metadata and controls
769 lines (694 loc) · 26.8 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
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
const SUPABASE_URL = "https://elrwpaezjnemmiegkyin.supabase.co";
const SUPABASE_KEY =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImVscndwYWV6am5lbW1pZWdreWluIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzgwNzAyMDUsImV4cCI6MjA1MzY0NjIwNX0.p6R2S1HK8kPFYiEAYtYaxIAH8XSmzjQBWQ_ywy3akdI";
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
const studentId = sessionStorage.getItem("selectedStudentId");
const studentName = sessionStorage.getItem("selectedStudentName");
const globalTestType = sessionStorage.getItem("selectedTestType");
document.getElementById("dashboardTitle").textContent = `Risultati dei test di ${studentName}`;
if (!studentId) {
alert("Error: No student selected.");
window.location.href = "tutor_dashboard.html";
}
// Global variables for fetched data and chart instances.
let globalAnswers = [];
let globalQuestions = [];
let studentTestsData = []; // Data from student_tests for the current student & test type.
async function loadDashboard() {
// Make sure all filters are visible.
document.getElementById("sectionFilter").style.display = "inline-block";
document.getElementById("tipologiaFilter").style.display = "inline-block";
document.getElementById("progressivoFilter").style.display = "inline-block";
document.getElementById("argomentoFilter").style.display = "inline-block";
// Determine answer and question tables based on globalTestType.
const answerTable = globalTestType.includes("PDF")
? "student_answers"
: "studentbocconi_answers";
const questionTable = globalTestType.includes("PDF")
? "questions"
: "questions_bancaDati";
// Fetch student answers including the submitted_at timestamp.
const { data: answers, error: answersError } = await supabase
.from(answerTable)
.select("answer, auto_score, question_id, submitted_at, test_id")
.eq("auth_uid", studentId);
if (answersError) {
console.error("❌ Error fetching student answers:", answersError.message);
return;
}
// Fetch questions.
const { data: questions, error: questionsError } = await supabase
.from(questionTable)
.select("id, section, tipologia_esercizi, progressivo, argomento")
.eq("tipologia_test", globalTestType);
if (questionsError) {
console.error("❌ Error fetching questions:", questionsError.message);
return;
}
globalAnswers = answers;
globalQuestions = questions;
// Fetch student_tests data.
const { data: testsData, error: testsError } = await supabase
.from("student_tests")
.select("section, tipologia_esercizi, progressivo, status, id")
.eq("auth_uid", studentId)
.eq("tipologia_test", globalTestType);
if (testsError) {
console.error("❌ Error fetching student_tests data:", testsError.message);
return;
}
studentTestsData = testsData;
populateFiltersFromStudentTests(studentTestsData);
document.getElementById("sectionFilter").addEventListener("change", () => {
populateDependentFilters();
filterDashboard();
updateInteractiveTable();
});
document.getElementById("tipologiaFilter").addEventListener("change", () => {
filterDashboard();
updateInteractiveTable();
});
document.getElementById("progressivoFilter").addEventListener("change", () => {
filterDashboard();
updateInteractiveTable();
});
document.getElementById("argomentoFilter").addEventListener("change", () => {
filterDashboard();
updateInteractiveTable();
});
filterDashboard();
updateInteractiveTable();
// After updating the interactive table...
populateLinePlotFilter();
updateLineChart();
// Also attach event listeners.
document.getElementById("sectionFilter").addEventListener("change", updateLineChart);
document.getElementById("tipologiaFilter").addEventListener("change", updateLineChart);
document.getElementById("progressivoFilter").addEventListener("change", updateLineChart);
document.getElementById("linePlotArgomentoFilter").addEventListener("change", updateLineChart);
}
function populateFiltersFromStudentTests(testsData) {
const sectionFilter = document.getElementById("sectionFilter");
const tipologiaFilter = document.getElementById("tipologiaFilter");
const progressivoFilter = document.getElementById("progressivoFilter");
const argomentoFilter = document.getElementById("argomentoFilter");
const completedTests = testsData.filter(test => test.status === "completed");
sectionFilter.innerHTML = `<option value="all">Tutte le Sezioni</option>`;
tipologiaFilter.innerHTML = `<option value="all">Tutte le Tipologie</option>`;
progressivoFilter.innerHTML = `<option value="all">Tutti i Progressivi</option>`;
argomentoFilter.innerHTML = `<option value="all">Tutti gli Argomenti</option>`;
const sections = Array.from(new Set(completedTests.map(test => test.section)));
const tipologie = Array.from(new Set(completedTests.map(test => test.tipologia_esercizi)));
const progressivi = Array.from(new Set(completedTests.map(test => test.progressivo)));
sections.forEach(s => {
sectionFilter.innerHTML += `<option value="${s}">${s}</option>`;
});
tipologie.forEach(t => {
tipologiaFilter.innerHTML += `<option value="${t}">${t}</option>`;
});
progressivi.forEach(p => {
progressivoFilter.innerHTML += `<option value="${p}">${p}</option>`;
});
}
function populateDependentFilters() {
const sectionVal = document.getElementById("sectionFilter").value;
const tipologiaFilter = document.getElementById("tipologiaFilter");
const progressivoFilter = document.getElementById("progressivoFilter");
const argomentoFilter = document.getElementById("argomentoFilter");
let filteredTests = studentTestsData.filter(test => test.status === "completed");
if (sectionVal !== "all") {
filteredTests = filteredTests.filter(test => test.section.toString() === sectionVal);
}
tipologiaFilter.innerHTML = `<option value="all">Tutte le Tipologie</option>`;
progressivoFilter.innerHTML = `<option value="all">Tutti i Progressivi</option>`;
const tipologie = Array.from(new Set(filteredTests.map(test => test.tipologia_esercizi)));
const progressivi = Array.from(new Set(filteredTests.map(test => test.progressivo)));
tipologie.forEach(t => {
tipologiaFilter.innerHTML += `<option value="${t}">${t}</option>`;
});
progressivi.forEach(p => {
progressivoFilter.innerHTML += `<option value="${p}">${p}</option>`;
});
let filteredQuestions = globalQuestions;
if (sectionVal !== "all") {
filteredQuestions = filteredQuestions.filter(q => q.section.toString() === sectionVal);
}
argomentoFilter.innerHTML = `<option value="all">Tutti gli Argomenti</option>`;
const argomenti = Array.from(new Set(filteredQuestions.map(q => q.argomento).filter(a => a)));
argomenti.forEach(a => {
argomentoFilter.innerHTML += `<option value="${a}">${a}</option>`;
});
}
function filterDashboard() {
const sectionVal = document.getElementById("sectionFilter").value;
const tipologiaVal = document.getElementById("tipologiaFilter").value;
const progressivoVal = document.getElementById("progressivoFilter").value;
const argomentoVal = document.getElementById("argomentoFilter").value;
const scoreDisplay = document.getElementById("scoreDisplay");
const scoreDisplay2 = document.getElementById("scoreDisplay2");
let filteredTests = studentTestsData.filter(test => test.status === "completed");
if (sectionVal !== "all") {
filteredTests = filteredTests.filter(q => q.section.toString() === sectionVal);
}
if (tipologiaVal !== "all") {
filteredTests = filteredTests.filter(q => Number(q.tipologia_esercizi) === Number(tipologiaVal));
}
if (progressivoVal !== "all") {
filteredTests = filteredTests.filter(q => Number(q.progressivo) === Number(progressivoVal));
}
let filteredQuestions = globalQuestions;
if (sectionVal !== "all") {
filteredQuestions = filteredQuestions.filter(q => q.section.toString() === sectionVal);
}
if (argomentoVal !== "all") {
filteredQuestions = filteredQuestions.filter(q => q.argomento.toString() === argomentoVal);
}
if (progressivoVal !== "all") {
filteredQuestions = filteredQuestions.filter(q => Number(q.progressivo) === Number(progressivoVal));
}
const allowedQuestionIds = new Set(filteredQuestions.map(q => q.id));
const filteredAnswers = globalAnswers.filter(ans => allowedQuestionIds.has(ans.question_id));
// Assuming 'filteredAnswers' is already computed:
let correctCount = 0, incorrectCount = 0, insicuroCount = 0, nonHoIdeaCount = 0, nonDatoCount = 0;
filteredAnswers.forEach(d => {
if (d.auto_score === 1) {
correctCount++;
} else if (d.auto_score === 0 && !["x", "y", "z"].includes(d.answer)) {
incorrectCount++;
} else if (d.answer === "x") {
insicuroCount++;
} else if (d.answer === "y") {
nonHoIdeaCount++;
} else {
nonDatoCount++;
}
});
updateEChartsPie(correctCount, incorrectCount, insicuroCount, nonHoIdeaCount, nonDatoCount);
if (
sectionVal != "all" &&
tipologiaVal != "all" &&
progressivoVal != "all" &&
argomentoVal === "all"
) {
const score = calculateScore(filteredAnswers, 1);
scoreDisplay.textContent = `Score (1 for correct, 0 otherwise): ${score}`;
const score2 = calculateScore(filteredAnswers, 2);
scoreDisplay2.textContent = `Score (1 for correct, -0.25 for incorrect, 0 otherwise): ${score2}`;
scoreDisplay.style.display = "block";
scoreDisplay2.style.display = "block";
} else {
scoreDisplay.style.display = "none";
scoreDisplay2.style.display = "none";
}
}
function calculateScore(answers, modality) {
let score = 0;
answers.forEach(ans => {
if (modality === 1) {
score += ans.auto_score === 1 ? 1 : 0;
} else if (modality === 2) {
if (ans.auto_score === 1) {
score += 1;
} else if (ans.auto_score === 0 && !["x", "y", "z"].includes(ans.answer)) {
score -= 0.25;
}
}
});
return score;
}
function goBack() {
window.history.back();
}
// Build a nested header structure for the interactive table.
function buildHeaderStructureInt(questionsData) {
const structure = {};
questionsData.forEach(q => {
if (!structure[q.section]) {
structure[q.section] = {};
}
if (!structure[q.section][q.tipologia_esercizi]) {
structure[q.section][q.tipologia_esercizi] = new Set();
}
structure[q.section][q.tipologia_esercizi].add(q.progressivo);
});
for (const section in structure) {
for (const tipologia in structure[section]) {
structure[section][tipologia] = Array.from(structure[section][tipologia]).sort((a, b) => a - b);
}
}
return structure;
}
// Flatten header structure into an ordered array.
function buildHeaderDefinitionsInt(structure) {
const headerDefs = [];
const sections = Object.keys(structure).sort();
sections.forEach(section => {
const tipologie = Object.keys(structure[section]).sort();
tipologie.forEach(tipologia => {
structure[section][tipologia].forEach(progressivo => {
headerDefs.push({ section, tipologia, progressivo });
});
});
});
return headerDefs;
}
function generateInteractiveTable(questionsData, answersData) {
const container = document.getElementById("interactiveTableContainer");
container.innerHTML = "";
const table = document.createElement("table");
const displayAll = true;
const headerStructure = buildHeaderStructureInt(questionsData);
const headerDefs = buildHeaderDefinitionsInt(headerStructure);
const thead = document.createElement("thead");
// Header Row 1: Sections
const headerRow1 = document.createElement("tr");
const emptyTh = document.createElement("th");
emptyTh.rowSpan = 4;
emptyTh.textContent = "";
headerRow1.appendChild(emptyTh);
Object.keys(headerStructure).sort().forEach(section => {
let colCount = 0;
const tipologie = headerStructure[section];
for (const tipologia in tipologie) {
colCount += tipologie[tipologia].length * (displayAll ? 5 : 1);
}
const th = document.createElement("th");
th.textContent = section;
th.colSpan = colCount;
headerRow1.appendChild(th);
});
thead.appendChild(headerRow1);
// Header Row 2: Tipologia
const headerRow2 = document.createElement("tr");
Object.keys(headerStructure).sort().forEach(section => {
const tipologie = headerStructure[section];
Object.keys(tipologie).sort().forEach(tipologia => {
const colCount = tipologie[tipologia].length * (displayAll ? 5 : 1);
const th = document.createElement("th");
th.textContent = tipologia;
th.colSpan = colCount;
headerRow2.appendChild(th);
});
});
thead.appendChild(headerRow2);
// Header Row 3: Progressivo
const headerRow3 = document.createElement("tr");
Object.keys(headerStructure).sort().forEach(section => {
const tipologie = headerStructure[section];
Object.keys(tipologie).sort().forEach(tipologia => {
tipologie[tipologia].forEach(progressivo => {
const th = document.createElement("th");
th.textContent = progressivo;
th.colSpan = (displayAll ? 5 : 1);
th.classList.add("double-border-right");
headerRow3.appendChild(th);
});
});
});
thead.appendChild(headerRow3);
// Header Row 4: Answers
const headerRow4 = document.createElement("tr");
headerDefs.forEach(() => {
if (displayAll) {
["Corretto", "Incorretto", "Insicuro", "Non ho idea", "Non dato"].forEach(label => {
const th = document.createElement("th");
th.textContent = label;
headerRow4.appendChild(th);
});
} else {
const labels = ["Corretto", "Incorretto", "Insicuro", "Non ho idea", "Non dato"];
const th = document.createElement("th");
th.textContent = labels[selectedIndex];
if (selectedIndex === 4) { // After last answer category
th.classList.add("double-border-right");
}
headerRow4.appendChild(th);
}
});
thead.appendChild(headerRow4);
table.appendChild(thead);
// Body
const tbody = document.createElement("tbody");
const answersMap = {};
answersData.forEach(ans => {
answersMap[ans.question_id] = ans;
});
const questionsMap = {};
questionsData.forEach(q => {
const key = q.section + "|" + q.tipologia_esercizi + "|" + q.progressivo + "|" + q.argomento;
if (!questionsMap[key]) {
questionsMap[key] = [];
}
questionsMap[key].push(q);
});
const argomenti = Array.from(new Set(questionsData.map(q => q.argomento))).sort();
const totals = {};
headerDefs.forEach((def, idx) => {
totals[idx] = displayAll ? [0, 0, 0, 0, 0] : [0];
});
argomenti.forEach(argomento => {
const tr = document.createElement("tr");
const thArg = document.createElement("th");
thArg.textContent = argomento;
tr.appendChild(thArg);
headerDefs.forEach((def, idx) => {
const key = def.section + "|" + def.tipologia + "|" + def.progressivo + "|" + argomento;
const counts = [0, 0, 0, 0, 0];
if (questionsMap[key]) {
questionsMap[key].forEach(q => {
const ansRecord = answersMap[q.id];
if (ansRecord) {
if (ansRecord.auto_score === 1) counts[0]++;
else if (ansRecord.answer === "x") counts[2]++;
else if (ansRecord.answer === "y") counts[3]++;
else if (ansRecord.answer === "z") counts[4]++;
else counts[1]++;
}
});
}
const total = counts.reduce((a, b) => a + b, 0);
if (displayAll) {
for (let i = 0; i < 5; i++) {
const td = document.createElement("td");
if (total === 0) {
td.textContent = "-";
} else {
if (counts[i] === 0) {
td.textContent = "0";
} else {
td.textContent = `${counts[i]} (${((counts[i] / total) * 100).toFixed(0)}%)`;
}
}
if (counts[i] > 0) {
if (i === 0) td.classList.add("correct-light");
if (i === 1) td.classList.add("incorrect-light");
if (i === 2) td.classList.add("x-answer-light");
if (i === 3) td.classList.add("y-answer-light");
if (i === 4) td.classList.add("z-answer-light");
totals[idx][i] += counts[i];
}
if (i === 4) { // After last column of a progressivo
td.classList.add("double-border-right");
}
tr.appendChild(td);
}
} else {
const td = document.createElement("td");
if (total === 0) {
td.textContent = "-";
} else {
if (counts[selectedIndex] > 0) {
td.textContent = `${counts[selectedIndex]} (${((counts[selectedIndex] / total) * 100).toFixed(0)}%)`;
} else {
td.textContent = counts[selectedIndex];
}
}
if (counts[selectedIndex] > 0) {
if (selectedIndex === 0) td.classList.add("correct-light");
if (selectedIndex === 1) td.classList.add("incorrect-light");
if (selectedIndex === 2) td.classList.add("x-answer-light");
if (selectedIndex === 3) td.classList.add("y-answer-light");
if (selectedIndex === 4) td.classList.add("z-answer-light");
totals[idx][0] += counts[selectedIndex];
}
tr.appendChild(td);
}
});
tbody.appendChild(tr);
});
// Totals Row
const totalTr = document.createElement("tr");
const thTotal = document.createElement("th");
thTotal.textContent = "Totale";
totalTr.appendChild(thTotal);
headerDefs.forEach((def, idx) => {
if (displayAll) {
const sumTotal = totals[idx].reduce((a, b) => a + b, 0);
for (let i = 0; i < 5; i++) {
const td = document.createElement("td");
if (sumTotal === 0) {
td.textContent = "-";
} else {
if (totals[idx][i] > 0) {
td.textContent = `${totals[idx][i]} (${((totals[idx][i] / sumTotal) * 100).toFixed(0)}%)`;
}
else {
td.textContent = totals[idx][i];
}
}
if (totals[idx][i] > 0) {
if (i === 0) td.classList.add("corretto");
if (i === 1) td.classList.add("incorretto");
if (i === 2) td.classList.add("x-answer");
if (i === 3) td.classList.add("y-answer");
if (i === 4) td.classList.add("z-answer");
}
if (i === 4) { // After last column of a progressivo
td.classList.add("double-border-right");
}
totalTr.appendChild(td);
}
} else {
const td = document.createElement("td");
const val = totals[idx][0];
if (val === 0) {
td.textContent = "-";
} else {
td.textContent = `${val} (100%)`;
}
if (val > 0) {
if (selectedIndex === 0) td.classList.add("corretto");
if (selectedIndex === 1) td.classList.add("incorretto");
if (selectedIndex === 2) td.classList.add("x-answer");
if (selectedIndex === 3) td.classList.add("y-answer");
if (selectedIndex === 4) td.classList.add("z-answer");
}
totalTr.appendChild(td);
}
});
tbody.appendChild(totalTr);
table.appendChild(tbody);
container.appendChild(table);
}
function filterInteractiveTable() {
// Use common filters.
const sectionVal = document.getElementById("sectionFilter").value;
const tipologiaVal = document.getElementById("tipologiaFilter").value;
const progressivoVal = document.getElementById("progressivoFilter").value;
const argomentoVal = document.getElementById("argomentoFilter").value;
let filteredQuestions = globalQuestions.slice();
if (sectionVal !== "all") {
filteredQuestions = filteredQuestions.filter(q => q.section === sectionVal);
}
if (tipologiaVal !== "all") {
filteredQuestions = filteredQuestions.filter(q => q.tipologia_esercizi === tipologiaVal);
}
if (progressivoVal !== "all") {
filteredQuestions = filteredQuestions.filter(q => q.progressivo === Number(progressivoVal));
}
if (argomentoVal !== "all") {
filteredQuestions = filteredQuestions.filter(q => q.argomento === argomentoVal);
}
const filteredAnswers = globalAnswers.filter(a =>
filteredQuestions.some(q => q.id === a.question_id)
);
return { filteredQuestions, filteredAnswers };
}
function updateInteractiveTable() {
const { filteredQuestions, filteredAnswers } = filterInteractiveTable();
generateInteractiveTable(filteredQuestions, filteredAnswers);
}
function updateEChartsPie(correctCount, incorrectCount, insicuroCount, nonHoIdeaCount, nonDatoCount) {
const chartDom = document.getElementById('echartsPieContainer');
const myChart = echarts.init(chartDom);
const option = {
backgroundColor: '#2c343c',
tooltip: {
trigger: 'item',
formatter: '{b}: {c} ({d}%)'
},
series: [
{
name: 'Answers',
type: 'pie',
radius: ['40%', '70%'], // Inner radius and outer radius
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2,
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
},
label: {
show: true,
position: 'outside',
fontSize: 16,
color: '#fff',
formatter: '{b}: {d}%'
},
labelLine: {
show: true,
length: 20,
length2: 30,
smooth: true,
lineStyle: {
width: 2
}
},
emphasis: {
scale: true,
scaleSize: 10,
itemStyle: {
shadowBlur: 30,
shadowColor: 'rgba(0, 0, 0, 0.8)'
}
},
data: [
{ value: correctCount, name: 'Corretto', itemStyle: { color: '#4CAF50' } },
{ value: incorrectCount, name: 'Incorretto', itemStyle: { color: '#F44336' } },
{ value: insicuroCount, name: 'Insicuro', itemStyle: { color: '#2196F3' } },
{ value: nonHoIdeaCount, name: 'Non ho idea', itemStyle: { color: '#FFC107' } },
{ value: nonDatoCount, name: 'Non dato', itemStyle: { color: '#9E9E9E' } }
]
}
]
};
myChart.setOption(option);
}
function populateLinePlotFilter() {
const lineFilter = document.getElementById("linePlotArgomentoFilter");
lineFilter.innerHTML = "";
lineFilter.innerHTML += `<option value="Totale">Totale</option>`;
// Get all unique argomenti from all questions.
const argomenti = Array.from(new Set(globalQuestions.map(q => q.argomento).filter(a => a)));
argomenti.forEach(arg => {
lineFilter.innerHTML += `<option value="${arg}">${arg}</option>`;
});
}
function updateLineChart() {
// Use all global answers (line graph is independent of the common filters)
let filteredAnswers = globalAnswers;
// Filter by argomento if a specific one is selected
const selectedLineArg = document.getElementById("linePlotArgomentoFilter").value;
if (selectedLineArg !== "Totale") {
// Create a lookup from question_id to its details.
const questionsMap = {};
globalQuestions.forEach(q => { questionsMap[q.id] = q; });
filteredAnswers = filteredAnswers.filter(ans => {
const q = questionsMap[ans.question_id];
return q && q.argomento && q.argomento.toString() === selectedLineArg;
});
}
// Group the answers by test_id.
const groupedByTest = {};
filteredAnswers.forEach(ans => {
const testId = ans.test_id || "unknown";
if (!groupedByTest[testId]) {
groupedByTest[testId] = [];
}
groupedByTest[testId].push(ans);
});
// Build an array of test groups with their earliest submitted_at date.
const testGroups = [];
for (let testId in groupedByTest) {
const testAnswers = groupedByTest[testId];
// Get the earliest submitted_at in this test group.
const earliest = testAnswers.reduce((min, curr) => {
return (!min || curr.submitted_at < min) ? curr.submitted_at : min;
}, null);
testGroups.push({ testId, earliest });
}
// Sort the test groups by their earliest submitted_at date.
testGroups.sort((a, b) => a.earliest.localeCompare(b.earliest));
// Create a sorted list of testIds based on the sorted groups.
const sortedTestIds = testGroups.map(group => group.testId);
// Define the answer categories.
const categories = ["Corretto", "Incorretto", "Insicuro", "Non ho idea", "Non dato"];
// Prepare an object to store the series data per category.
const seriesData = {
"Corretto": [],
"Incorretto": [],
"Insicuro": [],
"Non ho idea": [],
"Non dato": []
};
// Prepare the x-axis labels array.
const xLabels = [];
// For each test group (in chronological order), compute percentages and build the label.
sortedTestIds.forEach(testId => {
const answersForTest = groupedByTest[testId];
let counts = [0, 0, 0, 0, 0]; // Order: Corretto, Incorretto, Insicuro, Non ho idea, Non dato.
answersForTest.forEach(ans => {
if (ans.auto_score === 1) {
counts[0]++;
} else if (ans.auto_score === 0 && !["x", "y", "z"].includes(ans.answer)) {
counts[1]++;
} else if (ans.answer === "x") {
counts[2]++;
} else if (ans.answer === "y") {
counts[3]++;
} else if (ans.answer === "z") {
counts[4]++;
}
});
const total = counts.reduce((a, b) => a + b, 0);
// Calculate percentages.
const percentages = counts.map(c => total > 0 ? Number(((c / total) * 100).toFixed(0)) : 0);
categories.forEach((cat, idx) => {
seriesData[cat].push(percentages[idx]);
});
// Lookup the associated test record from student_tests (studentTestsData is assumed to be loaded).
const testRecord = studentTestsData.find(t => String(t.id) === testId);
if (testRecord) {
// Build a label: first line shows the section,
// second line shows tipologia_esercizi and progressivo.
const label = `${testRecord.section}\n${testRecord.tipologia_esercizi} ${testRecord.progressivo}`;
xLabels.push(label);
} else {
xLabels.push(testId);
}
});
// Use the same colour mapping as used in your pie chart and table.
const colorMap = {
"Corretto": "#4CAF50",
"Incorretto": "#F44336",
"Insicuro": "#2196F3",
"Non ho idea": "#FFC107",
"Non dato": "#9E9E9E"
};
// Initialize or update the line chart using ECharts.
const lineChartDom = document.getElementById("lineChartContainer");
const lineChart = echarts.init(lineChartDom);
const option = {
tooltip: { trigger: 'axis' },
legend: { data: categories, textStyle: { color: "#333" } },
xAxis: {
type: 'category',
data: xLabels,
axisLabel: {
// Using newlines in labels; the formatter returns the label as it is.
formatter: function(value) {
return value;
}
}
},
yAxis: {
type: 'value',
name: 'Percentuale',
max: 100
},
series: categories.map(cat => ({
name: cat,
type: 'line',
data: seriesData[cat],
smooth: true,
itemStyle: { color: colorMap[cat] }
}))
};
lineChart.setOption(option);
}
loadDashboard();
window.goBack = goBack;