IntelligentExamController.php 48 KB

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