| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783 |
- <?php
- namespace App\Http\Controllers;
- use App\Jobs\RegeneratePdfJob;
- use App\Models\KnowledgeExplanation;
- use App\Models\Paper;
- use App\Services\ExamPdfExportService;
- use App\Services\KnowledgeExplanationService;
- use App\Services\PaperIdGenerator;
- 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;
- 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);
- // 方案B:必须先检测到至少4个连续选项字母(如 A/B/C/D)才允许拆分选项。
- if (! $this->hasConsecutiveOptionMarkers($contentWithoutSvg, 4)) {
- return [];
- }
- // 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, ?string $questionType = null): array
- {
- // 仅选择题需要做“题干/选项拆分”,其他题型直接返回原始题干。
- if ($questionType === null || $this->normalizeQuestionTypeValue($questionType) !== 'choice') {
- return [$content, []];
- }
- // 【修复】先移除SVG内容,避免误匹配SVG注释中的 BD:DC、A:B 等内容
- $contentWithoutSvg = preg_replace('/<svg[^>]*>.*?<\/svg>/is', '[SVG_PLACEHOLDER]', $content);
- // 方案B:必须至少命中4个连续选项字母(A→D)才判定为选择题选项区。
- $hasOptions = $this->hasConsecutiveOptionMarkers($contentWithoutSvg, 4);
- 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, []];
- }
- /**
- * 检测题干中是否存在至少 N 个连续选项字母(如 A/B/C/D)。
- */
- private function hasConsecutiveOptionMarkers(string $content, int $minRun = 4): bool
- {
- if ($minRun <= 1) {
- return preg_match('/(?:^|\s)[A-H][\.、.]/u', $content) === 1;
- }
- if (! preg_match_all('/(?:^|\s)([A-H])[\.、.]/u', $content, $matches)) {
- return false;
- }
- $letters = array_map(static fn ($ch) => strtoupper((string) $ch), $matches[1] ?? []);
- if (empty($letters)) {
- return false;
- }
- $longestRun = 1;
- $currentRun = 1;
- for ($i = 1, $count = count($letters); $i < $count; $i++) {
- $prev = ord($letters[$i - 1]);
- $curr = ord($letters[$i]);
- if ($curr === $prev + 1) {
- $currentRun++;
- } else {
- $currentRun = 1;
- }
- if ($currentRun > $longestRun) {
- $longestRun = $currentRun;
- }
- if ($longestRun >= $minRun) {
- return true;
- }
- }
- return $longestRun >= $minRun;
- }
- /**
- * 根据题型获取默认分数
- */
- 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}",
- ];
- }
- 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'] ?? '中等';
- // 为 demo 试卷获取完整的题目详情(包括选项)
- if (! empty($questionsData)) {
- $questionBankService = app(QuestionBankService::class);
- $questionIds = array_column($questionsData, 'id');
- $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['question_type'] ?? null);
- $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 ?? '',
- ];
- }
- Log::debug('paper_questions 获取题目', [
- 'paper_id' => $paper_id,
- 'question_count' => count($questionsData),
- ]);
- // 如果需要完整题目详情(stem等),可以从题库获取
- // 但要严格限制只获取这8道题
- if (! empty($questionsData)) {
- $questionBankService = app(QuestionBankService::class);
- $questionIds = array_column($questionsData, 'id');
- $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, $q['question_type'] ?? null);
- // 合并数据,优先使用题库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 = ['choice' => [], 'fill' => [], 'answer' => []];
- foreach ($questionsData as $q) {
- // 题库API返回的是 stem 字段,不是 content
- $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
- // 分离题干和选项
- [$content, $extractedOptions] = $this->separateStemAndOptions($rawContent, $q['question_type'] ?? null);
- // 如果从题库API获取了选项,优先使用
- $options = $q['options'] ?? $extractedOptions;
- $answer = $q['answer'] ?? '';
- $solution = $q['solution'] ?? '';
- // 优先使用 question_type 字段,如果没有则根据内容智能判断
- $type = isset($q['question_type'])
- ? $this->normalizeQuestionTypeValue((string) $q['question_type'])
- : $this->determineQuestionType($q);
- // 详细调试:记录题目类型判断结果
- Log::debug('题目类型判断', [
- '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, // 同时提供stem字段
- '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; // 添加标记
- $qData = (object) $questionData;
- $questions[$type][] = $qData;
- }
- // 【关键】确保每个题型内的题目按 question_number 排序
- 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;
- });
- }
- }
- // 调试:记录最终分类结果
- 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'] ?? '中等';
- if (! empty($questionsData)) {
- $questionBankService = app(QuestionBankService::class);
- $questionIds = array_column($questionsData, 'id');
- $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['question_type'] ?? null);
- $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 ?? '',
- ];
- }
- if (! empty($questionsData)) {
- $questionBankService = app(QuestionBankService::class);
- $questionIds = array_column($questionsData, 'id');
- $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['question_type'] ?? null);
- $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 = ['choice' => [], 'fill' => [], 'answer' => []];
- foreach ($questionsData as $q) {
- $rawContent = $q['stem'] ?? $q['content'] ?? '题目内容缺失';
- [$content, $extractedOptions] = $this->separateStemAndOptions($rawContent, $q['question_type'] ?? null);
- $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 (! isset($questions[$type])) {
- $type = 'answer';
- }
- // 统一处理数学公式和选项数据
- $questionData = [
- 'id' => $q['id'] ?? $q['question_bank_id'] ?? null,
- 'question_number' => $q['question_number'] ?? null, // 【关键】保留题目序号
- 'content' => $content,
- 'stem' => $content, // 同时提供stem字段
- '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; // 添加标记
- $qData = (object) $questionData;
- $questions[$type][] = $qData;
- }
- // 【关键】确保每个题型内的题目按 question_number 排序
- 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;
- });
- }
- }
- $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,
- ]);
- }
- /**
- * 按题号顺序从试卷题目反推知识点编码,去重(集合顺序用于同级兜底)。
- * 展示顺序由 {@see sortKnowledgePointCodesByHierarchy} 按知识点树 DFS 决定。
- *
- * @return array<int,string>
- */
- private function extractKnowledgePointCodesFromPaperQuestions(string $paperId): array
- {
- $paperQuestions = \App\Models\PaperQuestion::query()
- ->where('paper_id', $paperId)
- ->orderBy('question_number')
- ->get();
- if ($paperQuestions->isEmpty()) {
- return [];
- }
- $questionBankIds = $paperQuestions
- ->pluck('question_bank_id')
- ->filter()
- ->unique()
- ->values();
- $questionKpMap = [];
- if ($questionBankIds->isNotEmpty()) {
- $questionKpMap = \App\Models\Question::query()
- ->whereIn('id', $questionBankIds)
- ->pluck('kp_code', 'id')
- ->toArray();
- }
- $ordered = [];
- $seen = [];
- 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;
- $ordered[] = $kpCode;
- }
- return $ordered;
- }
- /**
- * papers.params 中的 kp_codes / kp_code_list(仅作无 paper_questions 时的兜底,例如未入库题目的讲解卷)。
- *
- * @param array<string,mixed>|null $params
- * @return array<int,string>
- */
- private function kpCodesFromAssembleRequestPayload(?array $params): array
- {
- if ($params === null || $params === []) {
- return [];
- }
- $seen = [];
- foreach (['kp_codes', 'kp_code_list'] as $key) {
- if (! isset($params[$key])) {
- continue;
- }
- $raw = $params[$key];
- if (is_string($raw)) {
- $parts = array_filter(array_map('trim', explode(',', $raw)));
- foreach ($parts as $c) {
- if ($c !== '') {
- $seen[$c] = true;
- }
- }
- } elseif (is_array($raw)) {
- foreach ($raw as $c) {
- $c = trim((string) $c);
- if ($c !== '') {
- $seen[$c] = true;
- }
- }
- }
- }
- return array_keys($seen);
- }
- /**
- * 按知识点树层级排序:根在前,同层兄弟按 kp_code 字典序,深度优先。
- * 库中不存在的编码保留在末尾,顺序与原列表一致。
- *
- * @param array<int,string> $kpCodes
- * @return array<int,string>
- */
- private function sortKnowledgePointCodesByHierarchy(array $kpCodes): array
- {
- $kpCodes = array_values(array_unique(array_filter(array_map(static fn ($c) => trim((string) $c), $kpCodes), static fn ($c) => $c !== '')));
- if (count($kpCodes) <= 1) {
- return $kpCodes;
- }
- $byCode = [];
- $pending = $kpCodes;
- $guard = 0;
- while ($pending !== [] && $guard < 100) {
- $guard++;
- $rows = \App\Models\KnowledgePoint::query()
- ->whereIn('kp_code', $pending)
- ->get()
- ->keyBy('kp_code');
- $next = [];
- foreach ($rows as $code => $row) {
- $byCode[$code] = $row;
- $p = trim((string) ($row->parent_kp_code ?? ''));
- if ($p !== '' && ! isset($byCode[$p])) {
- $next[$p] = true;
- }
- }
- $pending = array_keys($next);
- }
- if ($byCode === []) {
- return $kpCodes;
- }
- $childrenByParent = [];
- foreach ($byCode as $code => $row) {
- $p = trim((string) ($row->parent_kp_code ?? ''));
- if ($p !== '' && isset($byCode[$p])) {
- $childrenByParent[$p][] = $code;
- }
- }
- foreach ($childrenByParent as &$kids) {
- sort($kids, SORT_STRING);
- }
- unset($kids);
- $roots = [];
- foreach ($byCode as $code => $row) {
- $p = trim((string) ($row->parent_kp_code ?? ''));
- if ($p === '' || ! isset($byCode[$p])) {
- $roots[] = $code;
- }
- }
- sort($roots, SORT_STRING);
- $want = array_flip($kpCodes);
- $out = [];
- $visit = function (string $node) use (&$visit, &$out, &$want, &$childrenByParent): void {
- if (isset($want[$node])) {
- $out[] = $node;
- }
- foreach ($childrenByParent[$node] ?? [] as $child) {
- $visit($child);
- }
- };
- foreach ($roots as $r) {
- $visit($r);
- }
- foreach ($kpCodes as $c) {
- if (! isset($byCode[$c])) {
- $out[] = $c;
- }
- }
- return $out;
- }
- /**
- * 知识点讲解视图
- */
- 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');
- // 1) 主路径:由题目反推知识点(去重后有几个展示几块)
- $kpCodes = $this->extractKnowledgePointCodesFromPaperQuestions((string) $paper_id);
- // 2) 无题目行时:策略层 explanation_kp_codes
- if ($kpCodes === []) {
- $kpCodes = $paper->explanation_kp_codes ?? [];
- }
- if (! is_array($kpCodes)) {
- $kpCodes = [];
- }
- // 3) 仍为空:params 快照(无 paper_questions 的边界场景)
- if ($kpCodes === []) {
- $kpCodes = $this->kpCodesFromAssembleRequestPayload(is_array($paper->params) ? $paper->params : null);
- }
- if (count($kpCodes) > 1) {
- $kpCodes = $this->sortKnowledgePointCodesByHierarchy($kpCodes);
- }
- // 使用 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);
- }
- if (! PaperIdGenerator::validatePaperId((string) $paper_id)) {
- Log::warning('RegeneratePdf: 非标准15位 paper_id', ['paper_id' => $paper_id]);
- }
- try {
- // 【修复】首先检查试卷是否存在
- $paperModel = Paper::with('questions')->find($paper_id);
- if (! $paperModel || $paperModel->questions->isEmpty()) {
- return response()->json([
- 'success' => false,
- 'message' => '无效的试卷',
- 'paper_id' => $paper_id,
- ], 400);
- }
- // 调用 PDF 生成服务
- $pdfService = app(\App\Services\ExamPdfExportService::class);
- // 生成统一 PDF(卷子 + 判卷)
- $pdfUrl = $pdfService->generateUnifiedPdf($paper_id);
- 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(保持同一个 knowledge_id)。
- *
- * @param string $knowledge_id
- * @return \Illuminate\Http\JsonResponse
- */
- public function regenerateKnowledgeExplanationPdf(
- Request $request,
- string $knowledge_id,
- KnowledgeExplanationService $knowledgeExplanationService,
- ExamPdfExportService $pdfService
- ) {
- Log::info('RegenerateKnowledgeExplanationPdf: 开始重新生成PDF', ['knowledge_id' => $knowledge_id]);
- if (empty($knowledge_id) || ! preg_match('/^(?:knowledge_|paper_)[1-9]\d{14}$/', $knowledge_id)) {
- return response()->json([
- 'success' => false,
- 'message' => '无效的知识点讲解ID格式',
- 'knowledge_id' => $knowledge_id,
- ], 400);
- }
- try {
- $record = KnowledgeExplanation::query()
- ->where('knowledge_id', $knowledge_id)
- ->first();
- if (! $record) {
- return response()->json([
- 'success' => false,
- 'message' => '知识点讲解记录不存在',
- 'knowledge_id' => $knowledge_id,
- ], 404);
- }
- $record->update(['status' => 'processing']);
- $knowledgePoints = $knowledgeExplanationService->rebuildKnowledgePointsForRecord($record->refresh());
- $pdfUrl = $pdfService->generateKnowledgeExplanationStandalonePdf($record, $knowledgePoints);
- if (! $pdfUrl) {
- $record->update(['status' => 'failed']);
- return response()->json([
- 'success' => false,
- 'message' => '知识点讲解PDF生成失败',
- 'knowledge_id' => $knowledge_id,
- ], 500);
- }
- $record->update([
- 'status' => 'completed',
- 'pdf_url' => $pdfUrl,
- 'generated_at' => now(),
- ]);
- Log::info('RegenerateKnowledgeExplanationPdf: PDF重新生成成功', [
- 'knowledge_id' => $knowledge_id,
- 'url' => $pdfUrl,
- ]);
- return response()->json([
- 'success' => true,
- 'message' => '知识点讲解PDF重新生成成功',
- 'knowledge_id' => $knowledge_id,
- 'pdf_url' => $pdfUrl,
- ]);
- } catch (\Throwable $e) {
- KnowledgeExplanation::query()
- ->where('knowledge_id', $knowledge_id)
- ->update(['status' => 'failed']);
- Log::error('RegenerateKnowledgeExplanationPdf: 异常错误', [
- 'knowledge_id' => $knowledge_id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- return response()->json([
- 'success' => false,
- 'message' => '知识点讲解PDF生成异常:'.$e->getMessage(),
- 'knowledge_id' => $knowledge_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);
- }
- if (! PaperIdGenerator::validatePaperId((string) $paper_id)) {
- Log::warning('RegenerateExamPdf: 非标准15位 paper_id', ['paper_id' => $paper_id]);
- }
- 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);
- }
- if (! PaperIdGenerator::validatePaperId((string) $paper_id)) {
- Log::warning('RegenerateGradingPdf: 非标准15位 paper_id', ['paper_id' => $paper_id]);
- }
- 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';
- 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);
- $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);
- }
- 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);
- $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);
- }
- }
- }
|