AssembleExamTaskJob.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\MistakeRecord;
  4. use App\Services\LearningAnalyticsService;
  5. use App\Services\QuestionBankService;
  6. use App\Services\TaskManager;
  7. use Illuminate\Bus\Queueable;
  8. use Illuminate\Contracts\Queue\ShouldQueue;
  9. use Illuminate\Foundation\Bus\Dispatchable;
  10. use Illuminate\Queue\InteractsWithQueue;
  11. use Illuminate\Queue\SerializesModels;
  12. use Illuminate\Support\Facades\Log;
  13. use Throwable;
  14. class AssembleExamTaskJob implements ShouldQueue
  15. {
  16. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  17. public string $taskId;
  18. public int $tries = 2;
  19. public int $timeout = 180;
  20. public function __construct(string $taskId)
  21. {
  22. $this->taskId = $taskId;
  23. // 复用现有 pdf-worker,避免 default 队列无人消费
  24. $this->onQueue('pdf');
  25. $this->afterCommit();
  26. }
  27. public function handle(
  28. LearningAnalyticsService $learningAnalyticsService,
  29. QuestionBankService $questionBankService,
  30. TaskManager $taskManager
  31. ): void {
  32. $task = $taskManager->getTaskStatus($this->taskId);
  33. if (!is_array($task) || empty($task['data']) || !is_array($task['data'])) {
  34. $taskManager->markTaskFailed($this->taskId, '任务数据不存在');
  35. return;
  36. }
  37. $data = $task['data'];
  38. $assembleStartedAt = microtime(true);
  39. try {
  40. $taskManager->updateTaskProgress($this->taskId, 5, '开始异步组卷...');
  41. $assembleType = (int) ($data['assemble_type'] ?? 4);
  42. $difficultyCategory = $data['difficulty_category'] ?? 1;
  43. $paperName = $data['paper_name'] ?? ('智能试卷_'.now()->format('Ymd_His'));
  44. $mistakeIds = $data['mistake_ids'] ?? [];
  45. $mistakeQuestionIds = $data['mistake_question_ids'] ?? [];
  46. $paperIds = $data['paper_ids'] ?? [];
  47. $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
  48. $questions = [];
  49. $result = null;
  50. $diagnosticChapterId = null;
  51. $explanationKpCodes = null;
  52. if (! empty($mistakeIds) || ! empty($mistakeQuestionIds)) {
  53. $questionIds = $this->resolveMistakeQuestionIds((string) $data['student_id'], $mistakeIds, $mistakeQuestionIds);
  54. if (empty($questionIds)) {
  55. $taskManager->markTaskFailed($this->taskId, '未找到可用的错题题目');
  56. return;
  57. }
  58. $bankQuestions = $questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
  59. if (empty($bankQuestions)) {
  60. $taskManager->markTaskFailed($this->taskId, '错题对应题库题目不可用');
  61. return;
  62. }
  63. $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes'] ?? []);
  64. $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
  65. $paperName = $data['paper_name'] ?? ('错题复习_'.$data['student_id'].'_'.now()->format('Ymd_His'));
  66. } else {
  67. $params = [
  68. 'student_id' => $data['student_id'],
  69. 'grade' => $data['grade'] ?? null,
  70. 'total_questions' => $data['total_questions'],
  71. 'kp_codes' => $assembleType === 3 ? null : ($data['kp_codes'] ?? null),
  72. 'skills' => $data['skills'] ?? [],
  73. 'question_type_ratio' => $questionTypeRatio,
  74. 'difficulty_category' => $difficultyCategory,
  75. 'assemble_type' => $assembleType,
  76. 'exam_type' => $data['exam_type'] ?? 'general',
  77. 'paper_ids' => $paperIds,
  78. 'textbook_id' => $data['textbook_id'] ?? null,
  79. 'end_catalog_id' => $data['end_catalog_id'] ?? null,
  80. 'chapter_id_list' => $data['chapter_id_list'] ?? null,
  81. 'kp_code_list' => $assembleType === 3 ? null : ($data['kp_code_list'] ?? $data['kp_codes'] ?? []),
  82. 'practice_options' => $data['practice_options'] ?? null,
  83. 'mistake_options' => $data['mistake_options'] ?? null,
  84. ];
  85. $result = $learningAnalyticsService->generateIntelligentExam($params);
  86. if (empty($result['success'])) {
  87. $taskManager->markTaskFailed($this->taskId, $result['message'] ?? '智能出卷失败');
  88. return;
  89. }
  90. if (isset($result['stats']['difficulty_category'])) {
  91. $difficultyCategory = $result['stats']['difficulty_category'];
  92. }
  93. $diagnosticChapterId = $result['diagnostic_chapter_id'] ?? null;
  94. $explanationKpCodes = $result['explanation_kp_codes'] ?? null;
  95. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes'] ?? []);
  96. }
  97. if (empty($questions)) {
  98. $taskManager->markTaskFailed($this->taskId, '未能生成有效题目');
  99. return;
  100. }
  101. $totalQuestions = min((int) ($data['total_questions'] ?? 10), count($questions));
  102. $questions = array_slice($questions, 0, $totalQuestions);
  103. $questions = $this->sortQuestionsWithinTypeByDifficulty($questions);
  104. $targetTotalScore = (float) ($data['total_score'] ?? 100.0);
  105. $questions = $this->adjustQuestionScores($questions, $targetTotalScore);
  106. $totalScore = array_sum(array_column($questions, 'score'));
  107. $finalAssembleType = ($result !== null && isset($result['assemble_type'])) ? $result['assemble_type'] : $assembleType;
  108. $paperId = $questionBankService->saveExamToDatabase([
  109. 'paper_id' => $data['paper_id'] ?? null,
  110. 'paper_name' => $paperName,
  111. 'student_id' => $data['student_id'],
  112. 'teacher_id' => $data['teacher_id'] ?? null,
  113. 'assembleType' => $finalAssembleType,
  114. 'difficulty_category' => $difficultyCategory,
  115. 'total_score' => $totalScore,
  116. 'questions' => $questions,
  117. 'diagnostic_chapter_id' => $diagnosticChapterId,
  118. 'explanation_kp_codes' => $explanationKpCodes,
  119. ]);
  120. if (! $paperId) {
  121. $taskManager->markTaskFailed($this->taskId, '试卷保存失败');
  122. return;
  123. }
  124. $finalStats = $result['stats'] ?? [
  125. 'total_selected' => count($questions),
  126. 'mistake_based' => ! empty($mistakeIds) || ! empty($mistakeQuestionIds),
  127. ];
  128. if (! isset($finalStats['difficulty_category'])) {
  129. $finalStats['difficulty_category'] = $difficultyCategory;
  130. }
  131. $taskManager->updateTaskStatus($this->taskId, [
  132. 'paper_id' => $paperId,
  133. 'stats' => $finalStats,
  134. 'assemble_elapsed_ms' => (int) round((microtime(true) - $assembleStartedAt) * 1000),
  135. ]);
  136. $taskManager->updateTaskProgress($this->taskId, 40, '组卷完成,开始生成PDF...');
  137. dispatch(new GenerateExamPdfJob($this->taskId, $paperId));
  138. Log::info('AssembleExamTaskJob: 组卷任务完成并已触发PDF任务', [
  139. 'task_id' => $this->taskId,
  140. 'paper_id' => $paperId,
  141. ]);
  142. } catch (\Exception $e) {
  143. Log::error('AssembleExamTaskJob: 异常', [
  144. 'task_id' => $this->taskId,
  145. 'error' => $e->getMessage(),
  146. ]);
  147. $taskManager->markTaskFailed($this->taskId, $e->getMessage());
  148. }
  149. }
  150. public function failed(Throwable $exception): void
  151. {
  152. app(TaskManager::class)->markTaskFailed($this->taskId, $exception->getMessage());
  153. }
  154. private function normalizeQuestionTypeRatio(array $input): array
  155. {
  156. $defaults = ['选择题' => 40, '填空题' => 20, '解答题' => 40];
  157. $normalized = [];
  158. foreach ($input as $key => $value) {
  159. if (! is_numeric($value)) {
  160. continue;
  161. }
  162. $type = $this->normalizeQuestionTypeKey((string) $key);
  163. if ($type) {
  164. $normalized[$type] = (float) $value;
  165. }
  166. }
  167. $merged = array_merge($defaults, $normalized);
  168. $sum = array_sum($merged);
  169. if ($sum > 0) {
  170. foreach ($merged as $k => $v) {
  171. $merged[$k] = round(($v / $sum) * 100, 2);
  172. }
  173. }
  174. return $merged;
  175. }
  176. private function normalizeQuestionTypeKey(string $key): ?string
  177. {
  178. $key = trim($key);
  179. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  180. return '选择题';
  181. }
  182. if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
  183. return '填空题';
  184. }
  185. if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  186. return '解答题';
  187. }
  188. return null;
  189. }
  190. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  191. {
  192. $questionIds = [];
  193. if (! empty($mistakeQuestionIds)) {
  194. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  195. }
  196. if (! empty($mistakeIds)) {
  197. $fromDb = MistakeRecord::query()->where('student_id', $studentId)->whereIn('id', $mistakeIds)->pluck('question_id')->filter()->values()->all();
  198. $questionIds = array_merge($questionIds, $fromDb);
  199. }
  200. return array_values(array_unique(array_filter($questionIds)));
  201. }
  202. private function hydrateQuestions(array $questions, array $kpCodes): array
  203. {
  204. $normalized = [];
  205. foreach ($questions as $question) {
  206. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  207. $score = $question['score'] ?? $this->defaultScore($type);
  208. $normalized[] = [
  209. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  210. 'question_id' => $question['question_id'] ?? null,
  211. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  212. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  213. 'content' => $question['content'] ?? $question['stem'] ?? '',
  214. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  215. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  216. 'solution' => $question['solution'] ?? '',
  217. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  218. 'score' => $score,
  219. 'estimated_time' => $question['estimated_time'] ?? 300,
  220. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  221. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  222. ];
  223. }
  224. return array_values(array_filter($normalized, fn ($q) => ! empty($q['id'])));
  225. }
  226. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  227. {
  228. if (empty($requestedIds)) {
  229. return $questions;
  230. }
  231. $order = array_flip($requestedIds);
  232. usort($questions, function ($a, $b) use ($order) {
  233. $aPos = $order[(string) ($a['id'] ?? '')] ?? PHP_INT_MAX;
  234. $bPos = $order[(string) ($b['id'] ?? '')] ?? PHP_INT_MAX;
  235. return $aPos <=> $bPos;
  236. });
  237. return $questions;
  238. }
  239. private function guessType(array $question): string
  240. {
  241. if (! empty($question['options']) && is_array($question['options'])) {
  242. return '选择题';
  243. }
  244. $content = $question['stem'] ?? $question['content'] ?? '';
  245. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  246. return '填空题';
  247. }
  248. return '解答题';
  249. }
  250. private function defaultScore(string $type): int
  251. {
  252. return match ($type) {
  253. '选择题' => 5,
  254. '填空题' => 5,
  255. '解答题' => 10,
  256. default => 5,
  257. };
  258. }
  259. private function sortQuestionsWithinTypeByDifficulty(array $questions): array
  260. {
  261. $grouped = ['choice' => [], 'fill' => [], 'answer' => []];
  262. foreach ($questions as $question) {
  263. $type = $this->normalizeQuestionType((string) ($question['question_type'] ?? 'answer'));
  264. $grouped[$type][] = $question;
  265. }
  266. $sortFn = function (array $a, array $b): int {
  267. $ad = (float) ($a['difficulty'] ?? 0.5);
  268. $bd = (float) ($b['difficulty'] ?? 0.5);
  269. if ($ad !== $bd) {
  270. return $ad <=> $bd;
  271. }
  272. return ((int) ($a['id'] ?? $a['question_id'] ?? 0)) <=> ((int) ($b['id'] ?? $b['question_id'] ?? 0));
  273. };
  274. usort($grouped['choice'], $sortFn);
  275. usort($grouped['fill'], $sortFn);
  276. usort($grouped['answer'], $sortFn);
  277. $sorted = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  278. foreach ($sorted as $idx => &$question) {
  279. $question['question_number'] = $idx + 1;
  280. }
  281. unset($question);
  282. return $sorted;
  283. }
  284. private function normalizeQuestionType(string $type): string
  285. {
  286. $type = strtolower(trim($type));
  287. if (in_array($type, ['choice', 'single_choice', 'multiple_choice', '选择题', '单选', '多选'], true)) {
  288. return 'choice';
  289. }
  290. if (in_array($type, ['fill', 'fill_in_the_blank', 'blank', '填空题', '填空'], true)) {
  291. return 'fill';
  292. }
  293. return 'answer';
  294. }
  295. private function adjustQuestionScores(array $questions, float $targetTotalScore = 100.0): array
  296. {
  297. if (empty($questions)) {
  298. return $questions;
  299. }
  300. // 第一步:按题型排序
  301. $sortedQuestions = [];
  302. $choiceQuestions = [];
  303. $fillQuestions = [];
  304. $answerQuestions = [];
  305. foreach ($questions as $question) {
  306. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  307. if ($type === 'choice') {
  308. $choiceQuestions[] = $question;
  309. } elseif ($type === 'fill') {
  310. $fillQuestions[] = $question;
  311. } else {
  312. $answerQuestions[] = $question;
  313. }
  314. }
  315. $sortedQuestions = array_merge($choiceQuestions, $fillQuestions, $answerQuestions);
  316. Log::debug('adjustQuestionScores 开始', [
  317. 'choice_count' => count($choiceQuestions),
  318. 'fill_count' => count($fillQuestions),
  319. 'answer_count' => count($answerQuestions),
  320. ]);
  321. foreach ($sortedQuestions as $idx => &$question) {
  322. $question['question_number'] = $idx + 1;
  323. }
  324. unset($question);
  325. $typeCounts = [
  326. 'choice' => count($choiceQuestions),
  327. 'fill' => count($fillQuestions),
  328. 'answer' => count($answerQuestions),
  329. ];
  330. $typeIndexes = ['choice' => [], 'fill' => [], 'answer' => []];
  331. foreach ($sortedQuestions as $index => $question) {
  332. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  333. $typeIndexes[$type][] = $index;
  334. }
  335. $questionScores = [];
  336. $totalQuestions = $typeCounts['choice'] + $typeCounts['fill'] + $typeCounts['answer'];
  337. $globalBaseScore = floor($targetTotalScore / $totalQuestions);
  338. $globalBaseScore = max(1, $globalBaseScore);
  339. $typeOrder = [];
  340. foreach ($sortedQuestions as $question) {
  341. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  342. if (! in_array($type, $typeOrder)) {
  343. $typeOrder[] = $type;
  344. }
  345. }
  346. $remainingBudget = $targetTotalScore;
  347. foreach ($typeOrder as $typeIndex => $type) {
  348. $count = $typeCounts[$type];
  349. if ($count === 0) {
  350. continue;
  351. }
  352. if ($typeIndex === 0) {
  353. $thisBase = $globalBaseScore;
  354. foreach ($typeIndexes[$type] as $idx) {
  355. $questionScores[$idx] = $thisBase;
  356. }
  357. foreach ($typeIndexes[$type] as $idx) {
  358. $questionScores[$idx] = max(1, $questionScores[$idx] - 1);
  359. }
  360. $allocated = 0;
  361. foreach ($typeIndexes[$type] as $idx) {
  362. $allocated += $questionScores[$idx];
  363. }
  364. $remainingBudget -= $allocated;
  365. } elseif ($typeIndex === count($typeOrder) - 1) {
  366. $thisBase = floor($remainingBudget / $count);
  367. $thisBase = max(1, $thisBase);
  368. foreach ($typeIndexes[$type] as $idx) {
  369. $questionScores[$idx] = $thisBase;
  370. }
  371. $total = $thisBase * $count;
  372. $remainder = $remainingBudget - $total;
  373. if ($remainder > 0) {
  374. $answerIndexes = array_values($typeIndexes[$type]);
  375. $startIdx = max(0, count($answerIndexes) - $remainder);
  376. for ($i = $startIdx; $i < count($answerIndexes); $i++) {
  377. $questionScores[$answerIndexes[$i]] += 1;
  378. }
  379. }
  380. } else {
  381. $thisBase = $globalBaseScore;
  382. foreach ($typeIndexes[$type] as $idx) {
  383. $questionScores[$idx] = $thisBase;
  384. }
  385. $allocated = 0;
  386. foreach ($typeIndexes[$type] as $idx) {
  387. $allocated += $questionScores[$idx];
  388. }
  389. $remainingBudget -= $allocated;
  390. }
  391. }
  392. if (count($typeOrder) > 1) {
  393. $lastType = end($typeOrder);
  394. $otherTypes = array_slice($typeOrder, 0, -1);
  395. $maxOtherScore = 0;
  396. foreach ($otherTypes as $type) {
  397. foreach ($typeIndexes[$type] as $idx) {
  398. $maxOtherScore = max($maxOtherScore, $questionScores[$idx]);
  399. }
  400. }
  401. $minLastScore = PHP_INT_MAX;
  402. foreach ($typeIndexes[$lastType] as $idx) {
  403. $minLastScore = min($minLastScore, $questionScores[$idx]);
  404. }
  405. if ($minLastScore <= $maxOtherScore) {
  406. $diff = $maxOtherScore - $minLastScore + 1;
  407. $reductionPerQuestion = min($diff, 2);
  408. foreach ($otherTypes as $type) {
  409. foreach ($typeIndexes[$type] as $idx) {
  410. $questionScores[$idx] = max(1, $questionScores[$idx] - $reductionPerQuestion);
  411. }
  412. }
  413. $reallocated = $targetTotalScore;
  414. foreach ($typeIndexes[$lastType] as $idx) {
  415. $reallocated -= $questionScores[$idx];
  416. }
  417. foreach ($otherTypes as $type) {
  418. foreach ($typeIndexes[$type] as $idx) {
  419. $reallocated -= $questionScores[$idx];
  420. }
  421. }
  422. if ($reallocated > 0) {
  423. $newBase = floor($reallocated / $typeCounts[$lastType]);
  424. foreach ($typeIndexes[$lastType] as $idx) {
  425. $questionScores[$idx] = $newBase;
  426. }
  427. $total = $newBase * $typeCounts[$lastType];
  428. $remainder = $reallocated - $total;
  429. if ($remainder > 0) {
  430. $lastIndexes = array_values($typeIndexes[$lastType]);
  431. $startIdx = max(0, count($lastIndexes) - $remainder);
  432. for ($i = $startIdx; $i < count($lastIndexes); $i++) {
  433. $questionScores[$lastIndexes[$i]] += 1;
  434. }
  435. }
  436. }
  437. }
  438. }
  439. $adjustedQuestions = [];
  440. foreach ($sortedQuestions as $index => $question) {
  441. $adjustedQuestions[$index] = $question;
  442. $adjustedQuestions[$index]['score'] = $questionScores[$index] ?? 5;
  443. }
  444. $total = array_sum(array_column($adjustedQuestions, 'score'));
  445. $diff = (int) $targetTotalScore - (int) $total;
  446. if ($diff !== 0 && ! empty($adjustedQuestions)) {
  447. $count = count($adjustedQuestions);
  448. $i = $count - 1;
  449. while ($diff !== 0) {
  450. $score = $adjustedQuestions[$i]['score'];
  451. if ($diff > 0) {
  452. $adjustedQuestions[$i]['score'] = $score + 1;
  453. $diff--;
  454. } else {
  455. if ($score > 1) {
  456. $adjustedQuestions[$i]['score'] = $score - 1;
  457. $diff++;
  458. }
  459. }
  460. $i--;
  461. if ($i < 0) {
  462. $i = $count - 1;
  463. if ($diff < 0) {
  464. $minScore = min(array_column($adjustedQuestions, 'score'));
  465. if ($minScore <= 1) {
  466. break;
  467. }
  468. }
  469. }
  470. }
  471. }
  472. return $adjustedQuestions;
  473. }
  474. }