AssembleExamTaskJob.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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 队列,与历史部署/消费者一致
  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 ($assembleType === 15) {
  53. // assemble_type=15(展示类型「错题再练」):paper_ids 为题库 question_id,须在该学生 mistake_records 中存在;与 assemble_type=5(卷 id 追练)分离
  54. $questionIdList = $this->normalizeBankQuestionIdsList($paperIds);
  55. if ($questionIdList === []) {
  56. $taskManager->markTaskFailed($this->taskId, '错题再练组卷需提供 paper_ids(题库题目 id)');
  57. return;
  58. }
  59. $strict = $this->resolveMistakeQuestionIdsStrictForStudent(
  60. (string) $data['student_id'],
  61. [],
  62. array_map(static fn ($id) => (string) $id, $questionIdList)
  63. );
  64. if (! ($strict['ok'] ?? false)) {
  65. $taskManager->markTaskFailed($this->taskId, $strict['message'] ?? '错题校验失败');
  66. return;
  67. }
  68. $questionIds = $strict['question_ids'];
  69. $bankQuestions = $questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
  70. if (empty($bankQuestions)) {
  71. $taskManager->markTaskFailed($this->taskId, '错题对应题库题目不可用');
  72. return;
  73. }
  74. $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes'] ?? []);
  75. $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
  76. $paperName = $data['paper_name'] ?? ('错题再练_'.$data['student_id'].'_'.now()->format('Ymd_His'));
  77. } elseif (! empty($mistakeIds) || ! empty($mistakeQuestionIds)) {
  78. // assemble_type=5 时 mistake_ids / mistake_question_ids 须严格归属该学生;其它类型走宽松解析。
  79. if ($assembleType === 5) {
  80. $strict = $this->resolveMistakeQuestionIdsStrictForStudent(
  81. (string) $data['student_id'],
  82. $mistakeIds,
  83. $mistakeQuestionIds
  84. );
  85. if (! ($strict['ok'] ?? false)) {
  86. $taskManager->markTaskFailed($this->taskId, $strict['message'] ?? '错题校验失败');
  87. return;
  88. }
  89. $questionIds = $strict['question_ids'];
  90. } else {
  91. $questionIds = $this->resolveMistakeQuestionIds((string) $data['student_id'], $mistakeIds, $mistakeQuestionIds);
  92. }
  93. if (empty($questionIds)) {
  94. $taskManager->markTaskFailed($this->taskId, '未找到可用的错题题目');
  95. return;
  96. }
  97. $bankQuestions = $questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
  98. if (empty($bankQuestions)) {
  99. $taskManager->markTaskFailed($this->taskId, '错题对应题库题目不可用');
  100. return;
  101. }
  102. $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes'] ?? []);
  103. $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
  104. $paperName = $data['paper_name'] ?? ('错题复习_'.$data['student_id'].'_'.now()->format('Ymd_His'));
  105. } else {
  106. $params = [
  107. 'student_id' => $data['student_id'],
  108. 'grade' => $data['grade'] ?? null,
  109. 'total_questions' => $data['total_questions'],
  110. 'kp_codes' => $assembleType === 3 ? null : ($data['kp_codes'] ?? null),
  111. 'skills' => $data['skills'] ?? [],
  112. 'question_type_ratio' => $questionTypeRatio,
  113. 'difficulty_category' => $difficultyCategory,
  114. 'assemble_type' => $assembleType,
  115. 'exam_type' => $data['exam_type'] ?? 'general',
  116. 'paper_ids' => $paperIds,
  117. 'textbook_id' => $data['textbook_id'] ?? null,
  118. 'end_catalog_id' => $data['end_catalog_id'] ?? null,
  119. 'chapter_id_list' => $data['chapter_id_list'] ?? null,
  120. 'kp_code_list' => $assembleType === 3 ? null : ($data['kp_code_list'] ?? $data['kp_codes'] ?? []),
  121. 'practice_options' => $data['practice_options'] ?? null,
  122. 'mistake_options' => $data['mistake_options'] ?? null,
  123. ];
  124. $result = $learningAnalyticsService->generateIntelligentExam($params);
  125. if (empty($result['success'])) {
  126. $taskManager->markTaskFailed($this->taskId, $result['message'] ?? '智能出卷失败');
  127. return;
  128. }
  129. if (isset($result['stats']['difficulty_category'])) {
  130. $difficultyCategory = $result['stats']['difficulty_category'];
  131. }
  132. $diagnosticChapterId = $result['diagnostic_chapter_id'] ?? null;
  133. $explanationKpCodes = $result['explanation_kp_codes'] ?? null;
  134. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes'] ?? []);
  135. }
  136. if (empty($questions)) {
  137. $taskManager->markTaskFailed($this->taskId, '未能生成有效题目');
  138. return;
  139. }
  140. $totalQuestions = min((int) ($data['total_questions'] ?? 10), count($questions));
  141. $questions = array_slice($questions, 0, $totalQuestions);
  142. $questions = $this->sortQuestionsWithinTypeByDifficulty($questions);
  143. $targetTotalScore = (float) ($data['total_score'] ?? 100.0);
  144. $questions = $this->adjustQuestionScores($questions, $targetTotalScore);
  145. $totalScore = array_sum(array_column($questions, 'score'));
  146. $finalAssembleType = ($result !== null && isset($result['assemble_type'])) ? $result['assemble_type'] : $assembleType;
  147. $paperId = $questionBankService->saveExamToDatabase([
  148. 'paper_id' => $data['paper_id'] ?? null,
  149. 'paper_name' => $paperName,
  150. 'student_id' => $data['student_id'],
  151. 'teacher_id' => $data['teacher_id'] ?? null,
  152. 'assembleType' => $finalAssembleType,
  153. 'difficulty_category' => $difficultyCategory,
  154. 'total_score' => $totalScore,
  155. 'questions' => $questions,
  156. 'diagnostic_chapter_id' => $diagnosticChapterId,
  157. 'explanation_kp_codes' => $explanationKpCodes,
  158. ]);
  159. if (! $paperId) {
  160. $taskManager->markTaskFailed($this->taskId, '试卷保存失败');
  161. return;
  162. }
  163. $finalStats = $result['stats'] ?? [
  164. 'total_selected' => count($questions),
  165. 'mistake_based' => ! empty($mistakeIds) || ! empty($mistakeQuestionIds) || $assembleType === 15,
  166. ];
  167. if (! isset($finalStats['difficulty_category'])) {
  168. $finalStats['difficulty_category'] = $difficultyCategory;
  169. }
  170. $taskManager->updateTaskStatus($this->taskId, [
  171. 'paper_id' => $paperId,
  172. 'stats' => $finalStats,
  173. 'assemble_elapsed_ms' => (int) round((microtime(true) - $assembleStartedAt) * 1000),
  174. ]);
  175. $taskManager->updateTaskProgress($this->taskId, 40, '组卷完成,开始生成PDF...');
  176. dispatch(new GenerateExamPdfJob($this->taskId, $paperId));
  177. Log::info('AssembleExamTaskJob: 组卷任务完成并已触发PDF任务', [
  178. 'task_id' => $this->taskId,
  179. 'paper_id' => $paperId,
  180. ]);
  181. } catch (\Exception $e) {
  182. Log::error('AssembleExamTaskJob: 异常', [
  183. 'task_id' => $this->taskId,
  184. 'error' => $e->getMessage(),
  185. ]);
  186. $taskManager->markTaskFailed($this->taskId, $e->getMessage());
  187. }
  188. }
  189. public function failed(Throwable $exception): void
  190. {
  191. app(TaskManager::class)->markTaskFailed($this->taskId, $exception->getMessage());
  192. }
  193. private function normalizeQuestionTypeRatio(array $input): array
  194. {
  195. $defaults = ['选择题' => 40, '填空题' => 20, '解答题' => 40];
  196. $normalized = [];
  197. foreach ($input as $key => $value) {
  198. if (! is_numeric($value)) {
  199. continue;
  200. }
  201. $type = $this->normalizeQuestionTypeKey((string) $key);
  202. if ($type) {
  203. $normalized[$type] = (float) $value;
  204. }
  205. }
  206. $merged = array_merge($defaults, $normalized);
  207. $sum = array_sum($merged);
  208. if ($sum > 0) {
  209. foreach ($merged as $k => $v) {
  210. $merged[$k] = round(($v / $sum) * 100, 2);
  211. }
  212. }
  213. return $merged;
  214. }
  215. private function normalizeQuestionTypeKey(string $key): ?string
  216. {
  217. $key = trim($key);
  218. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  219. return '选择题';
  220. }
  221. if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
  222. return '填空题';
  223. }
  224. if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  225. return '解答题';
  226. }
  227. return null;
  228. }
  229. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  230. {
  231. $questionIds = [];
  232. if (! empty($mistakeQuestionIds)) {
  233. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  234. }
  235. if (! empty($mistakeIds)) {
  236. $fromDb = MistakeRecord::query()->where('student_id', $studentId)->whereIn('id', $mistakeIds)->pluck('question_id')->filter()->values()->all();
  237. $questionIds = array_merge($questionIds, $fromDb);
  238. }
  239. return array_values(array_unique(array_filter($questionIds)));
  240. }
  241. /**
  242. * 追练(assemble_type=5)+ 指定错题:mistake_ids 须逐条命中该学生的 mistake_records;
  243. * mistake_question_ids 须在该学生错题本中至少有一条记录。顺序:先按 mistake_ids 请求顺序,再追加题号列表(去重)。
  244. * assemble_type=15(错题再练)将 paper_ids 解析为题库题目 id 后,仅使用本方法的 mistake_question_ids 分支做校验。
  245. *
  246. * @return array{ok: bool, message?: string, question_ids?: array<int, string>}
  247. */
  248. private function resolveMistakeQuestionIdsStrictForStudent(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  249. {
  250. $mistakeIds = array_values(array_filter(array_map('strval', $mistakeIds), fn ($v) => $v !== ''));
  251. $mistakeQuestionIds = array_values(array_filter(array_map('strval', $mistakeQuestionIds), fn ($v) => $v !== ''));
  252. $orderedQuestionIds = [];
  253. $seen = [];
  254. if ($mistakeIds !== []) {
  255. $rowIdSet = array_values(array_unique($mistakeIds));
  256. $records = MistakeRecord::query()
  257. ->where('student_id', $studentId)
  258. ->whereIn('id', $rowIdSet)
  259. ->get()
  260. ->keyBy(fn ($r) => (string) $r->id);
  261. foreach ($mistakeIds as $mid) {
  262. $rec = $records[$mid] ?? null;
  263. $qid = $rec && $rec->question_id !== null && $rec->question_id !== ''
  264. ? (string) $rec->question_id
  265. : '';
  266. if ($qid === '') {
  267. return [
  268. 'ok' => false,
  269. 'message' => '部分错题记录不存在或不属于该学生: '.$mid,
  270. ];
  271. }
  272. if (! isset($seen[$qid])) {
  273. $seen[$qid] = true;
  274. $orderedQuestionIds[] = $qid;
  275. }
  276. }
  277. }
  278. foreach ($mistakeQuestionIds as $qid) {
  279. $exists = MistakeRecord::query()
  280. ->where('student_id', $studentId)
  281. ->where('question_id', $qid)
  282. ->exists();
  283. if (! $exists) {
  284. return [
  285. 'ok' => false,
  286. 'message' => '学生错题本中不存在题目: '.$qid,
  287. ];
  288. }
  289. if (! isset($seen[$qid])) {
  290. $seen[$qid] = true;
  291. $orderedQuestionIds[] = $qid;
  292. }
  293. }
  294. return ['ok' => true, 'question_ids' => $orderedQuestionIds];
  295. }
  296. /**
  297. * assemble_type=15 时 paper_ids 承载题库题目 id:纯数字字符串转为 int,去重并保持首次出现顺序。
  298. *
  299. * @return array<int, int|string>
  300. */
  301. private function normalizeBankQuestionIdsList(array $raw): array
  302. {
  303. $out = [];
  304. $seen = [];
  305. foreach ($raw as $v) {
  306. if ($v === null) {
  307. continue;
  308. }
  309. if (is_string($v)) {
  310. $v = trim($v);
  311. if ($v === '') {
  312. continue;
  313. }
  314. }
  315. if (is_int($v)) {
  316. $normalized = $v;
  317. } elseif (is_float($v) && floor($v) == $v) {
  318. $normalized = (int) $v;
  319. } else {
  320. $s = trim((string) $v);
  321. if ($s === '') {
  322. continue;
  323. }
  324. $normalized = preg_match('/^-?\d+$/', $s) ? (int) $s : $s;
  325. }
  326. $dedupeKey = is_int($normalized) ? 'i:'.$normalized : 's:'.(string) $normalized;
  327. if (isset($seen[$dedupeKey])) {
  328. continue;
  329. }
  330. $seen[$dedupeKey] = true;
  331. $out[] = $normalized;
  332. }
  333. return $out;
  334. }
  335. private function hydrateQuestions(array $questions, array $kpCodes): array
  336. {
  337. $normalized = [];
  338. foreach ($questions as $question) {
  339. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  340. $score = $question['score'] ?? $this->defaultScore($type);
  341. $normalized[] = [
  342. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  343. 'question_id' => $question['question_id'] ?? null,
  344. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  345. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  346. 'content' => $question['content'] ?? $question['stem'] ?? '',
  347. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  348. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  349. 'solution' => $question['solution'] ?? '',
  350. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  351. 'score' => $score,
  352. 'estimated_time' => $question['estimated_time'] ?? 300,
  353. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  354. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  355. ];
  356. }
  357. return array_values(array_filter($normalized, fn ($q) => ! empty($q['id'])));
  358. }
  359. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  360. {
  361. if (empty($requestedIds)) {
  362. return $questions;
  363. }
  364. $order = array_flip($requestedIds);
  365. usort($questions, function ($a, $b) use ($order) {
  366. $aPos = $order[(string) ($a['id'] ?? '')] ?? PHP_INT_MAX;
  367. $bPos = $order[(string) ($b['id'] ?? '')] ?? PHP_INT_MAX;
  368. return $aPos <=> $bPos;
  369. });
  370. return $questions;
  371. }
  372. private function guessType(array $question): string
  373. {
  374. if (! empty($question['options']) && is_array($question['options'])) {
  375. return '选择题';
  376. }
  377. $content = $question['stem'] ?? $question['content'] ?? '';
  378. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  379. return '填空题';
  380. }
  381. return '解答题';
  382. }
  383. private function defaultScore(string $type): int
  384. {
  385. return match ($type) {
  386. '选择题' => 5,
  387. '填空题' => 5,
  388. '解答题' => 10,
  389. default => 5,
  390. };
  391. }
  392. private function sortQuestionsWithinTypeByDifficulty(array $questions): array
  393. {
  394. $grouped = ['choice' => [], 'fill' => [], 'answer' => []];
  395. foreach ($questions as $question) {
  396. $type = $this->normalizeQuestionType((string) ($question['question_type'] ?? 'answer'));
  397. $grouped[$type][] = $question;
  398. }
  399. $sortFn = function (array $a, array $b): int {
  400. $ad = (float) ($a['difficulty'] ?? 0.5);
  401. $bd = (float) ($b['difficulty'] ?? 0.5);
  402. if ($ad !== $bd) {
  403. return $ad <=> $bd;
  404. }
  405. return ((int) ($a['id'] ?? $a['question_id'] ?? 0)) <=> ((int) ($b['id'] ?? $b['question_id'] ?? 0));
  406. };
  407. usort($grouped['choice'], $sortFn);
  408. usort($grouped['fill'], $sortFn);
  409. usort($grouped['answer'], $sortFn);
  410. $sorted = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  411. foreach ($sorted as $idx => &$question) {
  412. $question['question_number'] = $idx + 1;
  413. }
  414. unset($question);
  415. return $sorted;
  416. }
  417. private function normalizeQuestionType(string $type): string
  418. {
  419. $type = strtolower(trim($type));
  420. if (in_array($type, ['choice', 'single_choice', 'multiple_choice', '选择题', '单选', '多选'], true)) {
  421. return 'choice';
  422. }
  423. if (in_array($type, ['fill', 'fill_in_the_blank', 'blank', '填空题', '填空'], true)) {
  424. return 'fill';
  425. }
  426. return 'answer';
  427. }
  428. private function adjustQuestionScores(array $questions, float $targetTotalScore = 100.0): array
  429. {
  430. if (empty($questions)) {
  431. return $questions;
  432. }
  433. // 第一步:按题型排序
  434. $sortedQuestions = [];
  435. $choiceQuestions = [];
  436. $fillQuestions = [];
  437. $answerQuestions = [];
  438. foreach ($questions as $question) {
  439. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  440. if ($type === 'choice') {
  441. $choiceQuestions[] = $question;
  442. } elseif ($type === 'fill') {
  443. $fillQuestions[] = $question;
  444. } else {
  445. $answerQuestions[] = $question;
  446. }
  447. }
  448. $sortedQuestions = array_merge($choiceQuestions, $fillQuestions, $answerQuestions);
  449. Log::debug('adjustQuestionScores 开始', [
  450. 'choice_count' => count($choiceQuestions),
  451. 'fill_count' => count($fillQuestions),
  452. 'answer_count' => count($answerQuestions),
  453. ]);
  454. foreach ($sortedQuestions as $idx => &$question) {
  455. $question['question_number'] = $idx + 1;
  456. }
  457. unset($question);
  458. $typeCounts = [
  459. 'choice' => count($choiceQuestions),
  460. 'fill' => count($fillQuestions),
  461. 'answer' => count($answerQuestions),
  462. ];
  463. $typeIndexes = ['choice' => [], 'fill' => [], 'answer' => []];
  464. foreach ($sortedQuestions as $index => $question) {
  465. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  466. $typeIndexes[$type][] = $index;
  467. }
  468. $questionScores = [];
  469. $totalQuestions = $typeCounts['choice'] + $typeCounts['fill'] + $typeCounts['answer'];
  470. $globalBaseScore = floor($targetTotalScore / $totalQuestions);
  471. $globalBaseScore = max(1, $globalBaseScore);
  472. $typeOrder = [];
  473. foreach ($sortedQuestions as $question) {
  474. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  475. if (! in_array($type, $typeOrder)) {
  476. $typeOrder[] = $type;
  477. }
  478. }
  479. $remainingBudget = $targetTotalScore;
  480. foreach ($typeOrder as $typeIndex => $type) {
  481. $count = $typeCounts[$type];
  482. if ($count === 0) {
  483. continue;
  484. }
  485. if ($typeIndex === 0) {
  486. $thisBase = $globalBaseScore;
  487. foreach ($typeIndexes[$type] as $idx) {
  488. $questionScores[$idx] = $thisBase;
  489. }
  490. foreach ($typeIndexes[$type] as $idx) {
  491. $questionScores[$idx] = max(1, $questionScores[$idx] - 1);
  492. }
  493. $allocated = 0;
  494. foreach ($typeIndexes[$type] as $idx) {
  495. $allocated += $questionScores[$idx];
  496. }
  497. $remainingBudget -= $allocated;
  498. } elseif ($typeIndex === count($typeOrder) - 1) {
  499. $thisBase = floor($remainingBudget / $count);
  500. $thisBase = max(1, $thisBase);
  501. foreach ($typeIndexes[$type] as $idx) {
  502. $questionScores[$idx] = $thisBase;
  503. }
  504. $total = $thisBase * $count;
  505. $remainder = $remainingBudget - $total;
  506. if ($remainder > 0) {
  507. $answerIndexes = array_values($typeIndexes[$type]);
  508. $startIdx = max(0, count($answerIndexes) - $remainder);
  509. for ($i = $startIdx; $i < count($answerIndexes); $i++) {
  510. $questionScores[$answerIndexes[$i]] += 1;
  511. }
  512. }
  513. } else {
  514. $thisBase = $globalBaseScore;
  515. foreach ($typeIndexes[$type] as $idx) {
  516. $questionScores[$idx] = $thisBase;
  517. }
  518. $allocated = 0;
  519. foreach ($typeIndexes[$type] as $idx) {
  520. $allocated += $questionScores[$idx];
  521. }
  522. $remainingBudget -= $allocated;
  523. }
  524. }
  525. if (count($typeOrder) > 1) {
  526. $lastType = end($typeOrder);
  527. $otherTypes = array_slice($typeOrder, 0, -1);
  528. $maxOtherScore = 0;
  529. foreach ($otherTypes as $type) {
  530. foreach ($typeIndexes[$type] as $idx) {
  531. $maxOtherScore = max($maxOtherScore, $questionScores[$idx]);
  532. }
  533. }
  534. $minLastScore = PHP_INT_MAX;
  535. foreach ($typeIndexes[$lastType] as $idx) {
  536. $minLastScore = min($minLastScore, $questionScores[$idx]);
  537. }
  538. if ($minLastScore <= $maxOtherScore) {
  539. $diff = $maxOtherScore - $minLastScore + 1;
  540. $reductionPerQuestion = min($diff, 2);
  541. foreach ($otherTypes as $type) {
  542. foreach ($typeIndexes[$type] as $idx) {
  543. $questionScores[$idx] = max(1, $questionScores[$idx] - $reductionPerQuestion);
  544. }
  545. }
  546. $reallocated = $targetTotalScore;
  547. foreach ($typeIndexes[$lastType] as $idx) {
  548. $reallocated -= $questionScores[$idx];
  549. }
  550. foreach ($otherTypes as $type) {
  551. foreach ($typeIndexes[$type] as $idx) {
  552. $reallocated -= $questionScores[$idx];
  553. }
  554. }
  555. if ($reallocated > 0) {
  556. $newBase = floor($reallocated / $typeCounts[$lastType]);
  557. foreach ($typeIndexes[$lastType] as $idx) {
  558. $questionScores[$idx] = $newBase;
  559. }
  560. $total = $newBase * $typeCounts[$lastType];
  561. $remainder = $reallocated - $total;
  562. if ($remainder > 0) {
  563. $lastIndexes = array_values($typeIndexes[$lastType]);
  564. $startIdx = max(0, count($lastIndexes) - $remainder);
  565. for ($i = $startIdx; $i < count($lastIndexes); $i++) {
  566. $questionScores[$lastIndexes[$i]] += 1;
  567. }
  568. }
  569. }
  570. }
  571. }
  572. $adjustedQuestions = [];
  573. foreach ($sortedQuestions as $index => $question) {
  574. $adjustedQuestions[$index] = $question;
  575. $adjustedQuestions[$index]['score'] = $questionScores[$index] ?? 5;
  576. }
  577. $total = array_sum(array_column($adjustedQuestions, 'score'));
  578. $diff = (int) $targetTotalScore - (int) $total;
  579. if ($diff !== 0 && ! empty($adjustedQuestions)) {
  580. $count = count($adjustedQuestions);
  581. $i = $count - 1;
  582. while ($diff !== 0) {
  583. $score = $adjustedQuestions[$i]['score'];
  584. if ($diff > 0) {
  585. $adjustedQuestions[$i]['score'] = $score + 1;
  586. $diff--;
  587. } else {
  588. if ($score > 1) {
  589. $adjustedQuestions[$i]['score'] = $score - 1;
  590. $diff++;
  591. }
  592. }
  593. $i--;
  594. if ($i < 0) {
  595. $i = $count - 1;
  596. if ($diff < 0) {
  597. $minScore = min(array_column($adjustedQuestions, 'score'));
  598. if ($minScore <= 1) {
  599. break;
  600. }
  601. }
  602. }
  603. }
  604. }
  605. return $adjustedQuestions;
  606. }
  607. }