ExamPdfController.php 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Jobs\RegeneratePdfJob;
  4. use App\Models\Paper;
  5. use App\Support\PaperNaming;
  6. use App\Services\QuestionBankService;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\Cache;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Schema;
  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. /**
  445. * questions_tem 待入库预览:转为与组卷/判卷页相同的 questionsData 形状(不经题库 API)
  446. *
  447. * @param array<int, object|array> $temRows
  448. * @return array<int, array<string, mixed>>
  449. */
  450. public function prepareQuestionsDataFromTemRows(array $temRows): array
  451. {
  452. $questionsData = [];
  453. foreach ($temRows as $index => $row) {
  454. $arr = is_array($row) ? $row : (array) $row;
  455. $rawContent = (string) ($arr['stem'] ?? $arr['content'] ?? '');
  456. $decodedOptions = null;
  457. if (isset($arr['options']) && $arr['options'] !== null && $arr['options'] !== '') {
  458. if (is_string($arr['options'])) {
  459. $decoded = json_decode($arr['options'], true);
  460. $decodedOptions = is_array($decoded) ? $decoded : null;
  461. } elseif (is_array($arr['options'])) {
  462. $decodedOptions = $arr['options'];
  463. }
  464. }
  465. $apiOptions = null;
  466. if (! empty($decodedOptions)) {
  467. $apiOptions = $this->normalizeOptions($decodedOptions);
  468. }
  469. $questionsData[] = [
  470. 'id' => isset($arr['id']) ? -abs((int) $arr['id']) : null,
  471. 'question_number' => $index + 1,
  472. 'stem' => $rawContent,
  473. 'content' => $rawContent,
  474. 'answer' => (string) ($arr['answer'] ?? $arr['correct_answer'] ?? ''),
  475. 'solution' => (string) ($arr['solution'] ?? ''),
  476. 'difficulty' => isset($arr['difficulty']) ? (float) $arr['difficulty'] : 0.5,
  477. 'kp_code' => (string) ($arr['kp_code'] ?? ''),
  478. 'tags' => is_string($arr['tags'] ?? null) ? $arr['tags'] : '',
  479. 'question_type' => $arr['question_type'] ?? $arr['tags'] ?? '',
  480. 'options' => $apiOptions,
  481. 'score' => 5,
  482. ];
  483. }
  484. return $questionsData;
  485. }
  486. /**
  487. * paper_questions 中 question_bank_id 为负数(待入库 tem)时,从 questions_tem 还原完整题干与选项,避免判卷页只有 stem、无选项。
  488. *
  489. * @param array<int, array<string, mixed>> $questionsData
  490. * @return array<int, array<string, mixed>>
  491. */
  492. private function hydratePaperQuestionsDataFromQuestionsTem(array $questionsData): array
  493. {
  494. if (! Schema::hasTable('questions_tem')) {
  495. return $questionsData;
  496. }
  497. $out = [];
  498. foreach ($questionsData as $q) {
  499. $bid = (int) ($q['id'] ?? 0);
  500. if ($bid >= 0) {
  501. $out[] = $q;
  502. continue;
  503. }
  504. $temId = abs($bid);
  505. $temRow = DB::table('questions_tem')->where('id', $temId)->first();
  506. if ($temRow) {
  507. $merged = $this->prepareQuestionsDataFromTemRows([(array) $temRow])[0];
  508. $merged['question_number'] = $q['question_number'] ?? $merged['question_number'];
  509. if (! empty($q['question_type'])) {
  510. $merged['question_type'] = $q['question_type'];
  511. }
  512. if (isset($q['score'])) {
  513. $merged['score'] = $q['score'];
  514. }
  515. $out[] = $merged;
  516. } else {
  517. $out[] = $q;
  518. }
  519. }
  520. return $out;
  521. }
  522. /**
  523. * 与 show()/showGrading() 中题型分类、MathFormulaProcessor 处理完全一致
  524. *
  525. * @param array<int, array<string, mixed>> $questionsData
  526. * @return array{choice: array<int, object>, fill: array<int, object>, answer: array<int, object>}
  527. */
  528. public function buildGroupedQuestionsForPaperBody(array $questionsData, ?string $paperIdForLog = null): array
  529. {
  530. $questions = ['choice' => [], 'fill' => [], 'answer' => []];
  531. foreach ($questionsData as $q) {
  532. $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
  533. [$content, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  534. $options = $q['options'] ?? $extractedOptions;
  535. $answer = $q['answer'] ?? '';
  536. $solution = $q['solution'] ?? '';
  537. $type = isset($q['question_type'])
  538. ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
  539. : $this->determineQuestionType($q);
  540. if ($paperIdForLog !== null) {
  541. Log::debug('题目类型判断', [
  542. 'paper_id' => $paperIdForLog,
  543. 'question_id' => $q['id'] ?? '',
  544. 'has_question_type' => isset($q['question_type']),
  545. 'question_type_value' => $q['question_type'] ?? null,
  546. 'tags' => $q['tags'] ?? '',
  547. 'stem_length' => mb_strlen($content),
  548. 'stem_preview' => mb_substr($content, 0, 100),
  549. 'has_extracted_options' => ! empty($extractedOptions),
  550. 'extracted_options_count' => count($extractedOptions),
  551. 'has_api_options' => isset($q['options']) && ! empty($q['options']),
  552. 'api_options_count' => isset($q['options']) ? count($q['options']) : 0,
  553. 'final_options_count' => count($options),
  554. 'determined_type' => $type,
  555. ]);
  556. }
  557. if (! isset($questions[$type])) {
  558. $type = 'answer';
  559. }
  560. $questionData = [
  561. 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
  562. 'question_number' => $q['question_number'] ?? null,
  563. 'content' => $content,
  564. 'stem' => $content,
  565. 'answer' => $answer,
  566. 'solution' => $solution,
  567. 'difficulty' => $q['difficulty'] ?? 0.5,
  568. 'kp_code' => $q['kp_code'] ?? '',
  569. 'tags' => $q['tags'] ?? '',
  570. 'options' => $options,
  571. 'score' => $q['score'] ?? $this->getQuestionScore($type),
  572. 'question_type' => $type,
  573. ];
  574. $questionData = \App\Services\MathFormulaProcessor::processQuestionData($questionData);
  575. $questionData['math_processed'] = true;
  576. $questions[$type][] = (object) $questionData;
  577. }
  578. foreach (['choice', 'fill', 'answer'] as $type) {
  579. if (! empty($questions[$type])) {
  580. usort($questions[$type], function ($a, $b) {
  581. $aNum = $a->question_number ?? 0;
  582. $bNum = $b->question_number ?? 0;
  583. return $aNum <=> $bNum;
  584. });
  585. }
  586. }
  587. return $questions;
  588. }
  589. public function show(Request $request, $paper_id)
  590. {
  591. // 获取是否显示答案的参数,默认为true
  592. $includeAnswer = $request->query('answer', 'true') !== 'false';
  593. // 使用 Eloquent 模型获取试卷数据
  594. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  595. if (! $paper) {
  596. // 尝试从缓存中获取生成的试卷数据(用于 demo 试卷)
  597. $cached = Cache::get('generated_exam_'.$paper_id);
  598. if ($cached) {
  599. Log::info('从缓存获取试卷数据', [
  600. 'paper_id' => $paper_id,
  601. 'cached_count' => count($cached['questions'] ?? []),
  602. 'cached_question_types' => array_column($cached['questions'] ?? [], 'question_type'),
  603. ]);
  604. // 构造临时 Paper 对象
  605. $paper = (object) [
  606. 'paper_id' => $paper_id,
  607. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  608. 'student_id' => $cached['student_id'] ?? null,
  609. 'teacher_id' => $cached['teacher_id'] ?? null,
  610. 'paper_type' => $cached['assemble_type'] ?? null,
  611. ];
  612. // 对于 demo 试卷,需要检查题目数量并限制为用户要求的数量
  613. $questionsData = $cached['questions'] ?? [];
  614. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  615. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  616. $questionsData = $this->hydratePaperQuestionsDataFromQuestionsTem($questionsData);
  617. // 为 demo 试卷获取完整的题目详情(包括选项)
  618. if (! empty($questionsData)) {
  619. $questionBankService = app(QuestionBankService::class);
  620. $questionIds = array_values(array_filter(
  621. array_column($questionsData, 'id'),
  622. static fn ($id) => (int) $id > 0
  623. ));
  624. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  625. $responseData = $questionsResponse['data'] ?? [];
  626. if (! empty($responseData)) {
  627. $responseDataMap = [];
  628. foreach ($responseData as $respQ) {
  629. $responseDataMap[$respQ['id']] = $respQ;
  630. }
  631. // 合并题库数据
  632. $questionsData = array_map(function ($q) use ($responseDataMap) {
  633. if (isset($responseDataMap[$q['id']])) {
  634. $apiData = $responseDataMap[$q['id']];
  635. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  636. // 分离题干和选项
  637. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  638. $q['stem'] = $stem;
  639. $q['content'] = $stem; // 同时设置content字段
  640. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  641. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  642. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  643. // 优先使用API选项,支持多种数据格式
  644. $apiOptions = $apiData['options'] ?? null;
  645. if (! empty($apiOptions)) {
  646. // 标准化options格式为数组值列表
  647. $q['options'] = $this->normalizeOptions($apiOptions);
  648. Log::debug('使用标准化API options', [
  649. 'question_id' => $q['id'],
  650. 'raw_options' => $apiOptions,
  651. 'normalized_options' => $q['options'],
  652. ]);
  653. } else {
  654. // 备选:从题干中提取的选项
  655. $q['options'] = $extractedOptions;
  656. Log::debug('使用提取的options', [
  657. 'question_id' => $q['id'],
  658. 'extracted_options' => $extractedOptions,
  659. ]);
  660. }
  661. }
  662. return $q;
  663. }, $questionsData);
  664. }
  665. }
  666. if (count($questionsData) > $totalQuestions) {
  667. Log::info('PDF预览时发现题目过多,进行筛选', [
  668. 'paper_id' => $paper_id,
  669. 'cached_count' => count($questionsData),
  670. 'required_count' => $totalQuestions,
  671. ]);
  672. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  673. Log::info('筛选后题目数据', [
  674. 'paper_id' => $paper_id,
  675. 'filtered_count' => count($questionsData),
  676. 'filtered_types' => array_column($questionsData, 'question_type'),
  677. ]);
  678. }
  679. } else {
  680. abort(404, '试卷未找到');
  681. }
  682. } else {
  683. // 获取试卷题目
  684. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  685. ->orderBy('question_number')
  686. ->get();
  687. Log::info('从数据库获取题目', [
  688. 'paper_id' => $paper_id,
  689. 'question_count' => $paperQuestions->count(),
  690. ]);
  691. // 将 paper_questions 表的数据转换为题库格式
  692. $questionsData = [];
  693. foreach ($paperQuestions as $pq) {
  694. $questionsData[] = [
  695. 'id' => $pq->question_bank_id,
  696. 'question_number' => $pq->question_number, // 【关键】保留题目序号,用于排序
  697. 'kp_code' => $pq->knowledge_point,
  698. 'question_type' => $pq->question_type ?? 'answer', // 包含题目类型
  699. 'stem' => $pq->question_text ?? '题目内容缺失', // 如果有存储题目文本
  700. 'solution' => $pq->solution ?? '', // 保存解题思路!
  701. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  702. 'difficulty' => $pq->difficulty ?? 0.5,
  703. 'score' => $pq->score ?? 5, // 包含已计算的分值
  704. 'tags' => '',
  705. 'content' => $pq->question_text ?? '',
  706. ];
  707. }
  708. $questionsData = $this->hydratePaperQuestionsDataFromQuestionsTem($questionsData);
  709. Log::debug('paper_questions 获取题目', [
  710. 'paper_id' => $paper_id,
  711. 'question_count' => count($questionsData),
  712. ]);
  713. // 如果需要完整题目详情(stem等),可以从题库获取
  714. // 但要严格限制只获取这8道题
  715. if (! empty($questionsData)) {
  716. $questionBankService = app(QuestionBankService::class);
  717. $questionIds = array_values(array_filter(
  718. array_column($questionsData, 'id'),
  719. static fn ($id) => (int) $id > 0
  720. ));
  721. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  722. $responseData = $questionsResponse['data'] ?? [];
  723. // 确保只返回请求的ID对应的题目,并保留数据库中的 question_type
  724. if (! empty($responseData)) {
  725. // 创建题库返回数据的映射
  726. $responseDataMap = [];
  727. foreach ($responseData as $respQ) {
  728. $responseDataMap[$respQ['id']] = $respQ;
  729. }
  730. // 遍历所有数据库中的题目,合并题库返回的数据
  731. $questionsData = array_map(function ($q) use ($responseDataMap, $paperQuestions) {
  732. // 从题库API获取的详细数据(如果有)
  733. if (isset($responseDataMap[$q['id']])) {
  734. $apiData = $responseDataMap[$q['id']];
  735. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  736. // 分离题干和选项
  737. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  738. // 合并数据,优先使用题库API的 stem、answer、solution、options
  739. $q['stem'] = $stem;
  740. $q['content'] = $stem; // 同时设置content字段
  741. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  742. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  743. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  744. // 优先使用API选项,支持多种数据格式
  745. $apiOptions = $apiData['options'] ?? null;
  746. if (! empty($apiOptions)) {
  747. // 标准化options格式为数组值列表
  748. $q['options'] = $this->normalizeOptions($apiOptions);
  749. Log::debug('使用标准化API options', [
  750. 'question_id' => $q['id'],
  751. 'raw_options' => $apiOptions,
  752. 'normalized_options' => $q['options'],
  753. ]);
  754. } else {
  755. // 备选:从题干中提取的选项
  756. $q['options'] = $extractedOptions;
  757. Log::debug('使用提取的options', [
  758. 'question_id' => $q['id'],
  759. 'extracted_options' => $extractedOptions,
  760. ]);
  761. }
  762. }
  763. // 从数据库 paper_questions 表中获取 question_type(已在前面设置,这里确保有值)
  764. if (! isset($q['question_type']) || empty($q['question_type'])) {
  765. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  766. if ($dbQuestion && $dbQuestion->question_type) {
  767. $q['question_type'] = $dbQuestion->question_type;
  768. }
  769. }
  770. return $q;
  771. }, $questionsData);
  772. }
  773. }
  774. }
  775. $questions = $this->buildGroupedQuestionsForPaperBody($questionsData, (string) $paper_id);
  776. // 调试:记录最终分类结果
  777. Log::info('最终分类结果', [
  778. 'paper_id' => $paper_id,
  779. 'choice_count' => count($questions['choice']),
  780. 'fill_count' => count($questions['fill']),
  781. 'answer_count' => count($questions['answer']),
  782. 'total' => count($questions['choice']) + count($questions['fill']) + count($questions['answer']),
  783. ]);
  784. // 渲染视图
  785. $viewName = $includeAnswer ? 'pdf.exam-grading' : 'pdf.exam-paper';
  786. $studentInfo = $this->getStudentInfo($paper->student_id);
  787. $teacherInfo = $this->getTeacherInfo($paper->teacher_id);
  788. $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
  789. return view($viewName, [
  790. 'paper' => $paper,
  791. 'questions' => $questions,
  792. 'student' => $studentInfo,
  793. 'teacher' => $teacherInfo,
  794. 'includeAnswer' => $includeAnswer,
  795. 'pdfMeta' => $pdfMeta,
  796. ]);
  797. }
  798. /**
  799. * 判卷视图:题目前带方框,题后附"正确答案+解题思路"
  800. */
  801. public function showGrading(Request $request, $paper_id)
  802. {
  803. // 复用现有逻辑获取题目分类
  804. $includeAnswer = true;
  805. // 直接调用 show 的前置逻辑(简化复用)
  806. $request->merge(['answer' => 'true']);
  807. // 复用 show() 内逻辑获取 questions/paper
  808. // 为避免重复代码,简单调用 showData 方法(拆分为私有方法?暂直接重用现有方法流程)
  809. // 这里直接复制 show 的主体以保持兼容
  810. // 使用 Eloquent 模型获取试卷数据
  811. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  812. if (! $paper) {
  813. $cached = Cache::get('generated_exam_'.$paper_id);
  814. if (! $cached) {
  815. abort(404, '试卷未找到');
  816. }
  817. $paper = (object) [
  818. 'paper_id' => $paper_id,
  819. 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
  820. 'student_id' => $cached['student_id'] ?? null,
  821. 'teacher_id' => $cached['teacher_id'] ?? null,
  822. 'paper_type' => $cached['assemble_type'] ?? null,
  823. ];
  824. $questionsData = $cached['questions'] ?? [];
  825. $totalQuestions = $cached['total_questions'] ?? count($questionsData);
  826. $difficultyCategory = $cached['difficulty_category'] ?? '中等';
  827. $questionsData = $this->hydratePaperQuestionsDataFromQuestionsTem($questionsData);
  828. if (! empty($questionsData)) {
  829. $questionBankService = app(QuestionBankService::class);
  830. $questionIds = array_values(array_filter(
  831. array_column($questionsData, 'id'),
  832. static fn ($id) => (int) $id > 0
  833. ));
  834. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  835. $responseData = $questionsResponse['data'] ?? [];
  836. if (! empty($responseData)) {
  837. $responseDataMap = [];
  838. foreach ($responseData as $respQ) {
  839. $responseDataMap[$respQ['id']] = $respQ;
  840. }
  841. $questionsData = array_map(function ($q) use ($responseDataMap) {
  842. if (isset($responseDataMap[$q['id']])) {
  843. $apiData = $responseDataMap[$q['id']];
  844. $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
  845. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  846. $q['stem'] = $stem;
  847. $q['content'] = $stem; // 同时设置content字段
  848. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  849. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  850. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  851. // 优先使用API选项,支持多种数据格式
  852. $apiOptions = $apiData['options'] ?? null;
  853. if (! empty($apiOptions)) {
  854. // 标准化options格式为数组值列表
  855. $q['options'] = $this->normalizeOptions($apiOptions);
  856. Log::debug('使用标准化API options', [
  857. 'question_id' => $q['id'],
  858. 'raw_options' => $apiOptions,
  859. 'normalized_options' => $q['options'],
  860. ]);
  861. } else {
  862. // 备选:从题干中提取的选项
  863. $q['options'] = $extractedOptions;
  864. Log::debug('使用提取的options', [
  865. 'question_id' => $q['id'],
  866. 'extracted_options' => $extractedOptions,
  867. ]);
  868. }
  869. }
  870. return $q;
  871. }, $questionsData);
  872. }
  873. }
  874. if (count($questionsData) > $totalQuestions) {
  875. $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
  876. }
  877. } else {
  878. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
  879. ->orderBy('question_number')
  880. ->get();
  881. $questionsData = [];
  882. foreach ($paperQuestions as $pq) {
  883. $questionsData[] = [
  884. 'id' => $pq->question_bank_id,
  885. 'question_number' => $pq->question_number, // 【关键】保留题目序号
  886. 'kp_code' => $pq->knowledge_point,
  887. 'question_type' => $pq->question_type ?? 'answer',
  888. 'stem' => $pq->question_text ?? '题目内容缺失',
  889. 'solution' => $pq->solution ?? '', // 保存解题思路!
  890. 'answer' => $pq->correct_answer ?? '', // 保存正确答案
  891. 'difficulty' => $pq->difficulty ?? 0.5,
  892. 'score' => $pq->score ?? 5,
  893. 'tags' => '',
  894. 'content' => $pq->question_text ?? '',
  895. ];
  896. }
  897. $questionsData = $this->hydratePaperQuestionsDataFromQuestionsTem($questionsData);
  898. if (! empty($questionsData)) {
  899. $questionBankService = app(QuestionBankService::class);
  900. $questionIds = array_values(array_filter(
  901. array_column($questionsData, 'id'),
  902. static fn ($id) => (int) $id > 0
  903. ));
  904. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  905. $responseData = $questionsResponse['data'] ?? [];
  906. if (! empty($responseData)) {
  907. $responseDataMap = [];
  908. foreach ($responseData as $respQ) {
  909. $responseDataMap[$respQ['id']] = $respQ;
  910. }
  911. $questionsData = array_map(function ($q) use ($responseDataMap, $paperQuestions) {
  912. if (isset($responseDataMap[$q['id']])) {
  913. $apiData = $responseDataMap[$q['id']];
  914. $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
  915. [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
  916. $q['stem'] = $stem;
  917. $q['content'] = $stem; // 同时设置content字段
  918. $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
  919. $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
  920. $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
  921. // 优先使用API选项,支持多种数据格式
  922. $apiOptions = $apiData['options'] ?? null;
  923. if (! empty($apiOptions)) {
  924. // 标准化options格式为数组值列表
  925. $q['options'] = $this->normalizeOptions($apiOptions);
  926. Log::debug('使用标准化API options', [
  927. 'question_id' => $q['id'],
  928. 'raw_options' => $apiOptions,
  929. 'normalized_options' => $q['options'],
  930. ]);
  931. } else {
  932. // 备选:从题干中提取的选项
  933. $q['options'] = $extractedOptions;
  934. Log::debug('使用提取的options', [
  935. 'question_id' => $q['id'],
  936. 'extracted_options' => $extractedOptions,
  937. ]);
  938. }
  939. }
  940. if (! isset($q['question_type']) || empty($q['question_type'])) {
  941. $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
  942. if ($dbQuestion && $dbQuestion->question_type) {
  943. $q['question_type'] = $dbQuestion->question_type;
  944. }
  945. }
  946. return $q;
  947. }, $questionsData);
  948. }
  949. }
  950. }
  951. $questions = $this->buildGroupedQuestionsForPaperBody($questionsData, (string) $paper_id);
  952. $studentInfo = $this->getStudentInfo($paper->student_id);
  953. $teacherInfo = $this->getTeacherInfo($paper->teacher_id);
  954. $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
  955. $appendScanSheet = config('exam.pdf_grading_append_scan_sheet', false);
  956. $gradingView = $appendScanSheet ? 'pdf.exam-answer-detail' : 'pdf.exam-grading';
  957. return view($gradingView, [
  958. 'paper' => $paper,
  959. 'questions' => $questions,
  960. 'student' => $studentInfo,
  961. 'teacher' => $teacherInfo,
  962. 'includeAnswer' => true,
  963. 'pdfMeta' => $pdfMeta,
  964. ]);
  965. }
  966. /**
  967. * 知识点讲解视图
  968. */
  969. public function showKnowledgeExplanation(Request $request, $paper_id)
  970. {
  971. // 获取试卷数据
  972. $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
  973. if (! $paper) {
  974. abort(404, '试卷未找到');
  975. }
  976. $studentInfo = $this->getStudentInfo($paper->student_id);
  977. $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
  978. $studentName = $pdfMeta['student_name'];
  979. // 生成时间(格式:2026年01月30日 15:04:05)
  980. $generateDateTime = now()->format('Y年m月d日 H:i:s');
  981. // 优先使用 paper 中保存的 explanation_kp_codes(组卷时指定的知识点,最多2个)
  982. $kpCodes = $paper->explanation_kp_codes ?? [];
  983. // 如果没有保存 explanation_kp_codes,回退到从题目中提取(兼容旧数据)
  984. if (empty($kpCodes)) {
  985. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)->get();
  986. $seen = [];
  987. $questionBankIds = $paperQuestions
  988. ->pluck('question_bank_id')
  989. ->filter()
  990. ->unique()
  991. ->values();
  992. $questionKpMap = [];
  993. if ($questionBankIds->isNotEmpty()) {
  994. $questionKpMap = \App\Models\Question::whereIn('id', $questionBankIds)
  995. ->pluck('kp_code', 'id')
  996. ->toArray();
  997. }
  998. foreach ($paperQuestions as $pq) {
  999. $kpCode = trim((string) ($pq->knowledge_point ?? ''));
  1000. if ($kpCode === '' && ! empty($pq->question_bank_id)) {
  1001. $kpCode = trim((string) ($questionKpMap[$pq->question_bank_id] ?? ''));
  1002. }
  1003. if ($kpCode === '') {
  1004. continue;
  1005. }
  1006. if (isset($seen[$kpCode])) {
  1007. continue;
  1008. }
  1009. $seen[$kpCode] = true;
  1010. $kpCodes[] = $kpCode;
  1011. }
  1012. }
  1013. // 使用 ExamPdfExportService 构建知识点数据
  1014. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1015. // 批量获取知识点讲解
  1016. $knowledgePoints = $pdfService->buildExplanations($kpCodes);
  1017. return view('pdf.exam-knowledge-explanation', [
  1018. 'paperId' => $paper_id,
  1019. 'examCode' => $pdfMeta['exam_code'],
  1020. 'studentName' => $studentName,
  1021. 'generateDateTime' => $generateDateTime,
  1022. 'knowledgePoints' => $knowledgePoints,
  1023. 'pdfMeta' => $pdfMeta,
  1024. ]);
  1025. }
  1026. /**
  1027. * 服务端渲染预览 - 试卷(与 PDF 生成效果一致,用于调试)
  1028. */
  1029. public function showServerRendered(Request $request, $paper_id)
  1030. {
  1031. // 强制不显示答案(试卷模式)
  1032. $request->merge(['answer' => 'false']);
  1033. // 复用 show() 获取 HTML
  1034. $view = $this->show($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. public function showGradingServerRendered(Request $request, $paper_id)
  1045. {
  1046. // 复用 showGrading() 获取 HTML
  1047. $view = $this->showGrading($request, $paper_id);
  1048. $html = $view->render();
  1049. // 使用 KatexRenderer 服务端渲染公式
  1050. $katexRenderer = new \App\Services\KatexRenderer();
  1051. $rendered = $katexRenderer->disableCache()->renderHtml($html);
  1052. return response($rendered);
  1053. }
  1054. /**
  1055. * 重新生成 PDF(统一生成卷子和判卷)
  1056. *
  1057. * @param string $paper_id
  1058. * @return \Illuminate\Http\JsonResponse
  1059. */
  1060. public function regeneratePdf(Request $request, $paper_id)
  1061. {
  1062. Log::info('RegeneratePdf: 开始重新生成PDF', ['paper_id' => $paper_id]);
  1063. // 验证 paper_id 格式
  1064. if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
  1065. return response()->json([
  1066. 'success' => false,
  1067. 'message' => '无效的试卷ID格式',
  1068. 'paper_id' => $paper_id,
  1069. ], 400);
  1070. }
  1071. try {
  1072. // 【修复】首先检查试卷是否存在
  1073. $paperModel = Paper::with('questions')->find($paper_id);
  1074. if (! $paperModel || $paperModel->questions->isEmpty()) {
  1075. return response()->json([
  1076. 'success' => false,
  1077. 'message' => '无效的试卷',
  1078. 'paper_id' => $paper_id,
  1079. ], 400);
  1080. }
  1081. // 根据 config 或 env 配置决定是否包含知识点讲解
  1082. // 还需要判断如果摸底(paper_type =0)的时候也是不需要插入知识点讲解内容
  1083. $includeKpExplain = null;
  1084. if ($request->has('include_kp_explain')) {
  1085. $includeKpExplain = filter_var(
  1086. $request->input('include_kp_explain'),
  1087. FILTER_VALIDATE_BOOLEAN,
  1088. FILTER_NULL_ON_FAILURE
  1089. );
  1090. } elseif ($paperModel->paper_type === 0) {
  1091. $includeKpExplain = false;
  1092. }
  1093. info("includekpexplain", [$includeKpExplain]);
  1094. // 调用 PDF 生成服务
  1095. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1096. // 生成统一 PDF(卷子 + 判卷)
  1097. $pdfUrl = $pdfService->generateUnifiedPdf($paper_id, $includeKpExplain);
  1098. if ($pdfUrl) {
  1099. Log::info('RegeneratePdf: PDF重新生成成功', [
  1100. 'paper_id' => $paper_id,
  1101. 'url' => $pdfUrl,
  1102. ]);
  1103. return response()->json([
  1104. 'success' => true,
  1105. 'message' => 'PDF重新生成成功',
  1106. 'paper_id' => $paper_id,
  1107. 'pdf_url' => $pdfUrl,
  1108. ]);
  1109. }
  1110. Log::error('RegeneratePdf: PDF生成失败', ['paper_id' => $paper_id]);
  1111. return response()->json([
  1112. 'success' => false,
  1113. 'message' => 'PDF生成失败',
  1114. 'paper_id' => $paper_id,
  1115. ], 500);
  1116. } catch (\Exception $e) {
  1117. Log::error('RegeneratePdf: 异常错误', [
  1118. 'paper_id' => $paper_id,
  1119. 'error' => $e->getMessage(),
  1120. 'trace' => $e->getTraceAsString(),
  1121. ]);
  1122. return response()->json([
  1123. 'success' => false,
  1124. 'message' => 'PDF生成异常:'.$e->getMessage(),
  1125. 'paper_id' => $paper_id,
  1126. ], 500);
  1127. }
  1128. }
  1129. /**
  1130. * 重新生成试卷 PDF(不含答案)
  1131. *
  1132. * @param string $paper_id
  1133. * @return \Illuminate\Http\JsonResponse
  1134. */
  1135. public function regenerateExamPdf(Request $request, $paper_id)
  1136. {
  1137. Log::info('RegenerateExamPdf: 开始重新生成试卷PDF', ['paper_id' => $paper_id]);
  1138. if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
  1139. return response()->json([
  1140. 'success' => false,
  1141. 'message' => '无效的试卷ID格式',
  1142. 'paper_id' => $paper_id,
  1143. ], 400);
  1144. }
  1145. try {
  1146. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1147. $pdfUrl = $pdfService->generateExamPdf($paper_id);
  1148. if ($pdfUrl) {
  1149. return response()->json([
  1150. 'success' => true,
  1151. 'message' => '试卷PDF重新生成成功',
  1152. 'paper_id' => $paper_id,
  1153. 'pdf_url' => $pdfUrl,
  1154. ]);
  1155. }
  1156. return response()->json([
  1157. 'success' => false,
  1158. 'message' => '试卷PDF生成失败',
  1159. 'paper_id' => $paper_id,
  1160. ], 500);
  1161. } catch (\Exception $e) {
  1162. Log::error('RegenerateExamPdf: 异常错误', [
  1163. 'paper_id' => $paper_id,
  1164. 'error' => $e->getMessage(),
  1165. ]);
  1166. return response()->json([
  1167. 'success' => false,
  1168. 'message' => 'PDF生成异常:'.$e->getMessage(),
  1169. 'paper_id' => $paper_id,
  1170. ], 500);
  1171. }
  1172. }
  1173. /**
  1174. * 重新生成判卷 PDF(含答案)
  1175. *
  1176. * @param string $paper_id
  1177. * @return \Illuminate\Http\JsonResponse
  1178. */
  1179. public function regenerateGradingPdf(Request $request, $paper_id)
  1180. {
  1181. Log::info('RegenerateGradingPdf: 开始重新生成判卷PDF', ['paper_id' => $paper_id]);
  1182. if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
  1183. return response()->json([
  1184. 'success' => false,
  1185. 'message' => '无效的试卷ID格式',
  1186. 'paper_id' => $paper_id,
  1187. ], 400);
  1188. }
  1189. try {
  1190. $pdfService = app(\App\Services\ExamPdfExportService::class);
  1191. $pdfUrl = $pdfService->generateGradingPdf($paper_id);
  1192. if ($pdfUrl) {
  1193. return response()->json([
  1194. 'success' => true,
  1195. 'message' => '判卷PDF重新生成成功',
  1196. 'paper_id' => $paper_id,
  1197. 'pdf_url' => $pdfUrl,
  1198. ]);
  1199. }
  1200. return response()->json([
  1201. 'success' => false,
  1202. 'message' => '判卷PDF生成失败',
  1203. 'paper_id' => $paper_id,
  1204. ], 500);
  1205. } catch (\Exception $e) {
  1206. Log::error('RegenerateGradingPdf: 异常错误', [
  1207. 'paper_id' => $paper_id,
  1208. 'error' => $e->getMessage(),
  1209. ]);
  1210. return response()->json([
  1211. 'success' => false,
  1212. 'message' => 'PDF生成异常:'.$e->getMessage(),
  1213. 'paper_id' => $paper_id,
  1214. ], 500);
  1215. }
  1216. }
  1217. /**
  1218. * 批量重新生成 PDF:按时间区间遍历 completed_at=NULL 的卷子,投递到队列异步处理
  1219. *
  1220. * 基于 /api/papers/{paper_id}/regenerate 逻辑,将符合条件的试卷投递到 pdf 队列。
  1221. * 时间格式 Y-m-d,start_date 从 00:00:00,end_date 到 23:59:59。
  1222. * 接口立即返回,实际生成由 queue worker 处理。
  1223. *
  1224. * @return \Illuminate\Http\JsonResponse
  1225. */
  1226. public function regeneratePdfBatch(Request $request)
  1227. {
  1228. $startDate = $request->input('start_date');
  1229. $endDate = $request->input('end_date');
  1230. $datePattern = '/^\d{4}-\d{2}-\d{2}$/';
  1231. if (empty($startDate) || ! preg_match($datePattern, $startDate)) {
  1232. return response()->json([
  1233. 'success' => false,
  1234. 'message' => '参数 start_date 必填,格式 Y-m-d(如 2026-03-20)',
  1235. ], 400);
  1236. }
  1237. if (empty($endDate) || ! preg_match($datePattern, $endDate)) {
  1238. return response()->json([
  1239. 'success' => false,
  1240. 'message' => '参数 end_date 必填,格式 Y-m-d(如 2026-03-22)',
  1241. ], 400);
  1242. }
  1243. if ($startDate > $endDate) {
  1244. return response()->json([
  1245. 'success' => false,
  1246. 'message' => 'start_date 不能大于 end_date',
  1247. ], 400);
  1248. }
  1249. $startTime = $startDate.' 00:00:00';
  1250. $endTime = $endDate.' 23:59:59';
  1251. $includeKpExplain = $request->has('include_kp_explain')
  1252. ? filter_var($request->input('include_kp_explain'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
  1253. : null;
  1254. Log::info('RegeneratePdfBatch: 投递队列', [
  1255. 'start_date' => $startDate,
  1256. 'end_date' => $endDate,
  1257. ]);
  1258. try {
  1259. $papers = Paper::with('questions')
  1260. ->whereBetween('created_at', [$startTime, $endTime])
  1261. ->whereNull('completed_at')
  1262. ->orderBy('paper_id')
  1263. ->get();
  1264. if ($papers->isEmpty()) {
  1265. return response()->json([
  1266. 'success' => true,
  1267. 'message' => '未找到符合条件的试卷',
  1268. 'start_date' => $startDate,
  1269. 'end_date' => $endDate,
  1270. 'queued' => 0,
  1271. 'skipped' => 0,
  1272. 'paper_ids' => [],
  1273. ]);
  1274. }
  1275. $queued = [];
  1276. $skipped = 0;
  1277. foreach ($papers as $paper) {
  1278. if ($paper->questions->isEmpty()) {
  1279. $skipped++;
  1280. continue;
  1281. }
  1282. RegeneratePdfJob::dispatch($paper->paper_id, $includeKpExplain);
  1283. $queued[] = $paper->paper_id;
  1284. }
  1285. Log::info('RegeneratePdfBatch: 已投递', [
  1286. 'start_date' => $startDate,
  1287. 'end_date' => $endDate,
  1288. 'queued' => count($queued),
  1289. 'skipped' => $skipped,
  1290. ]);
  1291. return response()->json([
  1292. 'success' => true,
  1293. 'message' => '已投递到 pdf 队列,请确保 queue worker 正在运行',
  1294. 'start_date' => $startDate,
  1295. 'end_date' => $endDate,
  1296. 'queued' => count($queued),
  1297. 'skipped' => $skipped,
  1298. 'paper_ids' => $queued,
  1299. ]);
  1300. } catch (\Exception $e) {
  1301. Log::error('RegeneratePdfBatch: 批量异常', ['error' => $e->getMessage()]);
  1302. return response()->json([
  1303. 'success' => false,
  1304. 'message' => '批量投递异常:'.$e->getMessage(),
  1305. ], 500);
  1306. }
  1307. }
  1308. /**
  1309. * 按卷子 ID 数组批量重新生成 PDF,投递到队列异步处理
  1310. *
  1311. * @return \Illuminate\Http\JsonResponse
  1312. */
  1313. public function regeneratePdfBatchByIds(Request $request)
  1314. {
  1315. $paperIds = $request->input('paper_ids');
  1316. if (empty($paperIds) || ! is_array($paperIds)) {
  1317. return response()->json([
  1318. 'success' => false,
  1319. 'message' => '参数 paper_ids 必填,且为数组(如 ["paper_123","paper_456"])',
  1320. ], 400);
  1321. }
  1322. $paperIds = array_values(array_unique(array_filter(array_map('trim', $paperIds))));
  1323. $validPattern = '/^paper_\d+$/';
  1324. $invalid = array_filter($paperIds, fn ($id) => ! preg_match($validPattern, $id));
  1325. if (! empty($invalid)) {
  1326. return response()->json([
  1327. 'success' => false,
  1328. 'message' => 'paper_ids 格式错误,需为 paper_ 开头的数字',
  1329. 'invalid' => array_values($invalid),
  1330. ], 400);
  1331. }
  1332. $includeKpExplain = $request->has('include_kp_explain')
  1333. ? filter_var($request->input('include_kp_explain'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
  1334. : null;
  1335. Log::info('RegeneratePdfBatchByIds: 投递队列', ['paper_ids' => $paperIds, 'count' => count($paperIds)]);
  1336. try {
  1337. $papers = Paper::with('questions')
  1338. ->whereIn('paper_id', $paperIds)
  1339. ->get()
  1340. ->keyBy('paper_id');
  1341. $queued = [];
  1342. $skipped = 0;
  1343. foreach ($paperIds as $paperId) {
  1344. $paper = $papers->get($paperId);
  1345. if (! $paper || $paper->questions->isEmpty()) {
  1346. $skipped++;
  1347. continue;
  1348. }
  1349. RegeneratePdfJob::dispatch($paperId, $includeKpExplain);
  1350. $queued[] = $paperId;
  1351. }
  1352. Log::info('RegeneratePdfBatchByIds: 已投递', [
  1353. 'queued' => count($queued),
  1354. 'skipped' => $skipped,
  1355. ]);
  1356. return response()->json([
  1357. 'success' => true,
  1358. 'message' => '已投递到 pdf 队列,请确保 queue worker 正在运行',
  1359. 'queued' => count($queued),
  1360. 'skipped' => $skipped,
  1361. 'paper_ids' => $queued,
  1362. ]);
  1363. } catch (\Exception $e) {
  1364. Log::error('RegeneratePdfBatchByIds: 批量异常', ['error' => $e->getMessage()]);
  1365. return response()->json([
  1366. 'success' => false,
  1367. 'message' => '批量投递异常:'.$e->getMessage(),
  1368. ], 500);
  1369. }
  1370. }
  1371. }