Exam.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. <?php
  2. namespace app\admin\controller\train;
  3. use app\admin\model\train\QuestionModel;
  4. use app\admin\model\train\TrainAdmin;
  5. use app\admin\model\train\TrainExamReAdmin;
  6. use app\admin\model\train\TrainExamReQuestion;
  7. use app\admin\model\train\TrainExamResult;
  8. use app\admin\model\train\TrainExamResultRecord;
  9. use app\admin\library\DingTalk;
  10. use app\admin\service\train\TrainService;
  11. use app\common\controller\Backend;
  12. use think\Db;
  13. use think\Exception;
  14. use think\exception\PDOException;
  15. use think\exception\ValidateException;
  16. /**
  17. * 培训-考试
  18. *
  19. * @icon fa fa-circle-o
  20. */
  21. class Exam extends Backend
  22. {
  23. /**
  24. * TrainExam模型对象
  25. * @var \app\admin\model\train\TrainExam
  26. */
  27. protected $model = null;
  28. protected $noNeedRight = ['managequestions', 'examquestionlist', 'removequestions', 'adminindex', 'manageadmins', 'examadminlist', 'removeadmins', 'pushexam', 'setscore', 'updateexamtotalscore', 'showmistakes', 'getexam'];
  29. public function _initialize()
  30. {
  31. parent::_initialize();
  32. $this->model = new \app\admin\model\train\TrainExam;
  33. }
  34. public function manageQuestions($ids)
  35. {
  36. if($this->request->isAjax()){
  37. $question_ids = $this->request->param('question_ids/a');
  38. $exam_question_ids = model(TrainExamReQuestion::class)
  39. ->where('exam_id', $ids)
  40. ->column('question_id');
  41. $new_question_ids = array_diff($question_ids, $exam_question_ids);
  42. $save = [];
  43. foreach ($new_question_ids as $question_id){
  44. $save[] = [
  45. 'exam_id' => $ids,
  46. 'question_id' => $question_id,
  47. ];
  48. }
  49. $res = model(TrainExamReQuestion::class)->insertAll($save);
  50. if(!$res){
  51. $this->error('没有可添加的题目');
  52. }
  53. $this->updateExamTotalScore($ids);
  54. $this->success('成功添加' . $res . '条');
  55. }
  56. $this->view->ids = $ids;
  57. return $this->view->fetch('manage_questions');
  58. }
  59. public function examQuestionList($ids)
  60. {
  61. $exam = $this->model->get($ids);
  62. $this->view->ids = $ids;
  63. $this->view->exam_titile = $exam['title'];
  64. $this->view->status = $exam['status'];
  65. $this->view->total = $exam['total'];
  66. $this->view->qualified = $exam['qualified'];
  67. return $this->view->fetch('question_list');
  68. }
  69. public function removeQuestions($ids)
  70. {
  71. $question_ids = $this->request->param('question_ids/a');
  72. $res = model(TrainExamReQuestion::class)
  73. ->where('exam_id', $ids)
  74. ->whereIn('question_id', $question_ids)
  75. ->delete();
  76. if(!$res){
  77. $this->error('没有可移除的题目');
  78. }
  79. $this->success('成功移除' . $res . '条');
  80. }
  81. /**
  82. * 查看
  83. */
  84. public function adminIndex()
  85. {
  86. //设置过滤方法
  87. $this->request->filter(['strip_tags']);
  88. if ($this->request->isAjax()) {
  89. //如果发送的来源是Selectpage,则转发到Selectpage
  90. if ($this->request->request('keyField')) {
  91. return $this->selectpage();
  92. }
  93. list($where, $sort, $order, $offset, $limit) = $this->buildparams('name');
  94. $exam_where = false;
  95. if($this->request->has('show_exam_id')){
  96. $admin_ids = model(TrainExamReAdmin::class)
  97. ->whereIn('exam_id', $this->request->param('show_exam_id'))
  98. ->column('admin_id');
  99. $exam_where = [
  100. 'id' => ['in', $admin_ids]
  101. ];
  102. }
  103. $total = model(TrainAdmin::class)
  104. ->where($where)
  105. ->where($exam_where)
  106. ->order($sort, $order)
  107. ->count();
  108. $list = model(TrainAdmin::class)
  109. ->where($where)
  110. ->where($exam_where)
  111. ->order($sort, $order)
  112. ->limit($offset, $limit)
  113. ->select();
  114. if($list){
  115. if($this->request->has('exam_id')){
  116. $admin_ids = model(TrainExamReAdmin::class)
  117. ->whereIn('exam_id', $this->request->param('exam_id'))
  118. ->column('admin_id');
  119. foreach ($list as &$val){
  120. $val['checkbox'] = in_array($val['id'], $admin_ids) ? 1 : 0;
  121. }
  122. unset($val);
  123. }
  124. if($this->request->has('show_exam_id')){
  125. $admin_ids = array_column($list,'id');
  126. $result_arr = TrainService::instance()->getResultByAdminIds($this->request->param('show_exam_id'), $admin_ids);
  127. foreach ($list as &$val){
  128. $val['result_id'] = $result_arr[$val['id']]['result_id'] ?? NULL;
  129. $val['status'] = $result_arr[$val['id']]['status'] ?? 0;
  130. $val['scores'] = $result_arr[$val['id']]['scores'] ?? 0;
  131. $val['is_qualified'] = $result_arr[$val['id']]['is_qualified'] ?? 0;
  132. }
  133. unset($val);
  134. }
  135. }
  136. $list = collection($list)->toArray();
  137. $result = array("total" => $total, "rows" => $list);
  138. return json($result);
  139. }
  140. return $this->view->fetch();
  141. }
  142. public function manageAdmins($ids)
  143. {
  144. if($this->request->isAjax()){
  145. $admin_ids = $this->request->param('admin_ids/a');
  146. $exam_admins_ids = model(TrainExamReAdmin::class)
  147. ->where('exam_id', $ids)
  148. ->column('admin_id');
  149. $new_admin_ids = array_diff($admin_ids, $exam_admins_ids);
  150. $save = [];
  151. foreach ($new_admin_ids as $admin_id){
  152. $save[] = [
  153. 'exam_id' => $ids,
  154. 'admin_id' => $admin_id,
  155. ];
  156. }
  157. $res = model(TrainExamReAdmin::class)->insertAll($save);
  158. if(!$res){
  159. $this->error('没有可添加的考生');
  160. }
  161. $this->success('成功添加' . $res . '条');
  162. }
  163. $this->view->ids = $ids;
  164. return $this->view->fetch('manage_admins');
  165. }
  166. public function examAdminList($ids)
  167. {
  168. $exam = $this->model->get($ids);
  169. $this->view->ids = $ids;
  170. $this->view->exam_titile = $exam['title'];
  171. $this->view->total = $exam['total'];
  172. $this->view->qualified = $exam['qualified'];
  173. $this->view->status = $exam['status'];
  174. return $this->view->fetch('admin_list');
  175. }
  176. public function removeAdmins($ids)
  177. {
  178. $admin_ids = $this->request->param('admin_ids/a');
  179. $res = model(TrainExamReAdmin::class)
  180. ->where('exam_id', $ids)
  181. ->whereIn('admin_id', $admin_ids)
  182. ->delete();
  183. if(!$res){
  184. $this->error('没有可移除的考生');
  185. }
  186. $this->success('成功移除' . $res . '人');
  187. }
  188. public function pushExam($ids, DingTalk $dingTalkService)
  189. {
  190. Db::startTrans();
  191. $res = $this->model
  192. ->where('id', $ids)
  193. ->update([
  194. 'status' => 1,
  195. 'push_time' => date('Y-m-d H:i:s'),
  196. 'push_admin_id' => $this->auth->id
  197. ]);
  198. if(!$res){
  199. Db::rollback();
  200. $this->error('修改考试状态失败');
  201. }
  202. $admin_ids = model(TrainExamReAdmin::class)
  203. ->whereIn('exam_id', $ids)
  204. ->column('admin_id');
  205. $save = [];
  206. foreach ($admin_ids as $admin_id){
  207. $save[] = [
  208. 'exam_id' => $ids,
  209. 'admin_id' => $admin_id
  210. ];
  211. }
  212. $res = model(TrainExamResult::class)
  213. ->insertAll($save);
  214. if(!$res){
  215. Db::rollback();
  216. $this->error('创建考试成绩表数据失败');
  217. }
  218. // 发送钉钉消息
  219. $exam = $this->model->get($ids);
  220. $token = $dingTalkService->getToken();
  221. $user_ids = implode(',', model(TrainAdmin::class)->whereIn('id', $admin_ids)->column('userid'));
  222. $dingTalkService->sendWorkNotice($token, [
  223. 'exam_title' => $exam['title'],
  224. 'start_time' => date('Y-m-d H:i', strtotime($exam['start_time'])),
  225. 'end_time' => date('Y-m-d H:i', strtotime($exam['end_time'])),
  226. 'qualified' => $exam['qualified'],
  227. 'single_title' => "中世大学",
  228. ], $user_ids);
  229. Db::commit();
  230. $this->success('发布成功');
  231. }
  232. public function setScore()
  233. {
  234. $params = $this->request->param();
  235. $score = (int) $params['score'];
  236. if(!is_numeric($score) || $score <= 0 ){
  237. $this->error('设置分数格式错误,请输入大于0的数字');
  238. }
  239. Db::startTrans();
  240. $res = model(TrainExamReQuestion::class)
  241. ->where('exam_id', $params['ids'])
  242. ->whereIn('question_id', $params['question_ids'])
  243. ->update([
  244. 'score' => $params['score']
  245. ]);
  246. if($res === false){
  247. Db::rollback();
  248. $this->error('设置分数失败');
  249. }
  250. $res = $this->updateExamTotalScore($params['ids']);
  251. if(!$res){
  252. Db::rollback();
  253. $this->error('更新考试总分失败');
  254. }
  255. Db::commit();
  256. $this->success('设置成功');
  257. }
  258. /**
  259. * 更新考试总分
  260. * @param $exam_id
  261. * @return bool
  262. */
  263. protected function updateExamTotalScore($exam_id)
  264. {
  265. $total = model(TrainExamReQuestion::class)
  266. ->where('exam_id', $exam_id)
  267. ->sum('score');
  268. if(!is_numeric($total) || $total <= 0){
  269. return false;
  270. }
  271. $res = $this->model
  272. ->where('id', $exam_id)
  273. ->update([
  274. 'total' => $total
  275. ]);
  276. return $res !== false;
  277. }
  278. public function del($ids = "")
  279. {
  280. if ($ids) {
  281. $pk = $this->model->getPk();
  282. $adminIds = $this->getDataLimitAdminIds();
  283. if (is_array($adminIds)) {
  284. $this->model->where($this->dataLimitField, 'in', $adminIds);
  285. }
  286. Db::startTrans();
  287. try {
  288. $count = $this->model->where($pk, 'in', $ids)
  289. ->update([
  290. 'is_del' => 1
  291. ]);
  292. } catch (PDOException $e) {
  293. Db::rollback();
  294. $this->error($e->getMessage());
  295. } catch (Exception $e) {
  296. Db::rollback();
  297. $this->error($e->getMessage());
  298. }
  299. if ($count) {
  300. $this->success();
  301. } else {
  302. $this->error(__('No rows were deleted'));
  303. }
  304. }
  305. $this->error(__('Parameter %s can not be empty', 'ids'));
  306. }
  307. public function showMistakes($result_id)
  308. {
  309. // 本次考试题目
  310. $result = model(TrainExamResult::class)->get($result_id);
  311. $data = model(TrainExamReQuestion::class)->alias('exam_question')
  312. ->join(model(QuestionModel::class)->getTable().' question', 'exam_question.question_id = question.id')
  313. ->where('exam_question.exam_id', $result['exam_id'])
  314. ->field('question_id, question.title, score as question_score, NULL as my_answer, type, question.result as right_result, answer1, answer2, answer3, answer4, answer5, answer6')
  315. ->order('question.type')
  316. ->select();
  317. $data = collection($data)->toArray();
  318. // 答题数据
  319. $record_data = model(TrainExamResultRecord::class)
  320. ->where('result_id', $result_id)
  321. // ->where('result', 0)
  322. ->column('question_id, answer, result');
  323. // 组合错题结果
  324. $trainService = TrainService::instance();
  325. $new_data = [];
  326. foreach ($data as $val){
  327. if (isset($record_data[$val['question_id']])) {
  328. if($record_data[$val['question_id']]['result'] === 0){
  329. $val['my_answer'] = $trainService->formatResult($record_data[$val['question_id']]['answer'], $val['type']);
  330. $val['right_result'] = $trainService->formatResult($val['right_result'], $val['type']);
  331. $val['type'] = $trainService->formatType($val['type']);
  332. $new_data[] = $val;
  333. }
  334. } else{
  335. $val['my_answer'] = '未填';
  336. $val['right_result'] = $trainService->formatResult($val['right_result'], $val['type']);
  337. $val['type'] = $trainService->formatType($val['type']);
  338. $new_data[] = $val;
  339. }
  340. }
  341. $this->view->assign('data', $new_data);
  342. return $this->view->fetch();
  343. }
  344. public function getExam($ids)
  345. {
  346. $data = $this->model->get($ids);
  347. $this->success('ok','',$data);
  348. }
  349. public function updateQueryOnJobUser(DingTalk $dingTalkService)
  350. {
  351. // 获取access_token
  352. $token = $dingTalkService->getToken();
  353. if(!$token){
  354. $this->error('获取access_token失败:' . $dingTalkService->getError());
  355. }
  356. // 获取用户id列表
  357. $user_ids = $dingTalkService->getQueryOnJob($token);
  358. if(!$user_ids){
  359. $this->error('获取用户id列表:' . $dingTalkService->getError());
  360. }
  361. $user_data = [];
  362. foreach ($user_ids as $user_id){
  363. $user = $dingTalkService->getUserDetail($user_id, $token);
  364. if($user){
  365. $user_data[] = [
  366. 'name' => $user['name'],
  367. 'mobile' => $user['mobile'],
  368. 'avatar' => $user['avatar'],
  369. 'title' => $user['title'] ?? '',
  370. 'userid' => $user['userid'],
  371. ];
  372. }
  373. }
  374. $model = model(TrainAdmin::class);
  375. $exist_arr = $model->column('userid, id');
  376. foreach ($user_data as $val){
  377. $save = [
  378. 'name' => $val['name'],
  379. 'mobile' => $val['mobile'],
  380. 'avatar' => $val['avatar'],
  381. 'title' => $val['title'] ?? '',
  382. 'userid' => $val['userid']
  383. ];
  384. if(isset($exist_arr[$val['userid']])){
  385. $model->where('id', $exist_arr[$val['userid']])->update($save);
  386. } else {
  387. $model->insert($save);
  388. }
  389. }
  390. $this->success();
  391. }
  392. public function sendNotice(DingTalk $dingTalkService)
  393. {
  394. }
  395. /**
  396. * 添加
  397. */
  398. public function add()
  399. {
  400. if ($this->request->isPost()) {
  401. $params = $this->request->post("row/a");
  402. if ($params) {
  403. $params = $this->preExcludeFields($params);
  404. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  405. $params[$this->dataLimitField] = $this->auth->id;
  406. }
  407. $result = false;
  408. Db::startTrans();
  409. try {
  410. //是否采用模型验证
  411. if ($this->modelValidate) {
  412. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  413. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  414. $this->model->validateFailException(true)->validate($validate);
  415. }
  416. $result = $this->model->allowField(true)->save($params);
  417. $exam_id = $this->model->getLastInsID();
  418. if($params['class_id'] && $params['question_count']){
  419. $question_ids = model(QuestionModel::class)
  420. ->where('class_id', $params['class_id'])
  421. ->where('is_del', 0)
  422. ->column('id');
  423. $checked_ids = array_rand($question_ids, $params['question_count']);
  424. $save = [];
  425. $score = $params['question_point'] ?? 1;
  426. foreach ($checked_ids as $checked_id){
  427. $save[] = [
  428. 'exam_id' => $exam_id,
  429. 'question_id' => $question_ids[$checked_id],
  430. 'score' => $score
  431. ];
  432. }
  433. $res = model(TrainExamReQuestion::class)->insertAll($save);
  434. if(!$res){
  435. Db::rollback();
  436. $this->error('创建考题失败');
  437. }
  438. }
  439. Db::commit();
  440. } catch (ValidateException $e) {
  441. Db::rollback();
  442. $this->error($e->getMessage());
  443. } catch (PDOException $e) {
  444. Db::rollback();
  445. $this->error($e->getMessage());
  446. } catch (Exception $e) {
  447. Db::rollback();
  448. $this->error($e->getMessage());
  449. }
  450. if ($result !== false) {
  451. $this->success();
  452. } else {
  453. $this->error(__('No rows were inserted'));
  454. }
  455. }
  456. $this->error(__('Parameter %s can not be empty', ''));
  457. }
  458. return $this->view->fetch();
  459. }
  460. }