IntelligentExamController.php 49 KB

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