AssembleExamTaskJob.php 25 KB

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