IntelligentExamController.php 43 KB

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