QuestionBankService.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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. $response = Http::timeout(60)
  820. ->post($this->baseUrl . '/api/questions/generate-from-ocr', [
  821. 'ocr_record_id' => $ocrRecordId,
  822. 'questions' => $formattedQuestions,
  823. 'grade_level' => $gradeLevel,
  824. 'subject' => $subject,
  825. 'callback_url' => $callbackUrl
  826. ]);
  827. if (!$response->successful()) {
  828. Log::error('提交OCR题目生成任务失败', [
  829. 'status' => $response->status(),
  830. 'body' => $response->body(),
  831. 'task_id' => $taskId
  832. ]);
  833. // 发送失败回调
  834. $callbackData = [
  835. 'task_id' => $taskId,
  836. 'ocr_record_id' => $ocrRecordId,
  837. 'status' => 'failed',
  838. 'error' => 'API调用失败: ' . $response->status(),
  839. 'timestamp' => now()->toISOString()
  840. ];
  841. Http::timeout(10)
  842. ->post($callbackUrl, $callbackData);
  843. return;
  844. }
  845. $result = $response->json();
  846. Log::info('OCR题目生成任务已提交到QuestionBank', [
  847. 'task_id' => $taskId,
  848. 'questionbank_task_id' => $result['task_id'] ?? 'unknown',
  849. 'status' => $result['status'] ?? 'unknown',
  850. 'callback_url' => $callbackUrl
  851. ]);
  852. // QuestionBank API会异步处理并通过回调通知,这里不需要立即触发回调
  853. // 回调会在题目生成完成后由QuestionBank API主动发送
  854. } catch (\Exception $e) {
  855. Log::error('OCR生成任务处理失败', [
  856. 'task_id' => $taskId,
  857. 'ocr_record_id' => $ocrRecordId,
  858. 'error' => $e->getMessage()
  859. ]);
  860. // 发送异常回调
  861. try {
  862. $callbackData = [
  863. 'task_id' => $taskId,
  864. 'ocr_record_id' => $ocrRecordId,
  865. 'status' => 'failed',
  866. 'error' => $e->getMessage(),
  867. 'timestamp' => now()->toISOString()
  868. ];
  869. Http::timeout(10)
  870. ->post($callbackUrl, $callbackData);
  871. } catch (\Exception $callbackException) {
  872. Log::error('发送异常回调失败', [
  873. 'error' => $callbackException->getMessage()
  874. ]);
  875. }
  876. }
  877. }
  878. /**
  879. * 动态生成回调URL
  880. *
  881. * @param string $routeName 路由名称
  882. * @return string 完整的回调URL
  883. */
  884. private function generateCallbackUrl(string $routeName): string
  885. {
  886. try {
  887. // 获取当前请求的域名
  888. $appUrl = config('app.url', 'http://localhost');
  889. // 如果是在命令行环境中运行,使用配置的域名
  890. if (app()->runningInConsole()) {
  891. $domain = config('services.question_bank.callback_domain', $appUrl);
  892. } else {
  893. $domain = request()->getSchemeAndHttpHost();
  894. }
  895. // 确保domain不为null
  896. $domain = $domain ?? $appUrl;
  897. // 移除末尾的斜杠
  898. $domain = rtrim($domain, '/');
  899. // 生成完整的URL
  900. $callbackUrl = $domain . route($routeName, [], false);
  901. Log::info('生成回调URL', [
  902. 'route_name' => $routeName,
  903. 'domain' => $domain,
  904. 'app_url' => $appUrl,
  905. 'callback_url' => $callbackUrl
  906. ]);
  907. return $callbackUrl;
  908. } catch (\Exception $e) {
  909. // 如果路由生成失败,使用默认URL
  910. Log::warning('路由生成失败,使用默认URL', [
  911. 'route_name' => $routeName,
  912. 'error' => $e->getMessage()
  913. ]);
  914. $fallbackUrl = config('app.url', 'http://localhost');
  915. if ($routeName === 'api.ocr.callback') {
  916. return $fallbackUrl . '/api/ocr-question-callback';
  917. }
  918. return $fallbackUrl;
  919. }
  920. }
  921. /**
  922. * 根据OCR识别的题目生成题库题目(同步版本,向后兼容)
  923. *
  924. * @param array $questions OCR题目数组 [['question_number' => 1, 'question_text' => '...']]
  925. * @param string $gradeLevel 年级
  926. * @param string $subject 科目
  927. * @return array 生成结果
  928. */
  929. public function generateQuestionsFromOcr(array $questions, string $gradeLevel = '高一', string $subject = '数学'): array
  930. {
  931. return $this->generateQuestionsFromOcrAsync($questions, $gradeLevel, $subject);
  932. }
  933. /**
  934. * 检查题目生成任务状态
  935. */
  936. public function checkGenerationTaskStatus(string $taskId): array
  937. {
  938. return $this->getTaskStatus($taskId) ?? ['status' => 'unknown'];
  939. }
  940. }