QuestionBankService.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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. protected int $timeout;
  9. protected int $retry;
  10. protected int $retryDelay;
  11. public function __construct()
  12. {
  13. // 从配置文件读取base_url
  14. $this->baseUrl = config('services.question_bank.base_url', env('QUESTION_BANK_API_BASE', 'http://localhost:5015'));
  15. $this->baseUrl = rtrim($this->baseUrl, '/');
  16. // 如果配置中不包含/api,则添加它
  17. if (!str_ends_with($this->baseUrl, '/api')) {
  18. $this->baseUrl .= '/api';
  19. }
  20. // 读取超时与重试配置
  21. $this->timeout = (int) config('services.question_bank.timeout', 60);
  22. $this->retry = (int) config('services.question_bank.retry', 2);
  23. $this->retryDelay = (int) config('services.question_bank.retry_delay', 500);
  24. }
  25. private function http()
  26. {
  27. return Http::timeout($this->timeout)
  28. ->retry($this->retry, $this->retryDelay);
  29. }
  30. /**
  31. * 从题目内容中提取选项
  32. */
  33. private function extractOptions(string $content): array
  34. {
  35. // 匹配 A. B. C. D. 格式的选项
  36. if (preg_match_all('/([A-D])\.\s*(.+?)(?=[A-D]\.|$)/s', $content, $matches, PREG_SET_ORDER)) {
  37. $options = [];
  38. foreach ($matches as $match) {
  39. $optionText = trim($match[2]);
  40. // 移除末尾的换行和空白
  41. $optionText = preg_replace('/\s+$/', '', $optionText);
  42. $options[] = $optionText;
  43. }
  44. return $options;
  45. }
  46. return [];
  47. }
  48. /**
  49. * 分离题干内容和选项
  50. */
  51. private function separateStemAndOptions(string $content): array
  52. {
  53. // 如果没有选项,直接返回
  54. if (!preg_match('/[A-D]\.\s+/m', $content)) {
  55. return [$content, []];
  56. }
  57. // 提取选项
  58. $options = $this->extractOptions($content);
  59. // 提取题干(选项前的部分)
  60. $stem = preg_replace('/[A-D]\.\s+.+?(?=[A-D]\.|$)/s', '', $content);
  61. $stem = trim($stem);
  62. // 移除末尾的括号或空白
  63. $stem = preg_replace('/()\s*$/', '', $stem);
  64. $stem = trim($stem);
  65. return [$stem, $options];
  66. }
  67. /**
  68. * 获取题目列表
  69. */
  70. public function listQuestions(int $page = 1, int $perPage = 50, array $filters = []): array
  71. {
  72. try {
  73. $response = $this->http()
  74. ->get($this->baseUrl . '/questions', [
  75. 'page' => $page,
  76. 'per_page' => $perPage,
  77. ...$filters
  78. ]);
  79. if ($response->successful()) {
  80. info("QuestionBankService::listQuestions", [$response->json()]);
  81. return $response->json();
  82. }
  83. Log::warning('题库API调用失败', [
  84. 'status' => $response->status()
  85. ]);
  86. } catch (\Exception $e) {
  87. Log::error('获取题目列表失败', [
  88. 'error' => $e->getMessage()
  89. ]);
  90. }
  91. return ['data' => [], 'meta' => ['total' => 0]];
  92. }
  93. /**
  94. * 获取题目详情
  95. */
  96. public function getQuestion(string $questionCode): ?array
  97. {
  98. try {
  99. $response = $this->http()
  100. ->get($this->baseUrl . "/questions/{$questionCode}");
  101. if ($response->successful()) {
  102. return $response->json();
  103. }
  104. Log::warning('获取题目详情失败', [
  105. 'code' => $questionCode,
  106. 'status' => $response->status()
  107. ]);
  108. } catch (\Exception $e) {
  109. Log::error('获取题目详情异常', [
  110. 'code' => $questionCode,
  111. 'error' => $e->getMessage()
  112. ]);
  113. }
  114. return null;
  115. }
  116. /**
  117. * 更新题目
  118. */
  119. public function updateQuestion(string $questionCode, array $payload): bool
  120. {
  121. try {
  122. $response = Http::timeout(10)
  123. ->patch($this->baseUrl . "/questions/{$questionCode}", $payload);
  124. if ($response->successful()) {
  125. return true;
  126. }
  127. Log::warning('更新题目失败', [
  128. 'code' => $questionCode,
  129. 'status' => $response->status(),
  130. 'body' => $response->json(),
  131. ]);
  132. } catch (\Exception $e) {
  133. Log::error('更新题目异常', [
  134. 'code' => $questionCode,
  135. 'error' => $e->getMessage()
  136. ]);
  137. }
  138. return false;
  139. }
  140. /**
  141. * 筛选题目 (支持 kp_codes, skills 等高级筛选)
  142. */
  143. public function filterQuestions(array $params): array
  144. {
  145. try {
  146. $response = Http::timeout(30)
  147. ->get($this->baseUrl . '/questions', $params);
  148. if ($response->successful()) {
  149. info("QuestionBankService::filterQuestions", [$response->json()]);
  150. return $response->json();
  151. }
  152. Log::warning('筛选题目API调用失败', [
  153. 'status' => $response->status(),
  154. 'params' => $params
  155. ]);
  156. } catch (\Exception $e) {
  157. Log::error('筛选题目异常', [
  158. 'error' => $e->getMessage(),
  159. 'params' => $params
  160. ]);
  161. }
  162. return ['data' => []];
  163. }
  164. /**
  165. * 批量获取题目详情(根据题目 ID 列表)
  166. */
  167. public function getQuestionsByIds(array $ids): array
  168. {
  169. if (empty($ids)) {
  170. return ['data' => []];
  171. }
  172. try {
  173. $response = $this->http()
  174. ->get($this->baseUrl . '/questions', [
  175. 'ids' => implode(',', $ids),
  176. ]);
  177. if ($response->successful()) {
  178. return $response->json();
  179. }
  180. Log::warning('批量获取题目失败', [
  181. 'ids' => $ids,
  182. 'status' => $response->status(),
  183. ]);
  184. } catch (\Exception $e) {
  185. Log::error('批量获取题目异常', [
  186. 'ids' => $ids,
  187. 'error' => $e->getMessage(),
  188. ]);
  189. }
  190. return ['data' => []];
  191. }
  192. /**
  193. * 智能生成题目(异步模式)
  194. */
  195. public function generateIntelligentQuestions(array $params, ?string $callbackUrl = null): array
  196. {
  197. try {
  198. // 添加回调 URL
  199. if ($callbackUrl) {
  200. $params['callback_url'] = $callbackUrl;
  201. }
  202. // 注意:这里的请求实际上是同步的,会等待响应
  203. // 真正的异步应该使用 Http::async()
  204. $response = $this->http()
  205. ->post($this->baseUrl . '/ai/generate-intelligent-questions', $params);
  206. if ($response->successful()) {
  207. return $response->json();
  208. }
  209. Log::warning('题目生成API调用失败', [
  210. 'status' => $response->status(),
  211. 'body' => $response->body()
  212. ]);
  213. } catch (\Illuminate\Http\Client\ConnectionException $e) {
  214. // 连接超时或网络错误
  215. Log::error('题目生成连接异常', [
  216. 'error' => $e->getMessage(),
  217. 'message' => '可能的原因:1. AI服务未启动 2. 网络连接问题 3. 服务负载过高'
  218. ]);
  219. return [
  220. 'success' => false,
  221. 'message' => '连接AI服务失败,请检查服务是否正常运行'
  222. ];
  223. } catch (\Exception $e) {
  224. Log::error('题目生成异常', [
  225. 'error' => $e->getMessage(),
  226. 'trace' => $e->getTraceAsString()
  227. ]);
  228. }
  229. return ['success' => false, 'message' => '生成失败'];
  230. }
  231. /**
  232. * 获取任务状态
  233. */
  234. public function getTaskStatus(string $taskId): ?array
  235. {
  236. try {
  237. $response = Http::timeout(10)
  238. ->get($this->baseUrl . '/tasks/' . $taskId);
  239. if ($response->successful()) {
  240. return $response->json();
  241. }
  242. Log::warning('获取任务状态失败', [
  243. 'task_id' => $taskId,
  244. 'status' => $response->status()
  245. ]);
  246. } catch (\Exception $e) {
  247. Log::error('获取任务状态异常', [
  248. 'task_id' => $taskId,
  249. 'error' => $e->getMessage()
  250. ]);
  251. }
  252. return null;
  253. }
  254. /**
  255. * 获取任务列表
  256. */
  257. public function listTasks(?string $status = null, int $page = 1, int $perPage = 10): array
  258. {
  259. try {
  260. $params = [
  261. 'page' => $page,
  262. 'per_page' => $perPage
  263. ];
  264. if ($status) {
  265. $params['status'] = $status;
  266. }
  267. $response = Http::timeout(10)
  268. ->get($this->baseUrl . '/tasks', $params);
  269. if ($response->successful()) {
  270. return $response->json();
  271. }
  272. Log::warning('获取任务列表失败', [
  273. 'status' => $response->status()
  274. ]);
  275. } catch (\Exception $e) {
  276. Log::error('获取任务列表异常', [
  277. 'error' => $e->getMessage()
  278. ]);
  279. }
  280. return ['data' => [], 'meta' => ['total' => 0]];
  281. }
  282. /**
  283. * 获取题目统计信息
  284. */
  285. public function getStatistics(): array
  286. {
  287. try {
  288. $response = Http::timeout(10)
  289. ->get($this->baseUrl . '/questions/statistics');
  290. if ($response->successful()) {
  291. return $response->json();
  292. }
  293. Log::warning('获取题目统计失败', [
  294. 'status' => $response->status()
  295. ]);
  296. } catch (\Exception $e) {
  297. Log::error('获取题目统计异常', [
  298. 'error' => $e->getMessage()
  299. ]);
  300. }
  301. return [
  302. 'total' => 0,
  303. 'by_difficulty' => [],
  304. 'by_kp' => [],
  305. 'by_source' => []
  306. ];
  307. }
  308. /**
  309. * 根据知识点获取题目
  310. */
  311. public function getQuestionsByKpCode(string $kpCode, int $limit = 100): array
  312. {
  313. try {
  314. $response = Http::timeout(10)
  315. ->get($this->baseUrl . '/questions', [
  316. 'kp_code' => $kpCode,
  317. 'limit' => $limit
  318. ]);
  319. if ($response->successful()) {
  320. return $response->json();
  321. }
  322. } catch (\Exception $e) {
  323. Log::error('根据知识点获取题目失败', [
  324. 'kp_code' => $kpCode,
  325. 'error' => $e->getMessage()
  326. ]);
  327. }
  328. return [];
  329. }
  330. /**
  331. * 删除题目
  332. */
  333. public function deleteQuestion(string $questionCode): bool
  334. {
  335. try {
  336. $response = Http::timeout(10)
  337. ->delete($this->baseUrl . "/questions/{$questionCode}");
  338. // 只有返回204(删除成功)才返回true,404(不存在)返回false
  339. if ($response->status() === 204) {
  340. return true;
  341. }
  342. if ($response->status() === 404) {
  343. Log::warning('尝试删除不存在的题目', ['question_code' => $questionCode]);
  344. return false;
  345. }
  346. return false;
  347. } catch (\Exception $e) {
  348. Log::error('删除题目失败', [
  349. 'question_code' => $questionCode,
  350. 'error' => $e->getMessage()
  351. ]);
  352. return false;
  353. }
  354. }
  355. /**
  356. * 智能选择试卷题目
  357. */
  358. public function selectQuestionsForExam(int $totalQuestions, array $filters): array
  359. {
  360. try {
  361. $response = Http::timeout(30)
  362. ->post($this->baseUrl . '/exam/select-questions', [
  363. 'total_questions' => $totalQuestions,
  364. 'filters' => $filters
  365. ]);
  366. if ($response->successful()) {
  367. return $response->json('data', []);
  368. }
  369. Log::warning('智能选题API调用失败', [
  370. 'status' => $response->status()
  371. ]);
  372. } catch (\Exception $e) {
  373. Log::error('智能选题异常', [
  374. 'error' => $e->getMessage()
  375. ]);
  376. }
  377. return [];
  378. }
  379. /**
  380. * 保存试卷到数据库(本地 papers 表)
  381. */
  382. public function saveExamToDatabase(array $examData): ?string
  383. {
  384. // 数据完整性检查
  385. if (empty($examData['questions'])) {
  386. Log::warning('尝试保存没有题目的试卷', [
  387. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  388. 'student_id' => $examData['student_id'] ?? 'unknown'
  389. ]);
  390. return null;
  391. }
  392. try {
  393. // 使用数据库事务确保数据一致性
  394. return \Illuminate\Support\Facades\DB::transaction(function () use ($examData) {
  395. // 生成试卷ID
  396. $paperId = 'paper_' . time() . '_' . bin2hex(random_bytes(4));
  397. Log::info('开始保存试卷到数据库', [
  398. 'paper_id' => $paperId,
  399. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  400. 'question_count' => count($examData['questions'])
  401. ]);
  402. // 使用Laravel模型保存到 papers 表
  403. $paper = \App\Models\Paper::create([
  404. 'paper_id' => $paperId,
  405. 'student_id' => $examData['student_id'] ?? '',
  406. 'teacher_id' => $examData['teacher_id'] ?? '',
  407. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  408. 'paper_type' => 'auto_generated',
  409. 'total_questions' => count($examData['questions']), // 使用实际题目数量
  410. 'total_score' => $examData['total_score'] ?? 0,
  411. 'status' => 'draft',
  412. 'difficulty_category' => $examData['difficulty_category'] ?? '基础',
  413. ]);
  414. // 获取所有题目的正确答案
  415. $questionBankIds = array_filter(array_map(function($q) {
  416. return $q['id'] ?? $q['question_id'] ?? null;
  417. }, $examData['questions']));
  418. $correctAnswersMap = [];
  419. if (!empty($questionBankIds)) {
  420. Log::info('获取题目正确答案', [
  421. 'paper_id' => $paperId,
  422. 'question_bank_ids' => $questionBankIds
  423. ]);
  424. try {
  425. $response = Http::timeout(10)->post($this->baseUrl . '/questions/batch', [
  426. 'ids' => array_values($questionBankIds)
  427. ]);
  428. if ($response->successful()) {
  429. $questionsDetails = $response->json('data', []);
  430. foreach ($questionsDetails as $detail) {
  431. $correctAnswersMap[$detail['id']] = $detail['answer'] ?? $detail['correct_answer'] ?? '';
  432. }
  433. Log::info('获取到题目正确答案', [
  434. 'paper_id' => $paperId,
  435. 'answers_count' => count($correctAnswersMap)
  436. ]);
  437. }
  438. } catch (\Exception $e) {
  439. Log::warning('获取题目正确答案失败', [
  440. 'paper_id' => $paperId,
  441. 'error' => $e->getMessage()
  442. ]);
  443. }
  444. }
  445. // 准备题目数据
  446. $questionInsertData = [];
  447. foreach ($examData['questions'] as $index => $question) {
  448. // 验证题目基本数据
  449. if (empty($question['stem']) && empty($question['content'])) {
  450. Log::warning('跳过没有内容的题目', [
  451. 'paper_id' => $paperId,
  452. 'question_index' => $index
  453. ]);
  454. continue;
  455. }
  456. // 处理题目内容:分离题干和选项(如果存在)
  457. $rawContent = $question['stem'] ?? $question['content'] ?? '';
  458. list($stem, $options) = $this->separateStemAndOptions($rawContent);
  459. // 将选项以换行符形式附加到题干末尾,方便后续渲染
  460. if (!empty($options)) {
  461. $stemWithOptions = $stem . "\n" . implode("\n", array_map(function($opt, $idx) {
  462. return chr(65 + $idx) . '. ' . $opt;
  463. }, $options, array_keys($options)));
  464. $question['stem'] = $stemWithOptions;
  465. $question['options'] = $options;
  466. } else {
  467. $question['stem'] = $stem;
  468. }
  469. // 处理难度字段:如果是字符串则转换为数字
  470. $difficultyValue = $question['difficulty'] ?? 0.5;
  471. if (is_string($difficultyValue)) {
  472. // 将中文难度转换为数字
  473. if (strpos($difficultyValue, '基础') !== false || strpos($difficultyValue, '简单') !== false) {
  474. $difficultyValue = 0.3;
  475. } elseif (strpos($difficultyValue, '中等') !== false || strpos($difficultyValue, '一般') !== false) {
  476. $difficultyValue = 0.6;
  477. } elseif (strpos($difficultyValue, '拔高') !== false || strpos($difficultyValue, '困难') !== false) {
  478. $difficultyValue = 0.9;
  479. } else {
  480. $difficultyValue = 0.5;
  481. }
  482. }
  483. // 确保 knowledge_point 有值
  484. $knowledgePoint = $question['kp'] ?? $question['kp_code'] ?? $question['knowledge_point'] ?? $question['knowledge_point_code'] ?? '';
  485. if (empty($knowledgePoint) && isset($question['kp_code'])) {
  486. $knowledgePoint = $question['kp_code'];
  487. }
  488. // 获取题目类型
  489. $questionType = $question['question_type'] ?? 'answer';
  490. if (!$questionType) {
  491. // 如果没有类型,根据内容推断
  492. $content = $question['stem'] ?? $question['content'] ?? '';
  493. if (is_string($content)) {
  494. // 1. 优先检查填空题(下划线)
  495. if (strpos($content, '____') !== false || strpos($content, '______') !== false) {
  496. $questionType = 'fill';
  497. }
  498. // 2. 检查选择题(必须有选项 A. B. C. D.)
  499. elseif (preg_match('/[A-D]\s*\./', $content) || preg_match('/\([A-D]\)/', $content)) {
  500. if (preg_match('/A\./', $content) && preg_match('/B\./', $content)) {
  501. $questionType = 'choice';
  502. } else {
  503. // 只有括号没有选项,可能是填空
  504. if (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  505. $questionType = 'fill';
  506. } else {
  507. $questionType = 'answer';
  508. }
  509. }
  510. }
  511. // 3. 检查纯括号填空
  512. elseif (strpos($content, '()') !== false || strpos($content, '()') !== false) {
  513. $questionType = 'fill';
  514. }
  515. else {
  516. $questionType = 'answer';
  517. }
  518. } else {
  519. $questionType = 'answer';
  520. }
  521. }
  522. // 获取正确答案
  523. $questionBankId = $question['id'] ?? $question['question_id'] ?? null;
  524. $correctAnswer = $correctAnswersMap[$questionBankId] ?? $question['answer'] ?? $question['correct_answer'] ?? '';
  525. $questionInsertData[] = [
  526. 'paper_id' => $paperId,
  527. 'question_id' => $question['question_code'] ?? $question['question_id'] ?? null,
  528. 'question_bank_id' => $question['id'] ?? $question['question_id'] ?? 0,
  529. 'knowledge_point' => $knowledgePoint,
  530. 'question_type' => $questionType,
  531. 'question_text' => $question['stem'] ?? $question['content'] ?? $question['question_text'] ?? '',
  532. 'correct_answer' => $correctAnswer, // 保存正确答案
  533. 'difficulty' => $difficultyValue,
  534. 'score' => $question['score'] ?? 5, // 默认5分
  535. 'estimated_time' => $question['estimated_time'] ?? 300,
  536. 'question_number' => $index + 1,
  537. ];
  538. }
  539. // 验证是否有有效的题目数据
  540. if (empty($questionInsertData)) {
  541. Log::error('没有有效的题目数据可以保存', ['paper_id' => $paperId]);
  542. throw new \Exception('没有有效的题目数据');
  543. }
  544. // 使用Laravel模型批量插入题目数据
  545. \App\Models\PaperQuestion::insert($questionInsertData);
  546. // 验证插入结果,使用关联关系
  547. $insertedQuestionCount = $paper->questions()->count();
  548. if ($insertedQuestionCount !== count($questionInsertData)) {
  549. throw new \Exception("题目插入数量不匹配:预期 {$insertedQuestionCount},实际 " . count($questionInsertData));
  550. }
  551. Log::info('试卷保存成功', [
  552. 'paper_id' => $paperId,
  553. 'expected_questions' => count($questionInsertData),
  554. 'actual_questions' => $insertedQuestionCount,
  555. 'paper_name' => $paper->paper_name
  556. ]);
  557. return $paperId;
  558. });
  559. } catch (\Exception $e) {
  560. Log::error('保存试卷到数据库失败', [
  561. 'error' => $e->getMessage(),
  562. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  563. 'student_id' => $examData['student_id'] ?? 'unknown',
  564. 'question_count' => count($examData['questions'] ?? []),
  565. 'trace' => $e->getTraceAsString()
  566. ]);
  567. return null;
  568. }
  569. }
  570. /**
  571. * 检查数据完整性 - 发现没有题目的试卷
  572. */
  573. public function checkDataIntegrity(): array
  574. {
  575. try {
  576. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  577. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  578. ->whereDoesntHave('questions')
  579. ->get();
  580. Log::warning('发现数据不一致的试卷', [
  581. 'count' => $inconsistentPapers->count(),
  582. 'papers' => $inconsistentPapers->map(function($paper) {
  583. return [
  584. 'paper_id' => $paper->paper_id,
  585. 'paper_name' => $paper->paper_name,
  586. 'expected_questions' => $paper->question_count,
  587. 'student_id' => $paper->student_id,
  588. 'created_at' => $paper->created_at
  589. ];
  590. })->toArray()
  591. ]);
  592. return [
  593. 'inconsistent_count' => $inconsistentPapers->count(),
  594. 'papers' => $inconsistentPapers->toArray()
  595. ];
  596. } catch (\Exception $e) {
  597. Log::error('检查数据完整性失败', ['error' => $e->getMessage()]);
  598. return ['inconsistent_count' => 0, 'papers' => []];
  599. }
  600. }
  601. /**
  602. * 清理没有题目的试卷记录
  603. */
  604. public function cleanupInconsistentPapers(): int
  605. {
  606. try {
  607. return \Illuminate\Support\Facades\DB::transaction(function () {
  608. // 使用Laravel模型查找显示有题目但实际没有题目的试卷
  609. $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
  610. ->whereDoesntHave('questions')
  611. ->get();
  612. if ($inconsistentPapers->isEmpty()) {
  613. return 0;
  614. }
  615. // 获取要删除的试卷ID列表
  616. $deletedPaperIds = $inconsistentPapers->pluck('paper_id')->toArray();
  617. // 使用Laravel模型删除这些不一致的试卷记录
  618. $deletedCount = \App\Models\Paper::whereIn('paper_id', $deletedPaperIds)->delete();
  619. Log::info('清理不一致的试卷记录', [
  620. 'deleted_count' => $deletedCount,
  621. 'deleted_paper_ids' => $deletedPaperIds
  622. ]);
  623. return $deletedCount;
  624. });
  625. } catch (\Exception $e) {
  626. Log::error('清理不一致试卷失败', ['error' => $e->getMessage()]);
  627. return 0;
  628. }
  629. }
  630. /**
  631. * 修复试卷的题目数量统计
  632. */
  633. public function fixPaperQuestionCounts(): int
  634. {
  635. try {
  636. $fixedCount = 0;
  637. // 使用Laravel模型获取所有试卷
  638. $papers = \App\Models\Paper::all();
  639. foreach ($papers as $paper) {
  640. // 计算实际的题目数量,使用关联关系
  641. $actualQuestionCount = $paper->questions()->count();
  642. // 如果题目数量不匹配,更新试卷
  643. if ($paper->question_count !== $actualQuestionCount) {
  644. $paper->update([
  645. 'question_count' => $actualQuestionCount,
  646. 'updated_at' => now()
  647. ]);
  648. $fixedCount++;
  649. Log::info('修复试卷题目数量', [
  650. 'paper_id' => $paper->paper_id,
  651. 'old_count' => $paper->getOriginal('question_count'),
  652. 'new_count' => $actualQuestionCount
  653. ]);
  654. }
  655. }
  656. Log::info('试卷题目数量修复完成', ['fixed_count' => $fixedCount]);
  657. return $fixedCount;
  658. } catch (\Exception $e) {
  659. Log::error('修复试卷题目数量失败', ['error' => $e->getMessage()]);
  660. return 0;
  661. }
  662. }
  663. /**
  664. * 获取试卷列表
  665. */
  666. public function listExams(int $page = 1, int $perPage = 20): array
  667. {
  668. try {
  669. $response = Http::timeout(10)
  670. ->get($this->baseUrl . '/exam/list', [
  671. 'page' => $page,
  672. 'per_page' => $perPage
  673. ]);
  674. if ($response->successful()) {
  675. return $response->json();
  676. }
  677. Log::warning('获取试卷列表失败', [
  678. 'status' => $response->status()
  679. ]);
  680. } catch (\Exception $e) {
  681. Log::error('获取试卷列表异常', [
  682. 'error' => $e->getMessage()
  683. ]);
  684. }
  685. return ['data' => [], 'meta' => ['total' => 0]];
  686. }
  687. /**
  688. * 获取试卷详情
  689. */
  690. public function getExamById(string $paperId): ?array
  691. {
  692. try {
  693. $response = Http::timeout(10)
  694. ->get($this->baseUrl . '/exam/' . $paperId);
  695. if ($response->successful()) {
  696. return $response->json();
  697. }
  698. Log::warning('获取试卷详情失败', [
  699. 'paper_id' => $paperId,
  700. 'status' => $response->status()
  701. ]);
  702. } catch (\Exception $e) {
  703. Log::error('获取试卷详情异常', [
  704. 'paper_id' => $paperId,
  705. 'error' => $e->getMessage()
  706. ]);
  707. }
  708. return null;
  709. }
  710. /**
  711. * 导出试卷为PDF
  712. */
  713. public function exportExamToPdf(string $paperId): ?string
  714. {
  715. try {
  716. $response = Http::timeout(60)
  717. ->get($this->baseUrl . '/exam/' . $paperId . '/export/pdf');
  718. if ($response->successful()) {
  719. // 返回PDF文件路径或URL
  720. return $response->json('pdf_url', null);
  721. }
  722. Log::warning('导出PDF失败', [
  723. 'paper_id' => $paperId,
  724. 'status' => $response->status()
  725. ]);
  726. } catch (\Exception $e) {
  727. Log::error('导出PDF异常', [
  728. 'paper_id' => $paperId,
  729. 'error' => $e->getMessage()
  730. ]);
  731. }
  732. return null;
  733. }
  734. /**
  735. * 检查服务健康状态
  736. */
  737. public function checkHealth(): bool
  738. {
  739. try {
  740. // 健康检查使用不带/api的路径
  741. $healthUrl = str_replace('/api', '', $this->baseUrl) . '/health';
  742. $response = Http::timeout(5)
  743. ->get($healthUrl);
  744. return $response->successful();
  745. } catch (\Exception $e) {
  746. Log::error('题库服务健康检查失败', [
  747. 'error' => $e->getMessage()
  748. ]);
  749. return false;
  750. }
  751. }
  752. /**
  753. * 根据OCR识别的题目生成完整题目并保存到题库(异步模拟版本)
  754. *
  755. * @param array $questions OCR识别的题目列表
  756. * @param string $gradeLevel 年级
  757. * @param string $subject 科目
  758. * @param int $ocrRecordId OCR记录ID,用于关联
  759. * @param string|null $callbackUrl 回调URL(可选,如果不提供则自动生成)
  760. * @param string|null $callbackRouteName 回调路由名称(用于动态生成URL)
  761. * @return array 任务ID和状态
  762. */
  763. public function generateQuestionsFromOcrAsync(
  764. array $questions,
  765. string $gradeLevel = '高一',
  766. string $subject = '数学',
  767. int $ocrRecordId = null,
  768. string $callbackUrl = null,
  769. string $callbackRouteName = 'api.ocr.callback'
  770. ): array {
  771. try {
  772. // 如果没有提供回调URL,但提供了OCR记录ID,则动态生成回调URL
  773. if (!$callbackUrl && $ocrRecordId) {
  774. $callbackUrl = $this->generateCallbackUrl($callbackRouteName);
  775. Log::info('动态生成回调URL', [
  776. 'route_name' => $callbackRouteName,
  777. 'generated_url' => $callbackUrl
  778. ]);
  779. }
  780. // 生成唯一的任务ID
  781. $taskId = 'ocr_' . $ocrRecordId . '_' . time() . '_' . substr(md5(uniqid()), 0, 8);
  782. // 更新OCR记录状态为生成中
  783. if ($ocrRecordId) {
  784. \DB::table('ocr_question_results')
  785. ->where('ocr_record_id', $ocrRecordId)
  786. ->where('question_bank_id', null) // 只更新未关联的题目
  787. ->update([
  788. 'generation_status' => 'generating',
  789. 'generation_task_id' => $taskId,
  790. 'generation_error' => null
  791. ]);
  792. }
  793. // 启动后台任务(使用Laravel的队列)
  794. if ($ocrRecordId && $callbackUrl) {
  795. // 使用Laravel队列异步处理
  796. $this->dispatchOcrGenerationJob($ocrRecordId, $questions, $gradeLevel, $subject, $callbackUrl, $taskId);
  797. } else {
  798. // 如果没有回调URL,使用同步方式
  799. $response = $this->generateQuestionsFromOcr($questions, $gradeLevel, $subject);
  800. return $response;
  801. }
  802. Log::info('OCR题目生成任务已提交到队列', [
  803. 'task_id' => $taskId,
  804. 'ocr_record_id' => $ocrRecordId,
  805. 'questions_count' => count($questions),
  806. 'callback_url' => $callbackUrl
  807. ]);
  808. return [
  809. 'status' => 'processing',
  810. 'task_id' => $taskId,
  811. 'ocr_record_id' => $ocrRecordId,
  812. 'message' => '题目生成任务已启动,完成后将通过回调通知',
  813. 'estimated_time' => '约' . (count($questions) * 2) . '秒',
  814. 'callback_info' => [
  815. 'will_callback' => !empty($callbackUrl),
  816. 'callback_url' => $callbackUrl
  817. ]
  818. ];
  819. } catch (\Exception $e) {
  820. Log::error('OCR题目生成任务提交异常', [
  821. 'error' => $e->getMessage(),
  822. 'ocr_record_id' => $ocrRecordId
  823. ]);
  824. return [
  825. 'status' => 'error',
  826. 'message' => '任务提交失败: ' . $e->getMessage()
  827. ];
  828. }
  829. }
  830. /**
  831. * 分发OCR生成任务到队列
  832. */
  833. private function dispatchOcrGenerationJob(
  834. int $ocrRecordId,
  835. array $questions,
  836. string $gradeLevel,
  837. string $subject,
  838. string $callbackUrl,
  839. string $taskId
  840. ): void {
  841. try {
  842. // 转换题目数据格式
  843. $formattedQuestions = [];
  844. foreach ($questions as $q) {
  845. $formattedQuestions[] = [
  846. 'id' => $q['id'] ?? uniqid(),
  847. 'content' => $q['content'] ?? ''
  848. ];
  849. }
  850. // 直接调用QuestionBank API的异步端点,提供回调URL
  851. // 注意: baseUrl 已经包含 /api,所以这里只需要 /ocr/questions/generate-from-ocr
  852. $response = Http::timeout(60)
  853. ->post($this->baseUrl . '/ocr/questions/generate-from-ocr', [
  854. 'ocr_record_id' => $ocrRecordId,
  855. 'questions' => $formattedQuestions,
  856. 'grade_level' => $gradeLevel,
  857. 'subject' => $subject,
  858. 'callback_url' => $callbackUrl
  859. ]);
  860. if (!$response->successful()) {
  861. Log::error('提交OCR题目生成任务失败', [
  862. 'status' => $response->status(),
  863. 'body' => $response->body(),
  864. 'task_id' => $taskId
  865. ]);
  866. // 发送失败回调
  867. $callbackData = [
  868. 'task_id' => $taskId,
  869. 'ocr_record_id' => $ocrRecordId,
  870. 'status' => 'failed',
  871. 'error' => 'API调用失败: ' . $response->status(),
  872. 'timestamp' => now()->toISOString()
  873. ];
  874. Http::timeout(10)
  875. ->post($callbackUrl, $callbackData);
  876. return;
  877. }
  878. $result = $response->json();
  879. Log::info('OCR题目生成任务已提交到QuestionBank', [
  880. 'task_id' => $taskId,
  881. 'questionbank_task_id' => $result['task_id'] ?? 'unknown',
  882. 'status' => $result['status'] ?? 'unknown',
  883. 'callback_url' => $callbackUrl
  884. ]);
  885. // QuestionBank API会异步处理并通过回调通知,这里不需要立即触发回调
  886. // 回调会在题目生成完成后由QuestionBank API主动发送
  887. } catch (\Exception $e) {
  888. Log::error('OCR生成任务处理失败', [
  889. 'task_id' => $taskId,
  890. 'ocr_record_id' => $ocrRecordId,
  891. 'error' => $e->getMessage()
  892. ]);
  893. // 发送异常回调
  894. try {
  895. $callbackData = [
  896. 'task_id' => $taskId,
  897. 'ocr_record_id' => $ocrRecordId,
  898. 'status' => 'failed',
  899. 'error' => $e->getMessage(),
  900. 'timestamp' => now()->toISOString()
  901. ];
  902. Http::timeout(10)
  903. ->post($callbackUrl, $callbackData);
  904. } catch (\Exception $callbackException) {
  905. Log::error('发送异常回调失败', [
  906. 'error' => $callbackException->getMessage()
  907. ]);
  908. }
  909. }
  910. }
  911. /**
  912. * 动态生成回调URL
  913. *
  914. * @param string $routeName 路由名称
  915. * @return string 完整的回调URL
  916. */
  917. private function generateCallbackUrl(string $routeName): string
  918. {
  919. try {
  920. // 获取当前请求的域名
  921. $appUrl = config('app.url', 'http://localhost');
  922. // 如果是在命令行环境中运行,使用配置的域名
  923. if (app()->runningInConsole()) {
  924. $domain = config('services.question_bank.callback_domain', $appUrl);
  925. } else {
  926. $domain = request()->getSchemeAndHttpHost();
  927. }
  928. // 确保domain不为null
  929. $domain = $domain ?? $appUrl;
  930. // 移除末尾的斜杠
  931. $domain = rtrim($domain, '/');
  932. // 生成完整的URL
  933. $callbackUrl = $domain . route($routeName, [], false);
  934. Log::info('生成回调URL', [
  935. 'route_name' => $routeName,
  936. 'domain' => $domain,
  937. 'app_url' => $appUrl,
  938. 'callback_url' => $callbackUrl
  939. ]);
  940. return $callbackUrl;
  941. } catch (\Exception $e) {
  942. // 如果路由生成失败,使用默认URL
  943. Log::warning('路由生成失败,使用默认URL', [
  944. 'route_name' => $routeName,
  945. 'error' => $e->getMessage()
  946. ]);
  947. $fallbackUrl = config('app.url', 'http://localhost');
  948. if ($routeName === 'api.ocr.callback') {
  949. return $fallbackUrl . '/api/ocr-question-callback';
  950. }
  951. return $fallbackUrl;
  952. }
  953. }
  954. /**
  955. * 根据OCR识别的题目生成题库题目(同步版本,向后兼容)
  956. *
  957. * @param array $questions OCR题目数组 [['question_number' => 1, 'question_text' => '...']]
  958. * @param string $gradeLevel 年级
  959. * @param string $subject 科目
  960. * @return array 生成结果
  961. */
  962. public function generateQuestionsFromOcr(array $questions, string $gradeLevel = '高一', string $subject = '数学'): array
  963. {
  964. return $this->generateQuestionsFromOcrAsync($questions, $gradeLevel, $subject);
  965. }
  966. /**
  967. * 检查题目生成任务状态
  968. */
  969. public function checkGenerationTaskStatus(string $taskId): array
  970. {
  971. return $this->getTaskStatus($taskId) ?? ['status' => 'unknown'];
  972. }
  973. /**
  974. * 获取知识点题目统计信息
  975. * 根据知识点代码,统计该知识点及其子知识点和技能点的题目数量
  976. */
  977. public function getKnowledgePointStatistics(?string $kpCode = null): array
  978. {
  979. try {
  980. // 获取知识图谱数据和题目统计数据
  981. $knowledgeGraph = $this->getKnowledgeGraph();
  982. $nodes = $knowledgeGraph['nodes'] ?? [];
  983. $edges = $knowledgeGraph['edges'] ?? [];
  984. $questionStats = $this->getQuestionsStatisticsFromApi();
  985. // 构建知识点索引
  986. $nodeMap = [];
  987. foreach ($nodes as $node) {
  988. if (!empty($node['kp_code'])) {
  989. $nodeMap[$node['kp_code']] = $node;
  990. }
  991. }
  992. // 构建子知识点关系(从edges中提取)
  993. $childrenMap = [];
  994. $parentMap = [];
  995. foreach ($edges as $edge) {
  996. $source = $edge['source'] ?? '';
  997. $target = $edge['target'] ?? '';
  998. $direction = $edge['relation_direction'] ?? '';
  999. if (!empty($source) && !empty($target)) {
  1000. if ($direction === 'DOWNSTREAM') {
  1001. $childrenMap[$source][] = $target;
  1002. $parentMap[$target] = $source;
  1003. }
  1004. }
  1005. }
  1006. // 构建技能点统计
  1007. $skillStats = [];
  1008. foreach ($questionStats as $stat) {
  1009. $code = $stat['kp_code'] ?? '';
  1010. $skills = $stat['skills_list'] ?? [];
  1011. if (!empty($code)) {
  1012. foreach ($skills as $skillCode) {
  1013. if (!empty($skillCode)) {
  1014. if (!isset($skillStats[$code])) {
  1015. $skillStats[$code] = [];
  1016. }
  1017. if (!isset($skillStats[$code][$skillCode])) {
  1018. $skillStats[$code][$skillCode] = 0;
  1019. }
  1020. $skillStats[$code][$skillCode]++;
  1021. }
  1022. }
  1023. }
  1024. }
  1025. // 如果指定了特定知识点,只返回该知识点的统计
  1026. if ($kpCode && isset($nodeMap[$kpCode])) {
  1027. return $this->buildKnowledgePointStats($kpCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1028. }
  1029. // 否则返回所有顶级知识点的统计
  1030. $result = [];
  1031. $rootNodes = [];
  1032. // 找出根节点(没有父节点的节点)
  1033. foreach ($nodes as $node) {
  1034. $code = $node['kp_code'] ?? '';
  1035. if (!empty($code) && !isset($parentMap[$code])) {
  1036. $rootNodes[] = $code;
  1037. }
  1038. }
  1039. foreach ($rootNodes as $rootCode) {
  1040. $result[] = $this->buildKnowledgePointStats($rootCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1041. }
  1042. // 按题目总数排序
  1043. usort($result, function($a, $b) {
  1044. return ($b['total_questions'] ?? 0) <=> ($a['total_questions'] ?? 0);
  1045. });
  1046. return $result;
  1047. } catch (\Exception $e) {
  1048. Log::error('获取知识点统计失败', [
  1049. 'kp_code' => $kpCode,
  1050. 'error' => $e->getMessage()
  1051. ]);
  1052. return [];
  1053. }
  1054. }
  1055. /**
  1056. * 获取知识图谱数据
  1057. */
  1058. private function getKnowledgeGraph(): array
  1059. {
  1060. try {
  1061. $knowledgeApiBase = config('services.knowledge_api.base_url', 'http://localhost:5011');
  1062. $response = Http::timeout(10)
  1063. ->get($knowledgeApiBase . '/graph/export');
  1064. if ($response->successful()) {
  1065. return $response->json();
  1066. }
  1067. } catch (\Exception $e) {
  1068. Log::error('获取知识图谱失败', ['error' => $e->getMessage()]);
  1069. }
  1070. return ['nodes' => [], 'edges' => []];
  1071. }
  1072. /**
  1073. * 从 API 获取题目统计
  1074. */
  1075. private function getQuestionsStatisticsFromApi(): array
  1076. {
  1077. try {
  1078. // 调用题库 API 获取统计数据
  1079. $response = Http::timeout(30)
  1080. ->get($this->baseUrl . '/questions/statistics');
  1081. if ($response->successful()) {
  1082. $data = $response->json();
  1083. return $data['by_kp'] ?? [];
  1084. }
  1085. Log::warning('获取题目统计API失败', [
  1086. 'status' => $response->status(),
  1087. 'url' => $this->baseUrl . '/questions/statistics'
  1088. ]);
  1089. } catch (\Exception $e) {
  1090. Log::error('获取题目统计异常', [
  1091. 'error' => $e->getMessage(),
  1092. 'url' => $this->baseUrl . '/questions/statistics'
  1093. ]);
  1094. }
  1095. return [];
  1096. }
  1097. /**
  1098. * 构建单个知识点的统计信息
  1099. */
  1100. private function buildKnowledgePointStats(
  1101. string $kpCode,
  1102. array $nodeMap,
  1103. array $childrenMap,
  1104. array $questionStats,
  1105. array $skillStats
  1106. ): array {
  1107. $node = $nodeMap[$kpCode] ?? null;
  1108. if (!$node) {
  1109. return [];
  1110. }
  1111. // 获取直接子知识点
  1112. $children = $childrenMap[$kpCode] ?? [];
  1113. $directQuestionCount = 0;
  1114. // 查找当前知识点的题目数
  1115. foreach ($questionStats as $stat) {
  1116. if ($stat['kp_code'] === $kpCode) {
  1117. $directQuestionCount = $stat['question_count'] ?? 0;
  1118. break;
  1119. }
  1120. }
  1121. // 计算子知识点统计
  1122. $childrenStats = [];
  1123. foreach ($children as $childCode) {
  1124. $childStats = $this->buildKnowledgePointStats($childCode, $nodeMap, $childrenMap, $questionStats, $skillStats);
  1125. if (!empty($childStats)) {
  1126. $childrenStats[] = $childStats;
  1127. }
  1128. }
  1129. // 计算子知识点题目总数
  1130. $childrenQuestionCount = 0;
  1131. foreach ($childrenStats as $child) {
  1132. $childrenQuestionCount += $child['total_questions'] ?? 0;
  1133. }
  1134. // 获取当前知识点的技能点统计
  1135. $skillsCount = 0;
  1136. if (isset($skillStats[$kpCode])) {
  1137. $skillsCount = array_sum($skillStats[$kpCode]);
  1138. }
  1139. return [
  1140. 'kp_code' => $kpCode,
  1141. 'cn_name' => $node['cn_name'] ?? $kpCode,
  1142. 'en_name' => $node['en_name'] ?? '',
  1143. 'total_questions' => $directQuestionCount + $childrenQuestionCount,
  1144. 'direct_questions' => $directQuestionCount,
  1145. 'children_questions' => $childrenQuestionCount,
  1146. 'children' => $childrenStats,
  1147. 'skills_count' => count($skillStats[$kpCode] ?? []),
  1148. 'skills_total_questions' => $skillsCount,
  1149. 'skills' => array_map(function($skillCode, $count) use ($kpCode) {
  1150. return [
  1151. 'kp_code' => $kpCode,
  1152. 'skill_code' => $skillCode,
  1153. 'question_count' => $count
  1154. ];
  1155. }, array_keys($skillStats[$kpCode] ?? []), array_values($skillStats[$kpCode] ?? []))
  1156. ];
  1157. }
  1158. /**
  1159. * 获取所有试卷列表
  1160. */
  1161. public function getAllPapers(): array
  1162. {
  1163. try {
  1164. $response = Http::timeout(10)
  1165. ->get($this->baseUrl . '/papers');
  1166. if ($response->successful()) {
  1167. return $response->json('data', []);
  1168. }
  1169. Log::warning('获取试卷列表失败', [
  1170. 'status' => $response->status(),
  1171. 'response' => $response->body(),
  1172. ]);
  1173. return [];
  1174. } catch (\Exception $e) {
  1175. Log::error('获取试卷列表异常', [
  1176. 'error' => $e->getMessage(),
  1177. ]);
  1178. return [];
  1179. }
  1180. }
  1181. /**
  1182. * 获取指定试卷的题目
  1183. */
  1184. public function getPaperQuestions(string $paperId): array
  1185. {
  1186. try {
  1187. $response = Http::timeout(10)
  1188. ->get($this->baseUrl . '/papers/' . $paperId . '/questions');
  1189. if ($response->successful()) {
  1190. return $response->json('data', []);
  1191. }
  1192. Log::warning('获取试卷题目失败', [
  1193. 'paper_id' => $paperId,
  1194. 'status' => $response->status(),
  1195. 'response' => $response->body(),
  1196. ]);
  1197. return [];
  1198. } catch (\Exception $e) {
  1199. Log::error('获取试卷题目异常', [
  1200. 'paper_id' => $paperId,
  1201. 'error' => $e->getMessage(),
  1202. ]);
  1203. return [];
  1204. }
  1205. }
  1206. }