PaperService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. $lastId = isset($info['answer_last_id'])? $info['answer_last_id'] : 0;
  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. $model1 = clone $model;
  250. // 验证最近一题是否为最后一题
  251. $model1 = $model1->where(function($query) use($tid,$lastId){
  252. // 答题卡选择的题目,否则默认按题目排序返回第一题
  253. if($tid>0){
  254. $query->where('a.id', $tid);
  255. }else if($lastId){
  256. $query->where('a.id', '>', $lastId);
  257. }
  258. });
  259. if($model1->value('a.id')<=0 && $lastId){
  260. $model = $model->where('a.id', $lastId);
  261. }else{
  262. $model = $model1;
  263. }
  264. $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'])
  265. ->orderBy('a.sort','desc')
  266. ->orderBy('a.id','asc')
  267. ->first();
  268. $info['topic'] = $info['topic']? $info['topic']->toArray() : [];
  269. $topicId = isset($info['topic']['id'])? $info['topic']['id'] : 0;
  270. if($info['topic'] && $topicId) {
  271. $info['topic']['accurate'] = isset($info['topic']['accurate'])?$info['topic']['accurate'] : -1;
  272. $info['topic']['topic_analysis'] = isset($info['topic']['topic_analysis'])?$info['topic']['topic_analysis'] : '';
  273. $info['topic']['answer_analysis'] = isset($info['topic']['answer_analysis'])?$info['topic']['answer_analysis'] : '';
  274. $info['topic']['topic_analysis'] = $info['topic']['topic_analysis']?$info['topic']['topic_analysis'] : $info['topic']['answer_analysis'];
  275. $info['topic']['submit_answer'] = isset($info['topic']['submit_answer'])?$info['topic']['submit_answer'] : '';
  276. $info['topic']['submit_answer_type'] = isset($info['topic']['submit_answer_type'])?$info['topic']['submit_answer_type'] : 1;
  277. $info['topic']['submit_answers'] = '';
  278. $info['topic']['collect_answers'] = [];
  279. if($info['topic']['submit_answer_type'] == 3){
  280. $info['topic']['submit_answer'] = get_image_url($info['topic']['submit_answer']);
  281. }else if($info['topic']['submit_answer_type'] == 4){
  282. $info['topic']['submit_answer'] = $info['topic']['submit_answer']?json_decode($info['topic']['submit_answer'], true):[];
  283. }else{
  284. $info['topic']['submit_answer'] = format_content($info['topic']['submit_answer']);
  285. }
  286. if($info['topic']['show_type'] == 1){
  287. $info['topic']['topic_name'] = format_content($info['topic']['topic_name']);
  288. }else if($info['topic']['show_type'] == 2){
  289. $info['topic']['topic_name'] = get_image_url($info['topic']['topic_name']);
  290. // 已经答题,返回答案
  291. if($rid>0 || $info['topic']['submit_answer']){
  292. $info['topic']['topic_analysis'] = get_image_url($info['topic']['topic_analysis']);
  293. if(preg_match("/(images|temp)/", $info['topic']['correct_answer'])){
  294. $info['topic']['correct_answer'] = get_image_url($info['topic']['correct_answer']);
  295. }
  296. if(preg_match("/(images|temp)/", $info['topic']['answer_A'])){
  297. $info['topic']['answer_A'] = get_image_url($info['topic']['answer_A']);
  298. }
  299. if(preg_match("/(images|temp)/", $info['topic']['answer_B'])){
  300. $info['topic']['answer_B'] = get_image_url($info['topic']['answer_B']);
  301. }
  302. if(preg_match("/(images|temp)/", $info['topic']['answer_C'])){
  303. $info['topic']['answer_C'] = get_image_url($info['topic']['answer_C']);
  304. }
  305. if(preg_match("/(images|temp)/", $info['topic']['answer_D'])){
  306. $info['topic']['answer_D'] = get_image_url($info['topic']['answer_D']);
  307. }
  308. if(preg_match("/(images|temp)/", $info['topic']['answer_E'])){
  309. $info['topic']['answer_E'] = get_image_url($info['topic']['answer_E']);
  310. }
  311. if(preg_match("/(images|temp)/", $info['topic']['answer_F'])){
  312. $info['topic']['answer_F'] = get_image_url($info['topic']['answer_F']);
  313. }
  314. }
  315. }
  316. // 未答题隐藏答案
  317. // if(empty($info['topic']['submit_answer'])){
  318. // $info['topic']['correct_answer'] = '未答题';
  319. // $info['topic']['topic_analysis'] = '';
  320. // }
  321. // 多选题
  322. $topicType = isset($info['topic']['topic_type'])? $info['topic']['topic_type'] : '';
  323. if($topicType == '多选题'){
  324. $info['topic']['submit_answers'] = $info['topic']['submit_answer']?explode(',', $info['topic']['submit_answer']) : '';
  325. $info['topic']['correct_answers'] = $info['topic']['correct_answer']?explode(',', $info['topic']['correct_answer']) : [];
  326. }
  327. $info['topic']['answers'] = [];
  328. if($info['topic']['answer_A']){
  329. $info['topic']['answers'][] = ['code'=>'A','value'=> $info['topic']['answer_A']];
  330. }
  331. if($info['topic']['answer_B']){
  332. $info['topic']['answers'][] = ['code'=>'B','value'=> $info['topic']['answer_B']];
  333. }
  334. if($info['topic']['answer_C']){
  335. $info['topic']['answers'][] = ['code'=>'C','value'=> $info['topic']['answer_C']];
  336. }
  337. if($info['topic']['answer_D']){
  338. $info['topic']['answers'][] = ['code'=>'D','value'=> $info['topic']['answer_D']];
  339. }
  340. if($info['topic']['answer_E']){
  341. $info['topic']['answers'][] = ['code'=>'E','value'=> $info['topic']['answer_E']];
  342. }
  343. if($info['topic']['answer_F']){
  344. $info['topic']['answers'][] = ['code'=>'F','value'=> $info['topic']['answer_F']];
  345. }
  346. // 上一题
  347. $info['last'] = ExamTopicModel::where(['paper_id'=> $paperId,'status'=>1,'mark'=>1])
  348. ->where('id','<', $topicId)
  349. ->select(['id','topic_name'])
  350. ->orderBy('sort','asc')
  351. ->orderBy('id','desc')
  352. ->first();
  353. $info['last'] = $info['last']? $info['last']->toArray() :['id'=>0];
  354. // 下一题
  355. $info['next'] = ExamTopicModel::where(['paper_id'=> $paperId,'status'=>1,'mark'=>1])
  356. ->where('id','>', $topicId)
  357. ->select(['id','topic_name'])
  358. ->orderBy('sort','desc')
  359. ->orderBy('id','asc')
  360. ->first();
  361. $info['next'] = $info['next']? $info['next']->toArray() :['id'=>0];
  362. }
  363. RedisService::set($cacheKey, $info, rand(10, 20));
  364. }
  365. return $info;
  366. }
  367. /**
  368. * 获取随机试卷
  369. * @param $userId 用户
  370. * @param $type 试卷类型
  371. * @param $sceneType 场景
  372. * @param false $refresh
  373. * @return array|mixed
  374. */
  375. public function getRandomPaper($userId, $type, $sceneType, $refresh=false)
  376. {
  377. $cacheKey = "caches:papers:random_{$userId}:{$type}_{$sceneType}";
  378. $data = RedisService::get($cacheKey);
  379. if($data && !$refresh){
  380. return $data;
  381. }
  382. $data = $this->model->where(['type'=>$type,'scene_type'=>$sceneType,'status'=>1,'mark'=>1])
  383. ->orderByRaw('RAND()')
  384. ->first();
  385. $data = $data? $data->toArray() : [];
  386. if($data){
  387. $data['score'] = 0;
  388. $data['paper_id'] = $data['id'];
  389. $data['accurate_count'] = 0;
  390. $data['date'] = date('Y-m-d');
  391. $data['answer_count'] = 0;
  392. $data['answer_times'] = 0;
  393. RedisService::set($cacheKey, $data, rand(10, 20));
  394. }
  395. return $data;
  396. }
  397. /**
  398. * 纠错
  399. * @param $userId
  400. * @param $params
  401. * @return bool
  402. */
  403. public function submitError($userId, $params)
  404. {
  405. $id = isset($params['id'])? $params['id'] : 0;
  406. $type = isset($params['type'])? $params['type'] : 0;
  407. $moduleType = isset($params['module_type'])? $params['module_type'] : 1;
  408. $description = isset($params['description'])? $params['description'] : '';
  409. if($id<=0 || $moduleType<=0){
  410. $this->error = '参数错误';
  411. return false;
  412. }
  413. if($type<=0){
  414. $this->error = '请选择错误类型';
  415. return false;
  416. }
  417. if(empty($description)){
  418. $this->error = '请输入错误描述';
  419. return false;
  420. }
  421. $limitTime = ConfigService::make()->getConfigByCode('limit_exam_error_submit', 5);
  422. $cacheKey = "caches:paper:errors_{$userId}:{$id}";
  423. if(RedisService::get($cacheKey) && $limitTime>0){
  424. $this->error = '您近期已提交过该题错误,请稍后再试~';
  425. return false;
  426. }
  427. $paperInfo = $this->model->where(['id' => $id, 'mark' => 1])->first();
  428. if (empty($paperInfo)) {
  429. $this->error = '试题不存在';
  430. return false;
  431. }
  432. if($limitTime>0 && $logId = ExamErrorModel::where(['user_id'=> $userId,'paper_id'=> $id,'mark'=>1])->where('create_time','>=', time() - $limitTime* 60)->value('id')){
  433. $this->error = '您近期已提交过该题错误,请稍后再试~';
  434. RedisService::set($cacheKey, ['id'=> $logId,'paper_id'=>$id], $limitTime* 60);
  435. return false;
  436. }
  437. $data = [
  438. 'user_id'=> $userId,
  439. 'paper_id'=> $id,
  440. 'type'=> $type,
  441. 'module_type'=> $moduleType,
  442. 'description'=> $description,
  443. 'image_url'=> isset($params['image_url']) && $params['image_url']? get_image_path($params['image_url']) : '',
  444. 'create_time'=>time(),
  445. 'status'=>1,
  446. 'mark'=>1
  447. ];
  448. if(!$logId = ExamErrorModel::insertGetId($data)){
  449. $this->error = '提交失败';
  450. return false;
  451. }
  452. $this->error = '提交成功';
  453. RedisService::set($cacheKey, $data, $limitTime* 60);
  454. return ['id'=> $logId, 'paper_id'=> $id];
  455. }
  456. }