IntelligentExamController.php 48 KB

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