IntelligentExamController.php 16 KB

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