api.php 19 KB

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