DiagnosticChapterService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Log;
  4. use App\Models\KnowledgePoint;
  5. use App\Models\StudentKnowledgeMastery;
  6. use App\Models\TextbookCatalog;
  7. use App\Models\TextbookChapterKnowledgeRelation;
  8. class DiagnosticChapterService
  9. {
  10. public function getTextbookKnowledgePointsInOrder(int $textbookId): array
  11. {
  12. $chapters = TextbookCatalog::query()
  13. ->where('textbook_id', $textbookId)
  14. ->where('node_type', 'chapter')
  15. ->orderBy('display_no')
  16. ->orderBy('sort_order')
  17. ->orderBy('id')
  18. ->get();
  19. if ($chapters->isEmpty()) {
  20. Log::warning('DiagnosticChapterService: 未找到章节节点', [
  21. 'textbook_id' => $textbookId,
  22. ]);
  23. return [];
  24. }
  25. $orderedCodes = [];
  26. $seen = [];
  27. foreach ($chapters as $chapter) {
  28. $sectionIds = TextbookCatalog::query()
  29. ->where('parent_id', $chapter->id)
  30. ->where('node_type', 'section')
  31. ->orderBy('display_no')
  32. ->orderBy('sort_order')
  33. ->orderBy('id')
  34. ->pluck('id')
  35. ->toArray();
  36. if (empty($sectionIds)) {
  37. continue;
  38. }
  39. $kpCodes = TextbookChapterKnowledgeRelation::query()
  40. ->whereIn('catalog_chapter_id', $sectionIds)
  41. ->where(function ($q) {
  42. $q->where('is_deleted', 0)->orWhereNull('is_deleted');
  43. })
  44. ->pluck('kp_code')
  45. ->filter()
  46. ->unique()
  47. ->values()
  48. ->toArray();
  49. $kpCodes = $this->expandWithChildKnowledgePoints($kpCodes);
  50. foreach ($kpCodes as $kpCode) {
  51. if (isset($seen[$kpCode])) {
  52. continue;
  53. }
  54. $seen[$kpCode] = true;
  55. $orderedCodes[] = $kpCode;
  56. }
  57. }
  58. Log::info('DiagnosticChapterService: 获取教材知识点顺序列表', [
  59. 'textbook_id' => $textbookId,
  60. 'kp_count' => count($orderedCodes),
  61. ]);
  62. return $orderedCodes;
  63. }
  64. public function getInitialChapterKnowledgePoints(int $textbookId): array
  65. {
  66. $chapter = TextbookCatalog::query()
  67. ->where('textbook_id', $textbookId)
  68. ->where('node_type', 'chapter')
  69. ->orderBy('display_no')
  70. ->orderBy('sort_order')
  71. ->orderBy('id')
  72. ->first();
  73. if (!$chapter) {
  74. Log::warning('DiagnosticChapterService: 未找到章节节点', [
  75. 'textbook_id' => $textbookId,
  76. ]);
  77. return [];
  78. }
  79. $sectionIds = TextbookCatalog::query()
  80. ->where('parent_id', $chapter->id)
  81. ->where('node_type', 'section')
  82. ->orderBy('display_no')
  83. ->orderBy('sort_order')
  84. ->orderBy('id')
  85. ->pluck('id')
  86. ->toArray();
  87. if (empty($sectionIds)) {
  88. Log::warning('DiagnosticChapterService: 章节下未找到section节点', [
  89. 'textbook_id' => $textbookId,
  90. 'chapter_id' => $chapter->id,
  91. ]);
  92. return [];
  93. }
  94. $kpCodes = TextbookChapterKnowledgeRelation::query()
  95. ->whereIn('catalog_chapter_id', $sectionIds)
  96. ->where(function ($q) {
  97. $q->where('is_deleted', 0)->orWhereNull('is_deleted');
  98. })
  99. ->pluck('kp_code')
  100. ->filter()
  101. ->unique()
  102. ->values()
  103. ->toArray();
  104. $kpCodes = $this->expandWithChildKnowledgePoints($kpCodes);
  105. Log::info('DiagnosticChapterService: 获取首章知识点', [
  106. 'textbook_id' => $textbookId,
  107. 'chapter_id' => $chapter->id,
  108. 'section_count' => count($sectionIds),
  109. 'kp_count' => count($kpCodes),
  110. ]);
  111. return [
  112. 'chapter_id' => $chapter->id,
  113. 'section_ids' => $sectionIds,
  114. 'kp_codes' => $kpCodes,
  115. ];
  116. }
  117. public function getFirstUnmasteredChapterKnowledgePoints(int $textbookId, int $studentId, float $threshold = 0.9): array
  118. {
  119. $chapters = TextbookCatalog::query()
  120. ->where('textbook_id', $textbookId)
  121. ->where('node_type', 'chapter')
  122. ->orderBy('display_no')
  123. ->orderBy('sort_order')
  124. ->orderBy('id')
  125. ->get();
  126. if ($chapters->isEmpty()) {
  127. Log::warning('DiagnosticChapterService: 未找到章节节点', [
  128. 'textbook_id' => $textbookId,
  129. ]);
  130. return [];
  131. }
  132. foreach ($chapters as $chapter) {
  133. $sectionIds = TextbookCatalog::query()
  134. ->where('parent_id', $chapter->id)
  135. ->where('node_type', 'section')
  136. ->orderBy('display_no')
  137. ->orderBy('sort_order')
  138. ->orderBy('id')
  139. ->pluck('id')
  140. ->toArray();
  141. if (empty($sectionIds)) {
  142. continue;
  143. }
  144. $kpCodes = TextbookChapterKnowledgeRelation::query()
  145. ->whereIn('catalog_chapter_id', $sectionIds)
  146. ->where(function ($q) {
  147. $q->where('is_deleted', 0)->orWhereNull('is_deleted');
  148. })
  149. ->pluck('kp_code')
  150. ->filter()
  151. ->unique()
  152. ->values()
  153. ->toArray();
  154. $kpCodes = $this->expandWithChildKnowledgePoints($kpCodes);
  155. if (empty($kpCodes)) {
  156. continue;
  157. }
  158. $allMastered = StudentKnowledgeMastery::allAtLeast($studentId, $kpCodes, $threshold);
  159. Log::info('DiagnosticChapterService: 章节掌握度评估', [
  160. 'student_id' => $studentId,
  161. 'textbook_id' => $textbookId,
  162. 'chapter_id' => $chapter->id,
  163. 'section_count' => count($sectionIds),
  164. 'kp_count' => count($kpCodes),
  165. 'all_mastered' => $allMastered,
  166. 'threshold' => $threshold,
  167. ]);
  168. if (!$allMastered) {
  169. return [
  170. 'chapter_id' => $chapter->id,
  171. 'section_ids' => $sectionIds,
  172. 'kp_codes' => $kpCodes,
  173. 'all_mastered' => $allMastered,
  174. ];
  175. }
  176. }
  177. Log::info('DiagnosticChapterService: 所有章节均达到掌握度阈值', [
  178. 'student_id' => $studentId,
  179. 'textbook_id' => $textbookId,
  180. 'threshold' => $threshold,
  181. ]);
  182. return [];
  183. }
  184. private function expandWithChildKnowledgePoints(array $kpCodes): array
  185. {
  186. if (empty($kpCodes)) {
  187. return [];
  188. }
  189. $baseCodes = collect($kpCodes)->filter()->values()->all();
  190. $children = KnowledgePoint::query()
  191. ->whereIn('parent_kp_code', $baseCodes)
  192. ->orderBy('kp_code')
  193. ->get(['parent_kp_code', 'kp_code']);
  194. $childrenMap = [];
  195. foreach ($children as $child) {
  196. $childrenMap[$child->parent_kp_code][] = $child->kp_code;
  197. }
  198. $ordered = [];
  199. $seen = [];
  200. foreach ($baseCodes as $kpCode) {
  201. if (!isset($seen[$kpCode])) {
  202. $seen[$kpCode] = true;
  203. $ordered[] = $kpCode;
  204. }
  205. foreach ($childrenMap[$kpCode] ?? [] as $childCode) {
  206. if (isset($seen[$childCode])) {
  207. continue;
  208. }
  209. $seen[$childCode] = true;
  210. $ordered[] = $childCode;
  211. }
  212. }
  213. return $ordered;
  214. }
  215. // ========== 以下是新增的方法(不扩展子知识点)==========
  216. /**
  217. * 获取章节的知识点(不扩展子知识点)
  218. * 直接返回 section 绑定的知识点
  219. */
  220. public function getChapterKnowledgePointsSimple(int $chapterId): array
  221. {
  222. $sectionIds = TextbookCatalog::query()
  223. ->where('parent_id', $chapterId)
  224. ->where('node_type', 'section')
  225. ->orderBy('display_no')
  226. ->orderBy('sort_order')
  227. ->orderBy('id')
  228. ->pluck('id')
  229. ->toArray();
  230. if (empty($sectionIds)) {
  231. return [
  232. 'section_ids' => [],
  233. 'kp_codes' => [],
  234. ];
  235. }
  236. $kpCodes = TextbookChapterKnowledgeRelation::query()
  237. ->whereIn('catalog_chapter_id', $sectionIds)
  238. ->where(function ($q) {
  239. $q->where('is_deleted', 0)->orWhereNull('is_deleted');
  240. })
  241. ->pluck('kp_code')
  242. ->filter()
  243. ->unique()
  244. ->values()
  245. ->toArray();
  246. // 不扩展子知识点,直接返回
  247. return [
  248. 'section_ids' => $sectionIds,
  249. 'kp_codes' => $kpCodes,
  250. ];
  251. }
  252. /**
  253. * 判断章节是否已经摸底过
  254. */
  255. public function hasChapterDiagnostic(int $studentId, int $chapterId): bool
  256. {
  257. return \App\Models\Paper::query()
  258. ->where('student_id', $studentId)
  259. ->where('paper_type', 0) // 摸底类型
  260. ->where('diagnostic_chapter_id', $chapterId)
  261. ->exists();
  262. }
  263. /**
  264. * 获取第一个未摸底的章节
  265. * 用于章节摸底流程
  266. */
  267. public function getFirstUndiagnosedChapter(int $textbookId, int $studentId): ?array
  268. {
  269. $chapters = TextbookCatalog::query()
  270. ->where('textbook_id', $textbookId)
  271. ->where('node_type', 'chapter')
  272. ->orderBy('display_no')
  273. ->orderBy('sort_order')
  274. ->orderBy('id')
  275. ->get();
  276. if ($chapters->isEmpty()) {
  277. return null;
  278. }
  279. foreach ($chapters as $chapter) {
  280. // 检查是否已摸底
  281. if (!$this->hasChapterDiagnostic($studentId, $chapter->id)) {
  282. $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
  283. // 过滤掉没有题目的知识点
  284. $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);
  285. if (empty($kpCodesWithQuestions)) {
  286. // 这个章节没有题目,跳过
  287. continue;
  288. }
  289. Log::info('DiagnosticChapterService: 找到第一个未摸底的章节', [
  290. 'textbook_id' => $textbookId,
  291. 'student_id' => $studentId,
  292. 'chapter_id' => $chapter->id,
  293. 'chapter_name' => $chapter->name ?? '',
  294. 'kp_count' => count($kpCodesWithQuestions),
  295. ]);
  296. return [
  297. 'chapter_id' => $chapter->id,
  298. 'chapter_name' => $chapter->name ?? '',
  299. 'section_ids' => $chapterData['section_ids'],
  300. 'kp_codes' => $kpCodesWithQuestions,
  301. ];
  302. }
  303. }
  304. // 所有章节都已摸底,返回第一章(重新开始)
  305. $firstChapter = $chapters->first();
  306. $chapterData = $this->getChapterKnowledgePointsSimple($firstChapter->id);
  307. $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);
  308. Log::info('DiagnosticChapterService: 所有章节都已摸底,返回第一章', [
  309. 'textbook_id' => $textbookId,
  310. 'student_id' => $studentId,
  311. 'chapter_id' => $firstChapter->id,
  312. ]);
  313. return [
  314. 'chapter_id' => $firstChapter->id,
  315. 'chapter_name' => $firstChapter->name ?? '',
  316. 'section_ids' => $chapterData['section_ids'],
  317. 'kp_codes' => $kpCodesWithQuestions,
  318. 'is_restart' => true, // 标记是重新开始
  319. ];
  320. }
  321. /**
  322. * 获取当前应该学习的章节(第一个有未达标知识点的章节)
  323. * 用于智能组卷流程
  324. */
  325. public function getCurrentLearningChapter(int $textbookId, int $studentId, float $threshold = 0.9): ?array
  326. {
  327. $chapters = TextbookCatalog::query()
  328. ->where('textbook_id', $textbookId)
  329. ->where('node_type', 'chapter')
  330. ->orderBy('display_no')
  331. ->orderBy('sort_order')
  332. ->orderBy('id')
  333. ->get();
  334. if ($chapters->isEmpty()) {
  335. return null;
  336. }
  337. foreach ($chapters as $chapter) {
  338. $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
  339. $kpCodes = $chapterData['kp_codes'];
  340. if (empty($kpCodes)) {
  341. continue;
  342. }
  343. // 使用新方法判断是否达标(跳过无题知识点)
  344. $allMastered = StudentKnowledgeMastery::allAtLeastSkipNoQuestions($studentId, $kpCodes, $threshold);
  345. if (!$allMastered) {
  346. // 检查是否已摸底
  347. $hasDiagnostic = $this->hasChapterDiagnostic($studentId, $chapter->id);
  348. Log::info('DiagnosticChapterService: 找到当前学习章节', [
  349. 'textbook_id' => $textbookId,
  350. 'student_id' => $studentId,
  351. 'student_id_type' => gettype($studentId),
  352. 'chapter_id' => $chapter->id,
  353. 'chapter_name' => $chapter->name ?? '',
  354. 'has_diagnostic' => $hasDiagnostic,
  355. 'kp_codes' => $kpCodes, // 显示实际的知识点列表
  356. 'kp_count' => count($kpCodes),
  357. ]);
  358. return [
  359. 'chapter_id' => $chapter->id,
  360. 'chapter_name' => $chapter->name ?? '',
  361. 'section_ids' => $chapterData['section_ids'],
  362. 'kp_codes' => $kpCodes,
  363. 'has_diagnostic' => $hasDiagnostic,
  364. ];
  365. }
  366. }
  367. // 所有章节都达标
  368. Log::info('DiagnosticChapterService: 所有章节都达标', [
  369. 'textbook_id' => $textbookId,
  370. 'student_id' => $studentId,
  371. ]);
  372. return null;
  373. }
  374. /**
  375. * 获取下一个章节
  376. */
  377. public function getNextChapter(int $textbookId, int $currentChapterId): ?array
  378. {
  379. $chapters = TextbookCatalog::query()
  380. ->where('textbook_id', $textbookId)
  381. ->where('node_type', 'chapter')
  382. ->orderBy('display_no')
  383. ->orderBy('sort_order')
  384. ->orderBy('id')
  385. ->get();
  386. $foundCurrent = false;
  387. foreach ($chapters as $chapter) {
  388. if ($foundCurrent) {
  389. $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
  390. $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);
  391. if (!empty($kpCodesWithQuestions)) {
  392. return [
  393. 'chapter_id' => $chapter->id,
  394. 'chapter_name' => $chapter->name ?? '',
  395. 'section_ids' => $chapterData['section_ids'],
  396. 'kp_codes' => $kpCodesWithQuestions,
  397. ];
  398. }
  399. }
  400. if ($chapter->id === $currentChapterId) {
  401. $foundCurrent = true;
  402. }
  403. }
  404. return null; // 没有下一章
  405. }
  406. /**
  407. * 过滤出有题目的知识点
  408. */
  409. public function filterKpCodesWithQuestions(array $kpCodes): array
  410. {
  411. if (empty($kpCodes)) {
  412. return [];
  413. }
  414. $kpCodesWithQuestions = \App\Models\Question::query()
  415. ->whereIn('kp_code', $kpCodes)
  416. ->distinct()
  417. ->pluck('kp_code')
  418. ->toArray();
  419. // 保持原有顺序
  420. return array_values(array_intersect($kpCodes, $kpCodesWithQuestions));
  421. }
  422. /**
  423. * 按顺序获取未达标的知识点(用于智能组卷)
  424. *
  425. * @param int $studentId 学生ID
  426. * @param array $kpCodes 知识点列表(按顺序)
  427. * @param float $threshold 达标阈值
  428. * @param int $maxCount 最多返回几个知识点
  429. * @param int $minQuestions 每个知识点最少需要的题目数
  430. * @return array 未达标的知识点列表
  431. */
  432. public function getUnmasteredKpCodesInOrder(
  433. int $studentId,
  434. array $kpCodes,
  435. float $threshold = 0.9,
  436. int $maxCount = 2,
  437. int $minQuestions = 20
  438. ): array {
  439. if (empty($kpCodes)) {
  440. return [];
  441. }
  442. // 获取掌握度(使用 DB::table 避免 Eloquent accessor 把数字转成文字标签)
  443. // 【新增】同时获取 direct_mastery_level 和 mastery_level,判断时优先使用 direct_mastery_level
  444. $masteryRecords = \Illuminate\Support\Facades\DB::table('student_knowledge_mastery')
  445. ->where('student_id', $studentId)
  446. ->whereIn('kp_code', $kpCodes)
  447. ->get(['kp_code', 'mastery_level', 'direct_mastery_level'])
  448. ->keyBy('kp_code');
  449. // 构建有效掌握度映射:优先使用 direct_mastery_level,其次使用 mastery_level
  450. $levels = [];
  451. foreach ($masteryRecords as $kpCode => $record) {
  452. // 优先使用 direct_mastery_level(直接学习掌握度)
  453. if ($record->direct_mastery_level !== null) {
  454. $levels[$kpCode] = (float) $record->direct_mastery_level;
  455. } else {
  456. $levels[$kpCode] = (float) $record->mastery_level;
  457. }
  458. }
  459. // 【调试】记录查询到的掌握度
  460. Log::info('DiagnosticChapterService: 查询掌握度结果', [
  461. 'student_id' => $studentId,
  462. 'student_id_type' => gettype($studentId),
  463. 'input_kp_codes' => $kpCodes,
  464. 'found_levels' => $levels,
  465. 'raw_records' => $masteryRecords->toArray(),
  466. ]);
  467. // 获取每个知识点的题目数量
  468. $questionCounts = \App\Models\Question::query()
  469. ->whereIn('kp_code', $kpCodes)
  470. ->selectRaw('kp_code, COUNT(*) as count')
  471. ->groupBy('kp_code')
  472. ->pluck('count', 'kp_code')
  473. ->toArray();
  474. $result = [];
  475. $totalQuestions = 0;
  476. foreach ($kpCodes as $kpCode) {
  477. // 跳过没有题目的知识点
  478. $count = $questionCounts[$kpCode] ?? 0;
  479. if ($count === 0) {
  480. continue;
  481. }
  482. // 检查是否达标
  483. $level = isset($levels[$kpCode]) ? (float) $levels[$kpCode] : 0.0;
  484. $isMastered = $level >= $threshold;
  485. Log::info("DiagnosticChapterService: 检查知识点", [
  486. 'kp_code' => $kpCode,
  487. 'level' => $level,
  488. 'threshold' => $threshold,
  489. 'is_mastered' => $isMastered,
  490. 'level_found_in_db' => isset($levels[$kpCode]),
  491. ]);
  492. if ($level >= $threshold) {
  493. continue;
  494. }
  495. // 添加到结果
  496. $result[] = $kpCode;
  497. $totalQuestions += $count;
  498. // 检查是否达到最大数量
  499. if (count($result) >= $maxCount) {
  500. break;
  501. }
  502. // 检查题目数量是否足够
  503. if ($totalQuestions >= $minQuestions) {
  504. break;
  505. }
  506. }
  507. Log::info('DiagnosticChapterService: 获取未达标知识点', [
  508. 'student_id' => $studentId,
  509. 'input_kp_codes' => $kpCodes,
  510. 'result_kp_codes' => $result,
  511. 'levels_found' => $levels,
  512. 'total_questions' => $totalQuestions,
  513. 'threshold' => $threshold,
  514. ]);
  515. return $result;
  516. }
  517. }