IntelligentExamController.php 38 KB

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