UploadExamPaper.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. <?php
  2. namespace App\Filament\Pages;
  3. use App\Jobs\ProcessOCRRecord;
  4. use App\Models\OCRRecord;
  5. use App\Models\Student;
  6. use App\Models\Teacher;
  7. use BackedEnum;
  8. use Filament\Notifications\Notification;
  9. use Filament\Pages\Page;
  10. use Livewire\WithFileUploads;
  11. use Livewire\Attributes\Computed;
  12. use Livewire\Attributes\On;
  13. use Illuminate\Support\Facades\Storage;
  14. use UnitEnum;
  15. class UploadExamPaper extends Page
  16. {
  17. use WithFileUploads;
  18. protected static ?string $title = '上传考试卷子';
  19. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-arrow-up-tray';
  20. protected static ?string $navigationLabel = '上传考试卷子';
  21. protected static string|UnitEnum|null $navigationGroup = '操作';
  22. protected static ?int $navigationSort = 2;
  23. protected static ?string $slug = 'upload-exam-paper';
  24. protected string $view = 'filament.pages.upload-exam-paper';
  25. public ?string $teacherId = null;
  26. public ?string $studentId = null;
  27. public $uploadedImage = null;
  28. public bool $isUploading = false;
  29. public ?string $paperType = null; // 试卷类型:unit_test, midterm, final, homework, quiz, other
  30. // 新增:模式选择
  31. public string $mode = 'upload'; // 'upload' 或 'select_paper'
  32. public ?string $selectedPaperId = null;
  33. public array $questionGrades = []; // 存储每道题的评分
  34. public function mount()
  35. {
  36. $this->teacherId = null;
  37. $this->studentId = null;
  38. $this->uploadedImage = null;
  39. $this->paperType = null;
  40. $this->mode = 'upload';
  41. $this->selectedPaperId = null;
  42. $this->questionGrades = [];
  43. }
  44. #[Computed]
  45. public function teachers(): array
  46. {
  47. try {
  48. $teachers = Teacher::query()
  49. ->leftJoin('users as u', 'teachers.teacher_id', '=', 'u.user_id')
  50. ->select(
  51. 'teachers.teacher_id',
  52. 'teachers.name',
  53. 'teachers.subject',
  54. 'u.username',
  55. 'u.email'
  56. )
  57. ->orderBy('teachers.name')
  58. ->get();
  59. // 检查是否有学生没有对应的老师记录
  60. $teacherIds = $teachers->pluck('teacher_id')->toArray();
  61. $missingTeacherIds = Student::query()
  62. ->distinct()
  63. ->whereNotIn('teacher_id', $teacherIds)
  64. ->pluck('teacher_id')
  65. ->toArray();
  66. $teachersArray = $teachers->all();
  67. if (!empty($missingTeacherIds)) {
  68. foreach ($missingTeacherIds as $missingId) {
  69. $teachersArray[] = (object) [
  70. 'teacher_id' => $missingId,
  71. 'name' => '未知老师 (' . $missingId . ')',
  72. 'subject' => '未知',
  73. 'username' => null,
  74. 'email' => null
  75. ];
  76. }
  77. usort($teachersArray, function($a, $b) {
  78. return strcmp($a->name, $b->name);
  79. });
  80. }
  81. return $teachersArray;
  82. } catch (\Exception $e) {
  83. \Illuminate\Support\Facades\Log::error('加载老师列表失败', [
  84. 'error' => $e->getMessage()
  85. ]);
  86. return [];
  87. }
  88. }
  89. #[Computed]
  90. public function students(): array
  91. {
  92. if (empty($this->teacherId)) {
  93. return [];
  94. }
  95. try {
  96. return Student::query()
  97. ->leftJoin('users as u', 'students.student_id', '=', 'u.user_id')
  98. ->where('students.teacher_id', $this->teacherId)
  99. ->select(
  100. 'students.student_id',
  101. 'students.name',
  102. 'students.grade',
  103. 'students.class_name',
  104. 'u.username',
  105. 'u.email'
  106. )
  107. ->orderBy('students.grade')
  108. ->orderBy('students.class_name')
  109. ->orderBy('students.name')
  110. ->get()
  111. ->all();
  112. } catch (\Exception $e) {
  113. \Illuminate\Support\Facades\Log::error('加载学生列表失败', [
  114. 'teacher_id' => $this->teacherId,
  115. 'error' => $e->getMessage()
  116. ]);
  117. return [];
  118. }
  119. }
  120. #[Computed]
  121. public function recentRecords(): array
  122. {
  123. // 1. 获取OCR记录(图片上传)
  124. $ocrQuery = OCRRecord::with('student')->latest();
  125. // 如果选择了学生,则筛选该学生的记录
  126. if (!empty($this->studentId)) {
  127. $ocrQuery->where('user_id', $this->studentId);
  128. }
  129. $ocrRecords = $ocrQuery->take(5)
  130. ->get()
  131. ->map(function($record) {
  132. return [
  133. 'type' => 'ocr_upload',
  134. 'id' => $record->id,
  135. 'record_id' => $record->id,
  136. 'paper_id' => null,
  137. 'student_id' => $record->user_id,
  138. 'student_name' => $record->student?->name ?? $record->user_id,
  139. 'paper_type' => $record->paper_type_label,
  140. 'paper_name' => $record->image_filename ?: '未命名图片',
  141. 'status' => $record->status,
  142. 'total_questions' => $record->total_questions,
  143. 'processed_questions' => $record->processed_questions ?? 0,
  144. 'created_at' => $record->created_at->format('Y-m-d H:i'),
  145. 'is_completed' => $record->status === 'completed',
  146. ];
  147. })->toArray();
  148. // 2. 获取所有Paper记录(包括草稿和已评分)
  149. $paperQuery = \App\Models\Paper::with(['student'])->latest();
  150. // 如果选择了学生,则筛选该学生的记录
  151. if (!empty($this->studentId)) {
  152. $paperQuery->where('student_id', $this->studentId);
  153. }
  154. $allPapers = $paperQuery->take(5)
  155. ->get()
  156. ->map(function($paper) {
  157. $type = $paper->status === 'completed' ? 'graded_paper' : 'generated';
  158. $paperType = $paper->status === 'completed' ? '已评分试卷' : '系统生成试卷';
  159. $iconColor = $paper->status === 'completed' ? 'text-green-500' : 'text-blue-500';
  160. return [
  161. 'type' => $type,
  162. 'id' => $paper->paper_id,
  163. 'record_id' => null,
  164. 'paper_id' => $paper->paper_id,
  165. 'student_id' => $paper->student_id,
  166. 'student_name' => $paper->student?->name ?? $paper->student_id,
  167. 'paper_type' => $paperType,
  168. 'paper_name' => $paper->paper_name ?? '未命名试卷',
  169. 'status' => $paper->difficulty_category,
  170. 'total_questions' => $paper->question_count ?? 0,
  171. 'created_at' => $paper->created_at->format('Y-m-d H:i'),
  172. 'is_completed' => $paper->status === 'completed',
  173. 'icon_color' => $iconColor,
  174. ];
  175. })->toArray();
  176. // 3. 合并并按时间排序
  177. $allRecords = array_merge($ocrRecords, $allPapers);
  178. usort($allRecords, function($a, $b) {
  179. return strcmp($b['created_at'], $a['created_at']);
  180. });
  181. return array_slice($allRecords, 0, 10);
  182. }
  183. /**
  184. * 获取学生的试卷列表
  185. */
  186. #[Computed]
  187. public function studentPapers(): array
  188. {
  189. if (empty($this->studentId)) {
  190. return [];
  191. }
  192. try {
  193. // 使用 Student 关联查询试卷
  194. $student = \App\Models\Student::find($this->studentId);
  195. if (!$student) {
  196. \Log::warning('未找到指定学生', ['student_id' => $this->studentId]);
  197. return [];
  198. }
  199. return $student->papers()
  200. ->withCount('questions') // 添加题目计数
  201. ->orderBy('created_at', 'desc')
  202. ->take(20)
  203. ->get()
  204. ->map(function($paper) {
  205. return [
  206. 'paper_id' => $paper->paper_id, // 使用 paper_id 而不是 id
  207. 'paper_name' => $paper->paper_name ?? '未命名试卷',
  208. 'total_questions' => $paper->questions_count ?? 0,
  209. 'total_score' => $paper->total_score ?? 0,
  210. 'created_at' => $paper->created_at->format('Y-m-d H:i'),
  211. ];
  212. })
  213. ->toArray();
  214. } catch (\Exception $e) {
  215. \Log::error('获取学生试卷列表失败', [
  216. 'student_id' => $this->studentId,
  217. 'error' => $e->getMessage()
  218. ]);
  219. return [];
  220. }
  221. }
  222. #[Computed]
  223. public function paperTypes(): array
  224. {
  225. return [
  226. '' => '请选择试卷形式',
  227. 'unit_test' => '单元测试',
  228. 'midterm' => '期中考试',
  229. 'final' => '期末考试',
  230. 'homework' => '家庭作业',
  231. 'quiz' => '随堂测验',
  232. 'other' => '其他',
  233. ];
  234. }
  235. /**
  236. * 获取选中试卷的题目列表
  237. */
  238. #[Computed]
  239. public function selectedPaperQuestions(): array
  240. {
  241. if (empty($this->selectedPaperId)) {
  242. return [];
  243. }
  244. try {
  245. // 首先检查试卷是否存在
  246. $paper = \App\Models\Paper::where('paper_id', $this->selectedPaperId)->first();
  247. if (!$paper) {
  248. \Log::warning('未找到指定试卷', ['paper_id' => $this->selectedPaperId]);
  249. return [];
  250. }
  251. // 使用关联关系查询题目
  252. $paperWithQuestions = \App\Models\Paper::with(['questions' => function($query) {
  253. $query->orderBy('question_number');
  254. }])->where('paper_id', $this->selectedPaperId)->first();
  255. $questions = $paperWithQuestions ? $paperWithQuestions->questions : collect([]);
  256. // 处理数据不一致的情况:如果题目为空但试卷显示有题目
  257. if ($questions->isEmpty() && ($paper->question_count ?? 0) > 0) {
  258. \Log::warning('试卷显示有题目但实际题目数据缺失', [
  259. 'paper_id' => $this->selectedPaperId,
  260. 'expected_questions' => $paper->question_count,
  261. 'actual_questions' => 0
  262. ]);
  263. // 返回占位题目,让用户知道有数据缺失
  264. return [
  265. [
  266. 'id' => 'missing_data',
  267. 'question_number' => 1,
  268. 'question_bank_id' => null,
  269. 'question_type' => 'info',
  270. 'content' => "⚠️ 数据异常:试卷显示应有 {$paper->question_count} 道题目,但未找到题目数据。这通常是试卷创建过程中断导致的。请联系管理员或重新创建试卷。",
  271. 'answer' => '',
  272. 'score' => 0,
  273. 'is_missing_data' => true
  274. ]
  275. ];
  276. }
  277. if ($questions->isEmpty()) {
  278. \Log::info('试卷确实没有题目', ['paper_id' => $this->selectedPaperId]);
  279. return [
  280. [
  281. 'id' => 'no_questions',
  282. 'question_number' => 1,
  283. 'question_bank_id' => null,
  284. 'question_type' => 'info',
  285. 'content' => '该试卷暂无题目数据',
  286. 'answer' => '',
  287. 'score' => 0,
  288. 'is_empty' => true
  289. ]
  290. ];
  291. }
  292. // 获取题目详情
  293. $questionBankService = app(\App\Services\QuestionBankService::class);
  294. $questionIds = $questions->pluck('question_bank_id')->filter()->unique()->toArray();
  295. if (empty($questionIds)) {
  296. \Log::info('题目没有关联题库ID', ['paper_id' => $this->selectedPaperId]);
  297. // 返回基本的题目信息,不包含题库详情
  298. return $questions->map(function($q) {
  299. return [
  300. 'id' => $q->id,
  301. 'question_number' => $q->question_number,
  302. 'question_bank_id' => $q->question_bank_id,
  303. 'question_type' => $q->question_type,
  304. 'content' => '题目内容未关联到题库',
  305. 'answer' => '',
  306. 'score' => $q->score ?? 5,
  307. ];
  308. })->toArray();
  309. }
  310. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  311. $questionDetails = collect($questionsResponse['data'] ?? [])->keyBy('id');
  312. return $questions->map(function($q) use ($questionDetails) {
  313. $detail = $questionDetails->get($q->question_bank_id);
  314. return [
  315. 'id' => $q->id,
  316. 'question_number' => $q->question_number,
  317. 'question_bank_id' => $q->question_bank_id,
  318. 'question_type' => $q->question_type,
  319. 'content' => $detail['stem'] ?? '题目内容缺失',
  320. 'answer' => $detail['answer'] ?? '',
  321. 'score' => $q->score ?? 5,
  322. 'kp_code' => $q->knowledge_point, // 从本地数据库获取知识点代码
  323. ];
  324. })->toArray();
  325. } catch (\Exception $e) {
  326. \Log::error('获取试卷题目失败', [
  327. 'paper_id' => $this->selectedPaperId,
  328. 'error' => $e->getMessage(),
  329. 'trace' => $e->getTraceAsString()
  330. ]);
  331. return [
  332. [
  333. 'id' => 'error',
  334. 'question_number' => 1,
  335. 'question_bank_id' => null,
  336. 'question_type' => 'error',
  337. 'content' => '获取题目数据时发生错误:' . $e->getMessage(),
  338. 'answer' => '',
  339. 'score' => 0,
  340. 'is_error' => true
  341. ]
  342. ];
  343. }
  344. }
  345. public function updatedTeacherId($value): void
  346. {
  347. // 当教师选择变化时,清空之前选择的学生
  348. $this->studentId = null;
  349. $this->selectedPaperId = null;
  350. $this->questionGrades = [];
  351. }
  352. public function updatedStudentId($value): void
  353. {
  354. // 当学生选择变化时,清空已选试卷
  355. $this->selectedPaperId = null;
  356. $this->questionGrades = [];
  357. }
  358. public function updatedMode($value): void
  359. {
  360. // 切换模式时重置相关字段
  361. $this->uploadedImage = null;
  362. $this->selectedPaperId = null;
  363. $this->questionGrades = [];
  364. }
  365. public function submitUpload(): void
  366. {
  367. if (!$this->teacherId) {
  368. Notification::make()
  369. ->title('请选择老师')
  370. ->danger()
  371. ->send();
  372. return;
  373. }
  374. if (!$this->studentId) {
  375. Notification::make()
  376. ->title('请选择学生')
  377. ->danger()
  378. ->send();
  379. return;
  380. }
  381. if (!$this->uploadedImage) {
  382. Notification::make()
  383. ->title('请上传图片')
  384. ->danger()
  385. ->send();
  386. return;
  387. }
  388. $this->isUploading = true;
  389. try {
  390. // 保存图片
  391. $path = $this->uploadedImage->store('ocr-uploads', 'public');
  392. $filename = basename($path);
  393. // 创建OCR记录
  394. $record = OCRRecord::create([
  395. 'user_id' => $this->studentId,
  396. 'file_path' => $path,
  397. 'paper_title' => $filename,
  398. 'paper_type' => $this->paperType,
  399. 'status' => 'pending',
  400. 'total_questions' => 0,
  401. ]);
  402. // 立即更新状态为处理中,提供更好的用户体验
  403. $record->update(['status' => 'processing']);
  404. // 自动触发OCR处理
  405. ProcessOCRRecord::dispatch($record->id);
  406. // 重置表单
  407. $this->teacherId = null;
  408. $this->studentId = null;
  409. $this->uploadedImage = null;
  410. $this->paperType = null;
  411. Notification::make()
  412. ->title('上传成功')
  413. ->body("卷子已上传并开始OCR处理,正在跳转到校准页面...")
  414. ->success()
  415. ->send();
  416. // 跳转到OCR记录详情页面进行校准和提交分析
  417. $this->redirect("/admin/ocr-record-view/{$record->id}");
  418. } catch (\Exception $e) {
  419. Notification::make()
  420. ->title('上传失败')
  421. ->body($e->getMessage())
  422. ->danger()
  423. ->send();
  424. } finally {
  425. $this->isUploading = false;
  426. }
  427. }
  428. #[On('teacherChanged')]
  429. public function updateTeacherId($teacherId)
  430. {
  431. $this->teacherId = $teacherId;
  432. $this->studentId = null;
  433. }
  434. #[On('studentChanged')]
  435. public function updateStudentId($teacherId, $studentId)
  436. {
  437. $this->studentId = $studentId;
  438. }
  439. public function removeImage(): void
  440. {
  441. $this->uploadedImage = null;
  442. }
  443. /**
  444. * 提交手动评分
  445. */
  446. public function submitManualGrading(): void
  447. {
  448. if (!$this->selectedPaperId) {
  449. Notification::make()
  450. ->title('请选择试卷')
  451. ->danger()
  452. ->send();
  453. return;
  454. }
  455. if (empty($this->questionGrades)) {
  456. Notification::make()
  457. ->title('请至少为一道题目评分')
  458. ->danger()
  459. ->send();
  460. return;
  461. }
  462. try {
  463. // 准备数据发送到 LearningAnalytics
  464. $analyticsData = [];
  465. // 获取题目详情以便查找kp_code
  466. $questionsMap = collect($this->selectedPaperQuestions)->keyBy('id');
  467. // 收集需要从API补充信息的题目ID
  468. $missingKpCodeQuestionIds = [];
  469. foreach ($this->questionGrades as $questionId => $grade) {
  470. $question = $questionsMap->get($questionId);
  471. if (!$question) {
  472. continue;
  473. }
  474. // 优先使用本地存储的 kp_code
  475. if (empty($question['kp_code'])) {
  476. $missingKpCodeQuestionIds[] = $questionId;
  477. }
  478. }
  479. // 如果有缺失 kp_code 的题目,尝试从 API 获取
  480. $apiDetailsMap = collect([]);
  481. if (!empty($missingKpCodeQuestionIds)) {
  482. $questionBankIds = collect($missingKpCodeQuestionIds)
  483. ->map(fn($qId) => $questionsMap->get($qId)['question_bank_id'] ?? null)
  484. ->filter()
  485. ->toArray();
  486. if (!empty($questionBankIds)) {
  487. $questionBankService = app(\App\Services\QuestionBankService::class);
  488. $questionsDetails = $questionBankService->getQuestionsByIds($questionBankIds);
  489. $apiDetailsMap = collect($questionsDetails['data'] ?? [])->keyBy('id');
  490. }
  491. }
  492. foreach ($this->questionGrades as $questionId => $grade) {
  493. $question = $questionsMap->get($questionId);
  494. if (!$question) {
  495. continue;
  496. }
  497. $kpCode = $question['kp_code'];
  498. // 如果本地没有,尝试从API结果中获取
  499. if (empty($kpCode)) {
  500. $detail = $apiDetailsMap->get($question['question_bank_id']);
  501. $kpCode = $detail['kp_code'] ?? $detail['knowledge_point_code'] ?? null;
  502. }
  503. $analyticsData[] = [
  504. 'question_bank_id' => $question['question_bank_id'],
  505. 'student_answer' => $grade['student_answer'] ?? '',
  506. 'is_correct' => $grade['is_correct'] ?? null,
  507. 'score' => $grade['score'] ?? null,
  508. 'max_score' => $question['score'],
  509. 'kp_code' => $kpCode, // 添加 kp_code
  510. ];
  511. }
  512. // 调用 LearningAnalytics 服务
  513. $learningAnalyticsService = app(\App\Services\LearningAnalyticsService::class);
  514. // 步骤0: 保存学生答案到本地数据库 (重要:确保数据持久化)
  515. foreach ($this->questionGrades as $questionId => $grade) {
  516. \App\Models\PaperQuestion::where('id', $questionId)->update([
  517. 'student_answer' => $grade['student_answer'] ?? '',
  518. 'is_correct' => $grade['is_correct'] ?? false,
  519. 'score_obtained' => $grade['score'] ?? 0,
  520. ]);
  521. }
  522. \Log::info('学生答案已保存到数据库', [
  523. 'student_id' => $this->studentId,
  524. 'paper_id' => $this->selectedPaperId,
  525. 'updated_count' => count($this->questionGrades)
  526. ]);
  527. // 步骤1: 保存答题记录到 LearningAnalytics
  528. \Log::info('准备调用submitBatchAttempts API', [
  529. 'student_id' => $this->studentId,
  530. 'paper_id' => $this->selectedPaperId,
  531. 'analytics_data_sample' => array_slice($analyticsData, 0, 2) // 记录前2题的数据作为样本
  532. ]);
  533. $result = $learningAnalyticsService->submitBatchAttempts($this->studentId, [
  534. 'paper_id' => $this->selectedPaperId,
  535. 'answers' => $analyticsData,
  536. ]);
  537. // 检查API返回结果
  538. if (is_array($result) && isset($result['error']) && $result['error']) {
  539. throw new \Exception($result['message'] ?? 'API调用失败');
  540. }
  541. if ($result === null || (is_array($result) && empty($result))) {
  542. throw new \Exception('API返回空数据');
  543. }
  544. \Log::info('答题记录已保存到学习分析服务', [
  545. 'student_id' => $this->studentId,
  546. 'paper_id' => $this->selectedPaperId,
  547. 'count' => count($analyticsData)
  548. ]);
  549. // 步骤2: 触发 AI 分析(包含掌握度更新和学习报告生成)
  550. try {
  551. $paper = \App\Models\Paper::find($this->selectedPaperId);
  552. // 构造 AI 分析请求数据
  553. $analysisQuestions = [];
  554. foreach ($this->questionGrades as $questionId => $grade) {
  555. $question = $questionsMap->get($questionId);
  556. if (!$question) {
  557. continue;
  558. }
  559. $kpCode = $question['kp_code'];
  560. if (empty($kpCode)) {
  561. $detail = $apiDetailsMap->get($question['question_bank_id']);
  562. $kpCode = $detail['kp_code'] ?? $detail['knowledge_point_code'] ?? null;
  563. }
  564. $analysisQuestions[] = [
  565. 'question_id' => $question['question_bank_id'],
  566. 'question_number' => (string)$question['question_number'],
  567. 'question_text' => $question['content'] ?? '',
  568. 'student_answer' => $grade['student_answer'] ?? '',
  569. 'correct_answer' => $question['answer'] ?? '',
  570. 'kp_code' => $kpCode,
  571. 'score_value' => $grade['score'] ?? 0,
  572. 'max_score' => $question['score'],
  573. 'is_correct' => $grade['is_correct'] ?? false,
  574. 'teacher_validated' => true, // 手动评分即为教师验证
  575. 'ocr_confidence' => 1.0, // 手动评分置信度为1
  576. ];
  577. }
  578. $analysisData = [
  579. 'exam_id' => $this->selectedPaperId,
  580. 'student_id' => $this->studentId,
  581. 'ocr_record_id' => 0, // 系统生成卷子没有OCR记录ID
  582. 'paper_id' => $this->selectedPaperId,
  583. 'teacher_name' => auth()->user()->name ?? 'Teacher',
  584. 'analysis_type' => 'mastery',
  585. 'questions' => $analysisQuestions,
  586. ];
  587. // 调用统一的 AI 分析接口
  588. \Log::info('准备调用submitOCRAnalysis API', [
  589. 'paper_id' => $this->selectedPaperId,
  590. 'student_id' => $this->studentId,
  591. 'analysis_data_sample' => [
  592. 'question_count' => count($analysisQuestions),
  593. 'first_question' => $analysisQuestions[0] ?? null
  594. ]
  595. ]);
  596. $analysisResult = $learningAnalyticsService->submitOCRAnalysis($analysisData);
  597. \Log::info('AI分析已触发', [
  598. 'paper_id' => $this->selectedPaperId,
  599. 'student_id' => $this->studentId,
  600. 'analysis_result_keys' => is_array($analysisResult) ? array_keys($analysisResult) : 'not_array',
  601. 'analysis_result' => $analysisResult
  602. ]);
  603. // 保存 analysis_id 到 Paper 表
  604. if (isset($analysisResult['analysis_id'])) {
  605. \App\Models\Paper::where('paper_id', $this->selectedPaperId)->update([
  606. 'analysis_id' => $analysisResult['analysis_id'],
  607. ]);
  608. \Log::info('已保存 analysis_id', [
  609. 'paper_id' => $this->selectedPaperId,
  610. 'analysis_id' => $analysisResult['analysis_id']
  611. ]);
  612. }
  613. } catch (\Exception $analysisError) {
  614. // AI 分析失败不影响主流程
  615. \Log::warning('触发AI分析失败', [
  616. 'paper_id' => $this->selectedPaperId,
  617. 'error' => $analysisError->getMessage()
  618. ]);
  619. }
  620. // 更新Paper表状态为已完成评分
  621. \App\Models\Paper::where('paper_id', $this->selectedPaperId)->update([
  622. 'status' => 'completed',
  623. 'completed_at' => now(),
  624. ]);
  625. Notification::make()
  626. ->title('提交成功')
  627. ->body('评分已提交,AI分析正在进行中')
  628. ->success()
  629. ->send();
  630. // 刷新最近记录列表
  631. unset($this->recentRecords);
  632. // 重置表单
  633. $this->selectedPaperId = null;
  634. $this->questionGrades = [];
  635. } catch (\Exception $e) {
  636. \Log::error('提交手动评分失败', [
  637. 'error' => $e->getMessage(),
  638. 'student_id' => $this->studentId,
  639. 'paper_id' => $this->selectedPaperId,
  640. ]);
  641. Notification::make()
  642. ->title('提交失败')
  643. ->body($e->getMessage())
  644. ->danger()
  645. ->send();
  646. }
  647. }
  648. }