IntelligentExamController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. return response()->json([
  121. 'success' => false,
  122. 'message' => $result['message'] ?? '智能出卷失败',
  123. ], 400);
  124. }
  125. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
  126. }
  127. if (empty($questions)) {
  128. return response()->json([
  129. 'success' => false,
  130. 'message' => '未能生成有效题目,请检查知识点或题库数据',
  131. ], 400);
  132. }
  133. $totalScore = array_sum(array_column($questions, 'score'));
  134. $totalQuestions = min($data['total_questions'], count($questions));
  135. $questions = array_slice($questions, 0, $totalQuestions);
  136. // 第二步:保存试卷到数据库(同步)
  137. $paperId = $this->questionBankService->saveExamToDatabase([
  138. 'paper_name' => $paperName,
  139. 'student_id' => $data['student_id'],
  140. 'teacher_id' => $data['teacher_id'] ?? null,
  141. 'difficulty_category' => $difficultyCategory,
  142. 'total_score' => $data['total_score'] ?? $totalScore,
  143. 'questions' => $questions,
  144. ]);
  145. if (!$paperId) {
  146. return response()->json([
  147. 'success' => false,
  148. 'message' => '试卷保存失败',
  149. ], 500);
  150. }
  151. // 第三步:创建异步任务(使用TaskManager)
  152. $taskId = $this->taskManager->createTask(TaskManager::TASK_TYPE_EXAM, array_merge($data, ['paper_id' => $paperId]));
  153. // 生成识别码
  154. $codes = $this->paperPayloadService->generatePaperCodes($paperId);
  155. // 立即返回完整的试卷数据(不等待PDF生成)
  156. $paperModel = Paper::with('questions')->find($paperId);
  157. $examContent = $paperModel
  158. ? $this->paperPayloadService->buildExamContent($paperModel)
  159. : [];
  160. // 触发后台PDF生成
  161. $this->triggerPdfGeneration($taskId, $paperId);
  162. $payload = [
  163. 'success' => true,
  164. 'message' => '智能试卷创建成功,PDF正在后台生成...',
  165. 'data' => [
  166. 'task_id' => $taskId,
  167. 'paper_id' => $paperId,
  168. 'status' => 'processing',
  169. // 识别码
  170. 'exam_code' => $codes['exam_code'], // 试卷识别码 (1+12位)
  171. 'grading_code' => $codes['grading_code'], // 判卷识别码 (2+12位)
  172. 'paper_id_num' => $codes['paper_id_num'], // 12位数字ID
  173. 'exam_content' => $examContent,
  174. 'urls' => [
  175. 'grading_url' => route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]),
  176. 'student_exam_url' => route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']),
  177. ],
  178. 'pdfs' => [
  179. 'exam_paper_pdf' => null,
  180. 'grading_pdf' => null,
  181. ],
  182. 'stats' => $result['stats'] ?? [
  183. 'total_selected' => count($questions),
  184. 'mistake_based' => !empty($mistakeIds) || !empty($mistakeQuestionIds),
  185. ],
  186. 'created_at' => now()->toISOString(),
  187. ],
  188. ];
  189. return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);
  190. } catch (\Exception $e) {
  191. Log::error('Intelligent exam API failed', [
  192. 'error' => $e->getMessage(),
  193. 'trace' => $e->getTraceAsString(),
  194. ]);
  195. return response()->json([
  196. 'success' => false,
  197. 'message' => '服务异常,请稍后重试',
  198. ], 500);
  199. }
  200. }
  201. /**
  202. * 轮询任务状态
  203. */
  204. public function status(string $taskId): JsonResponse
  205. {
  206. try {
  207. $task = $this->taskManager->getTaskStatus($taskId);
  208. if (!$task) {
  209. return response()->json([
  210. 'success' => false,
  211. 'message' => '任务不存在',
  212. ], 404);
  213. }
  214. return response()->json([
  215. 'success' => true,
  216. 'data' => $task,
  217. ]);
  218. } catch (\Exception $e) {
  219. Log::error('查询任务状态失败', [
  220. 'task_id' => $taskId,
  221. 'error' => $e->getMessage(),
  222. ]);
  223. return response()->json([
  224. 'success' => false,
  225. 'message' => '查询失败,请稍后重试',
  226. ], 500);
  227. }
  228. }
  229. /**
  230. * 触发PDF生成
  231. * 实际项目中应使用队列dispatch(new GenerateExamPdfJob($taskId, $paperId));
  232. */
  233. private function triggerPdfGeneration(string $taskId, string $paperId): void
  234. {
  235. // 实际项目中应该:
  236. // dispatch(new GenerateExamPdfJob($taskId, $paperId));
  237. // 目前使用同步调用模拟异步
  238. $this->processPdfGeneration($taskId, $paperId);
  239. }
  240. /**
  241. * 处理PDF生成(模拟后台任务)
  242. * 在实际项目中,这个方法应该在队列worker中执行
  243. */
  244. private function processPdfGeneration(string $taskId, string $paperId): void
  245. {
  246. try {
  247. $this->taskManager->updateTaskProgress($taskId, 10, '开始生成试卷PDF...');
  248. // 生成试卷PDF
  249. $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
  250. ?? $this->questionBankService->exportExamToPdf($paperId)
  251. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  252. $this->taskManager->updateTaskProgress($taskId, 50, '试卷PDF生成完成,开始生成判卷PDF...');
  253. // 生成判卷PDF
  254. $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
  255. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  256. // 构建完整的试卷内容
  257. $paperModel = Paper::with('questions')->find($paperId);
  258. $examContent = $paperModel
  259. ? $this->paperPayloadService->buildExamContent($paperModel)
  260. : [];
  261. // 标记任务完成
  262. $this->taskManager->markTaskCompleted($taskId, [
  263. 'exam_content' => $examContent,
  264. 'pdfs' => [
  265. 'exam_paper_pdf' => $pdfUrl,
  266. 'grading_pdf' => $gradingPdfUrl,
  267. ],
  268. ]);
  269. Log::info('异步任务完成', [
  270. 'task_id' => $taskId,
  271. 'paper_id' => $paperId,
  272. 'pdf_url' => $pdfUrl,
  273. 'grading_pdf_url' => $gradingPdfUrl,
  274. ]);
  275. // 发送回调通知
  276. $this->taskManager->sendCallback($taskId);
  277. } catch (\Exception $e) {
  278. Log::error('PDF生成失败', [
  279. 'task_id' => $taskId,
  280. 'paper_id' => $paperId,
  281. 'error' => $e->getMessage(),
  282. ]);
  283. $this->taskManager->markTaskFailed($taskId, $e->getMessage());
  284. }
  285. }
  286. /**
  287. * 兼容字符串/数组入参
  288. */
  289. private function normalizePayload(array $payload): array
  290. {
  291. // 处理 kp_codes:空字符串或null转换为空数组
  292. if (isset($payload['kp_codes'])) {
  293. if (is_string($payload['kp_codes'])) {
  294. $kpCodes = trim($payload['kp_codes']);
  295. if (empty($kpCodes)) {
  296. $payload['kp_codes'] = [];
  297. } else {
  298. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
  299. }
  300. } elseif (!is_array($payload['kp_codes'])) {
  301. $payload['kp_codes'] = [];
  302. }
  303. } else {
  304. $payload['kp_codes'] = [];
  305. }
  306. if (isset($payload['skills']) && is_string($payload['skills'])) {
  307. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  308. }
  309. foreach (['mistake_ids', 'mistake_question_ids'] as $key) {
  310. if (isset($payload[$key])) {
  311. if (is_string($payload[$key])) {
  312. $raw = trim($payload[$key]);
  313. $payload[$key] = $raw === ''
  314. ? []
  315. : array_values(array_filter(array_map('trim', explode(',', $raw))));
  316. } elseif (!is_array($payload[$key])) {
  317. $payload[$key] = [];
  318. }
  319. }
  320. }
  321. return $payload;
  322. }
  323. private function normalizeQuestionTypeRatio(array $input): array
  324. {
  325. // 默认按 4:2:4
  326. $defaults = [
  327. '选择题' => 40,
  328. '填空题' => 20,
  329. '解答题' => 40,
  330. ];
  331. $normalized = [];
  332. foreach ($input as $key => $value) {
  333. if (!is_numeric($value)) {
  334. continue;
  335. }
  336. $type = $this->normalizeQuestionTypeKey($key);
  337. if ($type) {
  338. $normalized[$type] = (float) $value;
  339. }
  340. }
  341. $merged = array_merge($defaults, $normalized);
  342. // 归一化到 100%
  343. $sum = array_sum($merged);
  344. if ($sum > 0) {
  345. foreach ($merged as $k => $v) {
  346. $merged[$k] = round(($v / $sum) * 100, 2);
  347. }
  348. }
  349. return $merged;
  350. }
  351. private function normalizeQuestionTypeKey(string $key): ?string
  352. {
  353. $key = trim($key);
  354. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
  355. return '选择题';
  356. }
  357. if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
  358. return '填空题';
  359. }
  360. if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
  361. return '解答题';
  362. }
  363. return null;
  364. }
  365. private function normalizeDifficultyRatio(array $input): array
  366. {
  367. $defaults = [
  368. '基础' => 50,
  369. '中等' => 35,
  370. '拔高' => 15,
  371. ];
  372. $normalized = [];
  373. foreach ($input as $key => $value) {
  374. if (!is_numeric($value)) {
  375. continue;
  376. }
  377. $label = trim($key);
  378. if (in_array($label, ['基础', 'easy', '简单'])) {
  379. $normalized['基础'] = (float) $value;
  380. } elseif (in_array($label, ['中等', 'medium'])) {
  381. $normalized['中等'] = (float) $value;
  382. } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
  383. $normalized['拔高'] = (float) $value;
  384. }
  385. }
  386. return array_merge($defaults, $normalized);
  387. }
  388. private function normalizeDifficultyCategory(?string $category): string
  389. {
  390. if (!$category) {
  391. return '基础';
  392. }
  393. $category = trim($category);
  394. if (in_array($category, ['基础', '进阶', '中等', 'easy'])) {
  395. return $category === 'easy' ? '基础' : $category;
  396. }
  397. if (in_array($category, ['拔高', '困难', 'hard', '竞赛'])) {
  398. return '拔高';
  399. }
  400. return '基础';
  401. }
  402. private function hydrateQuestions(array $questions, array $kpCodes): array
  403. {
  404. $normalized = [];
  405. foreach ($questions as $question) {
  406. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  407. $score = $question['score'] ?? $this->defaultScore($type);
  408. $normalized[] = [
  409. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  410. 'question_id' => $question['question_id'] ?? null,
  411. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  412. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  413. 'content' => $question['content'] ?? $question['stem'] ?? '',
  414. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  415. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  416. 'solution' => $question['solution'] ?? '',
  417. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  418. 'score' => $score,
  419. 'estimated_time' => $question['estimated_time'] ?? 300,
  420. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  421. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  422. ];
  423. }
  424. return array_values(array_filter($normalized, fn ($q) => !empty($q['id'])));
  425. }
  426. private function guessType(array $question): string
  427. {
  428. if (!empty($question['options']) && is_array($question['options'])) {
  429. return '选择题';
  430. }
  431. $content = $question['stem'] ?? $question['content'] ?? '';
  432. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  433. return '填空题';
  434. }
  435. return '解答题';
  436. }
  437. private function defaultScore(string $type): int
  438. {
  439. if ($type === '选择题' || $type === '填空题') {
  440. return 5;
  441. }
  442. return 10;
  443. }
  444. private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
  445. {
  446. $questionIds = [];
  447. if (!empty($mistakeQuestionIds)) {
  448. $questionIds = array_merge($questionIds, $mistakeQuestionIds);
  449. }
  450. if (!empty($mistakeIds)) {
  451. $mistakeQuestionIdsFromDb = MistakeRecord::query()
  452. ->where('student_id', $studentId)
  453. ->whereIn('id', $mistakeIds)
  454. ->pluck('question_id')
  455. ->filter()
  456. ->values()
  457. ->all();
  458. $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
  459. }
  460. $questionIds = array_values(array_unique(array_filter($questionIds)));
  461. return $questionIds;
  462. }
  463. private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
  464. {
  465. if (empty($requestedIds)) {
  466. return $questions;
  467. }
  468. $order = array_flip($requestedIds);
  469. usort($questions, function ($a, $b) use ($order) {
  470. $aId = (string) ($a['id'] ?? '');
  471. $bId = (string) ($b['id'] ?? '');
  472. $aPos = $order[$aId] ?? PHP_INT_MAX;
  473. $bPos = $order[$bId] ?? PHP_INT_MAX;
  474. return $aPos <=> $bPos;
  475. });
  476. return $questions;
  477. }
  478. }