MistakeBookService.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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 = 60; // 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. // 重复定义:同一学生 + 同一题目 + 同一卷子 的组合
  52. // 这样允许同一题目在不同卷子中重复,也允许同一卷子中的新题目被记录
  53. $query = MistakeRecord::where('student_id', $studentId)
  54. ->where('source', $source);
  55. // 如果有 question_id 和 paper_id,用它们去重
  56. // 否则用 question_text 去重
  57. if ($questionId && $paperId) {
  58. $query->where('question_id', $questionId)
  59. ->where('paper_id', $paperId);
  60. Log::debug('错题记录重复检查', [
  61. 'student_id' => $studentId,
  62. 'question_id' => $questionId,
  63. 'paper_id' => $paperId,
  64. 'check_type' => 'question_id + paper_id'
  65. ]);
  66. } elseif ($questionId) {
  67. $query->where('question_id', $questionId);
  68. Log::debug('错题记录重复检查', [
  69. 'student_id' => $studentId,
  70. 'question_id' => $questionId,
  71. 'check_type' => 'question_id only'
  72. ]);
  73. } elseif ($questionText) {
  74. $query->where('question_text', $questionText);
  75. Log::debug('错题记录重复检查', [
  76. 'student_id' => $studentId,
  77. 'question_text' => substr($questionText, 0, 50) . '...',
  78. 'check_type' => 'question_text'
  79. ]);
  80. } else {
  81. Log::warning('错题记录保存失败:缺少题目ID和题目文本', [
  82. 'student_id' => $studentId,
  83. 'paper_id' => $paperId
  84. ]);
  85. return [
  86. 'duplicate' => false,
  87. 'error' => '缺少题目ID和题目文本,无法创建错题记录'
  88. ];
  89. }
  90. $existingMistake = $query->first();
  91. if ($existingMistake) {
  92. Log::debug('发现重复错题记录,合并知识点', [
  93. 'student_id' => $studentId,
  94. 'question_id' => $questionId,
  95. 'paper_id' => $paperId,
  96. 'existing_mistake_id' => $existingMistake->id
  97. ]);
  98. // 合并知识点到已有记录中
  99. if ($kpIds) {
  100. $existingKpIds = $existingMistake->kp_ids ?? [];
  101. $newKpIds = is_array($kpIds) ? $kpIds : [$kpIds];
  102. // 合并并去重
  103. $mergedKpIds = array_values(array_unique(array_merge($existingKpIds, $newKpIds)));
  104. // 更新记录(仅更新 kp_ids)
  105. $existingMistake->update([
  106. 'kp_ids' => $mergedKpIds,
  107. ]);
  108. Log::info('错题记录知识点合并成功', [
  109. 'student_id' => $studentId,
  110. 'question_id' => $questionId,
  111. 'paper_id' => $paperId,
  112. 'existing_kp_ids' => $existingKpIds,
  113. 'new_kp_ids' => $newKpIds,
  114. 'merged_kp_ids' => $mergedKpIds
  115. ]);
  116. }
  117. return [
  118. 'duplicate' => true,
  119. 'mistake_id' => $existingMistake->id,
  120. 'message' => '错题已存在,已合并知识点',
  121. ];
  122. }
  123. // 创建错题记录(合并知识点到数组)
  124. $mistake = MistakeRecord::create([
  125. 'student_id' => $studentId,
  126. 'question_id' => $questionId,
  127. 'paper_id' => $paperId,
  128. 'student_answer' => $myAnswer,
  129. 'correct_answer' => $correctAnswer,
  130. 'question_text' => $questionText,
  131. 'knowledge_point' => $knowledgePoint,
  132. 'explanation' => $explanation,
  133. 'kp_ids' => is_array($kpIds) ? $kpIds : ($kpIds ? [$kpIds] : null), // 确保是数组
  134. 'source' => $source,
  135. 'created_at' => $happenedAt,
  136. 'review_status' => MistakeRecord::REVIEW_STATUS_PENDING,
  137. 'review_count' => 0,
  138. ]);
  139. // 清除相关缓存
  140. $this->clearCache($studentId);
  141. return [
  142. 'duplicate' => false,
  143. 'mistake_id' => $mistake->id,
  144. 'created_at' => $mistake->created_at,
  145. ];
  146. });
  147. }
  148. /**
  149. * 获取错题列表
  150. */
  151. public function listMistakes(array $params = []): array
  152. {
  153. $studentId = $params['student_id'] ?? null;
  154. $page = (int) ($params['page'] ?? 1);
  155. $perPage = (int) ($params['per_page'] ?? 20);
  156. if (!$studentId) {
  157. return [
  158. 'data' => [],
  159. 'meta' => ['total' => 0, 'page' => $page, 'per_page' => $perPage],
  160. 'statistics' => [ // ✅ 无 student_id 时也返回空统计
  161. 'total' => 0,
  162. 'pending' => 0,
  163. 'reviewed' => 0,
  164. 'mastered' => 0,
  165. 'favorites' => 0,
  166. 'in_retry_list' => 0,
  167. 'this_week' => 0,
  168. 'mastery_rate' => 0.0,
  169. ],
  170. ];
  171. }
  172. // 构建缓存键
  173. $cacheKey = $this->buildCacheKey('list', $params);
  174. // 尝试从缓存获取
  175. if (Cache::has($cacheKey)) {
  176. return Cache::get($cacheKey);
  177. }
  178. try {
  179. $query = MistakeRecord::forStudent($studentId)
  180. ->with(['student']) // 预加载学生信息
  181. ->orderByDesc('created_at');
  182. // 应用筛选条件
  183. $this->applyFilters($query, $params);
  184. // 获取总数
  185. $total = $query->count();
  186. // 分页获取数据
  187. $mistakes = $query->skip(($page - 1) * $perPage)
  188. ->take($perPage)
  189. ->get();
  190. // 转换数据格式
  191. $data = $mistakes->map(function ($mistake) {
  192. return $this->transformMistakeRecord($mistake, false);
  193. })->toArray();
  194. // 获取统计信息
  195. $summary = $this->summarize($studentId);
  196. $result = [
  197. 'data' => $data,
  198. 'meta' => [
  199. 'total' => $total,
  200. 'page' => $page,
  201. 'per_page' => $perPage,
  202. 'last_page' => (int) ceil($total / $perPage),
  203. ],
  204. 'statistics' => $summary, // ✅ 添加统计信息
  205. ];
  206. // 缓存结果
  207. Cache::put($cacheKey, $result, self::CACHE_TTL_LIST);
  208. return $result;
  209. } catch (\Throwable $e) {
  210. Log::error('获取错题列表失败', [
  211. 'student_id' => $studentId,
  212. 'error' => $e->getMessage(),
  213. 'params' => $params,
  214. ]);
  215. return [
  216. 'data' => [],
  217. 'meta' => ['total' => 0, 'page' => $page, 'per_page' => $perPage],
  218. 'statistics' => [ // ✅ 错误时也返回空统计
  219. 'total' => 0,
  220. 'pending' => 0,
  221. 'reviewed' => 0,
  222. 'mastered' => 0,
  223. 'favorites' => 0,
  224. 'in_retry_list' => 0,
  225. 'this_week' => 0,
  226. 'mastery_rate' => 0.0,
  227. ],
  228. ];
  229. }
  230. }
  231. /**
  232. * 获取错题详情
  233. */
  234. public function getMistakeDetail(string $mistakeId, ?string $studentId = null): array
  235. {
  236. try {
  237. $query = MistakeRecord::with(['student']);
  238. if ($studentId) {
  239. $query->forStudent($studentId);
  240. }
  241. $mistake = $query->find($mistakeId);
  242. if (!$mistake) {
  243. return [];
  244. }
  245. return $this->transformMistakeRecord($mistake, true);
  246. } catch (\Throwable $e) {
  247. Log::error('获取错题详情失败', [
  248. 'mistake_id' => $mistakeId,
  249. 'student_id' => $studentId,
  250. 'error' => $e->getMessage(),
  251. ]);
  252. return [];
  253. }
  254. }
  255. /**
  256. * 获取错题统计概要
  257. */
  258. public function summarize(string $studentId): array
  259. {
  260. $cacheKey = "mistake_book:summary:{$studentId}";
  261. return Cache::remember($cacheKey, self::CACHE_TTL_SUMMARY, function () use ($studentId) {
  262. return MistakeRecord::getSummary($studentId);
  263. });
  264. }
  265. /**
  266. * 获取错误模式分析
  267. */
  268. public function getMistakePatterns(string $studentId): array
  269. {
  270. $cacheKey = "mistake_book:patterns:{$studentId}";
  271. return Cache::remember($cacheKey, self::CACHE_TTL_PATTERNS, function () use ($studentId) {
  272. return MistakeRecord::getMistakePatterns($studentId);
  273. });
  274. }
  275. /**
  276. * 收藏/取消收藏错题
  277. */
  278. public function toggleFavorite(string $mistakeId, bool $favorite = true): bool
  279. {
  280. try {
  281. $mistake = MistakeRecord::find($mistakeId);
  282. if (!$mistake) {
  283. return false;
  284. }
  285. $mistake->update(['is_favorite' => $favorite]);
  286. // 清除缓存
  287. $this->clearCache($mistake->student_id);
  288. return true;
  289. } catch (\Throwable $e) {
  290. Log::error('收藏错题失败', [
  291. 'mistake_id' => $mistakeId,
  292. 'favorite' => $favorite,
  293. 'error' => $e->getMessage(),
  294. ]);
  295. return false;
  296. }
  297. }
  298. /**
  299. * 标记已复习
  300. */
  301. public function markReviewed(string $mistakeId): bool
  302. {
  303. try {
  304. $mistake = MistakeRecord::find($mistakeId);
  305. if (!$mistake) {
  306. return false;
  307. }
  308. $mistake->markAsReviewed();
  309. // 清除缓存
  310. $this->clearCache($mistake->student_id);
  311. return true;
  312. } catch (\Throwable $e) {
  313. Log::error('标记已复习失败', [
  314. 'mistake_id' => $mistakeId,
  315. 'error' => $e->getMessage(),
  316. ]);
  317. return false;
  318. }
  319. }
  320. /**
  321. * 修改复习状态
  322. */
  323. public function updateReviewStatus(string $mistakeId, string $action = 'increment', bool $forceReview = false): array
  324. {
  325. try {
  326. $mistake = MistakeRecord::find($mistakeId);
  327. if (!$mistake) {
  328. return [
  329. 'success' => false,
  330. 'error' => '错题记录不存在',
  331. ];
  332. }
  333. match ($action) {
  334. 'increment' => $mistake->markAsReviewed(),
  335. 'mastered' => $mistake->markAsMastered(),
  336. 'reset' => $mistake->update([
  337. 'review_status' => MistakeRecord::REVIEW_STATUS_PENDING,
  338. 'review_count' => 0,
  339. 'mastery_level' => null,
  340. 'reviewed_at' => null,
  341. 'next_review_at' => null,
  342. ]),
  343. default => throw new \InvalidArgumentException('无效的操作类型'),
  344. };
  345. // ⚠️ 重要:重新加载模型数据以获取最新状态
  346. $mistake->refresh();
  347. return [
  348. 'success' => true,
  349. 'mistake_id' => $mistakeId,
  350. 'review_status' => $mistake->review_status,
  351. 'review_count' => $mistake->review_count,
  352. 'reviewed_at' => $mistake->reviewed_at?->toISOString(),
  353. 'next_review_at' => $mistake->next_review_at?->toISOString(),
  354. 'mastery_level' => $mistake->mastery_level,
  355. 'message' => '复习状态更新成功',
  356. ];
  357. } catch (\Throwable $e) {
  358. Log::error('更新复习状态失败', [
  359. 'mistake_id' => $mistakeId,
  360. 'action' => $action,
  361. 'error' => $e->getMessage(),
  362. ]);
  363. return [
  364. 'success' => false,
  365. 'error' => $e->getMessage(),
  366. ];
  367. }
  368. }
  369. /**
  370. * 获取复习状态
  371. */
  372. public function getReviewStatus(string $mistakeId): array
  373. {
  374. try {
  375. $mistake = MistakeRecord::find($mistakeId);
  376. if (!$mistake) {
  377. return [
  378. 'success' => false,
  379. 'error' => '错题记录不存在',
  380. ];
  381. }
  382. return [
  383. 'success' => true,
  384. 'mistake_id' => $mistakeId,
  385. 'review_status' => $mistake->review_status,
  386. 'review_count' => $mistake->review_count,
  387. 'reviewed_at' => $mistake->reviewed_at?->toISOString(),
  388. 'next_review_at' => $mistake->next_review_at?->toISOString(),
  389. 'mastery_level' => $mistake->mastery_level,
  390. 'force_review' => $mistake->force_review,
  391. ];
  392. } catch (\Throwable $e) {
  393. Log::error('获取复习状态失败', [
  394. 'mistake_id' => $mistakeId,
  395. 'error' => $e->getMessage(),
  396. ]);
  397. return [
  398. 'success' => false,
  399. 'error' => $e->getMessage(),
  400. ];
  401. }
  402. }
  403. /**
  404. * 增加复习次数
  405. */
  406. public function incrementReviewCount(string $mistakeId, bool $forceReview = false): array
  407. {
  408. return $this->updateReviewStatus($mistakeId, 'increment', $forceReview);
  409. }
  410. /**
  411. * 重置为强制复习状态
  412. */
  413. public function resetReviewStatus(string $mistakeId): array
  414. {
  415. return $this->updateReviewStatus($mistakeId, 'reset');
  416. }
  417. /**
  418. * 添加到重练清单
  419. */
  420. public function addToRetryList(string $mistakeId): bool
  421. {
  422. try {
  423. $mistake = MistakeRecord::find($mistakeId);
  424. if (!$mistake) {
  425. return false;
  426. }
  427. $mistake->addToRetryList();
  428. // 清除缓存
  429. $this->clearCache($mistake->student_id);
  430. return true;
  431. } catch (\Throwable $e) {
  432. Log::error('加入重练清单失败', [
  433. 'mistake_id' => $mistakeId,
  434. 'error' => $e->getMessage(),
  435. ]);
  436. return false;
  437. }
  438. }
  439. /**
  440. * 批量操作错题
  441. */
  442. public function batchOperation(array $mistakeIds, string $operation, array $params = []): array
  443. {
  444. if (empty($mistakeIds)) {
  445. return [
  446. 'success' => false,
  447. 'error' => '请选择要操作的错题',
  448. ];
  449. }
  450. try {
  451. $mistakes = MistakeRecord::whereIn('id', $mistakeIds)->get();
  452. $successCount = 0;
  453. $errors = [];
  454. foreach ($mistakes as $mistake) {
  455. try {
  456. match ($operation) {
  457. 'favorite' => $mistake->toggleFavorite(),
  458. 'reviewed' => $mistake->markAsReviewed(),
  459. 'mastered' => $mistake->markAsMastered(),
  460. 'retry_list' => $mistake->addToRetryList(),
  461. 'remove_retry_list' => $mistake->removeFromRetryList(),
  462. 'set_error_type' => $mistake->update(['error_type' => $params['error_type'] ?? null]),
  463. 'set_importance' => $mistake->update(['importance' => $params['importance'] ?? 5]),
  464. default => throw new \InvalidArgumentException('不支持的操作'),
  465. };
  466. $successCount++;
  467. } catch (\Throwable $e) {
  468. $errors[] = [
  469. 'mistake_id' => $mistake->id,
  470. 'error' => $e->getMessage(),
  471. ];
  472. }
  473. }
  474. // 清除缓存
  475. if ($successCount > 0) {
  476. $studentIds = $mistakes->pluck('student_id')->unique();
  477. foreach ($studentIds as $studentId) {
  478. $this->clearCache($studentId);
  479. }
  480. }
  481. return [
  482. 'success' => true,
  483. 'total' => count($mistakeIds),
  484. 'success_count' => $successCount,
  485. 'error_count' => count($errors),
  486. 'errors' => $errors,
  487. ];
  488. } catch (\Throwable $e) {
  489. Log::error('批量操作失败', [
  490. 'operation' => $operation,
  491. 'mistake_ids' => $mistakeIds,
  492. 'error' => $e->getMessage(),
  493. ]);
  494. return [
  495. 'success' => false,
  496. 'error' => $e->getMessage(),
  497. ];
  498. }
  499. }
  500. /**
  501. * 基于错题推荐练习题(本地实现)
  502. */
  503. public function recommendPractice(string $studentId, array $kpIds = [], array $skillIds = []): array
  504. {
  505. try {
  506. // 获取学生未掌握的知识点
  507. $weakKnowledgePoints = MistakeRecord::forStudent($studentId)
  508. ->where('review_status', '!=', MistakeRecord::REVIEW_STATUS_MASTERED)
  509. ->pluck('knowledge_point')
  510. ->filter()
  511. ->unique()
  512. ->values()
  513. ->toArray();
  514. // 合并传入的知识点
  515. $allKpIds = array_unique(array_merge($kpIds, $weakKnowledgePoints));
  516. // TODO: 这里应该调用本地题库服务
  517. // 目前返回模拟数据
  518. $recommendations = [];
  519. foreach (array_slice($allKpIds, 0, 5) as $kpId) {
  520. $recommendations[] = [
  521. 'id' => "rec_{$kpId}_{$studentId}",
  522. 'kp_code' => $kpId,
  523. 'question_text' => "针对知识点 {$kpId} 的练习题",
  524. 'difficulty' => 0.5,
  525. 'source' => 'recommendation',
  526. ];
  527. }
  528. return ['data' => $recommendations];
  529. } catch (\Throwable $e) {
  530. Log::error('推荐练习题失败', [
  531. 'student_id' => $studentId,
  532. 'error' => $e->getMessage(),
  533. ]);
  534. return ['data' => []];
  535. }
  536. }
  537. /**
  538. * 获取仪表板快照数据
  539. */
  540. public function getPanelSnapshot(string $studentId, int $limit = 5): array
  541. {
  542. try {
  543. $recentMistakes = MistakeRecord::forStudent($studentId)
  544. ->orderByDesc('created_at')
  545. ->limit($limit)
  546. ->get()
  547. ->map(fn($m) => $this->transformMistakeRecord($m))
  548. ->toArray();
  549. $patterns = $this->getMistakePatterns($studentId);
  550. $summary = $this->summarize($studentId);
  551. return [
  552. 'recent' => $recentMistakes,
  553. 'weak_skills' => array_slice($patterns['error_types'] ?? [], 0, 5, true),
  554. 'weak_kps' => array_slice($patterns['knowledge_points'] ?? [], 0, 5, true),
  555. 'error_types' => $patterns['error_types'] ?? [],
  556. 'stats' => $summary,
  557. ];
  558. } catch (\Throwable $e) {
  559. Log::error('获取快照数据失败', [
  560. 'student_id' => $studentId,
  561. 'error' => $e->getMessage(),
  562. ]);
  563. return [
  564. 'recent' => [],
  565. 'weak_skills' => [],
  566. 'weak_kps' => [],
  567. 'error_types' => [],
  568. 'stats' => [
  569. 'total' => 0,
  570. 'pending' => 0,
  571. 'this_week' => 0,
  572. ],
  573. ];
  574. }
  575. }
  576. /**
  577. * 应用筛选条件
  578. */
  579. private function applyFilters($query, array $params): void
  580. {
  581. // 知识点筛选
  582. if (!empty($params['kp_ids'])) {
  583. $kpIds = is_array($params['kp_ids']) ? $params['kp_ids'] : explode(',', $params['kp_ids']);
  584. $query->byKnowledgePoint($kpIds);
  585. }
  586. // 技能筛选
  587. if (!empty($params['skill_ids'])) {
  588. $skillIds = is_array($params['skill_ids']) ? $params['skill_ids'] : explode(',', $params['skill_ids']);
  589. $query->where(function ($q) use ($skillIds) {
  590. foreach ($skillIds as $skillId) {
  591. $q->orWhereJsonContains('skill_ids', $skillId);
  592. }
  593. });
  594. }
  595. // 错误类型筛选
  596. if (!empty($params['error_types'])) {
  597. $errorTypes = is_array($params['error_types']) ? $params['error_types'] : explode(',', $params['error_types']);
  598. $query->whereIn('error_type', $errorTypes);
  599. }
  600. // 时间范围筛选
  601. if (!empty($params['time_range'])) {
  602. match ($params['time_range']) {
  603. 'last_7' => $query->where('created_at', '>=', now()->subDays(7)),
  604. 'last_30' => $query->where('created_at', '>=', now()->subDays(30)),
  605. 'last_90' => $query->where('created_at', '>=', now()->subDays(90)),
  606. default => null,
  607. };
  608. }
  609. // 自定义时间范围
  610. if (!empty($params['start_date'])) {
  611. $query->whereDate('created_at', '>=', $params['start_date']);
  612. }
  613. if (!empty($params['end_date'])) {
  614. $query->whereDate('created_at', '<=', $params['end_date']);
  615. }
  616. // 复习状态筛选
  617. if (!empty($params['unreviewed_only'])) {
  618. $query->pending();
  619. }
  620. if (!empty($params['favorite_only'])) {
  621. $query->favorites();
  622. }
  623. if (!empty($params['in_retry_list_only'])) {
  624. $query->inRetryList();
  625. }
  626. // 排序
  627. $sortBy = $params['sort_by'] ?? 'created_at_desc';
  628. match ($sortBy) {
  629. 'created_at_asc' => $query->orderBy('created_at'),
  630. 'created_at_desc' => $query->orderByDesc('created_at'),
  631. 'review_status_asc' => $query->orderBy('review_status'),
  632. 'difficulty_desc' => $query->orderByDesc('difficulty'),
  633. default => null,
  634. };
  635. }
  636. /**
  637. * 转换错题记录格式
  638. */
  639. private function transformMistakeRecord(MistakeRecord $mistake, bool $detailed = false): array
  640. {
  641. // 【新增】通过 question_id 关联获取题目详情
  642. $questionDetails = $this->getQuestionDetails($mistake->question_id);
  643. // 【新增】通过 kp_ids 或 textbook_catalog_nodes_id 获取知识点信息
  644. $knowledgePoints = $this->getKnowledgePoints(
  645. $mistake->kp_ids,
  646. $mistake->question_id,
  647. $questionDetails['textbook_catalog_nodes_id'] ?? null
  648. );
  649. $data = [
  650. // ========== 错题记录基本信息 ==========
  651. 'id' => $mistake->id,
  652. 'student_id' => $mistake->student_id,
  653. 'question_id' => $mistake->question_id,
  654. 'paper_id' => $mistake->paper_id,
  655. 'created_at' => $mistake->created_at?->toISOString(),
  656. 'review_status' => $mistake->review_status,
  657. 'review_status_label' => $mistake->review_status_label,
  658. 'review_count' => $mistake->review_count,
  659. 'is_favorite' => $mistake->is_favorite,
  660. 'in_retry_list' => $mistake->in_retry_list,
  661. 'reviewed_at' => $mistake->reviewed_at?->toISOString(),
  662. 'next_review_at' => $mistake->next_review_at?->toISOString(),
  663. 'error_type' => $mistake->error_type,
  664. 'error_type_label' => $mistake->error_type_label,
  665. 'explanation' => $mistake->explanation,
  666. 'skill_ids' => $mistake->skill_ids,
  667. 'difficulty' => $mistake->difficulty,
  668. 'difficulty_level' => $mistake->difficulty_level,
  669. 'importance' => $mistake->importance,
  670. 'mastery_level' => $mistake->mastery_level,
  671. // ========== 题目信息(优先呈现)==========
  672. // 题目内容:优先使用 questions.stem,其次使用错题本自带
  673. 'question_text' => $questionDetails['stem'] ?? $mistake->question_text,
  674. // 答案:优先使用 questions.answer,其次使用错题本自带
  675. 'correct_answer' => $questionDetails['answer'] ?? $mistake->correct_answer,
  676. // 解题过程/解析:优先使用 questions.solution
  677. 'solution' => $questionDetails['solution'] ?? $mistake->explanation,
  678. // 选项
  679. 'options' => $questionDetails['options'] ?? null,
  680. // 题目类型
  681. 'question_type' => $questionDetails['question_type'] ?? null,
  682. // 题目难度(从题目表获取)
  683. 'question_difficulty' => $questionDetails['difficulty'] ?? null,
  684. // 题目标签
  685. 'question_tags' => $questionDetails['tags'] ?? null,
  686. // 题目来源
  687. 'question_source' => $questionDetails['source'] ?? null,
  688. // 学生答案(始终使用错题本中的记录)
  689. 'student_answer' => $mistake->student_answer,
  690. // ========== 知识点信息 ==========
  691. 'knowledge_points' => $knowledgePoints,
  692. ];
  693. if ($detailed) {
  694. $data['student'] = [
  695. 'id' => $mistake->student?->student_id,
  696. 'name' => $mistake->student?->name,
  697. 'grade' => $mistake->student?->grade,
  698. 'class_name' => $mistake->student?->class_name,
  699. ];
  700. }
  701. return $data;
  702. }
  703. /**
  704. * 构建缓存键
  705. */
  706. private function buildCacheKey(string $type, array $params): string
  707. {
  708. $key = "mistake_book:{$type}:" . md5(serialize($params));
  709. return $key;
  710. }
  711. /**
  712. * 清除缓存
  713. */
  714. private function clearCache(string|int $studentId): void
  715. {
  716. try {
  717. $patterns = [
  718. "mistake_book:list:{$studentId}",
  719. "mistake_book:summary:{$studentId}",
  720. "mistake_book:patterns:{$studentId}",
  721. ];
  722. foreach ($patterns as $key) {
  723. Cache::forget($key);
  724. }
  725. } catch (\Exception $e) {
  726. // 缓存清除失败不影响主流程
  727. Log::debug('缓存清除失败(可忽略)', ['error' => $e->getMessage()]);
  728. }
  729. }
  730. /**
  731. * 【新增】通过 question_id 获取题目详情
  732. */
  733. private function getQuestionDetails(?string $questionId): ?array
  734. {
  735. if (!$questionId) {
  736. return null;
  737. }
  738. try {
  739. $question = \DB::connection('mysql')
  740. ->table('questions')
  741. ->where('id', $questionId)
  742. ->first();
  743. if (!$question) {
  744. return null;
  745. }
  746. return [
  747. 'stem' => $question->stem ?? null, // 题目内容(题干)
  748. 'options' => $question->options ?? null, // 选项
  749. 'answer' => $question->answer ?? null, // 答案
  750. 'solution' => $question->solution ?? null, // 解题过程/解析
  751. 'difficulty' => $question->difficulty ?? null,
  752. 'question_type' => $question->question_type ?? null,
  753. 'textbook_catalog_nodes_id' => $question->textbook_catalog_nodes_id ?? null,
  754. 'tags' => $question->tags ?? null, // 标签
  755. 'source' => $question->source ?? null, // 来源
  756. ];
  757. } catch (\Exception $e) {
  758. Log::warning('获取题目详情失败', [
  759. 'question_id' => $questionId,
  760. 'error' => $e->getMessage()
  761. ]);
  762. return null;
  763. }
  764. }
  765. /**
  766. * 【新增】通过 kp_ids 或 textbook_catalog_nodes_id 获取知识点信息
  767. *
  768. * 逻辑:
  769. * 1. 如果有 kp_ids,直接从 knowledge_points 表查询
  770. * 2. 如果没有 kp_ids,通过 textbook_catalog_nodes_id 关联 textbook_chapter_knowledge_relation 表获取 kp_id
  771. */
  772. private function getKnowledgePoints(?array $kpIds, ?string $questionId = null, ?int $catalogNodesId = null): array
  773. {
  774. // 如果有 kp_ids,直接查询
  775. if (!empty($kpIds)) {
  776. return $this->queryKnowledgePointsByCodes($kpIds);
  777. }
  778. // 如果没有 kp_ids,通过题目ID和目录节点ID关联查询
  779. if ($questionId || $catalogNodesId) {
  780. $kpCodesFromRelation = $this->getKpCodesFromRelation($questionId, $catalogNodesId);
  781. if (!empty($kpCodesFromRelation)) {
  782. return $this->queryKnowledgePointsByCodes($kpCodesFromRelation);
  783. }
  784. }
  785. return [];
  786. }
  787. /**
  788. * 通过 kp_codes 查询知识点信息
  789. */
  790. private function queryKnowledgePointsByCodes(array $kpCodes): array
  791. {
  792. try {
  793. $knowledgePoints = \DB::connection('mysql')
  794. ->table('knowledge_points')
  795. ->whereIn('kp_code', $kpCodes)
  796. ->select(['kp_code', 'name', 'parent_kp_code'])
  797. ->get()
  798. ->toArray();
  799. return array_map(function ($kp) {
  800. return [
  801. 'kp_code' => $kp->kp_code,
  802. 'name' => $kp->name ?? $kp->kp_code,
  803. 'parent_kp_code' => $kp->parent_kp_code,
  804. ];
  805. }, $knowledgePoints);
  806. } catch (\Exception $e) {
  807. Log::warning('通过kp_codes获取知识点信息失败', [
  808. 'kp_codes' => $kpCodes,
  809. 'error' => $e->getMessage()
  810. ]);
  811. return [];
  812. }
  813. }
  814. /**
  815. * 通过 textbook_catalog_nodes_id 关联 textbook_chapter_knowledge_relation 表获取 kp_codes
  816. */
  817. private function getKpCodesFromRelation(?string $questionId, ?int $catalogNodesId): array
  818. {
  819. try {
  820. $query = \DB::connection('mysql')
  821. ->table('textbook_chapter_knowledge_relation')
  822. ->where('is_deleted', 0);
  823. if ($catalogNodesId) {
  824. $query->where('catalog_chapter_id', $catalogNodesId);
  825. } elseif ($questionId) {
  826. // 如果没有catalog_nodes_id,尝试从questions表获取
  827. $question = \DB::connection('mysql')
  828. ->table('questions')
  829. ->where('id', $questionId)
  830. ->first();
  831. if ($question && $question->textbook_catalog_nodes_id) {
  832. $query->where('catalog_chapter_id', $question->textbook_catalog_nodes_id);
  833. }
  834. }
  835. $relations = $query->select('kp_code')->get();
  836. if ($relations->isNotEmpty()) {
  837. Log::debug('通过目录节点关联获取到知识点', [
  838. 'question_id' => $questionId,
  839. 'catalog_nodes_id' => $catalogNodesId,
  840. 'kp_codes' => $relations->pluck('kp_code')->toArray()
  841. ]);
  842. }
  843. return $relations->pluck('kp_code')->toArray();
  844. } catch (\Exception $e) {
  845. Log::warning('通过目录节点关联获取kp_codes失败', [
  846. 'question_id' => $questionId,
  847. 'catalog_nodes_id' => $catalogNodesId,
  848. 'error' => $e->getMessage()
  849. ]);
  850. return [];
  851. }
  852. }
  853. }