IntelligentExamController.php 44 KB

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