ExamPdfExportService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. */
  191. private function buildAnalysisData(string $paperId, string $studentId): ?array
  192. {
  193. $paper = Paper::with(['questions' => function ($query) {
  194. $query->orderBy('question_number')->orderBy('id');
  195. }])->find($paperId);
  196. if (!$paper) {
  197. Log::error('ExamPdfExportService: 未找到试卷', [
  198. 'paper_id' => $paperId,
  199. 'student_id' => $studentId,
  200. ]);
  201. return null;
  202. }
  203. $student = Student::find($studentId);
  204. $studentInfo = [
  205. 'id' => $student?->student_id ?? $studentId,
  206. 'name' => $student?->name ?? $studentId,
  207. 'grade' => $student?->grade ?? '未知年级',
  208. 'class' => $student?->class_name ?? '未知班级',
  209. ];
  210. // 获取分析数据
  211. $analysisData = [];
  212. if (!empty($paper->analysis_id)) {
  213. $analysis = $this->learningAnalyticsService->getAnalysisResult($paper->analysis_id);
  214. if (!empty($analysis['data'])) {
  215. $analysisData = $analysis['data'];
  216. }
  217. }
  218. // 获取掌握度数据
  219. $masteryData = [];
  220. $masteryResponse = $this->learningAnalyticsService->getStudentMastery($studentId);
  221. if (!empty($masteryResponse['data'])) {
  222. $masteryData = $masteryResponse['data'];
  223. }
  224. // 获取学习建议
  225. $recommendations = [];
  226. $recommendationResponse = $this->learningAnalyticsService->getLearningRecommendations($studentId);
  227. if (!empty($recommendationResponse['data'])) {
  228. $recommendations = $recommendationResponse['data'];
  229. }
  230. // 获取知识点名称映射
  231. $kpNameMap = $this->buildKnowledgePointNameMap();
  232. // 获取题目详情
  233. $questionDetails = $this->getQuestionDetailsFromPaper($paper);
  234. // 处理题目数据
  235. $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
  236. return [
  237. 'paper' => [
  238. 'id' => $paper->paper_id,
  239. 'name' => $paper->paper_name,
  240. 'total_questions' => $paper->question_count,
  241. 'total_score' => $paper->total_score,
  242. 'created_at' => $paper->created_at,
  243. ],
  244. 'student' => $studentInfo,
  245. 'questions' => $questions,
  246. 'mastery' => $this->buildMasterySummary($masteryData, $kpNameMap),
  247. 'insights' => $analysisData['question_results'] ?? [],
  248. 'recommendations' => $recommendations,
  249. 'analysis_data' => $analysisData,
  250. ];
  251. }
  252. /**
  253. * 获取题目详情
  254. */
  255. private function getQuestionDetailsFromPaper(Paper $paper): array
  256. {
  257. $details = [];
  258. $questionIds = $paper->questions->pluck('question_id')->filter()->unique()->values();
  259. foreach ($questionIds as $qid) {
  260. try {
  261. $detail = $this->questionBankService->getQuestion((string) $qid);
  262. if (!empty($detail)) {
  263. $details[(string) $qid] = $detail;
  264. }
  265. } catch (\Throwable $e) {
  266. Log::warning('ExamPdfExportService: 获取题目详情失败', [
  267. 'question_id' => $qid,
  268. 'error' => $e->getMessage(),
  269. ]);
  270. }
  271. }
  272. return $details;
  273. }
  274. /**
  275. * 处理题目数据(用于报告)
  276. */
  277. private function processQuestionsForReport(Paper $paper, array $questionDetails, array $kpNameMap): array
  278. {
  279. $grouped = [
  280. 'choice' => [],
  281. 'fill' => [],
  282. 'answer' => [],
  283. ];
  284. $sortedQuestions = $paper->questions
  285. ->sortBy(function (PaperQuestion $q, int $idx) {
  286. $number = $q->question_number ?? $idx + 1;
  287. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  288. });
  289. foreach ($sortedQuestions as $idx => $question) {
  290. $kpCode = $question->knowledge_point ?? '';
  291. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  292. $detail = $questionDetails[(string) ($question->question_id ?? '')] ?? [];
  293. $solution = $detail['solution'] ?? $detail['解析'] ?? $detail['analysis'] ?? null;
  294. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  295. $normalizedType = $this->normalizeQuestionType($typeRaw);
  296. $number = $question->question_number ?? ($idx + 1);
  297. $payload = [
  298. 'question_number' => $number,
  299. 'question_text' => is_array($question->question_text)
  300. ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
  301. : ($question->question_text ?? ''),
  302. 'question_type' => $normalizedType,
  303. 'knowledge_point' => $kpCode,
  304. 'knowledge_point_name' => $kpName,
  305. 'score' => $question->score,
  306. 'solution' => $solution,
  307. ];
  308. $grouped[$normalizedType][] = $payload;
  309. }
  310. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  311. // 按卷面顺序重新编号
  312. foreach ($ordered as $i => &$q) {
  313. $q['display_number'] = $i + 1;
  314. }
  315. unset($q);
  316. return $ordered;
  317. }
  318. /**
  319. * 构建PDF
  320. */
  321. private function buildPdf(string $html): ?string
  322. {
  323. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  324. $utf8Html = $this->ensureUtf8Html($html);
  325. file_put_contents($tmpHtml, $utf8Html);
  326. // 仅使用Chrome渲染
  327. $chromePdf = $this->renderWithChrome($tmpHtml);
  328. @unlink($tmpHtml);
  329. return $chromePdf;
  330. }
  331. /**
  332. * 使用Chrome渲染PDF
  333. */
  334. private function renderWithChrome(string $htmlPath): ?string
  335. {
  336. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  337. $userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
  338. $chromeBinary = $this->findChromeBinary();
  339. if (!$chromeBinary) {
  340. Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
  341. return null;
  342. }
  343. // 设置运行时目录
  344. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  345. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  346. if (!File::exists($runtimeHome)) {
  347. @File::makeDirectory($runtimeHome, 0755, true);
  348. }
  349. if (!File::exists($runtimeXdg)) {
  350. @File::makeDirectory($runtimeXdg, 0755, true);
  351. }
  352. $process = new Process([
  353. $chromeBinary,
  354. '--headless',
  355. '--disable-gpu',
  356. '--no-sandbox',
  357. '--disable-setuid-sandbox',
  358. '--disable-dev-shm-usage',
  359. '--no-zygote',
  360. '--disable-features=VizDisplayCompositor',
  361. '--disable-software-rasterizer',
  362. '--disable-extensions',
  363. '--disable-background-networking',
  364. '--disable-component-update',
  365. '--disable-client-side-phishing-detection',
  366. '--disable-default-apps',
  367. '--disable-domain-reliability',
  368. '--disable-sync',
  369. '--safebrowsing-disable-auto-update',
  370. '--no-first-run',
  371. '--no-default-browser-check',
  372. '--disable-crash-reporter',
  373. '--disable-print-preview',
  374. '--disable-features=PrintHeaderFooter',
  375. '--disable-features=TranslateUI',
  376. '--disable-features=OptimizationHints',
  377. '--disable-ipc-flooding-protection',
  378. '--disable-background-networking',
  379. '--disable-background-timer-throttling',
  380. '--disable-backgrounding-occluded-windows',
  381. '--disable-renderer-backgrounding',
  382. '--disable-features=AudioServiceOutOfProcess',
  383. '--user-data-dir=' . $userDataDir,
  384. '--print-to-pdf=' . $tmpPdf,
  385. '--print-to-pdf-no-header',
  386. '--allow-file-access-from-files',
  387. 'file://' . $htmlPath,
  388. ], null, [
  389. 'HOME' => $runtimeHome,
  390. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  391. ]);
  392. $process->setTimeout(60);
  393. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  394. try {
  395. $startedAt = microtime(true);
  396. $process->start();
  397. $pdfGenerated = false;
  398. // 轮询检测PDF是否生成
  399. $pollStart = microtime(true);
  400. $maxPollSeconds = 30;
  401. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  402. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  403. $pdfGenerated = true;
  404. $process->stop(5, $killSignal);
  405. break;
  406. }
  407. usleep(200_000);
  408. }
  409. if ($process->isRunning()) {
  410. $process->stop(5, $killSignal);
  411. }
  412. $process->wait();
  413. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  414. if ($process->isRunning()) {
  415. $process->stop(5, $killSignal);
  416. }
  417. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
  418. } catch (\Throwable $e) {
  419. if ($process->isRunning()) {
  420. $process->stop(5, $killSignal);
  421. }
  422. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  423. }
  424. return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
  425. }
  426. /**
  427. * 处理Chrome进程结果
  428. */
  429. private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
  430. {
  431. $pdfExists = file_exists($tmpPdf);
  432. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  433. if (!$process->isSuccessful()) {
  434. if ($pdfExists && $pdfSize > 0) {
  435. Log::warning('ExamPdfExportService: Chrome进程异常但生成了PDF', [
  436. 'exit_code' => $process->getExitCode(),
  437. 'tmp_pdf_size' => $pdfSize,
  438. ]);
  439. } else {
  440. Log::error('ExamPdfExportService: Chrome渲染失败', [
  441. 'exit_code' => $process->getExitCode(),
  442. 'error' => $process->getErrorOutput(),
  443. ]);
  444. @unlink($tmpPdf);
  445. File::deleteDirectory($userDataDir);
  446. return null;
  447. }
  448. }
  449. $pdfBinary = $pdfExists ? file_get_contents($tmpPdf) : null;
  450. @unlink($tmpPdf);
  451. File::deleteDirectory($userDataDir);
  452. return $pdfBinary ?: null;
  453. }
  454. /**
  455. * 查找Chrome二进制文件
  456. */
  457. private function findChromeBinary(): ?string
  458. {
  459. $candidates = [
  460. env('PDF_CHROME_BINARY'),
  461. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  462. '/usr/bin/google-chrome-stable',
  463. '/usr/bin/google-chrome',
  464. '/usr/bin/chromium-browser',
  465. '/usr/bin/chromium',
  466. ];
  467. foreach ($candidates as $path) {
  468. if ($path && is_file($path) && is_executable($path)) {
  469. return $path;
  470. }
  471. }
  472. return null;
  473. }
  474. /**
  475. * 确保HTML为UTF-8编码
  476. */
  477. private function ensureUtf8Html(string $html): string
  478. {
  479. $meta = '<meta charset="UTF-8">';
  480. if (stripos($html, '<head>') !== false) {
  481. return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  482. }
  483. return $meta . $html;
  484. }
  485. /**
  486. * 构建知识点名称映射
  487. */
  488. private function buildKnowledgePointNameMap(): array
  489. {
  490. try {
  491. $options = $this->questionServiceApi->getKnowledgePointOptions();
  492. return $options ?: [];
  493. } catch (\Throwable $e) {
  494. Log::warning('ExamPdfExportService: 获取知识点名称失败', [
  495. 'error' => $e->getMessage(),
  496. ]);
  497. return [];
  498. }
  499. }
  500. /**
  501. * 构建掌握度摘要
  502. */
  503. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  504. {
  505. $items = [];
  506. $total = 0;
  507. $count = 0;
  508. $hasMap = !empty($kpNameMap);
  509. foreach ($masteryData as $row) {
  510. $code = $row['kp_code'] ?? null;
  511. if ($hasMap && $code && !isset($kpNameMap[$code])) {
  512. continue;
  513. }
  514. $name = $row['kp_name'] ?? ($code ? ($kpNameMap[$code] ?? $code) : '未知知识点');
  515. $level = (float) ($row['mastery_level'] ?? 0);
  516. $delta = $row['mastery_change'] ?? null;
  517. $items[] = [
  518. 'kp_code' => $code,
  519. 'kp_name' => $name,
  520. 'mastery_level' => $level,
  521. 'mastery_change' => $delta,
  522. ];
  523. $total += $level;
  524. $count++;
  525. }
  526. $average = $count > 0 ? round($total / $count, 2) : null;
  527. // 按掌握度从低到高排序
  528. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  529. return [
  530. 'items' => $items,
  531. 'average' => $average,
  532. 'weak_list' => array_slice($items, 0, 5),
  533. ];
  534. }
  535. /**
  536. * 标准化题型
  537. */
  538. private function normalizeQuestionType(string $type): string
  539. {
  540. $t = strtolower(trim($type));
  541. return match (true) {
  542. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  543. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  544. default => 'answer',
  545. };
  546. }
  547. /**
  548. * 保存PDF URL到数据库
  549. */
  550. private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
  551. {
  552. try {
  553. $paper = Paper::where('paper_id', $paperId)->first();
  554. if ($paper) {
  555. $paper->update([$field => $url]);
  556. Log::info('ExamPdfExportService: PDF URL已写入数据库', [
  557. 'paper_id' => $paperId,
  558. 'field' => $field,
  559. 'url' => $url,
  560. ]);
  561. }
  562. } catch (\Throwable $e) {
  563. Log::error('ExamPdfExportService: 写入PDF URL失败', [
  564. 'paper_id' => $paperId,
  565. 'field' => $field,
  566. 'error' => $e->getMessage(),
  567. ]);
  568. }
  569. }
  570. /**
  571. * 保存学情分析PDF URL
  572. */
  573. private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
  574. {
  575. try {
  576. if ($recordId) {
  577. // OCR记录
  578. $ocrRecord = \App\Models\OCRRecord::find($recordId);
  579. if ($ocrRecord) {
  580. $ocrRecord->update(['analysis_pdf_url' => $url]);
  581. Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
  582. 'record_id' => $recordId,
  583. 'paper_id' => $paperId,
  584. 'student_id' => $studentId,
  585. 'url' => $url,
  586. ]);
  587. }
  588. } else {
  589. // 学生记录 - 使用新的 student_reports 表
  590. \App\Models\StudentReport::updateOrCreate(
  591. [
  592. 'student_id' => $studentId,
  593. 'report_type' => 'exam_analysis',
  594. 'exam_id' => $paperId,
  595. ],
  596. [
  597. 'pdf_url' => $url,
  598. 'generation_status' => 'completed',
  599. 'generated_at' => now(),
  600. 'updated_at' => now(),
  601. ]
  602. );
  603. Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表', [
  604. 'student_id' => $studentId,
  605. 'paper_id' => $paperId,
  606. 'url' => $url,
  607. ]);
  608. }
  609. } catch (\Throwable $e) {
  610. Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
  611. 'paper_id' => $paperId,
  612. 'student_id' => $studentId,
  613. 'record_id' => $recordId,
  614. 'error' => $e->getMessage(),
  615. ]);
  616. }
  617. }
  618. }