QuestionBankService.php 33 KB

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