QuestionBankService.php 47 KB

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