IntelligentExamController.php 46 KB

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