ExamPdfExportService.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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\Http\Request;
  9. use Illuminate\Support\Facades\File;
  10. use Illuminate\Support\Facades\Http;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Support\Facades\Storage;
  13. use Illuminate\Support\Facades\URL;
  14. use Symfony\Component\Process\Exception\ProcessSignaledException;
  15. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  16. use Symfony\Component\Process\Process;
  17. /**
  18. * PDF导出服务(重构版)
  19. * 负责生成试卷PDF、判卷PDF和学情报告PDF
  20. */
  21. class ExamPdfExportService
  22. {
  23. public function __construct(
  24. private readonly LearningAnalyticsService $learningAnalyticsService,
  25. private readonly QuestionBankService $questionBankService,
  26. private readonly QuestionServiceApi $questionServiceApi,
  27. private readonly PdfStorageService $pdfStorageService
  28. ) {}
  29. /**
  30. * 生成试卷 PDF(不含答案)
  31. */
  32. public function generateExamPdf(string $paperId): ?string
  33. {
  34. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: false, suffix: 'exam');
  35. // 如果生成成功,将 URL 写入数据库
  36. if ($url) {
  37. $this->savePdfUrlToDatabase($paperId, 'exam_pdf_url', $url);
  38. }
  39. return $url;
  40. }
  41. /**
  42. * 生成判卷 PDF(含答案与解析)
  43. */
  44. public function generateGradingPdf(string $paperId): ?string
  45. {
  46. $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
  47. // 如果生成成功,将 URL 写入数据库
  48. if ($url) {
  49. $this->savePdfUrlToDatabase($paperId, 'grading_pdf_url', $url);
  50. }
  51. return $url;
  52. }
  53. /**
  54. * 生成学情分析 PDF
  55. */
  56. public function generateAnalysisReportPdf(string $paperId, string $studentId, ?string $recordId = null): ?string
  57. {
  58. if (function_exists('set_time_limit')) {
  59. @set_time_limit(240);
  60. }
  61. try {
  62. // 构建分析数据
  63. $analysisData = $this->buildAnalysisData($paperId, $studentId);
  64. if (!$analysisData) {
  65. return null;
  66. }
  67. // 创建DTO
  68. $dto = ExamAnalysisDataDto::fromArray($analysisData);
  69. $payloadDto = ReportPayloadDto::fromExamAnalysisDataDto($dto);
  70. // 渲染HTML
  71. $html = view('exam-analysis.pdf-report', $payloadDto->toArray())->render();
  72. if (!$html) {
  73. Log::error('ExamPdfExportService: 渲染HTML为空', ['paper_id' => $paperId]);
  74. return null;
  75. }
  76. // 生成PDF
  77. $pdfBinary = $this->buildPdf($html);
  78. if (!$pdfBinary) {
  79. return null;
  80. }
  81. // 保存PDF
  82. $version = time();
  83. $path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
  84. $url = $this->pdfStorageService->put($path, $pdfBinary);
  85. if (!$url) {
  86. Log::error('ExamPdfExportService: 保存学情PDF失败', ['path' => $path]);
  87. return null;
  88. }
  89. // 保存URL到数据库
  90. $this->saveAnalysisPdfUrl($paperId, $studentId, $recordId, $url);
  91. return $url;
  92. } catch (\Throwable $e) {
  93. Log::error('ExamPdfExportService: 生成学情分析PDF失败', [
  94. 'paper_id' => $paperId,
  95. 'student_id' => $studentId,
  96. 'record_id' => $recordId,
  97. 'error' => $e->getMessage(),
  98. 'exception' => get_class($e),
  99. 'trace' => $e->getTraceAsString(),
  100. ]);
  101. return null;
  102. }
  103. }
  104. /**
  105. * 渲染并存储试卷PDF
  106. */
  107. private function renderAndStoreExamPdf(
  108. string $paperId,
  109. bool $includeAnswer,
  110. string $suffix,
  111. bool $useGradingView = false
  112. ): ?string {
  113. // 放宽脚本执行时间
  114. if (function_exists('set_time_limit')) {
  115. @set_time_limit(240);
  116. }
  117. try {
  118. $html = $this->renderExamHtml($paperId, $includeAnswer, $useGradingView);
  119. if (!$html) {
  120. Log::error('ExamPdfExportService: 渲染HTML为空', [
  121. 'paper_id' => $paperId,
  122. 'include_answer' => $includeAnswer,
  123. 'use_grading_view' => $useGradingView,
  124. ]);
  125. return null;
  126. }
  127. $pdfBinary = $this->buildPdf($html);
  128. if (!$pdfBinary) {
  129. return null;
  130. }
  131. $path = "exams/{$paperId}_{$suffix}.pdf";
  132. $url = $this->pdfStorageService->put($path, $pdfBinary);
  133. if (!$url) {
  134. Log::error('ExamPdfExportService: 保存PDF失败', ['path' => $path]);
  135. return null;
  136. }
  137. return $url;
  138. } catch (\Throwable $e) {
  139. Log::error('ExamPdfExportService: 生成PDF失败', [
  140. 'paper_id' => $paperId,
  141. 'suffix' => $suffix,
  142. 'error' => $e->getMessage(),
  143. 'exception' => get_class($e),
  144. 'trace' => $e->getTraceAsString(),
  145. ]);
  146. return null;
  147. }
  148. }
  149. /**
  150. * 渲染试卷HTML(重构版)
  151. */
  152. private function renderExamHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  153. {
  154. // 直接构造请求URL,使用路由生成HTML
  155. $routeName = $useGradingView
  156. ? 'filament.admin.auth.intelligent-exam.grading'
  157. : 'filament.admin.auth.intelligent-exam.pdf';
  158. $url = route($routeName, ['paper_id' => $paperId, 'answer' => $includeAnswer ? 'true' : 'false']);
  159. // 使用HTTP客户端获取渲染后的HTML
  160. try {
  161. $response = Http::get($url);
  162. if ($response->successful()) {
  163. return $this->ensureUtf8Html($response->body());
  164. }
  165. } catch (\Exception $e) {
  166. Log::warning('ExamPdfExportService: 通过HTTP获取HTML失败,使用备用方案', [
  167. 'paper_id' => $paperId,
  168. 'error' => $e->getMessage(),
  169. ]);
  170. }
  171. // 备用方案:直接渲染视图(如果路由不可用)
  172. try {
  173. $paper = Paper::with('questions')->find($paperId);
  174. if (!$paper) {
  175. return null;
  176. }
  177. $viewName = $useGradingView ? 'exam-pdf.grading' : 'exam-pdf.student';
  178. $html = view($viewName, compact('paper'))->render();
  179. return $this->ensureUtf8Html($html);
  180. } catch (\Exception $e) {
  181. Log::error('ExamPdfExportService: 备用方案渲染失败', [
  182. 'paper_id' => $paperId,
  183. 'error' => $e->getMessage(),
  184. ]);
  185. return null;
  186. }
  187. }
  188. /**
  189. * 构建分析数据(重构版)
  190. * 优先使用本地MySQL数据,减少API依赖
  191. */
  192. private function buildAnalysisData(string $paperId, string $studentId): ?array
  193. {
  194. $paper = Paper::with(['questions' => function ($query) {
  195. $query->orderBy('question_number')->orderBy('id');
  196. }])->find($paperId);
  197. if (!$paper) {
  198. Log::error('ExamPdfExportService: 未找到试卷', [
  199. 'paper_id' => $paperId,
  200. 'student_id' => $studentId,
  201. ]);
  202. return null;
  203. }
  204. $student = Student::find($studentId);
  205. $studentInfo = [
  206. 'id' => $student?->student_id ?? $studentId,
  207. 'name' => $student?->name ?? $studentId,
  208. 'grade' => $student?->grade ?? '未知年级',
  209. 'class' => $student?->class_name ?? '未知班级',
  210. ];
  211. // 【修改】直接从本地数据库获取分析数据(不再调用API)
  212. $analysisData = [];
  213. if (!empty($paper->analysis_id)) {
  214. Log::info('ExamPdfExportService: 从本地数据库获取试卷分析数据', [
  215. 'paper_id' => $paperId,
  216. 'student_id' => $studentId,
  217. 'analysis_id' => $paper->analysis_id
  218. ]);
  219. $analysisRecord = \DB::table('exam_analysis_results')
  220. ->where('id', $paper->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('ExamPdfExportService: 成功获取本地分析数据', [
  226. 'data_size' => strlen($analysisRecord->analysis_data)
  227. ]);
  228. } else {
  229. Log::warning('ExamPdfExportService: 未找到本地分析数据,将使用空数据', [
  230. 'paper_id' => $paperId,
  231. 'student_id' => $studentId,
  232. 'analysis_id' => $paper->analysis_id
  233. ]);
  234. }
  235. } else {
  236. Log::warning('ExamPdfExportService: 试卷无analysis_id,将使用空分析数据', [
  237. 'paper_id' => $paperId,
  238. 'student_id' => $studentId
  239. ]);
  240. }
  241. // 【修改】使用本地方法获取掌握度概览(替代API调用)
  242. $masteryData = [];
  243. try {
  244. Log::info('ExamPdfExportService: 获取学生掌握度概览', [
  245. 'student_id' => $studentId
  246. ]);
  247. $masteryOverview = $this->learningAnalyticsService->getStudentMasteryOverview($studentId);
  248. $masteryData = $masteryOverview['details'] ?? [];
  249. Log::info('ExamPdfExportService: 成功获取掌握度数据', [
  250. 'count' => count($masteryData)
  251. ]);
  252. } catch (\Exception $e) {
  253. Log::error('ExamPdfExportService: 获取掌握度数据失败', [
  254. 'student_id' => $studentId,
  255. 'error' => $e->getMessage()
  256. ]);
  257. }
  258. // 【修改】使用本地方法获取学习路径推荐(替代API调用)
  259. $recommendations = [];
  260. try {
  261. Log::info('ExamPdfExportService: 获取学习路径推荐', [
  262. 'student_id' => $studentId
  263. ]);
  264. $learningPaths = $this->learningAnalyticsService->recommendLearningPaths($studentId, 3);
  265. $recommendations = $learningPaths['recommendations'] ?? [];
  266. Log::info('ExamPdfExportService: 成功获取学习路径推荐', [
  267. 'count' => count($recommendations)
  268. ]);
  269. } catch (\Exception $e) {
  270. Log::error('ExamPdfExportService: 获取学习路径推荐失败', [
  271. 'student_id' => $studentId,
  272. 'error' => $e->getMessage()
  273. ]);
  274. }
  275. // 获取知识点名称映射
  276. $kpNameMap = $this->buildKnowledgePointNameMap();
  277. // 获取题目详情
  278. $questionDetails = $this->getQuestionDetailsFromPaper($paper);
  279. // 处理题目数据
  280. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  281. return [
  282. 'paper' => [
  283. 'id' => $paper->paper_id,
  284. 'name' => $paper->paper_name,
  285. 'total_questions' => $paper->question_count,
  286. 'total_score' => $paper->total_score,
  287. 'created_at' => $paper->created_at,
  288. ],
  289. 'student' => $studentInfo,
  290. 'questions' => $questions,
  291. 'mastery' => $this->buildMasterySummary($masteryData, $kpNameMap),
  292. 'insights' => $analysisData['question_analysis'] ?? [], // 使用question_analysis替代question_results
  293. 'recommendations' => $recommendations,
  294. 'analysis_data' => $analysisData,
  295. ];
  296. }
  297. /**
  298. * 获取题目详情
  299. */
  300. private function getQuestionDetailsFromPaper(Paper $paper): array
  301. {
  302. $details = [];
  303. $questionIds = $paper->questions->pluck('question_id')->filter()->unique()->values();
  304. foreach ($questionIds as $qid) {
  305. try {
  306. $detail = $this->questionBankService->getQuestion((string) $qid);
  307. if (!empty($detail)) {
  308. $details[(string) $qid] = $detail;
  309. }
  310. } catch (\Throwable $e) {
  311. Log::warning('ExamPdfExportService: 获取题目详情失败', [
  312. 'question_id' => $qid,
  313. 'error' => $e->getMessage(),
  314. ]);
  315. }
  316. }
  317. return $details;
  318. }
  319. /**
  320. * 处理题目数据(用于报告)
  321. */
  322. private function processQuestionsForReport(Paper $paper, array $questionDetails, array $kpNameMap): array
  323. {
  324. $grouped = [
  325. 'choice' => [],
  326. 'fill' => [],
  327. 'answer' => [],
  328. ];
  329. $sortedQuestions = $paper->questions
  330. ->sortBy(function (PaperQuestion $q, int $idx) {
  331. $number = $q->question_number ?? $idx + 1;
  332. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  333. });
  334. foreach ($sortedQuestions as $idx => $question) {
  335. $kpCode = $question->knowledge_point ?? '';
  336. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  337. $detail = $questionDetails[(string) ($question->question_id ?? '')] ?? [];
  338. $solution = $detail['solution'] ?? $detail['解析'] ?? $detail['analysis'] ?? null;
  339. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  340. $normalizedType = $this->normalizeQuestionType($typeRaw);
  341. $number = $question->question_number ?? ($idx + 1);
  342. $payload = [
  343. 'question_number' => $number,
  344. 'question_text' => is_array($question->question_text)
  345. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  346. : ($question->question_text ?? ''),
  347. 'question_type' => $normalizedType,
  348. 'knowledge_point' => $kpCode,
  349. 'knowledge_point_name' => $kpName,
  350. 'score' => $question->score,
  351. 'solution' => $solution,
  352. ];
  353. $grouped[$normalizedType][] = $payload;
  354. }
  355. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  356. // 按卷面顺序重新编号
  357. foreach ($ordered as $i => &$q) {
  358. $q['display_number'] = $i + 1;
  359. }
  360. unset($q);
  361. return $ordered;
  362. }
  363. /**
  364. * 构建PDF
  365. */
  366. private function buildPdf(string $html): ?string
  367. {
  368. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  369. $utf8Html = $this->ensureUtf8Html($html);
  370. file_put_contents($tmpHtml, $utf8Html);
  371. // 仅使用Chrome渲染
  372. $chromePdf = $this->renderWithChrome($tmpHtml);
  373. @unlink($tmpHtml);
  374. return $chromePdf;
  375. }
  376. /**
  377. * 使用Chrome渲染PDF
  378. */
  379. private function renderWithChrome(string $htmlPath): ?string
  380. {
  381. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  382. $userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
  383. $chromeBinary = $this->findChromeBinary();
  384. if (!$chromeBinary) {
  385. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  386. return null;
  387. }
  388. // 设置运行时目录
  389. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  390. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  391. if (!File::exists($runtimeHome)) {
  392. @File::makeDirectory($runtimeHome, 0755, true);
  393. }
  394. if (!File::exists($runtimeXdg)) {
  395. @File::makeDirectory($runtimeXdg, 0755, true);
  396. }
  397. $process = new Process([
  398. $chromeBinary,
  399. '--headless',
  400. '--disable-gpu',
  401. '--no-sandbox',
  402. '--disable-setuid-sandbox',
  403. '--disable-dev-shm-usage',
  404. '--no-zygote',
  405. '--disable-features=VizDisplayCompositor',
  406. '--disable-software-rasterizer',
  407. '--disable-extensions',
  408. '--disable-background-networking',
  409. '--disable-component-update',
  410. '--disable-client-side-phishing-detection',
  411. '--disable-default-apps',
  412. '--disable-domain-reliability',
  413. '--disable-sync',
  414. '--safebrowsing-disable-auto-update',
  415. '--no-first-run',
  416. '--no-default-browser-check',
  417. '--disable-crash-reporter',
  418. '--disable-print-preview',
  419. '--disable-features=PrintHeaderFooter',
  420. '--disable-features=TranslateUI',
  421. '--disable-features=OptimizationHints',
  422. '--disable-ipc-flooding-protection',
  423. '--disable-background-networking',
  424. '--disable-background-timer-throttling',
  425. '--disable-backgrounding-occluded-windows',
  426. '--disable-renderer-backgrounding',
  427. '--disable-features=AudioServiceOutOfProcess',
  428. '--user-data-dir=' . $userDataDir,
  429. '--print-to-pdf=' . $tmpPdf,
  430. '--print-to-pdf-no-header',
  431. '--allow-file-access-from-files',
  432. 'file://' . $htmlPath,
  433. ], null, [
  434. 'HOME' => $runtimeHome,
  435. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  436. ]);
  437. $process->setTimeout(60);
  438. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  439. try {
  440. $startedAt = microtime(true);
  441. $process->start();
  442. $pdfGenerated = false;
  443. // 轮询检测PDF是否生成
  444. $pollStart = microtime(true);
  445. $maxPollSeconds = 30;
  446. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  447. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  448. $pdfGenerated = true;
  449. $process->stop(5, $killSignal);
  450. break;
  451. }
  452. usleep(200_000);
  453. }
  454. if ($process->isRunning()) {
  455. $process->stop(5, $killSignal);
  456. }
  457. $process->wait();
  458. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  459. if ($process->isRunning()) {
  460. $process->stop(5, $killSignal);
  461. }
  462. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  463. } catch (\Throwable $e) {
  464. if ($process->isRunning()) {
  465. $process->stop(5, $killSignal);
  466. }
  467. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  468. }
  469. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  470. }
  471. /**
  472. * 处理Chrome进程结果
  473. */
  474. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  475. {
  476. $pdfExists = file_exists($tmpPdf);
  477. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  478. if (!$process->isSuccessful()) {
  479. if ($pdfExists && $pdfSize > 0) {
  480. Log::warning('ExamPdfExportService: Chrome进程异常但生成了PDF', [
  481. 'exit_code' => $process->getExitCode(),
  482. 'tmp_pdf_size' => $pdfSize,
  483. ]);
  484. } else {
  485. Log::error('ExamPdfExportService: Chrome渲染失败', [
  486. 'exit_code' => $process->getExitCode(),
  487. 'error' => $process->getErrorOutput(),
  488. ]);
  489. @unlink($tmpPdf);
  490. File::deleteDirectory($userDataDir);
  491. return null;
  492. }
  493. }
  494. $pdfBinary = $pdfExists ? file_get_contents($tmpPdf) : null;
  495. @unlink($tmpPdf);
  496. File::deleteDirectory($userDataDir);
  497. return $pdfBinary ?: null;
  498. }
  499. /**
  500. * 查找Chrome二进制文件
  501. */
  502. private function findChromeBinary(): ?string
  503. {
  504. $candidates = [
  505. env('PDF_CHROME_BINARY'),
  506. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  507. '/usr/bin/google-chrome-stable',
  508. '/usr/bin/google-chrome',
  509. '/usr/bin/chromium-browser',
  510. '/usr/bin/chromium',
  511. ];
  512. foreach ($candidates as $path) {
  513. if ($path && is_file($path) && is_executable($path)) {
  514. return $path;
  515. }
  516. }
  517. return null;
  518. }
  519. /**
  520. * 确保HTML为UTF-8编码
  521. */
  522. private function ensureUtf8Html(string $html): string
  523. {
  524. $meta = '<meta charset="UTF-8">';
  525. if (stripos($html, '<head>') !== false) {
  526. return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  527. }
  528. return $meta . $html;
  529. }
  530. /**
  531. * 构建知识点名称映射
  532. */
  533. private function buildKnowledgePointNameMap(): array
  534. {
  535. try {
  536. $options = $this->questionServiceApi->getKnowledgePointOptions();
  537. return $options ?: [];
  538. } catch (\Throwable $e) {
  539. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  540. 'error' => $e->getMessage(),
  541. ]);
  542. return [];
  543. }
  544. }
  545. /**
  546. * 构建掌握度摘要
  547. */
  548. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  549. {
  550. $items = [];
  551. $total = 0;
  552. $count = 0;
  553. $hasMap = !empty($kpNameMap);
  554. foreach ($masteryData as $row) {
  555. $code = $row['kp_code'] ?? null;
  556. if ($hasMap && $code && !isset($kpNameMap[$code])) {
  557. continue;
  558. }
  559. $name = $row['kp_name'] ?? ($code ? ($kpNameMap[$code] ?? $code) : '未知知识点');
  560. $level = (float) ($row['mastery_level'] ?? 0);
  561. $delta = $row['mastery_change'] ?? null;
  562. $items[] = [
  563. 'kp_code' => $code,
  564. 'kp_name' => $name,
  565. 'mastery_level' => $level,
  566. 'mastery_change' => $delta,
  567. ];
  568. $total += $level;
  569. $count++;
  570. }
  571. $average = $count > 0 ? round($total / $count, 2) : null;
  572. // 按掌握度从低到高排序
  573. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  574. return [
  575. 'items' => $items,
  576. 'average' => $average,
  577. 'weak_list' => array_slice($items, 0, 5),
  578. ];
  579. }
  580. /**
  581. * 标准化题型
  582. */
  583. private function normalizeQuestionType(string $type): string
  584. {
  585. $t = strtolower(trim($type));
  586. return match (true) {
  587. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  588. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  589. default => 'answer',
  590. };
  591. }
  592. /**
  593. * 保存PDF URL到数据库
  594. */
  595. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  596. {
  597. try {
  598. $paper = Paper::where('paper_id', $paperId)->first();
  599. if ($paper) {
  600. $paper->update([$field => $url]);
  601. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  602. 'paper_id' => $paperId,
  603. 'field' => $field,
  604. 'url' => $url,
  605. ]);
  606. }
  607. } catch (\Throwable $e) {
  608. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  609. 'paper_id' => $paperId,
  610. 'field' => $field,
  611. 'error' => $e->getMessage(),
  612. ]);
  613. }
  614. }
  615. /**
  616. * 保存学情分析PDF URL
  617. */
  618. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  619. {
  620. try {
  621. if ($recordId) {
  622. // OCR记录
  623. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  624. if ($ocrRecord) {
  625. $ocrRecord->update(['analysis_pdf_url' => $url]);
  626. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  627. 'record_id' => $recordId,
  628. 'paper_id' => $paperId,
  629. 'student_id' => $studentId,
  630. 'url' => $url,
  631. ]);
  632. }
  633. } else {
  634. // 学生记录 - 使用新的 student_reports 表
  635. \App\Models\StudentReport::updateOrCreate(
  636. [
  637. 'student_id' => $studentId,
  638. 'report_type' => 'exam_analysis',
  639. 'exam_id' => $paperId,
  640. ],
  641. [
  642. 'pdf_url' => $url,
  643. 'generation_status' => 'completed',
  644. 'generated_at' => now(),
  645. 'updated_at' => now(),
  646. ]
  647. );
  648. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表', [
  649. 'student_id' => $studentId,
  650. 'paper_id' => $paperId,
  651. 'url' => $url,
  652. ]);
  653. }
  654. } catch (\Throwable $e) {
  655. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  656. 'paper_id' => $paperId,
  657. 'student_id' => $studentId,
  658. 'record_id' => $recordId,
  659. 'error' => $e->getMessage(),
  660. ]);
  661. }
  662. }
  663. }