ExamAnalysisService.php 19 KB

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