ExamPdfController.php 61 KB

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