IntelligentExamController.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Paper;
  5. use App\Models\PaperQuestion;
  6. use App\Services\LearningAnalyticsService;
  7. use App\Services\ExamPdfExportService;
  8. use App\Services\ExternalIdService;
  9. use App\Services\QuestionBankService;
  10. use App\Services\PaperPayloadService;
  11. use App\Services\TaskManager;
  12. use App\Models\MistakeRecord;
  13. use App\Models\Student;
  14. use App\Models\Teacher;
  15. use Illuminate\Http\JsonResponse;
  16. use Illuminate\Http\Request;
  17. use Illuminate\Support\Facades\DB;
  18. use Illuminate\Support\Facades\Http;
  19. use Illuminate\Support\Facades\Log;
  20. use Illuminate\Support\Facades\URL;
  21. class IntelligentExamController extends Controller
  22. {
  23. private LearningAnalyticsService $learningAnalyticsService;
  24. private QuestionBankService $questionBankService;
  25. private ExamPdfExportService $pdfExportService;
  26. private PaperPayloadService $paperPayloadService;
  27. private TaskManager $taskManager;
  28. private ExternalIdService $externalIdService;
  29. public function __construct(
  30. LearningAnalyticsService $learningAnalyticsService,
  31. QuestionBankService $questionBankService,
  32. ExamPdfExportService $pdfExportService,
  33. PaperPayloadService $paperPayloadService,
  34. TaskManager $taskManager,
  35. ExternalIdService $externalIdService
  36. ) {
  37. $this->learningAnalyticsService = $learningAnalyticsService;
  38. $this->questionBankService = $questionBankService;
  39. $this->pdfExportService = $pdfExportService;
  40. $this->paperPayloadService = $paperPayloadService;
  41. $this->taskManager = $taskManager;
  42. $this->externalIdService = $externalIdService;
  43. }
  44. /**
  45. * 外部API:生成智能试卷(异步模式)
  46. * 立即返回任务ID,PDF生成在后台进行,完成后通过回调通知
  47. */
  48. public function store(Request $request): JsonResponse
  49. {
  50. // 优先从body获取数据,不使用query params
  51. $payload = $request->json()->all();
  52. if (empty($payload)) {
  53. $payload = $request->all();
  54. }
  55. $normalized = $this->normalizePayload($payload);
  56. $validator = validator($normalized, [
  57. 'student_id' => 'required|string|min:1|regex:/^\\d+$/', // 接受字符串或数字类型,如"1764913638"或1764913638
  58. 'teacher_id' => 'required|string|min:1|regex:/^\\d+$/',
  59. 'paper_name' => 'nullable|string|max:255',
  60. 'grade' => 'required|integer|in:7,8,9',
  61. 'student_name' => 'required|string|max:50',
  62. 'teacher_name' => 'required|string|max:50',
  63. 'total_questions' => 'nullable|integer|min:1|max:100',
  64. 'difficulty_category' => 'nullable|integer|in:1,2,3,4',
  65. 'kp_codes' => 'nullable|array',
  66. 'kp_codes.*' => 'string',
  67. 'skills' => 'nullable|array',
  68. 'skills.*' => 'string',
  69. 'question_type_ratio' => 'nullable|array',
  70. // 'difficulty_ratio' 参数已废弃,使用 difficulty_category 控制难度分布
  71. 'total_score' => 'nullable|numeric|min:1|max:1000',
  72. 'mistake_ids' => 'nullable|array',
  73. 'mistake_ids.*' => 'string',
  74. 'mistake_question_ids' => 'nullable|array',
  75. 'mistake_question_ids.*' => 'string',
  76. 'callback_url' => 'nullable|url', // 异步完成后推送通知的URL
  77. // 新增:组卷类型
  78. 'assemble_type' => 'nullable|integer|in:0,1,2,3,4,5,6',
  79. 'exam_type' => 'nullable|string|in:general,diagnostic,practice,mistake,textbook,knowledge,knowledge_points',
  80. // 错题本类型专用参数
  81. 'paper_ids' => 'nullable|array',
  82. 'paper_ids.*' => 'string',
  83. // 修改:使用series_id + semester_code + grade替代textbook_id
  84. 'series_id' => 'nullable|integer|min:1', // 教材系列ID(替代textbook_id)
  85. 'semester_code' => 'nullable|integer|in:1,2', // 上下册:1=上册,2=下册
  86. // 新增:各组卷类型的专用参数
  87. 'chapter_id_list' => 'nullable|array', // 教材组卷专用
  88. 'chapter_id_list.*' => 'integer|min:1',
  89. 'kp_code_list' => 'nullable|array', // 知识点组卷专用
  90. 'kp_code_list.*' => 'string',
  91. // 新增:专项练习选项
  92. 'practice_options' => 'nullable|array',
  93. 'practice_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  94. 'practice_options.intensity' => 'nullable|string|in:low,medium,high',
  95. 'practice_options.include_new_questions' => 'nullable|boolean',
  96. 'practice_options.focus_weaknesses' => 'nullable|boolean',
  97. // 新增:错题选项
  98. 'mistake_options' => 'nullable|array',
  99. 'mistake_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  100. 'mistake_options.review_mistakes' => 'nullable|boolean',
  101. 'mistake_options.intensity' => 'nullable|string|in:low,medium,high',
  102. 'mistake_options.include_new_questions' => 'nullable|boolean',
  103. 'mistake_options.focus_weaknesses' => 'nullable|boolean',
  104. // 新增:按知识点组卷选项
  105. 'knowledge_points_options' => 'nullable|array',
  106. 'knowledge_points_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
  107. 'knowledge_points_options.intensity' => 'nullable|string|in:low,medium,high',
  108. 'knowledge_points_options.focus_weaknesses' => 'nullable|boolean',
  109. ]);
  110. if ($validator->fails()) {
  111. return response()->json([
  112. 'success' => false,
  113. 'message' => '参数错误',
  114. 'errors' => $validator->errors()->toArray(),
  115. ], 422);
  116. }
  117. $data = $validator->validated();
  118. $data['total_questions'] = $data['total_questions'] ?? 20;
  119. $this->ensureStudentTeacherRelation($data);
  120. // 【修改】使用series_id、semester_code和grade获取textbook_id
  121. $textbookId = $this->resolveTextbookId($data);
  122. if ($textbookId) {
  123. $data['textbook_id'] = $textbookId;
  124. }
  125. // 确保 kp_codes 是数组
  126. $data['kp_codes'] = $data['kp_codes'] ?? [];
  127. if (!is_array($data['kp_codes'])) {
  128. $data['kp_codes'] = [];
  129. }
  130. $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
  131. // 注意: difficulty_ratio 参数已废弃,使用 difficulty_category 控制难度分布
  132. $paperName = $data['paper_name'] ?? ('智能试卷_' . now()->format('Ymd_His'));
  133. $difficultyCategory = $data['difficulty_category'] ?? 1; // 直接使用数字,不转换
  134. $mistakeIds = $data['mistake_ids'] ?? [];
  135. $mistakeQuestionIds = $data['mistake_question_ids'] ?? [];
  136. $paperIds = $data['paper_ids'] ?? [];
  137. $assembleType = $data['assemble_type'] ?? 4; // 默认为通用类型(4)
  138. try {
  139. $questions = [];
  140. $result = null;
  141. if (!empty($mistakeIds) || !empty($mistakeQuestionIds)) {
  142. $questionIds = $this->resolveMistakeQuestionIds(
  143. $data['student_id'],
  144. $mistakeIds,
  145. $mistakeQuestionIds
  146. );
  147. if (empty($questionIds)) {
  148. return response()->json([
  149. 'success' => false,
  150. 'message' => '未找到可用的错题题目,请检查错题ID或学生ID',
  151. ], 400);
  152. }
  153. $bankQuestions = $this->questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
  154. if (empty($bankQuestions)) {
  155. return response()->json([
  156. 'success' => false,
  157. 'message' => '错题对应的题库题目不存在或不可用',
  158. ], 400);
  159. }
  160. $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes']);
  161. $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
  162. $paperName = $data['paper_name'] ?? ('错题复习_' . $data['student_id'] . '_' . now()->format('Ymd_His'));
  163. } else {
  164. // 第一步:生成智能试卷(同步)
  165. $params = [
  166. 'student_id' => $data['student_id'],
  167. 'grade' => $data['grade'] ?? null,
  168. 'total_questions' => $data['total_questions'],
  169. // 【修复】教材组卷时不使用用户传入的kp_codes,只使用章节关联的知识点
  170. 'kp_codes' => $assembleType == 3 ? null : ($data['kp_codes'] ?? null),
  171. 'kp_code_list' => $assembleType == 3 ? null : ($data['kp_code_list'] ?? $data['kp_codes'] ?? []),
  172. 'skills' => $data['skills'] ?? [],
  173. 'question_type_ratio' => $questionTypeRatio,
  174. 'difficulty_category' => $difficultyCategory, // 传递难度分类(数字)
  175. 'assemble_type' => $assembleType, // 新版组卷类型
  176. 'exam_type' => $data['exam_type'] ?? 'general', // 兼容旧版参数
  177. 'paper_ids' => $paperIds, // 错题本类型专用参数
  178. 'textbook_id' => $data['textbook_id'] ?? null, // 摸底和智能组卷专用
  179. 'chapter_id_list' => $data['chapter_id_list'] ?? null, // 教材组卷专用
  180. 'kp_code_list' => $assembleType == 3 ? null : ($data['kp_code_list'] ?? null), // 知识点组卷专用
  181. 'practice_options' => $data['practice_options'] ?? null, // 传递专项练习选项
  182. 'mistake_options' => $data['mistake_options'] ?? null, // 传递错题选项
  183. ];
  184. $result = $this->learningAnalyticsService->generateIntelligentExam($params);
  185. if (empty($result['success'])) {
  186. $errorMsg = $result['message'] ?? '智能出卷失败';
  187. Log::error('智能出卷失败', [
  188. 'student_id' => $data['student_id'],
  189. 'error' => $result
  190. ]);
  191. // 提供更详细的错误信息
  192. if (strpos($errorMsg, '超时') !== false) {
  193. $errorMsg = '服务响应超时,请稍后重试';
  194. } elseif (strpos($errorMsg, '连接') !== false) {
  195. $errorMsg = '依赖服务连接失败,请检查服务状态';
  196. }
  197. return response()->json([
  198. 'success' => false,
  199. 'message' => $errorMsg,
  200. 'details' => $result['details'] ?? null,
  201. ], 400);
  202. }
  203. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
  204. }
  205. if (empty($questions)) {
  206. return response()->json([
  207. 'success' => false,
  208. 'message' => '未能生成有效题目,请检查知识点或题库数据',
  209. ], 400);
  210. }
  211. // 错题本类型不需要限制题目数量,由错题数量决定
  212. if ($assembleType === 5) {
  213. // 错题本:使用所有错题,不限制数量
  214. Log::info('错题本类型,使用所有错题', [
  215. 'assemble_type' => $assembleType,
  216. 'question_count' => count($questions)
  217. ]);
  218. } else {
  219. // 其他类型:限制题目数量
  220. $totalQuestions = min($data['total_questions'], count($questions));
  221. $questions = array_slice($questions, 0, $totalQuestions);
  222. }
  223. // 调整题目分值,确保符合中国中学卷子标准(总分100分)
  224. $questions = $this->adjustQuestionScores($questions, 100.0);
  225. // 计算总分
  226. $totalScore = array_sum(array_column($questions, 'score'));
  227. // 第二步:保存试卷到数据库(同步)
  228. $paperId = $this->questionBankService->saveExamToDatabase([
  229. 'paper_name' => $paperName,
  230. 'student_id' => $data['student_id'],
  231. 'teacher_id' => $data['teacher_id'] ?? null,
  232. 'difficulty_category' => $difficultyCategory,
  233. 'total_score' => $data['total_score'] ?? 100.0, // 默认100分
  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. ],
  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. $typeCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  732. foreach ($questions as $question) {
  733. $type = $question['question_type'] ?? 'answer';
  734. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  735. $type = 'choice';
  736. } elseif (in_array($type, ['FILL_IN_THE_BLANK', 'FILL'], true)) {
  737. $type = 'fill';
  738. } elseif (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF', 'ANSWER'], true)) {
  739. $type = 'answer';
  740. }
  741. if (isset($typeCounts[$type])) {
  742. $typeCounts[$type]++;
  743. }
  744. }
  745. // 标准分值范围
  746. $standardScoreRanges = [
  747. 'choice' => ['min' => 4, 'max' => 6],
  748. 'fill' => ['min' => 4, 'max' => 6],
  749. 'answer' => ['min' => 8, 'max' => 12],
  750. ];
  751. // 目标比例
  752. $typeRatios = ['choice' => 0.40, 'fill' => 0.25, 'answer' => 0.35];
  753. // 检查可用题型
  754. $availableTypes = array_filter($typeCounts, fn($count) => $count > 0);
  755. $availableTypeCount = count($availableTypes);
  756. $isPartialTypes = $availableTypeCount < 3 && $availableTypeCount > 0;
  757. if ($isPartialTypes) {
  758. $equalRatio = 1.0 / $availableTypeCount;
  759. foreach ($typeCounts as $type => $count) {
  760. if ($count > 0) {
  761. $typeRatios[$type] = $equalRatio;
  762. } else {
  763. $typeRatios[$type] = 0;
  764. }
  765. }
  766. }
  767. $typeQuestionIndexes = ['choice' => [], 'fill' => [], 'answer' => []];
  768. // 记录每种题型的题目索引
  769. foreach ($questions as $index => $question) {
  770. $type = $question['question_type'] ?? 'answer';
  771. if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  772. $type = 'choice';
  773. } elseif (in_array($type, ['FILL_IN_THE_BLANK', 'FILL'], true)) {
  774. $type = 'fill';
  775. } elseif (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF', 'ANSWER'], true)) {
  776. $type = 'answer';
  777. }
  778. $typeQuestionIndexes[$type][] = $index;
  779. }
  780. // 生成每种题型的可能分值选项
  781. $typeScoreOptions = [];
  782. foreach ($typeQuestionIndexes as $type => $indexes) {
  783. if (empty($indexes)) {
  784. continue;
  785. }
  786. $typeQuestionCount = count($indexes);
  787. $minScore = $standardScoreRanges[$type]['min'];
  788. $maxScore = $standardScoreRanges[$type]['max'];
  789. $targetTotal = $targetTotalScore * $typeRatios[$type];
  790. $idealPerQuestion = $targetTotal / $typeQuestionCount;
  791. $options = [];
  792. // 添加标准范围内的选项
  793. for ($score = $minScore; $score <= $maxScore; $score++) {
  794. $total = $score * $typeQuestionCount;
  795. $options[] = [
  796. 'score' => $score,
  797. 'total' => $total,
  798. 'difference' => abs($targetTotalScore - $total),
  799. ];
  800. }
  801. // 如果是部分题型,大幅扩展搜索范围
  802. if ($isPartialTypes) {
  803. $idealScore = (int) round($idealPerQuestion);
  804. $searchMin = max($minScore, $idealScore - 10);
  805. $searchMax = $idealScore + 10;
  806. for ($score = $searchMin; $score <= $searchMax; $score++) {
  807. if ($score >= $minScore) {
  808. $total = $score * $typeQuestionCount;
  809. if (!in_array($total, array_column($options, 'total'))) {
  810. $options[] = [
  811. 'score' => $score,
  812. 'total' => $total,
  813. 'difference' => abs($targetTotalScore - $total),
  814. ];
  815. }
  816. }
  817. }
  818. }
  819. $typeScoreOptions[$type] = $options;
  820. }
  821. // 生成所有可能的组合
  822. $types = array_keys(array_filter($typeQuestionIndexes, fn($indexes) => !empty($indexes)));
  823. $allCombinations = [[]];
  824. foreach ($types as $type) {
  825. $newCombinations = [];
  826. foreach ($allCombinations as $combo) {
  827. foreach ($typeScoreOptions[$type] as $option) {
  828. $newCombo = $combo;
  829. $newCombo[$type] = $option;
  830. $newCombinations[] = $newCombo;
  831. }
  832. }
  833. $allCombinations = $newCombinations;
  834. }
  835. // 找到最佳组合(优先精确匹配,其次最接近)
  836. $bestCombination = null;
  837. $bestDifference = PHP_FLOAT_MAX;
  838. $exactMatchFound = false;
  839. foreach ($allCombinations as $combo) {
  840. $totalScore = array_sum(array_column($combo, 'total'));
  841. $difference = abs($targetTotalScore - $totalScore);
  842. if ($difference == 0) {
  843. $bestCombination = $combo;
  844. $exactMatchFound = true;
  845. break;
  846. }
  847. if ($difference < $bestDifference) {
  848. $bestDifference = $difference;
  849. $bestCombination = $combo;
  850. }
  851. }
  852. // 应用最佳组合
  853. $adjustedQuestions = [];
  854. if ($bestCombination) {
  855. foreach ($bestCombination as $type => $option) {
  856. $score = $option['score'];
  857. foreach ($typeQuestionIndexes[$type] as $index) {
  858. $question = $questions[$index];
  859. $question['score'] = $score;
  860. $adjustedQuestions[$index] = $question;
  861. }
  862. }
  863. }
  864. return array_values($adjustedQuestions);
  865. }
  866. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  867. {
  868. $questionIds = [];
  869. if (!empty($mistakeQuestionIds)) {
  870. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  871. }
  872. if (!empty($mistakeIds)) {
  873. $mistakeQuestionIdsFromDb = MistakeRecord::query()
  874. ->where('student_id', $studentId)
  875. ->whereIn('id', $mistakeIds)
  876. ->pluck('question_id')
  877. ->filter()
  878. ->values()
  879. ->all();
  880. $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
  881. }
  882. $questionIds = array_values(array_unique(array_filter($questionIds)));
  883. return $questionIds;
  884. }
  885. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  886. {
  887. if (empty($requestedIds)) {
  888. return $questions;
  889. }
  890. $order = array_flip($requestedIds);
  891. usort($questions, function ($a, $b) use ($order) {
  892. $aId = (string) ($a['id'] ?? '');
  893. $bId = (string) ($b['id'] ?? '');
  894. $aPos = $order[$aId] ?? PHP_INT_MAX;
  895. $bPos = $order[$bId] ?? PHP_INT_MAX;
  896. return $aPos <=> $bPos;
  897. });
  898. return $questions;
  899. }
  900. /**
  901. * 【新增】根据series_id、semester_code和grade获取textbook_id
  902. * 替代原来直接传入textbook_id的方式
  903. */
  904. private function resolveTextbookId(array $data): ?int
  905. {
  906. // 如果提供了series_id和semester_code,则查询textbook_id
  907. $seriesId = $data['series_id'] ?? null;
  908. $semesterCode = $data['semester_code'] ?? null;
  909. $grade = $data['grade'] ?? null;
  910. // 如果没有提供series_id或semester_code,则不设置textbook_id
  911. if (!$seriesId || !$semesterCode) {
  912. return null;
  913. }
  914. try {
  915. // 根据series_id、semester_code和grade查询textbooks表
  916. $query = DB::connection('mysql')
  917. ->table('textbooks')
  918. ->where('series_id', $seriesId)
  919. ->where('semester', $semesterCode);
  920. // 如果提供了grade,可以作为额外筛选条件
  921. if ($grade) {
  922. $query->where('grade', $grade);
  923. }
  924. $textbook = $query->first();
  925. if ($textbook) {
  926. Log::info('成功解析textbook_id', [
  927. 'series_id' => $seriesId,
  928. 'semester_code' => $semesterCode,
  929. 'grade' => $grade,
  930. 'textbook_id' => $textbook->id
  931. ]);
  932. return (int) $textbook->id;
  933. }
  934. Log::warning('未找到匹配的教材', [
  935. 'series_id' => $seriesId,
  936. 'semester_code' => $semesterCode,
  937. 'grade' => $grade
  938. ]);
  939. return null;
  940. } catch (\Exception $e) {
  941. Log::error('查询textbook_id失败', [
  942. 'series_id' => $seriesId,
  943. 'semester_code' => $semesterCode,
  944. 'grade' => $grade,
  945. 'error' => $e->getMessage()
  946. ]);
  947. return null;
  948. }
  949. }
  950. }