From c20ed86aa6b1a071d28099e89c59976ac91c4e87 Mon Sep 17 00:00:00 2001 From: phgkfux43 <3469266505@qq.com> Date: Sat, 26 Apr 2025 22:38:17 +0800 Subject: [PATCH] ADD file via upload --- results.js | 93 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 results.js diff --git a/results.js b/results.js new file mode 100644 index 0000000..e908f86 --- /dev/null +++ b/results.js @@ -0,0 +1,93 @@ +const Result = require('../models/Result'); +const Exam = require('../models/Exam'); + +// 提交考试结果 +exports.submitResult = async (req, res, next) => { + try { + const { examId, answers, timeTaken } = req.body; + + // 验证考试 + const exam = await Exam.findById(examId); + if (!exam) { + return res.status(404).json({ message: 'Exam not found' }); + } + + // 计算分数 + let totalScore = 0; + const answerResults = exam.questions.map(question => { + const userAnswer = answers[question._id]; + let isCorrect = false; + let score = 0; + + if (question.type === 'text') { + // 简答题默认给一半分 + if (userAnswer && userAnswer.trim().length > 0) { + isCorrect = true; + score = question.score / 2; + } + } else if (Array.isArray(question.answer)) { + // 多选题 + const correctAnswers = [...question.answer].sort().toString(); + const userAns = [...userAnswer].sort().toString(); + isCorrect = correctAnswers === userAns; + score = isCorrect ? question.score : 0; + } else { + // 单选题 + isCorrect = userAnswer === question.answer; + score = isCorrect ? question.score : 0; + } + + totalScore += score; + + return { + questionId: question._id, + userAnswer, + isCorrect, + score + }; + }); + + // 保存结果 + const result = new Result({ + exam: examId, + user: req.user.id, + answers: answerResults, + totalScore, + maxScore: exam.questions.reduce((sum, q) => sum + q.score, 0), + timeTaken + }); + + await result.save(); + + res.status(201).json(result); + } catch (err) { + next(err); + } +}; + +// 获取用户成绩 +exports.getUserResults = async (req, res, next) => { + try { + const results = await Result.find({ user: req.user.id }) + .populate('exam', 'title description') + .sort({ submittedAt: -1 }); + + res.json(results); + } catch (err) { + next(err); + } +}; + +// 获取考试所有成绩 (教师/管理员) +exports.getExamResults = async (req, res, next) => { + try { + const results = await Result.find({ exam: req.params.id }) + .populate('user', 'username') + .populate('exam', 'title') + .sort({ totalScore: -1 }); + + res.json(results); + } catch (err) { + next(err); + } +}; \ No newline at end of file