ExamPdfController.php 64 KB

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