| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555 |
- <?php
- namespace App\Http\Controllers\Api;
- use App\Http\Controllers\Controller;
- use App\Models\Paper;
- use App\Models\PaperQuestion;
- use App\Services\LearningAnalyticsService;
- use App\Services\ExamPdfExportService;
- use App\Services\QuestionBankService;
- use App\Services\PaperPayloadService;
- use App\Services\TaskManager;
- use App\Models\MistakeRecord;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\URL;
- class IntelligentExamController extends Controller
- {
- private LearningAnalyticsService $learningAnalyticsService;
- private QuestionBankService $questionBankService;
- private ExamPdfExportService $pdfExportService;
- private PaperPayloadService $paperPayloadService;
- private TaskManager $taskManager;
- public function __construct(
- LearningAnalyticsService $learningAnalyticsService,
- QuestionBankService $questionBankService,
- ExamPdfExportService $pdfExportService,
- PaperPayloadService $paperPayloadService,
- TaskManager $taskManager
- ) {
- $this->learningAnalyticsService = $learningAnalyticsService;
- $this->questionBankService = $questionBankService;
- $this->pdfExportService = $pdfExportService;
- $this->paperPayloadService = $paperPayloadService;
- $this->taskManager = $taskManager;
- }
- /**
- * 外部API:生成智能试卷(异步模式)
- * 立即返回任务ID,PDF生成在后台进行,完成后通过回调通知
- */
- public function store(Request $request): JsonResponse
- {
- $normalized = $this->normalizePayload($request->all());
- $validator = validator($normalized, [
- 'student_id' => 'required|string',
- 'teacher_id' => 'required|string',
- 'paper_name' => 'nullable|string|max:255',
- 'grade' => 'nullable|string|max:50',
- 'total_questions' => 'required|integer|min:6|max:100',
- 'difficulty_category' => 'nullable|string',
- 'kp_codes' => 'nullable|array',
- 'kp_codes.*' => 'string',
- 'skills' => 'array',
- 'skills.*' => 'string',
- 'question_type_ratio' => 'array',
- 'difficulty_ratio' => 'array',
- 'total_score' => 'nullable|numeric|min:1|max:1000',
- 'mistake_ids' => 'nullable|array',
- 'mistake_ids.*' => 'string',
- 'mistake_question_ids' => 'nullable|array',
- 'mistake_question_ids.*' => 'string',
- ]);
- if ($validator->fails()) {
- return response()->json([
- 'success' => false,
- 'message' => '参数错误',
- 'errors' => $validator->errors()->toArray(),
- ], 422);
- }
- $data = $validator->validated();
- // 确保 kp_codes 是数组
- $data['kp_codes'] = $data['kp_codes'] ?? [];
- if (!is_array($data['kp_codes'])) {
- $data['kp_codes'] = [];
- }
- $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
- $difficultyRatio = $this->normalizeDifficultyRatio($data['difficulty_ratio'] ?? []);
- $paperName = $data['paper_name'] ?? ('智能试卷_' . now()->format('Ymd_His'));
- $difficultyCategory = $this->normalizeDifficultyCategory($data['difficulty_category'] ?? null);
- $mistakeIds = $data['mistake_ids'] ?? [];
- $mistakeQuestionIds = $data['mistake_question_ids'] ?? [];
- try {
- $questions = [];
- $result = null;
- if (!empty($mistakeIds) || !empty($mistakeQuestionIds)) {
- $questionIds = $this->resolveMistakeQuestionIds(
- $data['student_id'],
- $mistakeIds,
- $mistakeQuestionIds
- );
- if (empty($questionIds)) {
- return response()->json([
- 'success' => false,
- 'message' => '未找到可用的错题题目,请检查错题ID或学生ID',
- ], 400);
- }
- $bankQuestions = $this->questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
- if (empty($bankQuestions)) {
- return response()->json([
- 'success' => false,
- 'message' => '错题对应的题库题目不存在或不可用',
- ], 400);
- }
- $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes']);
- $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
- $paperName = $data['paper_name'] ?? ('错题复习_' . $data['student_id'] . '_' . now()->format('Ymd_His'));
- } else {
- // 第一步:生成智能试卷(同步)
- $result = $this->learningAnalyticsService->generateIntelligentExam([
- 'student_id' => $data['student_id'],
- 'grade' => $data['grade'] ?? null,
- 'total_questions' => $data['total_questions'],
- 'kp_codes' => $data['kp_codes'],
- 'skills' => $data['skills'] ?? [],
- 'question_type_ratio' => $questionTypeRatio,
- 'difficulty_ratio' => $difficultyRatio,
- ]);
- if (empty($result['success'])) {
- return response()->json([
- 'success' => false,
- 'message' => $result['message'] ?? '智能出卷失败',
- ], 400);
- }
- $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
- }
- if (empty($questions)) {
- return response()->json([
- 'success' => false,
- 'message' => '未能生成有效题目,请检查知识点或题库数据',
- ], 400);
- }
- $totalScore = array_sum(array_column($questions, 'score'));
- $totalQuestions = min($data['total_questions'], count($questions));
- $questions = array_slice($questions, 0, $totalQuestions);
- // 第二步:保存试卷到数据库(同步)
- $paperId = $this->questionBankService->saveExamToDatabase([
- 'paper_name' => $paperName,
- 'student_id' => $data['student_id'],
- 'teacher_id' => $data['teacher_id'],
- 'difficulty_category' => $difficultyCategory,
- 'total_score' => $data['total_score'] ?? $totalScore,
- 'questions' => $questions,
- ]);
- if (!$paperId) {
- return response()->json([
- 'success' => false,
- 'message' => '试卷保存失败',
- ], 500);
- }
- // 第三步:创建异步任务(使用TaskManager)
- $taskId = $this->taskManager->createTask(TaskManager::TASK_TYPE_EXAM, array_merge($data, ['paper_id' => $paperId]));
- // 生成识别码
- $codes = $this->paperPayloadService->generatePaperCodes($paperId);
- // 立即返回完整的试卷数据(不等待PDF生成)
- $paperModel = Paper::with('questions')->find($paperId);
- $examContent = $paperModel
- ? $this->paperPayloadService->buildExamContent($paperModel)
- : [];
- // 触发后台PDF生成
- $this->triggerPdfGeneration($taskId, $paperId);
- $payload = [
- 'success' => true,
- 'message' => '智能试卷创建成功,PDF正在后台生成...',
- 'data' => [
- 'task_id' => $taskId,
- 'paper_id' => $paperId,
- 'status' => 'processing',
- // 识别码
- 'exam_code' => $codes['exam_code'], // 试卷识别码 (1+12位)
- 'grading_code' => $codes['grading_code'], // 判卷识别码 (2+12位)
- 'paper_id_num' => $codes['paper_id_num'], // 12位数字ID
- 'exam_content' => $examContent,
- 'urls' => [
- 'grading_url' => route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]),
- 'student_exam_url' => route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']),
- ],
- 'pdfs' => [
- 'exam_paper_pdf' => null,
- 'grading_pdf' => null,
- ],
- 'stats' => $result['stats'] ?? [
- 'total_selected' => count($questions),
- 'mistake_based' => !empty($mistakeIds) || !empty($mistakeQuestionIds),
- ],
- 'created_at' => now()->toISOString(),
- ],
- ];
- return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);
- } catch (\Exception $e) {
- Log::error('Intelligent exam API failed', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- return response()->json([
- 'success' => false,
- 'message' => '服务异常,请稍后重试',
- ], 500);
- }
- }
- /**
- * 轮询任务状态
- */
- public function status(string $taskId): JsonResponse
- {
- try {
- $task = $this->taskManager->getTaskStatus($taskId);
- if (!$task) {
- return response()->json([
- 'success' => false,
- 'message' => '任务不存在',
- ], 404);
- }
- return response()->json([
- 'success' => true,
- 'data' => $task,
- ]);
- } catch (\Exception $e) {
- Log::error('查询任务状态失败', [
- 'task_id' => $taskId,
- 'error' => $e->getMessage(),
- ]);
- return response()->json([
- 'success' => false,
- 'message' => '查询失败,请稍后重试',
- ], 500);
- }
- }
- /**
- * 触发PDF生成
- * 实际项目中应使用队列dispatch(new GenerateExamPdfJob($taskId, $paperId));
- */
- private function triggerPdfGeneration(string $taskId, string $paperId): void
- {
- // 实际项目中应该:
- // dispatch(new GenerateExamPdfJob($taskId, $paperId));
- // 目前使用同步调用模拟异步
- $this->processPdfGeneration($taskId, $paperId);
- }
- /**
- * 处理PDF生成(模拟后台任务)
- * 在实际项目中,这个方法应该在队列worker中执行
- */
- private function processPdfGeneration(string $taskId, string $paperId): void
- {
- try {
- $this->taskManager->updateTaskProgress($taskId, 10, '开始生成试卷PDF...');
- // 生成试卷PDF
- $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
- ?? $this->questionBankService->exportExamToPdf($paperId)
- ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
- $this->taskManager->updateTaskProgress($taskId, 50, '试卷PDF生成完成,开始生成判卷PDF...');
- // 生成判卷PDF
- $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
- ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
- // 构建完整的试卷内容
- $paperModel = Paper::with('questions')->find($paperId);
- $examContent = $paperModel
- ? $this->paperPayloadService->buildExamContent($paperModel)
- : [];
- // 标记任务完成
- $this->taskManager->markTaskCompleted($taskId, [
- 'exam_content' => $examContent,
- 'pdfs' => [
- 'exam_paper_pdf' => $pdfUrl,
- 'grading_pdf' => $gradingPdfUrl,
- ],
- ]);
- Log::info('异步任务完成', [
- 'task_id' => $taskId,
- 'paper_id' => $paperId,
- 'pdf_url' => $pdfUrl,
- 'grading_pdf_url' => $gradingPdfUrl,
- ]);
- // 发送回调通知
- $this->taskManager->sendCallback($taskId);
- } catch (\Exception $e) {
- Log::error('PDF生成失败', [
- 'task_id' => $taskId,
- 'paper_id' => $paperId,
- 'error' => $e->getMessage(),
- ]);
- $this->taskManager->markTaskFailed($taskId, $e->getMessage());
- }
- }
- /**
- * 兼容字符串/数组入参
- */
- private function normalizePayload(array $payload): array
- {
- // 处理 kp_codes:空字符串或null转换为空数组
- if (isset($payload['kp_codes'])) {
- if (is_string($payload['kp_codes'])) {
- $kpCodes = trim($payload['kp_codes']);
- if (empty($kpCodes)) {
- $payload['kp_codes'] = [];
- } else {
- $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
- }
- } elseif (!is_array($payload['kp_codes'])) {
- $payload['kp_codes'] = [];
- }
- } else {
- $payload['kp_codes'] = [];
- }
- if (isset($payload['skills']) && is_string($payload['skills'])) {
- $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
- }
- foreach (['mistake_ids', 'mistake_question_ids'] as $key) {
- if (isset($payload[$key])) {
- if (is_string($payload[$key])) {
- $raw = trim($payload[$key]);
- $payload[$key] = $raw === ''
- ? []
- : array_values(array_filter(array_map('trim', explode(',', $raw))));
- } elseif (!is_array($payload[$key])) {
- $payload[$key] = [];
- }
- }
- }
- return $payload;
- }
- private function normalizeQuestionTypeRatio(array $input): array
- {
- // 默认按 4:2:4
- $defaults = [
- '选择题' => 40,
- '填空题' => 20,
- '解答题' => 40,
- ];
- $normalized = [];
- foreach ($input as $key => $value) {
- if (!is_numeric($value)) {
- continue;
- }
- $type = $this->normalizeQuestionTypeKey($key);
- if ($type) {
- $normalized[$type] = (float) $value;
- }
- }
- $merged = array_merge($defaults, $normalized);
- // 归一化到 100%
- $sum = array_sum($merged);
- if ($sum > 0) {
- foreach ($merged as $k => $v) {
- $merged[$k] = round(($v / $sum) * 100, 2);
- }
- }
- return $merged;
- }
- private function normalizeQuestionTypeKey(string $key): ?string
- {
- $key = trim($key);
- if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
- return '选择题';
- }
- if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
- return '填空题';
- }
- if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
- return '解答题';
- }
- return null;
- }
- private function normalizeDifficultyRatio(array $input): array
- {
- $defaults = [
- '基础' => 50,
- '中等' => 35,
- '拔高' => 15,
- ];
- $normalized = [];
- foreach ($input as $key => $value) {
- if (!is_numeric($value)) {
- continue;
- }
- $label = trim($key);
- if (in_array($label, ['基础', 'easy', '简单'])) {
- $normalized['基础'] = (float) $value;
- } elseif (in_array($label, ['中等', 'medium'])) {
- $normalized['中等'] = (float) $value;
- } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
- $normalized['拔高'] = (float) $value;
- }
- }
- return array_merge($defaults, $normalized);
- }
- private function normalizeDifficultyCategory(?string $category): string
- {
- if (!$category) {
- return '基础';
- }
- $category = trim($category);
- if (in_array($category, ['基础', '进阶', '中等', 'easy'])) {
- return $category === 'easy' ? '基础' : $category;
- }
- if (in_array($category, ['拔高', '困难', 'hard', '竞赛'])) {
- return '拔高';
- }
- return '基础';
- }
- private function hydrateQuestions(array $questions, array $kpCodes): array
- {
- $normalized = [];
- foreach ($questions as $question) {
- $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
- $score = $question['score'] ?? $this->defaultScore($type);
- $normalized[] = [
- 'id' => $question['id'] ?? $question['question_id'] ?? null,
- 'question_id' => $question['question_id'] ?? null,
- 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
- 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
- 'content' => $question['content'] ?? $question['stem'] ?? '',
- 'options' => $question['options'] ?? ($question['choices'] ?? []),
- 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
- 'solution' => $question['solution'] ?? '',
- 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
- 'score' => $score,
- 'estimated_time' => $question['estimated_time'] ?? 300,
- 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
- 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
- ];
- }
- return array_values(array_filter($normalized, fn ($q) => !empty($q['id'])));
- }
- private function guessType(array $question): string
- {
- if (!empty($question['options']) && is_array($question['options'])) {
- return '选择题';
- }
- $content = $question['stem'] ?? $question['content'] ?? '';
- if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
- return '填空题';
- }
- return '解答题';
- }
- private function defaultScore(string $type): int
- {
- if ($type === '选择题' || $type === '填空题') {
- return 5;
- }
- return 10;
- }
- private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
- {
- $questionIds = [];
- if (!empty($mistakeQuestionIds)) {
- $questionIds = array_merge($questionIds, $mistakeQuestionIds);
- }
- if (!empty($mistakeIds)) {
- $mistakeQuestionIdsFromDb = MistakeRecord::query()
- ->where('student_id', $studentId)
- ->whereIn('id', $mistakeIds)
- ->pluck('question_id')
- ->filter()
- ->values()
- ->all();
- $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
- }
- $questionIds = array_values(array_unique(array_filter($questionIds)));
- return $questionIds;
- }
- private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
- {
- if (empty($requestedIds)) {
- return $questions;
- }
- $order = array_flip($requestedIds);
- usort($questions, function ($a, $b) use ($order) {
- $aId = (string) ($a['id'] ?? '');
- $bId = (string) ($b['id'] ?? '');
- $aPos = $order[$aId] ?? PHP_INT_MAX;
- $bPos = $order[$bId] ?? PHP_INT_MAX;
- return $aPos <=> $bPos;
- });
- return $questions;
- }
- }
|