QuestionBankService.php 38 KB

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