IntelligentExamController.php 36 KB

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