PaperService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Api;
  12. use App\Models\ExamAccessLogModel;
  13. use App\Models\ExamAnswerModel;
  14. use App\Models\ExamAnswerTopicModel;
  15. use App\Models\ExamErrorModel;
  16. use App\Models\ExamPaperModel;
  17. use App\Models\ExamTopicModel;
  18. use App\Services\BaseService;
  19. use App\Services\ConfigService;
  20. use App\Services\RedisService;
  21. /**
  22. * 试卷服务-服务类
  23. * @author laravel开发员
  24. * @since 2020/11/11
  25. * @package App\Services\Api
  26. */
  27. class PaperService extends BaseService
  28. {
  29. // 静态对象
  30. protected static $instance = null;
  31. /**
  32. * 构造函数
  33. * @author laravel开发员
  34. * @since 2020/11/11
  35. */
  36. public function __construct()
  37. {
  38. $this->model = new ExamPaperModel();
  39. }
  40. /**
  41. * 静态入口
  42. */
  43. public static function make()
  44. {
  45. if (!self::$instance) {
  46. self::$instance = new static();
  47. }
  48. return self::$instance;
  49. }
  50. /**
  51. * @param $params
  52. * @param int $pageSize
  53. * @return array
  54. */
  55. public function getDataList($params, $pageSize = 15)
  56. {
  57. $page = isset($params['page']) ? $params['page'] : 1;
  58. $cacheKey = "caches:paper:list_{$page}_{$pageSize}:" . md5(json_encode($params));
  59. $datas = RedisService::get($cacheKey);
  60. // 访问次数统计
  61. $sc = isset($params['sc']) ? $params['sc'] : 0;
  62. $type = isset($params['type']) ? $params['type'] : 0;
  63. $sceneType = isset($params['scene_type']) ? $params['scene_type'] : 0;
  64. if (empty($sc) && !in_array($sceneType, [3, 4, 6])) {
  65. ExamAccessLogModel::saveLog(date('Y-m-d'), $type, $sceneType);
  66. }
  67. if ($datas) {
  68. return $datas;
  69. }
  70. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  71. $query = $this->getQuery($params);
  72. $list = $query->with(['answer' => function ($query) use ($userId) {
  73. $query->where('user_id', $userId);
  74. }])
  75. ->where('a.topic_count', '>', 0)->select(['a.*', 'b.id as rid', 'b.score', 'b.accurate_count', 'b.user_id', 'b.answer_times', 'b.answer_count', 'b.is_submit'])
  76. ->orderBy('a.sort', 'desc')->orderBy('a.id', 'desc')
  77. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  78. $list = $list ? $list->toArray() : [];
  79. if ($list) {
  80. foreach ($list['data'] as &$item) {
  81. $item['score'] = !empty($item['score']) ? $item['score'] : 0;
  82. $item['is_submit'] = !empty($item['is_submit']) ? $item['is_submit'] : 0;
  83. $item['answer_count'] = !empty($item['answer_count']) ? $item['answer_count'] : 0;
  84. $item['accurate_count'] = !empty($item['accurate_count']) ? $item['accurate_count'] : 0;
  85. $item['date'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d') : '';
  86. }
  87. }
  88. $rows = isset($list['data']) ? $list['data'] : [];
  89. $datas = [
  90. 'pageSize' => $pageSize,
  91. 'total' => isset($list['total']) ? $list['total'] : 0,
  92. 'list' => $rows
  93. ];
  94. if ($rows) {
  95. RedisService::set($cacheKey, $datas, rand(300, 600));
  96. }
  97. return $datas;
  98. }
  99. /**
  100. * 查询
  101. * @param $params
  102. * @return mixed
  103. */
  104. public function getQuery($params)
  105. {
  106. $where = ['a.status' => 1, 'a.mark' => 1];
  107. $status = isset($params['status']) ? $params['status'] : 0;
  108. $type = isset($params['type']) ? $params['type'] : 0;
  109. $sceneType = isset($params['scene_type']) ? $params['scene_type'] : 0;
  110. $subjectId = isset($params['subject_id']) ? $params['subject_id'] : 0;
  111. if ($status > 0) {
  112. $where['a.status'] = $status;
  113. }
  114. if ($type > 0) {
  115. $where['a.type'] = $type;
  116. }
  117. if ($sceneType > 0) {
  118. $where['a.scene_type'] = $sceneType;
  119. }
  120. if ($subjectId > 0) {
  121. $where['a.subject_id'] = $subjectId;
  122. }
  123. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  124. return $this->model->from('exam_papers as a')
  125. ->leftJoin('exam_answers as b', function ($join) use ($userId) {
  126. // 未完成交卷的答题数据
  127. $join->on('b.paper_id', '=', 'a.id')->where(['b.user_id' => $userId, 'b.status' => 1, 'b.mark' => 1]);
  128. })
  129. ->where($where)
  130. ->where(function ($query) use ($params) {
  131. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  132. if ($keyword) {
  133. $query->where('a.name', 'like', "%{$keyword}%");
  134. }
  135. });
  136. }
  137. /**
  138. * 最近是否答过该题
  139. * @param $userId 用户ID
  140. * @param $paperId 试卷ID
  141. * @param int $submit 是否已交卷,1-是,0-否
  142. * @return array|mixed
  143. */
  144. public function getLastAnswer($userId, $paperId, $submit = 0)
  145. {
  146. $cacheKey = "caches:paper:answer_last_{$userId}:{$paperId}_{$submit}";
  147. $data = RedisService::get($cacheKey);
  148. if ($data) {
  149. return $data;
  150. }
  151. $lastTime = ConfigService::make()->getConfigByCode('submit_paper_time', 30);
  152. $lastTime = $lastTime >= 1 && $lastTime <= 150 ? $lastTime : 30;
  153. $data = ExamAnswerModel::where(['user_id' => $userId, 'is_submit' => $submit, 'paper_id' => $paperId, 'status' => 1, 'mark' => 1])
  154. ->where(function ($query) use ($lastTime, $submit) {
  155. if ($submit <= 0) {
  156. // 未交卷
  157. $query->where('is_submit', 0)->orWhere('answer_last_at', '>=', time() - $lastTime * 60);
  158. } else {
  159. $query->where('is_submit', $submit)->orWhere('answer_last_at', '<', time() - $lastTime * 60);
  160. }
  161. })
  162. ->select(['id', 'paper_id', 'score', 'answer_last_at', 'answer_last_id'])
  163. ->first();
  164. $data = $data ? $data->toArray() : [];
  165. if ($data) {
  166. RedisService::set($cacheKey, $data, rand(5, 10));
  167. }
  168. return $data;
  169. }
  170. /**
  171. * 用户最近答题记录
  172. * @param $userId
  173. * @param $paperId
  174. * @return array|mixed
  175. */
  176. public function getLastAnswerLogId($userId, $paperId)
  177. {
  178. $cacheKey = "caches:paper:log_{$userId}_{$paperId}";
  179. $id = RedisService::get($cacheKey);
  180. if ($id) {
  181. return $id;
  182. }
  183. $id = ExamAnswerModel::where(['user_id' => $userId, 'paper_id' => $paperId, 'status' => 1, 'mark' => 1])
  184. ->where('create_time', '>=', strtotime(date('Y-m-d')))
  185. ->value('id');
  186. if ($id) {
  187. RedisService::set($cacheKey, $id, rand(5, 10));
  188. }
  189. return $id;
  190. }
  191. /**
  192. * 获取详情
  193. * @param $id
  194. * @return array|mixed
  195. */
  196. public function getInfo($userId, $paperId, $params = [])
  197. {
  198. $lid = isset($params['lid']) ? intval($params['lid']) : 0;
  199. $tid = isset($params['tid']) ? intval($params['tid']) : 0;
  200. $rid = isset($params['rid']) ? intval($params['rid']) : 0;
  201. $type = isset($params['type']) ? intval($params['type']) : 1;
  202. $cacheKey = "caches:paper:info_{$userId}:p{$paperId}_t{$tid}_r{$rid}_l{$lid}";
  203. $info = RedisService::get($cacheKey);
  204. if ($info) {
  205. return $info;
  206. }
  207. // 若进行答题
  208. if ($rid <= 0) {
  209. if ($type != 1) {
  210. // 判断N分钟内是否有未交卷的答题
  211. $lastAnswerInfo = $this->getLastAnswer($userId, $paperId, 0);
  212. $rid = isset($lastAnswerInfo['id']) ? $lastAnswerInfo['id'] : 0;
  213. } else {
  214. $rid = $this->getLastAnswerLogId($userId, $paperId);
  215. }
  216. }
  217. $where = ['a.id' => $paperId, 'a.status' => 1, 'a.mark' => 1];
  218. $info = $this->model->from('exam_papers as a')
  219. ->leftJoin('exam_answers as b', function ($join) use ($rid, $userId) {
  220. $join->on('b.paper_id', '=', 'a.id')->where(['b.id' => $rid, 'b.user_id' => $userId, 'b.status' => 1]);
  221. })
  222. ->where($where)
  223. ->select(['a.id as paper_id', 'b.id as rid', 'b.score', 'b.accurate_count', 'b.is_submit', 'b.answer_count', 'b.answer_last_id', 'b.answer_times', 'a.name', 'a.type', 'a.scene_type', 'a.subject_id', 'a.score_total', 'a.topic_count', 'a.total_time', 'a.is_charge', 'a.create_time', 'a.status'])
  224. ->first();
  225. $info = $info ? $info->toArray() : [];
  226. if ($info) {
  227. $info['create_time'] = $info['create_time'] ? datetime($info['create_time'], 'Y-m-d') : '';
  228. $info['answer_count'] = isset($info['answer_count']) ? intval($info['answer_count']) : 0;
  229. $info['accurate_count'] = isset($info['accurate_count']) ? intval($info['accurate_count']) : 0;
  230. $info['score'] = isset($info['score']) ? intval($info['score']) : 0;
  231. $info['rid'] = isset($info['rid']) ? intval($info['rid']) : 0;
  232. // 剩余时间
  233. $isSubmit = isset($info['is_submit']) ? $info['is_submit'] : 0;
  234. $totalTime = isset($info['total_time']) ? intval($info['total_time']) : 0;
  235. $totalTime = $totalTime > 0 ? $totalTime : ConfigService::make()->getConfigByCode('answer_total_time', 1800);
  236. $info['answer_times'] = isset($info['answer_times']) ? intval($info['answer_times']) : 0;
  237. $info['remain_time'] = $totalTime > $info['answer_times'] ? $totalTime - $info['answer_times'] : 0;
  238. $info['remain_time'] = $isSubmit ? 0 : $info['remain_time'];
  239. $info['remain_time_text'] = $info['remain_time'] ? format_times($info['remain_time']) : '00:00';
  240. $info['progress'] = $info['topic_count'] ? intval($info['answer_count'] / $info['topic_count'] * 100) : 0;
  241. // 当前题目
  242. //$prefix = env('DB_PREFIX','_lev');
  243. $model = ExamTopicModel::from('exam_topics as a')
  244. ->leftJoin('exam_answers_topics as b', function ($join) use ($rid, $userId) {
  245. // 是否有最近答题记录
  246. $join->on('b.topic_id', '=', "a.id")->where("b.answer_log_id", '=', $rid)->where(['b.user_id' => $userId, 'b.status' => 1, "b.mark" => 1]);
  247. })
  248. ->where(['a.paper_id' => $paperId, 'a.status' => 1, 'a.mark' => 1])
  249. ->where(function ($query) use ($tid) {
  250. // 答题卡选择的题目,否则默认按题目排序返回第一题
  251. if ($tid > 0) {
  252. $query->where('a.id', $tid);
  253. }
  254. });
  255. $info['topic'] = $model->select(['a.*', 'b.id as answer_topic_id', 'b.answer_log_id', 'b.answer as submit_answer', 'b.answer_analysis', 'b.answer_type as submit_answer_type', 'b.score as submit_score', 'b.accurate'])
  256. ->orderBy('a.sort', 'desc')
  257. ->orderBy('a.id', 'asc')
  258. ->first();
  259. $info['topic'] = $info['topic'] ? $info['topic']->toArray() : [];
  260. $topicId = isset($info['topic']['id']) ? $info['topic']['id'] : 0;
  261. if ($info['topic'] && $topicId) {
  262. $info['topic']['accurate'] = isset($info['topic']['accurate']) ? $info['topic']['accurate'] : -1;
  263. $info['topic']['topic_analysis'] = isset($info['topic']['topic_analysis']) ? $info['topic']['topic_analysis'] : '';
  264. $info['topic']['answer_analysis'] = isset($info['topic']['answer_analysis']) ? $info['topic']['answer_analysis'] : '';
  265. $info['topic']['topic_analysis'] = $info['topic']['topic_analysis'] ? $info['topic']['topic_analysis'] : $info['topic']['answer_analysis'];
  266. $info['topic']['submit_answer'] = isset($info['topic']['submit_answer']) ? $info['topic']['submit_answer'] : '';
  267. $info['topic']['submit_answer_type'] = isset($info['topic']['submit_answer_type']) ? $info['topic']['submit_answer_type'] : 1;
  268. $info['topic']['submit_answers'] = '';
  269. $info['topic']['collect_answers'] = [];
  270. if ($info['topic']['submit_answer_type'] == 3) {
  271. $info['topic']['submit_answer'] = get_image_url($info['topic']['submit_answer']);
  272. } else if ($info['topic']['submit_answer_type'] == 4) {
  273. $info['topic']['submit_answer'] = $info['topic']['submit_answer'] ? json_decode($info['topic']['submit_answer'], true) : [];
  274. } else {
  275. $info['topic']['submit_answer'] = format_content($info['topic']['submit_answer']);
  276. }
  277. if ($info['topic']['show_type'] == 1) {
  278. $info['topic']['topic_name'] = format_content($info['topic']['topic_name']);
  279. } else if ($info['topic']['show_type'] == 2) {
  280. $info['topic']['topic_name'] = get_image_url($info['topic']['topic_name']);
  281. // 已经答题,返回答案
  282. if ($rid > 0 || $info['topic']['submit_answer']) {
  283. $info['topic']['topic_analysis'] = get_image_url($info['topic']['topic_analysis']);
  284. if (preg_match("/(images|temp)/", $info['topic']['correct_answer'])) {
  285. $info['topic']['correct_answer'] = get_image_url($info['topic']['correct_answer']);
  286. }
  287. if (preg_match("/(images|temp)/", $info['topic']['answer_A'])) {
  288. $info['topic']['answer_A'] = get_image_url($info['topic']['answer_A']);
  289. }
  290. if (preg_match("/(images|temp)/", $info['topic']['answer_B'])) {
  291. $info['topic']['answer_B'] = get_image_url($info['topic']['answer_B']);
  292. }
  293. if (preg_match("/(images|temp)/", $info['topic']['answer_C'])) {
  294. $info['topic']['answer_C'] = get_image_url($info['topic']['answer_C']);
  295. }
  296. if (preg_match("/(images|temp)/", $info['topic']['answer_D'])) {
  297. $info['topic']['answer_D'] = get_image_url($info['topic']['answer_D']);
  298. }
  299. if (preg_match("/(images|temp)/", $info['topic']['answer_E'])) {
  300. $info['topic']['answer_E'] = get_image_url($info['topic']['answer_E']);
  301. }
  302. if (preg_match("/(images|temp)/", $info['topic']['answer_F'])) {
  303. $info['topic']['answer_F'] = get_image_url($info['topic']['answer_F']);
  304. }
  305. }
  306. }
  307. // 未答题隐藏答案
  308. // if(empty($info['topic']['submit_answer'])){
  309. // $info['topic']['correct_answer'] = '未答题';
  310. // $info['topic']['topic_analysis'] = '';
  311. // }
  312. // 多选题
  313. $topicType = isset($info['topic']['topic_type']) ? $info['topic']['topic_type'] : '';
  314. if ($topicType == '多选题') {
  315. $info['topic']['submit_answers'] = $info['topic']['submit_answer'] ? explode(',', $info['topic']['submit_answer']) : '';
  316. $info['topic']['correct_answers'] = $info['topic']['correct_answer'] ? explode(',', $info['topic']['correct_answer']) : [];
  317. }
  318. $info['topic']['answers'] = [];
  319. if ($info['topic']['answer_A']) {
  320. $info['topic']['answers'][] = ['code' => 'A', 'value' => $info['topic']['answer_A']];
  321. }
  322. if ($info['topic']['answer_B']) {
  323. $info['topic']['answers'][] = ['code' => 'B', 'value' => $info['topic']['answer_B']];
  324. }
  325. if ($info['topic']['answer_C']) {
  326. $info['topic']['answers'][] = ['code' => 'C', 'value' => $info['topic']['answer_C']];
  327. }
  328. if ($info['topic']['answer_D']) {
  329. $info['topic']['answers'][] = ['code' => 'D', 'value' => $info['topic']['answer_D']];
  330. }
  331. if ($info['topic']['answer_E']) {
  332. $info['topic']['answers'][] = ['code' => 'E', 'value' => $info['topic']['answer_E']];
  333. }
  334. if ($info['topic']['answer_F']) {
  335. $info['topic']['answers'][] = ['code' => 'F', 'value' => $info['topic']['answer_F']];
  336. }
  337. // 上一题
  338. $info['last'] = ExamTopicModel::where(['paper_id' => $paperId, 'status' => 1, 'mark' => 1])
  339. ->where('id', '<', $topicId)
  340. ->select(['id', 'topic_name'])
  341. ->orderBy('sort', 'asc')
  342. ->orderBy('id', 'desc')
  343. ->first();
  344. $info['last'] = $info['last'] ? $info['last']->toArray() : ['id' => 0];
  345. // 下一题
  346. $info['next'] = ExamTopicModel::where(['paper_id' => $paperId, 'status' => 1, 'mark' => 1])
  347. ->where('id', '>', $topicId)
  348. ->select(['id', 'topic_name'])
  349. ->orderBy('sort', 'desc')
  350. ->orderBy('id', 'asc')
  351. ->first();
  352. $info['next'] = $info['next'] ? $info['next']->toArray() : ['id' => 0];
  353. }
  354. RedisService::set($cacheKey, $info, rand(10, 20));
  355. }
  356. return $info;
  357. }
  358. /**
  359. * 获取随机试卷
  360. * @param $userId 用户
  361. * @param $type 试卷类型
  362. * @param $sceneType 场景
  363. * @param false $refresh
  364. * @return array|mixed
  365. */
  366. public function getRandomPaper($userId, $type, $sceneType, $refresh = false)
  367. {
  368. $cacheKey = "caches:papers:random_{$userId}:{$type}_{$sceneType}";
  369. $data = RedisService::get($cacheKey);
  370. if ($data && !$refresh) {
  371. return $data;
  372. }
  373. $data = $this->model->where(['type' => $type, 'scene_type' => $sceneType, 'status' => 1, 'mark' => 1])
  374. ->orderByRaw('RAND()')
  375. ->first();
  376. $data = $data ? $data->toArray() : [];
  377. if ($data) {
  378. $data['score'] = 0;
  379. $data['paper_id'] = $data['id'];
  380. $data['accurate_count'] = 0;
  381. $data['date'] = date('Y-m-d');
  382. $data['answer_count'] = 0;
  383. $data['answer_times'] = 0;
  384. RedisService::set($cacheKey, $data, rand(10, 20));
  385. }
  386. return $data;
  387. }
  388. /**
  389. * 纠错
  390. * @param $userId
  391. * @param $params
  392. * @return bool
  393. */
  394. public function submitError($userId, $params)
  395. {
  396. $id = isset($params['id']) ? $params['id'] : 0;
  397. $rid = isset($params['rid']) ? $params['rid'] : 0;
  398. $type = isset($params['type']) ? $params['type'] : 0;
  399. $moduleType = isset($params['module_type']) ? $params['module_type'] : 1;
  400. $description = isset($params['description']) ? $params['description'] : '';
  401. if ($id <= 0 || $moduleType <= 0) {
  402. $this->error = '参数错误';
  403. return false;
  404. }
  405. if ($type <= 0) {
  406. $this->error = '请选择错误类型';
  407. return false;
  408. }
  409. if (empty($description)) {
  410. $this->error = '请输入错误描述';
  411. return false;
  412. }
  413. $limitTime = ConfigService::make()->getConfigByCode('limit_exam_error_submit', 5);
  414. $cacheKey = "caches:paper:errors_{$userId}:{$id}_{$rid}";
  415. if (RedisService::get($cacheKey) && $limitTime > 0) {
  416. $this->error = '您近期已提交过该题错误,请稍后再试~';
  417. return false;
  418. }
  419. $paperInfo = $this->model->where(['id' => $id, 'mark' => 1])->first();
  420. if (empty($paperInfo)) {
  421. $this->error = '试题不存在';
  422. return false;
  423. }
  424. if ($limitTime > 0 && $logId = ExamErrorModel::where(['user_id' => $userId, 'rid' => $rid, 'paper_id' => $id, 'mark' => 1])->where('create_time', '>=', time() - $limitTime * 60)->value('id')) {
  425. $this->error = '您近期已提交过该题错误,请稍后再试~';
  426. RedisService::set($cacheKey, ['id' => $logId, 'paper_id' => $id], $limitTime * 60);
  427. return false;
  428. }
  429. $data = [
  430. 'user_id' => $userId,
  431. 'paper_id' => $id,
  432. 'rid' => $rid,
  433. 'type' => $type,
  434. 'module_type' => $moduleType,
  435. 'description' => $description,
  436. 'image_url' => isset($params['image_url']) && $params['image_url'] ? get_image_path($params['image_url']) : '',
  437. 'create_time' => time(),
  438. 'status' => 1,
  439. 'mark' => 1
  440. ];
  441. if (!$logId = ExamErrorModel::insertGetId($data)) {
  442. $this->error = '提交失败';
  443. return false;
  444. }
  445. $this->error = '提交成功';
  446. RedisService::set($cacheKey, $data, $limitTime * 60);
  447. return ['id' => $logId, 'paper_id' => $id];
  448. }
  449. }