IntelligentExamController.php 50 KB

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