ExamPdfController.php 63 KB

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