IntelligentExamController.php 45 KB

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