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. }])->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'])
  75. ->orderBy('a.create_time','desc')
  76. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  77. $list = $list? $list->toArray() :[];
  78. if($list){
  79. foreach($list['data'] as &$item){
  80. $item['score'] = !empty($item['score'])? $item['score'] : 0;
  81. $item['is_submit'] = !empty($item['is_submit'])? $item['is_submit'] : 0;
  82. $item['answer_count'] = !empty($item['answer_count'])? $item['answer_count'] : 0;
  83. $item['accurate_count'] = !empty($item['accurate_count'])? $item['accurate_count'] : 0;
  84. $item['date'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d') : '';
  85. }
  86. }
  87. $rows = isset($list['data'])? $list['data'] : [];
  88. $datas = [
  89. 'pageSize'=> $pageSize,
  90. 'total'=> isset($list['total'])? $list['total'] : 0,
  91. 'list'=> $rows
  92. ];
  93. if($rows){
  94. RedisService::set($cacheKey, $datas, rand(300, 600));
  95. }
  96. return $datas;
  97. }
  98. /**
  99. * 查询
  100. * @param $params
  101. * @return mixed
  102. */
  103. public function getQuery($params)
  104. {
  105. $where = ['a.status'=>1,'a.mark'=>1];
  106. $status = isset($params['status'])? $params['status'] : 0;
  107. $type = isset($params['type'])? $params['type'] : 0;
  108. $sceneType = isset($params['scene_type'])? $params['scene_type'] : 0;
  109. $subjectId = isset($params['subject_id'])? $params['subject_id'] : 0;
  110. if($status>0){
  111. $where['a.status'] = $status;
  112. }
  113. if($type>0){
  114. $where['a.type'] = $type;
  115. }
  116. if($sceneType>0){
  117. $where['a.scene_type'] = $sceneType;
  118. }
  119. if($subjectId>0){
  120. $where['a.subject_id'] = $subjectId;
  121. }
  122. $userId = isset($params['user_id'])? $params['user_id'] : 0;
  123. return $this->model->from('exam_papers as a')
  124. ->leftJoin('exam_answers as b', function($join) use($userId){
  125. // 未完成交卷的答题数据
  126. $join->on('b.paper_id','=','a.id')->where(['b.user_id'=>$userId,'b.status'=>1,'b.mark'=>1]);
  127. })
  128. ->where($where)
  129. ->where(function ($query) use($params){
  130. $keyword = isset($params['keyword'])? $params['keyword'] : '';
  131. if($keyword){
  132. $query->where('a.name','like',"%{$keyword}%");
  133. }
  134. });
  135. }
  136. /**
  137. * 最近是否答过该题
  138. * @param $userId 用户ID
  139. * @param $paperId 试卷ID
  140. * @param int $submit 是否已交卷,1-是,0-否
  141. * @return array|mixed
  142. */
  143. public function getLastAnswer($userId, $paperId, $submit=0)
  144. {
  145. $cacheKey = "caches:paper:answer_last_{$userId}:{$paperId}_{$submit}";
  146. $data = RedisService::get($cacheKey);
  147. if($data){
  148. return $data;
  149. }
  150. $lastTime = ConfigService::make()->getConfigByCode('submit_paper_time', 30);
  151. $lastTime = $lastTime>=1 && $lastTime <= 150? $lastTime : 30;
  152. $data = ExamAnswerModel::where(['user_id'=>$userId,'is_submit'=> $submit,'paper_id'=> $paperId,'status'=>1,'mark'=>1])
  153. ->where(function($query) use($lastTime, $submit){
  154. if($submit<=0){
  155. // 未交卷
  156. $query->where('is_submit', 0)->orWhere('answer_last_at','>=', time() - $lastTime * 60);
  157. }else{
  158. $query->where('is_submit', $submit)->orWhere('answer_last_at','<', time() - $lastTime * 60);
  159. }
  160. })
  161. ->select(['id','paper_id','score','answer_last_at','answer_last_id'])
  162. ->first();
  163. $data = $data? $data->toArray() : [];
  164. if($data){
  165. RedisService::set($cacheKey, $data, rand(5, 10));
  166. }
  167. return $data;
  168. }
  169. /**
  170. * 用户最近答题记录
  171. * @param $userId
  172. * @param $paperId
  173. * @return array|mixed
  174. */
  175. public function getLastAnswerLogId($userId,$paperId)
  176. {
  177. $cacheKey = "caches:paper:log_{$userId}_{$paperId}";
  178. $id = RedisService::get($cacheKey);
  179. if($id){
  180. return $id;
  181. }
  182. $id = ExamAnswerModel::where(['user_id'=> $userId,'paper_id'=> $paperId,'status'=>1,'mark'=>1])
  183. ->where('create_time','>=', strtotime(date('Y-m-d')))
  184. ->value('id');
  185. if($id){
  186. RedisService::set($cacheKey, $id, rand(5, 10));
  187. }
  188. return $id;
  189. }
  190. /**
  191. * 获取详情
  192. * @param $id
  193. * @return array|mixed
  194. */
  195. public function getInfo($userId, $paperId, $params=[])
  196. {
  197. $lid = isset($params['lid'])? intval($params['lid']) : 0;
  198. $tid = isset($params['tid'])? intval($params['tid']) : 0;
  199. $rid = isset($params['rid'])? intval($params['rid']) : 0;
  200. $type = isset($params['type'])? intval($params['type']) : 1;
  201. $cacheKey = "caches:paper:info_{$userId}:p{$paperId}_t{$tid}_r{$rid}_l{$lid}";
  202. $info = RedisService::get($cacheKey);
  203. if($info){
  204. return $info;
  205. }
  206. // 若进行答题
  207. if($rid<=0) {
  208. if($type != 1){
  209. // 判断N分钟内是否有未交卷的答题
  210. $lastAnswerInfo = $this->getLastAnswer($userId, $paperId, 0);
  211. $rid = isset($lastAnswerInfo['id']) ? $lastAnswerInfo['id'] : 0;
  212. }else {
  213. $rid = $this->getLastAnswerLogId($userId, $paperId);
  214. }
  215. }
  216. $where = ['a.id'=> $paperId,'a.status'=>1,'a.mark'=>1];
  217. $info = $this->model->from('exam_papers as a')
  218. ->leftJoin('exam_answers as b',function($join) use($rid,$userId){
  219. $join->on('b.paper_id','=','a.id')->where(['b.id'=>$rid,'b.user_id'=>$userId,'b.status'=>1]);
  220. })
  221. ->where($where)
  222. ->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'])
  223. ->first();
  224. $info = $info? $info->toArray() : [];
  225. if($info){
  226. $info['create_time'] = $info['create_time']? datetime($info['create_time'],'Y-m-d') : '';
  227. $info['answer_count'] = isset($info['answer_count'])? intval($info['answer_count']) : 0;
  228. $info['accurate_count'] = isset($info['accurate_count'])? intval($info['accurate_count']) : 0;
  229. $info['score'] = isset($info['score'])? intval($info['score']) : 0;
  230. $info['rid'] = isset($info['rid'])? intval($info['rid']) : 0;
  231. // 剩余时间
  232. $isSubmit = isset($info['is_submit'])? $info['is_submit'] : 0;
  233. $totalTime = isset($info['total_time'])? intval($info['total_time']) : 0;
  234. $totalTime = $totalTime>0? $totalTime : ConfigService::make()->getConfigByCode('answer_total_time', 1800);
  235. $info['answer_times'] = isset($info['answer_times'])? intval($info['answer_times']) : 0;
  236. $info['remain_time'] = $totalTime>$info['answer_times']? $totalTime-$info['answer_times'] : 0;
  237. $info['remain_time'] = $isSubmit? 0 : $info['remain_time'];
  238. $info['remain_time_text'] = $info['remain_time']? format_times($info['remain_time']) : '00:00';
  239. $info['progress'] = $info['topic_count']?intval($info['answer_count']/$info['topic_count'] * 100) : 0;
  240. // 当前题目
  241. //$prefix = env('DB_PREFIX','_lev');
  242. $model = ExamTopicModel::from('exam_topics as a')
  243. ->leftJoin('exam_answers_topics as b', function($join) use($rid, $userId){
  244. // 是否有最近答题记录
  245. $join->on('b.topic_id','=',"a.id")->where("b.answer_log_id",'=', $rid)->where(['b.user_id'=>$userId,'b.status'=>1,"b.mark"=> 1]);
  246. })
  247. ->where(['a.paper_id'=> $paperId,'a.status'=>1,'a.mark'=>1])
  248. ->where(function($query) use($tid){
  249. // 答题卡选择的题目,否则默认按题目排序返回第一题
  250. if($tid>0){
  251. $query->where('a.id', $tid);
  252. }
  253. });
  254. $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'])
  255. ->orderBy('a.sort','desc')
  256. ->orderBy('a.id','asc')
  257. ->first();
  258. $info['topic'] = $info['topic']? $info['topic']->toArray() : [];
  259. $topicId = isset($info['topic']['id'])? $info['topic']['id'] : 0;
  260. if($info['topic'] && $topicId) {
  261. $info['topic']['accurate'] = isset($info['topic']['accurate'])?$info['topic']['accurate'] : -1;
  262. $info['topic']['topic_analysis'] = isset($info['topic']['topic_analysis'])?$info['topic']['topic_analysis'] : '';
  263. $info['topic']['answer_analysis'] = isset($info['topic']['answer_analysis'])?$info['topic']['answer_analysis'] : '';
  264. $info['topic']['topic_analysis'] = $info['topic']['topic_analysis']?$info['topic']['topic_analysis'] : $info['topic']['answer_analysis'];
  265. $info['topic']['submit_answer'] = isset($info['topic']['submit_answer'])?$info['topic']['submit_answer'] : '';
  266. $info['topic']['submit_answer_type'] = isset($info['topic']['submit_answer_type'])?$info['topic']['submit_answer_type'] : 1;
  267. $info['topic']['submit_answers'] = '';
  268. $info['topic']['collect_answers'] = [];
  269. if($info['topic']['submit_answer_type'] == 3){
  270. $info['topic']['submit_answer'] = get_image_url($info['topic']['submit_answer']);
  271. }else if($info['topic']['submit_answer_type'] == 4){
  272. $info['topic']['submit_answer'] = $info['topic']['submit_answer']?json_decode($info['topic']['submit_answer'], true):[];
  273. }else{
  274. $info['topic']['submit_answer'] = format_content($info['topic']['submit_answer']);
  275. }
  276. if($info['topic']['show_type'] == 1){
  277. $info['topic']['topic_name'] = format_content($info['topic']['topic_name']);
  278. }else if($info['topic']['show_type'] == 2){
  279. $info['topic']['topic_name'] = get_image_url($info['topic']['topic_name']);
  280. // 已经答题,返回答案
  281. if($rid>0 || $info['topic']['submit_answer']){
  282. $info['topic']['topic_analysis'] = get_image_url($info['topic']['topic_analysis']);
  283. if(preg_match("/(images|temp)/", $info['topic']['correct_answer'])){
  284. $info['topic']['correct_answer'] = get_image_url($info['topic']['correct_answer']);
  285. }
  286. if(preg_match("/(images|temp)/", $info['topic']['answer_A'])){
  287. $info['topic']['answer_A'] = get_image_url($info['topic']['answer_A']);
  288. }
  289. if(preg_match("/(images|temp)/", $info['topic']['answer_B'])){
  290. $info['topic']['answer_B'] = get_image_url($info['topic']['answer_B']);
  291. }
  292. if(preg_match("/(images|temp)/", $info['topic']['answer_C'])){
  293. $info['topic']['answer_C'] = get_image_url($info['topic']['answer_C']);
  294. }
  295. if(preg_match("/(images|temp)/", $info['topic']['answer_D'])){
  296. $info['topic']['answer_D'] = get_image_url($info['topic']['answer_D']);
  297. }
  298. if(preg_match("/(images|temp)/", $info['topic']['answer_E'])){
  299. $info['topic']['answer_E'] = get_image_url($info['topic']['answer_E']);
  300. }
  301. if(preg_match("/(images|temp)/", $info['topic']['answer_F'])){
  302. $info['topic']['answer_F'] = get_image_url($info['topic']['answer_F']);
  303. }
  304. }
  305. }
  306. // 未答题隐藏答案
  307. // if(empty($info['topic']['submit_answer'])){
  308. // $info['topic']['correct_answer'] = '未答题';
  309. // $info['topic']['topic_analysis'] = '';
  310. // }
  311. // 多选题
  312. $topicType = isset($info['topic']['topic_type'])? $info['topic']['topic_type'] : '';
  313. if($topicType == '多选题'){
  314. $info['topic']['submit_answers'] = $info['topic']['submit_answer']?explode(',', $info['topic']['submit_answer']) : '';
  315. $info['topic']['correct_answers'] = $info['topic']['correct_answer']?explode(',', $info['topic']['correct_answer']) : [];
  316. }
  317. $info['topic']['answers'] = [];
  318. if($info['topic']['answer_A']){
  319. $info['topic']['answers'][] = ['code'=>'A','value'=> $info['topic']['answer_A']];
  320. }
  321. if($info['topic']['answer_B']){
  322. $info['topic']['answers'][] = ['code'=>'B','value'=> $info['topic']['answer_B']];
  323. }
  324. if($info['topic']['answer_C']){
  325. $info['topic']['answers'][] = ['code'=>'C','value'=> $info['topic']['answer_C']];
  326. }
  327. if($info['topic']['answer_D']){
  328. $info['topic']['answers'][] = ['code'=>'D','value'=> $info['topic']['answer_D']];
  329. }
  330. if($info['topic']['answer_E']){
  331. $info['topic']['answers'][] = ['code'=>'E','value'=> $info['topic']['answer_E']];
  332. }
  333. if($info['topic']['answer_F']){
  334. $info['topic']['answers'][] = ['code'=>'F','value'=> $info['topic']['answer_F']];
  335. }
  336. // 上一题
  337. $info['last'] = ExamTopicModel::where(['paper_id'=> $paperId,'status'=>1,'mark'=>1])
  338. ->where('id','<', $topicId)
  339. ->select(['id','topic_name'])
  340. ->orderBy('sort','asc')
  341. ->orderBy('id','desc')
  342. ->first();
  343. $info['last'] = $info['last']? $info['last']->toArray() :['id'=>0];
  344. // 下一题
  345. $info['next'] = ExamTopicModel::where(['paper_id'=> $paperId,'status'=>1,'mark'=>1])
  346. ->where('id','>', $topicId)
  347. ->select(['id','topic_name'])
  348. ->orderBy('sort','desc')
  349. ->orderBy('id','asc')
  350. ->first();
  351. $info['next'] = $info['next']? $info['next']->toArray() :['id'=>0];
  352. }
  353. RedisService::set($cacheKey, $info, rand(10, 20));
  354. }
  355. return $info;
  356. }
  357. /**
  358. * 获取随机试卷
  359. * @param $userId 用户
  360. * @param $type 试卷类型
  361. * @param $sceneType 场景
  362. * @param false $refresh
  363. * @return array|mixed
  364. */
  365. public function getRandomPaper($userId, $type, $sceneType, $refresh=false)
  366. {
  367. $cacheKey = "caches:papers:random_{$userId}:{$type}_{$sceneType}";
  368. $data = RedisService::get($cacheKey);
  369. if($data && !$refresh){
  370. return $data;
  371. }
  372. $data = $this->model->where(['type'=>$type,'scene_type'=>$sceneType,'status'=>1,'mark'=>1])
  373. ->orderByRaw('RAND()')
  374. ->first();
  375. $data = $data? $data->toArray() : [];
  376. if($data){
  377. $data['score'] = 0;
  378. $data['paper_id'] = $data['id'];
  379. $data['accurate_count'] = 0;
  380. $data['date'] = date('Y-m-d');
  381. $data['answer_count'] = 0;
  382. $data['answer_times'] = 0;
  383. RedisService::set($cacheKey, $data, rand(10, 20));
  384. }
  385. return $data;
  386. }
  387. /**
  388. * 纠错
  389. * @param $userId
  390. * @param $params
  391. * @return bool
  392. */
  393. public function submitError($userId, $params)
  394. {
  395. $id = isset($params['id'])? $params['id'] : 0;
  396. $rid = isset($params['rid'])? $params['rid'] : 0;
  397. $type = isset($params['type'])? $params['type'] : 0;
  398. $moduleType = isset($params['module_type'])? $params['module_type'] : 1;
  399. $description = isset($params['description'])? $params['description'] : '';
  400. if($id<=0 || $moduleType<=0){
  401. $this->error = '参数错误';
  402. return false;
  403. }
  404. if($type<=0){
  405. $this->error = '请选择错误类型';
  406. return false;
  407. }
  408. if(empty($description)){
  409. $this->error = '请输入错误描述';
  410. return false;
  411. }
  412. $limitTime = ConfigService::make()->getConfigByCode('limit_exam_error_submit', 5);
  413. $cacheKey = "caches:paper:errors_{$userId}:{$id}_{$rid}";
  414. if(RedisService::get($cacheKey) && $limitTime>0){
  415. $this->error = '您近期已提交过该题错误,请稍后再试~';
  416. return false;
  417. }
  418. $paperInfo = $this->model->where(['id' => $id, 'mark' => 1])->first();
  419. if (empty($paperInfo)) {
  420. $this->error = '试题不存在';
  421. return false;
  422. }
  423. if($limitTime>0 && $logId = ExamErrorModel::where(['user_id'=> $userId,'rid'=>$rid,'paper_id'=> $id,'mark'=>1])->where('create_time','>=', time() - $limitTime* 60)->value('id')){
  424. $this->error = '您近期已提交过该题错误,请稍后再试~';
  425. RedisService::set($cacheKey, ['id'=> $logId,'paper_id'=>$id], $limitTime* 60);
  426. return false;
  427. }
  428. $data = [
  429. 'user_id'=> $userId,
  430. 'paper_id'=> $id,
  431. 'rid'=> $rid,
  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. }