IntelligentExamController.php 40 KB

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