laureen Claude Opus 5.5 commited on
Commit ·
21023ea
1
Parent(s): 0361d73
Open the assessment with a quiz that unlocks the exercises
Browse filesThe quiz answers are emailed when the student clicks "Terminer le quiz";
the backend then remembers it is finished so it cannot be reopened.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- app/.env.static +2 -2
- app/apps-script/Code.gs +62 -4
- app/server/exam.mjs +34 -13
- app/server/examCatalogue.mjs +8 -0
- app/src/training/useExam.js +22 -1
- app/src/ui/CodeTraining.jsx +4 -3
- app/src/ui/ExamPanel.jsx +25 -8
- app/src/ui/codeTraining.css +12 -1
- app/test/apps-script.test.js +26 -0
- app/test/appsScriptHarness.js +1 -1
- app/test/browser/exam-apps-script.spec.js +47 -7
- app/test/browser/exam.spec.js +10 -2
- app/test/exam.test.js +24 -0
- docs/exam-apps-script.md +9 -1
app/.env.static
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# Build settings for the static Hugging Face Space (npm run build -- --mode static).
|
| 2 |
# Assessment backend: the Google Apps Script web app URL (docs/exam-apps-script.md).
|
| 3 |
-
VITE_EXAM_ENDPOINT=
|
| 4 |
# Set to true once VITE_EXAM_ENDPOINT is filled in.
|
| 5 |
-
VITE_EXAM_ENABLED=
|
|
|
|
| 1 |
# Build settings for the static Hugging Face Space (npm run build -- --mode static).
|
| 2 |
# Assessment backend: the Google Apps Script web app URL (docs/exam-apps-script.md).
|
| 3 |
+
VITE_EXAM_ENDPOINT=https://script.google.com/macros/s/AKfycbxHTZfb2abrBU-Qsa27TcxyEo4xMygNXhQHrk0bGbPG4EBfQuybtRO3VJ-hpX82q9x-/exec
|
| 4 |
# Set to true once VITE_EXAM_ENDPOINT is filled in.
|
| 5 |
+
VITE_EXAM_ENABLED=true
|
app/apps-script/Code.gs
CHANGED
|
@@ -6,6 +6,16 @@
|
|
| 6 |
// generated on first use.
|
| 7 |
|
| 8 |
const EXERCISES = [1, 2, 3, 4, 5].map(n => ({ id: `exercice-${n}`, title: { fr: `Exercice ${n}`, en: `Exercise ${n}` } }));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
const SESSION_MS = 8 * 60 * 60 * 1000;
|
| 10 |
const MAX_SOURCE_BYTES = 64 * 1024;
|
| 11 |
|
|
@@ -27,6 +37,14 @@ function doGet() {
|
|
| 27 |
return ContentService.createTextOutput('Service d’évaluation actif.');
|
| 28 |
}
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
// Run once from the editor: it asks for the Gmail and Drive permissions.
|
| 31 |
function autoriser() {
|
| 32 |
folder('suivi'); folder('copies');
|
|
@@ -55,11 +73,16 @@ function handle(body, now) {
|
|
| 55 |
const settings = config();
|
| 56 |
if (!settings.code) throw fail('exam_unavailable');
|
| 57 |
const cache = CacheService.getScriptCache();
|
|
|
|
|
|
|
| 58 |
const sign = payload => Utilities.base64EncodeWebSafe(Utilities.computeHmacSha256Signature(payload, settings.secret));
|
| 59 |
-
const summary = session =>
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
| 63 |
const authenticate = () => {
|
| 64 |
const token = typeof body.token === 'string' ? body.token : '';
|
| 65 |
const [payload, signature, extra] = token.split('.');
|
|
@@ -93,6 +116,24 @@ function handle(body, now) {
|
|
| 93 |
saveActivity({ examId: settings.examId, student: session.student, studentKey: session.studentKey, receivedAt: now, activity: validateActivity(body.activity, now) });
|
| 94 |
return { saved: true };
|
| 95 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
if (body.action === 'submit' || body.action === 'submit-all') {
|
| 97 |
const session = authenticate();
|
| 98 |
const { exerciseId, source, requestId, copies, activity } = body;
|
|
@@ -149,6 +190,23 @@ function sendCopies({ settings, session, entries, all, now, key }) {
|
|
| 149 |
return { id: `exam-${key.slice(0, 24)}`, sentAt: new Date(now).toISOString() };
|
| 150 |
}
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
// Storage: a Drive folder "Évaluation C" with the journals in suivi/ and a
|
| 153 |
// copy of every submitted file in copies/.
|
| 154 |
function folder(name) {
|
|
|
|
| 6 |
// generated on first use.
|
| 7 |
|
| 8 |
const EXERCISES = [1, 2, 3, 4, 5].map(n => ({ id: `exercice-${n}`, title: { fr: `Exercice ${n}`, en: `Exercise ${n}` } }));
|
| 9 |
+
// Quiz shown first; exercises unlock once the student clicks "Terminer le quiz".
|
| 10 |
+
// Without choices, the answer is free text. Run reinitialiserQuiz after a test.
|
| 11 |
+
const QUIZ = [
|
| 12 |
+
{ id: 'q1', question: 'Question test 1 : de quelle couleur est Microduck ?', choices: ['Jaune', 'Bleu', 'Vert', 'Violet'] },
|
| 13 |
+
{ id: 'q2', question: 'Question test 2 : combien de pattes a un canard ?', choices: ['1', '2', '3', '4'] },
|
| 14 |
+
{ id: 'q3', question: 'Question test 3 : quel robot est à gauche dans le simulateur ?', choices: ['Reachy Mini', 'Microduck', 'Aucun'] },
|
| 15 |
+
{ id: 'q4', question: 'Question test 4 : quel mot-clé C renvoie une valeur ?', choices: ['return', 'break', 'printf', 'main'] },
|
| 16 |
+
{ id: 'q5', question: 'Question test 5 : écrivez une phrase de votre choix.' },
|
| 17 |
+
];
|
| 18 |
+
const MAX_ANSWER_LENGTH = 2000;
|
| 19 |
const SESSION_MS = 8 * 60 * 60 * 1000;
|
| 20 |
const MAX_SOURCE_BYTES = 64 * 1024;
|
| 21 |
|
|
|
|
| 37 |
return ContentService.createTextOutput('Service d’évaluation actif.');
|
| 38 |
}
|
| 39 |
|
| 40 |
+
// Run from the editor after a test: every student can take the quiz again.
|
| 41 |
+
function reinitialiserQuiz() {
|
| 42 |
+
const props = PropertiesService.getScriptProperties();
|
| 43 |
+
const keys = props.getKeys().filter(key => key.startsWith('quiz:'));
|
| 44 |
+
for (const key of keys) props.deleteProperty(key);
|
| 45 |
+
console.log(`${keys.length} quiz réinitialisé(s).`);
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
// Run once from the editor: it asks for the Gmail and Drive permissions.
|
| 49 |
function autoriser() {
|
| 50 |
folder('suivi'); folder('copies');
|
|
|
|
| 73 |
const settings = config();
|
| 74 |
if (!settings.code) throw fail('exam_unavailable');
|
| 75 |
const cache = CacheService.getScriptCache();
|
| 76 |
+
const props = PropertiesService.getScriptProperties();
|
| 77 |
+
const quizKey = session => `quiz:${settings.examId}:${session.studentKey}`;
|
| 78 |
const sign = payload => Utilities.base64EncodeWebSafe(Utilities.computeHmacSha256Signature(payload, settings.secret));
|
| 79 |
+
const summary = session => {
|
| 80 |
+
const quizDone = Boolean(props.getProperty(quizKey(session)));
|
| 81 |
+
return {
|
| 82 |
+
student: session.student, studentKey: session.studentKey, expiresAt: session.expiresAt,
|
| 83 |
+
exam: { id: settings.examId, exercises: EXERCISES, quiz: quizDone ? [] : QUIZ }, quizDone, submissionAvailable: Boolean(settings.recipient),
|
| 84 |
+
};
|
| 85 |
+
};
|
| 86 |
const authenticate = () => {
|
| 87 |
const token = typeof body.token === 'string' ? body.token : '';
|
| 88 |
const [payload, signature, extra] = token.split('.');
|
|
|
|
| 116 |
saveActivity({ examId: settings.examId, student: session.student, studentKey: session.studentKey, receivedAt: now, activity: validateActivity(body.activity, now) });
|
| 117 |
return { saved: true };
|
| 118 |
}
|
| 119 |
+
if (body.action === 'quiz') {
|
| 120 |
+
const session = authenticate();
|
| 121 |
+
const answers = body.answers;
|
| 122 |
+
if (!answers || typeof answers !== 'object' || Array.isArray(answers) || Object.keys(answers).some(id => !QUIZ.some(item => item.id === id)) ||
|
| 123 |
+
QUIZ.some(item => answers[item.id] !== undefined && (typeof answers[item.id] !== 'string' || answers[item.id].length > MAX_ANSWER_LENGTH ||
|
| 124 |
+
(item.choices && answers[item.id] && !item.choices.includes(answers[item.id]))))) throw fail('invalid_answers');
|
| 125 |
+
if (!settings.recipient) throw fail('mail_unavailable');
|
| 126 |
+
// Once finished, the quiz is closed: a retry gets the first receipt, never a second email.
|
| 127 |
+
const lock = LockService.getScriptLock();
|
| 128 |
+
lock.waitLock(30000);
|
| 129 |
+
try {
|
| 130 |
+
const done = props.getProperty(quizKey(session));
|
| 131 |
+
if (done) return JSON.parse(done);
|
| 132 |
+
const receipt = sendQuiz({ settings, session, answers, now });
|
| 133 |
+
props.setProperty(quizKey(session), JSON.stringify(receipt));
|
| 134 |
+
return receipt;
|
| 135 |
+
} finally { lock.releaseLock(); }
|
| 136 |
+
}
|
| 137 |
if (body.action === 'submit' || body.action === 'submit-all') {
|
| 138 |
const session = authenticate();
|
| 139 |
const { exerciseId, source, requestId, copies, activity } = body;
|
|
|
|
| 190 |
return { id: `exam-${key.slice(0, 24)}`, sentAt: new Date(now).toISOString() };
|
| 191 |
}
|
| 192 |
|
| 193 |
+
function sendQuiz({ settings, session, answers, now }) {
|
| 194 |
+
const student = session.student;
|
| 195 |
+
const slug = student.normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^a-zA-Z0-9_-]+/g, '-').slice(0, 60) || 'student';
|
| 196 |
+
const report = QUIZ.map((item, index) => `${index + 1}. ${item.question}\n→ ${(answers[item.id] || '').trim() || '(sans réponse)'}`).join('\n\n');
|
| 197 |
+
const file = Utilities.newBlob(`${student}\n\n${report}\n`, 'text/plain', `${slug}-quiz.txt`);
|
| 198 |
+
try {
|
| 199 |
+
MailApp.sendEmail({
|
| 200 |
+
to: settings.recipient, name: '��valuation C',
|
| 201 |
+
subject: `[Évaluation C] ${student} — Quiz`,
|
| 202 |
+
body: `Étudiant : ${student}\nExamen : ${settings.examId}\nDate : ${new Date(now).toISOString()}\n\n${report}\n`,
|
| 203 |
+
attachments: [file],
|
| 204 |
+
});
|
| 205 |
+
} catch (error) { console.error(error); throw fail('mail_failed'); }
|
| 206 |
+
folder('copies').createFile(file.copyBlob().setName(`${new Date(now).toISOString().replace(/[:.]/g, '-')}-${file.getName()}`));
|
| 207 |
+
return { id: `quiz-${hash(`${settings.examId}:${session.studentKey}`).slice(0, 24)}`, sentAt: new Date(now).toISOString() };
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
// Storage: a Drive folder "Évaluation C" with the journals in suivi/ and a
|
| 211 |
// copy of every submitted file in copies/.
|
| 212 |
function folder(name) {
|
app/server/exam.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
| 2 |
-
import { examExercises } from './examCatalogue.mjs';
|
| 3 |
import { createGmailTransport } from './gmail.mjs';
|
| 4 |
import { createActivityStore } from './examActivity.mjs';
|
| 5 |
import { activityReport, validateActivity } from '../shared/examActivity.js';
|
|
@@ -30,17 +30,19 @@ async function readJson(req) {
|
|
| 30 |
} catch { throw fail(400, 'invalid_request'); }
|
| 31 |
}
|
| 32 |
|
| 33 |
-
|
|
|
|
| 34 |
const slug = student.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-zA-Z0-9_-]+/g, '-').slice(0, 60) || 'student';
|
| 35 |
-
const
|
| 36 |
-
const
|
| 37 |
-
const
|
| 38 |
-
files
|
| 39 |
-
|
|
|
|
| 40 |
const message = {
|
| 41 |
from: env.EXAM_MAIL_FROM, to: [env.EXAM_RECIPIENT],
|
| 42 |
subject: `[Évaluation C] ${student} — ${title}`,
|
| 43 |
-
text: `Étudiant : ${student}\nExamen : ${env.EXAM_ID || 'exam-demo-v1'}\nDate : ${new Date(now).toISOString()}\n\n${inventory}
|
| 44 |
attachments: files.map(file => ({ filename: file.filename, content: file.content.toString('base64'), content_type: 'text/plain' })),
|
| 45 |
};
|
| 46 |
if (gmailReady(env)) {
|
|
@@ -73,13 +75,16 @@ export async function sendExamEmail({ env, student, exercise, source, copies, ac
|
|
| 73 |
export function createExamHandler({ env = process.env, now = Date.now, sendMail = sendExamEmail, activityStore = createActivityStore(env.EXAM_ACTIVITY_DIR) } = {}) {
|
| 74 |
const signingKey = env.EXAM_SESSION_SECRET || randomBytes(32).toString('hex');
|
| 75 |
const examId = env.EXAM_ID || 'exam-demo-v1';
|
| 76 |
-
const failedAttempts = new Map(), submissions = new Map(), sendRates = new Map();
|
| 77 |
const sign = payload => createHmac('sha256', signingKey).update(payload).digest('base64url');
|
| 78 |
const mailReady = () => Boolean(env.EXAM_RECIPIENT && (gmailReady(env) || (env.RESEND_API_KEY && env.EXAM_MAIL_FROM)));
|
| 79 |
-
const summary = session =>
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
| 83 |
const authenticate = req => {
|
| 84 |
const token = req.headers.authorization?.replace(/^Bearer /, '') || '';
|
| 85 |
if (token.length > 2048) throw fail(401, 'session_expired');
|
|
@@ -133,6 +138,22 @@ export function createExamHandler({ env = process.env, now = Date.now, sendMail
|
|
| 133 |
const { activity } = await readJson(req);
|
| 134 |
await activityStore.save({ examId, student: session.student, studentKey: session.studentKey, receivedAt: now(), activity: validateActivity(activity, now()) });
|
| 135 |
json(res, 200, { saved: true });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
} else if (['/api/exam/submit', '/api/exam/submit-all'].includes(route) && req.method === 'POST') {
|
| 137 |
const session = authenticate(req);
|
| 138 |
const { exerciseId, source, requestId, copies, activity } = await readJson(req);
|
|
|
|
| 1 |
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
| 2 |
+
import { examExercises, examQuiz } from './examCatalogue.mjs';
|
| 3 |
import { createGmailTransport } from './gmail.mjs';
|
| 4 |
import { createActivityStore } from './examActivity.mjs';
|
| 5 |
import { activityReport, validateActivity } from '../shared/examActivity.js';
|
|
|
|
| 30 |
} catch { throw fail(400, 'invalid_request'); }
|
| 31 |
}
|
| 32 |
|
| 33 |
+
// With `quiz` (the answers as text), sends the quiz instead of the C files.
|
| 34 |
+
export async function sendExamEmail({ env, student, exercise, source, copies, quiz, activityRecords = [], key, now, fetchImpl = fetch, createTransport = createGmailTransport }) {
|
| 35 |
const slug = student.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-zA-Z0-9_-]+/g, '-').slice(0, 60) || 'student';
|
| 36 |
+
const textFile = (name, text) => ({ filename: `${slug}-${name}`, content: Buffer.from(text, 'utf8'), contentType: 'text/plain; charset=utf-8' });
|
| 37 |
+
const entries = quiz ? [] : copies || [{ exercise, source }];
|
| 38 |
+
const title = quiz ? 'Quiz' : copies ? 'Tous les exercices' : exercise.title.fr;
|
| 39 |
+
const files = quiz ? [textFile('quiz.txt', `${student}\n\n${quiz}\n`)] : entries.map(item => textFile(`${item.exercise.id}.c`, item.source));
|
| 40 |
+
if (!quiz) files.push(textFile('suivi.txt', activityReport(activityRecords, now)));
|
| 41 |
+
const inventory = quiz || `${entries.map(item => `${item.exercise.title.fr} : ${item.source.trim() ? 'copie jointe' : 'non répondu (fichier vide)'}`).join('\n')}\n\nLes copies et le journal de visibilité sont joints à cet email.`;
|
| 42 |
const message = {
|
| 43 |
from: env.EXAM_MAIL_FROM, to: [env.EXAM_RECIPIENT],
|
| 44 |
subject: `[Évaluation C] ${student} — ${title}`,
|
| 45 |
+
text: `Étudiant : ${student}\nExamen : ${env.EXAM_ID || 'exam-demo-v1'}\nDate : ${new Date(now).toISOString()}\n\n${inventory}`,
|
| 46 |
attachments: files.map(file => ({ filename: file.filename, content: file.content.toString('base64'), content_type: 'text/plain' })),
|
| 47 |
};
|
| 48 |
if (gmailReady(env)) {
|
|
|
|
| 75 |
export function createExamHandler({ env = process.env, now = Date.now, sendMail = sendExamEmail, activityStore = createActivityStore(env.EXAM_ACTIVITY_DIR) } = {}) {
|
| 76 |
const signingKey = env.EXAM_SESSION_SECRET || randomBytes(32).toString('hex');
|
| 77 |
const examId = env.EXAM_ID || 'exam-demo-v1';
|
| 78 |
+
const failedAttempts = new Map(), submissions = new Map(), sendRates = new Map(), quizzes = new Map();
|
| 79 |
const sign = payload => createHmac('sha256', signingKey).update(payload).digest('base64url');
|
| 80 |
const mailReady = () => Boolean(env.EXAM_RECIPIENT && (gmailReady(env) || (env.RESEND_API_KEY && env.EXAM_MAIL_FROM)));
|
| 81 |
+
const summary = session => {
|
| 82 |
+
const quizDone = quizzes.has(session.studentKey);
|
| 83 |
+
return {
|
| 84 |
+
student: session.student, studentKey: session.studentKey, expiresAt: session.expiresAt,
|
| 85 |
+
exam: { id: examId, exercises: examExercises, quiz: quizDone ? [] : examQuiz }, quizDone, submissionAvailable: mailReady(),
|
| 86 |
+
};
|
| 87 |
+
};
|
| 88 |
const authenticate = req => {
|
| 89 |
const token = req.headers.authorization?.replace(/^Bearer /, '') || '';
|
| 90 |
if (token.length > 2048) throw fail(401, 'session_expired');
|
|
|
|
| 138 |
const { activity } = await readJson(req);
|
| 139 |
await activityStore.save({ examId, student: session.student, studentKey: session.studentKey, receivedAt: now(), activity: validateActivity(activity, now()) });
|
| 140 |
json(res, 200, { saved: true });
|
| 141 |
+
} else if (route === '/api/exam/quiz' && req.method === 'POST') {
|
| 142 |
+
const session = authenticate(req);
|
| 143 |
+
const { answers } = await readJson(req);
|
| 144 |
+
if (!answers || typeof answers !== 'object' || Array.isArray(answers) || Object.keys(answers).some(id => !examQuiz.some(item => item.id === id)) ||
|
| 145 |
+
examQuiz.some(item => answers[item.id] !== undefined && (typeof answers[item.id] !== 'string' || answers[item.id].length > 2000 ||
|
| 146 |
+
(item.choices && answers[item.id] && !item.choices.includes(answers[item.id]))))) throw fail(400, 'invalid_answers');
|
| 147 |
+
if (!mailReady()) throw fail(503, 'mail_unavailable');
|
| 148 |
+
// Once finished, the quiz is closed: a retry gets the first receipt, never a second email.
|
| 149 |
+
let sent = quizzes.get(session.studentKey);
|
| 150 |
+
if (!sent) {
|
| 151 |
+
const report = examQuiz.map((item, index) => `${index + 1}. ${item.question}\n→ ${answers[item.id]?.trim() || '(sans réponse)'}`).join('\n\n');
|
| 152 |
+
sent = sendMail({ env, student: session.student, quiz: report, key: `quiz:${examId}:${session.studentKey}`, now: now() });
|
| 153 |
+
quizzes.set(session.studentKey, sent);
|
| 154 |
+
}
|
| 155 |
+
try { json(res, 200, await sent); }
|
| 156 |
+
catch { quizzes.delete(session.studentKey); throw fail(502, 'mail_failed'); }
|
| 157 |
} else if (['/api/exam/submit', '/api/exam/submit-all'].includes(route) && req.method === 'POST') {
|
| 158 |
const session = authenticate(req);
|
| 159 |
const { exerciseId, source, requestId, copies, activity } = await readJson(req);
|
app/server/examCatalogue.mjs
CHANGED
|
@@ -1,2 +1,10 @@
|
|
| 1 |
// Loaded only by the server, after access-code validation. Statements are handed out separately.
|
| 2 |
export const examExercises = [1, 2, 3, 4, 5].map(n => ({ id: `exercice-${n}`, title: { fr: `Exercice ${n}`, en: `Exercise ${n}` } }));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
// Loaded only by the server, after access-code validation. Statements are handed out separately.
|
| 2 |
export const examExercises = [1, 2, 3, 4, 5].map(n => ({ id: `exercice-${n}`, title: { fr: `Exercice ${n}`, en: `Exercise ${n}` } }));
|
| 3 |
+
// Quiz shown before the exercises (keep in step with QUIZ in apps-script/Code.gs). Without choices, the answer is free text.
|
| 4 |
+
export const examQuiz = [
|
| 5 |
+
{ id: 'q1', question: 'Question test 1 : de quelle couleur est Microduck ?', choices: ['Jaune', 'Bleu', 'Vert', 'Violet'] },
|
| 6 |
+
{ id: 'q2', question: 'Question test 2 : combien de pattes a un canard ?', choices: ['1', '2', '3', '4'] },
|
| 7 |
+
{ id: 'q3', question: 'Question test 3 : quel robot est à gauche dans le simulateur ?', choices: ['Reachy Mini', 'Microduck', 'Aucun'] },
|
| 8 |
+
{ id: 'q4', question: 'Question test 4 : quel mot-clé C renvoie une valeur ?', choices: ['return', 'break', 'printf', 'main'] },
|
| 9 |
+
{ id: 'q5', question: 'Question test 5 : écrivez une phrase de votre choix.' },
|
| 10 |
+
];
|
app/src/training/useExam.js
CHANGED
|
@@ -13,6 +13,7 @@ const messages = {
|
|
| 13 |
too_many_attempts: ['Trop de tentatives. Réessayez dans 15 minutes.', 'Too many attempts. Try again in 15 minutes.'],
|
| 14 |
too_many_submissions: ['Veuillez patienter une minute avant de renvoyer.', 'Please wait one minute before submitting again.'],
|
| 15 |
source_too_large: ['Le fichier dépasse 64 Ko.', 'The file exceeds 64 KB.'],
|
|
|
|
| 16 |
empty_source: ['Saisissez au moins une réponse avant l’envoi.', 'Enter at least one answer before submitting.'],
|
| 17 |
};
|
| 18 |
export function useExam({ source, replaceSource, language }) {
|
|
@@ -83,7 +84,7 @@ export function useExam({ source, replaceSource, language }) {
|
|
| 83 |
finally { lock.current = false; setWorking(false); }
|
| 84 |
}
|
| 85 |
function choose(item) {
|
| 86 |
-
if (lock.current) return;
|
| 87 |
save(); setSelected(item); setNotice('');
|
| 88 |
replaceSource(typeof drafts.current[item.id]?.source === 'string' ? drafts.current[item.id].source : '');
|
| 89 |
}
|
|
@@ -101,6 +102,25 @@ export function useExam({ source, replaceSource, language }) {
|
|
| 101 |
} catch (error) { errorNotice(error); }
|
| 102 |
finally { lock.current = false; setWorking(false); }
|
| 103 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
const allCopies = () => auth?.exam.exercises.map(item => ({ exerciseId: item.id, source: item.id === selected?.id ? source : drafts.current[item.id]?.source || '' })) || [];
|
| 105 |
const fingerprint = () => JSON.stringify(allCopies());
|
| 106 |
async function submitAll() {
|
|
@@ -124,6 +144,7 @@ export function useExam({ source, replaceSource, language }) {
|
|
| 124 |
const allSent = drafts.current._all?.receipt?.stamp === fingerprint();
|
| 125 |
useEffect(() => { if (auth && !allSent) activity.resume(); }, [auth, allSent, source]);
|
| 126 |
return { active, auth, selected, working, notice, storageError, enter, leave, login, choose, submit, submitAll, activity,
|
|
|
|
| 127 |
hasCopies: allCopies().some(item => item.source.trim()),
|
| 128 |
allSent,
|
| 129 |
sent: !!selected && drafts.current[selected.id]?.receipt?.source === source,
|
|
|
|
| 13 |
too_many_attempts: ['Trop de tentatives. Réessayez dans 15 minutes.', 'Too many attempts. Try again in 15 minutes.'],
|
| 14 |
too_many_submissions: ['Veuillez patienter une minute avant de renvoyer.', 'Please wait one minute before submitting again.'],
|
| 15 |
source_too_large: ['Le fichier dépasse 64 Ko.', 'The file exceeds 64 KB.'],
|
| 16 |
+
invalid_answers: ['Réponses du quiz refusées. Rechargez la page puis réessayez.', 'Quiz answers refused. Reload the page and retry.'],
|
| 17 |
empty_source: ['Saisissez au moins une réponse avant l’envoi.', 'Enter at least one answer before submitting.'],
|
| 18 |
};
|
| 19 |
export function useExam({ source, replaceSource, language }) {
|
|
|
|
| 84 |
finally { lock.current = false; setWorking(false); }
|
| 85 |
}
|
| 86 |
function choose(item) {
|
| 87 |
+
if (lock.current || quizPending) return;
|
| 88 |
save(); setSelected(item); setNotice('');
|
| 89 |
replaceSource(typeof drafts.current[item.id]?.source === 'string' ? drafts.current[item.id].source : '');
|
| 90 |
}
|
|
|
|
| 102 |
} catch (error) { errorNotice(error); }
|
| 103 |
finally { lock.current = false; setWorking(false); }
|
| 104 |
}
|
| 105 |
+
const quizPending = !!auth && !auth.quizDone;
|
| 106 |
+
const quizAnswers = drafts.current._quiz || {};
|
| 107 |
+
function answer(id, value) {
|
| 108 |
+
drafts.current._quiz = { ...drafts.current._quiz, [id]: value };
|
| 109 |
+
persist(); refresh(n => n + 1);
|
| 110 |
+
}
|
| 111 |
+
async function finishQuiz() {
|
| 112 |
+
if (lock.current || !quizPending) return;
|
| 113 |
+
lock.current = true; setWorking(true); setNotice('');
|
| 114 |
+
try {
|
| 115 |
+
const receipt = await request('quiz', { answers: quizAnswers }, auth.token);
|
| 116 |
+
if (!receipt.id) throw new Error('mail_failed');
|
| 117 |
+
delete drafts.current._quiz; persist();
|
| 118 |
+
setAuth({ ...auth, quizDone: true, exam: { ...auth.exam, quiz: [] } });
|
| 119 |
+
setNotice(t('Quiz terminé et envoyé. Choisissez un exercice.', 'Quiz finished and submitted. Choose an exercise.'));
|
| 120 |
+
return true;
|
| 121 |
+
} catch (error) { errorNotice(error); return false; }
|
| 122 |
+
finally { lock.current = false; setWorking(false); }
|
| 123 |
+
}
|
| 124 |
const allCopies = () => auth?.exam.exercises.map(item => ({ exerciseId: item.id, source: item.id === selected?.id ? source : drafts.current[item.id]?.source || '' })) || [];
|
| 125 |
const fingerprint = () => JSON.stringify(allCopies());
|
| 126 |
async function submitAll() {
|
|
|
|
| 144 |
const allSent = drafts.current._all?.receipt?.stamp === fingerprint();
|
| 145 |
useEffect(() => { if (auth && !allSent) activity.resume(); }, [auth, allSent, source]);
|
| 146 |
return { active, auth, selected, working, notice, storageError, enter, leave, login, choose, submit, submitAll, activity,
|
| 147 |
+
quizPending, quizAnswers, answer, finishQuiz,
|
| 148 |
hasCopies: allCopies().some(item => item.source.trim()),
|
| 149 |
allSent,
|
| 150 |
sent: !!selected && drafts.current[selected.id]?.receipt?.source === source,
|
app/src/ui/CodeTraining.jsx
CHANGED
|
@@ -13,7 +13,7 @@ import { createRaceProtocol } from "../training/raceProtocol.js";
|
|
| 13 |
import { createInteractionProtocol } from "../training/interactionProtocol.js";
|
| 14 |
import { INTERACTIVE_EXERCISES } from "./trainingExercises.jsx";
|
| 15 |
import { useExam } from '../training/useExam.js';
|
| 16 |
-
import { ExamPanel, ExamActions } from './ExamPanel.jsx';
|
| 17 |
import { asOwnEdit } from '../training/editProvenance.js';
|
| 18 |
import DebugPanel from './DebugPanel.jsx';
|
| 19 |
|
|
@@ -464,7 +464,7 @@ export default function CodeTraining({ onClose }) {
|
|
| 464 |
}
|
| 465 |
}
|
| 466 |
const diagnosticTone = /(?:fatal )?error:/.test(diagnostics) ? "has-errors" : "has-warnings";
|
| 467 |
-
return createPortal(<><dialog ref={dialog} className={`code-training${debugMode ? ' is-debugging' : ''}${exam.active ? ' is-exam' : ''}${exam.active && !examToolsOpen ? ' exam-wide' : ''}${docked ? " is-docked" : ""}${exerciseRunning ? " exercise-running" : ""}`} style={{ '--editor-font': EDITOR_FONTS[editorFont].family, '--editor-size': `${editorSize}px` }} aria-labelledby="code-training-title" onCancel={(event) => { event.preventDefault(); onClose(); }}>
|
| 468 |
<header className="code-training-header">
|
| 469 |
<div><strong id="code-training-title">{exam.active ? exam.t('ÉVALUATION', 'ASSESSMENT') : 'CODE TRAINING'}</strong><span>{exam.active ? exam.t('Éditeur C · simulation 3D en pause', 'C editor · 3D simulation paused') : 'Learn with Microduck & Reachy Mini'}</span></div>
|
| 470 |
<label>Language <select aria-label="Programming language" defaultValue="c"><option value="c">C (C17)</option></select></label>
|
|
@@ -497,6 +497,7 @@ export default function CodeTraining({ onClose }) {
|
|
| 497 |
{pendingFile && <section className="load-confirm" role="dialog" aria-label="Save before opening file"><strong>Ouvrir « {pendingFile.name} » ?</strong><p>Le code actuel sera remplacé. Souhaites-tu d’abord l’enregistrer ?</p><button type="button" onClick={() => { saveSource(); loadPendingFile(); }}>Sauvegarder puis ouvrir</button><button type="button" onClick={loadPendingFile}>Ouvrir sans sauvegarder</button><button type="button" onClick={() => setPendingFile(null)}>Annuler</button></section>}
|
| 498 |
{helpOpen && <section className="reachy-help" aria-label="Reachy code help"><button type="button" className="feedback-close" aria-label="Close Reachy help" onClick={() => setHelpOpen(false)}>×</button><strong>Ask Reachy · local WebGPU</strong><p>Aucune clé ni API : le modèle se télécharge une fois sur cet appareil, puis reste dans le navigateur.</p><textarea aria-label="Question for Reachy" value={helpQuestion} disabled={helpBusy} onChange={(e) => setHelpQuestion(e.target.value)} placeholder="Pourquoi mon programme ne compile pas ?" /><button type="button" disabled={helpBusy || !helpQuestion.trim()} onClick={askReachy}>{helpBusy ? "Preparing…" : "Ask"}</button>{helpStatus && <p className="help-status" role="status">{helpStatus}</p>}{helpAnswer && <pre>{helpAnswer}</pre>}</section>}
|
| 499 |
{exam.active && <section className="exam-statement" aria-label={exam.t('Énoncé', 'Assignment')}><strong>{exam.selected?.title[language === 'fr' ? 'fr' : 'en'] || exam.t('Choisissez un exercice après avoir saisi le code d’accès.', 'Enter the access code, then choose an exercise.')}</strong></section>}
|
|
|
|
| 500 |
{exam.active && !examToolsOpen && <>
|
| 501 |
{exam.notice && <p className="code-notice" role="status">{exam.notice}</p>}
|
| 502 |
{exam.storageError && <p className="code-notice" role="alert">{exam.t('Stockage indisponible : téléchargez votre fichier .c avant de fermer cette page.', 'Storage unavailable: download your .c file before closing this page.')}</p>}
|
|
@@ -549,7 +550,7 @@ export default function CodeTraining({ onClose }) {
|
|
| 549 |
<footer>Your code is saved on this device. Closing stops the program.</footer>
|
| 550 |
</dialog>
|
| 551 |
<aside className={`exercise-panel${exerciseOpen ? " is-open" : ""}${exam.active && !examToolsOpen ? ' exam-tools-collapsed' : ''}`} aria-label="Exercises">
|
| 552 |
-
{exam.active && <button type="button" className="exercise-panel-button exam-tools-toggle" aria-expanded={examToolsOpen} onClick={() => setExamToolsOpen(value => !value)}>{examToolsOpen ? exam.t('Agrandir le code', 'Expand code') : exam.t('Sujets et évaluation', 'Assignments and assessment')}</button>}
|
| 553 |
<button type="button" className="exercise-panel-button" disabled={exam.working} onClick={() => { if (exam.active) exam.leave(); setExerciseOpen((value) => !value); }}>Exercices</button>
|
| 554 |
{import.meta.env.VITE_EXAM_ENABLED !== 'false' && <button type="button" className="exercise-panel-button exam-toggle" aria-pressed={exam.active} disabled={exam.working} onClick={() => { if (exam.active) exam.leave(); else { useGame.setState({ speechLanguage: 'fr' }); exam.enter(); } }}>Evaluation</button>}
|
| 555 |
{exam.active && <ExamPanel exam={exam} language={language} />}
|
|
|
|
| 13 |
import { createInteractionProtocol } from "../training/interactionProtocol.js";
|
| 14 |
import { INTERACTIVE_EXERCISES } from "./trainingExercises.jsx";
|
| 15 |
import { useExam } from '../training/useExam.js';
|
| 16 |
+
import { ExamPanel, ExamActions, ExamQuiz } from './ExamPanel.jsx';
|
| 17 |
import { asOwnEdit } from '../training/editProvenance.js';
|
| 18 |
import DebugPanel from './DebugPanel.jsx';
|
| 19 |
|
|
|
|
| 464 |
}
|
| 465 |
}
|
| 466 |
const diagnosticTone = /(?:fatal )?error:/.test(diagnostics) ? "has-errors" : "has-warnings";
|
| 467 |
+
return createPortal(<><dialog ref={dialog} className={`code-training${debugMode ? ' is-debugging' : ''}${exam.active ? ' is-exam' : ''}${exam.active && exam.quizPending ? ' is-quiz' : ''}${exam.active && !examToolsOpen ? ' exam-wide' : ''}${docked ? " is-docked" : ""}${exerciseRunning ? " exercise-running" : ""}`} style={{ '--editor-font': EDITOR_FONTS[editorFont].family, '--editor-size': `${editorSize}px` }} aria-labelledby="code-training-title" onCancel={(event) => { event.preventDefault(); onClose(); }}>
|
| 468 |
<header className="code-training-header">
|
| 469 |
<div><strong id="code-training-title">{exam.active ? exam.t('ÉVALUATION', 'ASSESSMENT') : 'CODE TRAINING'}</strong><span>{exam.active ? exam.t('Éditeur C · simulation 3D en pause', 'C editor · 3D simulation paused') : 'Learn with Microduck & Reachy Mini'}</span></div>
|
| 470 |
<label>Language <select aria-label="Programming language" defaultValue="c"><option value="c">C (C17)</option></select></label>
|
|
|
|
| 497 |
{pendingFile && <section className="load-confirm" role="dialog" aria-label="Save before opening file"><strong>Ouvrir « {pendingFile.name} » ?</strong><p>Le code actuel sera remplacé. Souhaites-tu d’abord l’enregistrer ?</p><button type="button" onClick={() => { saveSource(); loadPendingFile(); }}>Sauvegarder puis ouvrir</button><button type="button" onClick={loadPendingFile}>Ouvrir sans sauvegarder</button><button type="button" onClick={() => setPendingFile(null)}>Annuler</button></section>}
|
| 498 |
{helpOpen && <section className="reachy-help" aria-label="Reachy code help"><button type="button" className="feedback-close" aria-label="Close Reachy help" onClick={() => setHelpOpen(false)}>×</button><strong>Ask Reachy · local WebGPU</strong><p>Aucune clé ni API : le modèle se télécharge une fois sur cet appareil, puis reste dans le navigateur.</p><textarea aria-label="Question for Reachy" value={helpQuestion} disabled={helpBusy} onChange={(e) => setHelpQuestion(e.target.value)} placeholder="Pourquoi mon programme ne compile pas ?" /><button type="button" disabled={helpBusy || !helpQuestion.trim()} onClick={askReachy}>{helpBusy ? "Preparing…" : "Ask"}</button>{helpStatus && <p className="help-status" role="status">{helpStatus}</p>}{helpAnswer && <pre>{helpAnswer}</pre>}</section>}
|
| 499 |
{exam.active && <section className="exam-statement" aria-label={exam.t('Énoncé', 'Assignment')}><strong>{exam.selected?.title[language === 'fr' ? 'fr' : 'en'] || exam.t('Choisissez un exercice après avoir saisi le code d’accès.', 'Enter the access code, then choose an exercise.')}</strong></section>}
|
| 500 |
+
{exam.active && exam.quizPending && <ExamQuiz exam={exam} />}
|
| 501 |
{exam.active && !examToolsOpen && <>
|
| 502 |
{exam.notice && <p className="code-notice" role="status">{exam.notice}</p>}
|
| 503 |
{exam.storageError && <p className="code-notice" role="alert">{exam.t('Stockage indisponible : téléchargez votre fichier .c avant de fermer cette page.', 'Storage unavailable: download your .c file before closing this page.')}</p>}
|
|
|
|
| 550 |
<footer>Your code is saved on this device. Closing stops the program.</footer>
|
| 551 |
</dialog>
|
| 552 |
<aside className={`exercise-panel${exerciseOpen ? " is-open" : ""}${exam.active && !examToolsOpen ? ' exam-tools-collapsed' : ''}`} aria-label="Exercises">
|
| 553 |
+
{exam.active && !exam.quizPending && <button type="button" className="exercise-panel-button exam-tools-toggle" aria-expanded={examToolsOpen} onClick={() => setExamToolsOpen(value => !value)}>{examToolsOpen ? exam.t('Agrandir le code', 'Expand code') : exam.t('Sujets et évaluation', 'Assignments and assessment')}</button>}
|
| 554 |
<button type="button" className="exercise-panel-button" disabled={exam.working} onClick={() => { if (exam.active) exam.leave(); setExerciseOpen((value) => !value); }}>Exercices</button>
|
| 555 |
{import.meta.env.VITE_EXAM_ENABLED !== 'false' && <button type="button" className="exercise-panel-button exam-toggle" aria-pressed={exam.active} disabled={exam.working} onClick={() => { if (exam.active) exam.leave(); else { useGame.setState({ speechLanguage: 'fr' }); exam.enter(); } }}>Evaluation</button>}
|
| 556 |
{exam.active && <ExamPanel exam={exam} language={language} />}
|
app/src/ui/ExamPanel.jsx
CHANGED
|
@@ -5,20 +5,14 @@ export function ExamPanel({ exam, language }) {
|
|
| 5 |
const { t } = exam;
|
| 6 |
const locale = language === 'fr' ? 'fr' : 'en';
|
| 7 |
return <section className="exercise-panel-content exam-panel" aria-label={t('Évaluation', 'Assessment')}>
|
| 8 |
-
<strong>{t('Évaluation en C', 'C assessment')}</strong>
|
| 9 |
-
<p className="exam-note">{t('Suivi de l’évaluation : les changements d’onglet, pertes de focus, fermetures et retours sont horodatés et transmis à l’enseignant avec leur durée. Les indices d’aide extérieure le sont aussi : collages, copies, texte inséré sans frappe, panneau latéral du navigateur (assistant IA) et extensions ajoutées à la page. Aucun contenu des autres applications ni du presse-papiers n’est enregistré.', 'Assessment monitoring: tab changes, loss of focus, page exits and returns are timestamped and shared with the teacher, including their duration. So are clues of outside help: pastes, copies, text inserted without typing, browser side panels (AI assistants) and extensions added to the page. No content from other applications or the clipboard is recorded.')}</p>
|
| 10 |
{!exam.auth ? <form onSubmit={async event => { event.preventDefault(); if (await exam.login(student, code)) setCode(''); }}>
|
| 11 |
<label>{t('Nom et prénom', 'Full name')}<input autoComplete="name" value={student} maxLength={100} required disabled={exam.working} onChange={e => setStudent(e.target.value)} /></label>
|
| 12 |
<label>{t('Code d’accès', 'Access code')}<input type="password" autoComplete="off" value={code} maxLength={256} required disabled={exam.working} onChange={e => setCode(e.target.value)} /></label>
|
| 13 |
<button className="exercise-item" disabled={exam.working}>{t('Accéder à l’examen', 'Open assessment')}</button>
|
| 14 |
</form> : <>
|
| 15 |
-
<p>{
|
| 16 |
-
|
| 17 |
{!exam.auth.submissionAvailable && <p className="exam-warning">{t('L’enseignant doit encore configurer l’envoi des copies.', 'The teacher still needs to configure submissions.')}</p>}
|
| 18 |
-
<p className="exam-note">{t('Les brouillons restent dans ce navigateur, même en changeant d’exercice.', 'Drafts stay in this browser when you switch exercises.')}</p>
|
| 19 |
-
<p className="exam-note">{t('Tout envoyer joint tous les exercices dans un seul email ; les exercices non répondus sont signalés.', 'Submit all attaches all exercises in one email; unanswered exercises are marked.')}</p>
|
| 20 |
-
<p className="exam-note">{t('Le suivi s’arrête après Tout envoyer confirmé et reprend si vous modifiez une réponse.', 'Monitoring stops after Submit all is confirmed and resumes if you edit an answer.')}</p>
|
| 21 |
-
<p aria-label={t('Suivi de présence', 'Activity summary')}>{t('Sorties observées', 'Observed departures')} : {exam.activity.summary.count} · {Math.floor(exam.activity.summary.totalMs / 1000)} s · {t('Indices d’aide extérieure', 'Outside-help clues')} : {exam.activity.signals}</p>
|
| 22 |
{exam.activity.syncError && <p role="alert">{t('Journal non synchronisé. Une nouvelle tentative sera faite au retour de la connexion.', 'Activity log not synced. It will be retried when the connection returns.')}</p>}
|
| 23 |
</>}
|
| 24 |
{exam.notice && <p role="status">{exam.notice}</p>}
|
|
@@ -26,6 +20,29 @@ export function ExamPanel({ exam, language }) {
|
|
| 26 |
</section>;
|
| 27 |
}
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
export function ExamActions({ exam, source, busy }) {
|
| 30 |
return <>
|
| 31 |
<button disabled={!exam.selected || exam.working} onClick={exam.keep}>{exam.t('Conserver code', 'Keep code')}</button>
|
|
|
|
| 5 |
const { t } = exam;
|
| 6 |
const locale = language === 'fr' ? 'fr' : 'en';
|
| 7 |
return <section className="exercise-panel-content exam-panel" aria-label={t('Évaluation', 'Assessment')}>
|
|
|
|
|
|
|
| 8 |
{!exam.auth ? <form onSubmit={async event => { event.preventDefault(); if (await exam.login(student, code)) setCode(''); }}>
|
| 9 |
<label>{t('Nom et prénom', 'Full name')}<input autoComplete="name" value={student} maxLength={100} required disabled={exam.working} onChange={e => setStudent(e.target.value)} /></label>
|
| 10 |
<label>{t('Code d’accès', 'Access code')}<input type="password" autoComplete="off" value={code} maxLength={256} required disabled={exam.working} onChange={e => setCode(e.target.value)} /></label>
|
| 11 |
<button className="exercise-item" disabled={exam.working}>{t('Accéder à l’examen', 'Open assessment')}</button>
|
| 12 |
</form> : <>
|
| 13 |
+
{exam.quizPending ? <p>{t('Commencez par le quiz. Les exercices s’ouvriront quand vous l’aurez terminé.', 'Start with the quiz. The exercises open once you finish it.')}</p>
|
| 14 |
+
: exam.auth.exam.exercises.map(item => <button key={item.id} className="exercise-item" aria-pressed={exam.selected?.id === item.id} disabled={exam.working} onClick={() => exam.choose(item)}>{item.title[locale]}</button>)}
|
| 15 |
{!exam.auth.submissionAvailable && <p className="exam-warning">{t('L’enseignant doit encore configurer l’envoi des copies.', 'The teacher still needs to configure submissions.')}</p>}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
{exam.activity.syncError && <p role="alert">{t('Journal non synchronisé. Une nouvelle tentative sera faite au retour de la connexion.', 'Activity log not synced. It will be retried when the connection returns.')}</p>}
|
| 17 |
</>}
|
| 18 |
{exam.notice && <p role="status">{exam.notice}</p>}
|
|
|
|
| 20 |
</section>;
|
| 21 |
}
|
| 22 |
|
| 23 |
+
// Shown in place of the editor until the student finishes the quiz; it cannot be reopened afterwards.
|
| 24 |
+
export function ExamQuiz({ exam }) {
|
| 25 |
+
const [confirming, setConfirming] = useState(false);
|
| 26 |
+
const { t, quizAnswers: answers } = exam;
|
| 27 |
+
const questions = exam.auth.exam.quiz;
|
| 28 |
+
const missing = questions.filter(item => !answers[item.id]?.trim()).length;
|
| 29 |
+
return <section className="exam-quiz" aria-label="Quiz">
|
| 30 |
+
<strong>{t(`Quiz — ${questions.length} questions`, `Quiz — ${questions.length} questions`)}</strong>
|
| 31 |
+
<p>{t('Répondez aux questions puis cliquez sur « Terminer le quiz ». Vos réponses sont alors envoyées à l’enseignant et le quiz n’est plus accessible ; les exercices s’ouvrent ensuite.', 'Answer the questions, then click “Finish quiz”. Your answers are sent to the teacher and the quiz closes; the exercises open next.')}</p>
|
| 32 |
+
<ol>{questions.map((item, index) => <li key={item.id}><fieldset disabled={exam.working}>
|
| 33 |
+
<legend>{index + 1}. {item.question}</legend>
|
| 34 |
+
{item.choices ? item.choices.map(choice => <label key={choice}><input type="radio" name={`quiz-${item.id}`} checked={answers[item.id] === choice} onChange={() => exam.answer(item.id, choice)} />{choice}</label>)
|
| 35 |
+
: <textarea aria-label={item.question} value={answers[item.id] || ''} maxLength={2000} onChange={e => exam.answer(item.id, e.target.value)} />}
|
| 36 |
+
</fieldset></li>)}</ol>
|
| 37 |
+
{!confirming ? <button type="button" disabled={exam.working} onClick={() => setConfirming(true)}>{t('Terminer le quiz', 'Finish quiz')}</button>
|
| 38 |
+
: <div className="exam-quiz-confirm" role="group" aria-label={t('Confirmation', 'Confirmation')}>
|
| 39 |
+
<p>{missing ? t(`${missing} question(s) sans réponse. `, `${missing} unanswered question(s). `) : ''}{t('Après confirmation, vous ne pourrez plus revenir au quiz.', 'Once confirmed, you cannot come back to the quiz.')}</p>
|
| 40 |
+
<button type="button" disabled={exam.working} onClick={async () => { if (!await exam.finishQuiz()) setConfirming(false); }}>{exam.working ? t('Envoi…', 'Sending…') : t('Confirmer et envoyer', 'Confirm and send')}</button>
|
| 41 |
+
<button type="button" disabled={exam.working} onClick={() => setConfirming(false)}>{t('Revenir au quiz', 'Back to the quiz')}</button>
|
| 42 |
+
</div>}
|
| 43 |
+
</section>;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
export function ExamActions({ exam, source, busy }) {
|
| 47 |
return <>
|
| 48 |
<button disabled={!exam.selected || exam.working} onClick={exam.keep}>{exam.t('Conserver code', 'Keep code')}</button>
|
app/src/ui/codeTraining.css
CHANGED
|
@@ -139,10 +139,21 @@
|
|
| 139 |
.exam-panel .exercise-item[aria-pressed="true"] { border-color: #d49ce8; background: #3c294c; }
|
| 140 |
.exam-panel p { margin-top: 12px; overflow-wrap: anywhere; }
|
| 141 |
.exam-panel .exam-warning, .exam-panel [role="alert"] { color: #ffd08f; }
|
| 142 |
-
.exam-panel .exam-note { color: #b9aebe; font-size: 11px; }
|
| 143 |
.exam-panel button:disabled, .exercise-panel-button:disabled { opacity: .5; cursor: default; }
|
| 144 |
.exam-statement { margin: 0 16px 12px; padding: 12px; border-left: 3px solid #c58be1; background: #292033; color: #f4e6fd; }
|
| 145 |
.exam-statement p { margin: 6px 0 0; white-space: pre-wrap; line-height: 1.5; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
.exercise-panel-content { max-height: min(620px, calc(100dvh - 145px)); margin-top: 7px; padding: 12px; overflow-y: auto; overscroll-behavior: contain; background: #15151d; border: 1px solid #6b6771; border-radius: 6px; box-shadow: 0 18px 50px #0009; scrollbar-color: #d89b4d #101018; }
|
| 147 |
.exercise-panel-content strong { display: block; color: #ffad6b; letter-spacing: .06em; }
|
| 148 |
.exercise-panel-content h2 { margin: 9px 0; color: #ffad6b; font-size: 15px; }
|
|
|
|
| 139 |
.exam-panel .exercise-item[aria-pressed="true"] { border-color: #d49ce8; background: #3c294c; }
|
| 140 |
.exam-panel p { margin-top: 12px; overflow-wrap: anywhere; }
|
| 141 |
.exam-panel .exam-warning, .exam-panel [role="alert"] { color: #ffd08f; }
|
|
|
|
| 142 |
.exam-panel button:disabled, .exercise-panel-button:disabled { opacity: .5; cursor: default; }
|
| 143 |
.exam-statement { margin: 0 16px 12px; padding: 12px; border-left: 3px solid #c58be1; background: #292033; color: #f4e6fd; }
|
| 144 |
.exam-statement p { margin: 6px 0 0; white-space: pre-wrap; line-height: 1.5; }
|
| 145 |
+
.code-training.is-quiz > :not(.code-training-header):not(.exam-quiz) { display: none; }
|
| 146 |
+
.exam-quiz { margin: 0 16px 16px; padding: 16px; border-left: 3px solid #c58be1; background: #292033; color: #f4e6fd; font-size: 14px; }
|
| 147 |
+
.exam-quiz > p { color: #c7bfd0; line-height: 1.5; }
|
| 148 |
+
.exam-quiz ol { margin: 16px 0; padding: 0; list-style: none; }
|
| 149 |
+
.exam-quiz li { margin-bottom: 16px; }
|
| 150 |
+
.exam-quiz fieldset { margin: 0; padding: 0; border: 0; }
|
| 151 |
+
.exam-quiz legend { margin-bottom: 8px; font-weight: bold; }
|
| 152 |
+
.exam-quiz label { display: flex; margin-left: 16px; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; }
|
| 153 |
+
.exam-quiz textarea { box-sizing: border-box; width: 100%; min-height: 80px; padding: 8px; background: #0d0d16; color: white; border: 1px solid #84718e; border-radius: 4px; font: inherit; resize: vertical; }
|
| 154 |
+
.exam-quiz .exam-quiz-confirm { padding: 12px; border: 1px solid #d49ce8; border-radius: 4px; }
|
| 155 |
+
.exam-quiz .exam-quiz-confirm p { margin: 0 0 10px; color: #ffd08f; }
|
| 156 |
+
.exam-quiz .exam-quiz-confirm button + button { margin-left: 8px; }
|
| 157 |
.exercise-panel-content { max-height: min(620px, calc(100dvh - 145px)); margin-top: 7px; padding: 12px; overflow-y: auto; overscroll-behavior: contain; background: #15151d; border: 1px solid #6b6771; border-radius: 6px; box-shadow: 0 18px 50px #0009; scrollbar-color: #d89b4d #101018; }
|
| 158 |
.exercise-panel-content strong { display: block; color: #ffad6b; letter-spacing: .06em; }
|
| 159 |
.exercise-panel-content h2 { margin: 9px 0; color: #ffad6b; font-size: 15px; }
|
app/test/apps-script.test.js
CHANGED
|
@@ -59,6 +59,32 @@ test('Apps Script submit all sends one email with every file, even when retried'
|
|
| 59 |
assert.equal(call({ action: 'submit', token: auth.token, exerciseId: 'nope', source: 'x', requestId: randomUUID() }).error, 'invalid_request');
|
| 60 |
});
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
test('Apps Script journal helpers stay identical to shared/examActivity.js', () => {
|
| 63 |
const { context } = load();
|
| 64 |
const log = journal(3, [{ at: 1000, state: 'active' }, { at: 4000, state: 'hidden' }, { at: 4500, state: 'unfocused' }, { at: 9000, state: 'active' }, { at: 12000, state: 'closed' }]);
|
|
|
|
| 59 |
assert.equal(call({ action: 'submit', token: auth.token, exerciseId: 'nope', source: 'x', requestId: randomUUID() }).error, 'invalid_request');
|
| 60 |
});
|
| 61 |
|
| 62 |
+
test('Apps Script quiz sends the answers once, then stays closed until the teacher resets it', () => {
|
| 63 |
+
const { call, mails, context } = load({ EXAM_ACCESS_CODE: 'code-secret', EXAM_RECIPIENT: 'prof@example.org' });
|
| 64 |
+
const auth = call({ action: 'access', code: 'code-secret', student: 'Élise Test' });
|
| 65 |
+
assert.equal(auth.quizDone, false);
|
| 66 |
+
assert.equal(auth.exam.quiz.length, 5);
|
| 67 |
+
const [first, , , , free] = auth.exam.quiz;
|
| 68 |
+
assert.equal(call({ action: 'quiz', answers: {} }).error, 'session_expired');
|
| 69 |
+
assert.equal(call({ action: 'quiz', token: auth.token, answers: { [first.id]: 'Pas un choix' } }).error, 'invalid_answers');
|
| 70 |
+
assert.equal(call({ action: 'quiz', token: auth.token, answers: { inconnue: 'x' } }).error, 'invalid_answers');
|
| 71 |
+
const body = { action: 'quiz', token: auth.token, answers: { [first.id]: first.choices[0], [free.id]: 'Réponse libre' } };
|
| 72 |
+
const receipt = call(body);
|
| 73 |
+
assert.match(receipt.id, /^quiz-/);
|
| 74 |
+
assert.deepEqual(call({ ...body, answers: {} }), receipt);
|
| 75 |
+
assert.equal(mails.length, 1);
|
| 76 |
+
assert.equal(mails[0].subject, '[Évaluation C] Élise Test — Quiz');
|
| 77 |
+
assert.match(mails[0].body, new RegExp(`1\\. ${first.question.replace(/[?]/g, '\\?')}\\n→ ${first.choices[0]}`));
|
| 78 |
+
assert.match(mails[0].body, /2\. .*\n→ \(sans réponse\)/);
|
| 79 |
+
assert.match(mails[0].body, /→ Réponse libre/);
|
| 80 |
+
assert.equal(mails[0].attachments[0].getName(), 'Elise-Test-quiz.txt');
|
| 81 |
+
const again = call({ action: 'access', code: 'code-secret', student: 'élise test' });
|
| 82 |
+
assert.equal(again.quizDone, true);
|
| 83 |
+
assert.deepEqual([...again.exam.quiz], []);
|
| 84 |
+
context.reinitialiserQuiz();
|
| 85 |
+
assert.equal(call({ action: 'session', token: auth.token }).quizDone, false);
|
| 86 |
+
});
|
| 87 |
+
|
| 88 |
test('Apps Script journal helpers stay identical to shared/examActivity.js', () => {
|
| 89 |
const { context } = load();
|
| 90 |
const log = journal(3, [{ at: 1000, state: 'active' }, { at: 4000, state: 'hidden' }, { at: 4500, state: 'unfocused' }, { at: 9000, state: 'active' }, { at: 12000, state: 'closed' }]);
|
app/test/appsScriptHarness.js
CHANGED
|
@@ -33,7 +33,7 @@ export function load(properties = { EXAM_ACCESS_CODE: 'code-secret' }) {
|
|
| 33 |
const props = new Map(Object.entries(properties)), cache = new Map(), drive = new Map(), mails = [];
|
| 34 |
const context = vm.createContext({
|
| 35 |
console,
|
| 36 |
-
PropertiesService: { getScriptProperties: () => ({ getProperty: key => props.get(key) ?? null, setProperty: (key, value) => props.set(key, value) }) },
|
| 37 |
CacheService: { getScriptCache: () => ({ get: key => cache.get(key) ?? null, put: (key, value) => cache.set(key, value), remove: key => cache.delete(key) }) },
|
| 38 |
LockService: { getScriptLock: () => ({ waitLock() {}, releaseLock() {} }) },
|
| 39 |
Session: { getEffectiveUser: () => ({ getEmail: () => 'teacher@example.org' }) },
|
|
|
|
| 33 |
const props = new Map(Object.entries(properties)), cache = new Map(), drive = new Map(), mails = [];
|
| 34 |
const context = vm.createContext({
|
| 35 |
console,
|
| 36 |
+
PropertiesService: { getScriptProperties: () => ({ getProperty: key => props.get(key) ?? null, setProperty: (key, value) => props.set(key, value), getKeys: () => [...props.keys()], deleteProperty: key => props.delete(key) }) },
|
| 37 |
CacheService: { getScriptCache: () => ({ get: key => cache.get(key) ?? null, put: (key, value) => cache.set(key, value), remove: key => cache.delete(key) }) },
|
| 38 |
LockService: { getScriptLock: () => ({ waitLock() {}, releaseLock() {} }) },
|
| 39 |
Session: { getEffectiveUser: () => ({ getEmail: () => 'teacher@example.org' }) },
|
app/test/browser/exam-apps-script.spec.js
CHANGED
|
@@ -30,15 +30,55 @@ test('static build submits the assessment through Google Apps Script', async ({
|
|
| 30 |
await expect(page.getByText('Code incorrect.')).toBeVisible();
|
| 31 |
await page.getByLabel('Code d’accès').fill('apps-script-code');
|
| 32 |
await page.getByRole('button', { name: 'Accéder à l’examen' }).click();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
for (let n = 1; n <= 5; n++) await expect(page.getByRole('button', { name: `Exercice ${n}`, exact: true })).toBeVisible();
|
| 34 |
await page.getByRole('button', { name: 'Exercice 2', exact: true }).click();
|
| 35 |
await page.getByLabel('C source code').fill('int main(void) { return 0; }');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
await page.getByRole('button', { name: 'Tout envoyer', exact: true }).click();
|
| 37 |
await expect(page.getByRole('button', { name: 'Tout envoyé', exact: true })).toBeDisabled();
|
| 38 |
-
expect(script.mails).toHaveLength(
|
| 39 |
-
expect(script.mails[
|
| 40 |
-
expect(script.mails[
|
| 41 |
-
expect(actions).toEqual(expect.arrayContaining(['access', 'activity', 'submit-all']));
|
| 42 |
});
|
| 43 |
|
| 44 |
test('assessment journal reports clues of outside help without flagging normal editing', async ({ page }) => {
|
|
@@ -53,6 +93,8 @@ test('assessment journal reports clues of outside help without flagging normal e
|
|
| 53 |
await page.getByLabel('Nom et prénom').fill('Élise Test');
|
| 54 |
await page.getByLabel('Code d’accès').fill('apps-script-code');
|
| 55 |
await page.getByRole('button', { name: 'Accéder à l’examen' }).click();
|
|
|
|
|
|
|
| 56 |
await page.getByRole('button', { name: 'Exercice 1', exact: true }).click();
|
| 57 |
const editor = page.getByLabel('C source code');
|
| 58 |
// Normal editing: typing, Enter, Tab, Ctrl+F reindent and a window resize.
|
|
@@ -64,7 +106,6 @@ test('assessment journal reports clues of outside help without flagging normal e
|
|
| 64 |
// Resizing the whole window is not a side panel.
|
| 65 |
await page.setViewportSize({ width: 1300, height: 900 });
|
| 66 |
await page.waitForTimeout(1200);
|
| 67 |
-
await expect(page.getByLabel('Suivi de présence')).toContainText('Indices d’aide extérieure : 0');
|
| 68 |
// Clues: a docked side panel, a pasted block, an inserted block, a scripted edit, an extension UI.
|
| 69 |
// A docked panel narrows the page but not the window: keep outerWidth fixed.
|
| 70 |
await page.evaluate(() => { const width = outerWidth; Object.defineProperty(window, 'outerWidth', { get: () => width }); });
|
|
@@ -83,10 +124,9 @@ test('assessment journal reports clues of outside help without flagging normal e
|
|
| 83 |
document.body.append(document.createElement('sider-sidebar'));
|
| 84 |
document.documentElement.setAttribute('data-gr-ext-installed', '');
|
| 85 |
});
|
| 86 |
-
await expect(page.getByLabel('Suivi de présence')).toContainText('Indices d’aide extérieure : 6');
|
| 87 |
await page.getByRole('button', { name: 'Tout envoyer', exact: true }).click();
|
| 88 |
await expect(page.getByRole('button', { name: 'Tout envoyé', exact: true })).toBeDisabled();
|
| 89 |
-
const report = script.mails
|
| 90 |
expect(report).toContain('6 signal(aux) d’aide extérieure possible');
|
| 91 |
expect(report).toContain('panneau latéral du navigateur ouvert / fermé | zone de la page : 1300 → 1100 px');
|
| 92 |
expect(report).toContain('collage | 42 caractères');
|
|
|
|
| 30 |
await expect(page.getByText('Code incorrect.')).toBeVisible();
|
| 31 |
await page.getByLabel('Code d’accès').fill('apps-script-code');
|
| 32 |
await page.getByRole('button', { name: 'Accéder à l’examen' }).click();
|
| 33 |
+
// The quiz comes first: exercises and the editor stay hidden until it is finished.
|
| 34 |
+
const quiz = page.getByLabel('Quiz', { exact: true });
|
| 35 |
+
await expect(quiz).toBeVisible();
|
| 36 |
+
await expect(page.getByRole('button', { name: 'Exercice 1', exact: true })).toHaveCount(0);
|
| 37 |
+
await expect(page.getByLabel('C source code')).toBeHidden();
|
| 38 |
+
await quiz.getByLabel('Jaune').check();
|
| 39 |
+
await quiz.getByLabel('return').check();
|
| 40 |
+
await quiz.getByRole('textbox').fill('Coin coin.');
|
| 41 |
+
await page.getByRole('button', { name: 'Terminer le quiz' }).scrollIntoViewIfNeeded();
|
| 42 |
+
await page.screenshot({ path: 'test-results/exam-quiz.png' });
|
| 43 |
+
// Answers survive a reload until the quiz is finished.
|
| 44 |
+
await page.reload();
|
| 45 |
+
await page.waitForFunction(() => window.__store?.getState().bootDone || window.__store?.getState().bootFailed);
|
| 46 |
+
await page.evaluate(() => window.__gameApi.startEntrance());
|
| 47 |
+
await page.waitForFunction(() => window.rl && !window.rl.inputLocked);
|
| 48 |
+
await page.getByRole('button', { name: 'CODE TRAINING', exact: true }).click();
|
| 49 |
+
await page.getByRole('button', { name: 'Evaluation', exact: true }).click();
|
| 50 |
+
await expect(quiz.getByLabel('Jaune')).toBeChecked();
|
| 51 |
+
await page.getByRole('button', { name: 'Terminer le quiz' }).click();
|
| 52 |
+
await expect(quiz).toContainText('2 question(s) sans réponse');
|
| 53 |
+
await page.getByRole('button', { name: 'Revenir au quiz' }).click();
|
| 54 |
+
expect(script.mails).toHaveLength(0);
|
| 55 |
+
await page.getByRole('button', { name: 'Terminer le quiz' }).click();
|
| 56 |
+
await page.getByRole('button', { name: 'Confirmer et envoyer' }).click();
|
| 57 |
+
await expect(quiz).toHaveCount(0);
|
| 58 |
+
expect(script.mails).toHaveLength(1);
|
| 59 |
+
expect(script.mails[0].subject).toBe('[Évaluation C] Élise Test — Quiz');
|
| 60 |
+
expect(script.mails[0].body).toContain('1. Question test 1 : de quelle couleur est Microduck ?\n→ Jaune');
|
| 61 |
+
expect(script.mails[0].body).toContain('2. Question test 2 : combien de pattes a un canard ?\n→ (sans réponse)');
|
| 62 |
+
expect(script.mails[0].body).toContain('→ Coin coin.');
|
| 63 |
for (let n = 1; n <= 5; n++) await expect(page.getByRole('button', { name: `Exercice ${n}`, exact: true })).toBeVisible();
|
| 64 |
await page.getByRole('button', { name: 'Exercice 2', exact: true }).click();
|
| 65 |
await page.getByLabel('C source code').fill('int main(void) { return 0; }');
|
| 66 |
+
// Once finished, the quiz never comes back, even after a reload.
|
| 67 |
+
await page.reload();
|
| 68 |
+
await page.waitForFunction(() => window.__store?.getState().bootDone || window.__store?.getState().bootFailed);
|
| 69 |
+
await page.evaluate(() => window.__gameApi.startEntrance());
|
| 70 |
+
await page.waitForFunction(() => window.rl && !window.rl.inputLocked);
|
| 71 |
+
await page.getByRole('button', { name: 'CODE TRAINING', exact: true }).click();
|
| 72 |
+
await page.getByRole('button', { name: 'Evaluation', exact: true }).click();
|
| 73 |
+
await page.getByRole('button', { name: 'Exercice 2', exact: true }).click();
|
| 74 |
+
await expect(quiz).toHaveCount(0);
|
| 75 |
+
await expect(page.getByLabel('C source code')).toHaveValue('int main(void) { return 0; }');
|
| 76 |
await page.getByRole('button', { name: 'Tout envoyer', exact: true }).click();
|
| 77 |
await expect(page.getByRole('button', { name: 'Tout envoyé', exact: true })).toBeDisabled();
|
| 78 |
+
expect(script.mails).toHaveLength(2);
|
| 79 |
+
expect(script.mails[1].attachments[1].getDataAsString()).toBe('int main(void) { return 0; }');
|
| 80 |
+
expect(script.mails[1].attachments[0].getDataAsString()).toBe('/* Non répondu */\n');
|
| 81 |
+
expect(actions).toEqual(expect.arrayContaining(['access', 'quiz', 'activity', 'submit-all']));
|
| 82 |
});
|
| 83 |
|
| 84 |
test('assessment journal reports clues of outside help without flagging normal editing', async ({ page }) => {
|
|
|
|
| 93 |
await page.getByLabel('Nom et prénom').fill('Élise Test');
|
| 94 |
await page.getByLabel('Code d’accès').fill('apps-script-code');
|
| 95 |
await page.getByRole('button', { name: 'Accéder à l’examen' }).click();
|
| 96 |
+
await page.getByRole('button', { name: 'Terminer le quiz' }).click();
|
| 97 |
+
await page.getByRole('button', { name: 'Confirmer et envoyer' }).click();
|
| 98 |
await page.getByRole('button', { name: 'Exercice 1', exact: true }).click();
|
| 99 |
const editor = page.getByLabel('C source code');
|
| 100 |
// Normal editing: typing, Enter, Tab, Ctrl+F reindent and a window resize.
|
|
|
|
| 106 |
// Resizing the whole window is not a side panel.
|
| 107 |
await page.setViewportSize({ width: 1300, height: 900 });
|
| 108 |
await page.waitForTimeout(1200);
|
|
|
|
| 109 |
// Clues: a docked side panel, a pasted block, an inserted block, a scripted edit, an extension UI.
|
| 110 |
// A docked panel narrows the page but not the window: keep outerWidth fixed.
|
| 111 |
await page.evaluate(() => { const width = outerWidth; Object.defineProperty(window, 'outerWidth', { get: () => width }); });
|
|
|
|
| 124 |
document.body.append(document.createElement('sider-sidebar'));
|
| 125 |
document.documentElement.setAttribute('data-gr-ext-installed', '');
|
| 126 |
});
|
|
|
|
| 127 |
await page.getByRole('button', { name: 'Tout envoyer', exact: true }).click();
|
| 128 |
await expect(page.getByRole('button', { name: 'Tout envoyé', exact: true })).toBeDisabled();
|
| 129 |
+
const report = script.mails.at(-1).attachments.at(-1).getDataAsString();
|
| 130 |
expect(report).toContain('6 signal(aux) d’aide extérieure possible');
|
| 131 |
expect(report).toContain('panneau latéral du navigateur ouvert / fermé | zone de la page : 1300 → 1100 px');
|
| 132 |
expect(report).toContain('collage | 42 caractères');
|
app/test/browser/exam.spec.js
CHANGED
|
@@ -1,13 +1,23 @@
|
|
| 1 |
import { test, expect } from '@playwright/test';
|
| 2 |
import { readdir } from 'node:fs/promises';
|
| 3 |
|
|
|
|
| 4 |
async function chooseExercise(page, name) {
|
| 5 |
const toggle = page.getByRole('button', { name: 'Sujets et évaluation', exact: true });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
if (await toggle.isVisible()) await toggle.click();
|
| 7 |
await page.getByRole('button', { name, exact: true }).click();
|
| 8 |
}
|
| 9 |
|
| 10 |
async function open(page) {
|
|
|
|
|
|
|
| 11 |
await page.goto('/?boot=1');
|
| 12 |
await page.waitForFunction(() => window.__store?.getState().bootDone || window.__store?.getState().bootFailed);
|
| 13 |
expect(await page.evaluate(() => window.__store.getState().bootFailed)).toBe(false);
|
|
@@ -191,7 +201,6 @@ test('submit all includes every draft and a durable activity log, with safe retr
|
|
| 191 |
});
|
| 192 |
await open(page);
|
| 193 |
await page.getByRole('button', { name: 'Evaluation', exact: true }).click();
|
| 194 |
-
await expect(page.getByLabel('Évaluation', { exact: true })).toContainText('transmis à l’enseignant');
|
| 195 |
await page.getByLabel('Nom et prénom').fill('Suivi Test');
|
| 196 |
await page.getByLabel('Code d’accès').fill('browser-test-code');
|
| 197 |
await page.getByRole('button', { name: 'Accéder à l’examen' }).click();
|
|
@@ -212,7 +221,6 @@ test('submit all includes every draft and a durable activity log, with safe retr
|
|
| 212 |
Object.defineProperty(document, 'hasFocus', { configurable: true, value: () => true });
|
| 213 |
document.dispatchEvent(new Event('visibilitychange'));
|
| 214 |
});
|
| 215 |
-
await expect(page.getByLabel('Suivi de présence')).toContainText('1');
|
| 216 |
let pending;
|
| 217 |
await page.route('**/api/exam/submit-all', async route => {
|
| 218 |
pending = route.request().postDataJSON();
|
|
|
|
| 1 |
import { test, expect } from '@playwright/test';
|
| 2 |
import { readdir } from 'node:fs/promises';
|
| 3 |
|
| 4 |
+
// The assessment opens on the quiz; the exercises appear once it is finished.
|
| 5 |
async function chooseExercise(page, name) {
|
| 6 |
const toggle = page.getByRole('button', { name: 'Sujets et évaluation', exact: true });
|
| 7 |
+
const quiz = page.getByLabel('Quiz', { exact: true });
|
| 8 |
+
await expect(quiz.or(toggle).or(page.getByRole('button', { name, exact: true })).first()).toBeVisible();
|
| 9 |
+
if (await quiz.isVisible()) {
|
| 10 |
+
await page.getByRole('button', { name: 'Terminer le quiz' }).click();
|
| 11 |
+
await page.getByRole('button', { name: 'Confirmer et envoyer' }).click();
|
| 12 |
+
await expect(quiz).toHaveCount(0);
|
| 13 |
+
}
|
| 14 |
if (await toggle.isVisible()) await toggle.click();
|
| 15 |
await page.getByRole('button', { name, exact: true }).click();
|
| 16 |
}
|
| 17 |
|
| 18 |
async function open(page) {
|
| 19 |
+
// The dev server has no mail credentials: accept the quiz here.
|
| 20 |
+
await page.route('**/api/exam/quiz', route => route.fulfill({ json: { id: 'quiz-receipt', sentAt: new Date().toISOString() } }));
|
| 21 |
await page.goto('/?boot=1');
|
| 22 |
await page.waitForFunction(() => window.__store?.getState().bootDone || window.__store?.getState().bootFailed);
|
| 23 |
expect(await page.evaluate(() => window.__store.getState().bootFailed)).toBe(false);
|
|
|
|
| 201 |
});
|
| 202 |
await open(page);
|
| 203 |
await page.getByRole('button', { name: 'Evaluation', exact: true }).click();
|
|
|
|
| 204 |
await page.getByLabel('Nom et prénom').fill('Suivi Test');
|
| 205 |
await page.getByLabel('Code d’accès').fill('browser-test-code');
|
| 206 |
await page.getByRole('button', { name: 'Accéder à l’examen' }).click();
|
|
|
|
| 221 |
Object.defineProperty(document, 'hasFocus', { configurable: true, value: () => true });
|
| 222 |
document.dispatchEvent(new Event('visibilitychange'));
|
| 223 |
});
|
|
|
|
| 224 |
let pending;
|
| 225 |
await page.route('**/api/exam/submit-all', async route => {
|
| 226 |
pending = route.request().postDataJSON();
|
app/test/exam.test.js
CHANGED
|
@@ -44,6 +44,30 @@ test('submit all validates a complete catalogue, sends one email, and retries wi
|
|
| 44 |
assert.equal((await request('submit-all', { ...body, copies: copies.map(item => ({ ...item, source: 'é'.repeat(33000) })) }, data.token)).status, 413);
|
| 45 |
});
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
test('activity is authenticated, validated and joined to submissions; teacher report is private', async t => {
|
| 48 |
let received;
|
| 49 |
const { login, request } = await setup(t, { env: { ...env, EXAM_ADMIN_SECRET: 'teacher-secret' }, sendMail: async value => { received = value; return { id: 'receipt' }; } });
|
|
|
|
| 44 |
assert.equal((await request('submit-all', { ...body, copies: copies.map(item => ({ ...item, source: 'é'.repeat(33000) })) }, data.token)).status, 413);
|
| 45 |
});
|
| 46 |
|
| 47 |
+
test('quiz answers are validated, sent once, and the quiz then closes', async t => {
|
| 48 |
+
let calls = 0, received;
|
| 49 |
+
const { login, request } = await setup(t, { sendMail: async value => { calls++; received = value; return { id: 'quiz-receipt' }; } });
|
| 50 |
+
const { data } = await login();
|
| 51 |
+
assert.equal(data.quizDone, false);
|
| 52 |
+
const [first, second] = data.exam.quiz;
|
| 53 |
+
assert.equal((await request('quiz', { answers: {} })).status, 401);
|
| 54 |
+
assert.equal((await request('quiz', { answers: { [first.id]: 'Pas un choix' } }, data.token)).status, 400);
|
| 55 |
+
const body = { answers: { [first.id]: first.choices[1] } };
|
| 56 |
+
const replies = await Promise.all([request('quiz', body, data.token), request('quiz', body, data.token)]);
|
| 57 |
+
assert.ok(replies.every(reply => reply.status === 200 && reply.data.id === 'quiz-receipt'));
|
| 58 |
+
assert.equal(calls, 1);
|
| 59 |
+
assert.match(received.quiz, new RegExp(`→ ${first.choices[1]}`));
|
| 60 |
+
assert.match(received.quiz, new RegExp(`${second.question.replace(/[?]/g, '\\?')}\\n→ \\(sans réponse\\)`));
|
| 61 |
+
const again = await login();
|
| 62 |
+
assert.equal(again.data.quizDone, true);
|
| 63 |
+
assert.deepEqual(again.data.exam.quiz, []);
|
| 64 |
+
let mail;
|
| 65 |
+
await sendExamEmail({ env, student: 'Élise Test', quiz: received.quiz, key: 'k', now: 0, fetchImpl: async (_, options) => { mail = JSON.parse(options.body); return { ok: true, json: async () => ({ id: 'x' }) }; } });
|
| 66 |
+
assert.equal(mail.subject, '[Évaluation C] Élise Test — Quiz');
|
| 67 |
+
assert.ok(mail.text.endsWith(received.quiz));
|
| 68 |
+
assert.deepEqual(mail.attachments.map(file => file.filename), ['Elise-Test-quiz.txt']);
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
test('activity is authenticated, validated and joined to submissions; teacher report is private', async t => {
|
| 72 |
let received;
|
| 73 |
const { login, request } = await setup(t, { env: { ...env, EXAM_ADMIN_SECRET: 'teacher-secret' }, sendMail: async value => { received = value; return { id: 'receipt' }; } });
|
docs/exam-apps-script.md
CHANGED
|
@@ -26,9 +26,17 @@ Le code du script se trouve dans `app/apps-script/Code.gs`. Le test `app/test/ap
|
|
| 26 |
|
| 27 |
L’URL n’est pas secrète : sans le code d’accès, le script refuse toute demande.
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
## Pendant et après l’évaluation
|
| 30 |
|
| 31 |
-
- Les emails arrivent avec le sujet `[Évaluation C] Nom — Exercice n` ou `— Tous les exercices`.
|
| 32 |
- Le dossier Drive **Évaluation C** contient `copies/` (chaque fichier envoyé, horodaté) et `suivi/` (les journaux, y compris ceux des étudiants qui n’ont rien envoyé).
|
| 33 |
- Rapport de suivi de toute la classe : dans l’éditeur, exécuter `rapportDeSuivi`, puis lire le journal d’exécution.
|
| 34 |
- Changer le code d’accès : modifier la propriété `EXAM_ACCESS_CODE`. C’est immédiat, sans redéploiement.
|
|
|
|
| 26 |
|
| 27 |
L’URL n’est pas secrète : sans le code d’accès, le script refuse toute demande.
|
| 28 |
|
| 29 |
+
## Le quiz d’ouverture
|
| 30 |
+
|
| 31 |
+
L’évaluation commence par un quiz. Les exercices restent cachés jusqu’à ce que l’étudiant clique sur **Terminer le quiz** puis **Confirmer et envoyer**. Ses réponses partent alors par email (sujet `[Évaluation C] Nom — Quiz`, une copie dans `copies/`) et le quiz ne s’affiche plus, même après rechargement ou changement de navigateur : le script retient qu’il est terminé.
|
| 32 |
+
|
| 33 |
+
- **Changer les questions** : modifier la liste `QUIZ` en haut de `Code.gs`, puis publier une nouvelle version (voir plus bas). Une question avec `choices` est un QCM ; sans `choices`, la réponse est libre.
|
| 34 |
+
- **Après un essai** : exécuter `reinitialiserQuiz` dans l’éditeur pour que tout le monde puisse refaire le quiz. Changer `EXAM_ID` a le même effet et repart aussi de brouillons vides.
|
| 35 |
+
- Les réponses du quiz sont gardées dans le navigateur jusqu’à l’envoi, un rechargement ne les perd pas.
|
| 36 |
+
|
| 37 |
## Pendant et après l’évaluation
|
| 38 |
|
| 39 |
+
- Les emails arrivent avec le sujet `[Évaluation C] Nom — Quiz`, `— Exercice n` ou `— Tous les exercices`.
|
| 40 |
- Le dossier Drive **Évaluation C** contient `copies/` (chaque fichier envoyé, horodaté) et `suivi/` (les journaux, y compris ceux des étudiants qui n’ont rien envoyé).
|
| 41 |
- Rapport de suivi de toute la classe : dans l’éditeur, exécuter `rapportDeSuivi`, puis lire le journal d’exécution.
|
| 42 |
- Changer le code d’accès : modifier la propriété `EXAM_ACCESS_CODE`. C’est immédiat, sans redéploiement.
|