IntelligentExamController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. * 实际项目中应使用队列dispatch(new GenerateExamPdfJob($taskId, $paperId));
  244. */
  245. private function triggerPdfGeneration(string $taskId, string $paperId): void
  246. {
  247. // 实际项目中应该:
  248. // dispatch(new GenerateExamPdfJob($taskId, $paperId));
  249. // 目前使用同步调用模拟异步
  250. $this->processPdfGeneration($taskId, $paperId);
  251. }
  252. /**
  253. * 处理PDF生成(模拟后台任务)
  254. * 在实际项目中,这个方法应该在队列worker中执行
  255. */
  256. private function processPdfGeneration(string $taskId, string $paperId): void
  257. {
  258. try {
  259. $this->taskManager->updateTaskProgress($taskId, 10, '开始生成试卷PDF...');
  260. // 生成试卷PDF
  261. $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
  262. ?? $this->questionBankService->exportExamToPdf($paperId)
  263. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  264. $this->taskManager->updateTaskProgress($taskId, 50, '试卷PDF生成完成,开始生成判卷PDF...');
  265. // 生成判卷PDF
  266. $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
  267. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  268. // 构建完整的试卷内容
  269. $paperModel = Paper::with('questions')->find($paperId);
  270. $examContent = $paperModel
  271. ? $this->paperPayloadService->buildExamContent($paperModel)
  272. : [];
  273. // 标记任务完成
  274. $this->taskManager->markTaskCompleted($taskId, [
  275. 'exam_content' => $examContent,
  276. 'pdfs' => [
  277. 'exam_paper_pdf' => $pdfUrl,
  278. 'grading_pdf' => $gradingPdfUrl,
  279. ],
  280. ]);
  281. Log::info('异步任务完成', [
  282. 'task_id' => $taskId,
  283. 'paper_id' => $paperId,
  284. 'pdf_url' => $pdfUrl,
  285. 'grading_pdf_url' => $gradingPdfUrl,
  286. ]);
  287. // 发送回调通知
  288. $this->taskManager->sendCallback($taskId);
  289. } catch (\Exception $e) {
  290. Log::error('PDF生成失败', [
  291. 'task_id' => $taskId,
  292. 'paper_id' => $paperId,
  293. 'error' => $e->getMessage(),
  294. ]);
  295. $this->taskManager->markTaskFailed($taskId, $e->getMessage());
  296. }
  297. }
  298. /**
  299. * 兼容字符串/数组入参
  300. */
  301. private function normalizePayload(array $payload): array
  302. {
  303. // 处理 kp_codes:空字符串或null转换为空数组
  304. if (isset($payload['kp_codes'])) {
  305. if (is_string($payload['kp_codes'])) {
  306. $kpCodes = trim($payload['kp_codes']);
  307. if (empty($kpCodes)) {
  308. $payload['kp_codes'] = [];
  309. } else {
  310. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
  311. }
  312. } elseif (!is_array($payload['kp_codes'])) {
  313. $payload['kp_codes'] = [];
  314. }
  315. } else {
  316. $payload['kp_codes'] = [];
  317. }
  318. if (isset($payload['skills']) && is_string($payload['skills'])) {
  319. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  320. }
  321. foreach (['mistake_ids', 'mistake_question_ids'] as $key) {
  322. if (isset($payload[$key])) {
  323. if (is_string($payload[$key])) {
  324. $raw = trim($payload[$key]);
  325. $payload[$key] = $raw === ''
  326. ? []
  327. : array_values(array_filter(array_map('trim', explode(',', $raw))));
  328. } elseif (!is_array($payload[$key])) {
  329. $payload[$key] = [];
  330. }
  331. }
  332. }
  333. return $payload;
  334. }
  335. private function normalizeQuestionTypeRatio(array $input): array
  336. {
  337. // 默认按 4:2:4
  338. $defaults = [
  339. '选择题' => 40,
  340. '填空题' => 20,
  341. '解答题' => 40,
  342. ];
  343. $normalized = [];
  344. foreach ($input as $key => $value) {
  345. if (!is_numeric($value)) {
  346. continue;
  347. }
  348. $type = $this->normalizeQuestionTypeKey($key);
  349. if ($type) {
  350. $normalized[$type] = (float) $value;
  351. }
  352. }
  353. $merged = array_merge($defaults, $normalized);
  354. // 归一化到 100%
  355. $sum = array_sum($merged);
  356. if ($sum > 0) {
  357. foreach ($merged as $k => $v) {
  358. $merged[$k] = round(($v / $sum) * 100, 2);
  359. }
  360. }
  361. return $merged;
  362. }
  363. private function normalizeQuestionTypeKey(string $key): ?string
  364. {
  365. $key = trim($key);
  366. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  367. return '选择题';
  368. }
  369. if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
  370. return '填空题';
  371. }
  372. if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  373. return '解答题';
  374. }
  375. return null;
  376. }
  377. private function normalizeDifficultyRatio(array $input): array
  378. {
  379. $defaults = [
  380. '基础' => 50,
  381. '中等' => 35,
  382. '拔高' => 15,
  383. ];
  384. $normalized = [];
  385. foreach ($input as $key => $value) {
  386. if (!is_numeric($value)) {
  387. continue;
  388. }
  389. $label = trim($key);
  390. if (in_array($label, ['基础', 'easy', '简单'])) {
  391. $normalized['基础'] = (float) $value;
  392. } elseif (in_array($label, ['中等', 'medium'])) {
  393. $normalized['中等'] = (float) $value;
  394. } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
  395. $normalized['拔高'] = (float) $value;
  396. }
  397. }
  398. return array_merge($defaults, $normalized);
  399. }
  400. private function normalizeDifficultyCategory(?string $category): string
  401. {
  402. if (!$category) {
  403. return '基础';
  404. }
  405. $category = trim($category);
  406. if (in_array($category, ['基础', '进阶', '中等', 'easy'])) {
  407. return $category === 'easy' ? '基础' : $category;
  408. }
  409. if (in_array($category, ['拔高', '困难', 'hard', '竞赛'])) {
  410. return '拔高';
  411. }
  412. return '基础';
  413. }
  414. private function hydrateQuestions(array $questions, array $kpCodes): array
  415. {
  416. $normalized = [];
  417. foreach ($questions as $question) {
  418. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  419. $score = $question['score'] ?? $this->defaultScore($type);
  420. $normalized[] = [
  421. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  422. 'question_id' => $question['question_id'] ?? null,
  423. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  424. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  425. 'content' => $question['content'] ?? $question['stem'] ?? '',
  426. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  427. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  428. 'solution' => $question['solution'] ?? '',
  429. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  430. 'score' => $score,
  431. 'estimated_time' => $question['estimated_time'] ?? 300,
  432. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  433. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  434. ];
  435. }
  436. return array_values(array_filter($normalized, fn ($q) => !empty($q['id'])));
  437. }
  438. private function guessType(array $question): string
  439. {
  440. if (!empty($question['options']) && is_array($question['options'])) {
  441. return '选择题';
  442. }
  443. $content = $question['stem'] ?? $question['content'] ?? '';
  444. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  445. return '填空题';
  446. }
  447. return '解答题';
  448. }
  449. private function defaultScore(string $type): int
  450. {
  451. if ($type === '选择题' || $type === '填空题') {
  452. return 5;
  453. }
  454. return 10;
  455. }
  456. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  457. {
  458. $questionIds = [];
  459. if (!empty($mistakeQuestionIds)) {
  460. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  461. }
  462. if (!empty($mistakeIds)) {
  463. $mistakeQuestionIdsFromDb = MistakeRecord::query()
  464. ->where('student_id', $studentId)
  465. ->whereIn('id', $mistakeIds)
  466. ->pluck('question_id')
  467. ->filter()
  468. ->values()
  469. ->all();
  470. $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
  471. }
  472. $questionIds = array_values(array_unique(array_filter($questionIds)));
  473. return $questionIds;
  474. }
  475. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  476. {
  477. if (empty($requestedIds)) {
  478. return $questions;
  479. }
  480. $order = array_flip($requestedIds);
  481. usort($questions, function ($a, $b) use ($order) {
  482. $aId = (string) ($a['id'] ?? '');
  483. $bId = (string) ($b['id'] ?? '');
  484. $aPos = $order[$aId] ?? PHP_INT_MAX;
  485. $bPos = $order[$bId] ?? PHP_INT_MAX;
  486. return $aPos <=> $bPos;
  487. });
  488. return $questions;
  489. }
  490. }