IntelligentExamController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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 Illuminate\Http\JsonResponse;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Support\Facades\URL;
  13. class IntelligentExamController extends Controller
  14. {
  15. private LearningAnalyticsService $learningAnalyticsService;
  16. private QuestionBankService $questionBankService;
  17. private ExamPdfExportService $pdfExportService;
  18. public function __construct(
  19. LearningAnalyticsService $learningAnalyticsService,
  20. QuestionBankService $questionBankService,
  21. ExamPdfExportService $pdfExportService
  22. ) {
  23. $this->learningAnalyticsService = $learningAnalyticsService;
  24. $this->questionBankService = $questionBankService;
  25. $this->pdfExportService = $pdfExportService;
  26. }
  27. /**
  28. * 外部API:生成智能试卷,保存并返回 PDF/判卷链接
  29. */
  30. public function store(Request $request): JsonResponse
  31. {
  32. $normalized = $this->normalizePayload($request->all());
  33. $validator = validator($normalized, [
  34. 'student_id' => 'required|string',
  35. 'teacher_id' => 'required|string',
  36. 'paper_name' => 'nullable|string|max:255',
  37. 'grade' => 'nullable|string|max:50',
  38. 'total_questions' => 'required|integer|min:6|max:100',
  39. 'difficulty_category' => 'nullable|string',
  40. 'kp_codes' => 'required|array|min:1',
  41. 'kp_codes.*' => 'string',
  42. 'skills' => 'array',
  43. 'skills.*' => 'string',
  44. 'question_type_ratio' => 'array',
  45. 'difficulty_ratio' => 'array',
  46. 'total_score' => 'nullable|numeric|min:1|max:1000',
  47. ]);
  48. if ($validator->fails()) {
  49. return response()->json([
  50. 'success' => false,
  51. 'message' => '参数错误',
  52. 'errors' => $validator->errors()->toArray(),
  53. ], 422);
  54. }
  55. $data = $validator->validated();
  56. $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
  57. $difficultyRatio = $this->normalizeDifficultyRatio($data['difficulty_ratio'] ?? []);
  58. $paperName = $data['paper_name'] ?? ('智能试卷_' . now()->format('Ymd_His'));
  59. $difficultyCategory = $this->normalizeDifficultyCategory($data['difficulty_category'] ?? null);
  60. try {
  61. $result = $this->learningAnalyticsService->generateIntelligentExam([
  62. 'student_id' => $data['student_id'],
  63. 'grade' => $data['grade'] ?? null,
  64. 'total_questions' => $data['total_questions'],
  65. 'kp_codes' => $data['kp_codes'],
  66. 'skills' => $data['skills'] ?? [],
  67. 'question_type_ratio' => $questionTypeRatio,
  68. 'difficulty_ratio' => $difficultyRatio,
  69. ]);
  70. if (empty($result['success'])) {
  71. return response()->json([
  72. 'success' => false,
  73. 'message' => $result['message'] ?? '智能出卷失败',
  74. ], 400);
  75. }
  76. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
  77. if (empty($questions)) {
  78. return response()->json([
  79. 'success' => false,
  80. 'message' => '未能生成有效题目,请检查知识点或题库数据',
  81. ], 400);
  82. }
  83. $totalScore = array_sum(array_column($questions, 'score'));
  84. $paperId = $this->questionBankService->saveExamToDatabase([
  85. 'paper_name' => $paperName,
  86. 'student_id' => $data['student_id'],
  87. 'teacher_id' => $data['teacher_id'],
  88. 'difficulty_category' => $difficultyCategory,
  89. 'total_score' => $data['total_score'] ?? $totalScore,
  90. 'questions' => $questions,
  91. ]);
  92. if (!$paperId) {
  93. return response()->json([
  94. 'success' => false,
  95. 'message' => '试卷保存失败',
  96. ], 500);
  97. }
  98. $paperPayload = $this->buildPaperPayload($paperId);
  99. // 生成真实 PDF(试卷 + 判卷),若失败则回退到 HTML 预览
  100. $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
  101. ?? $this->questionBankService->exportExamToPdf($paperId)
  102. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  103. $gradingUrl = $this->pdfExportService->generateGradingPdf($paperId)
  104. ?? route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]);
  105. $payload = [
  106. 'success' => true,
  107. 'message' => '智能试卷生成成功',
  108. 'data' => [
  109. 'paper' => $paperPayload,
  110. 'pdf_url' => $pdfUrl,
  111. 'grading_url' => $gradingUrl,
  112. 'stats' => $result['stats'] ?? null,
  113. ],
  114. ];
  115. // 返回不转义的完整 URL
  116. return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);
  117. } catch (\Exception $e) {
  118. Log::error('Intelligent exam API failed', [
  119. 'error' => $e->getMessage(),
  120. 'trace' => $e->getTraceAsString(),
  121. ]);
  122. return response()->json([
  123. 'success' => false,
  124. 'message' => '服务异常,请稍后重试',
  125. ], 500);
  126. }
  127. }
  128. /**
  129. * 兼容字符串/数组入参
  130. */
  131. private function normalizePayload(array $payload): array
  132. {
  133. if (isset($payload['kp_codes']) && is_string($payload['kp_codes'])) {
  134. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $payload['kp_codes']))));
  135. }
  136. if (isset($payload['skills']) && is_string($payload['skills'])) {
  137. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  138. }
  139. return $payload;
  140. }
  141. private function normalizeQuestionTypeRatio(array $input): array
  142. {
  143. $defaults = [
  144. '选择题' => 40,
  145. '填空题' => 30,
  146. '解答题' => 30,
  147. ];
  148. $normalized = [];
  149. foreach ($input as $key => $value) {
  150. if (!is_numeric($value)) {
  151. continue;
  152. }
  153. $type = $this->normalizeQuestionTypeKey($key);
  154. if ($type) {
  155. $normalized[$type] = (float) $value;
  156. }
  157. }
  158. return array_merge($defaults, $normalized);
  159. }
  160. private function normalizeQuestionTypeKey(string $key): ?string
  161. {
  162. $key = trim($key);
  163. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice'])) {
  164. return '选择题';
  165. }
  166. if (in_array($key, ['fill', '填空题', 'blank'])) {
  167. return '填空题';
  168. }
  169. if (in_array($key, ['answer', '解答题', '计算题'])) {
  170. return '解答题';
  171. }
  172. return null;
  173. }
  174. private function normalizeDifficultyRatio(array $input): array
  175. {
  176. $defaults = [
  177. '基础' => 50,
  178. '中等' => 35,
  179. '拔高' => 15,
  180. ];
  181. $normalized = [];
  182. foreach ($input as $key => $value) {
  183. if (!is_numeric($value)) {
  184. continue;
  185. }
  186. $label = trim($key);
  187. if (in_array($label, ['基础', 'easy', '简单'])) {
  188. $normalized['基础'] = (float) $value;
  189. } elseif (in_array($label, ['中等', 'medium'])) {
  190. $normalized['中等'] = (float) $value;
  191. } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
  192. $normalized['拔高'] = (float) $value;
  193. }
  194. }
  195. return array_merge($defaults, $normalized);
  196. }
  197. private function normalizeDifficultyCategory(?string $category): string
  198. {
  199. if (!$category) {
  200. return '基础';
  201. }
  202. $category = trim($category);
  203. if (in_array($category, ['基础', '进阶', '中等', 'easy'])) {
  204. return $category === 'easy' ? '基础' : $category;
  205. }
  206. if (in_array($category, ['拔高', '困难', 'hard', '竞赛'])) {
  207. return '拔高';
  208. }
  209. return '基础';
  210. }
  211. private function hydrateQuestions(array $questions, array $kpCodes): array
  212. {
  213. $normalized = [];
  214. foreach ($questions as $question) {
  215. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  216. $score = $question['score'] ?? $this->defaultScore($type);
  217. $normalized[] = [
  218. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  219. 'question_id' => $question['question_id'] ?? null,
  220. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  221. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  222. 'content' => $question['content'] ?? $question['stem'] ?? '',
  223. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  224. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  225. 'solution' => $question['solution'] ?? '',
  226. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  227. 'score' => $score,
  228. 'estimated_time' => $question['estimated_time'] ?? 300,
  229. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  230. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  231. ];
  232. }
  233. return array_values(array_filter($normalized, fn ($q) => !empty($q['id'])));
  234. }
  235. private function guessType(array $question): string
  236. {
  237. if (!empty($question['options']) && is_array($question['options'])) {
  238. return '选择题';
  239. }
  240. $content = $question['stem'] ?? $question['content'] ?? '';
  241. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  242. return '填空题';
  243. }
  244. return '解答题';
  245. }
  246. private function defaultScore(string $type): int
  247. {
  248. if ($type === '选择题' || $type === '填空题') {
  249. return 5;
  250. }
  251. return 10;
  252. }
  253. private function buildPaperPayload(string $paperId): array
  254. {
  255. $paper = Paper::with('questions')->find($paperId);
  256. $questions = $paper ? $paper->questions : collect();
  257. return [
  258. 'paper_id' => $paperId,
  259. 'paper_name' => $paper?->paper_name ?? '',
  260. 'student_id' => $paper?->student_id ?? '',
  261. 'teacher_id' => $paper?->teacher_id ?? '',
  262. 'total_questions' => $questions->count(),
  263. 'total_score' => $paper?->total_score ?? 0,
  264. 'difficulty_category' => $paper?->difficulty_category ?? '基础',
  265. 'questions' => $questions->map(function (PaperQuestion $q) {
  266. return [
  267. 'question_bank_id' => $q->question_bank_id,
  268. 'question_number' => $q->question_number,
  269. 'question_type' => $q->question_type,
  270. 'knowledge_point' => $q->knowledge_point,
  271. 'difficulty' => $q->difficulty,
  272. 'score' => $q->score,
  273. 'estimated_time' => $q->estimated_time,
  274. ];
  275. })->toArray(),
  276. ];
  277. }
  278. }