IntelligentExamController.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\MistakeRecord;
  5. use App\Models\Paper;
  6. use App\Models\Student;
  7. use App\Services\ExamPdfExportService;
  8. use App\Services\ExternalIdService;
  9. use App\Services\LearningAnalyticsService;
  10. use App\Services\PaperPayloadService;
  11. use App\Services\QuestionBankService;
  12. use App\Services\TaskManager;
  13. use Illuminate\Http\JsonResponse;
  14. use Illuminate\Http\Request;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. class IntelligentExamController extends Controller
  18. {
  19. private LearningAnalyticsService $learningAnalyticsService;
  20. private QuestionBankService $questionBankService;
  21. private ExamPdfExportService $pdfExportService;
  22. private PaperPayloadService $paperPayloadService;
  23. private TaskManager $taskManager;
  24. private ExternalIdService $externalIdService;
  25. public function __construct(
  26. LearningAnalyticsService $learningAnalyticsService,
  27. QuestionBankService $questionBankService,
  28. ExamPdfExportService $pdfExportService,
  29. PaperPayloadService $paperPayloadService,
  30. TaskManager $taskManager,
  31. ExternalIdService $externalIdService
  32. ) {
  33. $this->learningAnalyticsService = $learningAnalyticsService;
  34. $this->questionBankService = $questionBankService;
  35. $this->pdfExportService = $pdfExportService;
  36. $this->paperPayloadService = $paperPayloadService;
  37. $this->taskManager = $taskManager;
  38. $this->externalIdService = $externalIdService;
  39. }
  40. /**
  41. * 外部API:生成智能试卷(异步模式)
  42. * 立即返回任务ID,PDF生成在后台进行,完成后通过回调通知
  43. */
  44. public function store(Request $request): JsonResponse
  45. {
  46. // 优先从body获取数据,不使用query params
  47. $payload = $request->json()->all();
  48. if (empty($payload)) {
  49. $payload = $request->all();
  50. }
  51. $normalized = $this->normalizePayload($payload);
  52. $validator = validator($normalized, [
  53. 'student_id' => 'required|string|min:1|regex:/^\\d+$/', // 接受字符串或数字类型,如"1764913638"或1764913638
  54. 'teacher_id' => 'required|string|min:1|regex:/^\\d+$/',
  55. 'paper_name' => 'nullable|string|max:255',
  56. 'grade' => 'required|integer|min:1|max:12', // 支持小学1-6、初中7-9、高中10-12
  57. 'student_name' => 'required|string|max:50',
  58. 'teacher_name' => 'required|string|max:50',
  59. 'total_questions' => 'nullable|integer|min:1|max:100',
  60. 'difficulty_category' => 'nullable|integer|in:1,2,3,4',
  61. 'kp_codes' => 'nullable|array',
  62. 'kp_codes.*' => 'string',
  63. 'skills' => 'nullable|array',
  64. 'skills.*' => 'string',
  65. 'question_type_ratio' => 'nullable|array',
  66. // 'difficulty_ratio' 参数已废弃,使用 difficulty_category 控制难度分布
  67. 'total_score' => 'nullable|numeric|min:1|max:1000',
  68. 'mistake_ids' => 'nullable|array',
  69. 'mistake_ids.*' => 'string',
  70. 'mistake_question_ids' => 'nullable|array',
  71. 'mistake_question_ids.*' => 'string',
  72. 'callback_url' => 'nullable|url', // 异步完成后推送通知的URL
  73. // 新增:组卷类型
  74. 'assemble_type' => 'nullable|integer|in:0,1,2,3,4,5,6',
  75. 'exam_type' => 'nullable|string|in:general,diagnostic,practice,mistake,textbook,knowledge,knowledge_points',
  76. // 错题本类型专用参数
  77. 'paper_ids' => 'nullable|array',
  78. 'paper_ids.*' => 'string',
  79. // 修改:使用series_id + semester_code + grade替代textbook_id
  80. 'series_id' => 'nullable|integer|min:1', // 教材系列ID(替代textbook_id)
  81. 'semester_code' => 'nullable|integer|in:1,2', // 上下册:1=上册,2=下册
  82. // 新增:各组卷类型的专用参数
  83. 'chapter_id_list' => 'nullable|array', // 教材组卷专用
  84. 'chapter_id_list.*' => 'integer|min:1',
  85. 'kp_code_list' => 'nullable|array', // 知识点组卷专用
  86. 'kp_code_list.*' => 'string',
  87. 'end_catalog_id' => 'nullable|integer|min:1', // 摸底专用:截止章节ID
  88. // 新增:专项练习选项
  89. 'practice_options' => 'nullable|array',
  90. 'practice_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  91. 'practice_options.intensity' => 'nullable|string|in:low,medium,high',
  92. 'practice_options.include_new_questions' => 'nullable|boolean',
  93. 'practice_options.focus_weaknesses' => 'nullable|boolean',
  94. // 新增:错题选项
  95. 'mistake_options' => 'nullable|array',
  96. 'mistake_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  97. 'mistake_options.review_mistakes' => 'nullable|boolean',
  98. 'mistake_options.intensity' => 'nullable|string|in:low,medium,high',
  99. 'mistake_options.include_new_questions' => 'nullable|boolean',
  100. 'mistake_options.focus_weaknesses' => 'nullable|boolean',
  101. // 新增:按知识点组卷选项
  102. 'knowledge_points_options' => 'nullable|array',
  103. 'knowledge_points_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  104. 'knowledge_points_options.intensity' => 'nullable|string|in:low,medium,high',
  105. 'knowledge_points_options.focus_weaknesses' => 'nullable|boolean',
  106. ]);
  107. if ($validator->fails()) {
  108. return response()->json([
  109. 'success' => false,
  110. 'message' => '参数错误',
  111. 'errors' => $validator->errors()->toArray(),
  112. ], 422);
  113. }
  114. $data = $validator->validated();
  115. $data['total_questions'] = $data['total_questions'] ?? 20;
  116. $this->ensureStudentTeacherRelation($data);
  117. // 【修改】使用series_id、semester_code和grade获取textbook_id
  118. $textbookId = $this->resolveTextbookId($data);
  119. if ($textbookId) {
  120. $data['textbook_id'] = $textbookId;
  121. }
  122. // 确保 kp_codes 是数组
  123. $data['kp_codes'] = $data['kp_codes'] ?? [];
  124. if (! is_array($data['kp_codes'])) {
  125. $data['kp_codes'] = [];
  126. }
  127. $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
  128. // 注意: difficulty_ratio 参数已废弃,使用 difficulty_category 控制难度分布
  129. $paperName = $data['paper_name'] ?? ('智能试卷_'.now()->format('Ymd_His'));
  130. $difficultyCategory = $data['difficulty_category'] ?? 1; // 直接使用数字,不转换
  131. $mistakeIds = $data['mistake_ids'] ?? [];
  132. $mistakeQuestionIds = $data['mistake_question_ids'] ?? [];
  133. $paperIds = $data['paper_ids'] ?? [];
  134. $assembleType = $data['assemble_type'] ?? 4; // 默认为通用类型(4)
  135. try {
  136. $questions = [];
  137. $result = null;
  138. if (! empty($mistakeIds) || ! empty($mistakeQuestionIds)) {
  139. $questionIds = $this->resolveMistakeQuestionIds(
  140. $data['student_id'],
  141. $mistakeIds,
  142. $mistakeQuestionIds
  143. );
  144. if (empty($questionIds)) {
  145. return response()->json([
  146. 'success' => false,
  147. 'message' => '未找到可用的错题题目,请检查错题ID或学生ID',
  148. ], 400);
  149. }
  150. $bankQuestions = $this->questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
  151. if (empty($bankQuestions)) {
  152. return response()->json([
  153. 'success' => false,
  154. 'message' => '错题对应的题库题目不存在或不可用',
  155. ], 400);
  156. }
  157. $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes']);
  158. $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
  159. $paperName = $data['paper_name'] ?? ('错题复习_'.$data['student_id'].'_'.now()->format('Ymd_His'));
  160. } else {
  161. // 第一步:生成智能试卷(同步)
  162. $params = [
  163. 'student_id' => $data['student_id'],
  164. 'grade' => $data['grade'] ?? null,
  165. 'total_questions' => $data['total_questions'],
  166. // 【修复】教材组卷时不使用用户传入的kp_codes,只使用章节关联的知识点
  167. 'kp_codes' => $assembleType == 3 ? null : ($data['kp_codes'] ?? null),
  168. 'skills' => $data['skills'] ?? [],
  169. 'question_type_ratio' => $questionTypeRatio,
  170. 'difficulty_category' => $difficultyCategory, // 传递难度分类(数字)
  171. 'assemble_type' => $assembleType, // 新版组卷类型
  172. 'exam_type' => $data['exam_type'] ?? 'general', // 兼容旧版参数
  173. 'paper_ids' => $paperIds, // 错题本类型专用参数
  174. 'textbook_id' => $data['textbook_id'] ?? null, // 摸底和智能组卷专用
  175. 'end_catalog_id' => $data['end_catalog_id'] ?? null, // 摸底专用:截止章节ID
  176. 'chapter_id_list' => $data['chapter_id_list'] ?? null, // 教材组卷专用
  177. 'kp_code_list' => $assembleType == 3 ? null : ($data['kp_code_list'] ?? $data['kp_codes'] ?? []), // 知识点组卷专用
  178. 'practice_options' => $data['practice_options'] ?? null, // 传递专项练习选项
  179. 'mistake_options' => $data['mistake_options'] ?? null, // 传递错题选项
  180. ];
  181. $result = $this->learningAnalyticsService->generateIntelligentExam($params);
  182. if (empty($result['success'])) {
  183. $errorMsg = $result['message'] ?? '智能出卷失败';
  184. Log::error('智能出卷失败', [
  185. 'student_id' => $data['student_id'],
  186. 'error' => $result,
  187. ]);
  188. // 提供更详细的错误信息
  189. if (strpos($errorMsg, '超时') !== false) {
  190. $errorMsg = '服务响应超时,请稍后重试';
  191. } elseif (strpos($errorMsg, '连接') !== false) {
  192. $errorMsg = '依赖服务连接失败,请检查服务状态';
  193. }
  194. return response()->json([
  195. 'success' => false,
  196. 'message' => $errorMsg,
  197. 'details' => $result['details'] ?? null,
  198. ], 400);
  199. }
  200. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
  201. }
  202. if (empty($questions)) {
  203. return response()->json([
  204. 'success' => false,
  205. 'message' => '未能生成有效题目,请检查知识点或题库数据',
  206. ], 400);
  207. }
  208. // 错题本类型不需要限制题目数量,由错题数量决定
  209. if ($assembleType === 5) {
  210. // 错题本:使用所有错题,不限制数量
  211. Log::info('错题本类型,使用所有错题', [
  212. 'assemble_type' => $assembleType,
  213. 'question_count' => count($questions),
  214. ]);
  215. } else {
  216. // 其他类型:限制题目数量
  217. $totalQuestions = min($data['total_questions'], count($questions));
  218. $questions = array_slice($questions, 0, $totalQuestions);
  219. }
  220. // 调整题目分值,确保符合目标总分
  221. $targetTotalScore = $data['total_score'] ?? 100.0;
  222. $questions = $this->adjustQuestionScores($questions, $targetTotalScore);
  223. // 计算总分
  224. $totalScore = array_sum(array_column($questions, 'score'));
  225. // 第二步:保存试卷到数据库(同步)
  226. $paperId = $this->questionBankService->saveExamToDatabase([
  227. 'paper_name' => $paperName,
  228. 'student_id' => $data['student_id'],
  229. 'teacher_id' => $data['teacher_id'] ?? null,
  230. 'assembleType' => $assembleType,
  231. 'difficulty_category' => $difficultyCategory,
  232. 'total_score' => $totalScore, // 使用计算后的实际总分
  233. 'questions' => $questions,
  234. ]);
  235. if (! $paperId) {
  236. return response()->json([
  237. 'success' => false,
  238. 'message' => '试卷保存失败',
  239. ], 500);
  240. }
  241. // 第三步:创建异步任务(使用TaskManager)
  242. // 注意:callback_url会在TaskManager中被提取并保存
  243. $taskId = $this->taskManager->createTask(TaskManager::TASK_TYPE_EXAM, array_merge($data, ['paper_id' => $paperId]));
  244. // 生成识别码
  245. $codes = $this->paperPayloadService->generatePaperCodes($paperId);
  246. // 立即返回完整的试卷数据(不等待PDF生成)
  247. $paperModel = Paper::with('questions')->find($paperId);
  248. $examContent = $paperModel
  249. ? $this->paperPayloadService->buildExamContent($paperModel)
  250. : [];
  251. // 触发后台PDF生成
  252. $this->triggerPdfGeneration($taskId, $paperId);
  253. $payload = [
  254. 'success' => true,
  255. 'message' => '智能试卷创建成功,PDF正在后台生成...',
  256. 'data' => [
  257. 'task_id' => $taskId,
  258. 'paper_id' => $paperId,
  259. 'status' => 'processing',
  260. // 识别码
  261. 'exam_code' => $codes['exam_code'], // 试卷识别码 (1+12位)
  262. 'grading_code' => $codes['grading_code'], // 判卷识别码 (2+12位)
  263. 'paper_id_num' => $codes['paper_id_num'], // 12位数字ID
  264. 'exam_content' => $examContent,
  265. 'urls' => [
  266. 'grading_url' => route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]),
  267. 'student_exam_url' => route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']),
  268. 'knowledge_explanation_url' => route('filament.admin.auth.intelligent-exam.knowledge-explanation', ['paper_id' => $paperId]),
  269. ],
  270. 'pdfs' => [
  271. 'exam_paper_pdf' => null,
  272. 'grading_pdf' => null,
  273. ],
  274. 'stats' => $result['stats'] ?? [
  275. 'total_selected' => count($questions),
  276. 'mistake_based' => ! empty($mistakeIds) || ! empty($mistakeQuestionIds),
  277. ],
  278. 'created_at' => now()->toISOString(),
  279. ],
  280. ];
  281. return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);
  282. } catch (\Exception $e) {
  283. Log::error('Intelligent exam API failed', [
  284. 'error' => $e->getMessage(),
  285. 'trace' => $e->getTraceAsString(),
  286. ]);
  287. // 返回更具体的错误信息
  288. $errorMessage = $e->getMessage();
  289. if (strpos($errorMessage, 'Connection') !== false || strpos($errorMessage, 'connection') !== false) {
  290. $errorMessage = '依赖服务连接失败,请检查服务状态';
  291. } elseif (strpos($errorMessage, 'timeout') !== false || strpos($errorMessage, '超时') !== false) {
  292. $errorMessage = '服务响应超时,请稍后重试';
  293. } elseif (strpos($errorMessage, 'not found') !== false || strpos($errorMessage, '未找到') !== false) {
  294. $errorMessage = '请求的资源不存在';
  295. } elseif (strpos($errorMessage, 'invalid') !== false || strpos($errorMessage, '无效') !== false) {
  296. $errorMessage = '请求参数无效';
  297. }
  298. return response()->json([
  299. 'success' => false,
  300. 'message' => $errorMessage ?: '服务异常,请稍后重试',
  301. ], 500);
  302. }
  303. }
  304. /**
  305. * 轮询任务状态
  306. */
  307. public function status(string $taskId): JsonResponse
  308. {
  309. try {
  310. $task = $this->taskManager->getTaskStatus($taskId);
  311. if (! $task) {
  312. return response()->json([
  313. 'success' => false,
  314. 'message' => '任务不存在',
  315. ], 404);
  316. }
  317. return response()->json([
  318. 'success' => true,
  319. 'data' => $task,
  320. ]);
  321. } catch (\Exception $e) {
  322. Log::error('查询任务状态失败', [
  323. 'task_id' => $taskId,
  324. 'error' => $e->getMessage(),
  325. ]);
  326. return response()->json([
  327. 'success' => false,
  328. 'message' => '查询失败,请稍后重试',
  329. ], 500);
  330. }
  331. }
  332. /**
  333. * 触发PDF生成
  334. * 使用队列进行异步处理
  335. */
  336. private function triggerPdfGeneration(string $taskId, string $paperId): void
  337. {
  338. // 异步处理PDF生成 - 将任务放入队列
  339. try {
  340. dispatch(new \App\Jobs\GenerateExamPdfJob($taskId, $paperId));
  341. Log::info('PDF生成任务已加入队列', [
  342. 'task_id' => $taskId,
  343. 'paper_id' => $paperId,
  344. ]);
  345. } catch (\Exception $e) {
  346. Log::error('PDF生成任务队列失败,不回退到同步处理', [
  347. 'task_id' => $taskId,
  348. 'paper_id' => $paperId,
  349. 'error' => $e->getMessage(),
  350. 'note' => '依赖队列重试机制,不进行同步处理以避免并发冲突',
  351. ]);
  352. // 【优化】不回退到同步处理,避免与队列任务并发冲突
  353. // 队列系统有重试机制,会自动处理失败情况
  354. // $this->processPdfGeneration($taskId, $paperId);
  355. }
  356. }
  357. /**
  358. * 处理PDF生成(模拟后台任务)
  359. * 在实际项目中,这个方法应该在队列worker中执行
  360. */
  361. private function processPdfGeneration(string $taskId, string $paperId): void
  362. {
  363. try {
  364. $this->taskManager->updateTaskProgress($taskId, 10, '开始生成试卷PDF...');
  365. // 生成试卷PDF
  366. $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
  367. ?? $this->questionBankService->exportExamToPdf($paperId)
  368. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  369. $this->taskManager->updateTaskProgress($taskId, 50, '试卷PDF生成完成,开始生成判卷PDF...');
  370. // 生成判卷PDF
  371. $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
  372. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  373. // 构建完整的试卷内容
  374. $paperModel = Paper::with('questions')->find($paperId);
  375. $examContent = $paperModel
  376. ? $this->paperPayloadService->buildExamContent($paperModel)
  377. : [];
  378. // 标记任务完成
  379. $this->taskManager->markTaskCompleted($taskId, [
  380. 'exam_content' => $examContent,
  381. 'pdfs' => [
  382. 'exam_paper_pdf' => $pdfUrl,
  383. 'grading_pdf' => $gradingPdfUrl,
  384. ],
  385. ]);
  386. Log::info('异步任务完成', [
  387. 'task_id' => $taskId,
  388. 'paper_id' => $paperId,
  389. 'pdf_url' => $pdfUrl,
  390. 'grading_pdf_url' => $gradingPdfUrl,
  391. ]);
  392. // 发送回调通知
  393. $this->taskManager->sendCallback($taskId);
  394. } catch (\Exception $e) {
  395. Log::error('PDF生成失败', [
  396. 'task_id' => $taskId,
  397. 'paper_id' => $paperId,
  398. 'error' => $e->getMessage(),
  399. ]);
  400. $this->taskManager->markTaskFailed($taskId, $e->getMessage());
  401. }
  402. }
  403. /**
  404. * 兼容字符串/数组入参
  405. */
  406. private function normalizePayload(array $payload): array
  407. {
  408. // 处理 question_count 参数:转换为 total_questions
  409. if (isset($payload['question_count']) && ! isset($payload['total_questions'])) {
  410. $payload['total_questions'] = $payload['question_count'];
  411. unset($payload['question_count']);
  412. }
  413. // 将student_id转换为字符串(支持数字和字符串输入)
  414. if (isset($payload['student_id'])) {
  415. $payload['student_id'] = (string) $payload['student_id'];
  416. }
  417. if (isset($payload['teacher_id'])) {
  418. $payload['teacher_id'] = (string) $payload['teacher_id'];
  419. }
  420. if (isset($payload['grade'])) {
  421. $payload['grade'] = (string) $payload['grade'];
  422. }
  423. // 处理 kp_codes:空字符串或null转换为空数组
  424. if (isset($payload['kp_codes'])) {
  425. if (is_string($payload['kp_codes'])) {
  426. $kpCodes = trim($payload['kp_codes']);
  427. if (empty($kpCodes)) {
  428. $payload['kp_codes'] = [];
  429. } else {
  430. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
  431. }
  432. } elseif (! is_array($payload['kp_codes'])) {
  433. $payload['kp_codes'] = [];
  434. }
  435. } else {
  436. $payload['kp_codes'] = [];
  437. }
  438. if (isset($payload['skills']) && is_string($payload['skills'])) {
  439. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  440. }
  441. foreach (['mistake_ids', 'mistake_question_ids'] as $key) {
  442. if (isset($payload[$key])) {
  443. if (is_string($payload[$key])) {
  444. $raw = trim($payload[$key]);
  445. $payload[$key] = $raw === ''
  446. ? []
  447. : array_values(array_filter(array_map('trim', explode(',', $raw))));
  448. } elseif (! is_array($payload[$key])) {
  449. $payload[$key] = [];
  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. $normalized = [];
  669. foreach ($questions as $question) {
  670. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  671. $score = $question['score'] ?? $this->defaultScore($type);
  672. $normalized[] = [
  673. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  674. 'question_id' => $question['question_id'] ?? null,
  675. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  676. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  677. 'content' => $question['content'] ?? $question['stem'] ?? '',
  678. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  679. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  680. 'solution' => $question['solution'] ?? '',
  681. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  682. 'score' => $score,
  683. 'estimated_time' => $question['estimated_time'] ?? 300,
  684. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  685. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  686. ];
  687. }
  688. return array_values(array_filter($normalized, fn ($q) => ! empty($q['id'])));
  689. }
  690. private function guessType(array $question): string
  691. {
  692. if (! empty($question['options']) && is_array($question['options'])) {
  693. return '选择题';
  694. }
  695. $content = $question['stem'] ?? $question['content'] ?? '';
  696. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  697. return '填空题';
  698. }
  699. return '解答题';
  700. }
  701. /**
  702. * 根据题目类型获取默认分值(中国中学卷子标准)
  703. * 选择题:5分/题,填空题:5分/题,解答题:10分/题
  704. */
  705. private function defaultScore(string $type): int
  706. {
  707. return match ($type) {
  708. '选择题' => 5,
  709. '填空题' => 5,
  710. '解答题' => 10,
  711. default => 5,
  712. };
  713. }
  714. /**
  715. * 计算试卷总分并调整各题目分值,确保总分接近目标分数
  716. * 符合中国中学卷子标准:
  717. * - 选择题:约40%总分(每题4-6分,整数分值)
  718. * - 填空题:约25%总分(每题4-6分,整数分值)
  719. * - 解答题:约35%总分(每题8-12分,整数分值)
  720. * 使用组合优化算法确保:
  721. * 1. 所有分值都是整数(无小数点)
  722. * 2. 同类型题目分值均匀
  723. * 3. 总分精确匹配目标分数(或最接近)
  724. */
  725. private function adjustQuestionScores(array $questions, float $targetTotalScore = 100.0): array
  726. {
  727. if (empty($questions)) {
  728. return $questions;
  729. }
  730. // 第一步:按题型排序
  731. $sortedQuestions = [];
  732. $choiceQuestions = [];
  733. $fillQuestions = [];
  734. $answerQuestions = [];
  735. foreach ($questions as $question) {
  736. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  737. if ($type === 'choice') {
  738. $choiceQuestions[] = $question;
  739. } elseif ($type === 'fill') {
  740. $fillQuestions[] = $question;
  741. } else {
  742. $answerQuestions[] = $question;
  743. }
  744. }
  745. $sortedQuestions = array_merge($choiceQuestions, $fillQuestions, $answerQuestions);
  746. // 调试日志
  747. \Illuminate\Support\Facades\Log::info('adjustQuestionScores 开始', [
  748. 'choice_count' => count($choiceQuestions),
  749. 'fill_count' => count($fillQuestions),
  750. 'answer_count' => count($answerQuestions),
  751. ]);
  752. // 重新编号
  753. foreach ($sortedQuestions as $idx => &$question) {
  754. $question['question_number'] = $idx + 1;
  755. }
  756. unset($question);
  757. // 各题型数量
  758. $typeCounts = [
  759. 'choice' => count($choiceQuestions),
  760. 'fill' => count($fillQuestions),
  761. 'answer' => count($answerQuestions),
  762. ];
  763. // 记录各题型索引
  764. $typeIndexes = ['choice' => [], 'fill' => [], 'answer' => []];
  765. foreach ($sortedQuestions as $index => $question) {
  766. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  767. $typeIndexes[$type][] = $index;
  768. }
  769. // 第二步:分配分值
  770. $questionScores = [];
  771. $totalQuestions = $typeCounts['choice'] + $typeCounts['fill'] + $typeCounts['answer'];
  772. $globalBaseScore = floor($targetTotalScore / $totalQuestions);
  773. $globalBaseScore = max(1, $globalBaseScore);
  774. // 确定题型处理顺序(基于 sortedQuestions 中的顺序)
  775. $typeOrder = [];
  776. foreach ($sortedQuestions as $question) {
  777. $type = $this->normalizeQuestionType($question['question_type'] ?? 'answer');
  778. if (! in_array($type, $typeOrder)) {
  779. $typeOrder[] = $type;
  780. }
  781. }
  782. // 记录当前剩余预算
  783. $remainingBudget = $targetTotalScore;
  784. // 按顺序处理每种题型
  785. foreach ($typeOrder as $typeIndex => $type) {
  786. $count = $typeCounts[$type];
  787. if ($count === 0) {
  788. continue;
  789. }
  790. if ($typeIndex === 0) {
  791. // 第一个题型:拿平均分,然后都-1
  792. $thisBase = $globalBaseScore;
  793. foreach ($typeIndexes[$type] as $idx) {
  794. $questionScores[$idx] = $thisBase;
  795. }
  796. // 都-1
  797. foreach ($typeIndexes[$type] as $idx) {
  798. $questionScores[$idx] = max(1, $questionScores[$idx] - 1);
  799. }
  800. // 计算已分配的分数
  801. $allocated = 0;
  802. foreach ($typeIndexes[$type] as $idx) {
  803. $allocated += $questionScores[$idx];
  804. }
  805. $remainingBudget -= $allocated;
  806. } elseif ($typeIndex === count($typeOrder) - 1) {
  807. // 最后一个题型:用剩余分数分配
  808. $thisBase = floor($remainingBudget / $count);
  809. $thisBase = max(1, $thisBase);
  810. foreach ($typeIndexes[$type] as $idx) {
  811. $questionScores[$idx] = $thisBase;
  812. }
  813. // 余数补偿:分散到多道题,从后往前各+1
  814. $total = $thisBase * $count;
  815. $remainder = $remainingBudget - $total;
  816. if ($remainder > 0) {
  817. // 从最后一道题开始,往前 $remainder 道题各+1
  818. $answerIndexes = array_values($typeIndexes[$type]);
  819. $startIdx = max(0, count($answerIndexes) - $remainder);
  820. for ($i = $startIdx; $i < count($answerIndexes); $i++) {
  821. $questionScores[$answerIndexes[$i]] += 1;
  822. }
  823. }
  824. } else {
  825. // 中间的题型:直接用全局平均分(不减)
  826. $thisBase = $globalBaseScore;
  827. foreach ($typeIndexes[$type] as $idx) {
  828. $questionScores[$idx] = $thisBase;
  829. }
  830. // 计算已分配的分数
  831. $allocated = 0;
  832. foreach ($typeIndexes[$type] as $idx) {
  833. $allocated += $questionScores[$idx];
  834. }
  835. $remainingBudget -= $allocated;
  836. }
  837. }
  838. // 第三步:确保最后一类题型分数 > 前面所有题型
  839. if (count($typeOrder) > 1) {
  840. $lastType = end($typeOrder);
  841. $otherTypes = array_slice($typeOrder, 0, -1);
  842. // 前面题型的最高分
  843. $maxOtherScore = 0;
  844. foreach ($otherTypes as $type) {
  845. foreach ($typeIndexes[$type] as $idx) {
  846. $maxOtherScore = max($maxOtherScore, $questionScores[$idx]);
  847. }
  848. }
  849. // 最后一类题型的最低分
  850. $minLastScore = PHP_INT_MAX;
  851. foreach ($typeIndexes[$lastType] as $idx) {
  852. $minLastScore = min($minLastScore, $questionScores[$idx]);
  853. }
  854. // 如果最后一类不够高,从前面扣分
  855. if ($minLastScore <= $maxOtherScore) {
  856. $diff = $maxOtherScore - $minLastScore + 1;
  857. // 从前面题型扣分(每道最多扣2分)
  858. $reductionPerQuestion = min($diff, 2);
  859. foreach ($otherTypes as $type) {
  860. foreach ($typeIndexes[$type] as $idx) {
  861. $questionScores[$idx] = max(1, $questionScores[$idx] - $reductionPerQuestion);
  862. }
  863. }
  864. // 重新计算剩余给最后一类
  865. $reallocated = $targetTotalScore;
  866. foreach ($typeIndexes[$lastType] as $idx) {
  867. $reallocated -= $questionScores[$idx];
  868. }
  869. foreach ($otherTypes as $type) {
  870. foreach ($typeIndexes[$type] as $idx) {
  871. $reallocated -= $questionScores[$idx];
  872. }
  873. }
  874. if ($reallocated > 0) {
  875. $newBase = floor($reallocated / $typeCounts[$lastType]);
  876. foreach ($typeIndexes[$lastType] as $idx) {
  877. $questionScores[$idx] = $newBase;
  878. }
  879. $total = $newBase * $typeCounts[$lastType];
  880. $remainder = $reallocated - $total;
  881. if ($remainder > 0) {
  882. // 余数分散到多道题,从后往前各+1
  883. $lastIndexes = array_values($typeIndexes[$lastType]);
  884. $startIdx = max(0, count($lastIndexes) - $remainder);
  885. for ($i = $startIdx; $i < count($lastIndexes); $i++) {
  886. $questionScores[$lastIndexes[$i]] += 1;
  887. }
  888. }
  889. }
  890. }
  891. }
  892. // 第三步:构建结果
  893. $adjustedQuestions = [];
  894. foreach ($sortedQuestions as $index => $question) {
  895. $adjustedQuestions[$index] = $question;
  896. $adjustedQuestions[$index]['score'] = $questionScores[$index] ?? 5;
  897. }
  898. return $adjustedQuestions;
  899. }
  900. /**
  901. * 标准化题目类型
  902. */
  903. private function normalizeQuestionType(string $type): string
  904. {
  905. $type = strtolower(trim($type));
  906. if (in_array($type, ['choice', 'single_choice', 'multiple_choice', '选择题', '单选', '多选'], true)) {
  907. return 'choice';
  908. }
  909. if (in_array($type, ['fill', 'fill_in_the_blank', 'blank', '填空题', '填空'], true)) {
  910. return 'fill';
  911. }
  912. return 'answer';
  913. }
  914. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  915. {
  916. $questionIds = [];
  917. if (! empty($mistakeQuestionIds)) {
  918. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  919. }
  920. if (! empty($mistakeIds)) {
  921. $mistakeQuestionIdsFromDb = MistakeRecord::query()
  922. ->where('student_id', $studentId)
  923. ->whereIn('id', $mistakeIds)
  924. ->pluck('question_id')
  925. ->filter()
  926. ->values()
  927. ->all();
  928. $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
  929. }
  930. $questionIds = array_values(array_unique(array_filter($questionIds)));
  931. return $questionIds;
  932. }
  933. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  934. {
  935. if (empty($requestedIds)) {
  936. return $questions;
  937. }
  938. $order = array_flip($requestedIds);
  939. usort($questions, function ($a, $b) use ($order) {
  940. $aId = (string) ($a['id'] ?? '');
  941. $bId = (string) ($b['id'] ?? '');
  942. $aPos = $order[$aId] ?? PHP_INT_MAX;
  943. $bPos = $order[$bId] ?? PHP_INT_MAX;
  944. return $aPos <=> $bPos;
  945. });
  946. return $questions;
  947. }
  948. /**
  949. * 【新增】根据series_id、semester_code和grade获取textbook_id
  950. * 替代原来直接传入textbook_id的方式
  951. */
  952. private function resolveTextbookId(array $data): ?int
  953. {
  954. // 如果提供了series_id和semester_code,则查询textbook_id
  955. $seriesId = $data['series_id'] ?? null;
  956. $semesterCode = $data['semester_code'] ?? null;
  957. $grade = $data['grade'] ?? null;
  958. // 如果没有提供series_id或semester_code,则不设置textbook_id
  959. if (! $seriesId || ! $semesterCode) {
  960. return null;
  961. }
  962. try {
  963. // 根据series_id、semester_code和grade查询textbooks表
  964. $query = DB::connection('mysql')
  965. ->table('textbooks')
  966. ->where('series_id', $seriesId)
  967. ->where('semester', $semesterCode);
  968. // 如果提供了grade,可以作为额外筛选条件
  969. if ($grade) {
  970. $query->where('grade', $grade);
  971. }
  972. $textbook = $query->first();
  973. if ($textbook) {
  974. Log::info('成功解析textbook_id', [
  975. 'series_id' => $seriesId,
  976. 'semester_code' => $semesterCode,
  977. 'grade' => $grade,
  978. 'textbook_id' => $textbook->id,
  979. ]);
  980. return (int) $textbook->id;
  981. }
  982. Log::warning('未找到匹配的教材', [
  983. 'series_id' => $seriesId,
  984. 'semester_code' => $semesterCode,
  985. 'grade' => $grade,
  986. ]);
  987. return null;
  988. } catch (\Exception $e) {
  989. Log::error('查询textbook_id失败', [
  990. 'series_id' => $seriesId,
  991. 'semester_code' => $semesterCode,
  992. 'grade' => $grade,
  993. 'error' => $e->getMessage(),
  994. ]);
  995. return null;
  996. }
  997. }
  998. }