QuestionBankService.php 38 KB

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