ExamPdfController.php 70 KB

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