ExamPdfController.php 62 KB

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