ExamAnalysisService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. $this->taskManager->updateTaskProgress($taskId, 10, '正在获取分析数据...');
  105. // 获取分析数据
  106. $analysisData = $this->getAnalysisData($paperId, $studentId, $recordId);
  107. $this->taskManager->updateTaskProgress($taskId, 50, '正在生成PDF报告...');
  108. // 生成PDF
  109. $pdfUrl = $this->pdfExportService->generateAnalysisReportPdf($paperId, $studentId, $recordId);
  110. if (!$pdfUrl) {
  111. throw new \Exception('PDF生成失败');
  112. }
  113. $this->taskManager->updateTaskProgress($taskId, 90, '正在保存报告...');
  114. // 保存PDF URL到数据库
  115. $this->savePdfUrl($paperId, $studentId, $recordId, $pdfUrl);
  116. // 标记任务完成
  117. $this->taskManager->markTaskCompleted($taskId, [
  118. 'pdf_url' => $pdfUrl,
  119. ]);
  120. Log::info('ExamAnalysisService: 学情报告生成完成', [
  121. 'task_id' => $taskId,
  122. 'paper_id' => $paperId,
  123. 'student_id' => $studentId,
  124. 'pdf_url' => $pdfUrl,
  125. ]);
  126. // 发送回调通知
  127. $this->taskManager->sendCallback($taskId);
  128. } catch (\Exception $e) {
  129. Log::error('ExamAnalysisService: 报告生成失败', [
  130. 'task_id' => $taskId,
  131. 'paper_id' => $paperId,
  132. 'student_id' => $studentId,
  133. 'error' => $e->getMessage(),
  134. ]);
  135. $this->taskManager->markTaskFailed($taskId, $e->getMessage());
  136. }
  137. }
  138. /**
  139. * 获取试卷数据
  140. */
  141. private function getPaperData(string $paperId): ?array
  142. {
  143. $paper = Paper::with(['questions' => function ($query) {
  144. $query->orderBy('question_number')->orderBy('id');
  145. }])->find($paperId);
  146. if (!$paper) {
  147. return null;
  148. }
  149. return [
  150. 'id' => $paper->paper_id,
  151. 'paper_id' => $paper->paper_id,
  152. 'name' => $paper->paper_name,
  153. 'total_questions' => $paper->question_count,
  154. 'total_score' => $paper->total_score,
  155. 'analysis_id' => $paper->analysis_id,
  156. 'created_at' => $paper->created_at->toISOString(),
  157. ];
  158. }
  159. /**
  160. * 获取学生数据
  161. */
  162. private function getStudentData(string $studentId): array
  163. {
  164. $student = Student::find($studentId);
  165. return [
  166. 'id' => $student?->student_id ?? $studentId,
  167. 'student_id' => $student?->student_id ?? $studentId,
  168. 'name' => $student?->name ?? $studentId,
  169. 'grade' => $student?->grade ?? '未知年级',
  170. 'class' => $student?->class_name ?? '未知班级',
  171. ];
  172. }
  173. /**
  174. * 获取题目数据
  175. */
  176. private function getQuestionsData(string $paperId, array $paperData): array
  177. {
  178. $paper = Paper::with('questions')->find($paperId);
  179. if (!$paper || $paper->questions->isEmpty()) {
  180. return [];
  181. }
  182. $kpNameMap = $this->getKnowledgePointNameMap();
  183. $questionDetails = $this->getQuestionDetails($paper);
  184. $questions = [];
  185. $sortedQuestions = $paper->questions->sortBy(function (PaperQuestion $q, int $idx) {
  186. $number = $q->question_number ?? $idx + 1;
  187. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  188. });
  189. foreach ($sortedQuestions as $idx => $question) {
  190. $kpCode = $question->knowledge_point ?? '';
  191. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  192. $detail = $questionDetails[(string) ($question->question_id ?? '')] ?? [];
  193. $solution = $detail['solution'] ?? $detail['解析'] ?? $detail['analysis'] ?? null;
  194. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  195. $normalizedType = $this->normalizeQuestionType($typeRaw);
  196. $number = $question->question_number ?? ($idx + 1);
  197. $questions[] = [
  198. 'question_number' => $number,
  199. 'question_text' => is_array($question->question_text)
  200. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  201. : ($question->question_text ?? ''),
  202. 'question_type' => $normalizedType,
  203. 'knowledge_point' => $kpCode,
  204. 'knowledge_point_name' => $kpName,
  205. 'score' => $question->score,
  206. 'solution' => $solution,
  207. ];
  208. }
  209. return $questions;
  210. }
  211. /**
  212. * 获取学习分析数据(修改为本地数据库查询)
  213. */
  214. private function getLearningAnalysisData(string $paperId, string $studentId, array $paperData): array
  215. {
  216. $analysisData = [];
  217. if (!empty($paperData['analysis_id'])) {
  218. Log::info('ExamAnalysisService: 从本地数据库获取分析数据', [
  219. 'paper_id' => $paperId,
  220. 'student_id' => $studentId,
  221. 'analysis_id' => $paperData['analysis_id']
  222. ]);
  223. $analysisRecord = \DB::table('exam_analysis_results')
  224. ->where('id', $paperData['analysis_id'])
  225. ->where('student_id', $studentId)
  226. ->first();
  227. if ($analysisRecord && !empty($analysisRecord->analysis_data)) {
  228. $analysisData = json_decode($analysisRecord->analysis_data, true);
  229. Log::info('ExamAnalysisService: 成功获取本地分析数据', [
  230. 'data_size' => strlen($analysisRecord->analysis_data)
  231. ]);
  232. } else {
  233. Log::warning('ExamAnalysisService: 未找到本地分析数据', [
  234. 'paper_id' => $paperId,
  235. 'student_id' => $studentId,
  236. 'analysis_id' => $paperData['analysis_id']
  237. ]);
  238. }
  239. }
  240. return $analysisData;
  241. }
  242. /**
  243. * 获取掌握度数据(修改为使用本地方法)
  244. */
  245. private function getMasteryData(string $studentId): array
  246. {
  247. try {
  248. Log::info('ExamAnalysisService: 获取学生掌握度概览', [
  249. 'student_id' => $studentId
  250. ]);
  251. $masteryOverview = $this->learningAnalyticsService->getStudentMasteryOverview($studentId);
  252. $masteryData = $masteryOverview['details'] ?? [];
  253. Log::info('ExamAnalysisService: 成功获取掌握度数据', [
  254. 'count' => count($masteryData)
  255. ]);
  256. return $masteryData;
  257. } catch (\Exception $e) {
  258. Log::error('ExamAnalysisService: 获取掌握度数据失败', [
  259. 'student_id' => $studentId,
  260. 'error' => $e->getMessage()
  261. ]);
  262. return [];
  263. }
  264. }
  265. /**
  266. * 获取学习建议(修改为使用本地方法)
  267. */
  268. private function getLearningRecommendations(string $studentId): array
  269. {
  270. try {
  271. Log::info('ExamAnalysisService: 获取学习路径推荐', [
  272. 'student_id' => $studentId
  273. ]);
  274. $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
  275. $recommendations = $learningPaths['recommendations'] ?? [];
  276. Log::info('ExamAnalysisService: 成功获取学习路径推荐', [
  277. 'count' => count($recommendations)
  278. ]);
  279. return $recommendations;
  280. } catch (\Exception $e) {
  281. Log::error('ExamAnalysisService: 获取学习路径推荐失败', [
  282. 'student_id' => $studentId,
  283. 'error' => $e->getMessage()
  284. ]);
  285. return [];
  286. }
  287. }
  288. /**
  289. * 获取知识点名称映射
  290. */
  291. private function getKnowledgePointNameMap(): array
  292. {
  293. try {
  294. $options = $this->questionServiceApi->getKnowledgePointOptions();
  295. return $options ?: [];
  296. } catch (\Exception $e) {
  297. Log::warning('ExamAnalysisService: 获取知识点名称失败', [
  298. 'error' => $e->getMessage(),
  299. ]);
  300. return [];
  301. }
  302. }
  303. /**
  304. * 获取题目详情
  305. */
  306. private function getQuestionDetails(Paper $paper): array
  307. {
  308. $details = [];
  309. $questionIds = $paper->questions->pluck('question_id')->filter()->unique()->values();
  310. foreach ($questionIds as $qid) {
  311. try {
  312. $detail = $this->questionBankService->getQuestion((string) $qid);
  313. if (!empty($detail)) {
  314. $details[(string) $qid] = $detail;
  315. }
  316. } catch (\Throwable $e) {
  317. Log::warning('ExamAnalysisService: 获取题目详情失败', [
  318. 'question_id' => $qid,
  319. 'error' => $e->getMessage(),
  320. ]);
  321. }
  322. }
  323. return $details;
  324. }
  325. /**
  326. * 构建掌握度摘要
  327. */
  328. private function buildMasterySummary(array $masteryData): array
  329. {
  330. $items = [];
  331. $total = 0;
  332. $count = 0;
  333. foreach ($masteryData as $row) {
  334. $code = $row['kp_code'] ?? null;
  335. $name = $row['kp_name'] ?? ($code ?? '未知知识点');
  336. $level = (float) ($row['mastery_level'] ?? 0);
  337. $delta = $row['mastery_change'] ?? null;
  338. $items[] = [
  339. 'kp_code' => $code,
  340. 'kp_name' => $name,
  341. 'mastery_level' => $level,
  342. 'mastery_change' => $delta,
  343. ];
  344. $total += $level;
  345. $count++;
  346. }
  347. $average = $count > 0 ? round($total / $count, 2) : null;
  348. // 按掌握度从低到高排序
  349. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  350. return [
  351. 'items' => $items,
  352. 'average' => $average,
  353. 'weak_list' => array_slice($items, 0, 5),
  354. ];
  355. }
  356. /**
  357. * 标准化题型
  358. */
  359. private function normalizeQuestionType(string $type): string
  360. {
  361. $t = strtolower(trim($type));
  362. return match (true) {
  363. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  364. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  365. default => 'answer',
  366. };
  367. }
  368. /**
  369. * 保存PDF URL到数据库
  370. */
  371. private function savePdfUrl(string $paperId, string $studentId, ?string $recordId, string $pdfUrl): void
  372. {
  373. try {
  374. if ($recordId) {
  375. // OCR记录
  376. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  377. if ($ocrRecord) {
  378. $ocrRecord->update(['analysis_pdf_url' => $pdfUrl]);
  379. }
  380. } else {
  381. // 学生记录 - 使用新的 student_reports 表
  382. \App\Models\StudentReport::updateOrCreate(
  383. [
  384. 'student_id' => $studentId,
  385. 'report_type' => 'exam_analysis',
  386. 'paper_id' => $paperId,
  387. ],
  388. [
  389. 'pdf_url' => $pdfUrl,
  390. 'generation_status' => 'completed',
  391. 'generated_at' => now(),
  392. 'updated_at' => now(),
  393. ]
  394. );
  395. Log::info('ExamAnalysisService: PDF URL已保存到student_reports表', [
  396. 'paper_id' => $paperId,
  397. 'student_id' => $studentId,
  398. 'pdf_url' => $pdfUrl,
  399. ]);
  400. }
  401. } catch (\Throwable $e) {
  402. Log::error('ExamAnalysisService: 保存PDF URL失败', [
  403. 'paper_id' => $paperId,
  404. 'student_id' => $studentId,
  405. 'record_id' => $recordId,
  406. 'error' => $e->getMessage(),
  407. ]);
  408. }
  409. }
  410. /**
  411. * 使用步骤级分析算法分析考试答题数据
  412. *
  413. * 这是基于《卷子分析思考.md》思路的增强版分析方法
  414. * 支持步骤级分析、知识点映射和智能出卷推荐
  415. *
  416. * @param array $examData 考试数据,包含题目和步骤信息
  417. * @return array 分析结果
  418. *
  419. * 示例输入:
  420. * [
  421. * 'paper_id' => 'exam_001',
  422. * 'student_id' => 'student_001',
  423. * 'questions' => [
  424. * [
  425. * 'question_id' => 'Q1',
  426. * 'score' => 5,
  427. * 'score_obtained' => 3,
  428. * 'steps' => [
  429. * ['step_index' => 1, 'is_correct' => true, 'kp_id' => 'K-SQRT-SIMPLE'],
  430. * ['step_index' => 2, 'is_correct' => false, 'kp_id' => 'K-NUM-ADD-SUB']
  431. * ]
  432. * ]
  433. * ]
  434. * ]
  435. */
  436. public function analyzeWithSteps(array $examData): array
  437. {
  438. Log::info('ExamAnalysisService: 开始步骤级分析', [
  439. 'paper_id' => $examData['paper_id'] ?? 'unknown',
  440. 'student_id' => $examData['student_id'] ?? 'unknown',
  441. 'question_count' => count($examData['questions'] ?? [])
  442. ]);
  443. try {
  444. // 使用增强的分析算法
  445. $result = $this->examAnswerAnalysisService->analyzeExamAnswers($examData);
  446. Log::info('ExamAnalysisService: 步骤级分析完成', [
  447. 'paper_id' => $examData['paper_id'],
  448. 'student_id' => $examData['student_id'],
  449. 'knowledge_points_analyzed' => count($result['knowledge_point_analysis'] ?? [])
  450. ]);
  451. return $result;
  452. } catch (\Exception $e) {
  453. Log::error('ExamAnalysisService: 步骤级分析失败', [
  454. 'paper_id' => $examData['paper_id'] ?? 'unknown',
  455. 'student_id' => $examData['student_id'] ?? 'unknown',
  456. 'error' => $e->getMessage(),
  457. 'trace' => $e->getTraceAsString()
  458. ]);
  459. throw new \Exception('步骤级分析失败:' . $e->getMessage());
  460. }
  461. }
  462. /**
  463. * 获取步骤级分析结果
  464. *
  465. * @param string $studentId
  466. * @param string $paperId
  467. * @return array|null
  468. */
  469. public function getStepAnalysisResult(string $studentId, string $paperId): ?array
  470. {
  471. try {
  472. $result = \DB::connection('pgsql')
  473. ->table('exam_analysis_results')
  474. ->where('student_id', $studentId)
  475. ->where('paper_id', $paperId)
  476. ->orderBy('created_at', 'desc')
  477. ->first();
  478. if (!$result) {
  479. return null;
  480. }
  481. return json_decode($result->analysis_data, true);
  482. } catch (\Exception $e) {
  483. Log::error('ExamAnalysisService: 获取步骤级分析结果失败', [
  484. 'student_id' => $studentId,
  485. 'paper_id' => $paperId,
  486. 'error' => $e->getMessage()
  487. ]);
  488. return null;
  489. }
  490. }
  491. }