| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565 |
- <?php
- namespace App\Http\Controllers;
- use App\Jobs\RegeneratePdfJob;
- use App\Models\Paper;
- use App\Support\AnswerSolutionStepMarkerInjector;
- use App\Support\PaperNaming;
- use App\Services\QuestionBankService;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Schema;
- class ExamPdfController extends Controller
- {
- /**
- * 标准化选项格式为数组值列表
- * 支持格式:
- * 1. {"A": "0", "B": "5", "C": "-3", "D": "12"} -> ["0", "5", "-3", "12"]
- * 2. [["label": "A", "text": "选项A"], ...] -> ["选项A", "选项B", ...]
- * 3. ["A", "B", "C", "D"] -> ["A", "B", "C", "D"]
- */
- private function normalizeOptions($options): array
- {
- if (empty($options)) {
- return [];
- }
- // 如果是对象格式 {"A": "值1", "B": "值2", ...}
- if (is_array($options) && ! isset($options[0])) {
- return array_values($options);
- }
- // 如果是AI生成格式 [{"label": "A", "text": "选项A"}, ...]
- if (is_array($options) && isset($options[0]) && is_array($options[0])) {
- // 提取text字段,如果不存在则使用整个数组元素
- $normalized = [];
- foreach ($options as $opt) {
- if (isset($opt['text'])) {
- $normalized[] = $opt['text'];
- } elseif (isset($opt['value'])) {
- $normalized[] = $opt['value'];
- } else {
- // 如果既没有text也没有value,取数组的第一个值
- $normalized[] = is_array($opt) ? (string) reset($opt) : (string) $opt;
- }
- }
- return $normalized;
- }
- // 如果已经是简单数组格式 ["A", "B", "C", "D"]
- if (is_array($options)) {
- return array_values($options);
- }
- // 其他情况返回空数组
- return [];
- }
- /**
- * 根据题目内容或类型字段判断题型
- */
- private function determineQuestionType(array $question): string
- {
- // 优先根据题目内容判断(而不是数据库字段)
- $stem = $question['stem'] ?? $question['content'] ?? '';
- $tags = $question['tags'] ?? '';
- $skills = $question['skills'] ?? [];
- // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
- if (is_string($stem)) {
- // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
- $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
- $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
- $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
- $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
- $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
- // 至少有2个选项就认为是选择题(降低阈值)
- $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
- if ($optionCount >= 2) {
- return 'choice';
- }
- // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
- if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
- return 'choice';
- }
- }
- // 2. 根据技能点判断
- if (is_array($skills)) {
- $skillsStr = implode(',', $skills);
- if (strpos($skillsStr, '选择题') !== false) {
- return 'choice';
- }
- if (strpos($skillsStr, '填空题') !== false) {
- return 'fill';
- }
- if (strpos($skillsStr, '解答题') !== false) {
- return 'answer';
- }
- }
- // 3. 根据题目已有类型字段判断(作为后备)
- if (! empty($question['question_type'])) {
- $type = strtolower(trim($question['question_type']));
- if (in_array($type, ['choice', '选择题', 'choice question'])) {
- return 'choice';
- }
- if (in_array($type, ['fill', '填空题', 'fill in the blank'])) {
- return 'fill';
- }
- if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) {
- return 'answer';
- }
- }
- if (! empty($question['type'])) {
- $type = strtolower(trim($question['type']));
- if (in_array($type, ['choice', '选择题', 'choice question'])) {
- return 'choice';
- }
- if (in_array($type, ['fill', '填空题', 'fill in the blank'])) {
- return 'fill';
- }
- if (in_array($type, ['answer', '解答题', 'calculation', '简答题'])) {
- return 'answer';
- }
- }
- // 4. 根据标签判断
- if (is_string($tags)) {
- if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
- return 'choice';
- }
- if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
- return 'fill';
- }
- if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
- return 'answer';
- }
- }
- // 5. 填空题特征:连续下划线或明显的填空括号
- if (is_string($stem)) {
- // 检查填空题特征:连续下划线
- if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
- return 'fill';
- }
- // 空括号填空
- if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
- return 'fill';
- }
- }
- // 6. 根据题干内容关键词判断
- if (is_string($stem)) {
- // 有证明、解答、计算、求证等关键词的是解答题
- if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
- return 'answer';
- }
- }
- // 默认是解答题(更安全的默认值)
- return 'answer';
- }
- private function normalizeQuestionTypeValue(string $type): string
- {
- $type = trim($type);
- $lower = strtolower($type);
- if (in_array($lower, ['choice', 'single_choice', 'multiple_choice'], true)) {
- return 'choice';
- }
- if (in_array($lower, ['fill', 'blank', 'fill_in_the_blank'], true)) {
- return 'fill';
- }
- if (in_array($lower, ['answer', 'calculation', 'word_problem', 'proof'], true)) {
- return 'answer';
- }
- if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
- return 'choice';
- }
- if (in_array($type, ['FILL', 'FILL_IN_THE_BLANK'], true)) {
- return 'fill';
- }
- if (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
- return 'answer';
- }
- if (in_array($type, ['选择题'], true)) {
- return 'choice';
- }
- if (in_array($type, ['填空题'], true)) {
- return 'fill';
- }
- if (in_array($type, ['解答题', '计算题'], true)) {
- return 'answer';
- }
- return $lower ?: 'answer';
- }
- /**
- * 从题目内容中提取选项
- */
- private function extractOptions(string $content): array
- {
- $options = [];
- // 【修复】先移除SVG内容,避免误匹配SVG注释中的 BD:DC、A:B 等内容
- $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
- // 1. 尝试匹配多种格式的选项:A. / A、/ A: / A.(中文句点)/ A.(无空格)
- // 【修复】选项标记必须在行首或空白后,避免误匹配 SVG 注释中的 BD:DC 等内容
- $pattern = '/(?:^|\s)([A-D])[\.、:.:]\s*(.+?)(?=(?:^|\s)[A-D][\.、:.:]|$)/su';
- if (preg_match_all($pattern, $contentWithoutSvg, $matches, PREG_SET_ORDER)) {
- foreach ($matches as $match) {
- $optionText = trim($match[2]);
- // 移除末尾的换行和空白
- $optionText = preg_replace('/\s+$/', '', $optionText);
- // 清理 LaTeX 格式但保留内容
- $optionText = preg_replace('/^\$\$\s*/', '', $optionText);
- $optionText = preg_replace('/\s*\$\$$/', '', $optionText);
- if (! empty($optionText)) {
- $options[] = $optionText;
- }
- }
- }
- // 2. 如果上面没提取到,尝试按换行分割
- if (empty($options)) {
- $lines = preg_split('/[\r\n]+/', $contentWithoutSvg);
- foreach ($lines as $line) {
- $line = trim($line);
- // 【修复】行首匹配选项标记
- if (preg_match('/^([A-D])[\.、:.:]\s*(.+)$/u', $line, $match)) {
- $optionText = trim($match[2]);
- if (! empty($optionText)) {
- $options[] = $optionText;
- }
- }
- }
- }
- Log::debug('选项提取结果', [
- 'content_preview' => mb_substr($content, 0, 150),
- 'options_count' => count($options),
- 'options' => $options,
- ]);
- return $options;
- }
- /**
- * 分离题干内容和选项
- */
- private function separateStemAndOptions(string $content): array
- {
- // 【修复】先移除SVG内容,避免误匹配SVG注释中的 BD:DC、A:B 等内容
- $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
- // 【修复】检测是否有选项时,要求选项标记在行首或空白后
- $hasOptions = preg_match('/(?:^|\s)[A-D][\.、:.:]/u', $contentWithoutSvg);
- if (! $hasOptions) {
- return [$content, []];
- }
- // 提取选项
- $options = $this->extractOptions($content);
- // 如果提取到选项,分离题干
- if (! empty($options)) {
- // 【修复】找到第一个选项的位置,要求选项标记在行首或空白后
- if (preg_match('/^(.+?)(?=(?:^|\s)[A-D][\.、:.:])/su', $contentWithoutSvg, $match)) {
- $stem = trim($match[1]);
- // 如果题干中有SVG占位符,从原始内容中提取对应部分
- if (strpos($stem, '[SVG_PLACEHOLDER]') !== false) {
- // 找到原始内容中对应位置的题干
- $stemLength = mb_strlen(str_replace('[SVG_PLACEHOLDER]', '', $stem));
- // 使用更精确的方法:找到第一个有效选项标记的位置
- foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
- // 只匹配在空白后的选项标记
- if (preg_match('/\s'.preg_quote($marker, '/').'/', $content, $m, PREG_OFFSET_CAPTURE)) {
- $pos = $m[0][1];
- if ($pos > 0) {
- $stem = trim(mb_substr($content, 0, $pos));
- break;
- }
- }
- }
- }
- } else {
- // 如果正则失败,尝试按位置分割
- $stem = $content;
- foreach (['A.', 'A、', 'A:', 'A.', 'A:'] as $marker) {
- // 【修复】只匹配在空白后的选项标记
- if (preg_match('/\s'.preg_quote($marker, '/').'/', $content, $m, PREG_OFFSET_CAPTURE)) {
- $pos = $m[0][1];
- if ($pos > 0) {
- $stem = trim(mb_substr($content, 0, $pos));
- break;
- }
- }
- }
- }
- // 移除末尾的括号或空白
- $stem = preg_replace('/()\s*$/', '', $stem);
- $stem = trim($stem);
- return [$stem, $options];
- }
- return [$content, []];
- }
- /**
- * 根据题型获取默认分数
- */
- private function getQuestionScore(string $type): int
- {
- switch ($type) {
- case 'choice':
- return 5; // 选择题5分
- case 'fill':
- return 5; // 填空题5分
- case 'answer':
- return 10; // 解答题10分
- default:
- return 5;
- }
- }
- /**
- * 获取学生信息
- */
- private function getStudentInfo(?string $studentId): array
- {
- if (! $studentId) {
- return [
- 'name' => '未知学生',
- 'grade' => '未知年级',
- 'class' => '未知班级',
- ];
- }
- try {
- $student = DB::table('students')
- ->where('student_id', $studentId)
- ->first();
- if ($student) {
- return [
- 'name' => $student->name ?? $studentId,
- 'grade' => $student->grade ?? '未知',
- 'class' => $student->class ?? '未知',
- ];
- }
- } catch (\Exception $e) {
- Log::warning('获取学生信息失败', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage(),
- ]);
- }
- return [
- 'name' => $studentId,
- 'grade' => '未知',
- 'class' => '未知',
- ];
- }
- /**
- * 为 PDF 预览筛选题目(简化版)
- */
- private function selectBestQuestionsForPdf(array $questions, int $targetCount, string $difficultyCategory): array
- {
- if (count($questions) <= $targetCount) {
- return $questions;
- }
- // 1. 按题型分类题目
- $categorizedQuestions = [
- 'choice' => [],
- 'fill' => [],
- 'answer' => [],
- ];
- foreach ($questions as $question) {
- $type = $this->determineQuestionType($question);
- if (! isset($categorizedQuestions[$type])) {
- $type = 'answer';
- }
- $categorizedQuestions[$type][] = $question;
- }
- // 2. 默认题型配比
- $typeRatio = [
- '选择题' => 50, // 50%
- '填空题' => 30, // 30%
- '解答题' => 20, // 20%
- ];
- // 3. 根据配比选择题目
- $selectedQuestions = [];
- foreach ($typeRatio as $type => $ratio) {
- $typeKey = $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer');
- $countForType = floor($targetCount * $ratio / 100);
- if ($countForType > 0 && ! empty($categorizedQuestions[$typeKey])) {
- $availableCount = count($categorizedQuestions[$typeKey]);
- $takeCount = min($countForType, $availableCount, $targetCount - count($selectedQuestions));
- // 随机选择题目
- $keys = array_keys($categorizedQuestions[$typeKey]);
- shuffle($keys);
- $selectedKeys = array_slice($keys, 0, $takeCount);
- foreach ($selectedKeys as $key) {
- $selectedQuestions[] = $categorizedQuestions[$typeKey][$key];
- }
- }
- }
- // 4. 如果数量不足,随机补充
- while (count($selectedQuestions) < $targetCount) {
- $randomQuestion = $questions[array_rand($questions)];
- if (! in_array($randomQuestion, $selectedQuestions)) {
- $selectedQuestions[] = $randomQuestion;
- }
- }
- // 5. 限制数量并打乱
- shuffle($selectedQuestions);
- return array_slice($selectedQuestions, 0, $targetCount);
- }
- /**
- * 获取教师信息
- */
- private function getTeacherInfo(?string $teacherId): array
- {
- if (! $teacherId) {
- return [
- 'name' => '未知教师',
- ];
- }
- try {
- $teacher = DB::table('teachers')
- ->where('teacher_id', $teacherId)
- ->first();
- if ($teacher) {
- return [
- 'name' => $teacher->name ?? $teacherId,
- ];
- }
- } catch (\Exception $e) {
- Log::warning('获取教师信息失败', [
- 'teacher_id' => $teacherId,
- 'error' => $e->getMessage(),
- ]);
- }
- return [
- 'name' => $teacherId,
- ];
- }
- private function buildPdfMeta(object $paper, string $fallbackPaperId, ?array $studentInfo = null): array
- {
- $rawPaperId = (string) ($paper->paper_id ?? $fallbackPaperId);
- $assembleType = isset($paper->paper_type) && $paper->paper_type !== '' && $paper->paper_type !== null
- ? (int) $paper->paper_type
- : null;
- $examCode = PaperNaming::extractExamCode($rawPaperId);
- $studentName = $studentInfo['name'] ?? ($paper->student_id ?? '________');
- try {
- $assembleTypeLabel = $assembleType !== null ? PaperNaming::assembleTypeLabel($assembleType) : '未知类型';
- } catch (\Throwable $e) {
- $assembleTypeLabel = '未知类型';
- }
- $headerTitle = $examCode;
- return [
- 'student_name' => $studentName,
- 'exam_code' => $examCode,
- 'assemble_type_label' => $assembleTypeLabel,
- 'header_title' => $headerTitle,
- 'exam_pdf_title' => "试卷_{$headerTitle}",
- 'grading_pdf_title' => "判卷_{$headerTitle}",
- 'knowledge_pdf_title' => "知识点讲解_{$headerTitle}",
- ];
- }
- /**
- * questions_tem 待入库预览:转为与组卷/判卷页相同的 questionsData 形状(不经题库 API)
- *
- * @param array<int, object|array> $temRows
- * @return array<int, array<string, mixed>>
- */
- public function prepareQuestionsDataFromTemRows(array $temRows): array
- {
- $questionsData = [];
- foreach ($temRows as $index => $row) {
- $arr = is_array($row) ? $row : (array) $row;
- $rawContent = (string) ($arr['stem'] ?? '');
- $decodedOptions = null;
- if (isset($arr['options']) && $arr['options'] !== null && $arr['options'] !== '') {
- if (is_string($arr['options'])) {
- $decoded = json_decode($arr['options'], true);
- $decodedOptions = is_array($decoded) ? $decoded : null;
- } elseif (is_array($arr['options'])) {
- $decodedOptions = $arr['options'];
- }
- }
- $apiOptions = null;
- if (! empty($decodedOptions)) {
- $apiOptions = $this->normalizeOptions($decodedOptions);
- }
- $rawSolution = (string) ($arr['solution'] ?? '');
- $solutionForPreview = AnswerSolutionStepMarkerInjector::enrichIfNeeded(
- $rawSolution,
- $arr['question_type'] ?? $arr['tags'] ?? ''
- );
- $questionsData[] = [
- 'id' => isset($arr['id']) ? -abs((int) $arr['id']) : null,
- 'question_number' => $index + 1,
- 'stem' => $rawContent,
- 'content' => $rawContent,
- 'answer' => (string) ($arr['answer'] ?? $arr['correct_answer'] ?? ''),
- 'solution' => $solutionForPreview,
- 'difficulty' => isset($arr['difficulty']) ? (float) $arr['difficulty'] : 0.5,
- 'kp_code' => (string) ($arr['kp_code'] ?? ''),
- 'tags' => is_string($arr['tags'] ?? null) ? $arr['tags'] : '',
- 'question_type' => $arr['question_type'] ?? $arr['tags'] ?? '',
- 'options' => $apiOptions,
- 'score' => 5,
- ];
- }
- return $questionsData;
- }
- /**
- * paper_questions 中 question_bank_id 为负数(待入库 tem)时,从 questions_tem 还原完整题干与选项,避免判卷页只有 stem、无选项。
- *
- * @param array<int, array<string, mixed>> $questionsData
- * @return array<int, array<string, mixed>>
- */
- private function hydratePaperQuestionsDataFromQuestionsTem(array $questionsData): array
- {
- if (! Schema::hasTable('questions_tem')) {
- return $questionsData;
- }
- $out = [];
- foreach ($questionsData as $q) {
- $bid = (int) ($q['id'] ?? 0);
- if ($bid >= 0) {
- $out[] = $q;
- continue;
- }
- $temId = abs($bid);
- $temRow = DB::table('questions_tem')->where('id', $temId)->first();
- if ($temRow) {
- $merged = $this->prepareQuestionsDataFromTemRows([(array) $temRow])[0];
- $merged['question_number'] = $q['question_number'] ?? $merged['question_number'];
- if (! empty($q['question_type'])) {
- $merged['question_type'] = $q['question_type'];
- }
- if (isset($q['score'])) {
- $merged['score'] = $q['score'];
- }
- $out[] = $merged;
- } else {
- $out[] = $q;
- }
- }
- return $out;
- }
- /**
- * 与 show()/showGrading() 中题型分类、MathFormulaProcessor 处理完全一致
- *
- * @param array<int, array<string, mixed>> $questionsData
- * @return array{choice: array<int, object>, fill: array<int, object>, answer: array<int, object>}
- */
- public function buildGroupedQuestionsForPaperBody(array $questionsData, ?string $paperIdForLog = null): array
- {
- $questions = ['choice' => [], 'fill' => [], 'answer' => []];
- foreach ($questionsData as $q) {
- $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
- [$content, $extractedOptions] = $this->separateStemAndOptions($rawContent);
- $options = $q['options'] ?? $extractedOptions;
- $answer = $q['answer'] ?? '';
- $solution = $q['solution'] ?? '';
- $type = isset($q['question_type'])
- ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
- : $this->determineQuestionType($q);
- if ($paperIdForLog !== null) {
- Log::debug('题目类型判断', [
- 'paper_id' => $paperIdForLog,
- 'question_id' => $q['id'] ?? '',
- 'has_question_type' => isset($q['question_type']),
- 'question_type_value' => $q['question_type'] ?? null,
- 'tags' => $q['tags'] ?? '',
- 'stem_length' => mb_strlen($content),
- 'stem_preview' => mb_substr($content, 0, 100),
- 'has_extracted_options' => ! empty($extractedOptions),
- 'extracted_options_count' => count($extractedOptions),
- 'has_api_options' => isset($q['options']) && ! empty($q['options']),
- 'api_options_count' => isset($q['options']) ? count($q['options']) : 0,
- 'final_options_count' => count($options),
- 'determined_type' => $type,
- ]);
- }
- if (! isset($questions[$type])) {
- $type = 'answer';
- }
- $questionData = [
- 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
- 'question_number' => $q['question_number'] ?? null,
- 'content' => $content,
- 'stem' => $content,
- 'answer' => $answer,
- 'solution' => $solution,
- 'difficulty' => $q['difficulty'] ?? 0.5,
- 'kp_code' => $q['kp_code'] ?? '',
- 'tags' => $q['tags'] ?? '',
- 'options' => $options,
- 'score' => $q['score'] ?? $this->getQuestionScore($type),
- 'question_type' => $type,
- ];
- $questionData = \App\Services\MathFormulaProcessor::processQuestionData($questionData);
- $questionData['math_processed'] = true;
- $questions[$type][] = (object) $questionData;
- }
- foreach (['choice', 'fill', 'answer'] as $type) {
- if (! empty($questions[$type])) {
- usort($questions[$type], function ($a, $b) {
- $aNum = $a->question_number ?? 0;
- $bNum = $b->question_number ?? 0;
- return $aNum <=> $bNum;
- });
- }
- }
- return $questions;
- }
- public function show(Request $request, $paper_id)
- {
- // 获取是否显示答案的参数,默认为true
- $includeAnswer = $request->query('answer', 'true') !== 'false';
- // 使用 Eloquent 模型获取试卷数据
- $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
- if (! $paper) {
- // 尝试从缓存中获取生成的试卷数据(用于 demo 试卷)
- $cached = Cache::get('generated_exam_'.$paper_id);
- if ($cached) {
- Log::info('从缓存获取试卷数据', [
- 'paper_id' => $paper_id,
- 'cached_count' => count($cached['questions'] ?? []),
- 'cached_question_types' => array_column($cached['questions'] ?? [], 'question_type'),
- ]);
- // 构造临时 Paper 对象
- $paper = (object) [
- 'paper_id' => $paper_id,
- 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
- 'student_id' => $cached['student_id'] ?? null,
- 'teacher_id' => $cached['teacher_id'] ?? null,
- 'paper_type' => $cached['assemble_type'] ?? null,
- ];
- // 对于 demo 试卷,需要检查题目数量并限制为用户要求的数量
- $questionsData = $cached['questions'] ?? [];
- $totalQuestions = $cached['total_questions'] ?? count($questionsData);
- $difficultyCategory = $cached['difficulty_category'] ?? '中等';
- $questionsData = $this->hydratePaperQuestionsDataFromQuestionsTem($questionsData);
- // 为 demo 试卷获取完整的题目详情(包括选项)
- if (! empty($questionsData)) {
- $questionBankService = app(QuestionBankService::class);
- $questionIds = array_values(array_filter(
- array_column($questionsData, 'id'),
- static fn ($id) => (int) $id > 0
- ));
- $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
- $responseData = $questionsResponse['data'] ?? [];
- if (! empty($responseData)) {
- $responseDataMap = [];
- foreach ($responseData as $respQ) {
- $responseDataMap[$respQ['id']] = $respQ;
- }
- // 合并题库数据
- $questionsData = array_map(function ($q) use ($responseDataMap) {
- if (isset($responseDataMap[$q['id']])) {
- $apiData = $responseDataMap[$q['id']];
- $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
- // 分离题干和选项
- [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
- $q['stem'] = $stem;
- $q['content'] = $stem; // 同时设置content字段
- $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
- $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
- $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
- // 优先使用API选项,支持多种数据格式
- $apiOptions = $apiData['options'] ?? null;
- if (! empty($apiOptions)) {
- // 标准化options格式为数组值列表
- $q['options'] = $this->normalizeOptions($apiOptions);
- Log::debug('使用标准化API options', [
- 'question_id' => $q['id'],
- 'raw_options' => $apiOptions,
- 'normalized_options' => $q['options'],
- ]);
- } else {
- // 备选:从题干中提取的选项
- $q['options'] = $extractedOptions;
- Log::debug('使用提取的options', [
- 'question_id' => $q['id'],
- 'extracted_options' => $extractedOptions,
- ]);
- }
- }
- return $q;
- }, $questionsData);
- }
- }
- if (count($questionsData) > $totalQuestions) {
- Log::info('PDF预览时发现题目过多,进行筛选', [
- 'paper_id' => $paper_id,
- 'cached_count' => count($questionsData),
- 'required_count' => $totalQuestions,
- ]);
- $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
- Log::info('筛选后题目数据', [
- 'paper_id' => $paper_id,
- 'filtered_count' => count($questionsData),
- 'filtered_types' => array_column($questionsData, 'question_type'),
- ]);
- }
- } else {
- abort(404, '试卷未找到');
- }
- } else {
- // 获取试卷题目
- $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
- ->orderBy('question_number')
- ->get();
- Log::info('从数据库获取题目', [
- 'paper_id' => $paper_id,
- 'question_count' => $paperQuestions->count(),
- ]);
- // 将 paper_questions 表的数据转换为题库格式
- $questionsData = [];
- foreach ($paperQuestions as $pq) {
- $questionsData[] = [
- 'id' => $pq->question_bank_id,
- 'question_number' => $pq->question_number, // 【关键】保留题目序号,用于排序
- 'kp_code' => $pq->knowledge_point,
- 'question_type' => $pq->question_type ?? 'answer', // 包含题目类型
- 'stem' => $pq->question_text ?? '题目内容缺失', // 如果有存储题目文本
- 'solution' => $pq->solution ?? '', // 保存解题思路!
- 'answer' => $pq->correct_answer ?? '', // 保存正确答案
- 'difficulty' => $pq->difficulty ?? 0.5,
- 'score' => $pq->score ?? 5, // 包含已计算的分值
- 'tags' => '',
- 'content' => $pq->question_text ?? '',
- ];
- }
- $questionsData = $this->hydratePaperQuestionsDataFromQuestionsTem($questionsData);
- Log::debug('paper_questions 获取题目', [
- 'paper_id' => $paper_id,
- 'question_count' => count($questionsData),
- ]);
- // 如果需要完整题目详情(stem等),可以从题库获取
- // 但要严格限制只获取这8道题
- if (! empty($questionsData)) {
- $questionBankService = app(QuestionBankService::class);
- $questionIds = array_values(array_filter(
- array_column($questionsData, 'id'),
- static fn ($id) => (int) $id > 0
- ));
- $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
- $responseData = $questionsResponse['data'] ?? [];
- // 确保只返回请求的ID对应的题目,并保留数据库中的 question_type
- if (! empty($responseData)) {
- // 创建题库返回数据的映射
- $responseDataMap = [];
- foreach ($responseData as $respQ) {
- $responseDataMap[$respQ['id']] = $respQ;
- }
- // 遍历所有数据库中的题目,合并题库返回的数据
- $questionsData = array_map(function ($q) use ($responseDataMap, $paperQuestions) {
- // 从题库API获取的详细数据(如果有)
- if (isset($responseDataMap[$q['id']])) {
- $apiData = $responseDataMap[$q['id']];
- $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
- // 分离题干和选项
- [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
- // 合并数据,优先使用题库API的 stem、answer、solution、options
- $q['stem'] = $stem;
- $q['content'] = $stem; // 同时设置content字段
- $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
- $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
- $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
- // 优先使用API选项,支持多种数据格式
- $apiOptions = $apiData['options'] ?? null;
- if (! empty($apiOptions)) {
- // 标准化options格式为数组值列表
- $q['options'] = $this->normalizeOptions($apiOptions);
- Log::debug('使用标准化API options', [
- 'question_id' => $q['id'],
- 'raw_options' => $apiOptions,
- 'normalized_options' => $q['options'],
- ]);
- } else {
- // 备选:从题干中提取的选项
- $q['options'] = $extractedOptions;
- Log::debug('使用提取的options', [
- 'question_id' => $q['id'],
- 'extracted_options' => $extractedOptions,
- ]);
- }
- }
- // 从数据库 paper_questions 表中获取 question_type(已在前面设置,这里确保有值)
- if (! isset($q['question_type']) || empty($q['question_type'])) {
- $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
- if ($dbQuestion && $dbQuestion->question_type) {
- $q['question_type'] = $dbQuestion->question_type;
- }
- }
- return $q;
- }, $questionsData);
- }
- }
- }
- $questions = $this->buildGroupedQuestionsForPaperBody($questionsData, (string) $paper_id);
- // 调试:记录最终分类结果
- Log::info('最终分类结果', [
- 'paper_id' => $paper_id,
- 'choice_count' => count($questions['choice']),
- 'fill_count' => count($questions['fill']),
- 'answer_count' => count($questions['answer']),
- 'total' => count($questions['choice']) + count($questions['fill']) + count($questions['answer']),
- ]);
- // 渲染视图
- $viewName = $includeAnswer ? 'pdf.exam-grading' : 'pdf.exam-paper';
- $studentInfo = $this->getStudentInfo($paper->student_id);
- $teacherInfo = $this->getTeacherInfo($paper->teacher_id);
- $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
- return view($viewName, [
- 'paper' => $paper,
- 'questions' => $questions,
- 'student' => $studentInfo,
- 'teacher' => $teacherInfo,
- 'includeAnswer' => $includeAnswer,
- 'pdfMeta' => $pdfMeta,
- ]);
- }
- /**
- * 判卷视图:题目前带方框,题后附"正确答案+解题思路"
- */
- public function showGrading(Request $request, $paper_id)
- {
- // 复用现有逻辑获取题目分类
- $includeAnswer = true;
- // 直接调用 show 的前置逻辑(简化复用)
- $request->merge(['answer' => 'true']);
- // 复用 show() 内逻辑获取 questions/paper
- // 为避免重复代码,简单调用 showData 方法(拆分为私有方法?暂直接重用现有方法流程)
- // 这里直接复制 show 的主体以保持兼容
- // 使用 Eloquent 模型获取试卷数据
- $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
- if (! $paper) {
- $cached = Cache::get('generated_exam_'.$paper_id);
- if (! $cached) {
- abort(404, '试卷未找到');
- }
- $paper = (object) [
- 'paper_id' => $paper_id,
- 'paper_name' => $cached['paper_name'] ?? 'Demo Paper',
- 'student_id' => $cached['student_id'] ?? null,
- 'teacher_id' => $cached['teacher_id'] ?? null,
- 'paper_type' => $cached['assemble_type'] ?? null,
- ];
- $questionsData = $cached['questions'] ?? [];
- $totalQuestions = $cached['total_questions'] ?? count($questionsData);
- $difficultyCategory = $cached['difficulty_category'] ?? '中等';
- $questionsData = $this->hydratePaperQuestionsDataFromQuestionsTem($questionsData);
- if (! empty($questionsData)) {
- $questionBankService = app(QuestionBankService::class);
- $questionIds = array_values(array_filter(
- array_column($questionsData, 'id'),
- static fn ($id) => (int) $id > 0
- ));
- $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
- $responseData = $questionsResponse['data'] ?? [];
- if (! empty($responseData)) {
- $responseDataMap = [];
- foreach ($responseData as $respQ) {
- $responseDataMap[$respQ['id']] = $respQ;
- }
- $questionsData = array_map(function ($q) use ($responseDataMap) {
- if (isset($responseDataMap[$q['id']])) {
- $apiData = $responseDataMap[$q['id']];
- $rawContent = $apiData['stem'] ?? $q['stem'] ?? $q['content'] ?? '';
- [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
- $q['stem'] = $stem;
- $q['content'] = $stem; // 同时设置content字段
- $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
- $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
- $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
- // 优先使用API选项,支持多种数据格式
- $apiOptions = $apiData['options'] ?? null;
- if (! empty($apiOptions)) {
- // 标准化options格式为数组值列表
- $q['options'] = $this->normalizeOptions($apiOptions);
- Log::debug('使用标准化API options', [
- 'question_id' => $q['id'],
- 'raw_options' => $apiOptions,
- 'normalized_options' => $q['options'],
- ]);
- } else {
- // 备选:从题干中提取的选项
- $q['options'] = $extractedOptions;
- Log::debug('使用提取的options', [
- 'question_id' => $q['id'],
- 'extracted_options' => $extractedOptions,
- ]);
- }
- }
- return $q;
- }, $questionsData);
- }
- }
- if (count($questionsData) > $totalQuestions) {
- $questionsData = $this->selectBestQuestionsForPdf($questionsData, $totalQuestions, $difficultyCategory);
- }
- } else {
- $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)
- ->orderBy('question_number')
- ->get();
- $questionsData = [];
- foreach ($paperQuestions as $pq) {
- $questionsData[] = [
- 'id' => $pq->question_bank_id,
- 'question_number' => $pq->question_number, // 【关键】保留题目序号
- 'kp_code' => $pq->knowledge_point,
- 'question_type' => $pq->question_type ?? 'answer',
- 'stem' => $pq->question_text ?? '题目内容缺失',
- 'solution' => $pq->solution ?? '', // 保存解题思路!
- 'answer' => $pq->correct_answer ?? '', // 保存正确答案
- 'difficulty' => $pq->difficulty ?? 0.5,
- 'score' => $pq->score ?? 5,
- 'tags' => '',
- 'content' => $pq->question_text ?? '',
- ];
- }
- $questionsData = $this->hydratePaperQuestionsDataFromQuestionsTem($questionsData);
- if (! empty($questionsData)) {
- $questionBankService = app(QuestionBankService::class);
- $questionIds = array_values(array_filter(
- array_column($questionsData, 'id'),
- static fn ($id) => (int) $id > 0
- ));
- $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
- $responseData = $questionsResponse['data'] ?? [];
- if (! empty($responseData)) {
- $responseDataMap = [];
- foreach ($responseData as $respQ) {
- $responseDataMap[$respQ['id']] = $respQ;
- }
- $questionsData = array_map(function ($q) use ($responseDataMap, $paperQuestions) {
- if (isset($responseDataMap[$q['id']])) {
- $apiData = $responseDataMap[$q['id']];
- $rawContent = $apiData['stem'] ?? $q['stem'] ?? '题目内容缺失';
- [$stem, $extractedOptions] = $this->separateStemAndOptions($rawContent);
- $q['stem'] = $stem;
- $q['content'] = $stem; // 同时设置content字段
- $q['answer'] = $apiData['answer'] ?? $q['answer'] ?? '';
- $q['solution'] = $apiData['solution'] ?? $q['solution'] ?? '';
- $q['tags'] = $apiData['tags'] ?? $q['tags'] ?? '';
- // 优先使用API选项,支持多种数据格式
- $apiOptions = $apiData['options'] ?? null;
- if (! empty($apiOptions)) {
- // 标准化options格式为数组值列表
- $q['options'] = $this->normalizeOptions($apiOptions);
- Log::debug('使用标准化API options', [
- 'question_id' => $q['id'],
- 'raw_options' => $apiOptions,
- 'normalized_options' => $q['options'],
- ]);
- } else {
- // 备选:从题干中提取的选项
- $q['options'] = $extractedOptions;
- Log::debug('使用提取的options', [
- 'question_id' => $q['id'],
- 'extracted_options' => $extractedOptions,
- ]);
- }
- }
- if (! isset($q['question_type']) || empty($q['question_type'])) {
- $dbQuestion = $paperQuestions->firstWhere('question_bank_id', $q['id']);
- if ($dbQuestion && $dbQuestion->question_type) {
- $q['question_type'] = $dbQuestion->question_type;
- }
- }
- return $q;
- }, $questionsData);
- }
- }
- }
- $questions = $this->buildGroupedQuestionsForPaperBody($questionsData, (string) $paper_id);
- $studentInfo = $this->getStudentInfo($paper->student_id);
- $teacherInfo = $this->getTeacherInfo($paper->teacher_id);
- $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
- $appendScanSheet = config('exam.pdf_grading_append_scan_sheet', false);
- $gradingView = $appendScanSheet ? 'pdf.exam-answer-detail' : 'pdf.exam-grading';
- return view($gradingView, [
- 'paper' => $paper,
- 'questions' => $questions,
- 'student' => $studentInfo,
- 'teacher' => $teacherInfo,
- 'includeAnswer' => true,
- 'pdfMeta' => $pdfMeta,
- ]);
- }
- /**
- * 知识点讲解视图
- */
- public function showKnowledgeExplanation(Request $request, $paper_id)
- {
- // 获取试卷数据
- $paper = \App\Models\Paper::where('paper_id', $paper_id)->first();
- if (! $paper) {
- abort(404, '试卷未找到');
- }
- $studentInfo = $this->getStudentInfo($paper->student_id);
- $pdfMeta = $this->buildPdfMeta($paper, (string) $paper_id, $studentInfo);
- $studentName = $pdfMeta['student_name'];
- // 生成时间(格式:2026年01月30日 15:04:05)
- $generateDateTime = now()->format('Y年m月d日 H:i:s');
- // 优先使用 paper 中保存的 explanation_kp_codes(组卷时指定的知识点,最多2个)
- $kpCodes = $paper->explanation_kp_codes ?? [];
- // 如果没有保存 explanation_kp_codes,回退到从题目中提取(兼容旧数据)
- if (empty($kpCodes)) {
- $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paper_id)->get();
- $seen = [];
- $questionBankIds = $paperQuestions
- ->pluck('question_bank_id')
- ->filter()
- ->unique()
- ->values();
- $questionKpMap = [];
- if ($questionBankIds->isNotEmpty()) {
- $questionKpMap = \App\Models\Question::whereIn('id', $questionBankIds)
- ->pluck('kp_code', 'id')
- ->toArray();
- }
- foreach ($paperQuestions as $pq) {
- $kpCode = trim((string) ($pq->knowledge_point ?? ''));
- if ($kpCode === '' && ! empty($pq->question_bank_id)) {
- $kpCode = trim((string) ($questionKpMap[$pq->question_bank_id] ?? ''));
- }
- if ($kpCode === '') {
- continue;
- }
- if (isset($seen[$kpCode])) {
- continue;
- }
- $seen[$kpCode] = true;
- $kpCodes[] = $kpCode;
- }
- }
- // 使用 ExamPdfExportService 构建知识点数据
- $pdfService = app(\App\Services\ExamPdfExportService::class);
- // 批量获取知识点讲解
- $knowledgePoints = $pdfService->buildExplanations($kpCodes);
- return view('pdf.exam-knowledge-explanation', [
- 'paperId' => $paper_id,
- 'examCode' => $pdfMeta['exam_code'],
- 'studentName' => $studentName,
- 'generateDateTime' => $generateDateTime,
- 'knowledgePoints' => $knowledgePoints,
- 'pdfMeta' => $pdfMeta,
- ]);
- }
- /**
- * 服务端渲染预览 - 试卷(与 PDF 生成效果一致,用于调试)
- */
- public function showServerRendered(Request $request, $paper_id)
- {
- // 强制不显示答案(试卷模式)
- $request->merge(['answer' => 'false']);
- // 复用 show() 获取 HTML
- $view = $this->show($request, $paper_id);
- $html = $view->render();
- // 使用 KatexRenderer 服务端渲染公式
- $katexRenderer = new \App\Services\KatexRenderer();
- $rendered = $katexRenderer->disableCache()->renderHtml($html);
- return response($rendered);
- }
- /**
- * 服务端渲染预览 - 判卷(与 PDF 生成效果一致,用于调试)
- */
- public function showGradingServerRendered(Request $request, $paper_id)
- {
- // 复用 showGrading() 获取 HTML
- $view = $this->showGrading($request, $paper_id);
- $html = $view->render();
- // 使用 KatexRenderer 服务端渲染公式
- $katexRenderer = new \App\Services\KatexRenderer();
- $rendered = $katexRenderer->disableCache()->renderHtml($html);
- return response($rendered);
- }
- /**
- * 重新生成 PDF(统一生成卷子和判卷)
- *
- * @param string $paper_id
- * @return \Illuminate\Http\JsonResponse
- */
- public function regeneratePdf(Request $request, $paper_id)
- {
- Log::info('RegeneratePdf: 开始重新生成PDF', ['paper_id' => $paper_id]);
- // 验证 paper_id 格式
- if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
- return response()->json([
- 'success' => false,
- 'message' => '无效的试卷ID格式',
- 'paper_id' => $paper_id,
- ], 400);
- }
- try {
- // 【修复】首先检查试卷是否存在
- $paperModel = Paper::with('questions')->find($paper_id);
- if (! $paperModel || $paperModel->questions->isEmpty()) {
- return response()->json([
- 'success' => false,
- 'message' => '无效的试卷',
- 'paper_id' => $paper_id,
- ], 400);
- }
- // 根据 config 或 env 配置决定是否包含知识点讲解
- // 还需要判断如果摸底(paper_type =0)的时候也是不需要插入知识点讲解内容
- $includeKpExplain = null;
- if ($request->has('include_kp_explain')) {
- $includeKpExplain = filter_var(
- $request->input('include_kp_explain'),
- FILTER_VALIDATE_BOOLEAN,
- FILTER_NULL_ON_FAILURE
- );
- } elseif ($paperModel->paper_type === 0) {
- $includeKpExplain = false;
- }
- info("includekpexplain", [$includeKpExplain]);
- // 调用 PDF 生成服务
- $pdfService = app(\App\Services\ExamPdfExportService::class);
- // 生成统一 PDF(卷子 + 判卷)
- $pdfUrl = $pdfService->generateUnifiedPdf($paper_id, $includeKpExplain);
- if ($pdfUrl) {
- Log::info('RegeneratePdf: PDF重新生成成功', [
- 'paper_id' => $paper_id,
- 'url' => $pdfUrl,
- ]);
- return response()->json([
- 'success' => true,
- 'message' => 'PDF重新生成成功',
- 'paper_id' => $paper_id,
- 'pdf_url' => $pdfUrl,
- ]);
- }
- Log::error('RegeneratePdf: PDF生成失败', ['paper_id' => $paper_id]);
- return response()->json([
- 'success' => false,
- 'message' => 'PDF生成失败',
- 'paper_id' => $paper_id,
- ], 500);
- } catch (\Exception $e) {
- Log::error('RegeneratePdf: 异常错误', [
- 'paper_id' => $paper_id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- return response()->json([
- 'success' => false,
- 'message' => 'PDF生成异常:'.$e->getMessage(),
- 'paper_id' => $paper_id,
- ], 500);
- }
- }
- /**
- * 重新生成试卷 PDF(不含答案)
- *
- * @param string $paper_id
- * @return \Illuminate\Http\JsonResponse
- */
- public function regenerateExamPdf(Request $request, $paper_id)
- {
- Log::info('RegenerateExamPdf: 开始重新生成试卷PDF', ['paper_id' => $paper_id]);
- if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
- return response()->json([
- 'success' => false,
- 'message' => '无效的试卷ID格式',
- 'paper_id' => $paper_id,
- ], 400);
- }
- try {
- $pdfService = app(\App\Services\ExamPdfExportService::class);
- $pdfUrl = $pdfService->generateExamPdf($paper_id);
- if ($pdfUrl) {
- return response()->json([
- 'success' => true,
- 'message' => '试卷PDF重新生成成功',
- 'paper_id' => $paper_id,
- 'pdf_url' => $pdfUrl,
- ]);
- }
- return response()->json([
- 'success' => false,
- 'message' => '试卷PDF生成失败',
- 'paper_id' => $paper_id,
- ], 500);
- } catch (\Exception $e) {
- Log::error('RegenerateExamPdf: 异常错误', [
- 'paper_id' => $paper_id,
- 'error' => $e->getMessage(),
- ]);
- return response()->json([
- 'success' => false,
- 'message' => 'PDF生成异常:'.$e->getMessage(),
- 'paper_id' => $paper_id,
- ], 500);
- }
- }
- /**
- * 重新生成判卷 PDF(含答案)
- *
- * @param string $paper_id
- * @return \Illuminate\Http\JsonResponse
- */
- public function regenerateGradingPdf(Request $request, $paper_id)
- {
- Log::info('RegenerateGradingPdf: 开始重新生成判卷PDF', ['paper_id' => $paper_id]);
- if (empty($paper_id) || ! preg_match('/^paper_\d+$/', $paper_id)) {
- return response()->json([
- 'success' => false,
- 'message' => '无效的试卷ID格式',
- 'paper_id' => $paper_id,
- ], 400);
- }
- try {
- $pdfService = app(\App\Services\ExamPdfExportService::class);
- $pdfUrl = $pdfService->generateGradingPdf($paper_id);
- if ($pdfUrl) {
- return response()->json([
- 'success' => true,
- 'message' => '判卷PDF重新生成成功',
- 'paper_id' => $paper_id,
- 'pdf_url' => $pdfUrl,
- ]);
- }
- return response()->json([
- 'success' => false,
- 'message' => '判卷PDF生成失败',
- 'paper_id' => $paper_id,
- ], 500);
- } catch (\Exception $e) {
- Log::error('RegenerateGradingPdf: 异常错误', [
- 'paper_id' => $paper_id,
- 'error' => $e->getMessage(),
- ]);
- return response()->json([
- 'success' => false,
- 'message' => 'PDF生成异常:'.$e->getMessage(),
- 'paper_id' => $paper_id,
- ], 500);
- }
- }
- /**
- * 批量重新生成 PDF:按时间区间遍历 completed_at=NULL 的卷子,投递到队列异步处理
- *
- * 基于 /api/papers/{paper_id}/regenerate 逻辑,将符合条件的试卷投递到 pdf 队列。
- * 时间格式 Y-m-d,start_date 从 00:00:00,end_date 到 23:59:59。
- * 接口立即返回,实际生成由 queue worker 处理。
- *
- * @return \Illuminate\Http\JsonResponse
- */
- public function regeneratePdfBatch(Request $request)
- {
- $startDate = $request->input('start_date');
- $endDate = $request->input('end_date');
- $datePattern = '/^\d{4}-\d{2}-\d{2}$/';
- if (empty($startDate) || ! preg_match($datePattern, $startDate)) {
- return response()->json([
- 'success' => false,
- 'message' => '参数 start_date 必填,格式 Y-m-d(如 2026-03-20)',
- ], 400);
- }
- if (empty($endDate) || ! preg_match($datePattern, $endDate)) {
- return response()->json([
- 'success' => false,
- 'message' => '参数 end_date 必填,格式 Y-m-d(如 2026-03-22)',
- ], 400);
- }
- if ($startDate > $endDate) {
- return response()->json([
- 'success' => false,
- 'message' => 'start_date 不能大于 end_date',
- ], 400);
- }
- $startTime = $startDate.' 00:00:00';
- $endTime = $endDate.' 23:59:59';
- $includeKpExplain = $request->has('include_kp_explain')
- ? filter_var($request->input('include_kp_explain'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
- : null;
- Log::info('RegeneratePdfBatch: 投递队列', [
- 'start_date' => $startDate,
- 'end_date' => $endDate,
- ]);
- try {
- $papers = Paper::with('questions')
- ->whereBetween('created_at', [$startTime, $endTime])
- ->whereNull('completed_at')
- ->orderBy('paper_id')
- ->get();
- if ($papers->isEmpty()) {
- return response()->json([
- 'success' => true,
- 'message' => '未找到符合条件的试卷',
- 'start_date' => $startDate,
- 'end_date' => $endDate,
- 'queued' => 0,
- 'skipped' => 0,
- 'paper_ids' => [],
- ]);
- }
- $queued = [];
- $skipped = 0;
- foreach ($papers as $paper) {
- if ($paper->questions->isEmpty()) {
- $skipped++;
- continue;
- }
- RegeneratePdfJob::dispatch($paper->paper_id, $includeKpExplain);
- $queued[] = $paper->paper_id;
- }
- Log::info('RegeneratePdfBatch: 已投递', [
- 'start_date' => $startDate,
- 'end_date' => $endDate,
- 'queued' => count($queued),
- 'skipped' => $skipped,
- ]);
- return response()->json([
- 'success' => true,
- 'message' => '已投递到 pdf 队列,请确保 queue worker 正在运行',
- 'start_date' => $startDate,
- 'end_date' => $endDate,
- 'queued' => count($queued),
- 'skipped' => $skipped,
- 'paper_ids' => $queued,
- ]);
- } catch (\Exception $e) {
- Log::error('RegeneratePdfBatch: 批量异常', ['error' => $e->getMessage()]);
- return response()->json([
- 'success' => false,
- 'message' => '批量投递异常:'.$e->getMessage(),
- ], 500);
- }
- }
- /**
- * 按卷子 ID 数组批量重新生成 PDF,投递到队列异步处理
- *
- * @return \Illuminate\Http\JsonResponse
- */
- public function regeneratePdfBatchByIds(Request $request)
- {
- $paperIds = $request->input('paper_ids');
- if (empty($paperIds) || ! is_array($paperIds)) {
- return response()->json([
- 'success' => false,
- 'message' => '参数 paper_ids 必填,且为数组(如 ["paper_123","paper_456"])',
- ], 400);
- }
- $paperIds = array_values(array_unique(array_filter(array_map('trim', $paperIds))));
- $validPattern = '/^paper_\d+$/';
- $invalid = array_filter($paperIds, fn ($id) => ! preg_match($validPattern, $id));
- if (! empty($invalid)) {
- return response()->json([
- 'success' => false,
- 'message' => 'paper_ids 格式错误,需为 paper_ 开头的数字',
- 'invalid' => array_values($invalid),
- ], 400);
- }
- $includeKpExplain = $request->has('include_kp_explain')
- ? filter_var($request->input('include_kp_explain'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
- : null;
- Log::info('RegeneratePdfBatchByIds: 投递队列', ['paper_ids' => $paperIds, 'count' => count($paperIds)]);
- try {
- $papers = Paper::with('questions')
- ->whereIn('paper_id', $paperIds)
- ->get()
- ->keyBy('paper_id');
- $queued = [];
- $skipped = 0;
- foreach ($paperIds as $paperId) {
- $paper = $papers->get($paperId);
- if (! $paper || $paper->questions->isEmpty()) {
- $skipped++;
- continue;
- }
- RegeneratePdfJob::dispatch($paperId, $includeKpExplain);
- $queued[] = $paperId;
- }
- Log::info('RegeneratePdfBatchByIds: 已投递', [
- 'queued' => count($queued),
- 'skipped' => $skipped,
- ]);
- return response()->json([
- 'success' => true,
- 'message' => '已投递到 pdf 队列,请确保 queue worker 正在运行',
- 'queued' => count($queued),
- 'skipped' => $skipped,
- 'paper_ids' => $queued,
- ]);
- } catch (\Exception $e) {
- Log::error('RegeneratePdfBatchByIds: 批量异常', ['error' => $e->getMessage()]);
- return response()->json([
- 'success' => false,
- 'message' => '批量投递异常:'.$e->getMessage(),
- ], 500);
- }
- }
- }
|