UploadExamPaper.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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 App\Filament\Traits\HasUserRole;
  8. use BackedEnum;
  9. use Filament\Notifications\Notification;
  10. use Filament\Pages\Page;
  11. use Filament\Forms;
  12. use Livewire\WithFileUploads;
  13. use Livewire\Attributes\Computed;
  14. use Livewire\Attributes\On;
  15. use Illuminate\Support\Facades\Storage;
  16. use UnitEnum;
  17. class UploadExamPaper extends Page
  18. {
  19. use HasUserRole, WithFileUploads;
  20. protected static ?string $title = '上传试卷';
  21. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-cloud-arrow-up';
  22. protected static ?string $navigationLabel = '上传试卷';
  23. protected static string|UnitEnum|null $navigationGroup = '操作';
  24. protected static ?int $navigationSort = 2;
  25. protected static ?string $slug = 'upload-exam-paper';
  26. protected string $view = 'filament.pages.upload-exam-paper';
  27. public ?string $teacherId = null;
  28. public ?string $studentId = null;
  29. public $uploadedImage = null;
  30. public bool $isUploading = false;
  31. public ?string $paperType = null; // 试卷类型:unit_test, midterm, final, homework, quiz, other
  32. public $form;
  33. public array $data = [];
  34. public bool $analyzing = false;
  35. public ?string $analysisError = null;
  36. // 新增:模式选择
  37. public string $mode = 'upload'; // 'upload' 或 'select_paper'
  38. public ?string $selectedPaperId = null;
  39. public bool $showGrading = false;
  40. public array $questions = [];
  41. public array $gradingData = [];
  42. public ?string $paperName = null;
  43. public ?string $paperClass = null;
  44. public ?string $paperStudent = null;
  45. public ?string $paperDate = null;
  46. public array $questionGrades = []; // 存储每道题的评分
  47. public function mount()
  48. {
  49. // 初始化用户角色
  50. $this->initializeUserRole();
  51. // 如果是老师,自动选择当前老师
  52. if ($this->isTeacher) {
  53. $teacherId = $this->getCurrentTeacherId();
  54. if ($teacherId) {
  55. $this->teacherId = $teacherId;
  56. }
  57. } else {
  58. $this->teacherId = null;
  59. }
  60. $this->studentId = null;
  61. $this->uploadedImage = null;
  62. $this->paperType = null;
  63. $this->mode = 'upload';
  64. $this->selectedPaperId = null;
  65. $this->questionGrades = [];
  66. }
  67. public function form(Forms\Form $form): Forms\Form
  68. {
  69. return $form
  70. ->statePath('data')
  71. ->schema([
  72. Forms\Components\FileUpload::make('image')
  73. ->label('上传试卷图片')
  74. ->image()
  75. ->multiple()
  76. ->directory('exam-papers')
  77. ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/jpg'])
  78. ->helperText('支持PNG、JPG、JPEG格式,可同时上传多张图片')
  79. ->maxFiles(10)
  80. ->required(),
  81. Forms\Components\TextInput::make('paper_name')
  82. ->label('试卷名称')
  83. ->required()
  84. ->placeholder('例如:数学期末考试'),
  85. Forms\Components\Select::make('class')
  86. ->label('班级')
  87. ->options([
  88. 'ClassA' => '三年级一班',
  89. 'ClassB' => '三年级二班',
  90. 'ClassC' => '四年级一班',
  91. 'ClassD' => '四年级二班',
  92. 'ClassE' => '五年级一班',
  93. 'ClassF' => '五年级二班',
  94. 'ClassG' => '六年级一班',
  95. 'ClassH' => '六年级二班',
  96. ])
  97. ->required(),
  98. Forms\Components\TextInput::make('student_name')
  99. ->label('学生姓名')
  100. ->required()
  101. ->placeholder('请输入学生姓名'),
  102. Forms\Components\Select::make('paper_type')
  103. ->label('试卷类型')
  104. ->options([
  105. 'quiz' => '课堂测验',
  106. 'midterm' => '期中考试',
  107. 'final' => '期末考试',
  108. 'homework' => '家庭作业',
  109. ])
  110. ->default('quiz')
  111. ->required(),
  112. Forms\Components\TextInput::make('paper_subject')
  113. ->label('科目')
  114. ->default('数学')
  115. ->required(),
  116. ]);
  117. }
  118. #[Computed]
  119. public function teachers(): array
  120. {
  121. try {
  122. $query = Teacher::query()
  123. ->leftJoin('users as u', 'teachers.teacher_id', '=', 'u.user_id')
  124. ->select(
  125. 'teachers.teacher_id',
  126. 'teachers.name',
  127. 'teachers.subject',
  128. 'u.username',
  129. 'u.email'
  130. );
  131. // 如果是老师,只返回自己
  132. if ($this->isTeacher) {
  133. $teacherId = $this->getCurrentTeacherId();
  134. if ($teacherId) {
  135. $query->where('teachers.teacher_id', $teacherId);
  136. }
  137. }
  138. $teachers = $query->orderBy('teachers.name')->get();
  139. // 检查是否有学生没有对应的老师记录
  140. $teacherIds = $teachers->pluck('teacher_id')->toArray();
  141. $missingTeacherIds = Student::query()
  142. ->distinct()
  143. ->whereNotIn('teacher_id', $teacherIds)
  144. ->pluck('teacher_id')
  145. ->toArray();
  146. $teachersArray = $teachers->all();
  147. if (!empty($missingTeacherIds)) {
  148. foreach ($missingTeacherIds as $missingId) {
  149. $teachersArray[] = (object) [
  150. 'teacher_id' => $missingId,
  151. 'name' => '未知老师 (' . $missingId . ')',
  152. 'subject' => '未知',
  153. 'username' => null,
  154. 'email' => null
  155. ];
  156. }
  157. usort($teachersArray, function($a, $b) {
  158. return strcmp($a->name, $b->name);
  159. });
  160. }
  161. return $teachersArray;
  162. } catch (\Exception $e) {
  163. \Illuminate\Support\Facades\Log::error('加载老师列表失败', [
  164. 'error' => $e->getMessage()
  165. ]);
  166. return [];
  167. }
  168. }
  169. #[Computed]
  170. public function students(): array
  171. {
  172. if (empty($this->teacherId)) {
  173. return [];
  174. }
  175. try {
  176. return Student::query()
  177. ->leftJoin('users as u', 'students.student_id', '=', 'u.user_id')
  178. ->where('students.teacher_id', $this->teacherId)
  179. ->select(
  180. 'students.student_id',
  181. 'students.name',
  182. 'students.grade',
  183. 'students.class_name',
  184. 'u.username',
  185. 'u.email'
  186. )
  187. ->orderBy('students.grade')
  188. ->orderBy('students.class_name')
  189. ->orderBy('students.name')
  190. ->get()
  191. ->all();
  192. } catch (\Exception $e) {
  193. \Illuminate\Support\Facades\Log::error('加载学生列表失败', [
  194. 'teacher_id' => $this->teacherId,
  195. 'error' => $e->getMessage()
  196. ]);
  197. return [];
  198. }
  199. }
  200. #[Computed]
  201. public function recentRecords(): array
  202. {
  203. // 1. 获取OCR记录(图片上传)
  204. $ocrQuery = OCRRecord::with('student');
  205. // 如果选择了学生,则筛选该学生的记录
  206. if (!empty($this->studentId)) {
  207. $ocrQuery->where('user_id', $this->studentId);
  208. }
  209. $ocrRecords = $ocrQuery->latest()->take(5)->get()
  210. ->map(function($record) {
  211. $studentName = $record->student?->name ?: ('学生ID: ' . $record->user_id);
  212. return [
  213. 'type' => 'ocr_upload',
  214. 'id' => $record->id,
  215. 'record_id' => $record->id,
  216. 'paper_id' => null,
  217. 'student_id' => $record->user_id,
  218. 'student_name' => $studentName,
  219. 'paper_type' => $record->paper_type_label,
  220. 'paper_name' => $record->image_filename ?: '未命名图片',
  221. 'status' => $record->status,
  222. 'total_questions' => $record->total_questions,
  223. 'processed_questions' => $record->processed_questions ?? 0,
  224. 'created_at' => $record->created_at->format('Y-m-d H:i'),
  225. 'is_completed' => $record->status === 'completed',
  226. ];
  227. })->toArray();
  228. // 2. 获取所有Paper记录(包括草稿和已评分)
  229. $paperQuery = \App\Models\Paper::with('student');
  230. // 如果选择了学生,则筛选该学生的记录
  231. if (!empty($this->studentId)) {
  232. $paperQuery->where('student_id', $this->studentId);
  233. }
  234. $allPapers = $paperQuery->latest()->take(5)->get()
  235. ->map(function($paper) {
  236. $type = $paper->status === 'completed' ? 'graded_paper' : 'generated';
  237. $paperType = $paper->status === 'completed' ? '已评分试卷' : '系统生成试卷';
  238. $iconColor = $paper->status === 'completed' ? 'text-green-500' : 'text-blue-500';
  239. $studentName = $paper->student?->name ?: ('学生ID: ' . $paper->student_id);
  240. return [
  241. 'type' => $type,
  242. 'id' => $paper->paper_id,
  243. 'record_id' => null,
  244. 'paper_id' => $paper->paper_id,
  245. 'student_id' => $paper->student_id,
  246. 'student_name' => $studentName,
  247. 'paper_type' => $paperType,
  248. 'paper_name' => $paper->paper_name ?? '未命名试卷',
  249. 'status' => $paper->difficulty_category,
  250. 'total_questions' => $paper->question_count ?? 0,
  251. 'created_at' => $paper->created_at->format('Y-m-d H:i'),
  252. 'is_completed' => $paper->status === 'completed',
  253. 'icon_color' => $iconColor,
  254. ];
  255. })->toArray();
  256. // 3. 合并并按时间排序
  257. $allRecords = array_merge($ocrRecords, $allPapers);
  258. usort($allRecords, function($a, $b) {
  259. return strcmp($b['created_at'], $a['created_at']);
  260. });
  261. return array_slice($allRecords, 0, 10);
  262. }
  263. /**
  264. * 获取学生的试卷列表
  265. */
  266. #[Computed]
  267. public function studentPapers(): array
  268. {
  269. if (empty($this->studentId)) {
  270. return [];
  271. }
  272. try {
  273. // 使用 Student 关联查询试卷
  274. $student = \App\Models\Student::find($this->studentId);
  275. if (!$student) {
  276. \Log::warning('未找到指定学生', ['student_id' => $this->studentId]);
  277. return [];
  278. }
  279. return $student->papers()
  280. ->withCount('questions') // 添加题目计数
  281. ->orderBy('created_at', 'desc')
  282. ->take(20)
  283. ->get()
  284. ->map(function($paper) {
  285. return [
  286. 'paper_id' => $paper->paper_id, // 使用 paper_id 而不是 id
  287. 'paper_name' => $paper->paper_name ?? '未命名试卷',
  288. 'total_questions' => $paper->questions_count ?? 0,
  289. 'total_score' => $paper->total_score ?? 0,
  290. 'created_at' => $paper->created_at->format('Y-m-d H:i'),
  291. ];
  292. })
  293. ->toArray();
  294. } catch (\Exception $e) {
  295. \Log::error('获取学生试卷列表失败', [
  296. 'student_id' => $this->studentId,
  297. 'error' => $e->getMessage()
  298. ]);
  299. return [];
  300. }
  301. }
  302. #[Computed]
  303. public function paperTypes(): array
  304. {
  305. return [
  306. '' => '请选择试卷形式',
  307. 'unit_test' => '单元测试',
  308. 'midterm' => '期中考试',
  309. 'final' => '期末考试',
  310. 'homework' => '家庭作业',
  311. 'quiz' => '随堂测验',
  312. 'other' => '其他',
  313. ];
  314. }
  315. /**
  316. * 获取选中试卷的题目列表
  317. */
  318. #[Computed]
  319. public function selectedPaperQuestions(): array
  320. {
  321. if (empty($this->selectedPaperId)) {
  322. return [];
  323. }
  324. try {
  325. // 首先检查试卷是否存在
  326. $paper = \App\Models\Paper::where('paper_id', $this->selectedPaperId)->first();
  327. if (!$paper) {
  328. \Log::warning('未找到指定试卷', ['paper_id' => $this->selectedPaperId]);
  329. return [];
  330. }
  331. // 使用关联关系查询题目
  332. $paperWithQuestions = \App\Models\Paper::with(['questions' => function($query) {
  333. $query->orderBy('question_number');
  334. }])->where('paper_id', $this->selectedPaperId)->first();
  335. $questions = $paperWithQuestions ? $paperWithQuestions->questions : collect([]);
  336. // 处理数据不一致的情况:如果题目为空但试卷显示有题目
  337. if ($questions->isEmpty() && ($paper->question_count ?? 0) > 0) {
  338. \Log::warning('试卷显示有题目但实际题目数据缺失', [
  339. 'paper_id' => $this->selectedPaperId,
  340. 'expected_questions' => $paper->question_count,
  341. 'actual_questions' => 0
  342. ]);
  343. // 返回占位题目,让用户知道有数据缺失
  344. return [
  345. [
  346. 'id' => 'missing_data',
  347. 'question_number' => 1,
  348. 'question_bank_id' => null,
  349. 'question_type' => 'info',
  350. 'content' => "⚠️ 数据异常:试卷显示应有 {$paper->question_count} 道题目,但未找到题目数据。这通常是试卷创建过程中断导致的。请联系管理员或重新创建试卷。",
  351. 'answer' => '',
  352. 'score' => 0,
  353. 'is_missing_data' => true
  354. ]
  355. ];
  356. }
  357. if ($questions->isEmpty()) {
  358. \Log::info('试卷确实没有题目', ['paper_id' => $this->selectedPaperId]);
  359. return [
  360. [
  361. 'id' => 'no_questions',
  362. 'question_number' => 1,
  363. 'question_bank_id' => null,
  364. 'question_type' => 'info',
  365. 'content' => '该试卷暂无题目数据',
  366. 'answer' => '',
  367. 'score' => 0,
  368. 'is_empty' => true
  369. ]
  370. ];
  371. }
  372. // 获取题目详情
  373. $questionBankService = app(\App\Services\QuestionBankService::class);
  374. $questionIds = $questions->pluck('question_bank_id')->filter()->unique()->toArray();
  375. if (empty($questionIds)) {
  376. \Log::info('题目没有关联题库ID', ['paper_id' => $this->selectedPaperId]);
  377. // 返回基本的题目信息,不包含题库详情
  378. return $questions->map(function($q) {
  379. return [
  380. 'id' => $q->id,
  381. 'question_number' => $q->question_number,
  382. 'question_bank_id' => $q->question_bank_id,
  383. 'question_type' => $q->question_type,
  384. 'content' => '题目内容未关联到题库',
  385. 'answer' => '',
  386. 'score' => $q->score ?? 5,
  387. ];
  388. })->toArray();
  389. }
  390. $questionsResponse = $questionBankService->getQuestionsByIds($questionIds);
  391. $questionDetails = collect($questionsResponse['data'] ?? [])->keyBy('id');
  392. return $questions->map(function($q) use ($questionDetails) {
  393. $detail = $questionDetails->get($q->question_bank_id);
  394. return [
  395. 'id' => $q->id,
  396. 'question_number' => $q->question_number,
  397. 'question_bank_id' => $q->question_bank_id,
  398. 'question_type' => $q->question_type,
  399. 'content' => $detail['stem'] ?? '题目内容缺失',
  400. 'answer' => $detail['answer'] ?? '',
  401. 'score' => $q->score ?? 5,
  402. 'kp_code' => $q->knowledge_point, // 从本地数据库获取知识点代码
  403. ];
  404. })->toArray();
  405. } catch (\Exception $e) {
  406. \Log::error('获取试卷题目失败', [
  407. 'paper_id' => $this->selectedPaperId,
  408. 'error' => $e->getMessage(),
  409. 'trace' => $e->getTraceAsString()
  410. ]);
  411. return [
  412. [
  413. 'id' => 'error',
  414. 'question_number' => 1,
  415. 'question_bank_id' => null,
  416. 'question_type' => 'error',
  417. 'content' => '获取题目数据时发生错误:' . $e->getMessage(),
  418. 'answer' => '',
  419. 'score' => 0,
  420. 'is_error' => true
  421. ]
  422. ];
  423. }
  424. }
  425. public function updatedTeacherId($value): void
  426. {
  427. // 当教师选择变化时,清空之前选择的学生
  428. $this->studentId = null;
  429. $this->selectedPaperId = null;
  430. $this->questionGrades = [];
  431. }
  432. public function updatedStudentId($value): void
  433. {
  434. // 当学生选择变化时,清空已选试卷
  435. $this->selectedPaperId = null;
  436. $this->questionGrades = [];
  437. }
  438. public function updatedMode($value): void
  439. {
  440. // 切换模式时重置相关字段
  441. $this->uploadedImage = null;
  442. $this->selectedPaperId = null;
  443. $this->questionGrades = [];
  444. }
  445. public function submitUpload(): void
  446. {
  447. if (!$this->teacherId) {
  448. Notification::make()
  449. ->title('请选择老师')
  450. ->danger()
  451. ->send();
  452. return;
  453. }
  454. if (!$this->studentId) {
  455. Notification::make()
  456. ->title('请选择学生')
  457. ->danger()
  458. ->send();
  459. return;
  460. }
  461. // 获取表单数据
  462. $formData = $this->data;
  463. if (empty($formData['image'])) {
  464. Notification::make()
  465. ->title('请上传图片')
  466. ->danger()
  467. ->send();
  468. return;
  469. }
  470. if (empty($formData['paper_name'])) {
  471. Notification::make()
  472. ->title('请填写试卷名称')
  473. ->danger()
  474. ->send();
  475. return;
  476. }
  477. if (empty($formData['class'])) {
  478. Notification::make()
  479. ->title('请选择班级')
  480. ->danger()
  481. ->send();
  482. return;
  483. }
  484. if (empty($formData['student_name'])) {
  485. Notification::make()
  486. ->title('请填写学生姓名')
  487. ->danger()
  488. ->send();
  489. return;
  490. }
  491. $this->isUploading = true;
  492. try {
  493. // 处理图片(可能是单张或多张)
  494. $images = $formData['image'];
  495. if (!is_array($images)) {
  496. $images = [$images];
  497. }
  498. $paths = [];
  499. foreach ($images as $image) {
  500. if ($image) {
  501. $paths[] = storage_path('app/public/' . $image);
  502. }
  503. }
  504. if (empty($paths)) {
  505. throw new \Exception('图片保存失败');
  506. }
  507. $paperId = 'paper_' . time() . '_' . substr(md5(uniqid()), 0, 8);
  508. // AI分析服务调用
  509. $response = \Http::timeout(300)
  510. ->post('http://localhost:5016/analyze-exam', [
  511. 'paper_id' => $paperId,
  512. 'paper_name' => $formData['paper_name'],
  513. 'student_name' => $formData['student_name'],
  514. 'class_name' => $formData['class'],
  515. 'paper_type' => $formData['paper_type'],
  516. 'subject' => $formData['paper_subject'],
  517. 'image_files' => $paths,
  518. ]);
  519. if ($response->successful()) {
  520. $result = $response->json();
  521. $this->saveAnalysisResult($result, $paperId);
  522. $this->analysisResult = $result;
  523. Notification::make()
  524. ->title('分析完成')
  525. ->success()
  526. ->send();
  527. } else {
  528. $this->analysisError = '分析服务响应失败: ' . $response->status();
  529. Notification::make()
  530. ->title('分析失败')
  531. ->body($this->analysisError)
  532. ->error()
  533. ->send();
  534. }
  535. // 重置表单
  536. $this->teacherId = null;
  537. $this->studentId = null;
  538. $this->uploadedImage = null;
  539. $this->paperType = null;
  540. } catch (\Exception $e) {
  541. Notification::make()
  542. ->title('上传失败')
  543. ->body($e->getMessage())
  544. ->danger()
  545. ->send();
  546. } finally {
  547. $this->isUploading = false;
  548. $this->analyzing = false;
  549. }
  550. }
  551. #[On('teacherChanged')]
  552. public function updateTeacherId($teacherId)
  553. {
  554. $this->teacherId = $teacherId;
  555. $this->studentId = null;
  556. }
  557. #[On('studentChanged')]
  558. public function updateStudentId($teacherId, $studentId)
  559. {
  560. $this->studentId = $studentId;
  561. }
  562. public function removeImage(): void
  563. {
  564. $this->uploadedImage = null;
  565. }
  566. /**
  567. * 提交手动评分
  568. */
  569. public function submitManualGrading(): void
  570. {
  571. if (!$this->selectedPaperId) {
  572. Notification::make()
  573. ->title('请选择试卷')
  574. ->danger()
  575. ->send();
  576. return;
  577. }
  578. // 将 gradingData 转换为 questionGrades 格式
  579. $this->convertGradingDataToQuestionGrades();
  580. if (empty($this->questionGrades)) {
  581. Notification::make()
  582. ->title('请至少为一道题目评分')
  583. ->danger()
  584. ->send();
  585. return;
  586. }
  587. try {
  588. // 准备数据发送到 LearningAnalytics
  589. $analyticsData = [];
  590. // 获取题目详情以便查找kp_code
  591. $questionsMap = collect($this->selectedPaperQuestions)->keyBy('id');
  592. // 收集需要从API补充信息的题目ID
  593. $missingKpCodeQuestionIds = [];
  594. foreach ($this->questionGrades as $questionId => $grade) {
  595. $question = $questionsMap->get($questionId);
  596. if (!$question) {
  597. continue;
  598. }
  599. // 优先使用本地存储的 kp_code
  600. if (empty($question['kp_code'])) {
  601. $missingKpCodeQuestionIds[] = $questionId;
  602. }
  603. }
  604. // 如果有缺失 kp_code 的题目,尝试从 API 获取
  605. $apiDetailsMap = collect([]);
  606. if (!empty($missingKpCodeQuestionIds)) {
  607. $questionBankIds = collect($missingKpCodeQuestionIds)
  608. ->map(fn($qId) => $questionsMap->get($qId)['question_bank_id'] ?? null)
  609. ->filter()
  610. ->toArray();
  611. if (!empty($questionBankIds)) {
  612. $questionBankService = app(\App\Services\QuestionBankService::class);
  613. $questionsDetails = $questionBankService->getQuestionsByIds($questionBankIds);
  614. $apiDetailsMap = collect($questionsDetails['data'] ?? [])->keyBy('id');
  615. }
  616. }
  617. foreach ($this->questionGrades as $questionId => $grade) {
  618. $question = $questionsMap->get($questionId);
  619. if (!$question) {
  620. continue;
  621. }
  622. $kpCode = $question['kp_code'];
  623. // 如果本地没有,尝试从API结果中获取
  624. if (empty($kpCode)) {
  625. $detail = $apiDetailsMap->get($question['question_bank_id']);
  626. $kpCode = $detail['kp_code'] ?? $detail['knowledge_point_code'] ?? null;
  627. }
  628. // 确保 is_correct 有值(如果为 null,设置为 false)
  629. $isCorrect = $grade['is_correct'];
  630. if ($isCorrect === null) {
  631. $isCorrect = false;
  632. }
  633. $analyticsData[] = [
  634. 'question_bank_id' => $question['question_bank_id'],
  635. 'student_answer' => $grade['student_answer'] ?? '',
  636. 'is_correct' => $isCorrect,
  637. 'score' => $grade['score'] ?? 0,
  638. 'max_score' => $question['score'] ?? 0,
  639. 'kp_code' => $kpCode,
  640. 'ip_address' => '127.0.0.1', // 提供默认IP地址,避免PostgreSQL inet类型错误
  641. 'device_type' => 'web', // 提供默认设备类型
  642. 'feedback_provided' => false, // 提供默认反馈状态
  643. ];
  644. }
  645. // 调用 LearningAnalytics 服务
  646. $learningAnalyticsService = app(\App\Services\LearningAnalyticsService::class);
  647. // 步骤0: 保存学生答案到本地数据库 (重要:确保数据持久化)
  648. foreach ($this->questionGrades as $questionId => $grade) {
  649. // 确保 is_correct 是布尔值(转换字符串 'true'/'false' 为布尔值)
  650. $isCorrect = $grade['is_correct'];
  651. if ($isCorrect === 'true' || $isCorrect === true) {
  652. $isCorrect = true;
  653. } elseif ($isCorrect === 'false' || $isCorrect === false) {
  654. $isCorrect = false;
  655. }
  656. // 确保 score_obtained 是数字
  657. $score = $grade['score'];
  658. if ($score !== null) {
  659. $score = is_numeric($score) ? (float)$score : 0;
  660. }
  661. // **关键修复**:确保 is_correct 和 score 的一致性
  662. // 如果分数为满分或大于0,视为正确
  663. if ($score > 0) {
  664. $isCorrect = true;
  665. } elseif ($score === 0) {
  666. $isCorrect = false;
  667. }
  668. \App\Models\PaperQuestion::where('id', $questionId)->update([
  669. 'student_answer' => $grade['student_answer'] ?? '',
  670. 'is_correct' => $isCorrect,
  671. 'score_obtained' => $score ?? 0,
  672. ]);
  673. }
  674. \Log::info('学生答案已保存到数据库', [
  675. 'student_id' => $this->studentId,
  676. 'paper_id' => $this->selectedPaperId,
  677. 'updated_count' => count($this->questionGrades)
  678. ]);
  679. // 步骤1: 保存答题记录到 LearningAnalytics
  680. \Log::info('准备调用submitBatchAttempts API', [
  681. 'student_id' => $this->studentId,
  682. 'paper_id' => $this->selectedPaperId,
  683. 'analytics_data_sample' => array_slice($analyticsData, 0, 2) // 记录前2题的数据作为样本
  684. ]);
  685. $result = $learningAnalyticsService->submitBatchAttempts($this->studentId, [
  686. 'paper_id' => $this->selectedPaperId,
  687. 'answers' => $analyticsData,
  688. ]);
  689. // 检查API返回结果
  690. if (is_array($result) && isset($result['error']) && $result['error']) {
  691. throw new \Exception($result['message'] ?? 'API调用失败');
  692. }
  693. if ($result === null || (is_array($result) && empty($result))) {
  694. throw new \Exception('API返回空数据');
  695. }
  696. \Log::info('答题记录已保存到学习分析服务', [
  697. 'student_id' => $this->studentId,
  698. 'paper_id' => $this->selectedPaperId,
  699. 'count' => count($analyticsData)
  700. ]);
  701. // 步骤2: 触发 AI 分析(包含掌握度更新和学习报告生成)
  702. try {
  703. $paper = \App\Models\Paper::find($this->selectedPaperId);
  704. // 构造 AI 分析请求数据
  705. $analysisQuestions = [];
  706. foreach ($this->questionGrades as $questionId => $grade) {
  707. $question = $questionsMap->get($questionId);
  708. if (!$question) {
  709. continue;
  710. }
  711. $kpCode = $question['kp_code'];
  712. if (empty($kpCode)) {
  713. $detail = $apiDetailsMap->get($question['question_bank_id']);
  714. $kpCode = $detail['kp_code'] ?? $detail['knowledge_point_code'] ?? null;
  715. }
  716. $analysisQuestions[] = [
  717. 'question_id' => $question['question_bank_id'],
  718. 'question_number' => (string)$question['question_number'],
  719. 'question_text' => $question['content'] ?? '',
  720. 'student_answer' => $grade['student_answer'] ?? '',
  721. 'correct_answer' => $question['answer'] ?? '',
  722. 'kp_code' => $kpCode,
  723. 'score_value' => $grade['score'] ?? 0,
  724. 'max_score' => $question['score'],
  725. 'is_correct' => $grade['is_correct'] ?? false,
  726. 'teacher_validated' => true, // 手动评分即为教师验证
  727. 'ocr_confidence' => 1.0, // 手动评分置信度为1
  728. ];
  729. }
  730. $analysisData = [
  731. 'exam_id' => $this->selectedPaperId,
  732. 'student_id' => $this->studentId,
  733. 'ocr_record_id' => 0, // 系统生成卷子没有OCR记录ID
  734. 'paper_id' => $this->selectedPaperId,
  735. 'teacher_name' => auth()->user()->name ?? 'Teacher',
  736. 'analysis_type' => 'mastery',
  737. 'questions' => $analysisQuestions,
  738. ];
  739. // 调用统一的 AI 分析接口
  740. \Log::info('准备调用submitOCRAnalysis API', [
  741. 'paper_id' => $this->selectedPaperId,
  742. 'student_id' => $this->studentId,
  743. 'analysis_data_sample' => [
  744. 'question_count' => count($analysisQuestions),
  745. 'first_question' => $analysisQuestions[0] ?? null
  746. ]
  747. ]);
  748. $analysisResult = $learningAnalyticsService->submitOCRAnalysis($analysisData);
  749. \Log::info('AI分析已触发', [
  750. 'paper_id' => $this->selectedPaperId,
  751. 'student_id' => $this->studentId,
  752. 'analysis_result_keys' => is_array($analysisResult) ? array_keys($analysisResult) : 'not_array',
  753. 'analysis_result' => $analysisResult
  754. ]);
  755. // 保存 analysis_id 到 Paper 表
  756. if (isset($analysisResult['analysis_id'])) {
  757. \App\Models\Paper::where('paper_id', $this->selectedPaperId)->update([
  758. 'analysis_id' => $analysisResult['analysis_id'],
  759. ]);
  760. \Log::info('已保存 analysis_id', [
  761. 'paper_id' => $this->selectedPaperId,
  762. 'analysis_id' => $analysisResult['analysis_id']
  763. ]);
  764. }
  765. } catch (\Exception $analysisError) {
  766. // AI 分析失败不影响主流程
  767. \Log::warning('触发AI分析失败', [
  768. 'paper_id' => $this->selectedPaperId,
  769. 'error' => $analysisError->getMessage()
  770. ]);
  771. }
  772. // 更新Paper表状态为已完成评分
  773. \App\Models\Paper::where('paper_id', $this->selectedPaperId)->update([
  774. 'status' => 'completed',
  775. 'completed_at' => now(),
  776. ]);
  777. Notification::make()
  778. ->title('提交成功')
  779. ->body('评分已提交,AI分析正在进行中')
  780. ->success()
  781. ->send();
  782. // 刷新最近记录列表
  783. unset($this->recentRecords);
  784. // 重置表单
  785. $this->selectedPaperId = null;
  786. $this->questionGrades = [];
  787. } catch (\Exception $e) {
  788. \Log::error('提交手动评分失败', [
  789. 'error' => $e->getMessage(),
  790. 'student_id' => $this->studentId,
  791. 'paper_id' => $this->selectedPaperId,
  792. ]);
  793. Notification::make()
  794. ->title('提交失败')
  795. ->body($e->getMessage())
  796. ->danger()
  797. ->send();
  798. }
  799. }
  800. /**
  801. * 将 gradingData 转换为 questionGrades 格式
  802. * gradingData: 索引数组 [{is_correct: bool, score: float}]
  803. * questionGrades: 题目ID为键的数组 [questionId => {is_correct: bool, score: float, student_answer: string}]
  804. */
  805. private function convertGradingDataToQuestionGrades(): void
  806. {
  807. $this->questionGrades = [];
  808. // 遍历 questions 数组(包含题目信息)
  809. foreach ($this->questions as $index => $question) {
  810. // 获取对应索引的 gradingData
  811. $grading = $this->gradingData[$index] ?? null;
  812. // 只有当 grading 不为空且有评分数据时才添加
  813. if ($grading && (
  814. $grading['is_correct'] !== null ||
  815. ($grading['score'] ?? null) !== null
  816. )) {
  817. $questionId = $question['id'];
  818. // 处理 is_correct 值(字符串 'true'/'false' 或布尔值)
  819. $isCorrect = $grading['is_correct'];
  820. if ($isCorrect === 'true') {
  821. $isCorrect = true;
  822. } elseif ($isCorrect === 'false') {
  823. $isCorrect = false;
  824. }
  825. // 处理 score 值
  826. $score = $grading['score'];
  827. if ($score !== null && $score !== '') {
  828. $score = is_numeric($score) ? (float)$score : null;
  829. }
  830. // **关键修复**:根据题型处理缺失的字段
  831. if ($question['question_type'] === 'choice') {
  832. // 选择题:只有 is_correct,需要自动计算分数
  833. if ($isCorrect === true) {
  834. $score = $question['score'] ?? 0; // 正确给满分
  835. } elseif ($isCorrect === false) {
  836. $score = 0; // 错误给0分
  837. }
  838. } else {
  839. // 填空/解答题:只有 score,需要自动计算 is_correct
  840. if ($score !== null) {
  841. $isCorrect = ($score >= ($question['score'] ?? 0)); // 得分>=满分视为正确
  842. }
  843. }
  844. // 获取学生答案(优先使用 gradingData 中的值,如果没有则使用题目中的值)
  845. $studentAnswer = $grading['student_answer'] ?? $question['student_answer'] ?? '';
  846. // 对于选择题,如果学生答案为空,基于评分推断
  847. if (empty($studentAnswer) && $question['question_type'] === 'choice') {
  848. if ($isCorrect === true) {
  849. // 如果选"正确",学生答案就是正确答案
  850. $studentAnswer = $question['correct_answer'] ?? '正确答案';
  851. } elseif ($isCorrect === false) {
  852. // 如果选"错误",学生答案可以为空或者设置为特殊标记
  853. $studentAnswer = '错误答案';
  854. }
  855. }
  856. // 转换格式
  857. $this->questionGrades[$questionId] = [
  858. 'is_correct' => $isCorrect,
  859. 'score' => $score,
  860. 'student_answer' => $studentAnswer,
  861. ];
  862. }
  863. }
  864. \Log::info('转换评分数据', [
  865. 'grading_data_count' => count(array_filter($this->gradingData ?? [])),
  866. 'question_grades_count' => count($this->questionGrades),
  867. 'questions_count' => count($this->questions ?? []),
  868. 'sample_question_grades' => array_slice($this->questionGrades, 0, 2, true),
  869. ]);
  870. }
  871. #[Computed]
  872. public function gradingProgress(): string
  873. {
  874. $gradedCount = count(array_filter($this->gradingData ?? []));
  875. $totalCount = count($this->questions ?? []);
  876. return "已评分:{$gradedCount}/{$totalCount}题";
  877. }
  878. public function startAnalysis(): void
  879. {
  880. $this->analyzing = true;
  881. $this->analysisError = null;
  882. try {
  883. $this->submitUpload();
  884. } catch (\Exception $e) {
  885. $this->analysisError = $e->getMessage();
  886. $this->analyzing = false;
  887. }
  888. }
  889. public function saveGrading(): void
  890. {
  891. $this->submitManualGrading();
  892. }
  893. public function updatedSelectedPaperId($value): void
  894. {
  895. if (empty($value)) {
  896. $this->questions = [];
  897. $this->gradingData = [];
  898. $this->showGrading = false;
  899. return;
  900. }
  901. // 加载试卷信息和题目
  902. $this->loadPaperForGrading($value);
  903. }
  904. public function loadPaperForGrading($paperId): void
  905. {
  906. try {
  907. $paper = \App\Models\Paper::where('paper_id', $paperId)->first();
  908. if (!$paper) {
  909. Notification::make()
  910. ->title('试卷不存在')
  911. ->danger()
  912. ->send();
  913. return;
  914. }
  915. // 设置试卷信息
  916. $this->paperName = $paper->paper_name;
  917. $this->paperClass = $paper->difficulty_category ?? '未设置';
  918. $this->paperStudent = $paper->student_id;
  919. $this->paperDate = $paper->created_at->format('Y-m-d H:i');
  920. // 加载题目
  921. $paperWithQuestions = \App\Models\Paper::with(['questions' => function($query) {
  922. $query->orderBy('question_number');
  923. }])->where('paper_id', $paperId)->first();
  924. $questions = $paperWithQuestions ? $paperWithQuestions->questions : collect([]);
  925. // 如果没有正确答案,先尝试从题库API获取
  926. $apiDetailsMap = new \Illuminate\Support\Collection();
  927. if (!$questions->isEmpty()) {
  928. $questionBankIds = $questions->where('question_bank_id', '!=', null)->pluck('question_bank_id')->unique()->toArray();
  929. if (!empty($questionBankIds)) {
  930. try {
  931. $questionBankService = app(\App\Services\QuestionBankService::class);
  932. $apiResponse = $questionBankService->getQuestionsByIds($questionBankIds);
  933. if (!empty($apiResponse['data'])) {
  934. foreach ($apiResponse['data'] as $detail) {
  935. $apiDetailsMap->put($detail['id'], $detail);
  936. }
  937. \Log::info('成功从题库API获取题目详情', [
  938. 'count' => count($apiResponse['data']),
  939. 'ids' => array_keys($apiResponse['data'])
  940. ]);
  941. }
  942. } catch (\Exception $e) {
  943. \Log::warning('获取题库详情失败', ['error' => $e->getMessage()]);
  944. }
  945. }
  946. }
  947. if ($questions->isEmpty()) {
  948. $this->questions = [
  949. [
  950. 'id' => 'no_questions',
  951. 'question_number' => 1,
  952. 'question_type' => 'info',
  953. 'content' => '该试卷暂无题目数据',
  954. 'answer' => '',
  955. 'score' => 0,
  956. 'is_empty' => true
  957. ]
  958. ];
  959. } else {
  960. $this->questions = $questions->map(function($question, $index) use ($apiDetailsMap) {
  961. // 从 API 获取正确答案(优先使用 API 数据)
  962. $correctAnswer = $question->correct_answer;
  963. if (empty($correctAnswer) && $question->question_bank_id && $apiDetailsMap->has($question->question_bank_id)) {
  964. $detail = $apiDetailsMap->get($question->question_bank_id);
  965. $correctAnswer = $detail['answer'] ?? $detail['correct_answer'] ?? '';
  966. }
  967. return [
  968. 'id' => $question->id,
  969. 'question_number' => $question->question_number,
  970. 'question_type' => $question->question_type,
  971. 'question_text' => $question->question_text,
  972. 'content' => $question->question_text,
  973. 'options' => json_decode($question->options, true) ?: [],
  974. 'answer' => $correctAnswer,
  975. 'correct_answer' => $correctAnswer,
  976. 'student_answer' => '', // 学生答案暂不显示,等后续完善
  977. 'score' => $question->score,
  978. 'max_score' => $question->score,
  979. 'question_bank_id' => $question->question_bank_id,
  980. 'is_empty' => false
  981. ];
  982. })->toArray();
  983. }
  984. // 初始化评分数据
  985. $this->gradingData = array_fill(0, count($this->questions), ['score' => null, 'is_correct' => null, 'comment' => '']);
  986. $this->showGrading = true;
  987. } catch (\Exception $e) {
  988. \Log::error('加载试卷题目失败', [
  989. 'paper_id' => $paperId,
  990. 'error' => $e->getMessage()
  991. ]);
  992. Notification::make()
  993. ->title('加载失败')
  994. ->body($e->getMessage())
  995. ->danger()
  996. ->send();
  997. }
  998. }
  999. private function saveAnalysisResult(array $result, string $paperId): void
  1000. {
  1001. try {
  1002. \DB::beginTransaction();
  1003. // 保存试卷基本信息
  1004. $examPaper = \App\Models\Paper::create([
  1005. 'paper_id' => $paperId,
  1006. 'paper_name' => $result['paper_name'] ?? '未命名试卷',
  1007. 'student_id' => $this->studentId,
  1008. 'teacher_id' => $this->teacherId,
  1009. 'paper_type' => $result['paper_type'] ?? 'quiz',
  1010. 'question_count' => count($result['questions'] ?? []),
  1011. 'total_score' => $result['total_score'] ?? 0,
  1012. 'status' => 'completed',
  1013. ]);
  1014. // 保存题目信息
  1015. foreach ($result['questions'] ?? [] as $index => $questionData) {
  1016. \App\Models\PaperQuestion::create([
  1017. 'paper_id' => $paperId,
  1018. 'question_number' => $index + 1,
  1019. 'question_text' => $questionData['question_text'] ?? '',
  1020. 'question_type' => $questionData['question_type'] ?? 'choice',
  1021. 'options' => json_encode($questionData['options'] ?? []),
  1022. 'correct_answer' => $questionData['correct_answer'] ?? '',
  1023. 'score' => $questionData['score'] ?? 1,
  1024. ]);
  1025. }
  1026. \DB::commit();
  1027. } catch (\Exception $e) {
  1028. \DB::rollBack();
  1029. \Log::error('保存分析结果失败: ' . $e->getMessage());
  1030. }
  1031. }
  1032. /**
  1033. * 查看记录详情 - 使用页面跳转
  1034. */
  1035. public function getViewRecordUrl(string $type, string $paperId, string $recordId, string $studentId): string
  1036. {
  1037. // 返回ExamAnalysis详情页面URL
  1038. if (in_array($type, ['graded_paper', 'generated'])) {
  1039. // 系统生成或已评分试卷,使用paperId
  1040. return '/admin/exam-analysis?paperId=' . $paperId . '&studentId=' . $studentId;
  1041. } elseif ($type === 'ocr_upload') {
  1042. // OCR上传记录,也跳转到详情页
  1043. return '/admin/exam-analysis?recordId=' . $recordId . '&studentId=' . $studentId;
  1044. }
  1045. return '#';
  1046. }
  1047. }