PaperService.php 21 KB

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