IntelligentExamController.php 48 KB

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