IntelligentExamController.php 40 KB

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