IntelligentExamController.php 39 KB

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