IntelligentExamController.php 48 KB

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