| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980 |
- <?php
- namespace App\Services;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Facades\Log;
- class QuestionBankService
- {
- protected string $baseUrl;
- public function __construct()
- {
- // 从配置文件读取base_url
- $this->baseUrl = config('services.question_bank.base_url', env('QUESTION_BANK_API_BASE', 'http://localhost:5015'));
- $this->baseUrl = rtrim($this->baseUrl, '/');
- }
- /**
- * 获取题目列表
- */
- public function listQuestions(int $page = 1, int $perPage = 50, array $filters = []): array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/questions', [
- 'page' => $page,
- 'per_page' => $perPage,
- ...$filters
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('题库API调用失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取题目列表失败', [
- 'error' => $e->getMessage()
- ]);
- }
- return ['data' => [], 'meta' => ['total' => 0]];
- }
- /**
- * 获取题目详情
- */
- public function getQuestion(string $questionCode): ?array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . "/questions/{$questionCode}");
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取题目详情失败', [
- 'code' => $questionCode,
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取题目详情异常', [
- 'code' => $questionCode,
- 'error' => $e->getMessage()
- ]);
- }
- return null;
- }
- /**
- * 更新题目
- */
- public function updateQuestion(string $questionCode, array $payload): bool
- {
- try {
- $response = Http::timeout(10)
- ->patch($this->baseUrl . "/questions/{$questionCode}", $payload);
- if ($response->successful()) {
- return true;
- }
- Log::warning('更新题目失败', [
- 'code' => $questionCode,
- 'status' => $response->status(),
- 'body' => $response->json(),
- ]);
- } catch (\Exception $e) {
- Log::error('更新题目异常', [
- 'code' => $questionCode,
- 'error' => $e->getMessage()
- ]);
- }
- return false;
- }
- /**
- * 筛选题目 (支持 kp_codes, skills 等高级筛选)
- */
- public function filterQuestions(array $params): array
- {
- try {
- $response = Http::timeout(30)
- ->get($this->baseUrl . '/questions', $params);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('筛选题目API调用失败', [
- 'status' => $response->status(),
- 'params' => $params
- ]);
- } catch (\Exception $e) {
- Log::error('筛选题目异常', [
- 'error' => $e->getMessage(),
- 'params' => $params
- ]);
- }
- return ['data' => []];
- }
- /**
- * 批量获取题目详情(根据题目 ID 列表)
- */
- public function getQuestionsByIds(array $ids): array
- {
- if (empty($ids)) {
- return ['data' => []];
- }
- try {
- $response = Http::timeout(15)
- ->get($this->baseUrl . '/questions', [
- 'ids' => implode(',', $ids),
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('批量获取题目失败', [
- 'ids' => $ids,
- 'status' => $response->status(),
- ]);
- } catch (\Exception $e) {
- Log::error('批量获取题目异常', [
- 'ids' => $ids,
- 'error' => $e->getMessage(),
- ]);
- }
- return ['data' => []];
- }
- /**
- * 智能生成题目(异步模式)
- */
- public function generateIntelligentQuestions(array $params, ?string $callbackUrl = null): array
- {
- try {
- // 添加回调 URL
- if ($callbackUrl) {
- $params['callback_url'] = $callbackUrl;
- }
- // 增加超时时间到60秒,确保有足够时间启动异步任务
- // 注意:API是异步的,只需等待任务启动(1-2秒),不需要等待AI生成完成
- $response = Http::timeout(60)
- ->post($this->baseUrl . '/generate-intelligent-questions', $params);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('题目生成API调用失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('题目生成异常', [
- 'error' => $e->getMessage()
- ]);
- }
- return ['success' => false, 'message' => '生成失败'];
- }
- /**
- * 获取任务状态
- */
- public function getTaskStatus(string $taskId): ?array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/tasks/' . $taskId);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取任务状态失败', [
- 'task_id' => $taskId,
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取任务状态异常', [
- 'task_id' => $taskId,
- 'error' => $e->getMessage()
- ]);
- }
- return null;
- }
- /**
- * 获取任务列表
- */
- public function listTasks(?string $status = null, int $page = 1, int $perPage = 10): array
- {
- try {
- $params = [
- 'page' => $page,
- 'per_page' => $perPage
- ];
- if ($status) {
- $params['status'] = $status;
- }
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/tasks', $params);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取任务列表失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取任务列表异常', [
- 'error' => $e->getMessage()
- ]);
- }
- return ['data' => [], 'meta' => ['total' => 0]];
- }
- /**
- * 获取题目统计信息
- */
- public function getStatistics(): array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/questions/statistics');
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取题目统计失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取题目统计异常', [
- 'error' => $e->getMessage()
- ]);
- }
- return [
- 'total' => 0,
- 'by_difficulty' => [],
- 'by_kp' => [],
- 'by_source' => []
- ];
- }
- /**
- * 根据知识点获取题目
- */
- public function getQuestionsByKpCode(string $kpCode, int $limit = 100): array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/questions', [
- 'kp_code' => $kpCode,
- 'limit' => $limit
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- } catch (\Exception $e) {
- Log::error('根据知识点获取题目失败', [
- 'kp_code' => $kpCode,
- 'error' => $e->getMessage()
- ]);
- }
- return [];
- }
- /**
- * 删除题目
- */
- public function deleteQuestion(string $questionCode): bool
- {
- try {
- $response = Http::timeout(10)
- ->delete($this->baseUrl . "/questions/{$questionCode}");
- // 只有返回204(删除成功)才返回true,404(不存在)返回false
- if ($response->status() === 204) {
- return true;
- }
- if ($response->status() === 404) {
- Log::warning('尝试删除不存在的题目', ['question_code' => $questionCode]);
- return false;
- }
- return false;
- } catch (\Exception $e) {
- Log::error('删除题目失败', [
- 'question_code' => $questionCode,
- 'error' => $e->getMessage()
- ]);
- return false;
- }
- }
- /**
- * 智能选择试卷题目
- */
- public function selectQuestionsForExam(int $totalQuestions, array $filters): array
- {
- try {
- $response = Http::timeout(30)
- ->post($this->baseUrl . '/exam/select-questions', [
- 'total_questions' => $totalQuestions,
- 'filters' => $filters
- ]);
- if ($response->successful()) {
- return $response->json('data', []);
- }
- Log::warning('智能选题API调用失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('智能选题异常', [
- 'error' => $e->getMessage()
- ]);
- }
- return [];
- }
- /**
- * 保存试卷到数据库(本地 papers 表)
- */
- public function saveExamToDatabase(array $examData): ?string
- {
- // 数据完整性检查
- if (empty($examData['questions'])) {
- Log::warning('尝试保存没有题目的试卷', [
- 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
- 'student_id' => $examData['student_id'] ?? 'unknown'
- ]);
- return null;
- }
- try {
- // 使用数据库事务确保数据一致性
- return \Illuminate\Support\Facades\DB::transaction(function () use ($examData) {
- // 生成试卷ID
- $paperId = 'paper_' . time() . '_' . bin2hex(random_bytes(4));
- Log::info('开始保存试卷到数据库', [
- 'paper_id' => $paperId,
- 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
- 'question_count' => count($examData['questions'])
- ]);
- // 使用Laravel模型保存到 papers 表
- $paper = \App\Models\Paper::create([
- 'paper_id' => $paperId,
- 'student_id' => $examData['student_id'] ?? '',
- 'teacher_id' => $examData['teacher_id'] ?? '',
- 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
- 'paper_type' => 'auto_generated',
- 'question_count' => count($examData['questions']), // 使用实际题目数量
- 'total_score' => $examData['total_score'] ?? 0,
- 'status' => 'draft',
- 'difficulty_category' => $examData['difficulty_category'] ?? '基础',
- ]);
- // 准备题目数据
- $questionInsertData = [];
- foreach ($examData['questions'] as $index => $question) {
- // 验证题目基本数据
- if (empty($question['stem']) && empty($question['content'])) {
- Log::warning('跳过没有内容的题目', [
- 'paper_id' => $paperId,
- 'question_index' => $index
- ]);
- continue;
- }
- // 处理难度字段:如果是字符串则转换为数字
- $difficultyValue = $question['difficulty'] ?? 0.5;
- if (is_string($difficultyValue)) {
- // 将中文难度转换为数字
- if (strpos($difficultyValue, '基础') !== false || strpos($difficultyValue, '简单') !== false) {
- $difficultyValue = 0.3;
- } elseif (strpos($difficultyValue, '中等') !== false || strpos($difficultyValue, '一般') !== false) {
- $difficultyValue = 0.6;
- } elseif (strpos($difficultyValue, '拔高') !== false || strpos($difficultyValue, '困难') !== false) {
- $difficultyValue = 0.9;
- } else {
- $difficultyValue = 0.5;
- }
- }
- // 确保 knowledge_point 有值
- $knowledgePoint = $question['kp'] ?? $question['kp_code'] ?? $question['knowledge_point'] ?? $question['knowledge_point_code'] ?? '';
- if (empty($knowledgePoint) && isset($question['kp_code'])) {
- $knowledgePoint = $question['kp_code'];
- }
- // 获取题目类型
- $questionType = $question['question_type'] ?? 'answer';
- if (!$questionType) {
- // 如果没有类型,根据内容推断
- $content = $question['stem'] ?? $question['content'] ?? '';
- if (is_string($content)) {
- // 1. 优先检查填空题(下划线)
- if (strpos($content, '____') !== false || strpos($content, '______') !== false) {
- $questionType = 'fill';
- }
- // 2. 检查选择题(必须有选项 A. B. C. D.)
- elseif (preg_match('/[A-D]\s*\./', $content) || preg_match('/\([A-D]\)/', $content)) {
- if (preg_match('/A\./', $content) && preg_match('/B\./', $content)) {
- $questionType = 'choice';
- } else {
- // 只有括号没有选项,可能是填空
- if (strpos($content, '()') !== false || strpos($content, '()') !== false) {
- $questionType = 'fill';
- } else {
- $questionType = 'answer';
- }
- }
- }
- // 3. 检查纯括号填空
- elseif (strpos($content, '()') !== false || strpos($content, '()') !== false) {
- $questionType = 'fill';
- }
- else {
- $questionType = 'answer';
- }
- } else {
- $questionType = 'answer';
- }
- }
- $questionInsertData[] = [
- 'paper_id' => $paperId,
- 'question_id' => $question['question_code'] ?? $question['question_id'] ?? null,
- 'question_bank_id' => $question['id'] ?? $question['question_id'] ?? 0,
- 'knowledge_point' => $knowledgePoint,
- 'question_type' => $questionType,
- 'question_text' => $question['stem'] ?? $question['content'] ?? $question['question_text'] ?? '',
- 'difficulty' => $difficultyValue,
- 'score' => $question['score'] ?? 5, // 默认5分
- 'estimated_time' => $question['estimated_time'] ?? 300,
- 'question_number' => $index + 1,
- ];
- }
- // 验证是否有有效的题目数据
- if (empty($questionInsertData)) {
- Log::error('没有有效的题目数据可以保存', ['paper_id' => $paperId]);
- throw new \Exception('没有有效的题目数据');
- }
- // 使用Laravel模型批量插入题目数据
- \App\Models\PaperQuestion::insert($questionInsertData);
- // 验证插入结果,使用关联关系
- $insertedQuestionCount = $paper->questions()->count();
- if ($insertedQuestionCount !== count($questionInsertData)) {
- throw new \Exception("题目插入数量不匹配:预期 {$insertedQuestionCount},实际 " . count($questionInsertData));
- }
- Log::info('试卷保存成功', [
- 'paper_id' => $paperId,
- 'expected_questions' => count($questionInsertData),
- 'actual_questions' => $insertedQuestionCount,
- 'paper_name' => $paper->paper_name
- ]);
- return $paperId;
- });
- } catch (\Exception $e) {
- Log::error('保存试卷到数据库失败', [
- 'error' => $e->getMessage(),
- 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
- 'student_id' => $examData['student_id'] ?? 'unknown',
- 'question_count' => count($examData['questions'] ?? []),
- 'trace' => $e->getTraceAsString()
- ]);
- return null;
- }
- }
- /**
- * 检查数据完整性 - 发现没有题目的试卷
- */
- public function checkDataIntegrity(): array
- {
- try {
- // 使用Laravel模型查找显示有题目但实际没有题目的试卷
- $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
- ->whereDoesntHave('questions')
- ->get();
- Log::warning('发现数据不一致的试卷', [
- 'count' => $inconsistentPapers->count(),
- 'papers' => $inconsistentPapers->map(function($paper) {
- return [
- 'paper_id' => $paper->paper_id,
- 'paper_name' => $paper->paper_name,
- 'expected_questions' => $paper->question_count,
- 'student_id' => $paper->student_id,
- 'created_at' => $paper->created_at
- ];
- })->toArray()
- ]);
- return [
- 'inconsistent_count' => $inconsistentPapers->count(),
- 'papers' => $inconsistentPapers->toArray()
- ];
- } catch (\Exception $e) {
- Log::error('检查数据完整性失败', ['error' => $e->getMessage()]);
- return ['inconsistent_count' => 0, 'papers' => []];
- }
- }
- /**
- * 清理没有题目的试卷记录
- */
- public function cleanupInconsistentPapers(): int
- {
- try {
- return \Illuminate\Support\Facades\DB::transaction(function () {
- // 使用Laravel模型查找显示有题目但实际没有题目的试卷
- $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
- ->whereDoesntHave('questions')
- ->get();
- if ($inconsistentPapers->isEmpty()) {
- return 0;
- }
- // 获取要删除的试卷ID列表
- $deletedPaperIds = $inconsistentPapers->pluck('paper_id')->toArray();
- // 使用Laravel模型删除这些不一致的试卷记录
- $deletedCount = \App\Models\Paper::whereIn('paper_id', $deletedPaperIds)->delete();
- Log::info('清理不一致的试卷记录', [
- 'deleted_count' => $deletedCount,
- 'deleted_paper_ids' => $deletedPaperIds
- ]);
- return $deletedCount;
- });
- } catch (\Exception $e) {
- Log::error('清理不一致试卷失败', ['error' => $e->getMessage()]);
- return 0;
- }
- }
- /**
- * 修复试卷的题目数量统计
- */
- public function fixPaperQuestionCounts(): int
- {
- try {
- $fixedCount = 0;
- // 使用Laravel模型获取所有试卷
- $papers = \App\Models\Paper::all();
- foreach ($papers as $paper) {
- // 计算实际的题目数量,使用关联关系
- $actualQuestionCount = $paper->questions()->count();
- // 如果题目数量不匹配,更新试卷
- if ($paper->question_count !== $actualQuestionCount) {
- $paper->update([
- 'question_count' => $actualQuestionCount,
- 'updated_at' => now()
- ]);
- $fixedCount++;
- Log::info('修复试卷题目数量', [
- 'paper_id' => $paper->paper_id,
- 'old_count' => $paper->getOriginal('question_count'),
- 'new_count' => $actualQuestionCount
- ]);
- }
- }
- Log::info('试卷题目数量修复完成', ['fixed_count' => $fixedCount]);
- return $fixedCount;
- } catch (\Exception $e) {
- Log::error('修复试卷题目数量失败', ['error' => $e->getMessage()]);
- return 0;
- }
- }
- /**
- * 获取试卷列表
- */
- public function listExams(int $page = 1, int $perPage = 20): array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/exam/list', [
- 'page' => $page,
- 'per_page' => $perPage
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取试卷列表失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取试卷列表异常', [
- 'error' => $e->getMessage()
- ]);
- }
- return ['data' => [], 'meta' => ['total' => 0]];
- }
- /**
- * 获取试卷详情
- */
- public function getExamById(string $paperId): ?array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/exam/' . $paperId);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取试卷详情失败', [
- 'paper_id' => $paperId,
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取试卷详情异常', [
- 'paper_id' => $paperId,
- 'error' => $e->getMessage()
- ]);
- }
- return null;
- }
- /**
- * 导出试卷为PDF
- */
- public function exportExamToPdf(string $paperId): ?string
- {
- try {
- $response = Http::timeout(60)
- ->get($this->baseUrl . '/exam/' . $paperId . '/export/pdf');
- if ($response->successful()) {
- // 返回PDF文件路径或URL
- return $response->json('pdf_url', null);
- }
- Log::warning('导出PDF失败', [
- 'paper_id' => $paperId,
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('导出PDF异常', [
- 'paper_id' => $paperId,
- 'error' => $e->getMessage()
- ]);
- }
- return null;
- }
- /**
- * 检查服务健康状态
- */
- public function checkHealth(): bool
- {
- try {
- $response = Http::timeout(5)
- ->get($this->baseUrl . '/health');
- return $response->successful();
- } catch (\Exception $e) {
- Log::error('题库服务健康检查失败', [
- 'error' => $e->getMessage()
- ]);
- return false;
- }
- }
- /**
- * 根据OCR识别的题目生成完整题目并保存到题库(异步模拟版本)
- *
- * @param array $questions OCR识别的题目列表
- * @param string $gradeLevel 年级
- * @param string $subject 科目
- * @param int $ocrRecordId OCR记录ID,用于关联
- * @param string|null $callbackUrl 回调URL(可选,如果不提供则自动生成)
- * @param string|null $callbackRouteName 回调路由名称(用于动态生成URL)
- * @return array 任务ID和状态
- */
- public function generateQuestionsFromOcrAsync(
- array $questions,
- string $gradeLevel = '高一',
- string $subject = '数学',
- int $ocrRecordId = null,
- string $callbackUrl = null,
- string $callbackRouteName = 'api.ocr.callback'
- ): array {
- try {
- // 如果没有提供回调URL,但提供了OCR记录ID,则动态生成回调URL
- if (!$callbackUrl && $ocrRecordId) {
- $callbackUrl = $this->generateCallbackUrl($callbackRouteName);
- Log::info('动态生成回调URL', [
- 'route_name' => $callbackRouteName,
- 'generated_url' => $callbackUrl
- ]);
- }
- // 生成唯一的任务ID
- $taskId = 'ocr_' . $ocrRecordId . '_' . time() . '_' . substr(md5(uniqid()), 0, 8);
- // 更新OCR记录状态为生成中
- if ($ocrRecordId) {
- \DB::table('ocr_question_results')
- ->where('ocr_record_id', $ocrRecordId)
- ->where('question_bank_id', null) // 只更新未关联的题目
- ->update([
- 'generation_status' => 'generating',
- 'generation_task_id' => $taskId,
- 'generation_error' => null
- ]);
- }
- // 启动后台任务(使用Laravel的队列)
- if ($ocrRecordId && $callbackUrl) {
- // 使用Laravel队列异步处理
- $this->dispatchOcrGenerationJob($ocrRecordId, $questions, $gradeLevel, $subject, $callbackUrl, $taskId);
- } else {
- // 如果没有回调URL,使用同步方式
- $response = $this->generateQuestionsFromOcr($questions, $gradeLevel, $subject);
- return $response;
- }
- Log::info('OCR题目生成任务已提交到队列', [
- 'task_id' => $taskId,
- 'ocr_record_id' => $ocrRecordId,
- 'questions_count' => count($questions),
- 'callback_url' => $callbackUrl
- ]);
- return [
- 'status' => 'processing',
- 'task_id' => $taskId,
- 'ocr_record_id' => $ocrRecordId,
- 'message' => '题目生成任务已启动,完成后将通过回调通知',
- 'estimated_time' => '约' . (count($questions) * 2) . '秒',
- 'callback_info' => [
- 'will_callback' => !empty($callbackUrl),
- 'callback_url' => $callbackUrl
- ]
- ];
- } catch (\Exception $e) {
- Log::error('OCR题目生成任务提交异常', [
- 'error' => $e->getMessage(),
- 'ocr_record_id' => $ocrRecordId
- ]);
- return [
- 'status' => 'error',
- 'message' => '任务提交失败: ' . $e->getMessage()
- ];
- }
- }
- /**
- * 分发OCR生成任务到队列
- */
- private function dispatchOcrGenerationJob(
- int $ocrRecordId,
- array $questions,
- string $gradeLevel,
- string $subject,
- string $callbackUrl,
- string $taskId
- ): void {
- try {
- // 转换题目数据格式
- $formattedQuestions = [];
- foreach ($questions as $q) {
- $formattedQuestions[] = [
- 'id' => $q['id'] ?? uniqid(),
- 'content' => $q['content'] ?? ''
- ];
- }
- // 直接调用QuestionBank API的异步端点,提供回调URL
- $response = Http::timeout(60)
- ->post($this->baseUrl . '/api/questions/generate-from-ocr', [
- 'ocr_record_id' => $ocrRecordId,
- 'questions' => $formattedQuestions,
- 'grade_level' => $gradeLevel,
- 'subject' => $subject,
- 'callback_url' => $callbackUrl
- ]);
- if (!$response->successful()) {
- Log::error('提交OCR题目生成任务失败', [
- 'status' => $response->status(),
- 'body' => $response->body(),
- 'task_id' => $taskId
- ]);
- // 发送失败回调
- $callbackData = [
- 'task_id' => $taskId,
- 'ocr_record_id' => $ocrRecordId,
- 'status' => 'failed',
- 'error' => 'API调用失败: ' . $response->status(),
- 'timestamp' => now()->toISOString()
- ];
- Http::timeout(10)
- ->post($callbackUrl, $callbackData);
- return;
- }
- $result = $response->json();
- Log::info('OCR题目生成任务已提交到QuestionBank', [
- 'task_id' => $taskId,
- 'questionbank_task_id' => $result['task_id'] ?? 'unknown',
- 'status' => $result['status'] ?? 'unknown',
- 'callback_url' => $callbackUrl
- ]);
- // QuestionBank API会异步处理并通过回调通知,这里不需要立即触发回调
- // 回调会在题目生成完成后由QuestionBank API主动发送
- } catch (\Exception $e) {
- Log::error('OCR生成任务处理失败', [
- 'task_id' => $taskId,
- 'ocr_record_id' => $ocrRecordId,
- 'error' => $e->getMessage()
- ]);
- // 发送异常回调
- try {
- $callbackData = [
- 'task_id' => $taskId,
- 'ocr_record_id' => $ocrRecordId,
- 'status' => 'failed',
- 'error' => $e->getMessage(),
- 'timestamp' => now()->toISOString()
- ];
- Http::timeout(10)
- ->post($callbackUrl, $callbackData);
- } catch (\Exception $callbackException) {
- Log::error('发送异常回调失败', [
- 'error' => $callbackException->getMessage()
- ]);
- }
- }
- }
- /**
- * 动态生成回调URL
- *
- * @param string $routeName 路由名称
- * @return string 完整的回调URL
- */
- private function generateCallbackUrl(string $routeName): string
- {
- try {
- // 获取当前请求的域名
- $appUrl = config('app.url', 'http://localhost');
- // 如果是在命令行环境中运行,使用配置的域名
- if (app()->runningInConsole()) {
- $domain = config('services.question_bank.callback_domain', $appUrl);
- } else {
- $domain = request()->getSchemeAndHttpHost();
- }
- // 确保domain不为null
- $domain = $domain ?? $appUrl;
- // 移除末尾的斜杠
- $domain = rtrim($domain, '/');
- // 生成完整的URL
- $callbackUrl = $domain . route($routeName, [], false);
- Log::info('生成回调URL', [
- 'route_name' => $routeName,
- 'domain' => $domain,
- 'app_url' => $appUrl,
- 'callback_url' => $callbackUrl
- ]);
- return $callbackUrl;
- } catch (\Exception $e) {
- // 如果路由生成失败,使用默认URL
- Log::warning('路由生成失败,使用默认URL', [
- 'route_name' => $routeName,
- 'error' => $e->getMessage()
- ]);
- $fallbackUrl = config('app.url', 'http://localhost');
- if ($routeName === 'api.ocr.callback') {
- return $fallbackUrl . '/api/ocr-question-callback';
- }
- return $fallbackUrl;
- }
- }
- /**
- * 根据OCR识别的题目生成题库题目(同步版本,向后兼容)
- *
- * @param array $questions OCR题目数组 [['question_number' => 1, 'question_text' => '...']]
- * @param string $gradeLevel 年级
- * @param string $subject 科目
- * @return array 生成结果
- */
- public function generateQuestionsFromOcr(array $questions, string $gradeLevel = '高一', string $subject = '数学'): array
- {
- return $this->generateQuestionsFromOcrAsync($questions, $gradeLevel, $subject);
- }
- /**
- * 检查题目生成任务状态
- */
- public function checkGenerationTaskStatus(string $taskId): array
- {
- return $this->getTaskStatus($taskId) ?? ['status' => 'unknown'];
- }
- }
|