ExamPdfExportService.php 28 KB

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