AssembleExamTaskJob.php 29 KB

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