QuestionBankService.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. use Illuminate\Support\Facades\Log;
  5. class QuestionBankService
  6. {
  7. protected string $baseUrl;
  8. public function __construct()
  9. {
  10. // 从配置文件读取base_url
  11. $this->baseUrl = config('services.question_bank.base_url', env('QUESTION_BANK_API_BASE', 'http://localhost:5015'));
  12. $this->baseUrl = rtrim($this->baseUrl, '/');
  13. }
  14. /**
  15. * 获取题目列表
  16. */
  17. public function listQuestions(int $page = 1, int $perPage = 50, array $filters = []): array
  18. {
  19. try {
  20. $response = Http::timeout(10)
  21. ->get($this->baseUrl . '/questions', [
  22. 'page' => $page,
  23. 'per_page' => $perPage,
  24. ...$filters
  25. ]);
  26. if ($response->successful()) {
  27. return $response->json();
  28. }
  29. Log::warning('题库API调用失败', [
  30. 'status' => $response->status()
  31. ]);
  32. } catch (\Exception $e) {
  33. Log::error('获取题目列表失败', [
  34. 'error' => $e->getMessage()
  35. ]);
  36. }
  37. return ['data' => [], 'meta' => ['total' => 0]];
  38. }
  39. /**
  40. * 获取题目详情
  41. */
  42. public function getQuestion(string $questionCode): ?array
  43. {
  44. try {
  45. $response = Http::timeout(10)
  46. ->get($this->baseUrl . "/questions/{$questionCode}");
  47. if ($response->successful()) {
  48. return $response->json();
  49. }
  50. Log::warning('获取题目详情失败', [
  51. 'code' => $questionCode,
  52. 'status' => $response->status()
  53. ]);
  54. } catch (\Exception $e) {
  55. Log::error('获取题目详情异常', [
  56. 'code' => $questionCode,
  57. 'error' => $e->getMessage()
  58. ]);
  59. }
  60. return null;
  61. }
  62. /**
  63. * 更新题目
  64. */
  65. public function updateQuestion(string $questionCode, array $payload): bool
  66. {
  67. try {
  68. $response = Http::timeout(10)
  69. ->patch($this->baseUrl . "/questions/{$questionCode}", $payload);
  70. if ($response->successful()) {
  71. return true;
  72. }
  73. Log::warning('更新题目失败', [
  74. 'code' => $questionCode,
  75. 'status' => $response->status(),
  76. 'body' => $response->json(),
  77. ]);
  78. } catch (\Exception $e) {
  79. Log::error('更新题目异常', [
  80. 'code' => $questionCode,
  81. 'error' => $e->getMessage()
  82. ]);
  83. }
  84. return false;
  85. }
  86. /**
  87. * 筛选题目 (支持 kp_codes, skills 等高级筛选)
  88. */
  89. public function filterQuestions(array $params): array
  90. {
  91. try {
  92. $response = Http::timeout(30)
  93. ->get($this->baseUrl . '/questions', $params);
  94. if ($response->successful()) {
  95. return $response->json();
  96. }
  97. Log::warning('筛选题目API调用失败', [
  98. 'status' => $response->status(),
  99. 'params' => $params
  100. ]);
  101. } catch (\Exception $e) {
  102. Log::error('筛选题目异常', [
  103. 'error' => $e->getMessage(),
  104. 'params' => $params
  105. ]);
  106. }
  107. return ['data' => []];
  108. }
  109. /**
  110. * 批量获取题目详情(根据题目 ID 列表)
  111. */
  112. public function getQuestionsByIds(array $ids): array
  113. {
  114. if (empty($ids)) {
  115. return ['data' => []];
  116. }
  117. try {
  118. $response = Http::timeout(15)
  119. ->get($this->baseUrl . '/questions', [
  120. 'ids' => implode(',', $ids),
  121. ]);
  122. if ($response->successful()) {
  123. return $response->json();
  124. }
  125. Log::warning('批量获取题目失败', [
  126. 'ids' => $ids,
  127. 'status' => $response->status(),
  128. ]);
  129. } catch (\Exception $e) {
  130. Log::error('批量获取题目异常', [
  131. 'ids' => $ids,
  132. 'error' => $e->getMessage(),
  133. ]);
  134. }
  135. return ['data' => []];
  136. }
  137. /**
  138. * 智能生成题目(异步模式)
  139. */
  140. public function generateIntelligentQuestions(array $params, ?string $callbackUrl = null): array
  141. {
  142. try {
  143. // 添加回调 URL
  144. if ($callbackUrl) {
  145. $params['callback_url'] = $callbackUrl;
  146. }
  147. // 增加超时时间到60秒,确保有足够时间启动异步任务
  148. // 注意:API是异步的,只需等待任务启动(1-2秒),不需要等待AI生成完成
  149. $response = Http::timeout(60)
  150. ->post($this->baseUrl . '/generate-intelligent-questions', $params);
  151. if ($response->successful()) {
  152. return $response->json();
  153. }
  154. Log::warning('题目生成API调用失败', [
  155. 'status' => $response->status()
  156. ]);
  157. } catch (\Exception $e) {
  158. Log::error('题目生成异常', [
  159. 'error' => $e->getMessage()
  160. ]);
  161. }
  162. return ['success' => false, 'message' => '生成失败'];
  163. }
  164. /**
  165. * 获取任务状态
  166. */
  167. public function getTaskStatus(string $taskId): ?array
  168. {
  169. try {
  170. $response = Http::timeout(10)
  171. ->get($this->baseUrl . '/tasks/' . $taskId);
  172. if ($response->successful()) {
  173. return $response->json();
  174. }
  175. Log::warning('获取任务状态失败', [
  176. 'task_id' => $taskId,
  177. 'status' => $response->status()
  178. ]);
  179. } catch (\Exception $e) {
  180. Log::error('获取任务状态异常', [
  181. 'task_id' => $taskId,
  182. 'error' => $e->getMessage()
  183. ]);
  184. }
  185. return null;
  186. }
  187. /**
  188. * 获取任务列表
  189. */
  190. public function listTasks(?string $status = null, int $page = 1, int $perPage = 10): array
  191. {
  192. try {
  193. $params = [
  194. 'page' => $page,
  195. 'per_page' => $perPage
  196. ];
  197. if ($status) {
  198. $params['status'] = $status;
  199. }
  200. $response = Http::timeout(10)
  201. ->get($this->baseUrl . '/tasks', $params);
  202. if ($response->successful()) {
  203. return $response->json();
  204. }
  205. Log::warning('获取任务列表失败', [
  206. 'status' => $response->status()
  207. ]);
  208. } catch (\Exception $e) {
  209. Log::error('获取任务列表异常', [
  210. 'error' => $e->getMessage()
  211. ]);
  212. }
  213. return ['data' => [], 'meta' => ['total' => 0]];
  214. }
  215. /**
  216. * 获取题目统计信息
  217. */
  218. public function getStatistics(): array
  219. {
  220. try {
  221. $response = Http::timeout(10)
  222. ->get($this->baseUrl . '/questions/statistics');
  223. if ($response->successful()) {
  224. return $response->json();
  225. }
  226. Log::warning('获取题目统计失败', [
  227. 'status' => $response->status()
  228. ]);
  229. } catch (\Exception $e) {
  230. Log::error('获取题目统计异常', [
  231. 'error' => $e->getMessage()
  232. ]);
  233. }
  234. return [
  235. 'total' => 0,
  236. 'by_difficulty' => [],
  237. 'by_kp' => [],
  238. 'by_source' => []
  239. ];
  240. }
  241. /**
  242. * 根据知识点获取题目
  243. */
  244. public function getQuestionsByKpCode(string $kpCode, int $limit = 100): array
  245. {
  246. try {
  247. $response = Http::timeout(10)
  248. ->get($this->baseUrl . '/questions', [
  249. 'kp_code' => $kpCode,
  250. 'limit' => $limit
  251. ]);
  252. if ($response->successful()) {
  253. return $response->json();
  254. }
  255. } catch (\Exception $e) {
  256. Log::error('根据知识点获取题目失败', [
  257. 'kp_code' => $kpCode,
  258. 'error' => $e->getMessage()
  259. ]);
  260. }
  261. return [];
  262. }
  263. /**
  264. * 删除题目
  265. */
  266. public function deleteQuestion(string $questionCode): bool
  267. {
  268. try {
  269. $response = Http::timeout(10)
  270. ->delete($this->baseUrl . "/questions/{$questionCode}");
  271. // 只有返回204(删除成功)才返回true,404(不存在)返回false
  272. if ($response->status() === 204) {
  273. return true;
  274. }
  275. if ($response->status() === 404) {
  276. Log::warning('尝试删除不存在的题目', ['question_code' => $questionCode]);
  277. return false;
  278. }
  279. return false;
  280. } catch (\Exception $e) {
  281. Log::error('删除题目失败', [
  282. 'question_code' => $questionCode,
  283. 'error' => $e->getMessage()
  284. ]);
  285. return false;
  286. }
  287. }
  288. /**
  289. * 智能选择试卷题目
  290. */
  291. public function selectQuestionsForExam(int $totalQuestions, array $filters): array
  292. {
  293. try {
  294. $response = Http::timeout(30)
  295. ->post($this->baseUrl . '/exam/select-questions', [
  296. 'total_questions' => $totalQuestions,
  297. 'filters' => $filters
  298. ]);
  299. if ($response->successful()) {
  300. return $response->json('data', []);
  301. }
  302. Log::warning('智能选题API调用失败', [
  303. 'status' => $response->status()
  304. ]);
  305. } catch (\Exception $e) {
  306. Log::error('智能选题异常', [
  307. 'error' => $e->getMessage()
  308. ]);
  309. }
  310. return [];
  311. }
  312. /**
  313. * 保存试卷到数据库(本地 papers 表)
  314. */
  315. public function saveExamToDatabase(array $examData): ?string
  316. {
  317. // 数据完整性检查
  318. if (empty($examData['questions'])) {
  319. Log::warning('尝试保存没有题目的试卷', [
  320. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  321. 'student_id' => $examData['student_id'] ?? 'unknown'
  322. ]);
  323. return null;
  324. }
  325. try {
  326. // 使用数据库事务确保数据一致性
  327. return \Illuminate\Support\Facades\DB::transaction(function () use ($examData) {
  328. // 生成试卷ID
  329. $paperId = 'paper_' . time() . '_' . bin2hex(random_bytes(4));
  330. Log::info('开始保存试卷到数据库', [
  331. 'paper_id' => $paperId,
  332. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  333. 'question_count' => count($examData['questions'])
  334. ]);
  335. // 使用Laravel模型保存到 papers 表
  336. $paper = \App\Models\Paper::create([
  337. 'paper_id' => $paperId,
  338. 'student_id' => $examData['student_id'] ?? '',
  339. 'teacher_id' => $examData['teacher_id'] ?? '',
  340. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  341. 'paper_type' => 'auto_generated',
  342. 'question_count' => count($examData['questions']), // 使用实际题目数量
  343. 'total_score' => $examData['total_score'] ?? 0,
  344. 'status' => 'draft',
  345. 'difficulty_category' => $examData['difficulty_category'] ?? '基础',
  346. ]);
  347. // 准备题目数据
  348. $questionInsertData = [];
  349. foreach ($examData['questions'] as $index => $question) {
  350. // 验证题目基本数据
  351. if (empty($question['stem']) && empty($question['content'])) {
  352. Log::warning('跳过没有内容的题目', [
  353. 'paper_id' => $paperId,
  354. 'question_index' => $index
  355. ]);
  356. continue;
  357. }
  358. // 处理难度字段:如果是字符串则转换为数字
  359. $difficultyValue = $question['difficulty'] ?? 0.5;
  360. if (is_string($difficultyValue)) {
  361. // 将中文难度转换为数字
  362. if (strpos($difficultyValue, '基础') !== false || strpos($difficultyValue, '简单') !== false) {
  363. $difficultyValue = 0.3;
  364. } elseif (strpos($difficultyValue, '中等') !== false || strpos($difficultyValue, '一般') !== false) {
  365. $difficultyValue = 0.6;
  366. } elseif (strpos($difficultyValue, '拔高') !== false || strpos($difficultyValue, '困难') !== false) {
  367. $difficultyValue = 0.9;
  368. } else {
  369. $difficultyValue = 0.5;
  370. }
  371. }
  372. // 确保 knowledge_point 有值
  373. $knowledgePoint = $question['kp'] ?? $question['kp_code'] ?? $question['knowledge_point'] ?? $question['knowledge_point_code'] ?? '';
  374. if (empty($knowledgePoint) && isset($question['kp_code'])) {
  375. $knowledgePoint = $question['kp_code'];
  376. }
  377. // 获取题目类型
  378. $questionType = $question['question_type'] ?? 'answer';
  379. if (!$questionType) {
  380. // 如果没有类型,根据内容推断
  381. $content = $question['stem'] ?? $question['content'] ?? '';
  382. if (is_string($content)) {
  383. // 1. 优先检查填空题(下划线)
  384. if (strpos($content, '____') !== false || strpos($content, '______') !== false) {
  385. $questionType = 'fill';
  386. }
  387. // 2. 检查选择题(必须有选项 A. B. C. D.)
  388. elseif (preg_match('/[A-D]\s*\./', $content) || preg_match('/\([A-D]\)/', $content)) {
  389. if (preg_match('/A\./', $content) && preg_match('/B\./', $content)) {
  390. $questionType = 'choice';
  391. } else {
  392. // 只有括号没有选项,可能是填空
  393. if (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  394. $questionType = 'fill';
  395. } else {
  396. $questionType = 'answer';
  397. }
  398. }
  399. }
  400. // 3. 检查纯括号填空
  401. elseif (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  402. $questionType = 'fill';
  403. }
  404. else {
  405. $questionType = 'answer';
  406. }
  407. } else {
  408. $questionType = 'answer';
  409. }
  410. }
  411. $questionInsertData[] = [
  412. 'paper_id' => $paperId,
  413. 'question_id' => $question['question_code'] ?? $question['question_id'] ?? null,
  414. 'question_bank_id' => $question['id'] ?? $question['question_id'] ?? 0,
  415. 'knowledge_point' => $knowledgePoint,
  416. 'question_type' => $questionType,
  417. 'question_text' => $question['stem'] ?? $question['content'] ?? $question['question_text'] ?? '',
  418. 'difficulty' => $difficultyValue,
  419. 'score' => $question['score'] ?? 5, // 默认5分
  420. 'estimated_time' => $question['estimated_time'] ?? 300,
  421. 'question_number' => $index + 1,
  422. ];
  423. }
  424. // 验证是否有有效的题目数据
  425. if (empty($questionInsertData)) {
  426. Log::error('没有有效的题目数据可以保存', ['paper_id' => $paperId]);
  427. throw new \Exception('没有有效的题目数据');
  428. }
  429. // 使用Laravel模型批量插入题目数据
  430. \App\Models\PaperQuestion::insert($questionInsertData);
  431. // 验证插入结果,使用关联关系
  432. $insertedQuestionCount = $paper->questions()->count();
  433. if ($insertedQuestionCount !== count($questionInsertData)) {
  434. throw new \Exception("题目插入数量不匹配:预期 {$insertedQuestionCount},实际 " . count($questionInsertData));
  435. }
  436. Log::info('试卷保存成功', [
  437. 'paper_id' => $paperId,
  438. 'expected_questions' => count($questionInsertData),
  439. 'actual_questions' => $insertedQuestionCount,
  440. 'paper_name' => $paper->paper_name
  441. ]);
  442. return $paperId;
  443. });
  444. } catch (\Exception $e) {
  445. Log::error('保存试卷到数据库失败', [
  446. 'error' => $e->getMessage(),
  447. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  448. 'student_id' => $examData['student_id'] ?? 'unknown',
  449. 'question_count' => count($examData['questions'] ?? []),
  450. 'trace' => $e->getTraceAsString()
  451. ]);
  452. return null;
  453. }
  454. }
  455. /**
  456. * 检查数据完整性 - 发现没有题目的试卷
  457. */
  458. public function checkDataIntegrity(): array
  459. {
  460. try {
  461. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  462. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  463. ->whereDoesntHave('questions')
  464. ->get();
  465. Log::warning('发现数据不一致的试卷', [
  466. 'count' => $inconsistentPapers->count(),
  467. 'papers' => $inconsistentPapers->map(function($paper) {
  468. return [
  469. 'paper_id' => $paper->paper_id,
  470. 'paper_name' => $paper->paper_name,
  471. 'expected_questions' => $paper->question_count,
  472. 'student_id' => $paper->student_id,
  473. 'created_at' => $paper->created_at
  474. ];
  475. })->toArray()
  476. ]);
  477. return [
  478. 'inconsistent_count' => $inconsistentPapers->count(),
  479. 'papers' => $inconsistentPapers->toArray()
  480. ];
  481. } catch (\Exception $e) {
  482. Log::error('检查数据完整性失败', ['error' => $e->getMessage()]);
  483. return ['inconsistent_count' => 0, 'papers' => []];
  484. }
  485. }
  486. /**
  487. * 清理没有题目的试卷记录
  488. */
  489. public function cleanupInconsistentPapers(): int
  490. {
  491. try {
  492. return \Illuminate\Support\Facades\DB::transaction(function () {
  493. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  494. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  495. ->whereDoesntHave('questions')
  496. ->get();
  497. if ($inconsistentPapers->isEmpty()) {
  498. return 0;
  499. }
  500. // 获取要删除的试卷ID列表
  501. $deletedPaperIds = $inconsistentPapers->pluck('paper_id')->toArray();
  502. // 使用Laravel模型删除这些不一致的试卷记录
  503. $deletedCount = \App\Models\Paper::whereIn('paper_id', $deletedPaperIds)->delete();
  504. Log::info('清理不一致的试卷记录', [
  505. 'deleted_count' => $deletedCount,
  506. 'deleted_paper_ids' => $deletedPaperIds
  507. ]);
  508. return $deletedCount;
  509. });
  510. } catch (\Exception $e) {
  511. Log::error('清理不一致试卷失败', ['error' => $e->getMessage()]);
  512. return 0;
  513. }
  514. }
  515. /**
  516. * 修复试卷的题目数量统计
  517. */
  518. public function fixPaperQuestionCounts(): int
  519. {
  520. try {
  521. $fixedCount = 0;
  522. // 使用Laravel模型获取所有试卷
  523. $papers = \App\Models\Paper::all();
  524. foreach ($papers as $paper) {
  525. // 计算实际的题目数量,使用关联关系
  526. $actualQuestionCount = $paper->questions()->count();
  527. // 如果题目数量不匹配,更新试卷
  528. if ($paper->question_count !== $actualQuestionCount) {
  529. $paper->update([
  530. 'question_count' => $actualQuestionCount,
  531. 'updated_at' => now()
  532. ]);
  533. $fixedCount++;
  534. Log::info('修复试卷题目数量', [
  535. 'paper_id' => $paper->paper_id,
  536. 'old_count' => $paper->getOriginal('question_count'),
  537. 'new_count' => $actualQuestionCount
  538. ]);
  539. }
  540. }
  541. Log::info('试卷题目数量修复完成', ['fixed_count' => $fixedCount]);
  542. return $fixedCount;
  543. } catch (\Exception $e) {
  544. Log::error('修复试卷题目数量失败', ['error' => $e->getMessage()]);
  545. return 0;
  546. }
  547. }
  548. /**
  549. * 获取试卷列表
  550. */
  551. public function listExams(int $page = 1, int $perPage = 20): array
  552. {
  553. try {
  554. $response = Http::timeout(10)
  555. ->get($this->baseUrl . '/exam/list', [
  556. 'page' => $page,
  557. 'per_page' => $perPage
  558. ]);
  559. if ($response->successful()) {
  560. return $response->json();
  561. }
  562. Log::warning('获取试卷列表失败', [
  563. 'status' => $response->status()
  564. ]);
  565. } catch (\Exception $e) {
  566. Log::error('获取试卷列表异常', [
  567. 'error' => $e->getMessage()
  568. ]);
  569. }
  570. return ['data' => [], 'meta' => ['total' => 0]];
  571. }
  572. /**
  573. * 获取试卷详情
  574. */
  575. public function getExamById(string $paperId): ?array
  576. {
  577. try {
  578. $response = Http::timeout(10)
  579. ->get($this->baseUrl . '/exam/' . $paperId);
  580. if ($response->successful()) {
  581. return $response->json();
  582. }
  583. Log::warning('获取试卷详情失败', [
  584. 'paper_id' => $paperId,
  585. 'status' => $response->status()
  586. ]);
  587. } catch (\Exception $e) {
  588. Log::error('获取试卷详情异常', [
  589. 'paper_id' => $paperId,
  590. 'error' => $e->getMessage()
  591. ]);
  592. }
  593. return null;
  594. }
  595. /**
  596. * 导出试卷为PDF
  597. */
  598. public function exportExamToPdf(string $paperId): ?string
  599. {
  600. try {
  601. $response = Http::timeout(60)
  602. ->get($this->baseUrl . '/exam/' . $paperId . '/export/pdf');
  603. if ($response->successful()) {
  604. // 返回PDF文件路径或URL
  605. return $response->json('pdf_url', null);
  606. }
  607. Log::warning('导出PDF失败', [
  608. 'paper_id' => $paperId,
  609. 'status' => $response->status()
  610. ]);
  611. } catch (\Exception $e) {
  612. Log::error('导出PDF异常', [
  613. 'paper_id' => $paperId,
  614. 'error' => $e->getMessage()
  615. ]);
  616. }
  617. return null;
  618. }
  619. /**
  620. * 检查服务健康状态
  621. */
  622. public function checkHealth(): bool
  623. {
  624. try {
  625. $response = Http::timeout(5)
  626. ->get($this->baseUrl . '/health');
  627. return $response->successful();
  628. } catch (\Exception $e) {
  629. Log::error('题库服务健康检查失败', [
  630. 'error' => $e->getMessage()
  631. ]);
  632. return false;
  633. }
  634. }
  635. /**
  636. * 根据OCR识别的题目生成完整题目并保存到题库(异步模拟版本)
  637. *
  638. * @param array $questions OCR识别的题目列表
  639. * @param string $gradeLevel 年级
  640. * @param string $subject 科目
  641. * @param int $ocrRecordId OCR记录ID,用于关联
  642. * @param string|null $callbackUrl 回调URL(可选,如果不提供则自动生成)
  643. * @param string|null $callbackRouteName 回调路由名称(用于动态生成URL)
  644. * @return array 任务ID和状态
  645. */
  646. public function generateQuestionsFromOcrAsync(
  647. array $questions,
  648. string $gradeLevel = '高一',
  649. string $subject = '数学',
  650. int $ocrRecordId = null,
  651. string $callbackUrl = null,
  652. string $callbackRouteName = 'api.ocr.callback'
  653. ): array {
  654. try {
  655. // 如果没有提供回调URL,但提供了OCR记录ID,则动态生成回调URL
  656. if (!$callbackUrl && $ocrRecordId) {
  657. $callbackUrl = $this->generateCallbackUrl($callbackRouteName);
  658. Log::info('动态生成回调URL', [
  659. 'route_name' => $callbackRouteName,
  660. 'generated_url' => $callbackUrl
  661. ]);
  662. }
  663. // 生成唯一的任务ID
  664. $taskId = 'ocr_' . $ocrRecordId . '_' . time() . '_' . substr(md5(uniqid()), 0, 8);
  665. // 更新OCR记录状态为生成中
  666. if ($ocrRecordId) {
  667. \DB::table('ocr_question_results')
  668. ->where('ocr_record_id', $ocrRecordId)
  669. ->where('question_bank_id', null) // 只更新未关联的题目
  670. ->update([
  671. 'generation_status' => 'generating',
  672. 'generation_task_id' => $taskId,
  673. 'generation_error' => null
  674. ]);
  675. }
  676. // 启动后台任务(使用Laravel的队列)
  677. if ($ocrRecordId && $callbackUrl) {
  678. // 使用Laravel队列异步处理
  679. $this->dispatchOcrGenerationJob($ocrRecordId, $questions, $gradeLevel, $subject, $callbackUrl, $taskId);
  680. } else {
  681. // 如果没有回调URL,使用同步方式
  682. $response = $this->generateQuestionsFromOcr($questions, $gradeLevel, $subject);
  683. return $response;
  684. }
  685. Log::info('OCR题目生成任务已提交到队列', [
  686. 'task_id' => $taskId,
  687. 'ocr_record_id' => $ocrRecordId,
  688. 'questions_count' => count($questions),
  689. 'callback_url' => $callbackUrl
  690. ]);
  691. return [
  692. 'status' => 'processing',
  693. 'task_id' => $taskId,
  694. 'ocr_record_id' => $ocrRecordId,
  695. 'message' => '题目生成任务已启动,完成后将通过回调通知',
  696. 'estimated_time' => '约' . (count($questions) * 2) . '秒',
  697. 'callback_info' => [
  698. 'will_callback' => !empty($callbackUrl),
  699. 'callback_url' => $callbackUrl
  700. ]
  701. ];
  702. } catch (\Exception $e) {
  703. Log::error('OCR题目生成任务提交异常', [
  704. 'error' => $e->getMessage(),
  705. 'ocr_record_id' => $ocrRecordId
  706. ]);
  707. return [
  708. 'status' => 'error',
  709. 'message' => '任务提交失败: ' . $e->getMessage()
  710. ];
  711. }
  712. }
  713. /**
  714. * 分发OCR生成任务到队列
  715. */
  716. private function dispatchOcrGenerationJob(
  717. int $ocrRecordId,
  718. array $questions,
  719. string $gradeLevel,
  720. string $subject,
  721. string $callbackUrl,
  722. string $taskId
  723. ): void {
  724. try {
  725. // 转换题目数据格式
  726. $formattedQuestions = [];
  727. foreach ($questions as $q) {
  728. $formattedQuestions[] = [
  729. 'id' => $q['id'] ?? uniqid(),
  730. 'content' => $q['content'] ?? ''
  731. ];
  732. }
  733. // 直接调用QuestionBank API的异步端点,提供回调URL
  734. $response = Http::timeout(60)
  735. ->post($this->baseUrl . '/api/questions/generate-from-ocr', [
  736. 'ocr_record_id' => $ocrRecordId,
  737. 'questions' => $formattedQuestions,
  738. 'grade_level' => $gradeLevel,
  739. 'subject' => $subject,
  740. 'callback_url' => $callbackUrl
  741. ]);
  742. if (!$response->successful()) {
  743. Log::error('提交OCR题目生成任务失败', [
  744. 'status' => $response->status(),
  745. 'body' => $response->body(),
  746. 'task_id' => $taskId
  747. ]);
  748. // 发送失败回调
  749. $callbackData = [
  750. 'task_id' => $taskId,
  751. 'ocr_record_id' => $ocrRecordId,
  752. 'status' => 'failed',
  753. 'error' => 'API调用失败: ' . $response->status(),
  754. 'timestamp' => now()->toISOString()
  755. ];
  756. Http::timeout(10)
  757. ->post($callbackUrl, $callbackData);
  758. return;
  759. }
  760. $result = $response->json();
  761. Log::info('OCR题目生成任务已提交到QuestionBank', [
  762. 'task_id' => $taskId,
  763. 'questionbank_task_id' => $result['task_id'] ?? 'unknown',
  764. 'status' => $result['status'] ?? 'unknown',
  765. 'callback_url' => $callbackUrl
  766. ]);
  767. // QuestionBank API会异步处理并通过回调通知,这里不需要立即触发回调
  768. // 回调会在题目生成完成后由QuestionBank API主动发送
  769. } catch (\Exception $e) {
  770. Log::error('OCR生成任务处理失败', [
  771. 'task_id' => $taskId,
  772. 'ocr_record_id' => $ocrRecordId,
  773. 'error' => $e->getMessage()
  774. ]);
  775. // 发送异常回调
  776. try {
  777. $callbackData = [
  778. 'task_id' => $taskId,
  779. 'ocr_record_id' => $ocrRecordId,
  780. 'status' => 'failed',
  781. 'error' => $e->getMessage(),
  782. 'timestamp' => now()->toISOString()
  783. ];
  784. Http::timeout(10)
  785. ->post($callbackUrl, $callbackData);
  786. } catch (\Exception $callbackException) {
  787. Log::error('发送异常回调失败', [
  788. 'error' => $callbackException->getMessage()
  789. ]);
  790. }
  791. }
  792. }
  793. /**
  794. * 动态生成回调URL
  795. *
  796. * @param string $routeName 路由名称
  797. * @return string 完整的回调URL
  798. */
  799. private function generateCallbackUrl(string $routeName): string
  800. {
  801. try {
  802. // 获取当前请求的域名
  803. $appUrl = config('app.url', 'http://localhost');
  804. // 如果是在命令行环境中运行,使用配置的域名
  805. if (app()->runningInConsole()) {
  806. $domain = config('services.question_bank.callback_domain', $appUrl);
  807. } else {
  808. $domain = request()->getSchemeAndHttpHost();
  809. }
  810. // 确保domain不为null
  811. $domain = $domain ?? $appUrl;
  812. // 移除末尾的斜杠
  813. $domain = rtrim($domain, '/');
  814. // 生成完整的URL
  815. $callbackUrl = $domain . route($routeName, [], false);
  816. Log::info('生成回调URL', [
  817. 'route_name' => $routeName,
  818. 'domain' => $domain,
  819. 'app_url' => $appUrl,
  820. 'callback_url' => $callbackUrl
  821. ]);
  822. return $callbackUrl;
  823. } catch (\Exception $e) {
  824. // 如果路由生成失败,使用默认URL
  825. Log::warning('路由生成失败,使用默认URL', [
  826. 'route_name' => $routeName,
  827. 'error' => $e->getMessage()
  828. ]);
  829. $fallbackUrl = config('app.url', 'http://localhost');
  830. if ($routeName === 'api.ocr.callback') {
  831. return $fallbackUrl . '/api/ocr-question-callback';
  832. }
  833. return $fallbackUrl;
  834. }
  835. }
  836. /**
  837. * 根据OCR识别的题目生成题库题目(同步版本,向后兼容)
  838. *
  839. * @param array $questions OCR题目数组 [['question_number' => 1, 'question_text' => '...']]
  840. * @param string $gradeLevel 年级
  841. * @param string $subject 科目
  842. * @return array 生成结果
  843. */
  844. public function generateQuestionsFromOcr(array $questions, string $gradeLevel = '高一', string $subject = '数学'): array
  845. {
  846. return $this->generateQuestionsFromOcrAsync($questions, $gradeLevel, $subject);
  847. }
  848. /**
  849. * 检查题目生成任务状态
  850. */
  851. public function checkGenerationTaskStatus(string $taskId): array
  852. {
  853. return $this->getTaskStatus($taskId) ?? ['status' => 'unknown'];
  854. }
  855. }