ExamService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User : zgcLives
  5. * CreateTime : 2022/4/16 16:21
  6. */
  7. namespace addons\exam\library;
  8. use addons\exam\enum\CommonStatus;
  9. use addons\exam\enum\PaperMode;
  10. use addons\exam\enum\RoomSignupStatus;
  11. use addons\exam\model\GradeModel;
  12. use addons\exam\model\PaperModel;
  13. use addons\exam\model\QuestionModel;
  14. use addons\exam\model\RoomGradeModel;
  15. use addons\exam\model\RoomModel;
  16. use addons\exam\model\RoomSignupModel;
  17. use app\admin\model\exam\MaterialQuestionModel;
  18. /**
  19. * 考试相关服务
  20. */
  21. class ExamService
  22. {
  23. /**
  24. * 获取试卷题目
  25. * @param $paper_id
  26. * @param int $room_id
  27. * @return array`
  28. */
  29. public static function getExamQuestion($paper_id, $room_id = 0)
  30. {
  31. if (!$paper_id) {
  32. fail('缺少试卷ID');
  33. }
  34. $paper = self::validPaper($paper_id, $room_id);
  35. switch ($paper['mode']) {
  36. case PaperMode::RANDOM:
  37. $questions = self::getRandomQuestions($paper);
  38. break;
  39. case PaperMode::FIX:
  40. $questions = self::getFixQuestions($paper);
  41. break;
  42. default:
  43. fail('试卷取题模式有误');
  44. }
  45. return [
  46. 'paper' => $paper,
  47. 'questions' => $questions,
  48. 'start_time' => time(),
  49. ];
  50. }
  51. /**
  52. * 获取试卷随机题
  53. * @param $paper
  54. * @return array
  55. */
  56. public static function getRandomQuestions($paper)
  57. {
  58. $configs = $paper->configs;
  59. $questions = [];
  60. if (!isset($configs['cate_ids'])) {
  61. fail('试卷随机取题配置有误');
  62. }
  63. foreach (QuestionModel::kindList as $kind) {
  64. if (!isset($configs[strtolower($kind)])) {
  65. continue;
  66. }
  67. $kind_config = $configs[strtolower($kind)];
  68. // 使用难度选题
  69. if ($kind_config['use_difficulty']) {
  70. foreach ($kind_config['difficulty'] as $difficulty => $value) {
  71. if ($value['count']) {
  72. $question = QuestionModel::getListByCateAndKind($configs['cate_ids'], $kind, ['materialQuestions.question']);
  73. $questions = array_merge(
  74. $questions,
  75. $question->where('difficulty', $difficulty)->limit($value['count'])->select()
  76. // hidden_list_keys($question->where('difficulty', $difficulty)->limit($value['count'])->select(), ['answer', 'explain'])
  77. );
  78. }
  79. }
  80. } else {
  81. if ($kind_config['count']) {
  82. $question = QuestionModel::getListByCateAndKind($configs['cate_ids'], $kind, ['materialQuestions.question']);
  83. // dd(collection($question->limit($kind_config['count'])->select())->toArray());
  84. $questions = array_merge(
  85. $questions,
  86. $question->limit($kind_config['count'])->select()
  87. // hidden_list_keys($question->limit($kind_config['count'])->select(), ['answer', 'explain'])
  88. );
  89. }
  90. }
  91. }
  92. // 合并材料题子题目
  93. $questions = QuestionModel::mergeMaterialQuestions($questions);
  94. return hidden_list_keys($questions, ['answer', 'explain', 'origin_answer']);
  95. }
  96. /**
  97. * 获取试卷固定题
  98. * @param $paper
  99. * @return array
  100. */
  101. public static function getFixQuestions($paper, $hidden = true)
  102. {
  103. $questions = QuestionModel::getFixListByPaper($paper['id'], ['materialQuestions.question']);
  104. // 合并材料题子题目
  105. $questions = QuestionModel::mergeMaterialQuestions($questions);
  106. if ($hidden) {
  107. return hidden_list_keys($questions, ['answer', 'explain', 'origin_answer']);
  108. }
  109. return $questions;
  110. }
  111. /**
  112. * 试卷考试
  113. * @param $user_id
  114. * @param $paper_id
  115. * @param $user_questions
  116. * @param $start_time
  117. * @param $paper
  118. * @return array
  119. */
  120. public static function paperExam($user_id, $paper_id, $user_questions, $start_time, &$paper, $from_room = false)
  121. {
  122. // 验证试卷
  123. $paper = self::validPaper($paper_id, $from_room ? 1 : 0);
  124. if (!$questions_ids = array_column($user_questions, 'id')) {
  125. fail('提交的题目数据有误');
  126. }
  127. $answers = array_column($user_questions, 'answer'); // 用户答案
  128. $material_ids = array_column($user_questions, 'material_id'); // 材料题id
  129. $total_score = 0; // 试卷总分
  130. $error_count = 0; // 错误题目数量
  131. $error_ids = []; //错误题目id
  132. if ($paper['mode'] == PaperMode::RANDOM) {
  133. $questions = QuestionModel::whereIn('id', $questions_ids)->orderRaw("find_in_set(id, '" . implode(',', $questions_ids) . "')")->select();
  134. } else {
  135. $questions = self::getFixQuestions($paper, false);
  136. }
  137. // 材料题分数
  138. $material_score = [];
  139. foreach ($questions as $key => $question) {
  140. $score = 0;
  141. // 随机取题
  142. if ($paper['mode'] == PaperMode::RANDOM) {
  143. $kind = $question['kind'];
  144. $difficulty = $question['difficulty'];
  145. // 属于材料题子题
  146. if (isset($material_ids[$key]) && $material_ids[$key]) {
  147. if ($material_question = QuestionModel::where('id', $material_ids[$key])->cache(60)->find()) {
  148. $kind = 'MATERIAL';
  149. $difficulty = $material_question['difficulty'];
  150. // $score = PaperModel::getSingleScore($paper['configs'], strtolower($kind), strtolower($difficulty)); // 每题分数
  151. // 材料题子题目设定的分数
  152. $score = MaterialQuestionModel::where('parent_question_id', $material_ids[$key])->where('question_id', $question['id'])->cache(60)->value('score');
  153. }
  154. } else {
  155. $score = PaperModel::getSingleScore($paper['configs'], strtolower($kind), strtolower($difficulty)); // 每题分数
  156. }
  157. } else {
  158. // 固定取题
  159. $score = $question['score'];
  160. if ($question['id'] == 764) {
  161. // dd([$score, $question, isset($material_ids[$key]), $material_ids[$key]]);
  162. }
  163. }
  164. switch ($question['kind']) {
  165. case 'JUDGE': // 判断题
  166. case 'SINGLE': // 单选题
  167. case 'MULTI': // 多选题
  168. // 答题正确
  169. if (strtoupper($answers[$key]) == $question['answer']) {
  170. $total_score += $score;
  171. $user_questions[$key]['is_right'] = true;
  172. } else {
  173. array_push($error_ids, $question['id']);
  174. $error_count++;
  175. $user_questions[$key]['is_right'] = false;
  176. // 记录错题
  177. QuestionModel::recordWrong($question['id'], $user_id, $answers[$key]);
  178. // $question->logWrong($user_id, $answers[$key]);
  179. }
  180. break;
  181. case 'FILL': // 填空题
  182. $user_answers = $answers[$key];
  183. $fill_right_count = 0;
  184. $question['answer'] = is_array($question['answer']) ? $question['answer'] : json_decode($question['answer'], true);
  185. foreach ($question['answer'] as $fill_key => $fill_answer) {
  186. foreach ($fill_answer['answers'] as $answer) {
  187. if (isset($user_answers[$fill_key]) && str_trim($user_answers[$fill_key]) == str_trim($answer)) {
  188. $fill_right_count++;
  189. break;
  190. }
  191. }
  192. }
  193. // 所有填空项全对
  194. if ($fill_right_count == count($question['answer'])) {
  195. $user_questions[$key]['is_right'] = true;
  196. $total_score += $score;
  197. } else {
  198. $user_questions[$key]['is_right'] = false;
  199. array_push($error_ids, $question['id']);
  200. $error_count++;
  201. // 记录错题
  202. QuestionModel::recordWrong($question['id'], $user_id, $answers[$key]);
  203. // $question->logWrong($user_id, $answers[$key]);
  204. }
  205. break;
  206. case 'SHORT': // 简答题
  207. // 答案得分配置
  208. $answer_config = is_string($question['answer']) ? json_decode($question['answer'], true) : $question['answer'];
  209. $user_answers = $answers[$key];
  210. $right_score = 0;
  211. $answer_score = [];
  212. foreach ($answer_config['config'] as $answer_item) {
  213. if ($right_score < $score) {
  214. // 匹配答案关键词
  215. if (strpos($user_answers, $answer_item['answer']) !== false) {
  216. $right_score += $answer_item['score'];
  217. // 得分情况
  218. $answer_score[] = [
  219. 'answer' => $answer_item['answer'],
  220. 'score' => min($score, $answer_item['score']),
  221. 'keyword_score' => $answer_item['score'],
  222. 'max_score' => $score,
  223. ];
  224. }
  225. }
  226. }
  227. // 最高得分不能超过题目分数
  228. $right_score = min($right_score, $score);
  229. // 有得分
  230. if ($right_score > 0) {
  231. $user_questions[$key]['is_right'] = true;
  232. $total_score += $right_score;
  233. } else {
  234. $user_questions[$key]['is_right'] = false;
  235. array_push($error_ids, $question['id']);
  236. $error_count++;
  237. // 记录错题
  238. QuestionModel::recordWrong($question['id'], $user_id, $answers[$key]);
  239. }
  240. $user_questions[$key]['answer_score'] = $answer_score;
  241. break;
  242. }
  243. }
  244. // 递增参与人次
  245. $paper->setInc('join_count');
  246. return [
  247. 'total_score' => $paper['total_score'], // 试卷总分
  248. 'score' => $total_score, // 考试分数
  249. 'is_pass' => $total_score >= $paper['pass_score'], // 是否及格
  250. 'pass_score' => $paper['pass_score'], // 及格分数
  251. 'total_count' => count($questions), // 题目数量
  252. 'right_count' => count($questions) - $error_count, // 答对数量
  253. 'error_count' => $error_count, // 答错数量
  254. 'start_time' => $start_time, // 开始时间
  255. 'grade_time' => $paper['limit_time'] ? min(time() - $start_time, $paper['limit_time']) : time() - $start_time,// 考试用时
  256. 'error_ids' => implode(',', $error_ids), // 错误题目id
  257. 'question_ids' => implode(',', $questions_ids), // 试题ID集合
  258. 'user_answers' => json_encode($user_questions, JSON_UNESCAPED_UNICODE), // 用户答案集合
  259. 'configs' => json_encode($paper['configs']), // 试卷配置
  260. 'mode' => $paper['mode'], // 试卷选题模式
  261. ];
  262. }
  263. /**
  264. * 考场考试
  265. * @param $user_id
  266. * @param $room_id
  267. * @param $room_grade_id
  268. * @param $questions
  269. * @param $start_time
  270. * @param $paper
  271. * @param $room
  272. * @param $is_makeup
  273. * @param RoomGradeModel|null $room_grade_log
  274. * @return array
  275. */
  276. public static function roomExam($user_id, $room_id, $room_grade_id, $questions, $start_time, &$paper, &$room, &$is_makeup, &$room_grade_log)
  277. {
  278. // 验证考场信息
  279. $room = self::validRoom($user_id, $room_id, $room_grade_id, $is_makeup, $room_grade_log);
  280. return self::paperExam($user_id, $room['paper_id'], $questions, $start_time, $paper, true);
  281. }
  282. /**
  283. * 预创建考场考试记录(消耗一次考试记录,避免重复进入考场看题)
  284. * @param $room_id
  285. * @param $user_id
  286. * @return int
  287. */
  288. public static function preRoomGrade($room_id, $user_id)
  289. {
  290. if (!$room_id) {
  291. return 0;
  292. }
  293. // 验证考场信息
  294. $room = self::validRoom($user_id, $room_id, 0, $is_makeup);
  295. // 创建考场考试记录
  296. $grade = RoomGradeModel::create([
  297. 'user_id' => $user_id,
  298. 'room_id' => $room_id,
  299. 'cate_id' => $room['cate_id'],
  300. 'paper_id' => $room['paper_id'],
  301. 'score' => 0,
  302. 'is_pass' => 0,
  303. 'is_makeup' => $is_makeup,
  304. 'total_score' => $room['paper']['total_score'],
  305. 'total_count' => $room['paper']['quantity'],
  306. 'right_count' => 0,
  307. 'error_count' => $room['paper']['quantity'],
  308. 'rank' => 0,
  309. 'is_pre' => 1,// 标记为预载入,提交成绩时须改为0
  310. 'grade_time' => 0,
  311. ]);
  312. return $grade['id'];
  313. }
  314. /**
  315. * 验证试卷
  316. * @param int $paper_id 试卷ID
  317. * @param int $room_id 考场ID
  318. * @return PaperModel|null
  319. */
  320. private static function validPaper($paper_id, $room_id = 0)
  321. {
  322. $paper = PaperModel::get($paper_id);
  323. $user_id = getUserId();
  324. switch (true) {
  325. case !$paper:
  326. fail('试卷信息不存在');
  327. case $paper->status != CommonStatus::NORMAL:
  328. fail('试卷未开启');
  329. case $paper->mode == PaperMode::RANDOM && !$paper->configs:
  330. fail('试卷未配置');
  331. }
  332. // 普通考试
  333. if (!$room_id) {
  334. if ($user_id && $paper['day_limit_count'] > 0 && GradeModel::getUserDateGradeCount($paper_id, $user_id) >= $paper['day_limit_count']) {
  335. fail('当前试卷考试次数已达今日上限,明天再来吧~');
  336. }
  337. if ($paper['end_time'] > 0 && $paper['end_time'] < time()) {
  338. fail('该试卷已失效,不能参与考试了');
  339. }
  340. }
  341. return $paper;
  342. }
  343. /**
  344. * 验证考场
  345. * @param int $user_id 考试用户
  346. * @param int $room_id 试卷ID
  347. * @param int $room_grade_id 考场预创建成绩ID
  348. * @param int $is_makeup 返回是否是补考
  349. * @param RoomGradeModel|null $room_grade_log 预创建的成绩记录
  350. * @return RoomModel|null
  351. */
  352. private static function validRoom($user_id, $room_id, $room_grade_id, &$is_makeup, &$room_grade_log = null)
  353. {
  354. $room = RoomModel::get($room_id);
  355. switch (true) {
  356. case !$room:
  357. fail('考场信息不存在');
  358. case $room['status'] != CommonStatus::NORMAL:
  359. fail('考场未开启');
  360. case time() < $room['start_time'] || time() > $room['end_time']:
  361. fail('考场时间未开始或已结束');
  362. case !$roomSignup = RoomSignupModel::where('room_id', $room_id)->where('user_id', $user_id)->find():
  363. fail('您尚未报名此考场');
  364. case $roomSignup['status'] != RoomSignupStatus::ACCEPT:
  365. fail('您的考场报名信息状态有误');
  366. }
  367. // 考场允许补考
  368. if ($room['is_makeup'] == 1 && $room['makeup_count'] > 0) {
  369. // $query = RoomGradeModel::where('room_id', $room_id)->where('paper_id', $room['paper_id'])->where('user_id', $user_id);
  370. // 考试次数
  371. $room_exam_count = RoomGradeModel::where('room_id', $room_id)->where('paper_id', $room['paper_id'])->where('user_id', $user_id)->count();
  372. // 补考次数
  373. $makeup_count = RoomGradeModel::where('room_id', $room_id)->where('paper_id', $room['paper_id'])->where('user_id', $user_id)->where('is_makeup', 1)->count();
  374. $min_makeup_count = $makeup_count - ($room_grade_id ? 1 : 0);
  375. if ($min_makeup_count >= $room['makeup_count']) {
  376. fail("已超过补考次数");
  377. }
  378. $last_exam_log = RoomGradeModel::where('room_id', $room_id)->where('paper_id', $room['paper_id'])->where('user_id', $user_id)->order('id desc')->find();
  379. if ($last_exam_log && $last_exam_log['is_pass'] != 0) {
  380. fail('最后一次考试已及格,不需要补考了');
  381. }
  382. // 考试次数大于0视为补考
  383. $is_makeup = $room_exam_count > 1 ? 1 : 0;
  384. } else {
  385. if (RoomGradeModel::where('room_id', $room_id)->where('user_id', $user_id)->where('is_pre', 0)->count() > 0) {
  386. fail('您已参加过该考场考试了');
  387. }
  388. $is_makeup = 0;
  389. }
  390. // 考场预创建记录验证
  391. if ($room_grade_id) {
  392. if (!$room_grade_log = RoomGradeModel::where('id', $room_grade_id)->where('user_id', $user_id)->find()) {
  393. fail('考场成绩错误');
  394. } else if ($room_grade_log['is_pre'] == 0) {
  395. fail('本次考场考试已提交过成绩了,请勿重复提交');
  396. }
  397. }
  398. return $room;
  399. }
  400. }