IntelligentExamController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Paper;
  5. use App\Models\PaperQuestion;
  6. use App\Services\LearningAnalyticsService;
  7. use App\Services\ExamPdfExportService;
  8. use App\Services\QuestionBankService;
  9. use App\Services\PaperPayloadService;
  10. use App\Services\TaskManager;
  11. use App\Models\MistakeRecord;
  12. use Illuminate\Http\JsonResponse;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Support\Facades\Http;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\URL;
  17. class IntelligentExamController extends Controller
  18. {
  19. private LearningAnalyticsService $learningAnalyticsService;
  20. private QuestionBankService $questionBankService;
  21. private ExamPdfExportService $pdfExportService;
  22. private PaperPayloadService $paperPayloadService;
  23. private TaskManager $taskManager;
  24. public function __construct(
  25. LearningAnalyticsService $learningAnalyticsService,
  26. QuestionBankService $questionBankService,
  27. ExamPdfExportService $pdfExportService,
  28. PaperPayloadService $paperPayloadService,
  29. TaskManager $taskManager
  30. ) {
  31. $this->learningAnalyticsService = $learningAnalyticsService;
  32. $this->questionBankService = $questionBankService;
  33. $this->pdfExportService = $pdfExportService;
  34. $this->paperPayloadService = $paperPayloadService;
  35. $this->taskManager = $taskManager;
  36. }
  37. /**
  38. * 外部API:生成智能试卷(异步模式)
  39. * 立即返回任务ID,PDF生成在后台进行,完成后通过回调通知
  40. */
  41. public function store(Request $request): JsonResponse
  42. {
  43. $normalized = $this->normalizePayload($request->all());
  44. $validator = validator($normalized, [
  45. 'student_id' => 'required|string',
  46. 'teacher_id' => 'nullable|string',
  47. 'paper_name' => 'nullable|string|max:255',
  48. 'grade' => 'nullable|string|max:50',
  49. 'total_questions' => 'nullable|integer|min:6|max:100',
  50. 'difficulty_category' => 'nullable|string',
  51. 'kp_codes' => 'nullable|array',
  52. 'kp_codes.*' => 'string',
  53. 'skills' => 'nullable|array',
  54. 'skills.*' => 'string',
  55. 'question_type_ratio' => 'nullable|array',
  56. 'difficulty_ratio' => 'nullable|array',
  57. 'total_score' => 'nullable|numeric|min:1|max:1000',
  58. 'mistake_ids' => 'nullable|array',
  59. 'mistake_ids.*' => 'string',
  60. 'mistake_question_ids' => 'nullable|array',
  61. 'mistake_question_ids.*' => 'string',
  62. ]);
  63. if ($validator->fails()) {
  64. return response()->json([
  65. 'success' => false,
  66. 'message' => '参数错误',
  67. 'errors' => $validator->errors()->toArray(),
  68. ], 422);
  69. }
  70. $data = $validator->validated();
  71. $data['total_questions'] = $data['total_questions'] ?? 20;
  72. // 确保 kp_codes 是数组
  73. $data['kp_codes'] = $data['kp_codes'] ?? [];
  74. if (!is_array($data['kp_codes'])) {
  75. $data['kp_codes'] = [];
  76. }
  77. $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
  78. $difficultyRatio = $this->normalizeDifficultyRatio($data['difficulty_ratio'] ?? []);
  79. $paperName = $data['paper_name'] ?? ('智能试卷_' . now()->format('Ymd_His'));
  80. $difficultyCategory = $this->normalizeDifficultyCategory($data['difficulty_category'] ?? null);
  81. $mistakeIds = $data['mistake_ids'] ?? [];
  82. $mistakeQuestionIds = $data['mistake_question_ids'] ?? [];
  83. try {
  84. $questions = [];
  85. $result = null;
  86. if (!empty($mistakeIds) || !empty($mistakeQuestionIds)) {
  87. $questionIds = $this->resolveMistakeQuestionIds(
  88. $data['student_id'],
  89. $mistakeIds,
  90. $mistakeQuestionIds
  91. );
  92. if (empty($questionIds)) {
  93. return response()->json([
  94. 'success' => false,
  95. 'message' => '未找到可用的错题题目,请检查错题ID或学生ID',
  96. ], 400);
  97. }
  98. $bankQuestions = $this->questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
  99. if (empty($bankQuestions)) {
  100. return response()->json([
  101. 'success' => false,
  102. 'message' => '错题对应的题库题目不存在或不可用',
  103. ], 400);
  104. }
  105. $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes']);
  106. $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
  107. $paperName = $data['paper_name'] ?? ('错题复习_' . $data['student_id'] . '_' . now()->format('Ymd_His'));
  108. } else {
  109. // 第一步:生成智能试卷(同步)
  110. $result = $this->learningAnalyticsService->generateIntelligentExam([
  111. 'student_id' => $data['student_id'],
  112. 'grade' => $data['grade'] ?? null,
  113. 'total_questions' => $data['total_questions'],
  114. 'kp_codes' => $data['kp_codes'],
  115. 'skills' => $data['skills'] ?? [],
  116. 'question_type_ratio' => $questionTypeRatio,
  117. 'difficulty_ratio' => $difficultyRatio,
  118. ]);
  119. if (empty($result['success'])) {
  120. $errorMsg = $result['message'] ?? '智能出卷失败';
  121. Log::error('智能出卷失败', [
  122. 'student_id' => $data['student_id'],
  123. 'error' => $result
  124. ]);
  125. // 提供更详细的错误信息
  126. if (strpos($errorMsg, '超时') !== false) {
  127. $errorMsg = '服务响应超时,请稍后重试';
  128. } elseif (strpos($errorMsg, '连接') !== false) {
  129. $errorMsg = '依赖服务连接失败,请检查服务状态';
  130. }
  131. return response()->json([
  132. 'success' => false,
  133. 'message' => $errorMsg,
  134. 'details' => $result['details'] ?? null,
  135. ], 400);
  136. }
  137. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
  138. }
  139. if (empty($questions)) {
  140. return response()->json([
  141. 'success' => false,
  142. 'message' => '未能生成有效题目,请检查知识点或题库数据',
  143. ], 400);
  144. }
  145. $totalScore = array_sum(array_column($questions, 'score'));
  146. $totalQuestions = min($data['total_questions'], count($questions));
  147. $questions = array_slice($questions, 0, $totalQuestions);
  148. // 第二步:保存试卷到数据库(同步)
  149. $paperId = $this->questionBankService->saveExamToDatabase([
  150. 'paper_name' => $paperName,
  151. 'student_id' => $data['student_id'],
  152. 'teacher_id' => $data['teacher_id'] ?? null,
  153. 'difficulty_category' => $difficultyCategory,
  154. 'total_score' => $data['total_score'] ?? $totalScore,
  155. 'questions' => $questions,
  156. ]);
  157. if (!$paperId) {
  158. return response()->json([
  159. 'success' => false,
  160. 'message' => '试卷保存失败',
  161. ], 500);
  162. }
  163. // 第三步:创建异步任务(使用TaskManager)
  164. $taskId = $this->taskManager->createTask(TaskManager::TASK_TYPE_EXAM, array_merge($data, ['paper_id' => $paperId]));
  165. // 生成识别码
  166. $codes = $this->paperPayloadService->generatePaperCodes($paperId);
  167. // 立即返回完整的试卷数据(不等待PDF生成)
  168. $paperModel = Paper::with('questions')->find($paperId);
  169. $examContent = $paperModel
  170. ? $this->paperPayloadService->buildExamContent($paperModel)
  171. : [];
  172. // 触发后台PDF生成
  173. $this->triggerPdfGeneration($taskId, $paperId);
  174. $payload = [
  175. 'success' => true,
  176. 'message' => '智能试卷创建成功,PDF正在后台生成...',
  177. 'data' => [
  178. 'task_id' => $taskId,
  179. 'paper_id' => $paperId,
  180. 'status' => 'processing',
  181. // 识别码
  182. 'exam_code' => $codes['exam_code'], // 试卷识别码 (1+12位)
  183. 'grading_code' => $codes['grading_code'], // 判卷识别码 (2+12位)
  184. 'paper_id_num' => $codes['paper_id_num'], // 12位数字ID
  185. 'exam_content' => $examContent,
  186. 'urls' => [
  187. 'grading_url' => route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]),
  188. 'student_exam_url' => route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']),
  189. ],
  190. 'pdfs' => [
  191. 'exam_paper_pdf' => null,
  192. 'grading_pdf' => null,
  193. ],
  194. 'stats' => $result['stats'] ?? [
  195. 'total_selected' => count($questions),
  196. 'mistake_based' => !empty($mistakeIds) || !empty($mistakeQuestionIds),
  197. ],
  198. 'created_at' => now()->toISOString(),
  199. ],
  200. ];
  201. return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);
  202. } catch (\Exception $e) {
  203. Log::error('Intelligent exam API failed', [
  204. 'error' => $e->getMessage(),
  205. 'trace' => $e->getTraceAsString(),
  206. ]);
  207. return response()->json([
  208. 'success' => false,
  209. 'message' => '服务异常,请稍后重试',
  210. ], 500);
  211. }
  212. }
  213. /**
  214. * 轮询任务状态
  215. */
  216. public function status(string $taskId): JsonResponse
  217. {
  218. try {
  219. $task = $this->taskManager->getTaskStatus($taskId);
  220. if (!$task) {
  221. return response()->json([
  222. 'success' => false,
  223. 'message' => '任务不存在',
  224. ], 404);
  225. }
  226. return response()->json([
  227. 'success' => true,
  228. 'data' => $task,
  229. ]);
  230. } catch (\Exception $e) {
  231. Log::error('查询任务状态失败', [
  232. 'task_id' => $taskId,
  233. 'error' => $e->getMessage(),
  234. ]);
  235. return response()->json([
  236. 'success' => false,
  237. 'message' => '查询失败,请稍后重试',
  238. ], 500);
  239. }
  240. }
  241. /**
  242. * 触发PDF生成
  243. * 使用队列进行异步处理
  244. */
  245. private function triggerPdfGeneration(string $taskId, string $paperId): void
  246. {
  247. // 异步处理PDF生成 - 将任务放入队列
  248. try {
  249. dispatch(new \App\Jobs\GenerateExamPdfJob($taskId, $paperId));
  250. Log::info('PDF生成任务已加入队列', [
  251. 'task_id' => $taskId,
  252. 'paper_id' => $paperId
  253. ]);
  254. } catch (\Exception $e) {
  255. Log::error('PDF生成任务队列失败,回退到同步处理', [
  256. 'task_id' => $taskId,
  257. 'paper_id' => $paperId,
  258. 'error' => $e->getMessage()
  259. ]);
  260. // 队列失败时回退到同步处理
  261. $this->processPdfGeneration($taskId, $paperId);
  262. }
  263. }
  264. /**
  265. * 处理PDF生成(模拟后台任务)
  266. * 在实际项目中,这个方法应该在队列worker中执行
  267. */
  268. private function processPdfGeneration(string $taskId, string $paperId): void
  269. {
  270. try {
  271. $this->taskManager->updateTaskProgress($taskId, 10, '开始生成试卷PDF...');
  272. // 生成试卷PDF
  273. $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
  274. ?? $this->questionBankService->exportExamToPdf($paperId)
  275. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  276. $this->taskManager->updateTaskProgress($taskId, 50, '试卷PDF生成完成,开始生成判卷PDF...');
  277. // 生成判卷PDF
  278. $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
  279. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  280. // 构建完整的试卷内容
  281. $paperModel = Paper::with('questions')->find($paperId);
  282. $examContent = $paperModel
  283. ? $this->paperPayloadService->buildExamContent($paperModel)
  284. : [];
  285. // 标记任务完成
  286. $this->taskManager->markTaskCompleted($taskId, [
  287. 'exam_content' => $examContent,
  288. 'pdfs' => [
  289. 'exam_paper_pdf' => $pdfUrl,
  290. 'grading_pdf' => $gradingPdfUrl,
  291. ],
  292. ]);
  293. Log::info('异步任务完成', [
  294. 'task_id' => $taskId,
  295. 'paper_id' => $paperId,
  296. 'pdf_url' => $pdfUrl,
  297. 'grading_pdf_url' => $gradingPdfUrl,
  298. ]);
  299. // 发送回调通知
  300. $this->taskManager->sendCallback($taskId);
  301. } catch (\Exception $e) {
  302. Log::error('PDF生成失败', [
  303. 'task_id' => $taskId,
  304. 'paper_id' => $paperId,
  305. 'error' => $e->getMessage(),
  306. ]);
  307. $this->taskManager->markTaskFailed($taskId, $e->getMessage());
  308. }
  309. }
  310. /**
  311. * 兼容字符串/数组入参
  312. */
  313. private function normalizePayload(array $payload): array
  314. {
  315. // 处理 kp_codes:空字符串或null转换为空数组
  316. if (isset($payload['kp_codes'])) {
  317. if (is_string($payload['kp_codes'])) {
  318. $kpCodes = trim($payload['kp_codes']);
  319. if (empty($kpCodes)) {
  320. $payload['kp_codes'] = [];
  321. } else {
  322. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
  323. }
  324. } elseif (!is_array($payload['kp_codes'])) {
  325. $payload['kp_codes'] = [];
  326. }
  327. } else {
  328. $payload['kp_codes'] = [];
  329. }
  330. if (isset($payload['skills']) && is_string($payload['skills'])) {
  331. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  332. }
  333. foreach (['mistake_ids', 'mistake_question_ids'] as $key) {
  334. if (isset($payload[$key])) {
  335. if (is_string($payload[$key])) {
  336. $raw = trim($payload[$key]);
  337. $payload[$key] = $raw === ''
  338. ? []
  339. : array_values(array_filter(array_map('trim', explode(',', $raw))));
  340. } elseif (!is_array($payload[$key])) {
  341. $payload[$key] = [];
  342. }
  343. }
  344. }
  345. return $payload;
  346. }
  347. private function normalizeQuestionTypeRatio(array $input): array
  348. {
  349. // 默认按 4:2:4
  350. $defaults = [
  351. '选择题' => 40,
  352. '填空题' => 20,
  353. '解答题' => 40,
  354. ];
  355. $normalized = [];
  356. foreach ($input as $key => $value) {
  357. if (!is_numeric($value)) {
  358. continue;
  359. }
  360. $type = $this->normalizeQuestionTypeKey($key);
  361. if ($type) {
  362. $normalized[$type] = (float) $value;
  363. }
  364. }
  365. $merged = array_merge($defaults, $normalized);
  366. // 归一化到 100%
  367. $sum = array_sum($merged);
  368. if ($sum > 0) {
  369. foreach ($merged as $k => $v) {
  370. $merged[$k] = round(($v / $sum) * 100, 2);
  371. }
  372. }
  373. return $merged;
  374. }
  375. private function normalizeQuestionTypeKey(string $key): ?string
  376. {
  377. $key = trim($key);
  378. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  379. return '选择题';
  380. }
  381. if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
  382. return '填空题';
  383. }
  384. if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  385. return '解答题';
  386. }
  387. return null;
  388. }
  389. private function normalizeDifficultyRatio(array $input): array
  390. {
  391. $defaults = [
  392. '基础' => 50,
  393. '中等' => 35,
  394. '拔高' => 15,
  395. ];
  396. $normalized = [];
  397. foreach ($input as $key => $value) {
  398. if (!is_numeric($value)) {
  399. continue;
  400. }
  401. $label = trim($key);
  402. if (in_array($label, ['基础', 'easy', '简单'])) {
  403. $normalized['基础'] = (float) $value;
  404. } elseif (in_array($label, ['中等', 'medium'])) {
  405. $normalized['中等'] = (float) $value;
  406. } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
  407. $normalized['拔高'] = (float) $value;
  408. }
  409. }
  410. return array_merge($defaults, $normalized);
  411. }
  412. private function normalizeDifficultyCategory(?string $category): string
  413. {
  414. if (!$category) {
  415. return '基础';
  416. }
  417. $category = trim($category);
  418. if (in_array($category, ['基础', '进阶', '中等', 'easy'])) {
  419. return $category === 'easy' ? '基础' : $category;
  420. }
  421. if (in_array($category, ['拔高', '困难', 'hard', '竞赛'])) {
  422. return '拔高';
  423. }
  424. return '基础';
  425. }
  426. private function hydrateQuestions(array $questions, array $kpCodes): array
  427. {
  428. $normalized = [];
  429. foreach ($questions as $question) {
  430. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  431. $score = $question['score'] ?? $this->defaultScore($type);
  432. $normalized[] = [
  433. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  434. 'question_id' => $question['question_id'] ?? null,
  435. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  436. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  437. 'content' => $question['content'] ?? $question['stem'] ?? '',
  438. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  439. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  440. 'solution' => $question['solution'] ?? '',
  441. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  442. 'score' => $score,
  443. 'estimated_time' => $question['estimated_time'] ?? 300,
  444. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  445. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  446. ];
  447. }
  448. return array_values(array_filter($normalized, fn ($q) => !empty($q['id'])));
  449. }
  450. private function guessType(array $question): string
  451. {
  452. if (!empty($question['options']) && is_array($question['options'])) {
  453. return '选择题';
  454. }
  455. $content = $question['stem'] ?? $question['content'] ?? '';
  456. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  457. return '填空题';
  458. }
  459. return '解答题';
  460. }
  461. private function defaultScore(string $type): int
  462. {
  463. if ($type === '选择题' || $type === '填空题') {
  464. return 5;
  465. }
  466. return 10;
  467. }
  468. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  469. {
  470. $questionIds = [];
  471. if (!empty($mistakeQuestionIds)) {
  472. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  473. }
  474. if (!empty($mistakeIds)) {
  475. $mistakeQuestionIdsFromDb = MistakeRecord::query()
  476. ->where('student_id', $studentId)
  477. ->whereIn('id', $mistakeIds)
  478. ->pluck('question_id')
  479. ->filter()
  480. ->values()
  481. ->all();
  482. $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
  483. }
  484. $questionIds = array_values(array_unique(array_filter($questionIds)));
  485. return $questionIds;
  486. }
  487. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  488. {
  489. if (empty($requestedIds)) {
  490. return $questions;
  491. }
  492. $order = array_flip($requestedIds);
  493. usort($questions, function ($a, $b) use ($order) {
  494. $aId = (string) ($a['id'] ?? '');
  495. $bId = (string) ($b['id'] ?? '');
  496. $aPos = $order[$aId] ?? PHP_INT_MAX;
  497. $bPos = $order[$bId] ?? PHP_INT_MAX;
  498. return $aPos <=> $bPos;
  499. });
  500. return $questions;
  501. }
  502. }