IntelligentExamController.php 48 KB

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