ExamPdfController.php 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Jobs\RegeneratePdfJob;
  4. use App\Models\Paper;
  5. use App\Services\PaperIdGenerator;
  6. use App\Support\PaperNaming;
  7. use App\Services\QuestionBankService;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Support\Facades\Cache;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Log;
  12. class ExamPdfController extends Controller
  13. {
  14. /**
  15. * 标准化选项格式为数组值列表
  16. * 支持格式:
  17. * 1. {"A": "0", "B": "5", "C": "-3", "D": "12"} -> ["0", "5", "-3", "12"]
  18. * 2. [["label": "A", "text": "选项A"], ...] -> ["选项A", "选项B", ...]
  19. * 3. ["A", "B", "C", "D"] -> ["A", "B", "C", "D"]
  20. */
  21. private function normalizeOptions($options): array
  22. {
  23. if (empty($options)) {
  24. return [];
  25. }
  26. // 如果是对象格式 {"A": "值1", "B": "值2", ...}
  27. if (is_array($options) && ! isset($options[0])) {
  28. return array_values($options);
  29. }
  30. // 如果是AI生成格式 [{"label": "A", "text": "选项A"}, ...]
  31. if (is_array($options) && isset($options[0]) && is_array($options[0])) {
  32. // 提取text字段,如果不存在则使用整个数组元素
  33. $normalized = [];
  34. foreach ($options as $opt) {
  35. if (isset($opt['text'])) {
  36. $normalized[] = $opt['text'];
  37. } elseif (isset($opt['value'])) {
  38. $normalized[] = $opt['value'];
  39. } else {
  40. // 如果既没有text也没有value,取数组的第一个值
  41. $normalized[] = is_array($opt) ? (string) reset($opt) : (string) $opt;
  42. }
  43. }
  44. return $normalized;
  45. }
  46. // 如果已经是简单数组格式 ["A", "B", "C", "D"]
  47. if (is_array($options)) {
  48. return array_values($options);
  49. }
  50. // 其他情况返回空数组
  51. return [];
  52. }
  53. /**
  54. * 根据题目内容或类型字段判断题型
  55. */
  56. private function determineQuestionType(array $question): string
  57. {
  58. // 优先根据题目内容判断(而不是数据库字段)
  59. $stem = $question['stem'] ?? $question['content'] ?? '';
  60. $tags = $question['tags'] ?? '';
  61. $skills = $question['skills'] ?? [];
  62. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  63. if (is_string($stem)) {
  64. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  65. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  66. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  67. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  68. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  69. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  70. // 至少有2个选项就认为是选择题(降低阈值)
  71. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  72. if ($optionCount >= 2) {
  73. return 'choice';
  74. }
  75. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  76. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  77. return 'choice';
  78. }
  79. }
  80. // 2. 根据技能点判断
  81. if (is_array($skills)) {
  82. $skillsStr = implode(',', $skills);
  83. if (strpos($skillsStr, '选择题') !== false) {
  84. return 'choice';
  85. }
  86. if (strpos($skillsStr, '填空题') !== false) {
  87. return 'fill';
  88. }
  89. if (strpos($skillsStr, '解答题') !== false) {
  90. return 'answer';
  91. }
  92. }
  93. // 3. 根据题目已有类型字段判断(作为后备)
  94. if (! empty($question['question_type'])) {
  95. $type = strtolower(trim($question['question_type']));
  96. if (in_array($type, ['choice', '选择题', 'choice question'])) {
  97. return 'choice';
  98. }
  99. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) {
  100. return 'fill';
  101. }
  102. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) {
  103. return 'answer';
  104. }
  105. }
  106. if (! empty($question['type'])) {
  107. $type = strtolower(trim($question['type']));
  108. if (in_array($type, ['choice', '选择题', 'choice question'])) {
  109. return 'choice';
  110. }
  111. if (in_array($type, ['fill', '填空题', 'fill in the blank'])) {
  112. return 'fill';
  113. }
  114. if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) {
  115. return 'answer';
  116. }
  117. }
  118. // 4. 根据标签判断
  119. if (is_string($tags)) {
  120. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  121. return 'choice';
  122. }
  123. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  124. return 'fill';
  125. }
  126. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  127. return 'answer';
  128. }
  129. }
  130. // 5. 填空题特征:连续下划线或明显的填空括号
  131. if (is_string($stem)) {
  132. // 检查填空题特征:连续下划线
  133. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  134. return 'fill';
  135. }
  136. // 空括号填空
  137. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  138. return 'fill';
  139. }
  140. }
  141. // 6. 根据题干内容关键词判断
  142. if (is_string($stem)) {
  143. // 有证明、解答、计算、求证等关键词的是解答题
  144. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  145. return 'answer';
  146. }
  147. }
  148. // 默认是解答题(更安全的默认值)
  149. return 'answer';
  150. }
  151. private function normalizeQuestionTypeValue(string $type): string
  152. {
  153. $type = trim($type);
  154. $lower = strtolower($type);
  155. if (in_array($lower, ['choice', 'single_choice', 'multiple_choice'], true)) {
  156. return 'choice';
  157. }
  158. if (in_array($lower, ['fill', 'blank', 'fill_in_the_blank'], true)) {
  159. return 'fill';
  160. }
  161. if (in_array($lower, ['answer', 'calculation', 'word_problem', 'proof'], true)) {
  162. return 'answer';
  163. }
  164. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  165. return 'choice';
  166. }
  167. if (in_array($type, ['FILL', 'FILL_IN_THE_BLANK'], true)) {
  168. return 'fill';
  169. }
  170. if (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  171. return 'answer';
  172. }
  173. if (in_array($type, ['选择题'], true)) {
  174. return 'choice';
  175. }
  176. if (in_array($type, ['填空题'], true)) {
  177. return 'fill';
  178. }
  179. if (in_array($type, ['解答题', '计算题'], true)) {
  180. return 'answer';
  181. }
  182. return $lower ?: 'answer';
  183. }
  184. /**
  185. * 从题目内容中提取选项
  186. */
  187. private function extractOptions(string $content): array
  188. {
  189. $options = [];
  190. // 【修复】先移除SVG内容,避免误匹配SVG注释中的 BD:DC、A:B 等内容
  191. $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
  192. // 1. 尝试匹配多种格式的选项:A. / A、/ A: / A.(中文句点)/ A.(无空格)
  193. // 【修复】选项标记必须在行首或空白后,避免误匹配 SVG 注释中的 BD:DC 等内容
  194. $pattern = '/(?:^|\s)([A-D])[\.、:.:]\s*(.+?)(?=(?:^|\s)[A-D][\.、:.:]|$)/su';
  195. if (preg_match_all($pattern, $contentWithoutSvg, $matches, PREG_SET_ORDER)) {
  196. foreach ($matches as $match) {
  197. $optionText = trim($match[2]);
  198. // 移除末尾的换行和空白
  199. $optionText = preg_replace('/\s+$/', '', $optionText);
  200. // 清理 LaTeX 格式但保留内容
  201. $optionText = preg_replace('/^\$\$\s*/', '', $optionText);
  202. $optionText = preg_replace('/\s*\$\$$/', '', $optionText);
  203. if (! empty($optionText)) {
  204. $options[] = $optionText;
  205. }
  206. }
  207. }
  208. // 2. 如果上面没提取到,尝试按换行分割
  209. if (empty($options)) {
  210. $lines = preg_split('/[\r\n]+/', $contentWithoutSvg);
  211. foreach ($lines as $line) {
  212. $line = trim($line);
  213. // 【修复】行首匹配选项标记
  214. if (preg_match('/^([A-D])[\.、:.:]\s*(.+)$/u', $line, $match)) {
  215. $optionText = trim($match[2]);
  216. if (! empty($optionText)) {
  217. $options[] = $optionText;
  218. }
  219. }
  220. }
  221. }
  222. Log::debug('选项提取结果', [
  223. 'content_preview' => mb_substr($content, 0, 150),
  224. 'options_count' => count($options),
  225. 'options' => $options,
  226. ]);
  227. return $options;
  228. }
  229. /**
  230. * 分离题干内容和选项
  231. */
  232. private function separateStemAndOptions(string $content): array
  233. {
  234. // 【修复】先移除SVG内容,避免误匹配SVG注释中的 BD:DC、A:B 等内容
  235. $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
  236. // 【修复】检测是否有选项时,要求选项标记在行首或空白后
  237. $hasOptions = preg_match('/(?:^|\s)[A-D][\.、:.:]/u', $contentWithoutSvg);
  238. if (! $hasOptions) {
  239. return [$content, []];
  240. }
  241. // 提取选项
  242. $options = $this->extractOptions($content);
  243. // 如果提取到选项,分离题干
  244. if (! empty($options)) {
  245. // 【修复】找到第一个选项的位置,要求选项标记在行首或空白后
  246. if (preg_match('/^(.+?)(?=(?:^|\s)[A-D][\.、:.:])/su', $contentWithoutSvg, $match)) {
  247. $stem = trim($match[1]);
  248. // 如果题干中有SVG占位符,从原始内容中提取对应部分
  249. if (strpos($stem, '[SVG_PLACEHOLDER]') !== false) {
  250. // 找到原始内容中对应位置的题干
  251. $stemLength = mb_strlen(str_replace('[SVG_PLACEHOLDER]', '', $stem));
  252. // 使用更精确的方法:找到第一个有效选项标记的位置
  253. foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
  254. // 只匹配在空白后的选项标记
  255. if (preg_match('/\s'.preg_quote($marker, '/').'/', $content, $m, PREG_OFFSET_CAPTURE)) {
  256. $pos = $m[0][1];
  257. if ($pos > 0) {
  258. $stem = trim(mb_substr($content, 0, $pos));
  259. break;
  260. }
  261. }
  262. }
  263. }
  264. } else {
  265. // 如果正则失败,尝试按位置分割
  266. $stem = $content;
  267. foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
  268. // 【修复】只匹配在空白后的选项标记
  269. if (preg_match('/\s'.preg_quote($marker, '/').'/', $content, $m, PREG_OFFSET_CAPTURE)) {
  270. $pos = $m[0][1];
  271. if ($pos > 0) {
  272. $stem = trim(mb_substr($content, 0, $pos));
  273. break;
  274. }
  275. }
  276. }
  277. }
  278. // 移除末尾的括号或空白
  279. $stem = preg_replace('/()\s*$/', '', $stem);
  280. $stem = trim($stem);
  281. return [$stem, $options];
  282. }
  283. return [$content, []];
  284. }
  285. /**
  286. * 根据题型获取默认分数
  287. */
  288. private function getQuestionScore(string $type): int
  289. {
  290. switch ($type) {
  291. case 'choice':
  292. return 5; // 选择题5分
  293. case 'fill':
  294. return 5; // 填空题5分
  295. case 'answer':
  296. return 10; // 解答题10分
  297. default:
  298. return 5;
  299. }
  300. }
  301. /**
  302. * 获取学生信息
  303. */
  304. private function getStudentInfo(?string $studentId): array
  305. {
  306. if (! $studentId) {
  307. return [
  308. 'name' => '未知学生',
  309. 'grade' => '未知年级',
  310. 'class' => '未知班级',
  311. ];
  312. }
  313. try {
  314. $student = DB::table('students')
  315. ->where('student_id', $studentId)
  316. ->first();
  317. if ($student) {
  318. return [
  319. 'name' => $student->name ?? $studentId,
  320. 'grade' => $student->grade ?? '未知',
  321. 'class' => $student->class ?? '未知',
  322. ];
  323. }
  324. } catch (\Exception $e) {
  325. Log::warning('获取学生信息失败', [
  326. 'student_id' => $studentId,
  327. 'error' => $e->getMessage(),
  328. ]);
  329. }
  330. return [
  331. 'name' => $studentId,
  332. 'grade' => '未知',
  333. 'class' => '未知',
  334. ];
  335. }
  336. /**
  337. * 为 PDF 预览筛选题目(简化版)
  338. */
  339. private function selectBestQuestionsForPdf(array $questions, int $targetCount, string $difficultyCategory): array
  340. {
  341. if (count($questions) <= $targetCount) {
  342. return $questions;
  343. }
  344. // 1. 按题型分类题目
  345. $categorizedQuestions = [
  346. 'choice' => [],
  347. 'fill' => [],
  348. 'answer' => [],
  349. ];
  350. foreach ($questions as $question) {
  351. $type = $this->determineQuestionType($question);
  352. if (! isset($categorizedQuestions[$type])) {
  353. $type = 'answer';
  354. }
  355. $categorizedQuestions[$type][] = $question;
  356. }
  357. // 2. 默认题型配比
  358. $typeRatio = [
  359. '选择题' => 50, // 50%
  360. '填空题' => 30, // 30%
  361. '解答题' => 20, // 20%
  362. ];
  363. // 3. 根据配比选择题目
  364. $selectedQuestions = [];
  365. foreach ($typeRatio as $type => $ratio) {
  366. $typeKey = $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer');
  367. $countForType = floor($targetCount * $ratio / 100);
  368. if ($countForType > 0 && ! empty($categorizedQuestions[$typeKey])) {
  369. $availableCount = count($categorizedQuestions[$typeKey]);
  370. $takeCount = min($countForType, $availableCount, $targetCount - count($selectedQuestions));
  371. // 随机选择题目
  372. $keys = array_keys($categorizedQuestions[$typeKey]);
  373. shuffle($keys);
  374. $selectedKeys = array_slice($keys, 0, $takeCount);
  375. foreach ($selectedKeys as $key) {
  376. $selectedQuestions[] = $categorizedQuestions[$typeKey][$key];
  377. }
  378. }
  379. }
  380. // 4. 如果数量不足,随机补充
  381. while (count($selectedQuestions) < $targetCount) {
  382. $randomQuestion = $questions[array_rand($questions)];
  383. if (! in_array($randomQuestion, $selectedQuestions)) {
  384. $selectedQuestions[] = $randomQuestion;
  385. }
  386. }
  387. // 5. 限制数量并打乱
  388. shuffle($selectedQuestions);
  389. return array_slice($selectedQuestions, 0, $targetCount);
  390. }
  391. /**
  392. * 获取教师信息
  393. */
  394. private function getTeacherInfo(?string $teacherId): array
  395. {
  396. if (! $teacherId) {
  397. return [
  398. 'name' => '未知教师',
  399. ];
  400. }
  401. try {
  402. $teacher = DB::table('teachers')
  403. ->where('teacher_id', $teacherId)
  404. ->first();
  405. if ($teacher) {
  406. return [
  407. 'name' => $teacher->name ?? $teacherId,
  408. ];
  409. }
  410. } catch (\Exception $e) {
  411. Log::warning('获取教师信息失败', [
  412. 'teacher_id' => $teacherId,
  413. 'error' => $e->getMessage(),
  414. ]);
  415. }
  416. return [
  417. 'name' => $teacherId,
  418. ];
  419. }
  420. private function buildPdfMeta(object $paper, string $fallbackPaperId, ?array $studentInfo = null): array
  421. {
  422. $rawPaperId = (string) ($paper->paper_id ?? $fallbackPaperId);
  423. $assembleType = isset($paper->paper_type) && $paper->paper_type !== '' && $paper->paper_type !== null
  424. ? (int) $paper->paper_type
  425. : null;
  426. $examCode = PaperNaming::extractExamCode($rawPaperId);
  427. $studentName = $studentInfo['name'] ?? ($paper->student_id ?? '________');
  428. try {
  429. $assembleTypeLabel = $assembleType !== null ? PaperNaming::assembleTypeLabel($assembleType) : '未知类型';
  430. } catch (\Throwable $e) {
  431. $assembleTypeLabel = '未知类型';
  432. }
  433. $headerTitle = $examCode;
  434. return [
  435. 'student_name' => $studentName,
  436. 'exam_code' => $examCode,
  437. 'assemble_type_label' => $assembleTypeLabel,
  438. 'header_title' => $headerTitle,
  439. 'exam_pdf_title' => "试卷_{$headerTitle}",
  440. 'grading_pdf_title' => "判卷_{$headerTitle}",
  441. 'knowledge_pdf_title' => "知识点梳理_{$headerTitle}",
  442. ];
  443. }
  444. public function show(Request $request, $paper_id)
  445. {
  446. // 获取是否显示答案的参数,默认为true
  447. $includeAnswer = $request->query('answer', 'true') !== 'false';
  448. // 使用 Eloquent 模型获取试卷数据
  449. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  450. if (! $paper) {
  451. // 尝试从缓存中获取生成的试卷数据(用于 demo 试卷)
  452. $cached = Cache::get('generated_exam_'.$paper_id);
  453. if ($cached) {
  454. Log::info('从缓存获取试卷数据', [
  455. 'paper_id' => $paper_id,
  456. 'cached_count' => count($cached['questions'] ?? []),
  457. 'cached_question_types' => array_column($cached['questions'] ?? [], 'question_type'),
  458. ]);
  459. // 构造临时 Paper 对象
  460. $paper = (object) [
  461. 'paper_id' => $paper_id,
  462. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  463. 'student_id' => $cached['student_id'] ?? null,
  464. 'teacher_id' => $cached['teacher_id'] ?? null,
  465. 'paper_type' => $cached['assemble_type'] ?? null,
  466. ];
  467. // 对于 demo 试卷,需要检查题目数量并限制为用户要求的数量
  468. $questionsData = $cached['questions'] ?? [];
  469. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  470. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  471. // 为 demo 试卷获取完整的题目详情(包括选项)
  472. if (! empty($questionsData)) {
  473. $questionBankService = app(QuestionBankService::class);
  474. $questionIds = array_column($questionsData, 'id');
  475. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  476. $responseData = $questionsResponse['data'] ?? [];
  477. if (! empty($responseData)) {
  478. $responseDataMap = [];
  479. foreach ($responseData as $respQ) {
  480. $responseDataMap[$respQ['id']] = $respQ;
  481. }
  482. // 合并题库数据
  483. $questionsData = array_map(function ($q) use ($responseDataMap) {
  484. if (isset($responseDataMap[$q['id']])) {
  485. $apiData = $responseDataMap[$q['id']];
  486. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  487. // 分离题干和选项
  488. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  489. $q['stem'] = $stem;
  490. $q['content'] = $stem; // 同时设置content字段
  491. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  492. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  493. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  494. // 优先使用API选项,支持多种数据格式
  495. $apiOptions = $apiData['options'] ?? null;
  496. if (! empty($apiOptions)) {
  497. // 标准化options格式为数组值列表
  498. $q['options'] = $this->normalizeOptions($apiOptions);
  499. Log::debug('使用标准化API options', [
  500. 'question_id' => $q['id'],
  501. 'raw_options' => $apiOptions,
  502. 'normalized_options' => $q['options'],
  503. ]);
  504. } else {
  505. // 备选:从题干中提取的选项
  506. $q['options'] = $extractedOptions;
  507. Log::debug('使用提取的options', [
  508. 'question_id' => $q['id'],
  509. 'extracted_options' => $extractedOptions,
  510. ]);
  511. }
  512. }
  513. return $q;
  514. }, $questionsData);
  515. }
  516. }
  517. if (count($questionsData) > $totalQuestions) {
  518. Log::info('PDF预览时发现题目过多,进行筛选', [
  519. 'paper_id' => $paper_id,
  520. 'cached_count' => count($questionsData),
  521. 'required_count' => $totalQuestions,
  522. ]);
  523. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  524. Log::info('筛选后题目数据', [
  525. 'paper_id' => $paper_id,
  526. 'filtered_count' => count($questionsData),
  527. 'filtered_types' => array_column($questionsData, 'question_type'),
  528. ]);
  529. }
  530. } else {
  531. abort(404, '试卷未找到');
  532. }
  533. } else {
  534. // 获取试卷题目
  535. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  536. ->orderBy('question_number')
  537. ->get();
  538. Log::info('从数据库获取题目', [
  539. 'paper_id' => $paper_id,
  540. 'question_count' => $paperQuestions->count(),
  541. ]);
  542. // 将 paper_questions 表的数据转换为题库格式
  543. $questionsData = [];
  544. foreach ($paperQuestions as $pq) {
  545. $questionsData[] = [
  546. 'id' => $pq->question_bank_id,
  547. 'question_number' => $pq->question_number, // 【关键】保留题目序号,用于排序
  548. 'kp_code' => $pq->knowledge_point,
  549. 'question_type' => $pq->question_type ?? 'answer', // 包含题目类型
  550. 'stem' => $pq->question_text ?? '题目内容缺失', // 如果有存储题目文本
  551. 'solution' => $pq->solution ?? '', // 保存解题思路!
  552. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  553. 'difficulty' => $pq->difficulty ?? 0.5,
  554. 'score' => $pq->score ?? 5, // 包含已计算的分值
  555. 'tags' => '',
  556. 'content' => $pq->question_text ?? '',
  557. ];
  558. }
  559. Log::debug('paper_questions 获取题目', [
  560. 'paper_id' => $paper_id,
  561. 'question_count' => count($questionsData),
  562. ]);
  563. // 如果需要完整题目详情(stem等),可以从题库获取
  564. // 但要严格限制只获取这8道题
  565. if (! empty($questionsData)) {
  566. $questionBankService = app(QuestionBankService::class);
  567. $questionIds = array_column($questionsData, 'id');
  568. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  569. $responseData = $questionsResponse['data'] ?? [];
  570. // 确保只返回请求的ID对应的题目,并保留数据库中的 question_type
  571. if (! empty($responseData)) {
  572. // 创建题库返回数据的映射
  573. $responseDataMap = [];
  574. foreach ($responseData as $respQ) {
  575. $responseDataMap[$respQ['id']] = $respQ;
  576. }
  577. // 遍历所有数据库中的题目,合并题库返回的数据
  578. $questionsData = array_map(function ($q) use ($responseDataMap, $paperQuestions) {
  579. // 从题库API获取的详细数据(如果有)
  580. if (isset($responseDataMap[$q['id']])) {
  581. $apiData = $responseDataMap[$q['id']];
  582. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  583. // 分离题干和选项
  584. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  585. // 合并数据,优先使用题库API的 stem、answer、solution、options
  586. $q['stem'] = $stem;
  587. $q['content'] = $stem; // 同时设置content字段
  588. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  589. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  590. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  591. // 优先使用API选项,支持多种数据格式
  592. $apiOptions = $apiData['options'] ?? null;
  593. if (! empty($apiOptions)) {
  594. // 标准化options格式为数组值列表
  595. $q['options'] = $this->normalizeOptions($apiOptions);
  596. Log::debug('使用标准化API options', [
  597. 'question_id' => $q['id'],
  598. 'raw_options' => $apiOptions,
  599. 'normalized_options' => $q['options'],
  600. ]);
  601. } else {
  602. // 备选:从题干中提取的选项
  603. $q['options'] = $extractedOptions;
  604. Log::debug('使用提取的options', [
  605. 'question_id' => $q['id'],
  606. 'extracted_options' => $extractedOptions,
  607. ]);
  608. }
  609. }
  610. // 从数据库 paper_questions 表中获取 question_type(已在前面设置,这里确保有值)
  611. if (! isset($q['question_type']) || empty($q['question_type'])) {
  612. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  613. if ($dbQuestion && $dbQuestion->question_type) {
  614. $q['question_type'] = $dbQuestion->question_type;
  615. }
  616. }
  617. return $q;
  618. }, $questionsData);
  619. }
  620. }
  621. }
  622. // 按题型分类(使用标准的中学数学试卷格式)
  623. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  624. foreach ($questionsData as $q) {
  625. // 题库API返回的是 stem 字段,不是 content
  626. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  627. // 分离题干和选项
  628. [$content, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  629. // 如果从题库API获取了选项,优先使用
  630. $options = $q['options'] ?? $extractedOptions;
  631. $answer = $q['answer'] ?? '';
  632. $solution = $q['solution'] ?? '';
  633. // 优先使用 question_type 字段,如果没有则根据内容智能判断
  634. $type = isset($q['question_type'])
  635. ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
  636. : $this->determineQuestionType($q);
  637. // 详细调试:记录题目类型判断结果
  638. Log::debug('题目类型判断', [
  639. 'question_id' => $q['id'] ?? '',
  640. 'has_question_type' => isset($q['question_type']),
  641. 'question_type_value' => $q['question_type'] ?? null,
  642. 'tags' => $q['tags'] ?? '',
  643. 'stem_length' => mb_strlen($content),
  644. 'stem_preview' => mb_substr($content, 0, 100),
  645. 'has_extracted_options' => ! empty($extractedOptions),
  646. 'extracted_options_count' => count($extractedOptions),
  647. 'has_api_options' => isset($q['options']) && ! empty($q['options']),
  648. 'api_options_count' => isset($q['options']) ? count($q['options']) : 0,
  649. 'final_options_count' => count($options),
  650. 'determined_type' => $type,
  651. ]);
  652. if (! isset($questions[$type])) {
  653. $type = 'answer';
  654. }
  655. // 统一处理数学公式和选项数据
  656. $questionData = [
  657. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  658. 'question_number' => $q['question_number'] ?? null, // 【关键】保留题目序号
  659. 'content' => $content,
  660. 'stem' => $content, // 同时提供stem字段
  661. 'answer' => $answer,
  662. 'solution' => $solution,
  663. 'difficulty' => $q['difficulty'] ?? 0.5,
  664. 'kp_code' => $q['kp_code'] ?? '',
  665. 'tags' => $q['tags'] ?? '',
  666. 'options' => $options, // 使用分离后的选项
  667. 'score' => $q['score'] ?? $this->getQuestionScore($type),
  668. 'question_type' => $type,
  669. ];
  670. // 统一处理数学公式 - 标记已处理,避免模板中重复处理
  671. $questionData = \App\Services\MathFormulaProcessor::processQuestionData($questionData);
  672. $questionData['math_processed'] = true; // 添加标记
  673. $qData = (object) $questionData;
  674. $questions[$type][] = $qData;
  675. }
  676. // 【关键】确保每个题型内的题目按 question_number 排序
  677. foreach (['choice', 'fill', 'answer'] as $type) {
  678. if (! empty($questions[$type])) {
  679. usort($questions[$type], function ($a, $b) {
  680. $aNum = $a->question_number ?? 0;
  681. $bNum = $b->question_number ?? 0;
  682. return $aNum <=> $bNum;
  683. });
  684. }
  685. }
  686. // 调试:记录最终分类结果
  687. Log::info('最终分类结果', [
  688. 'paper_id' => $paper_id,
  689. 'choice_count' => count($questions['choice']),
  690. 'fill_count' => count($questions['fill']),
  691. 'answer_count' => count($questions['answer']),
  692. 'total' => count($questions['choice']) + count($questions['fill']) + count($questions['answer']),
  693. ]);
  694. // 渲染视图
  695. $viewName = $includeAnswer ? 'pdf.exam-grading' : 'pdf.exam-paper';
  696. $studentInfo = $this->getStudentInfo($paper->student_id);
  697. $teacherInfo = $this->getTeacherInfo($paper->teacher_id);
  698. $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
  699. return view($viewName, [
  700. 'paper' => $paper,
  701. 'questions' => $questions,
  702. 'student' => $studentInfo,
  703. 'teacher' => $teacherInfo,
  704. 'includeAnswer' => $includeAnswer,
  705. 'pdfMeta' => $pdfMeta,
  706. ]);
  707. }
  708. /**
  709. * 判卷视图:题目前带方框,题后附"正确答案+解题思路"
  710. */
  711. public function showGrading(Request $request, $paper_id)
  712. {
  713. // 复用现有逻辑获取题目分类
  714. $includeAnswer = true;
  715. // 直接调用 show 的前置逻辑(简化复用)
  716. $request->merge(['answer' => 'true']);
  717. // 复用 show() 内逻辑获取 questions/paper
  718. // 为避免重复代码,简单调用 showData 方法(拆分为私有方法?暂直接重用现有方法流程)
  719. // 这里直接复制 show 的主体以保持兼容
  720. // 使用 Eloquent 模型获取试卷数据
  721. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  722. if (! $paper) {
  723. $cached = Cache::get('generated_exam_'.$paper_id);
  724. if (! $cached) {
  725. abort(404, '试卷未找到');
  726. }
  727. $paper = (object) [
  728. 'paper_id' => $paper_id,
  729. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  730. 'student_id' => $cached['student_id'] ?? null,
  731. 'teacher_id' => $cached['teacher_id'] ?? null,
  732. 'paper_type' => $cached['assemble_type'] ?? null,
  733. ];
  734. $questionsData = $cached['questions'] ?? [];
  735. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  736. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  737. if (! empty($questionsData)) {
  738. $questionBankService = app(QuestionBankService::class);
  739. $questionIds = array_column($questionsData, 'id');
  740. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  741. $responseData = $questionsResponse['data'] ?? [];
  742. if (! empty($responseData)) {
  743. $responseDataMap = [];
  744. foreach ($responseData as $respQ) {
  745. $responseDataMap[$respQ['id']] = $respQ;
  746. }
  747. $questionsData = array_map(function ($q) use ($responseDataMap) {
  748. if (isset($responseDataMap[$q['id']])) {
  749. $apiData = $responseDataMap[$q['id']];
  750. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  751. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  752. $q['stem'] = $stem;
  753. $q['content'] = $stem; // 同时设置content字段
  754. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  755. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  756. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  757. // 优先使用API选项,支持多种数据格式
  758. $apiOptions = $apiData['options'] ?? null;
  759. if (! empty($apiOptions)) {
  760. // 标准化options格式为数组值列表
  761. $q['options'] = $this->normalizeOptions($apiOptions);
  762. Log::debug('使用标准化API options', [
  763. 'question_id' => $q['id'],
  764. 'raw_options' => $apiOptions,
  765. 'normalized_options' => $q['options'],
  766. ]);
  767. } else {
  768. // 备选:从题干中提取的选项
  769. $q['options'] = $extractedOptions;
  770. Log::debug('使用提取的options', [
  771. 'question_id' => $q['id'],
  772. 'extracted_options' => $extractedOptions,
  773. ]);
  774. }
  775. }
  776. return $q;
  777. }, $questionsData);
  778. }
  779. }
  780. if (count($questionsData) > $totalQuestions) {
  781. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  782. }
  783. } else {
  784. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  785. ->orderBy('question_number')
  786. ->get();
  787. $questionsData = [];
  788. foreach ($paperQuestions as $pq) {
  789. $questionsData[] = [
  790. 'id' => $pq->question_bank_id,
  791. 'question_number' => $pq->question_number, // 【关键】保留题目序号
  792. 'kp_code' => $pq->knowledge_point,
  793. 'question_type' => $pq->question_type ?? 'answer',
  794. 'stem' => $pq->question_text ?? '题目内容缺失',
  795. 'solution' => $pq->solution ?? '', // 保存解题思路!
  796. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  797. 'difficulty' => $pq->difficulty ?? 0.5,
  798. 'score' => $pq->score ?? 5,
  799. 'tags' => '',
  800. 'content' => $pq->question_text ?? '',
  801. ];
  802. }
  803. if (! empty($questionsData)) {
  804. $questionBankService = app(QuestionBankService::class);
  805. $questionIds = array_column($questionsData, 'id');
  806. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  807. $responseData = $questionsResponse['data'] ?? [];
  808. if (! empty($responseData)) {
  809. $responseDataMap = [];
  810. foreach ($responseData as $respQ) {
  811. $responseDataMap[$respQ['id']] = $respQ;
  812. }
  813. $questionsData = array_map(function ($q) use ($responseDataMap, $paperQuestions) {
  814. if (isset($responseDataMap[$q['id']])) {
  815. $apiData = $responseDataMap[$q['id']];
  816. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  817. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  818. $q['stem'] = $stem;
  819. $q['content'] = $stem; // 同时设置content字段
  820. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  821. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  822. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  823. // 优先使用API选项,支持多种数据格式
  824. $apiOptions = $apiData['options'] ?? null;
  825. if (! empty($apiOptions)) {
  826. // 标准化options格式为数组值列表
  827. $q['options'] = $this->normalizeOptions($apiOptions);
  828. Log::debug('使用标准化API options', [
  829. 'question_id' => $q['id'],
  830. 'raw_options' => $apiOptions,
  831. 'normalized_options' => $q['options'],
  832. ]);
  833. } else {
  834. // 备选:从题干中提取的选项
  835. $q['options'] = $extractedOptions;
  836. Log::debug('使用提取的options', [
  837. 'question_id' => $q['id'],
  838. 'extracted_options' => $extractedOptions,
  839. ]);
  840. }
  841. }
  842. if (! isset($q['question_type']) || empty($q['question_type'])) {
  843. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  844. if ($dbQuestion && $dbQuestion->question_type) {
  845. $q['question_type'] = $dbQuestion->question_type;
  846. }
  847. }
  848. return $q;
  849. }, $questionsData);
  850. }
  851. }
  852. }
  853. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  854. foreach ($questionsData as $q) {
  855. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  856. [$content, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  857. $options = $q['options'] ?? $extractedOptions;
  858. $answer = $q['answer'] ?? '';
  859. $solution = $q['solution'] ?? '';
  860. $type = isset($q['question_type'])
  861. ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
  862. : $this->determineQuestionType($q);
  863. if (! isset($questions[$type])) {
  864. $type = 'answer';
  865. }
  866. // 统一处理数学公式和选项数据
  867. $questionData = [
  868. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  869. 'question_number' => $q['question_number'] ?? null, // 【关键】保留题目序号
  870. 'content' => $content,
  871. 'stem' => $content, // 同时提供stem字段
  872. 'answer' => $answer,
  873. 'solution' => $solution,
  874. 'difficulty' => $q['difficulty'] ?? 0.5,
  875. 'kp_code' => $q['kp_code'] ?? '',
  876. 'tags' => $q['tags'] ?? '',
  877. 'options' => $options,
  878. 'score' => $q['score'] ?? $this->getQuestionScore($type),
  879. 'question_type' => $type,
  880. ];
  881. // 统一处理数学公式 - 标记已处理,避免模板中重复处理
  882. $questionData = \App\Services\MathFormulaProcessor::processQuestionData($questionData);
  883. $questionData['math_processed'] = true; // 添加标记
  884. $qData = (object) $questionData;
  885. $questions[$type][] = $qData;
  886. }
  887. // 【关键】确保每个题型内的题目按 question_number 排序
  888. foreach (['choice', 'fill', 'answer'] as $type) {
  889. if (! empty($questions[$type])) {
  890. usort($questions[$type], function ($a, $b) {
  891. $aNum = $a->question_number ?? 0;
  892. $bNum = $b->question_number ?? 0;
  893. return $aNum <=> $bNum;
  894. });
  895. }
  896. }
  897. $studentInfo = $this->getStudentInfo($paper->student_id);
  898. $teacherInfo = $this->getTeacherInfo($paper->teacher_id);
  899. $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
  900. $appendScanSheet = config('exam.pdf_grading_append_scan_sheet', false);
  901. $gradingView = $appendScanSheet ? 'pdf.exam-answer-detail' : 'pdf.exam-grading';
  902. return view($gradingView, [
  903. 'paper' => $paper,
  904. 'questions' => $questions,
  905. 'student' => $studentInfo,
  906. 'teacher' => $teacherInfo,
  907. 'includeAnswer' => true,
  908. 'pdfMeta' => $pdfMeta,
  909. ]);
  910. }
  911. /**
  912. * 知识点讲解视图
  913. */
  914. public function showKnowledgeExplanation(Request $request, $paper_id)
  915. {
  916. // 获取试卷数据
  917. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  918. if (! $paper) {
  919. abort(404, '试卷未找到');
  920. }
  921. $studentInfo = $this->getStudentInfo($paper->student_id);
  922. $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
  923. $studentName = $pdfMeta['student_name'];
  924. // 生成时间(格式:2026年01月30日 15:04:05)
  925. $generateDateTime = now()->format('Y年m月d日 H:i:s');
  926. // 优先使用 paper 中保存的 explanation_kp_codes(组卷时指定的知识点,最多2个)
  927. $kpCodes = $paper->explanation_kp_codes ?? [];
  928. // 如果没有保存 explanation_kp_codes,回退到从题目中提取(兼容旧数据)
  929. if (empty($kpCodes)) {
  930. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)->get();
  931. $seen = [];
  932. $questionBankIds = $paperQuestions
  933. ->pluck('question_bank_id')
  934. ->filter()
  935. ->unique()
  936. ->values();
  937. $questionKpMap = [];
  938. if ($questionBankIds->isNotEmpty()) {
  939. $questionKpMap = \App\Models\Question::whereIn('id', $questionBankIds)
  940. ->pluck('kp_code', 'id')
  941. ->toArray();
  942. }
  943. foreach ($paperQuestions as $pq) {
  944. $kpCode = trim((string) ($pq->knowledge_point ?? ''));
  945. if ($kpCode === '' && ! empty($pq->question_bank_id)) {
  946. $kpCode = trim((string) ($questionKpMap[$pq->question_bank_id] ?? ''));
  947. }
  948. if ($kpCode === '') {
  949. continue;
  950. }
  951. if (isset($seen[$kpCode])) {
  952. continue;
  953. }
  954. $seen[$kpCode] = true;
  955. $kpCodes[] = $kpCode;
  956. }
  957. }
  958. // 使用 ExamPdfExportService 构建知识点数据
  959. $pdfService = app(\App\Services\ExamPdfExportService::class);
  960. // 批量获取知识点讲解
  961. $knowledgePoints = $pdfService->buildExplanations($kpCodes);
  962. return view('pdf.exam-knowledge-explanation', [
  963. 'paperId' => $paper_id,
  964. 'examCode' => $pdfMeta['exam_code'],
  965. 'studentName' => $studentName,
  966. 'generateDateTime' => $generateDateTime,
  967. 'knowledgePoints' => $knowledgePoints,
  968. 'pdfMeta' => $pdfMeta,
  969. ]);
  970. }
  971. /**
  972. * 服务端渲染预览 - 试卷(与 PDF 生成效果一致,用于调试)
  973. */
  974. public function showServerRendered(Request $request, $paper_id)
  975. {
  976. // 强制不显示答案(试卷模式)
  977. $request->merge(['answer' => 'false']);
  978. // 复用 show() 获取 HTML
  979. $view = $this->show($request, $paper_id);
  980. $html = $view->render();
  981. // 使用 KatexRenderer 服务端渲染公式
  982. $katexRenderer = new \App\Services\KatexRenderer();
  983. $rendered = $katexRenderer->disableCache()->renderHtml($html);
  984. return response($rendered);
  985. }
  986. /**
  987. * 服务端渲染预览 - 判卷(与 PDF 生成效果一致,用于调试)
  988. */
  989. public function showGradingServerRendered(Request $request, $paper_id)
  990. {
  991. // 复用 showGrading() 获取 HTML
  992. $view = $this->showGrading($request, $paper_id);
  993. $html = $view->render();
  994. // 使用 KatexRenderer 服务端渲染公式
  995. $katexRenderer = new \App\Services\KatexRenderer();
  996. $rendered = $katexRenderer->disableCache()->renderHtml($html);
  997. return response($rendered);
  998. }
  999. /**
  1000. * 重新生成 PDF(统一生成卷子和判卷)
  1001. *
  1002. * @param string $paper_id
  1003. * @return \Illuminate\Http\JsonResponse
  1004. */
  1005. public function regeneratePdf(Request $request, $paper_id)
  1006. {
  1007. Log::info('RegeneratePdf: 开始重新生成PDF', ['paper_id' => $paper_id]);
  1008. // 验证 paper_id 格式
  1009. if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
  1010. return response()->json([
  1011. 'success' => false,
  1012. 'message' => '无效的试卷ID格式',
  1013. 'paper_id' => $paper_id,
  1014. ], 400);
  1015. }
  1016. if (! PaperIdGenerator::validatePaperId((string) $paper_id)) {
  1017. Log::warning('RegeneratePdf: 非标准15位 paper_id', ['paper_id' => $paper_id]);
  1018. }
  1019. try {
  1020. // 【修复】首先检查试卷是否存在
  1021. $paperModel = Paper::with('questions')->find($paper_id);
  1022. if (! $paperModel || $paperModel->questions->isEmpty()) {
  1023. return response()->json([
  1024. 'success' => false,
  1025. 'message' => '无效的试卷',
  1026. 'paper_id' => $paper_id,
  1027. ], 400);
  1028. }
  1029. // 调用 PDF 生成服务
  1030. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1031. // 生成统一 PDF(卷子 + 判卷)
  1032. $pdfUrl = $pdfService->generateUnifiedPdf($paper_id);
  1033. if ($pdfUrl) {
  1034. Log::info('RegeneratePdf: PDF重新生成成功', [
  1035. 'paper_id' => $paper_id,
  1036. 'url' => $pdfUrl,
  1037. ]);
  1038. return response()->json([
  1039. 'success' => true,
  1040. 'message' => 'PDF重新生成成功',
  1041. 'paper_id' => $paper_id,
  1042. 'pdf_url' => $pdfUrl,
  1043. ]);
  1044. }
  1045. Log::error('RegeneratePdf: PDF生成失败', ['paper_id' => $paper_id]);
  1046. return response()->json([
  1047. 'success' => false,
  1048. 'message' => 'PDF生成失败',
  1049. 'paper_id' => $paper_id,
  1050. ], 500);
  1051. } catch (\Exception $e) {
  1052. Log::error('RegeneratePdf: 异常错误', [
  1053. 'paper_id' => $paper_id,
  1054. 'error' => $e->getMessage(),
  1055. 'trace' => $e->getTraceAsString(),
  1056. ]);
  1057. return response()->json([
  1058. 'success' => false,
  1059. 'message' => 'PDF生成异常:'.$e->getMessage(),
  1060. 'paper_id' => $paper_id,
  1061. ], 500);
  1062. }
  1063. }
  1064. /**
  1065. * 重新生成试卷 PDF(不含答案)
  1066. *
  1067. * @param string $paper_id
  1068. * @return \Illuminate\Http\JsonResponse
  1069. */
  1070. public function regenerateExamPdf(Request $request, $paper_id)
  1071. {
  1072. Log::info('RegenerateExamPdf: 开始重新生成试卷PDF', ['paper_id' => $paper_id]);
  1073. if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
  1074. return response()->json([
  1075. 'success' => false,
  1076. 'message' => '无效的试卷ID格式',
  1077. 'paper_id' => $paper_id,
  1078. ], 400);
  1079. }
  1080. if (! PaperIdGenerator::validatePaperId((string) $paper_id)) {
  1081. Log::warning('RegenerateExamPdf: 非标准15位 paper_id', ['paper_id' => $paper_id]);
  1082. }
  1083. try {
  1084. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1085. $pdfUrl = $pdfService->generateExamPdf($paper_id);
  1086. if ($pdfUrl) {
  1087. return response()->json([
  1088. 'success' => true,
  1089. 'message' => '试卷PDF重新生成成功',
  1090. 'paper_id' => $paper_id,
  1091. 'pdf_url' => $pdfUrl,
  1092. ]);
  1093. }
  1094. return response()->json([
  1095. 'success' => false,
  1096. 'message' => '试卷PDF生成失败',
  1097. 'paper_id' => $paper_id,
  1098. ], 500);
  1099. } catch (\Exception $e) {
  1100. Log::error('RegenerateExamPdf: 异常错误', [
  1101. 'paper_id' => $paper_id,
  1102. 'error' => $e->getMessage(),
  1103. ]);
  1104. return response()->json([
  1105. 'success' => false,
  1106. 'message' => 'PDF生成异常:'.$e->getMessage(),
  1107. 'paper_id' => $paper_id,
  1108. ], 500);
  1109. }
  1110. }
  1111. /**
  1112. * 重新生成判卷 PDF(含答案)
  1113. *
  1114. * @param string $paper_id
  1115. * @return \Illuminate\Http\JsonResponse
  1116. */
  1117. public function regenerateGradingPdf(Request $request, $paper_id)
  1118. {
  1119. Log::info('RegenerateGradingPdf: 开始重新生成判卷PDF', ['paper_id' => $paper_id]);
  1120. if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
  1121. return response()->json([
  1122. 'success' => false,
  1123. 'message' => '无效的试卷ID格式',
  1124. 'paper_id' => $paper_id,
  1125. ], 400);
  1126. }
  1127. if (! PaperIdGenerator::validatePaperId((string) $paper_id)) {
  1128. Log::warning('RegenerateGradingPdf: 非标准15位 paper_id', ['paper_id' => $paper_id]);
  1129. }
  1130. try {
  1131. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1132. $pdfUrl = $pdfService->generateGradingPdf($paper_id);
  1133. if ($pdfUrl) {
  1134. return response()->json([
  1135. 'success' => true,
  1136. 'message' => '判卷PDF重新生成成功',
  1137. 'paper_id' => $paper_id,
  1138. 'pdf_url' => $pdfUrl,
  1139. ]);
  1140. }
  1141. return response()->json([
  1142. 'success' => false,
  1143. 'message' => '判卷PDF生成失败',
  1144. 'paper_id' => $paper_id,
  1145. ], 500);
  1146. } catch (\Exception $e) {
  1147. Log::error('RegenerateGradingPdf: 异常错误', [
  1148. 'paper_id' => $paper_id,
  1149. 'error' => $e->getMessage(),
  1150. ]);
  1151. return response()->json([
  1152. 'success' => false,
  1153. 'message' => 'PDF生成异常:'.$e->getMessage(),
  1154. 'paper_id' => $paper_id,
  1155. ], 500);
  1156. }
  1157. }
  1158. /**
  1159. * 批量重新生成 PDF:按时间区间遍历 completed_at=NULL 的卷子,投递到队列异步处理
  1160. *
  1161. * 基于 /api/papers/{paper_id}/regenerate 逻辑,将符合条件的试卷投递到 pdf 队列。
  1162. * 时间格式 Y-m-d,start_date 从 00:00:00,end_date 到 23:59:59。
  1163. * 接口立即返回,实际生成由 queue worker 处理。
  1164. *
  1165. * @return \Illuminate\Http\JsonResponse
  1166. */
  1167. public function regeneratePdfBatch(Request $request)
  1168. {
  1169. $startDate = $request->input('start_date');
  1170. $endDate = $request->input('end_date');
  1171. $datePattern = '/^\d{4}-\d{2}-\d{2}$/';
  1172. if (empty($startDate) || ! preg_match($datePattern, $startDate)) {
  1173. return response()->json([
  1174. 'success' => false,
  1175. 'message' => '参数 start_date 必填,格式 Y-m-d(如 2026-03-20)',
  1176. ], 400);
  1177. }
  1178. if (empty($endDate) || ! preg_match($datePattern, $endDate)) {
  1179. return response()->json([
  1180. 'success' => false,
  1181. 'message' => '参数 end_date 必填,格式 Y-m-d(如 2026-03-22)',
  1182. ], 400);
  1183. }
  1184. if ($startDate > $endDate) {
  1185. return response()->json([
  1186. 'success' => false,
  1187. 'message' => 'start_date 不能大于 end_date',
  1188. ], 400);
  1189. }
  1190. $startTime = $startDate.' 00:00:00';
  1191. $endTime = $endDate.' 23:59:59';
  1192. Log::info('RegeneratePdfBatch: 投递队列', [
  1193. 'start_date' => $startDate,
  1194. 'end_date' => $endDate,
  1195. ]);
  1196. try {
  1197. $papers = Paper::with('questions')
  1198. ->whereBetween('created_at', [$startTime, $endTime])
  1199. ->whereNull('completed_at')
  1200. ->orderBy('paper_id')
  1201. ->get();
  1202. if ($papers->isEmpty()) {
  1203. return response()->json([
  1204. 'success' => true,
  1205. 'message' => '未找到符合条件的试卷',
  1206. 'start_date' => $startDate,
  1207. 'end_date' => $endDate,
  1208. 'queued' => 0,
  1209. 'skipped' => 0,
  1210. 'paper_ids' => [],
  1211. ]);
  1212. }
  1213. $queued = [];
  1214. $skipped = 0;
  1215. foreach ($papers as $paper) {
  1216. if ($paper->questions->isEmpty()) {
  1217. $skipped++;
  1218. continue;
  1219. }
  1220. RegeneratePdfJob::dispatch($paper->paper_id);
  1221. $queued[] = $paper->paper_id;
  1222. }
  1223. Log::info('RegeneratePdfBatch: 已投递', [
  1224. 'start_date' => $startDate,
  1225. 'end_date' => $endDate,
  1226. 'queued' => count($queued),
  1227. 'skipped' => $skipped,
  1228. ]);
  1229. return response()->json([
  1230. 'success' => true,
  1231. 'message' => '已投递到 pdf 队列,请确保 queue worker 正在运行',
  1232. 'start_date' => $startDate,
  1233. 'end_date' => $endDate,
  1234. 'queued' => count($queued),
  1235. 'skipped' => $skipped,
  1236. 'paper_ids' => $queued,
  1237. ]);
  1238. } catch (\Exception $e) {
  1239. Log::error('RegeneratePdfBatch: 批量异常', ['error' => $e->getMessage()]);
  1240. return response()->json([
  1241. 'success' => false,
  1242. 'message' => '批量投递异常:'.$e->getMessage(),
  1243. ], 500);
  1244. }
  1245. }
  1246. /**
  1247. * 按卷子 ID 数组批量重新生成 PDF,投递到队列异步处理
  1248. *
  1249. * @return \Illuminate\Http\JsonResponse
  1250. */
  1251. public function regeneratePdfBatchByIds(Request $request)
  1252. {
  1253. $paperIds = $request->input('paper_ids');
  1254. if (empty($paperIds) || ! is_array($paperIds)) {
  1255. return response()->json([
  1256. 'success' => false,
  1257. 'message' => '参数 paper_ids 必填,且为数组(如 ["paper_123","paper_456"])',
  1258. ], 400);
  1259. }
  1260. $paperIds = array_values(array_unique(array_filter(array_map('trim', $paperIds))));
  1261. $validPattern = '/^paper_\d+$/';
  1262. $invalid = array_filter($paperIds, fn ($id) => ! preg_match($validPattern, $id));
  1263. if (! empty($invalid)) {
  1264. return response()->json([
  1265. 'success' => false,
  1266. 'message' => 'paper_ids 格式错误,需为 paper_ 开头的数字',
  1267. 'invalid' => array_values($invalid),
  1268. ], 400);
  1269. }
  1270. Log::info('RegeneratePdfBatchByIds: 投递队列', ['paper_ids' => $paperIds, 'count' => count($paperIds)]);
  1271. try {
  1272. $papers = Paper::with('questions')
  1273. ->whereIn('paper_id', $paperIds)
  1274. ->get()
  1275. ->keyBy('paper_id');
  1276. $queued = [];
  1277. $skipped = 0;
  1278. foreach ($paperIds as $paperId) {
  1279. $paper = $papers->get($paperId);
  1280. if (! $paper || $paper->questions->isEmpty()) {
  1281. $skipped++;
  1282. continue;
  1283. }
  1284. RegeneratePdfJob::dispatch($paperId);
  1285. $queued[] = $paperId;
  1286. }
  1287. Log::info('RegeneratePdfBatchByIds: 已投递', [
  1288. 'queued' => count($queued),
  1289. 'skipped' => $skipped,
  1290. ]);
  1291. return response()->json([
  1292. 'success' => true,
  1293. 'message' => '已投递到 pdf 队列,请确保 queue worker 正在运行',
  1294. 'queued' => count($queued),
  1295. 'skipped' => $skipped,
  1296. 'paper_ids' => $queued,
  1297. ]);
  1298. } catch (\Exception $e) {
  1299. Log::error('RegeneratePdfBatchByIds: 批量异常', ['error' => $e->getMessage()]);
  1300. return response()->json([
  1301. 'success' => false,
  1302. 'message' => '批量投递异常:'.$e->getMessage(),
  1303. ], 500);
  1304. }
  1305. }
  1306. }