ExamAnalysisService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. <?php
  2. namespace App\Services;
  3. use App\DTO\ExamAnalysisDataDto;
  4. use App\DTO\ReportPayloadDto;
  5. use App\Jobs\ProcessAnalysisReportTaskJob;
  6. use App\Models\Paper;
  7. use App\Models\PaperQuestion;
  8. use App\Models\Student;
  9. use Illuminate\Support\Facades\Log;
  10. /**
  11. * 学情报告核心服务
  12. * 负责协调学情报告生成的完整流程
  13. */
  14. class ExamAnalysisService
  15. {
  16. public function __construct(
  17. private readonly TaskManager $taskManager,
  18. private readonly LearningAnalyticsService $learningAnalyticsService,
  19. private readonly QuestionBankService $questionBankService,
  20. private readonly ExamPdfExportService $pdfExportService,
  21. private readonly QuestionServiceApi $questionServiceApi,
  22. private readonly ExamAnswerAnalysisService $examAnswerAnalysisService
  23. ) {}
  24. /**
  25. * 生成学情报告
  26. * 异步模式,立即返回任务ID。
  27. * 入队仅创建任务并投递 pdf 队列;构建分析数据、渲染与上传等复杂流程在 worker 内执行。
  28. */
  29. public function generateReport(string $paperId, string $studentId, ?string $recordId = null): string
  30. {
  31. // 创建异步任务
  32. $taskId = $this->taskManager->createTask(
  33. TaskManager::TASK_TYPE_ANALYSIS,
  34. compact('paperId', 'studentId', 'recordId')
  35. );
  36. Log::info('ExamAnalysisService: 开始生成学情报告', [
  37. 'task_id' => $taskId,
  38. 'paper_id' => $paperId,
  39. 'student_id' => $studentId,
  40. 'record_id' => $recordId,
  41. ]);
  42. // 复杂流程改为统一进入 pdf 队列异步处理
  43. dispatch(new ProcessAnalysisReportTaskJob(
  44. $taskId,
  45. $paperId,
  46. $studentId,
  47. $recordId
  48. ));
  49. return $taskId;
  50. }
  51. /**
  52. * 获取分析数据(同步模式)
  53. * 用于页面直接展示,不生成PDF
  54. */
  55. public function getAnalysisData(string $paperId, string $studentId, ?string $recordId = null): ExamAnalysisDataDto
  56. {
  57. try {
  58. Log::info('ExamAnalysisService: 获取分析数据', compact('paperId', 'studentId'));
  59. // 获取试卷数据
  60. $paperData = $this->getPaperData($paperId);
  61. if (!$paperData) {
  62. throw new \Exception('未找到试卷数据');
  63. }
  64. // 获取学生数据
  65. $studentData = $this->getStudentData($studentId);
  66. // 获取题目数据
  67. $questionsData = $this->getQuestionsData($paperId, $paperData);
  68. // 获取分析数据
  69. $analysisData = $this->getLearningAnalysisData($paperId, $studentId, $paperData);
  70. // 获取掌握度数据
  71. $masteryData = $this->getMasteryData($studentId);
  72. // 获取学习建议
  73. $recommendations = $this->getLearningRecommendations($studentId);
  74. $dto = new ExamAnalysisDataDto(
  75. paper: $paperData,
  76. student: $studentData,
  77. questions: $questionsData,
  78. mastery: $masteryData,
  79. insights: $analysisData,
  80. recommendations: $recommendations,
  81. analysisId: $paperData['analysis_id'] ?? null
  82. );
  83. Log::info('ExamAnalysisService: 分析数据获取完成', [
  84. 'paper_id' => $paperId,
  85. 'student_id' => $studentId,
  86. 'question_count' => count($questionsData),
  87. 'has_analysis' => !empty($analysisData),
  88. ]);
  89. return $dto;
  90. } catch (\Exception $e) {
  91. Log::error('ExamAnalysisService: 获取分析数据失败', [
  92. 'paper_id' => $paperId,
  93. 'student_id' => $studentId,
  94. 'error' => $e->getMessage(),
  95. ]);
  96. throw $e;
  97. }
  98. }
  99. /**
  100. * 处理报告生成(后台任务)
  101. */
  102. public function processReportGenerationTask(string $taskId, string $paperId, string $studentId, ?string $recordId): void
  103. {
  104. // 分析数据组装、渲染与 exam_analysis_results / student_reports 落库均在
  105. // ExamPdfExportService::generateAnalysisReportPdf 内完成;此处不再重复 getAnalysisData,
  106. // 避免 pdf worker 内双倍内存与 DB 压力(与 GenerateAnalysisPdfJob 路径一致)。
  107. $this->taskManager->updateTaskProgress($taskId, 10, '正在生成学情分析PDF...');
  108. $pdfUrl = $this->pdfExportService->generateAnalysisReportPdf($paperId, $studentId, $recordId);
  109. if (!$pdfUrl) {
  110. throw new \RuntimeException('PDF生成失败');
  111. }
  112. $this->taskManager->updateTaskProgress($taskId, 90, '正在完成任务...');
  113. // 标记任务完成
  114. $this->taskManager->markTaskCompleted($taskId, [
  115. 'pdf_url' => $pdfUrl,
  116. ]);
  117. Log::info('ExamAnalysisService: 学情报告生成完成', [
  118. 'task_id' => $taskId,
  119. 'paper_id' => $paperId,
  120. 'student_id' => $studentId,
  121. 'pdf_url' => $pdfUrl,
  122. ]);
  123. // 发送回调通知
  124. $this->taskManager->sendCallback($taskId);
  125. }
  126. /**
  127. * 获取试卷数据
  128. */
  129. private function getPaperData(string $paperId): ?array
  130. {
  131. $paper = Paper::with(['questions' => function ($query) {
  132. $query->orderBy('question_number')->orderBy('id');
  133. }])->find($paperId);
  134. if (!$paper) {
  135. return null;
  136. }
  137. return [
  138. 'id' => $paper->paper_id,
  139. 'paper_id' => $paper->paper_id,
  140. 'name' => $paper->paper_name,
  141. 'total_questions' => $paper->question_count,
  142. 'total_score' => $paper->total_score,
  143. 'analysis_id' => $paper->analysis_id,
  144. 'created_at' => $paper->created_at->toISOString(),
  145. ];
  146. }
  147. /**
  148. * 获取学生数据
  149. */
  150. private function getStudentData(string $studentId): array
  151. {
  152. $student = Student::find($studentId);
  153. return [
  154. 'id' => $student?->student_id ?? $studentId,
  155. 'student_id' => $student?->student_id ?? $studentId,
  156. 'name' => $student?->name ?? $studentId,
  157. 'grade' => $student?->grade ?? '未知年级',
  158. 'class' => $student?->class_name ?? '未知班级',
  159. ];
  160. }
  161. /**
  162. * 获取题目数据
  163. */
  164. private function getQuestionsData(string $paperId, array $paperData): array
  165. {
  166. $paper = Paper::with('questions')->find($paperId);
  167. if (!$paper || $paper->questions->isEmpty()) {
  168. return [];
  169. }
  170. $kpNameMap = $this->getKnowledgePointNameMap();
  171. $questionDetails = $this->getQuestionDetails($paper);
  172. $questions = [];
  173. $sortedQuestions = $paper->questions->sortBy(function (PaperQuestion $q, int $idx) {
  174. $number = $q->question_number ?? $idx + 1;
  175. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  176. });
  177. foreach ($sortedQuestions as $idx => $question) {
  178. $kpCode = $question->knowledge_point ?? '';
  179. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  180. $detail = $questionDetails[(string) ($question->question_id ?? '')] ?? [];
  181. $solution = $detail['solution'] ?? $detail['解析'] ?? $detail['analysis'] ?? null;
  182. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  183. $normalizedType = $this->normalizeQuestionType($typeRaw);
  184. $number = $question->question_number ?? ($idx + 1);
  185. $questions[] = [
  186. 'question_number' => $number,
  187. 'question_text' => is_array($question->question_text)
  188. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  189. : ($question->question_text ?? ''),
  190. 'question_type' => $normalizedType,
  191. 'knowledge_point' => $kpCode,
  192. 'knowledge_point_name' => $kpName,
  193. 'score' => $question->score,
  194. 'solution' => $solution,
  195. ];
  196. }
  197. return $questions;
  198. }
  199. /**
  200. * 获取学习分析数据(修改为本地数据库查询)
  201. */
  202. private function getLearningAnalysisData(string $paperId, string $studentId, array $paperData): array
  203. {
  204. $analysisData = [];
  205. if (!empty($paperData['analysis_id'])) {
  206. Log::info('ExamAnalysisService: 从本地数据库获取分析数据', [
  207. 'paper_id' => $paperId,
  208. 'student_id' => $studentId,
  209. 'analysis_id' => $paperData['analysis_id']
  210. ]);
  211. $analysisRecord = \DB::table('exam_analysis_results')
  212. ->where('id', $paperData['analysis_id'])
  213. ->where('student_id', $studentId)
  214. ->first();
  215. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  216. $analysisData = json_decode($analysisRecord->analysis_data, true);
  217. Log::info('ExamAnalysisService: 成功获取本地分析数据', [
  218. 'data_size' => strlen($analysisRecord->analysis_data)
  219. ]);
  220. } else {
  221. Log::warning('ExamAnalysisService: 未找到本地分析数据', [
  222. 'paper_id' => $paperId,
  223. 'student_id' => $studentId,
  224. 'analysis_id' => $paperData['analysis_id']
  225. ]);
  226. }
  227. }
  228. return $analysisData;
  229. }
  230. /**
  231. * 获取掌握度数据(修改为使用本地方法)
  232. */
  233. private function getMasteryData(string $studentId): array
  234. {
  235. try {
  236. Log::info('ExamAnalysisService: 获取学生掌握度概览', [
  237. 'student_id' => $studentId
  238. ]);
  239. $masteryOverview = $this->learningAnalyticsService->getStudentMasteryOverview($studentId);
  240. $masteryData = $masteryOverview['details'] ?? [];
  241. Log::info('ExamAnalysisService: 成功获取掌握度数据', [
  242. 'count' => count($masteryData)
  243. ]);
  244. return $masteryData;
  245. } catch (\Exception $e) {
  246. Log::error('ExamAnalysisService: 获取掌握度数据失败', [
  247. 'student_id' => $studentId,
  248. 'error' => $e->getMessage()
  249. ]);
  250. return [];
  251. }
  252. }
  253. /**
  254. * 获取学习建议(修改为使用本地方法)
  255. */
  256. private function getLearningRecommendations(string $studentId): array
  257. {
  258. try {
  259. Log::info('ExamAnalysisService: 获取学习路径推荐', [
  260. 'student_id' => $studentId
  261. ]);
  262. $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
  263. $recommendations = $learningPaths['recommendations'] ?? [];
  264. Log::info('ExamAnalysisService: 成功获取学习路径推荐', [
  265. 'count' => count($recommendations)
  266. ]);
  267. return $recommendations;
  268. } catch (\Exception $e) {
  269. Log::error('ExamAnalysisService: 获取学习路径推荐失败', [
  270. 'student_id' => $studentId,
  271. 'error' => $e->getMessage()
  272. ]);
  273. return [];
  274. }
  275. }
  276. /**
  277. * 获取知识点名称映射
  278. */
  279. private function getKnowledgePointNameMap(): array
  280. {
  281. try {
  282. $options = $this->questionServiceApi->getKnowledgePointOptions();
  283. return $options ?: [];
  284. } catch (\Exception $e) {
  285. Log::warning('ExamAnalysisService: 获取知识点名称失败', [
  286. 'error' => $e->getMessage(),
  287. ]);
  288. return [];
  289. }
  290. }
  291. /**
  292. * 获取题目详情
  293. */
  294. private function getQuestionDetails(Paper $paper): array
  295. {
  296. $details = [];
  297. $questionIds = $paper->questions->pluck('question_id')->filter()->unique()->values();
  298. foreach ($questionIds as $qid) {
  299. try {
  300. $detail = $this->questionBankService->getQuestion((string) $qid);
  301. if (!empty($detail)) {
  302. $details[(string) $qid] = $detail;
  303. }
  304. } catch (\Throwable $e) {
  305. Log::warning('ExamAnalysisService: 获取题目详情失败', [
  306. 'question_id' => $qid,
  307. 'error' => $e->getMessage(),
  308. ]);
  309. }
  310. }
  311. return $details;
  312. }
  313. /**
  314. * 构建掌握度摘要
  315. */
  316. private function buildMasterySummary(array $masteryData): array
  317. {
  318. $items = [];
  319. $total = 0;
  320. $count = 0;
  321. foreach ($masteryData as $row) {
  322. $code = $row['kp_code'] ?? null;
  323. $name = $row['kp_name'] ?? ($code ?? '未知知识点');
  324. $level = (float) ($row['mastery_level'] ?? 0);
  325. $delta = $row['mastery_change'] ?? null;
  326. $items[] = [
  327. 'kp_code' => $code,
  328. 'kp_name' => $name,
  329. 'mastery_level' => $level,
  330. 'mastery_change' => $delta,
  331. ];
  332. $total += $level;
  333. $count++;
  334. }
  335. $average = $count > 0 ? round($total / $count, 2) : null;
  336. // 按掌握度从低到高排序
  337. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  338. return [
  339. 'items' => $items,
  340. 'average' => $average,
  341. 'weak_list' => array_slice($items, 0, 5),
  342. ];
  343. }
  344. /**
  345. * 标准化题型
  346. */
  347. private function normalizeQuestionType(string $type): string
  348. {
  349. $t = strtolower(trim($type));
  350. return match (true) {
  351. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  352. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  353. default => 'answer',
  354. };
  355. }
  356. /**
  357. * 使用步骤级分析算法分析考试答题数据
  358. *
  359. * 这是基于《卷子分析思考.md》思路的增强版分析方法
  360. * 支持步骤级分析、知识点映射和智能出卷推荐
  361. *
  362. * @param array $examData 考试数据,包含题目和步骤信息
  363. * @return array 分析结果
  364. *
  365. * 示例输入:
  366. * [
  367. * 'paper_id' => 'exam_001',
  368. * 'student_id' => 'student_001',
  369. * 'questions' => [
  370. * [
  371. * 'question_id' => 'Q1',
  372. * 'score' => 5,
  373. * 'score_obtained' => 3,
  374. * 'steps' => [
  375. * ['step_index' => 1, 'is_correct' => true, 'kp_id' => 'K-SQRT-SIMPLE'],
  376. * ['step_index' => 2, 'is_correct' => false, 'kp_id' => 'K-NUM-ADD-SUB']
  377. * ]
  378. * ]
  379. * ]
  380. * ]
  381. */
  382. public function analyzeWithSteps(array $examData): array
  383. {
  384. Log::info('ExamAnalysisService: 开始步骤级分析', [
  385. 'paper_id' => $examData['paper_id'] ?? 'unknown',
  386. 'student_id' => $examData['student_id'] ?? 'unknown',
  387. 'question_count' => count($examData['questions'] ?? [])
  388. ]);
  389. try {
  390. // 使用增强的分析算法
  391. $result = $this->examAnswerAnalysisService->analyzeExamAnswers($examData);
  392. Log::info('ExamAnalysisService: 步骤级分析完成', [
  393. 'paper_id' => $examData['paper_id'],
  394. 'student_id' => $examData['student_id'],
  395. 'knowledge_points_analyzed' => count($result['knowledge_point_analysis'] ?? [])
  396. ]);
  397. return $result;
  398. } catch (\Exception $e) {
  399. Log::error('ExamAnalysisService: 步骤级分析失败', [
  400. 'paper_id' => $examData['paper_id'] ?? 'unknown',
  401. 'student_id' => $examData['student_id'] ?? 'unknown',
  402. 'error' => $e->getMessage(),
  403. 'trace' => $e->getTraceAsString()
  404. ]);
  405. throw new \Exception('步骤级分析失败:' . $e->getMessage());
  406. }
  407. }
  408. /**
  409. * 获取步骤级分析结果
  410. *
  411. * @param string $studentId
  412. * @param string $paperId
  413. * @return array|null
  414. */
  415. public function getStepAnalysisResult(string $studentId, string $paperId): ?array
  416. {
  417. try {
  418. $result = \DB::connection('pgsql')
  419. ->table('exam_analysis_results')
  420. ->where('student_id', $studentId)
  421. ->where('paper_id', $paperId)
  422. ->orderBy('created_at', 'desc')
  423. ->first();
  424. if (!$result) {
  425. return null;
  426. }
  427. return json_decode($result->analysis_data, true);
  428. } catch (\Exception $e) {
  429. Log::error('ExamAnalysisService: 获取步骤级分析结果失败', [
  430. 'student_id' => $studentId,
  431. 'paper_id' => $paperId,
  432. 'error' => $e->getMessage()
  433. ]);
  434. return null;
  435. }
  436. }
  437. }