ExamAnalysisService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. ) {}
  22. /**
  23. * 生成学情报告
  24. * 异步模式,立即返回任务ID
  25. */
  26. public function generateReport(string $paperId, string $studentId, ?string $recordId = null): string
  27. {
  28. // 创建异步任务
  29. $taskId = $this->taskManager->createTask(
  30. TaskManager::TASK_TYPE_ANALYSIS,
  31. compact('paperId', 'studentId', 'recordId')
  32. );
  33. Log::info('ExamAnalysisService: 开始生成学情报告', [
  34. 'task_id' => $taskId,
  35. 'paper_id' => $paperId,
  36. 'student_id' => $studentId,
  37. 'record_id' => $recordId,
  38. ]);
  39. // 触发后台处理(实际项目中应使用队列)
  40. // dispatch(new AnalysisReportJob($taskId));
  41. // 目前使用同步调用模拟异步
  42. $this->processReportGeneration($taskId, $paperId, $studentId, $recordId);
  43. return $taskId;
  44. }
  45. /**
  46. * 获取分析数据(同步模式)
  47. * 用于页面直接展示,不生成PDF
  48. */
  49. public function getAnalysisData(string $paperId, string $studentId, ?string $recordId = null): ExamAnalysisDataDto
  50. {
  51. try {
  52. Log::info('ExamAnalysisService: 获取分析数据', compact('paperId', 'studentId'));
  53. // 获取试卷数据
  54. $paperData = $this->getPaperData($paperId);
  55. if (!$paperData) {
  56. throw new \Exception('未找到试卷数据');
  57. }
  58. // 获取学生数据
  59. $studentData = $this->getStudentData($studentId);
  60. // 获取题目数据
  61. $questionsData = $this->getQuestionsData($paperId, $paperData);
  62. // 获取分析数据
  63. $analysisData = $this->getLearningAnalysisData($paperId, $studentId, $paperData);
  64. // 获取掌握度数据
  65. $masteryData = $this->getMasteryData($studentId);
  66. // 获取学习建议
  67. $recommendations = $this->getLearningRecommendations($studentId);
  68. $dto = new ExamAnalysisDataDto(
  69. paper: $paperData,
  70. student: $studentData,
  71. questions: $questionsData,
  72. mastery: $masteryData,
  73. insights: $analysisData,
  74. recommendations: $recommendations,
  75. analysisId: $paperData['analysis_id'] ?? null
  76. );
  77. Log::info('ExamAnalysisService: 分析数据获取完成', [
  78. 'paper_id' => $paperId,
  79. 'student_id' => $studentId,
  80. 'question_count' => count($questionsData),
  81. 'has_analysis' => !empty($analysisData),
  82. ]);
  83. return $dto;
  84. } catch (\Exception $e) {
  85. Log::error('ExamAnalysisService: 获取分析数据失败', [
  86. 'paper_id' => $paperId,
  87. 'student_id' => $studentId,
  88. 'error' => $e->getMessage(),
  89. ]);
  90. throw $e;
  91. }
  92. }
  93. /**
  94. * 处理报告生成(后台任务)
  95. */
  96. private function processReportGeneration(string $taskId, string $paperId, string $studentId, ?string $recordId): void
  97. {
  98. try {
  99. $this->taskManager->updateTaskProgress($taskId, 10, '正在获取分析数据...');
  100. // 获取分析数据
  101. $analysisData = $this->getAnalysisData($paperId, $studentId, $recordId);
  102. $this->taskManager->updateTaskProgress($taskId, 50, '正在生成PDF报告...');
  103. // 生成PDF
  104. $pdfUrl = $this->pdfExportService->generateAnalysisReportPdf($paperId, $studentId, $recordId);
  105. if (!$pdfUrl) {
  106. throw new \Exception('PDF生成失败');
  107. }
  108. $this->taskManager->updateTaskProgress($taskId, 90, '正在保存报告...');
  109. // 保存PDF URL到数据库
  110. $this->savePdfUrl($paperId, $studentId, $recordId, $pdfUrl);
  111. // 标记任务完成
  112. $this->taskManager->markTaskCompleted($taskId, [
  113. 'pdf_url' => $pdfUrl,
  114. ]);
  115. Log::info('ExamAnalysisService: 学情报告生成完成', [
  116. 'task_id' => $taskId,
  117. 'paper_id' => $paperId,
  118. 'student_id' => $studentId,
  119. 'pdf_url' => $pdfUrl,
  120. ]);
  121. // 发送回调通知
  122. $this->taskManager->sendCallback($taskId);
  123. } catch (\Exception $e) {
  124. Log::error('ExamAnalysisService: 报告生成失败', [
  125. 'task_id' => $taskId,
  126. 'paper_id' => $paperId,
  127. 'student_id' => $studentId,
  128. 'error' => $e->getMessage(),
  129. ]);
  130. $this->taskManager->markTaskFailed($taskId, $e->getMessage());
  131. }
  132. }
  133. /**
  134. * 获取试卷数据
  135. */
  136. private function getPaperData(string $paperId): ?array
  137. {
  138. $paper = Paper::with(['questions' => function ($query) {
  139. $query->orderBy('question_number')->orderBy('id');
  140. }])->find($paperId);
  141. if (!$paper) {
  142. return null;
  143. }
  144. return [
  145. 'id' => $paper->paper_id,
  146. 'paper_id' => $paper->paper_id,
  147. 'name' => $paper->paper_name,
  148. 'total_questions' => $paper->question_count,
  149. 'total_score' => $paper->total_score,
  150. 'analysis_id' => $paper->analysis_id,
  151. 'created_at' => $paper->created_at->toISOString(),
  152. ];
  153. }
  154. /**
  155. * 获取学生数据
  156. */
  157. private function getStudentData(string $studentId): array
  158. {
  159. $student = Student::find($studentId);
  160. return [
  161. 'id' => $student?->student_id ?? $studentId,
  162. 'student_id' => $student?->student_id ?? $studentId,
  163. 'name' => $student?->name ?? $studentId,
  164. 'grade' => $student?->grade ?? '未知年级',
  165. 'class' => $student?->class_name ?? '未知班级',
  166. ];
  167. }
  168. /**
  169. * 获取题目数据
  170. */
  171. private function getQuestionsData(string $paperId, array $paperData): array
  172. {
  173. $paper = Paper::with('questions')->find($paperId);
  174. if (!$paper || $paper->questions->isEmpty()) {
  175. return [];
  176. }
  177. $kpNameMap = $this->getKnowledgePointNameMap();
  178. $questionDetails = $this->getQuestionDetails($paper);
  179. $questions = [];
  180. $sortedQuestions = $paper->questions->sortBy(function (PaperQuestion $q, int $idx) {
  181. $number = $q->question_number ?? $idx + 1;
  182. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  183. });
  184. foreach ($sortedQuestions as $idx => $question) {
  185. $kpCode = $question->knowledge_point ?? '';
  186. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  187. $detail = $questionDetails[(string) ($question->question_id ?? '')] ?? [];
  188. $solution = $detail['solution'] ?? $detail['解析'] ?? $detail['analysis'] ?? null;
  189. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  190. $normalizedType = $this->normalizeQuestionType($typeRaw);
  191. $number = $question->question_number ?? ($idx + 1);
  192. $questions[] = [
  193. 'question_number' => $number,
  194. 'question_text' => is_array($question->question_text)
  195. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  196. : ($question->question_text ?? ''),
  197. 'question_type' => $normalizedType,
  198. 'knowledge_point' => $kpCode,
  199. 'knowledge_point_name' => $kpName,
  200. 'score' => $question->score,
  201. 'solution' => $solution,
  202. ];
  203. }
  204. return $questions;
  205. }
  206. /**
  207. * 获取学习分析数据
  208. */
  209. private function getLearningAnalysisData(string $paperId, string $studentId, array $paperData): array
  210. {
  211. $analysisData = [];
  212. if (!empty($paperData['analysis_id'])) {
  213. $analysis = $this->learningAnalyticsService->getAnalysisResult($paperData['analysis_id']);
  214. if (!empty($analysis['data'])) {
  215. $analysisData = $analysis['data'];
  216. }
  217. }
  218. return $analysisData;
  219. }
  220. /**
  221. * 获取掌握度数据
  222. */
  223. private function getMasteryData(string $studentId): array
  224. {
  225. $masteryData = [];
  226. $masteryResponse = $this->learningAnalyticsService->getStudentMastery($studentId);
  227. if (!empty($masteryResponse['data'])) {
  228. $masteryData = $this->buildMasterySummary($masteryResponse['data']);
  229. }
  230. return $masteryData;
  231. }
  232. /**
  233. * 获取学习建议
  234. */
  235. private function getLearningRecommendations(string $studentId): array
  236. {
  237. $recommendations = [];
  238. $recommendationResponse = $this->learningAnalyticsService->getLearningRecommendations($studentId);
  239. if (!empty($recommendationResponse['data'])) {
  240. $recommendations = $recommendationResponse['data'];
  241. }
  242. return $recommendations;
  243. }
  244. /**
  245. * 获取知识点名称映射
  246. */
  247. private function getKnowledgePointNameMap(): array
  248. {
  249. try {
  250. $options = $this->questionServiceApi->getKnowledgePointOptions();
  251. return $options ?: [];
  252. } catch (\Exception $e) {
  253. Log::warning('ExamAnalysisService: 获取知识点名称失败', [
  254. 'error' => $e->getMessage(),
  255. ]);
  256. return [];
  257. }
  258. }
  259. /**
  260. * 获取题目详情
  261. */
  262. private function getQuestionDetails(Paper $paper): array
  263. {
  264. $details = [];
  265. $questionIds = $paper->questions->pluck('question_id')->filter()->unique()->values();
  266. foreach ($questionIds as $qid) {
  267. try {
  268. $detail = $this->questionBankService->getQuestion((string) $qid);
  269. if (!empty($detail)) {
  270. $details[(string) $qid] = $detail;
  271. }
  272. } catch (\Throwable $e) {
  273. Log::warning('ExamAnalysisService: 获取题目详情失败', [
  274. 'question_id' => $qid,
  275. 'error' => $e->getMessage(),
  276. ]);
  277. }
  278. }
  279. return $details;
  280. }
  281. /**
  282. * 构建掌握度摘要
  283. */
  284. private function buildMasterySummary(array $masteryData): array
  285. {
  286. $items = [];
  287. $total = 0;
  288. $count = 0;
  289. foreach ($masteryData as $row) {
  290. $code = $row['kp_code'] ?? null;
  291. $name = $row['kp_name'] ?? ($code ?? '未知知识点');
  292. $level = (float) ($row['mastery_level'] ?? 0);
  293. $delta = $row['mastery_change'] ?? null;
  294. $items[] = [
  295. 'kp_code' => $code,
  296. 'kp_name' => $name,
  297. 'mastery_level' => $level,
  298. 'mastery_change' => $delta,
  299. ];
  300. $total += $level;
  301. $count++;
  302. }
  303. $average = $count > 0 ? round($total / $count, 2) : null;
  304. // 按掌握度从低到高排序
  305. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  306. return [
  307. 'items' => $items,
  308. 'average' => $average,
  309. 'weak_list' => array_slice($items, 0, 5),
  310. ];
  311. }
  312. /**
  313. * 标准化题型
  314. */
  315. private function normalizeQuestionType(string $type): string
  316. {
  317. $t = strtolower(trim($type));
  318. return match (true) {
  319. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  320. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  321. default => 'answer',
  322. };
  323. }
  324. /**
  325. * 保存PDF URL到数据库
  326. */
  327. private function savePdfUrl(string $paperId, string $studentId, ?string $recordId, string $pdfUrl): void
  328. {
  329. try {
  330. if ($recordId) {
  331. // OCR记录
  332. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  333. if ($ocrRecord) {
  334. $ocrRecord->update(['analysis_pdf_url' => $pdfUrl]);
  335. }
  336. } else {
  337. // 学生记录 - 使用新的 student_reports 表
  338. \App\Models\StudentReport::updateOrCreate(
  339. [
  340. 'student_id' => $studentId,
  341. 'report_type' => 'exam_analysis',
  342. 'exam_id' => $paperId,
  343. ],
  344. [
  345. 'pdf_url' => $pdfUrl,
  346. 'generation_status' => 'completed',
  347. 'generated_at' => now(),
  348. 'updated_at' => now(),
  349. ]
  350. );
  351. Log::info('ExamAnalysisService: PDF URL已保存到student_reports表', [
  352. 'paper_id' => $paperId,
  353. 'student_id' => $studentId,
  354. 'pdf_url' => $pdfUrl,
  355. ]);
  356. }
  357. } catch (\Throwable $e) {
  358. Log::error('ExamAnalysisService: 保存PDF URL失败', [
  359. 'paper_id' => $paperId,
  360. 'student_id' => $studentId,
  361. 'record_id' => $recordId,
  362. 'error' => $e->getMessage(),
  363. ]);
  364. }
  365. }
  366. }