IntelligentExamController.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\MistakeRecord;
  5. use App\Models\Paper;
  6. use App\Models\Student;
  7. use App\Services\ExamPdfExportService;
  8. use App\Services\ExternalIdService;
  9. use App\Services\LearningAnalyticsService;
  10. use App\Services\PaperPayloadService;
  11. use App\Services\QuestionBankService;
  12. use App\Services\TaskManager;
  13. use Illuminate\Http\JsonResponse;
  14. use Illuminate\Http\Request;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. class IntelligentExamController extends Controller
  18. {
  19. private LearningAnalyticsService $learningAnalyticsService;
  20. private QuestionBankService $questionBankService;
  21. private ExamPdfExportService $pdfExportService;
  22. private PaperPayloadService $paperPayloadService;
  23. private TaskManager $taskManager;
  24. private ExternalIdService $externalIdService;
  25. public function __construct(
  26. LearningAnalyticsService $learningAnalyticsService,
  27. QuestionBankService $questionBankService,
  28. ExamPdfExportService $pdfExportService,
  29. PaperPayloadService $paperPayloadService,
  30. TaskManager $taskManager,
  31. ExternalIdService $externalIdService
  32. ) {
  33. $this->learningAnalyticsService = $learningAnalyticsService;
  34. $this->questionBankService = $questionBankService;
  35. $this->pdfExportService = $pdfExportService;
  36. $this->paperPayloadService = $paperPayloadService;
  37. $this->taskManager = $taskManager;
  38. $this->externalIdService = $externalIdService;
  39. }
  40. /**
  41. * 外部API:生成智能试卷(异步模式)
  42. * 立即返回任务ID,PDF生成在后台进行,完成后通过回调通知
  43. */
  44. public function store(Request $request): JsonResponse
  45. {
  46. // 优先从body获取数据,不使用query params
  47. $payload = $request->json()->all();
  48. if (empty($payload)) {
  49. $payload = $request->all();
  50. }
  51. $normalized = $this->normalizePayload($payload);
  52. $validator = validator($normalized, [
  53. 'student_id' => 'required|string|min:1|regex:/^\\d+$/', // 接受字符串或数字类型,如"1764913638"或1764913638
  54. 'teacher_id' => 'required|string|min:1|regex:/^\\d+$/',
  55. 'paper_name' => 'nullable|string|max:255',
  56. 'grade' => 'required|integer|min:1|max:12', // 支持小学1-6、初中7-9、高中10-12
  57. 'student_name' => 'required|string|max:50',
  58. 'teacher_name' => 'required|string|max:50',
  59. 'total_questions' => 'nullable|integer|min:1|max:100',
  60. 'difficulty_category' => 'nullable|integer|in:0,1,2,3,4',
  61. 'kp_codes' => 'nullable|array',
  62. 'kp_codes.*' => 'string',
  63. 'skills' => 'nullable|array',
  64. 'skills.*' => 'string',
  65. 'question_type_ratio' => 'nullable|array',
  66. // 'difficulty_ratio' 参数已废弃,使用 difficulty_category 控制难度分布
  67. 'total_score' => 'nullable|numeric|min:1|max:1000',
  68. 'mistake_ids' => 'nullable|array',
  69. 'mistake_ids.*' => 'string',
  70. 'mistake_question_ids' => 'nullable|array',
  71. 'mistake_question_ids.*' => 'string',
  72. 'callback_url' => 'nullable|url', // 异步完成后推送通知的URL
  73. // 新增:组卷类型
  74. 'assemble_type' => 'nullable|integer|in:0,1,2,3,4,5,8,9',
  75. 'exam_type' => 'nullable|string|in:general,diagnostic,practice,mistake,textbook,knowledge,knowledge_points',
  76. // 错题本类型专用参数
  77. 'paper_ids' => 'nullable|array',
  78. 'paper_ids.*' => 'string',
  79. // 修改:使用series_id + semester_code + grade替代textbook_id
  80. 'series_id' => 'nullable|integer|min:1', // 教材系列ID(替代textbook_id)
  81. 'semester_code' => 'nullable|integer|in:1,2', // 上下册:1=上册,2=下册
  82. // 新增:各组卷类型的专用参数
  83. 'chapter_id_list' => 'nullable|array', // 教材组卷专用
  84. 'chapter_id_list.*' => 'integer|min:1',
  85. 'kp_code_list' => 'nullable|array', // 知识点组卷专用
  86. 'kp_code_list.*' => 'string',
  87. 'end_catalog_id' => 'nullable|integer|min:1', // 摸底专用:截止章节ID
  88. // 新增:专项练习选项
  89. 'practice_options' => 'nullable|array',
  90. 'practice_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  91. 'practice_options.intensity' => 'nullable|string|in:low,medium,high',
  92. 'practice_options.include_new_questions' => 'nullable|boolean',
  93. 'practice_options.focus_weaknesses' => 'nullable|boolean',
  94. // 新增:错题选项
  95. 'mistake_options' => 'nullable|array',
  96. 'mistake_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  97. 'mistake_options.review_mistakes' => 'nullable|boolean',
  98. 'mistake_options.intensity' => 'nullable|string|in:low,medium,high',
  99. 'mistake_options.include_new_questions' => 'nullable|boolean',
  100. 'mistake_options.focus_weaknesses' => 'nullable|boolean',
  101. // 新增:按知识点组卷选项
  102. 'knowledge_points_options' => 'nullable|array',
  103. 'knowledge_points_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  104. 'knowledge_points_options.intensity' => 'nullable|string|in:low,medium,high',
  105. 'knowledge_points_options.focus_weaknesses' => 'nullable|boolean',
  106. ]);
  107. if ($validator->fails()) {
  108. return response()->json([
  109. 'success' => false,
  110. 'message' => '参数错误',
  111. 'errors' => $validator->errors()->toArray(),
  112. ], 422);
  113. }
  114. $data = $validator->validated();
  115. $data['total_questions'] = $data['total_questions'] ?? 20;
  116. $this->ensureStudentTeacherRelation($data);
  117. // 【修改】使用series_id、semester_code和grade获取textbook_id
  118. $textbookId = $this->resolveTextbookId($data);
  119. if ($textbookId) {
  120. $data['textbook_id'] = $textbookId;
  121. }
  122. // 确保 kp_codes 是数组
  123. $data['kp_codes'] = $data['kp_codes'] ?? [];
  124. if (! is_array($data['kp_codes'])) {
  125. $data['kp_codes'] = [];
  126. }
  127. $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
  128. // 注意: difficulty_ratio 参数已废弃,使用 difficulty_category 控制难度分布
  129. $paperName = $data['paper_name'] ?? ('智能试卷_'.now()->format('Ymd_His'));
  130. $difficultyCategory = $data['difficulty_category'] ?? 1; // 直接使用数字,不转换
  131. $mistakeIds = $data['mistake_ids'] ?? [];
  132. $mistakeQuestionIds = $data['mistake_question_ids'] ?? [];
  133. $paperIds = $data['paper_ids'] ?? [];
  134. $assembleType = $data['assemble_type'] ?? 4; // 默认为通用类型(4)
  135. try {
  136. $questions = [];
  137. $result = null;
  138. // 【新增】初始化章节摸底和智能组卷的关键字段
  139. $diagnosticChapterId = null;
  140. $explanationKpCodes = null;
  141. if (! empty($mistakeIds) || ! empty($mistakeQuestionIds)) {
  142. $questionIds = $this->resolveMistakeQuestionIds(
  143. $data['student_id'],
  144. $mistakeIds,
  145. $mistakeQuestionIds
  146. );
  147. if (empty($questionIds)) {
  148. return response()->json([
  149. 'success' => false,
  150. 'message' => '未找到可用的错题题目,请检查错题ID或学生ID',
  151. ], 400);
  152. }
  153. $bankQuestions = $this->questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
  154. if (empty($bankQuestions)) {
  155. return response()->json([
  156. 'success' => false,
  157. 'message' => '错题对应的题库题目不存在或不可用',
  158. ], 400);
  159. }
  160. $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes']);
  161. $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
  162. $paperName = $data['paper_name'] ?? ('错题复习_'.$data['student_id'].'_'.now()->format('Ymd_His'));
  163. } else {
  164. // 第一步:生成智能试卷(同步)
  165. $params = [
  166. 'student_id' => $data['student_id'],
  167. 'grade' => $data['grade'] ?? null,
  168. 'total_questions' => $data['total_questions'],
  169. // 【修复】教材组卷时不使用用户传入的kp_codes,只使用章节关联的知识点
  170. 'kp_codes' => $assembleType == 3 ? null : ($data['kp_codes'] ?? null),
  171. 'skills' => $data['skills'] ?? [],
  172. 'question_type_ratio' => $questionTypeRatio,
  173. 'difficulty_category' => $difficultyCategory, // 传递难度分类(数字)
  174. 'assemble_type' => $assembleType, // 新版组卷类型
  175. 'exam_type' => $data['exam_type'] ?? 'general', // 兼容旧版参数
  176. 'paper_ids' => $paperIds, // 错题本类型专用参数
  177. 'textbook_id' => $data['textbook_id'] ?? null, // 摸底和智能组卷专用
  178. 'end_catalog_id' => $data['end_catalog_id'] ?? null, // 摸底专用:截止章节ID
  179. 'chapter_id_list' => $data['chapter_id_list'] ?? null, // 教材组卷专用
  180. 'kp_code_list' => $assembleType == 3 ? null : ($data['kp_code_list'] ?? $data['kp_codes'] ?? []), // 知识点组卷专用
  181. 'practice_options' => $data['practice_options'] ?? null, // 传递专项练习选项
  182. 'mistake_options' => $data['mistake_options'] ?? null, // 传递错题选项
  183. ];
  184. $result = $this->learningAnalyticsService->generateIntelligentExam($params);
  185. if (empty($result['success'])) {
  186. $errorMsg = $result['message'] ?? '智能出卷失败';
  187. Log::error('智能出卷失败', [
  188. 'student_id' => $data['student_id'],
  189. 'error' => $result,
  190. ]);
  191. // 提供更详细的错误信息
  192. if (strpos($errorMsg, '超时') !== false) {
  193. $errorMsg = '服务响应超时,请稍后重试';
  194. } elseif (strpos($errorMsg, '连接') !== false) {
  195. $errorMsg = '依赖服务连接失败,请检查服务状态';
  196. }
  197. return response()->json([
  198. 'success' => false,
  199. 'message' => $errorMsg,
  200. 'details' => $result['details'] ?? null,
  201. ], 400);
  202. }
  203. if (isset($result['stats']['difficulty_category'])) {
  204. $difficultyCategory = $result['stats']['difficulty_category'];
  205. }
  206. // 【新增】提取章节摸底和智能组卷的关键字段
  207. $diagnosticChapterId = $result['diagnostic_chapter_id'] ?? null;
  208. $explanationKpCodes = $result['explanation_kp_codes'] ?? null;
  209. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
  210. }
  211. if (empty($questions)) {
  212. return response()->json([
  213. 'success' => false,
  214. 'message' => '未能生成有效题目,请检查知识点或题库数据',
  215. ], 400);
  216. }
  217. // 错题本类型不需要限制题目数量,由错题数量决定
  218. if ($assembleType === 5) {
  219. // 错题本:使用所有错题,不限制数量
  220. Log::info('错题本类型,使用所有错题', [
  221. 'assemble_type' => $assembleType,
  222. 'question_count' => count($questions),
  223. ]);
  224. } else {
  225. // 其他类型:限制题目数量
  226. $totalQuestions = min($data['total_questions'], count($questions));
  227. $questions = array_slice($questions, 0, $totalQuestions);
  228. }
  229. // 调整题目分值,确保符合目标总分
  230. $targetTotalScore = $data['total_score'] ?? 100.0;
  231. $questions = $this->adjustQuestionScores($questions, $targetTotalScore);
  232. // 计算总分
  233. $totalScore = array_sum(array_column($questions, 'score'));
  234. // 第二步:保存试卷到数据库(同步)
  235. // 【修复】策略可能修改assembleType(如章节智能组卷检测到全部掌握后转为下一章节摸底)
  236. $finalAssembleType = ($result !== null && isset($result['assemble_type'])) ? $result['assemble_type'] : $assembleType;
  237. $paperId = $this->questionBankService->saveExamToDatabase([
  238. 'paper_name' => $paperName,
  239. 'student_id' => $data['student_id'],
  240. 'teacher_id' => $data['teacher_id'] ?? null,
  241. 'assembleType' => $finalAssembleType,
  242. 'difficulty_category' => $difficultyCategory,
  243. 'total_score' => $totalScore, // 使用计算后的实际总分
  244. 'questions' => $questions,
  245. // 【新增】章节摸底和智能组卷的关键字段
  246. 'diagnostic_chapter_id' => $diagnosticChapterId ?? null,
  247. 'explanation_kp_codes' => $explanationKpCodes ?? null,
  248. ]);
  249. if (! $paperId) {
  250. return response()->json([
  251. 'success' => false,
  252. 'message' => '试卷保存失败',
  253. ], 500);
  254. }
  255. // 第三步:创建异步任务(使用TaskManager)
  256. // 注意:callback_url会在TaskManager中被提取并保存
  257. $taskId = $this->taskManager->createTask(TaskManager::TASK_TYPE_EXAM, array_merge($data, ['paper_id' => $paperId]));
  258. // 生成识别码
  259. $codes = $this->paperPayloadService->generatePaperCodes($paperId);
  260. // 立即返回完整的试卷数据(不等待PDF生成)
  261. $paperModel = Paper::with('questions')->find($paperId);
  262. $examContent = $paperModel
  263. ? $this->paperPayloadService->buildExamContent($paperModel)
  264. : [];
  265. $finalStats = $result['stats'] ?? [
  266. 'total_selected' => count($questions),
  267. 'mistake_based' => ! empty($mistakeIds) || ! empty($mistakeQuestionIds),
  268. ];
  269. if (! isset($finalStats['difficulty_category'])) {
  270. $finalStats['difficulty_category'] = $difficultyCategory;
  271. }
  272. if (! isset($finalStats['final_distribution'])) {
  273. $distributionService = app(\App\Services\DifficultyDistributionService::class);
  274. $finalBuckets = $distributionService->groupQuestionsByDifficultyRange($questions, (int) $difficultyCategory);
  275. $finalTotal = max(1, count($questions));
  276. $finalStats['final_distribution'] = array_map(static function ($bucket) use ($finalTotal) {
  277. $count = count($bucket);
  278. return [
  279. 'count' => $count,
  280. 'ratio' => round(($count / $finalTotal) * 100, 2),
  281. ];
  282. }, $finalBuckets);
  283. }
  284. if (! isset($finalStats['final_distribution_shortage'])) {
  285. $distributionService = app(\App\Services\DifficultyDistributionService::class);
  286. $distribution = $distributionService->calculateDistribution((int) $difficultyCategory, (int) ($data['total_questions'] ?? count($questions)));
  287. $buckets = $distributionService->groupQuestionsByDifficultyRange($questions, (int) $difficultyCategory);
  288. $expected = [
  289. 'primary_low' => 0,
  290. 'primary_medium' => 0,
  291. 'primary_high' => 0,
  292. 'secondary' => 0,
  293. 'other' => 0,
  294. ];
  295. foreach ($distribution as $level => $config) {
  296. $bucketKey = $distributionService->mapDifficultyLevelToRangeKey($level, (int) $difficultyCategory);
  297. $expected[$bucketKey] += (int) ($config['count'] ?? 0);
  298. }
  299. $actual = array_map(static fn($bucket) => count($bucket), $buckets);
  300. $finalStats['final_distribution_shortage'] = array_map(static function ($count, $bucketKey) use ($actual) {
  301. $actualCount = $actual[$bucketKey] ?? 0;
  302. return [
  303. 'expected' => $count,
  304. 'actual' => $actualCount,
  305. 'short' => max(0, $count - $actualCount),
  306. ];
  307. }, $expected, array_keys($expected));
  308. }
  309. $this->taskManager->updateTaskStatus($taskId, [
  310. 'stats' => $finalStats,
  311. ]);
  312. // 触发后台PDF生成
  313. $this->triggerPdfGeneration($taskId, $paperId);
  314. $payload = [
  315. 'success' => true,
  316. 'message' => '智能试卷创建成功,PDF正在后台生成...',
  317. 'data' => [
  318. 'task_id' => $taskId,
  319. 'paper_id' => $paperId,
  320. 'status' => 'processing',
  321. // 识别码
  322. 'exam_code' => $codes['exam_code'], // 试卷识别码 (1+12位)
  323. 'grading_code' => $codes['grading_code'], // 判卷识别码 (2+12位)
  324. 'paper_id_num' => $codes['paper_id_num'], // 12位数字ID
  325. 'exam_content' => $examContent,
  326. 'urls' => [
  327. 'grading_url' => route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]),
  328. 'student_exam_url' => route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']),
  329. 'knowledge_explanation_url' => route('filament.admin.auth.intelligent-exam.knowledge-explanation', ['paper_id' => $paperId]),
  330. ],
  331. 'pdfs' => [
  332. 'exam_paper_pdf' => null,
  333. 'grading_pdf' => null,
  334. ],
  335. 'stats' => $finalStats,
  336. 'created_at' => now()->toISOString(),
  337. ],
  338. ];
  339. return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);
  340. } catch (\Exception $e) {
  341. Log::error('Intelligent exam API failed', [
  342. 'error' => $e->getMessage(),
  343. 'trace' => $e->getTraceAsString(),
  344. ]);
  345. // 返回更具体的错误信息
  346. $errorMessage = $e->getMessage();
  347. if (strpos($errorMessage, 'Connection') !== false || strpos($errorMessage, 'connection') !== false) {
  348. $errorMessage = '依赖服务连接失败,请检查服务状态';
  349. } elseif (strpos($errorMessage, 'timeout') !== false || strpos($errorMessage, '超时') !== false) {
  350. $errorMessage = '服务响应超时,请稍后重试';
  351. } elseif (strpos($errorMessage, 'not found') !== false || strpos($errorMessage, '未找到') !== false) {
  352. $errorMessage = '请求的资源不存在';
  353. } elseif (strpos($errorMessage, 'invalid') !== false || strpos($errorMessage, '无效') !== false) {
  354. $errorMessage = '请求参数无效';
  355. }
  356. return response()->json([
  357. 'success' => false,
  358. 'message' => $errorMessage ?: '服务异常,请稍后重试',
  359. ], 500);
  360. }
  361. }
  362. /**
  363. * 轮询任务状态
  364. */
  365. public function status(string $taskId): JsonResponse
  366. {
  367. try {
  368. $task = $this->taskManager->getTaskStatus($taskId);
  369. if (! $task) {
  370. return response()->json([
  371. 'success' => false,
  372. 'message' => '任务不存在',
  373. ], 404);
  374. }
  375. return response()->json([
  376. 'success' => true,
  377. 'data' => $task,
  378. ]);
  379. } catch (\Exception $e) {
  380. Log::error('查询任务状态失败', [
  381. 'task_id' => $taskId,
  382. 'error' => $e->getMessage(),
  383. ]);
  384. return response()->json([
  385. 'success' => false,
  386. 'message' => '查询失败,请稍后重试',
  387. ], 500);
  388. }
  389. }
  390. /**
  391. * 触发PDF生成
  392. * 使用队列进行异步处理
  393. */
  394. private function triggerPdfGeneration(string $taskId, string $paperId): void
  395. {
  396. // 异步处理PDF生成 - 将任务放入队列
  397. try {
  398. dispatch(new \App\Jobs\GenerateExamPdfJob($taskId, $paperId));
  399. Log::info('PDF生成任务已加入队列', [
  400. 'task_id' => $taskId,
  401. 'paper_id' => $paperId,
  402. ]);
  403. } catch (\Exception $e) {
  404. Log::error('PDF生成任务队列失败,不回退到同步处理', [
  405. 'task_id' => $taskId,
  406. 'paper_id' => $paperId,
  407. 'error' => $e->getMessage(),
  408. 'note' => '依赖队列重试机制,不进行同步处理以避免并发冲突',
  409. ]);
  410. // 【优化】不回退到同步处理,避免与队列任务并发冲突
  411. // 队列系统有重试机制,会自动处理失败情况
  412. // $this->processPdfGeneration($taskId, $paperId);
  413. }
  414. }
  415. /**
  416. * 处理PDF生成(模拟后台任务)
  417. * 在实际项目中,这个方法应该在队列worker中执行
  418. */
  419. private function processPdfGeneration(string $taskId, string $paperId): void
  420. {
  421. try {
  422. $this->taskManager->updateTaskProgress($taskId, 10, '开始生成试卷PDF...');
  423. // 生成试卷PDF
  424. $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
  425. ?? $this->questionBankService->exportExamToPdf($paperId)
  426. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  427. $this->taskManager->updateTaskProgress($taskId, 50, '试卷PDF生成完成,开始生成判卷PDF...');
  428. // 生成判卷PDF
  429. $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
  430. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  431. // 构建完整的试卷内容
  432. $paperModel = Paper::with('questions')->find($paperId);
  433. $examContent = $paperModel
  434. ? $this->paperPayloadService->buildExamContent($paperModel)
  435. : [];
  436. // 标记任务完成
  437. $this->taskManager->markTaskCompleted($taskId, [
  438. 'exam_content' => $examContent,
  439. 'pdfs' => [
  440. 'exam_paper_pdf' => $pdfUrl,
  441. 'grading_pdf' => $gradingPdfUrl,
  442. ],
  443. ]);
  444. Log::info('异步任务完成', [
  445. 'task_id' => $taskId,
  446. 'paper_id' => $paperId,
  447. 'pdf_url' => $pdfUrl,
  448. 'grading_pdf_url' => $gradingPdfUrl,
  449. ]);
  450. // 发送回调通知
  451. $this->taskManager->sendCallback($taskId);
  452. } catch (\Exception $e) {
  453. Log::error('PDF生成失败', [
  454. 'task_id' => $taskId,
  455. 'paper_id' => $paperId,
  456. 'error' => $e->getMessage(),
  457. ]);
  458. $this->taskManager->markTaskFailed($taskId, $e->getMessage());
  459. }
  460. }
  461. /**
  462. * 兼容字符串/数组入参
  463. */
  464. private function normalizePayload(array $payload): array
  465. {
  466. // 处理 question_count 参数:转换为 total_questions
  467. if (isset($payload['question_count']) && ! isset($payload['total_questions'])) {
  468. $payload['total_questions'] = $payload['question_count'];
  469. unset($payload['question_count']);
  470. }
  471. // 将student_id转换为字符串(支持数字和字符串输入)
  472. if (isset($payload['student_id'])) {
  473. $payload['student_id'] = (string) $payload['student_id'];
  474. }
  475. if (isset($payload['teacher_id'])) {
  476. $payload['teacher_id'] = (string) $payload['teacher_id'];
  477. }
  478. if (isset($payload['grade'])) {
  479. $payload['grade'] = (string) $payload['grade'];
  480. }
  481. // 处理 kp_codes:空字符串或null转换为空数组
  482. if (isset($payload['kp_codes'])) {
  483. if (is_string($payload['kp_codes'])) {
  484. $kpCodes = trim($payload['kp_codes']);
  485. if (empty($kpCodes)) {
  486. $payload['kp_codes'] = [];
  487. } else {
  488. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
  489. }
  490. } elseif (! is_array($payload['kp_codes'])) {
  491. $payload['kp_codes'] = [];
  492. }
  493. } else {
  494. $payload['kp_codes'] = [];
  495. }
  496. if (isset($payload['skills']) && is_string($payload['skills'])) {
  497. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  498. }
  499. foreach (['mistake_ids', 'mistake_question_ids'] as $key) {
  500. if (isset($payload[$key])) {
  501. if (is_string($payload[$key])) {
  502. $raw = trim($payload[$key]);
  503. $payload[$key] = $raw === ''
  504. ? []
  505. : array_values(array_filter(array_map('trim', explode(',', $raw))));
  506. } elseif (! is_array($payload[$key])) {
  507. $payload[$key] = [];
  508. }
  509. }
  510. }
  511. // 新增:处理组卷专用参数
  512. foreach (['chapter_id_list', 'kp_code_list'] as $key) {
  513. if (isset($payload[$key])) {
  514. if (is_string($payload[$key])) {
  515. $raw = trim($payload[$key]);
  516. $payload[$key] = $raw === ''
  517. ? []
  518. : array_values(array_filter(array_map('trim', explode(',', $raw))));
  519. } elseif (! is_array($payload[$key])) {
  520. $payload[$key] = [];
  521. }
  522. } else {
  523. $payload[$key] = [];
  524. }
  525. }
  526. // 【修改】处理series_id:字符串转换为整数
  527. if (isset($payload['series_id'])) {
  528. if (is_string($payload['series_id'])) {
  529. $payload['series_id'] = (int) trim($payload['series_id']);
  530. if ($payload['series_id'] <= 0) {
  531. unset($payload['series_id']);
  532. }
  533. } elseif (! is_int($payload['series_id']) || $payload['series_id'] <= 0) {
  534. unset($payload['series_id']);
  535. }
  536. }
  537. // 【新增】处理semester_code:确保是1或2
  538. if (isset($payload['semester_code'])) {
  539. if (is_string($payload['semester_code'])) {
  540. $payload['semester_code'] = (int) trim($payload['semester_code']);
  541. }
  542. // 只保留1或2,其他值都移除
  543. if (! in_array($payload['semester_code'], [1, 2], true)) {
  544. unset($payload['semester_code']);
  545. }
  546. }
  547. // 新增:处理组卷类型,默认值为 general
  548. if (! isset($payload['exam_type'])) {
  549. $payload['exam_type'] = 'general';
  550. }
  551. // 新增:处理专项练习选项
  552. if (isset($payload['practice_options'])) {
  553. if (is_string($payload['practice_options'])) {
  554. $decoded = json_decode($payload['practice_options'], true);
  555. $payload['practice_options'] = is_array($decoded) ? $decoded : [];
  556. } elseif (! is_array($payload['practice_options'])) {
  557. $payload['practice_options'] = [];
  558. }
  559. // 设置默认值
  560. $payload['practice_options'] = array_merge([
  561. 'weakness_threshold' => 0.7,
  562. 'intensity' => 'medium',
  563. 'include_new_questions' => true,
  564. 'focus_weaknesses' => true,
  565. ], $payload['practice_options']);
  566. } else {
  567. // 如果没有提供 practice_options,创建默认值
  568. $payload['practice_options'] = [
  569. 'weakness_threshold' => 0.7,
  570. 'intensity' => 'medium',
  571. 'include_new_questions' => true,
  572. 'focus_weaknesses' => true,
  573. ];
  574. }
  575. // 新增:处理错题选项
  576. if (isset($payload['mistake_options'])) {
  577. if (is_string($payload['mistake_options'])) {
  578. $decoded = json_decode($payload['mistake_options'], true);
  579. $payload['mistake_options'] = is_array($decoded) ? $decoded : [];
  580. } elseif (! is_array($payload['mistake_options'])) {
  581. $payload['mistake_options'] = [];
  582. }
  583. // 设置默认值
  584. $payload['mistake_options'] = array_merge([
  585. 'weakness_threshold' => 0.7,
  586. 'review_mistakes' => true,
  587. 'intensity' => 'medium',
  588. 'include_new_questions' => true,
  589. 'focus_weaknesses' => true,
  590. ], $payload['mistake_options']);
  591. } else {
  592. // 如果没有提供 mistake_options,创建默认值
  593. $payload['mistake_options'] = [
  594. 'weakness_threshold' => 0.7,
  595. 'review_mistakes' => true,
  596. 'intensity' => 'medium',
  597. 'include_new_questions' => true,
  598. 'focus_weaknesses' => true,
  599. ];
  600. }
  601. // 新增:处理按知识点组卷选项
  602. if (isset($payload['knowledge_points_options'])) {
  603. if (is_string($payload['knowledge_points_options'])) {
  604. $decoded = json_decode($payload['knowledge_points_options'], true);
  605. $payload['knowledge_points_options'] = is_array($decoded) ? $decoded : [];
  606. } elseif (! is_array($payload['knowledge_points_options'])) {
  607. $payload['knowledge_points_options'] = [];
  608. }
  609. // 设置默认值
  610. $payload['knowledge_points_options'] = array_merge([
  611. 'weakness_threshold' => 0.7,
  612. 'intensity' => 'medium',
  613. 'focus_weaknesses' => true,
  614. ], $payload['knowledge_points_options']);
  615. } else {
  616. // 如果没有提供 knowledge_points_options,创建默认值
  617. $payload['knowledge_points_options'] = [
  618. 'weakness_threshold' => 0.7,
  619. 'intensity' => 'medium',
  620. 'focus_weaknesses' => true,
  621. ];
  622. }
  623. return $payload;
  624. }
  625. private function ensureStudentTeacherRelation(array $data): void
  626. {
  627. $studentId = (int) $data['student_id'];
  628. $teacherId = (int) $data['teacher_id'];
  629. $studentName = (string) ($data['student_name'] ?? '未知学生');
  630. $teacherName = (string) ($data['teacher_name'] ?? '未知教师');
  631. $grade = (string) ($data['grade'] ?? '未知年级');
  632. $teacher = $this->externalIdService->handleTeacherExternalId($teacherId, [
  633. 'name' => $teacherName,
  634. 'subject' => '数学',
  635. ]);
  636. $student = Student::where('student_id', $studentId)->first();
  637. if ($student) {
  638. $updates = [];
  639. if ($studentName !== '' && $student->name !== $studentName) {
  640. $updates['name'] = $studentName;
  641. }
  642. if ($grade !== '' && $student->grade !== $grade) {
  643. $updates['grade'] = $grade;
  644. }
  645. if ($teacherId > 0 && (int) $student->teacher_id !== $teacherId) {
  646. $updates['teacher_id'] = $teacherId;
  647. }
  648. if (! empty($updates)) {
  649. $student->update($updates);
  650. }
  651. return;
  652. }
  653. $this->externalIdService->handleStudentExternalId($studentId, [
  654. 'name' => $studentName,
  655. 'grade' => $grade,
  656. 'teacher_id' => $teacherId,
  657. ]);
  658. }
  659. private function normalizeQuestionTypeRatio(array $input): array
  660. {
  661. // 默认按 4:2:4
  662. $defaults = [
  663. '选择题' => 40,
  664. '填空题' => 20,
  665. '解答题' => 40,
  666. ];
  667. $normalized = [];
  668. foreach ($input as $key => $value) {
  669. if (! is_numeric($value)) {
  670. continue;
  671. }
  672. $type = $this->normalizeQuestionTypeKey($key);
  673. if ($type) {
  674. $normalized[$type] = (float) $value;
  675. }
  676. }
  677. $merged = array_merge($defaults, $normalized);
  678. // 归一化到 100%
  679. $sum = array_sum($merged);
  680. if ($sum > 0) {
  681. foreach ($merged as $k => $v) {
  682. $merged[$k] = round(($v / $sum) * 100, 2);
  683. }
  684. }
  685. return $merged;
  686. }
  687. private function normalizeQuestionTypeKey(string $key): ?string
  688. {
  689. $key = trim($key);
  690. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  691. return '选择题';
  692. }
  693. if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
  694. return '填空题';
  695. }
  696. if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  697. return '解答题';
  698. }
  699. return null;
  700. }
  701. private function normalizeDifficultyRatio(array $input): array
  702. {
  703. $defaults = [
  704. '基础' => 50,
  705. '中等' => 35,
  706. '拔高' => 15,
  707. ];
  708. $normalized = [];
  709. foreach ($input as $key => $value) {
  710. if (! is_numeric($value)) {
  711. continue;
  712. }
  713. $label = trim($key);
  714. if (in_array($label, ['基础', 'easy', '简单'])) {
  715. $normalized['基础'] = (float) $value;
  716. } elseif (in_array($label, ['中等', 'medium'])) {
  717. $normalized['中等'] = (float) $value;
  718. } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
  719. $normalized['拔高'] = (float) $value;
  720. }
  721. }
  722. return array_merge($defaults, $normalized);
  723. }
  724. private function hydrateQuestions(array $questions, array $kpCodes): array
  725. {
  726. $normalized = [];
  727. foreach ($questions as $question) {
  728. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  729. $score = $question['score'] ?? $this->defaultScore($type);
  730. $normalized[] = [
  731. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  732. 'question_id' => $question['question_id'] ?? null,
  733. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  734. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  735. 'content' => $question['content'] ?? $question['stem'] ?? '',
  736. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  737. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  738. 'solution' => $question['solution'] ?? '',
  739. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  740. 'score' => $score,
  741. 'estimated_time' => $question['estimated_time'] ?? 300,
  742. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  743. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  744. ];
  745. }
  746. return array_values(array_filter($normalized, fn ($q) => ! empty($q['id'])));
  747. }
  748. private function guessType(array $question): string
  749. {
  750. if (! empty($question['options']) && is_array($question['options'])) {
  751. return '选择题';
  752. }
  753. $content = $question['stem'] ?? $question['content'] ?? '';
  754. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  755. return '填空题';
  756. }
  757. return '解答题';
  758. }
  759. /**
  760. * 根据题目类型获取默认分值(中国中学卷子标准)
  761. * 选择题:5分/题,填空题:5分/题,解答题:10分/题
  762. */
  763. private function defaultScore(string $type): int
  764. {
  765. return match ($type) {
  766. '选择题' => 5,
  767. '填空题' => 5,
  768. '解答题' => 10,
  769. default => 5,
  770. };
  771. }
  772. /**
  773. * 计算试卷总分并调整各题目分值,确保总分接近目标分数
  774. * 符合中国中学卷子标准:
  775. * - 选择题:约40%总分(每题4-6分,整数分值)
  776. * - 填空题:约25%总分(每题4-6分,整数分值)
  777. * - 解答题:约35%总分(每题8-12分,整数分值)
  778. * 使用组合优化算法确保:
  779. * 1. 所有分值都是整数(无小数点)
  780. * 2. 同类型题目分值均匀
  781. * 3. 总分精确匹配目标分数(或最接近)
  782. */
  783. private function adjustQuestionScores(array $questions, float $targetTotalScore = 100.0): array
  784. {
  785. if (empty($questions)) {
  786. return $questions;
  787. }
  788. // 第一步:按题型排序
  789. $sortedQuestions = [];
  790. $choiceQuestions = [];
  791. $fillQuestions = [];
  792. $answerQuestions = [];
  793. foreach ($questions as $question) {
  794. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  795. if ($type === 'choice') {
  796. $choiceQuestions[] = $question;
  797. } elseif ($type === 'fill') {
  798. $fillQuestions[] = $question;
  799. } else {
  800. $answerQuestions[] = $question;
  801. }
  802. }
  803. $sortedQuestions = array_merge($choiceQuestions, $fillQuestions, $answerQuestions);
  804. // 调试日志
  805. \Illuminate\Support\Facades\Log::info('adjustQuestionScores 开始', [
  806. 'choice_count' => count($choiceQuestions),
  807. 'fill_count' => count($fillQuestions),
  808. 'answer_count' => count($answerQuestions),
  809. ]);
  810. // 重新编号
  811. foreach ($sortedQuestions as $idx => &$question) {
  812. $question['question_number'] = $idx + 1;
  813. }
  814. unset($question);
  815. // 各题型数量
  816. $typeCounts = [
  817. 'choice' => count($choiceQuestions),
  818. 'fill' => count($fillQuestions),
  819. 'answer' => count($answerQuestions),
  820. ];
  821. // 记录各题型索引
  822. $typeIndexes = ['choice' => [], 'fill' => [], 'answer' => []];
  823. foreach ($sortedQuestions as $index => $question) {
  824. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  825. $typeIndexes[$type][] = $index;
  826. }
  827. // 第二步:分配分值
  828. $questionScores = [];
  829. $totalQuestions = $typeCounts['choice'] + $typeCounts['fill'] + $typeCounts['answer'];
  830. $globalBaseScore = floor($targetTotalScore / $totalQuestions);
  831. $globalBaseScore = max(1, $globalBaseScore);
  832. // 确定题型处理顺序(基于 sortedQuestions 中的顺序)
  833. $typeOrder = [];
  834. foreach ($sortedQuestions as $question) {
  835. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  836. if (! in_array($type, $typeOrder)) {
  837. $typeOrder[] = $type;
  838. }
  839. }
  840. // 记录当前剩余预算
  841. $remainingBudget = $targetTotalScore;
  842. // 按顺序处理每种题型
  843. foreach ($typeOrder as $typeIndex => $type) {
  844. $count = $typeCounts[$type];
  845. if ($count === 0) {
  846. continue;
  847. }
  848. if ($typeIndex === 0) {
  849. // 第一个题型:拿平均分,然后都-1
  850. $thisBase = $globalBaseScore;
  851. foreach ($typeIndexes[$type] as $idx) {
  852. $questionScores[$idx] = $thisBase;
  853. }
  854. // 都-1
  855. foreach ($typeIndexes[$type] as $idx) {
  856. $questionScores[$idx] = max(1, $questionScores[$idx] - 1);
  857. }
  858. // 计算已分配的分数
  859. $allocated = 0;
  860. foreach ($typeIndexes[$type] as $idx) {
  861. $allocated += $questionScores[$idx];
  862. }
  863. $remainingBudget -= $allocated;
  864. } elseif ($typeIndex === count($typeOrder) - 1) {
  865. // 最后一个题型:用剩余分数分配
  866. $thisBase = floor($remainingBudget / $count);
  867. $thisBase = max(1, $thisBase);
  868. foreach ($typeIndexes[$type] as $idx) {
  869. $questionScores[$idx] = $thisBase;
  870. }
  871. // 余数补偿:分散到多道题,从后往前各+1
  872. $total = $thisBase * $count;
  873. $remainder = $remainingBudget - $total;
  874. if ($remainder > 0) {
  875. // 从最后一道题开始,往前 $remainder 道题各+1
  876. $answerIndexes = array_values($typeIndexes[$type]);
  877. $startIdx = max(0, count($answerIndexes) - $remainder);
  878. for ($i = $startIdx; $i < count($answerIndexes); $i++) {
  879. $questionScores[$answerIndexes[$i]] += 1;
  880. }
  881. }
  882. } else {
  883. // 中间的题型:直接用全局平均分(不减)
  884. $thisBase = $globalBaseScore;
  885. foreach ($typeIndexes[$type] as $idx) {
  886. $questionScores[$idx] = $thisBase;
  887. }
  888. // 计算已分配的分数
  889. $allocated = 0;
  890. foreach ($typeIndexes[$type] as $idx) {
  891. $allocated += $questionScores[$idx];
  892. }
  893. $remainingBudget -= $allocated;
  894. }
  895. }
  896. // 第三步:确保最后一类题型分数 > 前面所有题型
  897. if (count($typeOrder) > 1) {
  898. $lastType = end($typeOrder);
  899. $otherTypes = array_slice($typeOrder, 0, -1);
  900. // 前面题型的最高分
  901. $maxOtherScore = 0;
  902. foreach ($otherTypes as $type) {
  903. foreach ($typeIndexes[$type] as $idx) {
  904. $maxOtherScore = max($maxOtherScore, $questionScores[$idx]);
  905. }
  906. }
  907. // 最后一类题型的最低分
  908. $minLastScore = PHP_INT_MAX;
  909. foreach ($typeIndexes[$lastType] as $idx) {
  910. $minLastScore = min($minLastScore, $questionScores[$idx]);
  911. }
  912. // 如果最后一类不够高,从前面扣分
  913. if ($minLastScore <= $maxOtherScore) {
  914. $diff = $maxOtherScore - $minLastScore + 1;
  915. // 从前面题型扣分(每道最多扣2分)
  916. $reductionPerQuestion = min($diff, 2);
  917. foreach ($otherTypes as $type) {
  918. foreach ($typeIndexes[$type] as $idx) {
  919. $questionScores[$idx] = max(1, $questionScores[$idx] - $reductionPerQuestion);
  920. }
  921. }
  922. // 重新计算剩余给最后一类
  923. $reallocated = $targetTotalScore;
  924. foreach ($typeIndexes[$lastType] as $idx) {
  925. $reallocated -= $questionScores[$idx];
  926. }
  927. foreach ($otherTypes as $type) {
  928. foreach ($typeIndexes[$type] as $idx) {
  929. $reallocated -= $questionScores[$idx];
  930. }
  931. }
  932. if ($reallocated > 0) {
  933. $newBase = floor($reallocated / $typeCounts[$lastType]);
  934. foreach ($typeIndexes[$lastType] as $idx) {
  935. $questionScores[$idx] = $newBase;
  936. }
  937. $total = $newBase * $typeCounts[$lastType];
  938. $remainder = $reallocated - $total;
  939. if ($remainder > 0) {
  940. // 余数分散到多道题,从后往前各+1
  941. $lastIndexes = array_values($typeIndexes[$lastType]);
  942. $startIdx = max(0, count($lastIndexes) - $remainder);
  943. for ($i = $startIdx; $i < count($lastIndexes); $i++) {
  944. $questionScores[$lastIndexes[$i]] += 1;
  945. }
  946. }
  947. }
  948. }
  949. }
  950. // 第三步:构建结果
  951. $adjustedQuestions = [];
  952. foreach ($sortedQuestions as $index => $question) {
  953. $adjustedQuestions[$index] = $question;
  954. $adjustedQuestions[$index]['score'] = $questionScores[$index] ?? 5;
  955. }
  956. $total = array_sum(array_column($adjustedQuestions, 'score'));
  957. $diff = (int) $targetTotalScore - (int) $total;
  958. if ($diff !== 0 && ! empty($adjustedQuestions)) {
  959. $count = count($adjustedQuestions);
  960. $i = $count - 1;
  961. while ($diff !== 0) {
  962. $score = $adjustedQuestions[$i]['score'];
  963. if ($diff > 0) {
  964. $adjustedQuestions[$i]['score'] = $score + 1;
  965. $diff--;
  966. } else {
  967. if ($score > 1) {
  968. $adjustedQuestions[$i]['score'] = $score - 1;
  969. $diff++;
  970. }
  971. }
  972. $i--;
  973. if ($i < 0) {
  974. $i = $count - 1;
  975. if ($diff < 0) {
  976. $minScore = min(array_column($adjustedQuestions, 'score'));
  977. if ($minScore <= 1) {
  978. break;
  979. }
  980. }
  981. }
  982. }
  983. }
  984. return $adjustedQuestions;
  985. }
  986. /**
  987. * 标准化题目类型
  988. */
  989. private function normalizeQuestionType(string $type): string
  990. {
  991. $type = strtolower(trim($type));
  992. if (in_array($type, ['choice', 'single_choice', 'multiple_choice', '选择题', '单选', '多选'], true)) {
  993. return 'choice';
  994. }
  995. if (in_array($type, ['fill', 'fill_in_the_blank', 'blank', '填空题', '填空'], true)) {
  996. return 'fill';
  997. }
  998. return 'answer';
  999. }
  1000. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  1001. {
  1002. $questionIds = [];
  1003. if (! empty($mistakeQuestionIds)) {
  1004. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  1005. }
  1006. if (! empty($mistakeIds)) {
  1007. $mistakeQuestionIdsFromDb = MistakeRecord::query()
  1008. ->where('student_id', $studentId)
  1009. ->whereIn('id', $mistakeIds)
  1010. ->pluck('question_id')
  1011. ->filter()
  1012. ->values()
  1013. ->all();
  1014. $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
  1015. }
  1016. $questionIds = array_values(array_unique(array_filter($questionIds)));
  1017. return $questionIds;
  1018. }
  1019. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  1020. {
  1021. if (empty($requestedIds)) {
  1022. return $questions;
  1023. }
  1024. $order = array_flip($requestedIds);
  1025. usort($questions, function ($a, $b) use ($order) {
  1026. $aId = (string) ($a['id'] ?? '');
  1027. $bId = (string) ($b['id'] ?? '');
  1028. $aPos = $order[$aId] ?? PHP_INT_MAX;
  1029. $bPos = $order[$bId] ?? PHP_INT_MAX;
  1030. return $aPos <=> $bPos;
  1031. });
  1032. return $questions;
  1033. }
  1034. /**
  1035. * 【新增】根据series_id、semester_code和grade获取textbook_id
  1036. * 替代原来直接传入textbook_id的方式
  1037. */
  1038. private function resolveTextbookId(array $data): ?int
  1039. {
  1040. // 如果提供了series_id和semester_code,则查询textbook_id
  1041. $seriesId = $data['series_id'] ?? null;
  1042. $semesterCode = $data['semester_code'] ?? null;
  1043. $grade = $data['grade'] ?? null;
  1044. // 如果没有提供series_id或semester_code,则不设置textbook_id
  1045. if (! $seriesId || ! $semesterCode) {
  1046. return null;
  1047. }
  1048. try {
  1049. // 根据series_id、semester_code和grade查询textbooks表
  1050. $query = DB::connection('mysql')
  1051. ->table('textbooks')
  1052. ->where('series_id', $seriesId)
  1053. ->where('semester', $semesterCode);
  1054. // 如果提供了grade,可以作为额外筛选条件
  1055. if ($grade) {
  1056. $query->where('grade', $grade);
  1057. }
  1058. $textbook = $query->first();
  1059. if ($textbook) {
  1060. Log::info('成功解析textbook_id', [
  1061. 'series_id' => $seriesId,
  1062. 'semester_code' => $semesterCode,
  1063. 'grade' => $grade,
  1064. 'textbook_id' => $textbook->id,
  1065. ]);
  1066. return (int) $textbook->id;
  1067. }
  1068. Log::warning('未找到匹配的教材', [
  1069. 'series_id' => $seriesId,
  1070. 'semester_code' => $semesterCode,
  1071. 'grade' => $grade,
  1072. ]);
  1073. return null;
  1074. } catch (\Exception $e) {
  1075. Log::error('查询textbook_id失败', [
  1076. 'series_id' => $seriesId,
  1077. 'semester_code' => $semesterCode,
  1078. 'grade' => $grade,
  1079. 'error' => $e->getMessage(),
  1080. ]);
  1081. return null;
  1082. }
  1083. }
  1084. }