IntelligentExamController.php 46 KB

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