QuestionBankService.php 32 KB

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