Paper.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. <?php
  2. namespace app\admin\controller\exam;
  3. use addons\exam\enum\PaperMode;
  4. use app\admin\model\exam\PaperQuestionModel;
  5. use app\admin\model\exam\QuestionModel;
  6. use app\common\controller\Backend;
  7. use think\Db;
  8. use think\exception\PDOException;
  9. use think\exception\ValidateException;
  10. use think\exception\DbException;
  11. use think\db\exception\DataNotFoundException;
  12. use think\db\exception\ModelNotFoundException;
  13. /**
  14. * 试卷
  15. *
  16. * @icon fa fa-circle-o
  17. */
  18. class Paper extends Backend
  19. {
  20. /**
  21. * PaperModel模型对象
  22. *
  23. * @var \app\admin\model\exam\PaperModel
  24. */
  25. protected $model = null;
  26. public function _initialize()
  27. {
  28. parent::_initialize();
  29. $this->model = new \app\admin\model\exam\PaperModel;
  30. $this->view->assign("modeList", $this->model->getModeList());
  31. $this->view->assign("kindList", $this->model->getKindList());
  32. $this->view->assign("statusList", $this->model->getStatusList());
  33. }
  34. /**
  35. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
  36. * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
  37. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  38. */
  39. /**
  40. * 查看
  41. */
  42. public function index()
  43. {
  44. //当前是否为关联查询
  45. $this->relationSearch = true;
  46. //设置过滤方法
  47. $this->request->filter(['strip_tags', 'trim']);
  48. if ($this->request->isAjax()) {
  49. //如果发送的来源是Selectpage,则转发到Selectpage
  50. if ($this->request->request('keyField')) {
  51. return $this->selectpage();
  52. }
  53. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  54. $list = $this->model
  55. ->with(['cate'])
  56. ->where($where)
  57. ->order($sort, $order)
  58. ->paginate($limit);
  59. foreach ($list as $row) {
  60. $row->getRelation('cate')->visible(['name']);
  61. }
  62. $result = ["total" => $list->total(), "rows" => $list->items()];
  63. return json($result);
  64. }
  65. return $this->view->fetch();
  66. }
  67. /**
  68. * 添加
  69. */
  70. public function add()
  71. {
  72. if ($this->request->isPost()) {
  73. $params = $this->request->post("row/a");
  74. if ($params) {
  75. $params = $this->preExcludeFields($params);
  76. $this->valid($params);
  77. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  78. $params[$this->dataLimitField] = $this->auth->id;
  79. }
  80. $result = false;
  81. Db::startTrans();
  82. try {
  83. //是否采用模型验证
  84. if ($this->modelValidate) {
  85. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  86. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  87. $this->model->validateFailException(true)->validate($validate);
  88. }
  89. // dd($params);
  90. $result = $this->model->allowField(true)->save($params);
  91. // 保存试卷固定题目
  92. $this->saveFixQuestion($this->model, $params);
  93. Db::commit();
  94. } catch (ValidateException $e) {
  95. Db::rollback();
  96. $this->error($e->getMessage());
  97. } catch (PDOException $e) {
  98. Db::rollback();
  99. $this->error($e->getMessage());
  100. } catch (\Exception $e) {
  101. Db::rollback();
  102. $this->error($e->getMessage());
  103. }
  104. if ($result !== false) {
  105. $this->success();
  106. } else {
  107. $this->error(__('No rows were inserted'));
  108. }
  109. }
  110. $this->error(__('Parameter %s can not be empty', ''));
  111. }
  112. return $this->view->fetch();
  113. }
  114. /**
  115. * 编辑
  116. */
  117. public function edit($ids = null)
  118. {
  119. $row = $this->model->get($ids);
  120. if (!$row) {
  121. $this->error(__('No Results were found'));
  122. }
  123. $adminIds = $this->getDataLimitAdminIds();
  124. if (is_array($adminIds)) {
  125. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  126. $this->error(__('You have no permission'));
  127. }
  128. }
  129. if ($this->request->isPost()) {
  130. $params = $this->request->post("row/a");
  131. if ($params) {
  132. $this->valid($params);
  133. $params = $this->preExcludeFields($params);
  134. $result = false;
  135. Db::startTrans();
  136. try {
  137. //是否采用模型验证
  138. if ($this->modelValidate) {
  139. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  140. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  141. $row->validateFailException(true)->validate($validate);
  142. }
  143. $result = $row->allowField(true)->save($params);
  144. // 保存试卷固定题目
  145. $this->saveFixQuestion($row, $params, 'edit');
  146. Db::commit();
  147. } catch (ValidateException $e) {
  148. Db::rollback();
  149. $this->error($e->getMessage());
  150. } catch (PDOException $e) {
  151. Db::rollback();
  152. $this->error($e->getMessage());
  153. } catch (\Exception $e) {
  154. Db::rollback();
  155. $this->error($e->getMessage());
  156. }
  157. if ($result !== false) {
  158. $this->success();
  159. } else {
  160. $this->error(__('No rows were updated'));
  161. }
  162. }
  163. $this->error(__('Parameter %s can not be empty', ''));
  164. }
  165. if ($row['mode'] == PaperMode::FIX) {
  166. $row['questions'] = QuestionModel::getFixListByPaper($row['id'], ['cates']);
  167. }
  168. $this->view->assign("row", $row);
  169. $this->view->assign("configs", json_decode($row['configs'], true));
  170. return $this->view->fetch();
  171. }
  172. /**
  173. * 删除
  174. *
  175. * @param $ids
  176. * @return void
  177. * @throws DbException
  178. * @throws DataNotFoundException
  179. * @throws ModelNotFoundException
  180. */
  181. public function del($ids = null)
  182. {
  183. if (false === $this->request->isPost()) {
  184. $this->error(__("Invalid parameters"));
  185. }
  186. $ids = $ids ?: $this->request->post("ids");
  187. if (empty($ids)) {
  188. $this->error(__('Parameter %s can not be empty', 'ids'));
  189. }
  190. $pk = $this->model->getPk();
  191. $adminIds = $this->getDataLimitAdminIds();
  192. if (is_array($adminIds)) {
  193. $this->model->where($this->dataLimitField, 'in', $adminIds);
  194. }
  195. $list = $this->model->where($pk, 'in', $ids)->select();
  196. foreach ($list as $item) {
  197. if ($this->model::getGradeCount($item['id'])) {
  198. $this->error("试卷【{$item['title']}】已有考试记录,无法删除");
  199. }
  200. if ($this->model::getRoomGradeCount($item['id'])) {
  201. $this->error("试卷【{$item['title']}】已有考场考试记录,无法删除");
  202. }
  203. }
  204. $count = 0;
  205. Db::startTrans();
  206. try {
  207. foreach ($list as $item) {
  208. $count += $item->delete();
  209. }
  210. Db::commit();
  211. } catch (PDOException|Exception $e) {
  212. Db::rollback();
  213. $this->error($e->getMessage());
  214. }
  215. if ($count) {
  216. $this->success();
  217. }
  218. $this->error(__('No rows were deleted'));
  219. }
  220. /**
  221. * 验证参数
  222. *
  223. * @param $params
  224. * @return void
  225. */
  226. protected function valid(&$params, $row = null)
  227. {
  228. if ($params['pass_score'] > $params['total_score']) {
  229. $this->error('及格分数不能大于总分');
  230. }
  231. $params['start_time'] = $params['start_time'] ?: 0;
  232. $params['end_time'] = $params['end_time'] ?: 0;
  233. if ($params['start_time']) {
  234. if ($params['start_time'] > $params['end_time']) {
  235. $this->error('开始时间不能大于结束时间');
  236. }
  237. // if (strtotime($params['start_time']) < time()) {
  238. // $this->error('开始时间不能小于当前时间');
  239. // }
  240. }
  241. if ($params['end_time']) {
  242. if (!$params['start_time']) {
  243. $this->error('请先选择开始时间');
  244. }
  245. }
  246. // 固定选题模式
  247. if ($params['mode'] == 'FIX') {
  248. $params['questions'] = json_decode($params['questions'], true);
  249. if (!$params['questions']) {
  250. $this->error('请先选择题目');
  251. }
  252. if (count($params['questions']) < $params['quantity']) {
  253. $this->error('题目数量不能大于题目总数');
  254. }
  255. }
  256. $limit_time = 0;
  257. if ($params['limit_time_hour']) {
  258. $limit_time += $params['limit_time_hour'] * 60 * 60;
  259. }
  260. if ($params['limit_time_minute']) {
  261. $limit_time += $params['limit_time_minute'] * 60;
  262. }
  263. $params['limit_time'] = $limit_time;
  264. // 编辑时
  265. if ($row) {
  266. $grade_count = $this->model::getGradeCount($row['id']);
  267. $room_grade_count = $this->model::getRoomGradeCount($row['id']);
  268. // 如果已有考试记录,不允许修改试卷主要数据
  269. if ($grade_count > 0 || $room_grade_count > 0) {
  270. if ($params['title'] != $row['title']) {
  271. $this->error('试卷已有考试记录(含考场考试记录),不允许修改试卷名称');
  272. }
  273. if ($params['mode'] != $row['mode']) {
  274. $this->error('试卷已有考试记录(含考场考试记录),不允许修改试卷选题模式');
  275. }
  276. if ($params['quantity'] != $row['quantity']) {
  277. $this->error('试卷已有考试记录(含考场考试记录),不允许修改试卷题目数');
  278. }
  279. if ($params['total_score'] != $row['total_score']) {
  280. $this->error('试卷已有考试记录(含考场考试记录),不允许修改试卷总分');
  281. }
  282. if ($params['pass_score'] != $row['pass_score']) {
  283. $this->error('试卷已有考试记录(含考场考试记录),不允许修改及格分数');
  284. }
  285. if ($params['limit_time'] != $row['limit_time']) {
  286. $this->error('试卷已有考试记录(含考场考试记录),不允许修改考试限时');
  287. }
  288. }
  289. }
  290. }
  291. /**
  292. * 保存固定选题
  293. *
  294. * @param $paper
  295. * @param $params
  296. * @return void
  297. */
  298. public function saveFixQuestion($paper, $params, $method = 'add')
  299. {
  300. if ($paper['mode'] != 'FIX') {
  301. return;
  302. }
  303. if ($method == 'edit') {
  304. PaperQuestionModel::where('paper_id', $paper['id'])->delete();
  305. }
  306. $questions = $params['questions'];
  307. $data = [];
  308. foreach ($questions as $key => $question) {
  309. $data[] = [
  310. 'paper_id' => $paper['id'],
  311. 'question_id' => $question['id'],
  312. 'score' => $question['score'],
  313. 'answer_config' => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
  314. 'sort' => $question['sort'] ?? ($key + 1),
  315. 'createtime' => time(),
  316. ];
  317. }
  318. (new PaperQuestionModel())->saveAll($data);
  319. }
  320. }