AssembleExamTaskJob.php 29 KB

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