-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathassign_tests.html
More file actions
362 lines (311 loc) · 14.1 KB
/
Copy pathassign_tests.html
File metadata and controls
362 lines (311 loc) · 14.1 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
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Assegna Nuovi Test</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>Assegna Nuovi Test</h2>
<label for="studentDropdown">Seleziona Studente:</label>
<select id="studentDropdown"></select>
<h3>Test non ancora assegnati:</h3>
<div id="unassignedTests"></div>
<button id="assignSelectedTests">Assegna Test</button>
<h3>Test d'ingresso non ancora assegnati:</h3>
<div id="unassignedIngressoTests"></div>
<button id="assignIngressoTests">Assegna Test d'ingresso</button>
<script type="module">
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
// Updated Supabase key to match tutor_dashboard.html
const supabase = createClient(
"https://elrwpaezjnemmiegkyin.supabase.co",
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImVscndwYWV6am5lbW1pZWdreWluIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzgwNzAyMDUsImV4cCI6MjA1MzY0NjIwNX0.p6R2S1HK8kPFYiEAYtYaxIAH8XSmzjQBWQ_ywy3akdI"
);
// Declare global variables
let globalStudentId = null;
let globalStudentTests = [];
// Helper: Get the logged in tutor's id.
async function getTutorId() {
const { data: userData, error: authError } = await supabase.auth.getUser();
if (authError || !userData || !userData.user) {
console.error("❌ Error getting authenticated tutor:", authError);
alert("Session expired. Please log in again.");
window.location.href = "login.html";
return null;
}
const authUid = userData.user.id;
const { data: tutorData, error: tutorError } = await supabase
.from("tutors")
.select("id")
.eq("auth_uid", authUid)
.single();
if (tutorError || !tutorData) {
console.error("❌ Error fetching tutor ID:", tutorError);
alert("Tutor account not found.");
window.location.href = "login.html";
}
return tutorData.id;
}
async function loadStudents() {
const tutorId = await getTutorId();
if (!tutorId) return;
// Fetch auth_uid and name from students
const { data: students, error } = await supabase
.from("students")
.select("auth_uid, name, tests")
.eq("tutor_id", tutorId);
//const studentTests = students.map(student => student.tests);
//console.log("Student tests:", studentTests);
//if (error) {
// console.error("❌ Error fetching students:", error.message);
// return;
//}
// 1) Populate dropdown:
students.forEach(student => {
const option = document.createElement("option");
option.value = student.auth_uid;
option.textContent = student.name;
// Save this student's tests in a data attribute:
option.dataset.tests = JSON.stringify(student.tests || []);
studentDropdown.appendChild(option);
});
// 2) After populating, pick the first student's tests:
const firstOption = studentDropdown.options[0];
const firstStudentTests = JSON.parse(firstOption.dataset.tests || "[]");
fetchUnassignedTests(firstStudentTests);
fetchUnassignedTestIngresso(firstStudentTests);
// 3) On dropdown change:
studentDropdown.addEventListener("change", () => {
const selectedOption = studentDropdown.selectedOptions[0];
const testsForThisStudent = JSON.parse(selectedOption.dataset.tests || "[]");
fetchUnassignedTests(testsForThisStudent);
fetchUnassignedTestIngresso(testsForThisStudent);
});
}
async function fetchUnassignedTests(studentTests) {
const studentId = document.getElementById("studentDropdown").value;
console.log("Selected student:", studentId);
if (!studentId) return;
// Fetch tests already assigned to the student.
const { data: assignedTests, error: assignedError } = await supabase
.from("student_tests")
.select("section, tipologia_esercizi, progressivo, tipologia_test")
.in("tipologia_test", studentTests)
.eq("auth_uid", studentId);
if (assignedError) {
console.error("❌ Error fetching assigned tests:", assignedError.message);
return;
}
// Build a set of composite keys for assigned tests.
const assignedCompositeSet = new Set();
(assignedTests || []).forEach(test => {
const key = `${test.section}-${test.tipologia_esercizi}-${test.progressivo}-${test.tipologia_test}`;
assignedCompositeSet.add(key);
});
// Query available tests from "questions"
let { data: availableTests, error: availableError } = await supabase
.from("questions")
.select("section, tipologia_esercizi, progressivo, tipologia_test")
.in("tipologia_test", studentTests);
// Query available tests from "questions_bancaDati"
// For bocconi tests, if "tipologia_esercizi" is missing, set it to "BOCCONI" and default progressivo to 1.
let { data: bocconiTests, error: bocconiError } = await supabase
.from("questions_bancaDati")
.select("section, tipologia_esercizi, tipologia_test")
.in("tipologia_test", studentTests);
if (availableError || bocconiError) {
console.error("❌ Error fetching unassigned tests:", availableError?.message || bocconiError?.message);
return;
}
// Transform availableTests rows to include composite key and composite name.
const tests1 = (availableTests || []).map(test => {
const compositeKey = `${test.section}-${test.tipologia_esercizi}-${test.progressivo}-${test.tipologia_test}`;
return {
section: test.section,
tipologia_esercizi: test.tipologia_esercizi,
progressivo: test.progressivo,
tipologia_test: test.tipologia_test,
compositeKey,
compositeName: `${test.section}: ${test.tipologia_esercizi} ${test.progressivo} of ${test.tipologia_test}`
};
});
// Transform bocconiTests rows – apply default values.
const tests2 = (bocconiTests || []).map(test => {
const tipologia_esercizi = test.tipologia_esercizi ? test.tipologia_esercizi : "BOCCONI";
const progressivo = 1; // default for bocconi tests
const compositeKey = `${test.section}-${tipologia_esercizi}-${progressivo}-${test.tipologia_test}`;
return {
section: test.section,
tipologia_esercizi: tipologia_esercizi,
progressivo: progressivo,
tipologia_test: test.tipologia_test,
compositeKey,
compositeName: `${test.section}: ${tipologia_esercizi} ${progressivo} of ${test.tipologia_test}`
};
});
// Combine tests from both sources.
const combinedTests = [...tests1, ...tests2];
// Filter out tests that are already assigned (by composite key).
const unassignedTests = combinedTests.filter(test => !assignedCompositeSet.has(test.compositeKey));
// Further deduplicate tests based on the composite key.
const uniqueTestsMap = new Map();
unassignedTests.forEach(test => {
uniqueTestsMap.set(test.compositeKey, test);
});
const uniqueTests = Array.from(uniqueTestsMap.values());
const testContainer = document.getElementById("unassignedTests");
testContainer.innerHTML = "";
uniqueTests.forEach(test => {
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = test.compositeKey;
// Use a safe ID (replace spaces and special characters)
checkbox.id = `test-${test.compositeKey.replace(/\W/g, '')}`;
// Store individual fields as data attributes
checkbox.dataset.section = test.section;
checkbox.dataset.tipologiaEs = test.tipologia_esercizi;
checkbox.dataset.progressivo = test.progressivo;
checkbox.dataset.tipologiaTest = test.tipologia_test;
const label = document.createElement("label");
label.htmlFor = checkbox.id;
label.textContent = test.compositeName;
testContainer.appendChild(checkbox);
testContainer.appendChild(label);
testContainer.appendChild(document.createElement("br"));
});
}
async function fetchUnassignedTestIngresso(studentTests) {
// Query tipologia_test from the "questions" table.
const { data: questionsData, error: questionsError } = await supabase
.from("questions")
.select("tipologia_test");
if (questionsError) {
console.error("Error fetching tests from questions:", questionsError.message);
return;
}
// Query tipologia_test from the "questions_bancaDati" table.
const { data: bocconiData, error: bocconiError } = await supabase
.from("questions_bancaDati")
.select("tipologia_test");
if (bocconiError) {
console.error("Error fetching tests from questions_bancaDati:", bocconiError.message);
return;
}
// Combine both results and deduplicate.
let allTests = [];
if (questionsData) {
allTests = allTests.concat(questionsData.map(item => item.tipologia_test));
}
if (bocconiData) {
allTests = allTests.concat(bocconiData.map(item => item.tipologia_test));
}
const uniqueTests = [...new Set(allTests)];
console.log("Unique ingresso tests:", uniqueTests);
console.log("Student tests:", studentTests);
// Filter out tests that already appear in the studentTests array.
const unassignedTests = uniqueTests.filter(test => !studentTests.includes(test));
console.log("Unassigned ingresso tests:", unassignedTests);
// Display these choices in a container.
const container = document.getElementById("unassignedIngressoTests");
if (!container) {
console.error("Container for unassigned ingresso tests not found.");
return;
}
container.innerHTML = ""; // Clear previous content
unassignedTests.forEach(test => {
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = test;
// Create a safe ID by removing non-word characters.
checkbox.id = "ingresso-" + test.replace(/\W/g, '');
const label = document.createElement("label");
label.htmlFor = checkbox.id;
label.textContent = test;
container.appendChild(checkbox);
container.appendChild(label);
container.appendChild(document.createElement("br"));
});
}
async function assignTests() {
const studentId = document.getElementById("studentDropdown").value;
if (!studentId) return;
const selectedCheckboxes = Array.from(document.querySelectorAll("#unassignedTests input:checked"));
if (selectedCheckboxes.length === 0) {
alert("Seleziona almeno un test!");
return;
}
// Map each selected checkbox to an entry including all required fields.
const testEntries = selectedCheckboxes.map(checkbox => ({
auth_uid: studentId,
section: checkbox.dataset.section,
tipologia_esercizi: checkbox.dataset.tipologiaEs,
progressivo: Number(checkbox.dataset.progressivo),
tipologia_test: checkbox.dataset.tipologiaTest,
status: "locked"
}));
console.log("Assigning tests:", testEntries);
const { error } = await supabase
.from("student_tests")
.insert(testEntries);
if (error) {
console.error("❌ Error assigning tests:", error.message);
alert("Errore nell'assegnazione dei test.");
return;
}
alert("✅ Test assegnati con successo!");
window.location.reload();
}
// Function to assign ingresso tests: append the selected ingresso tests to the student's tests array.
async function assignTestIngresso() {
const studentId = document.getElementById("studentDropdown").value;
if (!studentId) return;
const selectedCheckboxes = Array.from(document.querySelectorAll("#unassignedIngressoTests input:checked"));
if (selectedCheckboxes.length === 0) {
alert("Seleziona almeno un test d'ingresso!");
return;
}
const selectedTests = selectedCheckboxes.map(cb => cb.value);
// Fetch current tests from the student's record.
const { data: studentData, error: studentError } = await supabase
.from("students")
.select("tests")
.eq("auth_uid", studentId)
.single();
if (studentError || !studentData) {
console.error("Error fetching student data:", studentError?.message);
alert("Errore nel recupero dei dati dello studente.");
return;
}
const currentTests = studentData.tests || [];
const newTests = selectedTests.filter(test => !currentTests.includes(test));
if (newTests.length === 0) {
alert("I test d'ingresso selezionati sono già assegnati.");
return;
}
const updatedTests = currentTests.concat(newTests);
const { error } = await supabase
.from("students")
.update({ tests: updatedTests })
.eq("auth_uid", studentId);
if (error) {
console.error("Error updating student's tests:", error.message);
alert("Errore nell'assegnazione dei test d'ingresso.");
return;
}
alert("✅ Test d'ingresso assegnati con successo!");
fetchUnassignedTestIngresso(updatedTests);
window.location.reload();
}
document.getElementById("studentDropdown").addEventListener("change", async () => {
const tests = JSON.parse(document.getElementById("studentDropdown").selectedOptions[0].dataset.tests || "[]");
await fetchUnassignedTests(tests);
await fetchUnassignedTestIngresso(tests);
});
document.getElementById("assignSelectedTests").addEventListener("click", assignTests);
document.getElementById("assignIngressoTests").addEventListener("click", assignTestIngresso);
loadStudents();
</script>
</body>
</html>