ExamAnalysisService.php 19 KB

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