IntelligentExamController.php 20 KB

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