api.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. <?php
  2. use App\Http\Controllers\Api\IntelligentExamController;
  3. use App\Services\QuestionServiceApi;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Facades\Route;
  6. use App\Events\QuestionGenerationCompleted;
  7. use App\Events\QuestionGenerationFailed;
  8. /*
  9. |--------------------------------------------------------------------------
  10. | 题库管理 API 路由
  11. |--------------------------------------------------------------------------
  12. */
  13. // 接收题目生成回调
  14. Route::post('/questions/callback', function () {
  15. try {
  16. $data = request()->all();
  17. Log::info('Received question generation callback', $data);
  18. // 验证回调数据
  19. if (!isset($data['task_id']) || !isset($data['status'])) {
  20. return response()->json(['error' => 'Invalid callback data'], 400);
  21. }
  22. // 处理回调数据并存储通知到session
  23. if ($data['status'] === 'completed') {
  24. $result = $data['result'] ?? [];
  25. $total = $result['total'] ?? $data['total'] ?? ($result['saved'] ?? 0);
  26. $kpCode = $result['kp_code'] ?? $data['kp_code'] ?? '';
  27. // 将成功通知存储到session,供下次页面刷新时显示
  28. session()->flash('notification', [
  29. 'type' => 'success',
  30. 'title' => '✅ 题目生成完成',
  31. 'body' => "任务 ID: {$data['task_id']}\n生成题目: {$total} 道" . ($kpCode ? "\n知识点: {$kpCode}" : ''),
  32. 'color' => 'success'
  33. ]);
  34. Log::info("题目生成成功通知已存储", [
  35. 'task_id' => $data['task_id'],
  36. 'total' => $total,
  37. 'kp_code' => $kpCode
  38. ]);
  39. } elseif ($data['status'] === 'failed') {
  40. $error = $data['error'] ?? '未知错误';
  41. // 将失败通知存储到session
  42. session()->flash('notification', [
  43. 'type' => 'error',
  44. 'title' => '❌ 题目生成失败',
  45. 'body' => "任务 ID: {$data['task_id']}\n错误: {$error}",
  46. 'color' => 'danger'
  47. ]);
  48. Log::error("题目生成失败通知已存储", [
  49. 'task_id' => $data['task_id'],
  50. 'error' => $error
  51. ]);
  52. }
  53. return response()->json([
  54. 'success' => true,
  55. 'message' => 'Callback received and notification stored',
  56. 'status' => $data['status']
  57. ]);
  58. } catch (\Exception $e) {
  59. Log::error('Callback processing failed: ' . $e->getMessage());
  60. return response()->json(['error' => $e->getMessage()], 500);
  61. }
  62. })->name('api.questions.callback');
  63. // 接收OCR题目生成回调
  64. Route::post('/ocr-question-callback', function () {
  65. try {
  66. $data = request()->all();
  67. Log::info('Received OCR question generation callback', $data);
  68. // 验证必要的回调数据
  69. if (!isset($data['task_id']) || !isset($data['status']) || !isset($data['ocr_record_id'])) {
  70. Log::error('OCR callback missing required fields', $data);
  71. return response()->json([
  72. 'success' => false,
  73. 'error' => 'Missing required fields: task_id, status, ocr_record_id'
  74. ], 400);
  75. }
  76. $taskId = $data['task_id'];
  77. $ocrRecordId = $data['ocr_record_id'];
  78. $status = $data['status'];
  79. // 将回调结果存储到缓存中,供前端查询(保留30秒)
  80. $cacheKey = "ocr_callback_{$ocrRecordId}_{$taskId}";
  81. cache([$cacheKey => $data], now()->addSeconds(30));
  82. Log::info("OCR callback cached with key: {$cacheKey}", [
  83. 'ocr_record_id' => $ocrRecordId,
  84. 'task_id' => $taskId,
  85. 'status' => $status,
  86. 'total_generated' => $data['result']['total_generated'] ?? 0,
  87. 'total_saved' => $data['result']['total_saved'] ?? 0
  88. ]);
  89. // 处理题目关联逻辑
  90. if ($status === 'completed') {
  91. $updatedCount = 0;
  92. // 从result中提取question_mappings(QuestionBank API将它放在result字段中)
  93. $mappings = $data['result']['question_mappings'] ?? $data['question_mappings'] ?? [];
  94. Log::info("Processing OCR question associations", [
  95. 'ocr_record_id' => $ocrRecordId,
  96. 'task_id' => $taskId,
  97. 'mappings_count' => count($mappings)
  98. ]);
  99. // 更新ocr_question_results表中的关联关系
  100. foreach ($mappings as $mapping) {
  101. try {
  102. $ocrQuestionNumber = $mapping['ocr_question_number'] ?? null;
  103. $questionBankId = $mapping['question_bank_id'] ?? null;
  104. $questionCode = $mapping['question_code'] ?? null;
  105. if ($ocrQuestionNumber && $questionBankId) {
  106. // 查找对应的OCR题目结果并更新
  107. $updated = DB::table('ocr_question_results')
  108. ->where('ocr_record_id', $ocrRecordId)
  109. ->where('question_number', $ocrQuestionNumber)
  110. ->update([
  111. 'question_bank_id' => $questionBankId,
  112. 'generation_status' => 'completed',
  113. 'generation_task_id' => $taskId,
  114. 'generation_error' => null,
  115. ]);
  116. if ($updated) {
  117. $updatedCount++;
  118. Log::info("Updated OCR question association", [
  119. 'ocr_record_id' => $ocrRecordId,
  120. 'question_number' => $ocrQuestionNumber,
  121. 'question_bank_id' => $questionBankId,
  122. 'question_code' => $questionCode
  123. ]);
  124. } else {
  125. Log::warning("No OCR question result found for association", [
  126. 'ocr_record_id' => $ocrRecordId,
  127. 'question_number' => $ocrQuestionNumber
  128. ]);
  129. }
  130. }
  131. } catch (\Exception $e) {
  132. Log::error("Failed to update OCR question association", [
  133. 'mapping' => $mapping,
  134. 'error' => $e->getMessage()
  135. ]);
  136. }
  137. }
  138. Log::info("OCR question association completed", [
  139. 'ocr_record_id' => $ocrRecordId,
  140. 'task_id' => $taskId,
  141. 'total_mappings' => count($mappings),
  142. 'updated_count' => $updatedCount
  143. ]);
  144. // 更新OCR记录的整体状态为已完成
  145. try {
  146. DB::table('ocr_records')
  147. ->where('id', $ocrRecordId)
  148. ->update([
  149. 'status' => 'completed',
  150. 'processed_at' => now(),
  151. 'updated_at' => now()
  152. ]);
  153. Log::info("Updated OCR record status to completed", [
  154. 'ocr_record_id' => $ocrRecordId,
  155. 'task_id' => $taskId
  156. ]);
  157. } catch (\Exception $e) {
  158. Log::error("Failed to update OCR record status", [
  159. 'ocr_record_id' => $ocrRecordId,
  160. 'error' => $e->getMessage()
  161. ]);
  162. }
  163. } elseif ($status === 'failed') {
  164. // 更新所有相关的OCR题目结果为失败状态
  165. try {
  166. $updated = DB::table('ocr_question_results')
  167. ->where('ocr_record_id', $ocrRecordId)
  168. ->where('generation_status', 'pending') // 只更新待处理的
  169. ->update([
  170. 'generation_status' => 'failed',
  171. 'generation_task_id' => $taskId,
  172. 'generation_error' => $data['error'] ?? 'Unknown error',
  173. ]);
  174. Log::info("Updated OCR questions to failed status", [
  175. 'ocr_record_id' => $ocrRecordId,
  176. 'task_id' => $taskId,
  177. 'updated_count' => $updated,
  178. 'error' => $data['error'] ?? 'Unknown error'
  179. ]);
  180. // 更新OCR记录的状态为失败
  181. DB::table('ocr_records')
  182. ->where('id', $ocrRecordId)
  183. ->update([
  184. 'status' => 'failed',
  185. 'error_message' => $data['error'] ?? 'Question generation failed',
  186. 'updated_at' => now()
  187. ]);
  188. Log::info("Updated OCR record status to failed", [
  189. 'ocr_record_id' => $ocrRecordId,
  190. 'task_id' => $taskId,
  191. 'error' => $data['error'] ?? 'Unknown error'
  192. ]);
  193. } catch (\Exception $e) {
  194. Log::error("Failed to update OCR questions to failed status", [
  195. 'ocr_record_id' => $ocrRecordId,
  196. 'error' => $e->getMessage()
  197. ]);
  198. }
  199. }
  200. return response()->json([
  201. 'success' => true,
  202. 'message' => 'OCR callback received and processed',
  203. 'data' => [
  204. 'task_id' => $taskId,
  205. 'ocr_record_id' => $ocrRecordId,
  206. 'status' => $status,
  207. 'cache_key' => $cacheKey,
  208. 'associations_processed' => $status === 'completed' ? count($data['question_mappings'] ?? []) : 0
  209. ]
  210. ]);
  211. } catch (\Exception $e) {
  212. Log::error('OCR callback processing failed: ' . $e->getMessage());
  213. Log::error('Exception details: ' . $e->getTraceAsString());
  214. return response()->json([
  215. 'success' => false,
  216. 'error' => 'Callback processing failed: ' . $e->getMessage()
  217. ], 500);
  218. }
  219. })->name('api.ocr.callback');
  220. // 获取题目生成回调结果
  221. Route::get('/questions/callback/{taskId}', function (string $taskId) {
  222. // ✅ 优先从缓存读取(跨域友好)
  223. $callbackData = cache($taskId);
  224. if ($callbackData) {
  225. // 清除已读取的回调数据
  226. cache()->forget($taskId);
  227. session()->forget('question_gen_callback_' . $taskId);
  228. return response()->json($callbackData);
  229. }
  230. // 备选:从session读取
  231. $sessionData = session('question_gen_callback_' . $taskId);
  232. if ($sessionData) {
  233. // 清除已读取的回调数据
  234. session()->forget('question_gen_callback_' . $taskId);
  235. return response()->json($sessionData);
  236. }
  237. // 未收到回调
  238. return response()->json(['status' => 'pending'], 202);
  239. })->name('api.questions.callback.get');
  240. // 获取OCR题目生成回调结果
  241. Route::get('/ocr-question-callback/{ocrRecordId}/{taskId}', function (int $ocrRecordId, string $taskId) {
  242. $cacheKey = "ocr_callback_{$ocrRecordId}_{$taskId}";
  243. $callbackData = cache($cacheKey);
  244. if ($callbackData) {
  245. // 清除已读取的回调数据
  246. cache()->forget($cacheKey);
  247. return response()->json([
  248. 'success' => true,
  249. 'data' => $callbackData
  250. ]);
  251. }
  252. return response()->json([
  253. 'success' => false,
  254. 'status' => 'pending',
  255. 'message' => 'OCR callback not received yet'
  256. ], 202);
  257. })->name('api.ocr.callback.get');
  258. // 题目相关 API
  259. Route::get('/questions', function (QuestionServiceApi $service) {
  260. try {
  261. $page = (int) request()->get('page', 1);
  262. $perPage = (int) request()->get('per_page', 25);
  263. $filters = [
  264. 'kp_code' => request()->get('kp_code'),
  265. 'difficulty' => request()->get('difficulty'),
  266. 'search' => request()->get('search'),
  267. ];
  268. $response = $service->listQuestions($page, $perPage, $filters);
  269. return response()->json($response);
  270. } catch (\Exception $e) {
  271. \Log::error('Failed to fetch questions: ' . $e->getMessage());
  272. return response()->json([
  273. 'data' => [],
  274. 'meta' => [
  275. 'page' => 1,
  276. 'per_page' => 25,
  277. 'total' => 0,
  278. 'total_pages' => 0,
  279. ],
  280. 'error' => $e->getMessage(),
  281. ], 500);
  282. }
  283. });
  284. // 获取题目统计信息
  285. Route::get('/questions/statistics', function (QuestionServiceApi $service) {
  286. try {
  287. $stats = $service->getStatistics();
  288. return response()->json($stats);
  289. } catch (\Exception $e) {
  290. \Log::error('Failed to get question statistics: ' . $e->getMessage());
  291. return response()->json(['error' => $e->getMessage()], 500);
  292. }
  293. });
  294. // 语义搜索题目
  295. Route::post('/questions/search', function (QuestionServiceApi $service) {
  296. try {
  297. $data = request()->only(['query', 'limit']);
  298. $results = $service->searchQuestions($data['query'], $data['limit'] ?? 20);
  299. return response()->json($results);
  300. } catch (\Exception $e) {
  301. \Log::error('Question search failed: ' . $e->getMessage());
  302. return response()->json(['error' => $e->getMessage()], 500);
  303. }
  304. });
  305. // 获取单个题目详情
  306. Route::get('/questions/{id}', function (int $id, QuestionServiceApi $service) {
  307. try {
  308. $question = $service->getQuestionById($id);
  309. if (!$question) {
  310. return response()->json(['error' => 'Question not found'], 404);
  311. }
  312. return response()->json($question);
  313. } catch (\Exception $e) {
  314. \Log::error("Failed to get question {$id}: " . $e->getMessage());
  315. return response()->json(['error' => $e->getMessage()], 500);
  316. }
  317. });
  318. // AI 生成题目
  319. Route::post('/questions/generate', function (QuestionServiceApi $service) {
  320. try {
  321. $data = request()->only(['kp_code', 'keyword', 'count', 'strategy']);
  322. $result = $service->generateQuestions($data);
  323. return response()->json($result);
  324. } catch (\Exception $e) {
  325. \Log::error('Question generation failed: ' . $e->getMessage());
  326. return response()->json([
  327. 'success' => false,
  328. 'message' => $e->getMessage(),
  329. ], 500);
  330. }
  331. });
  332. // 删除题目
  333. Route::delete('/questions/{id}', function (int $id, QuestionServiceApi $service) {
  334. try {
  335. $deleted = $service->deleteQuestion($id);
  336. return response()->json([
  337. 'success' => $deleted,
  338. 'message' => $deleted ? 'Question deleted' : 'Failed to delete',
  339. ]);
  340. } catch (\Exception $e) {
  341. \Log::error("Failed to delete question {$id}: " . $e->getMessage());
  342. return response()->json([
  343. 'success' => false,
  344. 'message' => $e->getMessage(),
  345. ], 500);
  346. }
  347. });
  348. // 获取知识点选项
  349. Route::get('/knowledge-points', function (QuestionServiceApi $service) {
  350. try {
  351. $points = $service->getKnowledgePointOptions();
  352. return response()->json($points);
  353. } catch (\Exception $e) {
  354. \Log::error('Failed to get knowledge points: ' . $e->getMessage());
  355. return response()->json([], 500);
  356. }
  357. });
  358. // 智能出卷对外接口:生成试卷并返回PDF/判卷地址
  359. Route::post('/intelligent-exams', [IntelligentExamController::class, 'store'])
  360. ->name('api.intelligent-exams.store');
  361. /*
  362. |--------------------------------------------------------------------------
  363. | MathRecSys 集成 API 路由
  364. |--------------------------------------------------------------------------
  365. */
  366. use App\Http\Controllers\Api\StudentController;
  367. // 健康检查
  368. Route::get('/mathrecsys/health', [StudentController::class, 'checkServiceHealth'])->name('api.mathrecsys.health');
  369. // 学生相关 API
  370. Route::prefix('mathrecsys/students')->name('api.mathrecsys.students.')->group(function () {
  371. // 获取学生完整信息
  372. Route::get('{studentId}', [StudentController::class, 'show'])->name('show');
  373. // 获取个性化推荐
  374. Route::get('{studentId}/recommendations', [StudentController::class, 'getRecommendations'])->name('recommendations');
  375. // 获取学习轨迹
  376. Route::get('{studentId}/trajectory', [StudentController::class, 'getTrajectory'])->name('trajectory');
  377. // 获取学习建议
  378. Route::get('{studentId}/suggestions', [StudentController::class, 'getSuggestions'])->name('suggestions');
  379. // 智能分析题目
  380. Route::post('{studentId}/analyze', [StudentController::class, 'analyzeQuestion'])->name('analyze');
  381. // 更新掌握度
  382. Route::put('{studentId}/mastery', [StudentController::class, 'updateMastery'])->name('update-mastery');
  383. });
  384. // 班级分析 API
  385. Route::prefix('mathrecsys/classes')->name('api.mathrecsys.classes.')->group(function () {
  386. Route::get('{classId}/analysis', [StudentController::class, 'classAnalysis'])->name('analysis');
  387. });
  388. // 测试 API
  389. Route::get('/mathrecsys/test', function () {
  390. return response()->json([
  391. 'success' => true,
  392. 'message' => 'MathRecSys API integration is working',
  393. 'timestamp' => now()->toISOString()
  394. ]);
  395. })->name('api.mathrecsys.test');
  396. // 测试OCR题目生成API调用
  397. Route::post('/test-ocr-generation', function () {
  398. try {
  399. $service = new \App\Services\QuestionBankService();
  400. // 模拟前端传递的OCR题目数据
  401. $questions = [
  402. [
  403. 'id' => 1,
  404. 'content' => '计算:2+3-4'
  405. ],
  406. [
  407. 'id' => 2,
  408. 'content' => '解方程:x+5=10'
  409. ]
  410. ];
  411. Log::info('开始测试OCR题目生成', [
  412. 'questions_count' => count($questions),
  413. 'ocr_record_id' => 12
  414. ]);
  415. // 使用异步API,系统自动生成回调URL
  416. $response = $service->generateQuestionsFromOcrAsync(
  417. $questions,
  418. '高一',
  419. '数学',
  420. 12, // OCR记录ID
  421. null, // 让系统自动生成回调URL
  422. 'api.ocr.callback' // 回调路由名称
  423. );
  424. Log::info('OCR题目生成响应', [
  425. 'response' => $response,
  426. 'status' => $response['status'] ?? 'unknown',
  427. 'task_id' => $response['task_id'] ?? 'N/A'
  428. ]);
  429. return response()->json([
  430. 'success' => true,
  431. 'message' => 'OCR题目生成测试完成',
  432. 'data' => $response
  433. ]);
  434. } catch (\Exception $e) {
  435. Log::error('测试OCR题目生成失败', [
  436. 'error' => $e->getMessage(),
  437. 'trace' => $e->getTraceAsString()
  438. ]);
  439. return response()->json([
  440. 'success' => false,
  441. 'error' => $e->getMessage()
  442. ], 500);
  443. }
  444. })->name('api.test.ocr.generation');