MistakeBookService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. <?php
  2. namespace App\Services;
  3. use App\Models\MistakeRecord;
  4. use App\Models\Student;
  5. use App\Models\Teacher;
  6. use Illuminate\Support\Arr;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\Log;
  9. use Illuminate\Support\Facades\Http;
  10. class MistakeBookService
  11. {
  12. protected string $learningAnalyticsBase;
  13. protected int $timeout;
  14. // 缓存时间(秒)
  15. const CACHE_TTL_LIST = 300; // 5分钟
  16. const CACHE_TTL_SUMMARY = 600; // 10分钟
  17. const CACHE_TTL_PATTERNS = 1800; // 30分钟
  18. public function __construct(
  19. ?string $learningAnalyticsBase = null,
  20. ?int $timeout = null
  21. ) {
  22. // 已迁移到本地,不再使用LearningAnalytics
  23. $this->learningAnalyticsBase = '';
  24. $this->timeout = 20;
  25. }
  26. /**
  27. * 新增错题
  28. */
  29. public function createMistake(array $payload): array
  30. {
  31. $studentId = $payload['student_id'] ?? null;
  32. $questionId = $payload['question_id'] ?? null;
  33. $paperId = $payload['paper_id'] ?? null;
  34. $myAnswer = $payload['my_answer'] ?? null;
  35. $correctAnswer = $payload['correct_answer'] ?? null;
  36. $questionText = $payload['question_text'] ?? null;
  37. $knowledgePoint = $payload['knowledge_point'] ?? null;
  38. $explanation = $payload['explanation'] ?? null;
  39. $kpIds = $payload['kp_ids'] ?? null;
  40. $source = $payload['source'] ?? MistakeRecord::SOURCE_PRACTICE;
  41. $happenedAt = $payload['happened_at'] ?? now();
  42. if (!$studentId) {
  43. throw new \InvalidArgumentException('学生ID不能为空');
  44. }
  45. // 使用事务确保数据一致性
  46. return \DB::transaction(function () use (
  47. $studentId, $questionId, $paperId, $myAnswer, $correctAnswer,
  48. $questionText, $knowledgePoint, $explanation, $kpIds, $source, $happenedAt
  49. ) {
  50. // 检查是否已存在相同错题(避免重复)
  51. $query = MistakeRecord::where('student_id', $studentId)
  52. ->where('source', $source)
  53. ->where('created_at', '>=', now()->subDay());
  54. // 如果有 question_id,用它去重;否则用 question_text
  55. if ($questionId) {
  56. $query->where('question_id', $questionId);
  57. } elseif ($questionText) {
  58. $query->where('question_text', $questionText);
  59. }
  60. $existingMistake = $query->first();
  61. if ($existingMistake) {
  62. return [
  63. 'duplicate' => true,
  64. 'mistake_id' => $existingMistake->id,
  65. 'message' => '错题已存在',
  66. ];
  67. }
  68. // 创建错题记录
  69. $mistake = MistakeRecord::create([
  70. 'student_id' => $studentId,
  71. 'question_id' => $questionId,
  72. 'paper_id' => $paperId,
  73. 'student_answer' => $myAnswer,
  74. 'correct_answer' => $correctAnswer,
  75. 'question_text' => $questionText,
  76. 'knowledge_point' => $knowledgePoint,
  77. 'explanation' => $explanation,
  78. 'kp_ids' => $kpIds,
  79. 'source' => $source,
  80. 'created_at' => $happenedAt,
  81. 'review_status' => MistakeRecord::REVIEW_STATUS_PENDING,
  82. 'review_count' => 0,
  83. ]);
  84. // 清除相关缓存
  85. $this->clearCache($studentId);
  86. return [
  87. 'duplicate' => false,
  88. 'mistake_id' => $mistake->id,
  89. 'created_at' => $mistake->created_at,
  90. ];
  91. });
  92. }
  93. /**
  94. * 获取错题列表
  95. */
  96. public function listMistakes(array $params = []): array
  97. {
  98. $studentId = $params['student_id'] ?? null;
  99. $page = (int) ($params['page'] ?? 1);
  100. $perPage = (int) ($params['per_page'] ?? 20);
  101. if (!$studentId) {
  102. return [
  103. 'data' => [],
  104. 'meta' => ['total' => 0, 'page' => $page, 'per_page' => $perPage],
  105. ];
  106. }
  107. // 构建缓存键
  108. $cacheKey = $this->buildCacheKey('list', $params);
  109. // 尝试从缓存获取
  110. if (Cache::has($cacheKey)) {
  111. return Cache::get($cacheKey);
  112. }
  113. try {
  114. $query = MistakeRecord::forStudent($studentId)
  115. ->with(['student']) // 预加载学生信息
  116. ->orderByDesc('created_at');
  117. // 应用筛选条件
  118. $this->applyFilters($query, $params);
  119. // 获取总数
  120. $total = $query->count();
  121. // 分页获取数据
  122. $mistakes = $query->skip(($page - 1) * $perPage)
  123. ->take($perPage)
  124. ->get();
  125. // 转换数据格式
  126. $data = $mistakes->map(function ($mistake) {
  127. return $this->transformMistakeRecord($mistake);
  128. })->toArray();
  129. $result = [
  130. 'data' => $data,
  131. 'meta' => [
  132. 'total' => $total,
  133. 'page' => $page,
  134. 'per_page' => $perPage,
  135. 'last_page' => (int) ceil($total / $perPage),
  136. ],
  137. ];
  138. // 缓存结果
  139. Cache::put($cacheKey, $result, self::CACHE_TTL_LIST);
  140. return $result;
  141. } catch (\Throwable $e) {
  142. Log::error('获取错题列表失败', [
  143. 'student_id' => $studentId,
  144. 'error' => $e->getMessage(),
  145. 'params' => $params,
  146. ]);
  147. return [
  148. 'data' => [],
  149. 'meta' => ['total' => 0, 'page' => $page, 'per_page' => $perPage],
  150. ];
  151. }
  152. }
  153. /**
  154. * 获取错题详情
  155. */
  156. public function getMistakeDetail(string $mistakeId, ?string $studentId = null): array
  157. {
  158. try {
  159. $query = MistakeRecord::with(['student']);
  160. if ($studentId) {
  161. $query->forStudent($studentId);
  162. }
  163. $mistake = $query->find($mistakeId);
  164. if (!$mistake) {
  165. return [];
  166. }
  167. return $this->transformMistakeRecord($mistake, true);
  168. } catch (\Throwable $e) {
  169. Log::error('获取错题详情失败', [
  170. 'mistake_id' => $mistakeId,
  171. 'student_id' => $studentId,
  172. 'error' => $e->getMessage(),
  173. ]);
  174. return [];
  175. }
  176. }
  177. /**
  178. * 获取错题统计概要
  179. */
  180. public function summarize(string $studentId): array
  181. {
  182. $cacheKey = "mistake_book:summary:{$studentId}";
  183. return Cache::remember($cacheKey, self::CACHE_TTL_SUMMARY, function () use ($studentId) {
  184. return MistakeRecord::getSummary($studentId);
  185. });
  186. }
  187. /**
  188. * 获取错误模式分析
  189. */
  190. public function getMistakePatterns(string $studentId): array
  191. {
  192. $cacheKey = "mistake_book:patterns:{$studentId}";
  193. return Cache::remember($cacheKey, self::CACHE_TTL_PATTERNS, function () use ($studentId) {
  194. return MistakeRecord::getMistakePatterns($studentId);
  195. });
  196. }
  197. /**
  198. * 收藏/取消收藏错题
  199. */
  200. public function toggleFavorite(string $mistakeId, bool $favorite = true): bool
  201. {
  202. try {
  203. $mistake = MistakeRecord::find($mistakeId);
  204. if (!$mistake) {
  205. return false;
  206. }
  207. $mistake->update(['is_favorite' => $favorite]);
  208. // 清除缓存
  209. $this->clearCache($mistake->student_id);
  210. return true;
  211. } catch (\Throwable $e) {
  212. Log::error('收藏错题失败', [
  213. 'mistake_id' => $mistakeId,
  214. 'favorite' => $favorite,
  215. 'error' => $e->getMessage(),
  216. ]);
  217. return false;
  218. }
  219. }
  220. /**
  221. * 标记已复习
  222. */
  223. public function markReviewed(string $mistakeId): bool
  224. {
  225. try {
  226. $mistake = MistakeRecord::find($mistakeId);
  227. if (!$mistake) {
  228. return false;
  229. }
  230. $mistake->markAsReviewed();
  231. // 清除缓存
  232. $this->clearCache($mistake->student_id);
  233. return true;
  234. } catch (\Throwable $e) {
  235. Log::error('标记已复习失败', [
  236. 'mistake_id' => $mistakeId,
  237. 'error' => $e->getMessage(),
  238. ]);
  239. return false;
  240. }
  241. }
  242. /**
  243. * 修改复习状态
  244. */
  245. public function updateReviewStatus(string $mistakeId, string $action = 'increment', bool $forceReview = false): array
  246. {
  247. try {
  248. $mistake = MistakeRecord::find($mistakeId);
  249. if (!$mistake) {
  250. return [
  251. 'success' => false,
  252. 'error' => '错题记录不存在',
  253. ];
  254. }
  255. match ($action) {
  256. 'increment' => $mistake->markAsReviewed(),
  257. 'mastered' => $mistake->markAsMastered(),
  258. 'reset' => $mistake->update([
  259. 'review_status' => MistakeRecord::REVIEW_STATUS_PENDING,
  260. 'review_count' => 0,
  261. 'mastery_level' => null,
  262. ]),
  263. default => throw new \InvalidArgumentException('无效的操作类型'),
  264. };
  265. // 清除缓存
  266. $this->clearCache($mistake->student_id);
  267. return [
  268. 'success' => true,
  269. 'mistake_id' => $mistakeId,
  270. 'review_status' => $mistake->review_status,
  271. 'review_count' => $mistake->review_count,
  272. 'message' => '复习状态更新成功',
  273. ];
  274. } catch (\Throwable $e) {
  275. Log::error('更新复习状态失败', [
  276. 'mistake_id' => $mistakeId,
  277. 'action' => $action,
  278. 'error' => $e->getMessage(),
  279. ]);
  280. return [
  281. 'success' => false,
  282. 'error' => $e->getMessage(),
  283. ];
  284. }
  285. }
  286. /**
  287. * 获取复习状态
  288. */
  289. public function getReviewStatus(string $mistakeId): array
  290. {
  291. try {
  292. $mistake = MistakeRecord::find($mistakeId);
  293. if (!$mistake) {
  294. return [
  295. 'success' => false,
  296. 'error' => '错题记录不存在',
  297. ];
  298. }
  299. return [
  300. 'success' => true,
  301. 'mistake_id' => $mistakeId,
  302. 'review_status' => $mistake->review_status,
  303. 'review_count' => $mistake->review_count,
  304. 'reviewed_at' => $mistake->reviewed_at?->toISOString(),
  305. 'next_review_at' => $mistake->next_review_at?->toISOString(),
  306. 'mastery_level' => $mistake->mastery_level,
  307. 'force_review' => $mistake->force_review,
  308. ];
  309. } catch (\Throwable $e) {
  310. Log::error('获取复习状态失败', [
  311. 'mistake_id' => $mistakeId,
  312. 'error' => $e->getMessage(),
  313. ]);
  314. return [
  315. 'success' => false,
  316. 'error' => $e->getMessage(),
  317. ];
  318. }
  319. }
  320. /**
  321. * 增加复习次数
  322. */
  323. public function incrementReviewCount(string $mistakeId, bool $forceReview = false): array
  324. {
  325. return $this->updateReviewStatus($mistakeId, 'increment', $forceReview);
  326. }
  327. /**
  328. * 重置为强制复习状态
  329. */
  330. public function resetReviewStatus(string $mistakeId): array
  331. {
  332. return $this->updateReviewStatus($mistakeId, 'reset');
  333. }
  334. /**
  335. * 添加到重练清单
  336. */
  337. public function addToRetryList(string $mistakeId): bool
  338. {
  339. try {
  340. $mistake = MistakeRecord::find($mistakeId);
  341. if (!$mistake) {
  342. return false;
  343. }
  344. $mistake->addToRetryList();
  345. // 清除缓存
  346. $this->clearCache($mistake->student_id);
  347. return true;
  348. } catch (\Throwable $e) {
  349. Log::error('加入重练清单失败', [
  350. 'mistake_id' => $mistakeId,
  351. 'error' => $e->getMessage(),
  352. ]);
  353. return false;
  354. }
  355. }
  356. /**
  357. * 批量操作错题
  358. */
  359. public function batchOperation(array $mistakeIds, string $operation, array $params = []): array
  360. {
  361. if (empty($mistakeIds)) {
  362. return [
  363. 'success' => false,
  364. 'error' => '请选择要操作的错题',
  365. ];
  366. }
  367. try {
  368. $mistakes = MistakeRecord::whereIn('id', $mistakeIds)->get();
  369. $successCount = 0;
  370. $errors = [];
  371. foreach ($mistakes as $mistake) {
  372. try {
  373. match ($operation) {
  374. 'favorite' => $mistake->toggleFavorite(),
  375. 'reviewed' => $mistake->markAsReviewed(),
  376. 'mastered' => $mistake->markAsMastered(),
  377. 'retry_list' => $mistake->addToRetryList(),
  378. 'remove_retry_list' => $mistake->removeFromRetryList(),
  379. 'set_error_type' => $mistake->update(['error_type' => $params['error_type'] ?? null]),
  380. 'set_importance' => $mistake->update(['importance' => $params['importance'] ?? 5]),
  381. default => throw new \InvalidArgumentException('不支持的操作'),
  382. };
  383. $successCount++;
  384. } catch (\Throwable $e) {
  385. $errors[] = [
  386. 'mistake_id' => $mistake->id,
  387. 'error' => $e->getMessage(),
  388. ];
  389. }
  390. }
  391. // 清除缓存
  392. if ($successCount > 0) {
  393. $studentIds = $mistakes->pluck('student_id')->unique();
  394. foreach ($studentIds as $studentId) {
  395. $this->clearCache($studentId);
  396. }
  397. }
  398. return [
  399. 'success' => true,
  400. 'total' => count($mistakeIds),
  401. 'success_count' => $successCount,
  402. 'error_count' => count($errors),
  403. 'errors' => $errors,
  404. ];
  405. } catch (\Throwable $e) {
  406. Log::error('批量操作失败', [
  407. 'operation' => $operation,
  408. 'mistake_ids' => $mistakeIds,
  409. 'error' => $e->getMessage(),
  410. ]);
  411. return [
  412. 'success' => false,
  413. 'error' => $e->getMessage(),
  414. ];
  415. }
  416. }
  417. /**
  418. * 基于错题推荐练习题(本地实现)
  419. */
  420. public function recommendPractice(string $studentId, array $kpIds = [], array $skillIds = []): array
  421. {
  422. try {
  423. // 获取学生未掌握的知识点
  424. $weakKnowledgePoints = MistakeRecord::forStudent($studentId)
  425. ->where('review_status', '!=', MistakeRecord::REVIEW_STATUS_MASTERED)
  426. ->pluck('knowledge_point')
  427. ->filter()
  428. ->unique()
  429. ->values()
  430. ->toArray();
  431. // 合并传入的知识点
  432. $allKpIds = array_unique(array_merge($kpIds, $weakKnowledgePoints));
  433. // TODO: 这里应该调用本地题库服务
  434. // 目前返回模拟数据
  435. $recommendations = [];
  436. foreach (array_slice($allKpIds, 0, 5) as $kpId) {
  437. $recommendations[] = [
  438. 'id' => "rec_{$kpId}_{$studentId}",
  439. 'kp_code' => $kpId,
  440. 'question_text' => "针对知识点 {$kpId} 的练习题",
  441. 'difficulty' => 0.5,
  442. 'source' => 'recommendation',
  443. ];
  444. }
  445. return ['data' => $recommendations];
  446. } catch (\Throwable $e) {
  447. Log::error('推荐练习题失败', [
  448. 'student_id' => $studentId,
  449. 'error' => $e->getMessage(),
  450. ]);
  451. return ['data' => []];
  452. }
  453. }
  454. /**
  455. * 获取仪表板快照数据
  456. */
  457. public function getPanelSnapshot(string $studentId, int $limit = 5): array
  458. {
  459. try {
  460. $recentMistakes = MistakeRecord::forStudent($studentId)
  461. ->orderByDesc('created_at')
  462. ->limit($limit)
  463. ->get()
  464. ->map(fn($m) => $this->transformMistakeRecord($m))
  465. ->toArray();
  466. $patterns = $this->getMistakePatterns($studentId);
  467. $summary = $this->summarize($studentId);
  468. return [
  469. 'recent' => $recentMistakes,
  470. 'weak_skills' => array_slice($patterns['error_types'] ?? [], 0, 5, true),
  471. 'weak_kps' => array_slice($patterns['knowledge_points'] ?? [], 0, 5, true),
  472. 'error_types' => $patterns['error_types'] ?? [],
  473. 'stats' => $summary,
  474. ];
  475. } catch (\Throwable $e) {
  476. Log::error('获取快照数据失败', [
  477. 'student_id' => $studentId,
  478. 'error' => $e->getMessage(),
  479. ]);
  480. return [
  481. 'recent' => [],
  482. 'weak_skills' => [],
  483. 'weak_kps' => [],
  484. 'error_types' => [],
  485. 'stats' => [
  486. 'total' => 0,
  487. 'pending' => 0,
  488. 'this_week' => 0,
  489. ],
  490. ];
  491. }
  492. }
  493. /**
  494. * 应用筛选条件
  495. */
  496. private function applyFilters($query, array $params): void
  497. {
  498. // 知识点筛选
  499. if (!empty($params['kp_ids'])) {
  500. $kpIds = is_array($params['kp_ids']) ? $params['kp_ids'] : explode(',', $params['kp_ids']);
  501. $query->byKnowledgePoint($kpIds);
  502. }
  503. // 技能筛选
  504. if (!empty($params['skill_ids'])) {
  505. $skillIds = is_array($params['skill_ids']) ? $params['skill_ids'] : explode(',', $params['skill_ids']);
  506. $query->where(function ($q) use ($skillIds) {
  507. foreach ($skillIds as $skillId) {
  508. $q->orWhereJsonContains('skill_ids', $skillId);
  509. }
  510. });
  511. }
  512. // 错误类型筛选
  513. if (!empty($params['error_types'])) {
  514. $errorTypes = is_array($params['error_types']) ? $params['error_types'] : explode(',', $params['error_types']);
  515. $query->whereIn('error_type', $errorTypes);
  516. }
  517. // 时间范围筛选
  518. if (!empty($params['time_range'])) {
  519. match ($params['time_range']) {
  520. 'last_7' => $query->where('created_at', '>=', now()->subDays(7)),
  521. 'last_30' => $query->where('created_at', '>=', now()->subDays(30)),
  522. 'last_90' => $query->where('created_at', '>=', now()->subDays(90)),
  523. default => null,
  524. };
  525. }
  526. // 自定义时间范围
  527. if (!empty($params['start_date'])) {
  528. $query->whereDate('created_at', '>=', $params['start_date']);
  529. }
  530. if (!empty($params['end_date'])) {
  531. $query->whereDate('created_at', '<=', $params['end_date']);
  532. }
  533. // 复习状态筛选
  534. if (!empty($params['unreviewed_only'])) {
  535. $query->pending();
  536. }
  537. if (!empty($params['favorite_only'])) {
  538. $query->favorites();
  539. }
  540. if (!empty($params['in_retry_list_only'])) {
  541. $query->inRetryList();
  542. }
  543. // 排序
  544. $sortBy = $params['sort_by'] ?? 'created_at_desc';
  545. match ($sortBy) {
  546. 'created_at_asc' => $query->orderBy('created_at'),
  547. 'created_at_desc' => $query->orderByDesc('created_at'),
  548. 'review_status_asc' => $query->orderBy('review_status'),
  549. 'difficulty_desc' => $query->orderByDesc('difficulty'),
  550. default => null,
  551. };
  552. }
  553. /**
  554. * 转换错题记录格式
  555. */
  556. private function transformMistakeRecord(MistakeRecord $mistake, bool $detailed = false): array
  557. {
  558. $data = [
  559. 'id' => $mistake->id,
  560. 'student_id' => $mistake->student_id,
  561. 'question_id' => $mistake->question_id,
  562. 'paper_id' => $mistake->paper_id,
  563. 'question_text' => $mistake->question_text,
  564. 'student_answer' => $mistake->student_answer,
  565. 'correct_answer' => $mistake->correct_answer,
  566. 'knowledge_point' => $mistake->knowledge_point,
  567. 'explanation' => $mistake->explanation,
  568. 'source' => $mistake->source,
  569. 'source_label' => $mistake->source_label,
  570. 'created_at' => $mistake->created_at?->toISOString(),
  571. 'review_status' => $mistake->review_status,
  572. 'review_status_label' => $mistake->review_status_label,
  573. 'review_count' => $mistake->review_count,
  574. 'is_favorite' => $mistake->is_favorite,
  575. 'in_retry_list' => $mistake->in_retry_list,
  576. 'reviewed_at' => $mistake->reviewed_at?->toISOString(),
  577. 'next_review_at' => $mistake->next_review_at?->toISOString(),
  578. 'error_type' => $mistake->error_type,
  579. 'error_type_label' => $mistake->error_type_label,
  580. 'kp_ids' => $mistake->kp_ids,
  581. 'skill_ids' => $mistake->skill_ids,
  582. 'difficulty' => $mistake->difficulty,
  583. 'difficulty_level' => $mistake->difficulty_level,
  584. 'importance' => $mistake->importance,
  585. 'mastery_level' => $mistake->mastery_level,
  586. ];
  587. if ($detailed) {
  588. $data['student'] = [
  589. 'id' => $mistake->student?->student_id,
  590. 'name' => $mistake->student?->name,
  591. 'grade' => $mistake->student?->grade,
  592. 'class_name' => $mistake->student?->class_name,
  593. ];
  594. }
  595. return $data;
  596. }
  597. /**
  598. * 构建缓存键
  599. */
  600. private function buildCacheKey(string $type, array $params): string
  601. {
  602. $key = "mistake_book:{$type}:" . md5(serialize($params));
  603. return $key;
  604. }
  605. /**
  606. * 清除缓存
  607. */
  608. private function clearCache(string|int $studentId): void
  609. {
  610. try {
  611. $patterns = [
  612. "mistake_book:list:{$studentId}",
  613. "mistake_book:summary:{$studentId}",
  614. "mistake_book:patterns:{$studentId}",
  615. ];
  616. foreach ($patterns as $key) {
  617. Cache::forget($key);
  618. }
  619. } catch (\Exception $e) {
  620. // 缓存清除失败不影响主流程
  621. Log::debug('缓存清除失败(可忽略)', ['error' => $e->getMessage()]);
  622. }
  623. }
  624. }