IntelligentExamController.php 43 KB

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