ExamService.php 20 KB

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