MistakeBookService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Support\Facades\Http;
  5. use Illuminate\Support\Facades\Log;
  6. class MistakeBookService
  7. {
  8. protected string $learningAnalyticsBase;
  9. protected string $questionBankBase;
  10. protected int $timeout;
  11. public function __construct(
  12. ?string $learningAnalyticsBase = null,
  13. ?string $questionBankBase = null,
  14. ?int $timeout = null
  15. ) {
  16. $this->learningAnalyticsBase = rtrim(
  17. $learningAnalyticsBase
  18. ?: config('services.learning_analytics.url', env('LEARNING_ANALYTICS_API_BASE', 'http://localhost:5016')),
  19. '/'
  20. );
  21. $this->questionBankBase = rtrim(
  22. $questionBankBase
  23. ?: config('services.question_bank.base_url', env('QUESTION_BANK_API_BASE', 'http://localhost:5015')),
  24. '/'
  25. );
  26. $this->timeout = $timeout ?? (int) config('services.learning_analytics.timeout', 20);
  27. }
  28. /**
  29. * 获取错题列表(支持多维筛选)
  30. */
  31. public function listMistakes(array $params = []): array
  32. {
  33. $query = array_filter([
  34. 'student_id' => $params['student_id'] ?? null,
  35. 'kp_ids' => $this->implodeIfArray($params['kp_ids'] ?? null),
  36. 'skill_ids' => $this->implodeIfArray($params['skill_ids'] ?? null),
  37. 'error_types' => $this->implodeIfArray($params['error_types'] ?? null),
  38. 'time_range' => $params['time_range'] ?? null,
  39. 'start_date' => $params['start_date'] ?? null,
  40. 'end_date' => $params['end_date'] ?? null,
  41. 'page' => $params['page'] ?? 1,
  42. 'per_page' => $params['per_page'] ?? 20,
  43. ], fn ($value) => filled($value));
  44. try {
  45. $response = Http::timeout($this->timeout)
  46. ->get($this->learningAnalyticsBase . '/api/mistake-book', $query);
  47. if ($response->successful()) {
  48. info("MistakeBookService::listMistakes", [$response->json()]);
  49. $body = $response->json();
  50. return is_array($body) ? $body : ['data' => $body];
  51. }
  52. Log::warning('MistakeBook list failed', [
  53. 'status' => $response->status(),
  54. 'body' => $response->body(),
  55. 'query' => $query,
  56. ]);
  57. } catch (\Throwable $e) {
  58. Log::error('MistakeBook list exception', [
  59. 'error' => $e->getMessage(),
  60. 'query' => $query,
  61. ]);
  62. }
  63. return [
  64. 'data' => [],
  65. 'meta' => ['total' => 0, 'page' => 1, 'per_page' => $query['per_page'] ?? 20],
  66. ];
  67. }
  68. /**
  69. * 获取单条错题详情(可选带学生ID保证隔离)
  70. */
  71. public function getMistakeDetail(string $mistakeId, ?string $studentId = null): array
  72. {
  73. $query = array_filter([
  74. 'student_id' => $studentId,
  75. ], fn ($value) => filled($value));
  76. try {
  77. $response = Http::timeout($this->timeout)
  78. ->get($this->learningAnalyticsBase . '/api/mistake-book/' . $mistakeId, $query);
  79. if ($response->successful()) {
  80. $body = $response->json();
  81. return is_array($body) ? $body : [];
  82. }
  83. Log::warning('Mistake detail request failed', [
  84. 'mistake_id' => $mistakeId,
  85. 'status' => $response->status(),
  86. 'body' => $response->body(),
  87. ]);
  88. // 兼容:LearningAnalytics 当前未提供单条详情接口时,从列表中过滤
  89. if ($studentId) {
  90. $fallback = $this->listMistakes([
  91. 'student_id' => $studentId,
  92. 'per_page' => 100, // 兼容后端限制(<=100)
  93. ]);
  94. $matched = collect($fallback['data'] ?? [])->firstWhere('id', (int) $mistakeId);
  95. if ($matched) {
  96. return $matched;
  97. }
  98. }
  99. } catch (\Throwable $e) {
  100. Log::error('Mistake detail request exception', [
  101. 'mistake_id' => $mistakeId,
  102. 'student_id' => $studentId,
  103. 'error' => $e->getMessage(),
  104. ]);
  105. }
  106. return [];
  107. }
  108. /**
  109. * 获取错题统计概要
  110. */
  111. public function summarize(string $studentId): array
  112. {
  113. try {
  114. $response = Http::timeout($this->timeout)
  115. ->get($this->learningAnalyticsBase . '/api/mistake-book/summary', [
  116. 'student_id' => $studentId,
  117. ]);
  118. if ($response->successful()) {
  119. $body = $response->json();
  120. return is_array($body) ? $body : [];
  121. }
  122. Log::warning('MistakeBook summary failed', [
  123. 'status' => $response->status(),
  124. 'body' => $response->body(),
  125. 'student_id' => $studentId,
  126. ]);
  127. } catch (\Throwable $e) {
  128. Log::error('MistakeBook summary exception', [
  129. 'student_id' => $studentId,
  130. 'error' => $e->getMessage(),
  131. ]);
  132. }
  133. // fallback 返回一个空结构,避免前端崩溃
  134. return [
  135. 'total' => 0,
  136. 'this_week' => 0,
  137. 'pending_review' => 0,
  138. 'mastery_rate' => null,
  139. ];
  140. }
  141. /**
  142. * 获取错误模式与推荐路径
  143. */
  144. public function getMistakePatterns(string $studentId): array
  145. {
  146. try {
  147. $response = Http::timeout($this->timeout)
  148. ->get($this->learningAnalyticsBase . '/api/analytics/mistake-pattern', [
  149. 'student_id' => $studentId,
  150. ]);
  151. if ($response->successful()) {
  152. $body = $response->json();
  153. return is_array($body) ? $body : [];
  154. }
  155. Log::warning('Mistake pattern request failed', [
  156. 'status' => $response->status(),
  157. 'body' => $response->body(),
  158. 'student_id' => $studentId,
  159. ]);
  160. } catch (\Throwable $e) {
  161. Log::error('Mistake pattern request exception', [
  162. 'student_id' => $studentId,
  163. 'error' => $e->getMessage(),
  164. ]);
  165. }
  166. return [];
  167. }
  168. /**
  169. * 收藏/取消收藏错题
  170. */
  171. public function toggleFavorite(string $mistakeId, bool $favorite = true): bool
  172. {
  173. try {
  174. $response = Http::timeout($this->timeout)
  175. ->post($this->learningAnalyticsBase . '/api/mistake-book/' . $mistakeId . '/favorite', [
  176. 'favorite' => $favorite,
  177. ]);
  178. return $response->successful();
  179. } catch (\Throwable $e) {
  180. Log::error('Toggle favorite failed', [
  181. 'mistake_id' => $mistakeId,
  182. 'favorite' => $favorite,
  183. 'error' => $e->getMessage(),
  184. ]);
  185. }
  186. return false;
  187. }
  188. /**
  189. * 标记已复习
  190. */
  191. public function markReviewed(string $mistakeId): bool
  192. {
  193. try {
  194. $response = Http::timeout($this->timeout)
  195. ->post($this->learningAnalyticsBase . '/api/mistake-book/' . $mistakeId . '/review');
  196. return $response->successful();
  197. } catch (\Throwable $e) {
  198. Log::error('Mark reviewed failed', [
  199. 'mistake_id' => $mistakeId,
  200. 'error' => $e->getMessage(),
  201. ]);
  202. }
  203. return false;
  204. }
  205. /**
  206. * 添加到重练清单
  207. */
  208. public function addToRetryList(string $mistakeId): bool
  209. {
  210. try {
  211. $response = Http::timeout($this->timeout)
  212. ->post($this->learningAnalyticsBase . '/api/mistake-book/' . $mistakeId . '/retry-list');
  213. return $response->successful();
  214. } catch (\Throwable $e) {
  215. Log::error('Add to retry list failed', [
  216. 'mistake_id' => $mistakeId,
  217. 'error' => $e->getMessage(),
  218. ]);
  219. }
  220. return false;
  221. }
  222. /**
  223. * 基于错题推荐练习题
  224. */
  225. public function recommendPractice(string $studentId, array $kpIds = [], array $skillIds = []): array
  226. {
  227. $payload = array_filter([
  228. 'student_id' => $studentId,
  229. 'kp_ids' => array_values(array_unique($kpIds)),
  230. 'skill_ids' => array_values(array_unique($skillIds)),
  231. ], fn ($value) => $value !== null);
  232. try {
  233. $response = Http::timeout($this->timeout)
  234. ->post($this->questionBankBase . '/api/questions/recommend', $payload);
  235. if ($response->successful()) {
  236. $body = $response->json();
  237. return is_array($body) ? $body : ['data' => $body];
  238. }
  239. Log::warning('Recommend practice failed', [
  240. 'status' => $response->status(),
  241. 'body' => $response->body(),
  242. 'payload' => $payload,
  243. ]);
  244. } catch (\Throwable $e) {
  245. Log::error('Recommend practice exception', [
  246. 'payload' => $payload,
  247. 'error' => $e->getMessage(),
  248. ]);
  249. }
  250. return ['data' => []];
  251. }
  252. /**
  253. * 为学生仪表板提供快照数据
  254. */
  255. public function getPanelSnapshot(string $studentId, int $limit = 5): array
  256. {
  257. $list = $this->listMistakes([
  258. 'student_id' => $studentId,
  259. 'per_page' => $limit,
  260. ]);
  261. $patterns = $this->getMistakePatterns($studentId);
  262. $summary = $this->summarize($studentId);
  263. return [
  264. 'recent' => $list['data'] ?? [],
  265. 'weak_skills' => $patterns['top_skills'] ?? [],
  266. 'weak_kps' => $patterns['top_kps'] ?? [],
  267. 'error_types' => $patterns['error_types'] ?? [],
  268. 'recommend_path' => $patterns['recommend_path'] ?? [],
  269. 'stats' => [
  270. 'total' => $summary['total'] ?? Arr::get($list, 'meta.total', 0),
  271. 'this_week' => $summary['this_week'] ?? null,
  272. 'pending_review' => $summary['pending_review'] ?? null,
  273. 'mastery_rate' => $summary['mastery_rate'] ?? null,
  274. ],
  275. ];
  276. }
  277. private function implodeIfArray($value): ?string
  278. {
  279. if (is_array($value)) {
  280. return implode(',', array_filter($value));
  281. }
  282. return $value;
  283. }
  284. /**
  285. * 获取题目的全体正确率(LearningAnalytics 聚合)
  286. */
  287. public function getQuestionAccuracy(string $questionId): ?float
  288. {
  289. try {
  290. $response = Http::timeout($this->timeout)
  291. ->get($this->learningAnalyticsBase . '/api/analytics/question/' . $questionId . '/accuracy');
  292. if ($response->successful()) {
  293. $body = $response->json();
  294. return isset($body['accuracy']) ? floatval($body['accuracy']) : null;
  295. }
  296. } catch (\Throwable $e) {
  297. Log::warning('Get question accuracy failed', [
  298. 'question_id' => $questionId,
  299. 'error' => $e->getMessage(),
  300. ]);
  301. }
  302. return null;
  303. }
  304. }