IntelligentExamController.php 43 KB

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