ExamPdfExportService.php 26 KB

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