MistakeBookService.php 32 KB

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