MistakeBook.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. <?php
  2. namespace App\Filament\Pages;
  3. use App\Filament\Traits\HasUserRole;
  4. use App\Models\Student;
  5. use App\Services\KnowledgeGraphService;
  6. use App\Services\KnowledgeServiceApi;
  7. use App\Services\MistakeBookService;
  8. use App\Services\QuestionBankService;
  9. use BackedEnum;
  10. use Filament\Pages\Page;
  11. use Illuminate\Http\Request;
  12. use Illuminate\Support\Arr;
  13. use Illuminate\Support\Facades\Log;
  14. use UnitEnum;
  15. use Livewire\Attributes\On;
  16. use Livewire\Attributes\Computed;
  17. use App\Models\Teacher;
  18. class MistakeBook extends Page
  19. {
  20. use HasUserRole;
  21. protected static ?string $title = '错题本';
  22. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-bookmark';
  23. protected static ?string $navigationLabel = '错题本';
  24. protected static string|UnitEnum|null $navigationGroup = '操作';
  25. protected static ?int $navigationSort = 5;
  26. protected static ?string $slug = 'mistake-book';
  27. protected string $view = 'filament.pages.mistake-book';
  28. public string $teacherId = '';
  29. public string $studentId = '';
  30. public array $filters = [
  31. 'kp_ids' => [],
  32. 'skill_ids' => [],
  33. 'error_types' => [],
  34. 'time_range' => 'last_30',
  35. 'start_date' => null,
  36. 'end_date' => null,
  37. 'sort_by' => 'created_at_desc',
  38. 'correct_filter' => 'incorrect', // 默认只显示错误题目
  39. 'filter' => [],
  40. ];
  41. public array $filterOptions = [
  42. 'knowledge_points' => [],
  43. 'skills' => [],
  44. ];
  45. public array $mistakes = [];
  46. public array $patterns = [];
  47. public array $summary = [];
  48. public array $recommendations = [];
  49. public array $relatedQuestions = [];
  50. public array $selectedMistakeIds = [];
  51. public bool $isLoading = false;
  52. public string $errorMessage = '';
  53. public string $actionMessage = '';
  54. public string $actionMessageType = 'success';
  55. // 分页
  56. public int $page = 1;
  57. public int $perPage = 10;
  58. public int $total = 0;
  59. public function mount(Request $request): void
  60. {
  61. // 初始化用户角色检查
  62. $this->initializeUserRole();
  63. // 如果是老师,自动选择当前老师
  64. if ($this->isTeacher) {
  65. $teacherId = $this->getCurrentTeacherId();
  66. if ($teacherId) {
  67. $this->teacherId = $teacherId;
  68. }
  69. } else {
  70. $this->teacherId = (string) ($request->input('teacher_id') ?? '');
  71. }
  72. $this->studentId = (string) ($request->input('student_id') ?? '');
  73. $this->filters['time_range'] = (string) ($request->input('range') ?? 'last_30');
  74. if ($this->studentId && empty($this->teacherId)) {
  75. $student = Student::find($this->studentId);
  76. if ($student && $student->teacher_id) {
  77. $this->teacherId = (string) $student->teacher_id;
  78. }
  79. }
  80. $this->loadFilterOptions();
  81. if ($this->studentId) {
  82. $this->loadMistakeData();
  83. }
  84. }
  85. public function updatedStudentId(): void
  86. {
  87. if ($this->studentId) {
  88. $this->loadMistakeData();
  89. } else {
  90. $this->resetPageState();
  91. }
  92. }
  93. public function loadMistakeData(): void
  94. {
  95. if (empty($this->studentId)) {
  96. $this->errorMessage = '请先选择学生';
  97. return;
  98. }
  99. $this->isLoading = true;
  100. $this->errorMessage = '';
  101. $this->actionMessage = '';
  102. try {
  103. $service = app(MistakeBookService::class);
  104. // 处理筛选参数
  105. $params = [
  106. 'student_id' => $this->studentId,
  107. 'page' => $this->page,
  108. 'per_page' => $this->perPage,
  109. ];
  110. // 基础筛选
  111. if (!empty($this->filters['kp_ids'])) {
  112. $params['kp_ids'] = $this->filters['kp_ids'];
  113. }
  114. if (!empty($this->filters['skill_ids'])) {
  115. $params['skill_ids'] = $this->filters['skill_ids'];
  116. }
  117. if (!empty($this->filters['error_types'])) {
  118. $params['error_types'] = $this->filters['error_types'];
  119. }
  120. if (isset($this->filters['time_range']) && $this->filters['time_range'] !== 'all') {
  121. $params['time_range'] = $this->filters['time_range'];
  122. }
  123. if (!empty($this->filters['start_date'])) {
  124. $params['start_date'] = $this->filters['start_date'];
  125. }
  126. if (!empty($this->filters['end_date'])) {
  127. $params['end_date'] = $this->filters['end_date'];
  128. }
  129. if (!empty($this->filters['sort_by'])) {
  130. $params['sort_by'] = $this->filters['sort_by'];
  131. }
  132. // 正确与否筛选
  133. if (isset($this->filters['correct_filter']) && $this->filters['correct_filter'] !== 'all') {
  134. if ($this->filters['correct_filter'] === 'correct') {
  135. $params['correct_only'] = true;
  136. } elseif ($this->filters['correct_filter'] === 'incorrect') {
  137. $params['incorrect_only'] = true;
  138. }
  139. }
  140. // 状态筛选
  141. if (!empty($this->filters['filter'])) {
  142. if (in_array('unreviewed', $this->filters['filter'])) {
  143. $params['unreviewed_only'] = true;
  144. }
  145. if (in_array('favorite', $this->filters['filter'])) {
  146. $params['favorite_only'] = true;
  147. }
  148. }
  149. $list = $service->listMistakes($params);
  150. $this->mistakes = $list['data'] ?? [];
  151. $this->total = $list['meta']['total'] ?? 0;
  152. $this->summary = $service->summarize($this->studentId);
  153. $this->patterns = $service->getMistakePatterns($this->studentId);
  154. // 清理无效的选中项
  155. $validIds = collect($this->mistakes)->pluck('id')->filter()->all();
  156. $this->selectedMistakeIds = array_values(
  157. array_intersect($this->selectedMistakeIds, $validIds)
  158. );
  159. } catch (\Throwable $e) {
  160. $this->errorMessage = '加载错题本数据失败:' . $e->getMessage();
  161. Log::error('Load mistake book failed', [
  162. 'student_id' => $this->studentId,
  163. 'error' => $e->getMessage(),
  164. ]);
  165. } finally {
  166. $this->isLoading = false;
  167. }
  168. }
  169. public function gotoPage(int $page): void
  170. {
  171. $this->page = max(1, $page);
  172. $this->loadMistakeData();
  173. }
  174. public function nextPage(): void
  175. {
  176. $maxPage = (int) ceil($this->total / $this->perPage);
  177. if ($this->page < $maxPage) {
  178. $this->page++;
  179. $this->loadMistakeData();
  180. }
  181. }
  182. public function prevPage(): void
  183. {
  184. if ($this->page > 1) {
  185. $this->page--;
  186. $this->loadMistakeData();
  187. }
  188. }
  189. public function refreshPatterns(): void
  190. {
  191. if (!$this->studentId) {
  192. return;
  193. }
  194. try {
  195. $service = app(MistakeBookService::class);
  196. $this->patterns = $service->getMistakePatterns($this->studentId);
  197. } catch (\Throwable $e) {
  198. Log::error('Refresh mistake patterns failed', [
  199. 'student_id' => $this->studentId,
  200. 'error' => $e->getMessage(),
  201. ]);
  202. }
  203. }
  204. public function toggleFavorite(string $mistakeId): void
  205. {
  206. $service = app(MistakeBookService::class);
  207. $current = $this->findMistakeById($mistakeId);
  208. $willFavorite = !($current['favorite'] ?? false);
  209. if ($service->toggleFavorite($mistakeId, $willFavorite)) {
  210. $this->updateMistakeField($mistakeId, 'favorite', $willFavorite);
  211. $this->notify('已更新收藏状态');
  212. } else {
  213. $this->notify('收藏操作失败,请稍后再试', 'danger');
  214. }
  215. }
  216. public function markReviewed(string $mistakeId): void
  217. {
  218. $service = app(MistakeBookService::class);
  219. if ($service->markReviewed($mistakeId)) {
  220. $this->updateMistakeField($mistakeId, 'reviewed', true);
  221. $this->notify('已标记为已复习');
  222. } else {
  223. $this->notify('标记失败,请稍后再试', 'danger');
  224. }
  225. }
  226. public function addToRetryList(string $mistakeId): void
  227. {
  228. $service = app(MistakeBookService::class);
  229. if ($service->addToRetryList($mistakeId)) {
  230. $this->notify('已加入重练清单');
  231. } else {
  232. $this->notify('加入清单失败,请稍后再试', 'danger');
  233. }
  234. }
  235. public function loadRelatedQuestions(string $mistakeId): void
  236. {
  237. $mistake = $this->findMistakeById($mistakeId);
  238. if (empty($mistake)) {
  239. return;
  240. }
  241. $questionBank = app(QuestionBankService::class);
  242. $kpIds = Arr::wrap($mistake['kp_ids'] ?? []);
  243. $skills = Arr::wrap($mistake['skill_ids'] ?? $mistake['skills'] ?? []);
  244. $response = $questionBank->filterQuestions(array_filter([
  245. 'kp_codes' => !empty($kpIds) ? implode(',', $kpIds) : null,
  246. 'skills' => !empty($skills) ? implode(',', $skills) : null,
  247. 'limit' => 5,
  248. ]));
  249. $this->relatedQuestions[$mistakeId] = $response['data'] ?? [];
  250. }
  251. public function toggleSelection(string $mistakeId): void
  252. {
  253. if (in_array($mistakeId, $this->selectedMistakeIds, true)) {
  254. $this->selectedMistakeIds = array_values(array_diff($this->selectedMistakeIds, [$mistakeId]));
  255. } else {
  256. $this->selectedMistakeIds[] = $mistakeId;
  257. }
  258. }
  259. public function generatePracticeFromSelection(): void
  260. {
  261. if (empty($this->selectedMistakeIds)) {
  262. $this->notify('请先选择至少一道错题', 'warning');
  263. return;
  264. }
  265. $selected = array_filter($this->mistakes, fn ($item) => in_array($item['id'] ?? '', $this->selectedMistakeIds, true));
  266. $kpIds = collect($selected)
  267. ->pluck('kp_ids')
  268. ->flatten()
  269. ->filter()
  270. ->unique()
  271. ->values()
  272. ->all();
  273. $skillIds = collect($selected)
  274. ->pluck('skill_ids')
  275. ->flatten()
  276. ->filter()
  277. ->unique()
  278. ->values()
  279. ->all();
  280. $service = app(MistakeBookService::class);
  281. $result = $service->recommendPractice($this->studentId, $kpIds, $skillIds);
  282. $this->recommendations = $result['data'] ?? ($result['questions'] ?? []);
  283. if (!empty($this->recommendations)) {
  284. $this->notify('已生成重练题单');
  285. } else {
  286. $this->notify('未能生成题单,请稍后再试', 'warning');
  287. }
  288. }
  289. public function batchMarkReviewed(): void
  290. {
  291. if (empty($this->selectedMistakeIds)) {
  292. $this->notify('请先选择至少一道错题', 'warning');
  293. return;
  294. }
  295. $service = app(MistakeBookService::class);
  296. $successCount = 0;
  297. foreach ($this->selectedMistakeIds as $mistakeId) {
  298. if ($service->markReviewed($mistakeId)) {
  299. $this->updateMistakeField($mistakeId, 'reviewed', true);
  300. $successCount++;
  301. }
  302. }
  303. if ($successCount > 0) {
  304. $this->selectedMistakeIds = [];
  305. $this->notify("已标记 {$successCount} 道题为已复习");
  306. } else {
  307. $this->notify('操作失败,请稍后再试', 'danger');
  308. }
  309. }
  310. public function startQuickReview(): void
  311. {
  312. if (empty($this->mistakes)) {
  313. $this->notify('没有可复习的错题', 'warning');
  314. return;
  315. }
  316. // 选取前5题进行快速复习
  317. $reviewIds = collect($this->mistakes)
  318. ->take(5)
  319. ->pluck('id')
  320. ->filter()
  321. ->values()
  322. ->all();
  323. // 自动选中这些题
  324. $this->selectedMistakeIds = $reviewIds;
  325. $this->notify('已选择前5题进行快速复习');
  326. }
  327. public function applyFilters(): void
  328. {
  329. $this->page = 1; // 重置到第一页
  330. $this->loadMistakeData();
  331. }
  332. public function clearFilters(): void
  333. {
  334. $this->filters = [
  335. 'kp_ids' => [],
  336. 'skill_ids' => [],
  337. 'error_types' => [],
  338. 'time_range' => 'last_30',
  339. 'start_date' => null,
  340. 'end_date' => null,
  341. 'sort_by' => 'created_at_desc',
  342. 'correct_filter' => 'incorrect',
  343. 'filter' => [],
  344. ];
  345. $this->page = 1;
  346. $this->loadMistakeData();
  347. }
  348. public function resetFilters(): void
  349. {
  350. $this->filters = [
  351. 'kp_ids' => [],
  352. 'skill_ids' => [],
  353. 'error_types' => [],
  354. 'time_range' => 'last_30',
  355. 'start_date' => null,
  356. 'end_date' => null,
  357. 'sort_by' => 'created_at_desc',
  358. 'correct_filter' => 'incorrect',
  359. 'filter' => [],
  360. ];
  361. $this->page = 1;
  362. $this->loadMistakeData();
  363. }
  364. public function toggleFilter(string $type, string $value): void
  365. {
  366. $current = $this->filters[$type] ?? [];
  367. if (in_array($value, $current)) {
  368. // 移除
  369. $this->filters[$type] = array_values(array_diff($current, [$value]));
  370. } else {
  371. // 添加
  372. $this->filters[$type][] = $value;
  373. }
  374. $this->applyFilters();
  375. }
  376. public function clearCustomRange(): void
  377. {
  378. $this->filters['start_date'] = null;
  379. $this->filters['end_date'] = null;
  380. }
  381. #[Computed]
  382. public function teachers(): array
  383. {
  384. try {
  385. $query = Teacher::query()
  386. ->leftJoin('users as u', 'teachers.teacher_id', '=', 'u.user_id')
  387. ->select(
  388. 'teachers.teacher_id',
  389. 'teachers.name',
  390. 'teachers.subject',
  391. 'u.username',
  392. 'u.email'
  393. );
  394. // 如果是老师,只返回自己
  395. if ($this->isTeacher) {
  396. $teacherId = $this->getCurrentTeacherId();
  397. if ($teacherId) {
  398. $query->where('teachers.teacher_id', $teacherId);
  399. }
  400. }
  401. $teachers = $query->orderBy('teachers.name')->get();
  402. $teacherIds = $teachers->pluck('teacher_id')->toArray();
  403. $missingTeacherIds = Student::query()
  404. ->distinct()
  405. ->whereNotIn('teacher_id', $teacherIds)
  406. ->pluck('teacher_id')
  407. ->toArray();
  408. $teachersArray = $teachers->all();
  409. if (!empty($missingTeacherIds)) {
  410. foreach ($missingTeacherIds as $missingId) {
  411. $teachersArray[] = (object) [
  412. 'teacher_id' => $missingId,
  413. 'name' => '未知老师 (' . $missingId . ')',
  414. 'subject' => '未知',
  415. 'username' => null,
  416. 'email' => null
  417. ];
  418. }
  419. usort($teachersArray, function($a, $b) {
  420. return strcmp($a->name, $b->name);
  421. });
  422. }
  423. return $teachersArray;
  424. } catch (\Exception $e) {
  425. Log::error('加载老师列表失败', [
  426. 'error' => $e->getMessage()
  427. ]);
  428. return [];
  429. }
  430. }
  431. #[Computed]
  432. public function students(): array
  433. {
  434. if (empty($this->teacherId)) {
  435. return [];
  436. }
  437. try {
  438. return Student::query()
  439. ->leftJoin('users as u', 'students.student_id', '=', 'u.user_id')
  440. ->where('students.teacher_id', $this->teacherId)
  441. ->select(
  442. 'students.student_id',
  443. 'students.name',
  444. 'students.grade',
  445. 'students.class_name',
  446. 'u.username',
  447. 'u.email'
  448. )
  449. ->orderBy('students.grade')
  450. ->orderBy('students.class_name')
  451. ->orderBy('students.name')
  452. ->get()
  453. ->all();
  454. } catch (\Exception $e) {
  455. Log::error('加载学生列表失败', [
  456. 'teacher_id' => $this->teacherId,
  457. 'error' => $e->getMessage()
  458. ]);
  459. return [];
  460. }
  461. }
  462. public function getStudents(): array
  463. {
  464. return Student::query()
  465. ->select(['student_id', 'name', 'grade', 'class_name'])
  466. ->orderBy('grade')
  467. ->orderBy('class_name')
  468. ->orderBy('name')
  469. ->get()
  470. ->toArray();
  471. }
  472. #[On('teacherChanged')]
  473. public function onTeacherChanged(string $teacherId): void
  474. {
  475. $this->teacherId = $teacherId;
  476. $this->studentId = '';
  477. $this->resetPageState();
  478. }
  479. #[On('studentChanged')]
  480. public function onStudentChanged(?string $teacherId, ?string $studentId): void
  481. {
  482. $this->teacherId = (string) ($teacherId ?? '');
  483. $this->studentId = (string) ($studentId ?? '');
  484. if ($this->studentId) {
  485. $this->loadMistakeData();
  486. } else {
  487. $this->resetPageState();
  488. }
  489. }
  490. protected function loadFilterOptions(): void
  491. {
  492. try {
  493. $knowledgeService = app(KnowledgeServiceApi::class);
  494. $knowledge = $knowledgeService->listKnowledgePoints(150);
  495. $this->filterOptions['knowledge_points'] = $knowledge
  496. ->map(function ($item) {
  497. $code = $item['kp_code'] ?? $item['code'] ?? null;
  498. if (!$code) {
  499. return null;
  500. }
  501. return [
  502. 'code' => $code,
  503. 'name' => $item['cn_name'] ?? $item['name'] ?? $code,
  504. ];
  505. })
  506. ->filter()
  507. ->take(200)
  508. ->values()
  509. ->toArray();
  510. $skills = $knowledgeService->listSkills(null, 200);
  511. $this->filterOptions['skills'] = $skills
  512. ->map(function ($item) {
  513. return [
  514. 'id' => $item['skill_id'] ?? $item['id'] ?? ($item['code'] ?? ''),
  515. 'name' => $item['name'] ?? $item['skill_name'] ?? ($item['code'] ?? ''),
  516. 'kp_code' => $item['kp_code'] ?? $item['knowledge_point_code'] ?? null,
  517. ];
  518. })
  519. ->filter(fn ($item) => filled($item['id']))
  520. ->values()
  521. ->toArray();
  522. } catch (\Throwable $e) {
  523. Log::error('Load filter options failed', [
  524. 'error' => $e->getMessage(),
  525. ]);
  526. $this->filterOptions = ['knowledge_points' => [], 'skills' => []];
  527. }
  528. }
  529. protected function updateMistakeField(string $mistakeId, string $field, $value): void
  530. {
  531. foreach ($this->mistakes as &$mistake) {
  532. if (($mistake['id'] ?? null) === $mistakeId) {
  533. $mistake[$field] = $value;
  534. break;
  535. }
  536. }
  537. }
  538. protected function findMistakeById(string $mistakeId): array
  539. {
  540. foreach ($this->mistakes as $mistake) {
  541. if (($mistake['id'] ?? null) === $mistakeId) {
  542. return $mistake;
  543. }
  544. }
  545. return [];
  546. }
  547. protected function resetPageState(): void
  548. {
  549. $this->mistakes = [];
  550. $this->patterns = [];
  551. $this->summary = [];
  552. $this->selectedMistakeIds = [];
  553. $this->recommendations = [];
  554. $this->relatedQuestions = [];
  555. $this->actionMessage = '';
  556. $this->errorMessage = '';
  557. }
  558. #[Computed(cache: true, key: 'kp-options')]
  559. public function knowledgePointOptions(): array
  560. {
  561. try {
  562. $service = app(KnowledgeGraphService::class);
  563. $kps = $service->listKnowledgePoints(1, 1000);
  564. $options = [];
  565. foreach ($kps['data'] ?? [] as $kp) {
  566. $code = $kp['kp_code'] ?? $kp['id'];
  567. $name = $kp['cn_name'] ?? $kp['name'] ?? $code;
  568. $options[$code] = $name;
  569. }
  570. return $options;
  571. } catch (\Throwable $e) {
  572. Log::error('Failed to load knowledge points: ' . $e->getMessage());
  573. return [];
  574. }
  575. }
  576. protected function notify(string $message, string $type = 'success'): void
  577. {
  578. $this->actionMessage = $message;
  579. $this->actionMessageType = $type;
  580. }
  581. }