ExamAnalysisService.php 17 KB

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