DiagnosticChapterService.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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('sort_order')
  16. ->orderBy('display_no')
  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('sort_order')
  32. ->orderBy('display_no')
  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('sort_order')
  70. ->orderBy('display_no')
  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('sort_order')
  83. ->orderBy('display_no')
  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('sort_order')
  123. ->orderBy('display_no')
  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('sort_order')
  137. ->orderBy('display_no')
  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('sort_order')
  226. ->orderBy('display_no')
  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. * - 传入 targetChapterIds: 先在指定章节内按顺序找第一个未摸底章节;
  266. * 若指定章节都已摸底,则在该章节所属教材内继续按顺序找未摸底章节。
  267. * - 未传 targetChapterIds: 保持原逻辑,找教材内第一个未摸底章节。
  268. */
  269. public function getFirstUndiagnosedChapter(int $textbookId, int $studentId, ?array $targetChapterIds = null): ?array
  270. {
  271. $targetChapterIds = is_array($targetChapterIds)
  272. ? array_values(array_unique(array_filter(array_map('intval', $targetChapterIds), fn ($id) => $id > 0)))
  273. : [];
  274. $payloadCache = [];
  275. // 指定章节摸底流程:以传入章节为锚点。
  276. if (!empty($targetChapterIds)) {
  277. // 兜底:允许传入 section/subsection,自动向上映射到 chapter
  278. $targetChapterIds = $this->normalizeToChapterIds($targetChapterIds);
  279. if (empty($targetChapterIds)) {
  280. Log::warning('DiagnosticChapterService: 指定章节参数无可解析chapter,终止指定章节摸底', [
  281. 'textbook_id' => $textbookId,
  282. 'student_id' => $studentId,
  283. ]);
  284. return null;
  285. }
  286. // 保持传入顺序,首个有效章作为锚点
  287. $chapterMap = TextbookCatalog::query()
  288. ->whereIn('id', $targetChapterIds)
  289. ->where('node_type', 'chapter')
  290. ->get(['id', 'textbook_id', 'title', 'parent_id', 'node_type', 'sort_order', 'display_no'])
  291. ->keyBy('id');
  292. $anchorChapter = null;
  293. foreach ($targetChapterIds as $chapterId) {
  294. $candidate = $chapterMap->get($chapterId);
  295. if ($candidate) {
  296. $anchorChapter = $candidate;
  297. break;
  298. }
  299. }
  300. if (!$anchorChapter) {
  301. Log::warning('DiagnosticChapterService: 指定章节未找到有效chapter节点', [
  302. 'student_id' => $studentId,
  303. 'target_chapter_ids' => $targetChapterIds,
  304. ]);
  305. return null;
  306. }
  307. $anchorTextbookId = (int) ($anchorChapter->textbook_id ?? $textbookId);
  308. $chaptersInTextbook = TextbookCatalog::query()
  309. ->where('textbook_id', $anchorTextbookId)
  310. ->where('node_type', 'chapter')
  311. ->orderBy('sort_order')
  312. ->orderBy('display_no')
  313. ->orderBy('id')
  314. ->get();
  315. if ($chaptersInTextbook->isEmpty()) {
  316. Log::warning('DiagnosticChapterService: 指定章节所属教材无章节', [
  317. 'textbook_id' => $anchorTextbookId,
  318. 'student_id' => $studentId,
  319. 'target_chapter_ids' => $targetChapterIds,
  320. ]);
  321. return null;
  322. }
  323. $chaptersInTextbookIds = $chaptersInTextbook->pluck('id')->map(fn ($id) => (int) $id)->all();
  324. $diagnosedSet = $this->getDiagnosedChapterIdSet($studentId, $chaptersInTextbookIds);
  325. // 全教材都摸底:输入什么章就输出什么章(is_restart=true)
  326. $allDiagnosed = true;
  327. foreach ($chaptersInTextbookIds as $chapterId) {
  328. if (!isset($diagnosedSet[$chapterId])) {
  329. $allDiagnosed = false;
  330. break;
  331. }
  332. }
  333. $anchorPayload = $this->buildChapterPayload((int) $anchorChapter->id, $anchorChapter, $payloadCache);
  334. if ($allDiagnosed) {
  335. if ($anchorPayload !== null) {
  336. Log::info('DiagnosticChapterService: 全教材已摸底,返回输入锚点章节并重启', [
  337. 'textbook_id' => $anchorTextbookId,
  338. 'student_id' => $studentId,
  339. 'anchor_chapter_id' => $anchorChapter->id,
  340. ]);
  341. $anchorPayload['is_restart'] = true;
  342. return $anchorPayload;
  343. }
  344. // 兜底返回教材第一章(is_restart=true)
  345. $firstChapter = $chaptersInTextbook->first();
  346. if ($firstChapter) {
  347. $firstPayload = $this->buildChapterPayload((int) $firstChapter->id, $firstChapter, $payloadCache);
  348. if ($firstPayload !== null) {
  349. $firstPayload['is_restart'] = true;
  350. Log::info('DiagnosticChapterService: 全教材已摸底且输入章无有效题,兜底第一章重启', [
  351. 'textbook_id' => $anchorTextbookId,
  352. 'student_id' => $studentId,
  353. 'chapter_id' => $firstChapter->id,
  354. ]);
  355. return $firstPayload;
  356. }
  357. }
  358. return null;
  359. }
  360. // 未全教材摸底:优先检查锚点章,未达标就仍以该章摸底
  361. if ($anchorPayload !== null) {
  362. $allMastered = StudentKnowledgeMastery::allAtLeastSkipNoQuestions(
  363. $studentId,
  364. $anchorPayload['kp_codes'],
  365. 0.9
  366. );
  367. if (!$allMastered) {
  368. Log::info('DiagnosticChapterService: 锚点章节未达标,继续以该章摸底', [
  369. 'textbook_id' => $anchorTextbookId,
  370. 'student_id' => $studentId,
  371. 'anchor_chapter_id' => $anchorChapter->id,
  372. 'kp_count' => count($anchorPayload['kp_codes']),
  373. ]);
  374. return $anchorPayload;
  375. }
  376. }
  377. // 锚点达标后,按教材顺序向后找第一个未摸底章节
  378. $anchorIndex = $chaptersInTextbook->search(fn ($c) => (int) $c->id === (int) $anchorChapter->id);
  379. $anchorIndex = $anchorIndex === false ? 0 : (int) $anchorIndex;
  380. for ($i = $anchorIndex + 1; $i < $chaptersInTextbook->count(); $i++) {
  381. $chapter = $chaptersInTextbook[$i];
  382. if (isset($diagnosedSet[(int) $chapter->id])) {
  383. continue;
  384. }
  385. $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
  386. if ($payload === null) {
  387. continue;
  388. }
  389. Log::info('DiagnosticChapterService: 锚点章节已达标,向后推进到未摸底章节', [
  390. 'textbook_id' => $anchorTextbookId,
  391. 'student_id' => $studentId,
  392. 'anchor_chapter_id' => $anchorChapter->id,
  393. 'next_chapter_id' => $chapter->id,
  394. ]);
  395. return $payload;
  396. }
  397. // 若后续没有可用未摸底章,再从教材起点补找未摸底章
  398. for ($i = 0; $i <= $anchorIndex; $i++) {
  399. $chapter = $chaptersInTextbook[$i];
  400. if (isset($diagnosedSet[(int) $chapter->id])) {
  401. continue;
  402. }
  403. $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
  404. if ($payload !== null) {
  405. Log::info('DiagnosticChapterService: 锚点后无未摸底章,回到教材前序未摸底章节', [
  406. 'textbook_id' => $anchorTextbookId,
  407. 'student_id' => $studentId,
  408. 'anchor_chapter_id' => $anchorChapter->id,
  409. 'fallback_chapter_id' => $chapter->id,
  410. ]);
  411. return $payload;
  412. }
  413. }
  414. // 理论兜底:返回输入章并重启
  415. if ($anchorPayload !== null) {
  416. $anchorPayload['is_restart'] = true;
  417. Log::info('DiagnosticChapterService: 指定章节流程兜底返回输入章节重启', [
  418. 'textbook_id' => $anchorTextbookId,
  419. 'student_id' => $studentId,
  420. 'anchor_chapter_id' => $anchorChapter->id,
  421. ]);
  422. return $anchorPayload;
  423. }
  424. return null;
  425. }
  426. $chapters = TextbookCatalog::query()
  427. ->where('textbook_id', $textbookId)
  428. ->where('node_type', 'chapter')
  429. ->orderBy('sort_order')
  430. ->orderBy('display_no')
  431. ->orderBy('id')
  432. ->get();
  433. if ($chapters->isEmpty()) {
  434. return null;
  435. }
  436. $chapterIds = $chapters->pluck('id')->map(fn ($id) => (int) $id)->all();
  437. $diagnosedSet = $this->getDiagnosedChapterIdSet($studentId, $chapterIds);
  438. foreach ($chapters as $chapter) {
  439. // 检查是否已摸底
  440. if (!isset($diagnosedSet[(int) $chapter->id])) {
  441. $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
  442. if ($payload === null) {
  443. // 这个章节没有题目,跳过
  444. continue;
  445. }
  446. Log::info('DiagnosticChapterService: 找到第一个未摸底的章节', [
  447. 'textbook_id' => $textbookId,
  448. 'student_id' => $studentId,
  449. 'chapter_id' => $chapter->id,
  450. 'chapter_name' => $chapter->name ?? $chapter->title ?? '',
  451. 'kp_count' => count($payload['kp_codes']),
  452. ]);
  453. return $payload;
  454. }
  455. }
  456. // 所有章节都已摸底,返回第一章(重新开始)
  457. $firstChapter = $chapters->first();
  458. $firstPayload = $firstChapter ? $this->buildChapterPayload((int) $firstChapter->id, $firstChapter, $payloadCache) : null;
  459. if ($firstPayload === null) {
  460. return null;
  461. }
  462. Log::info('DiagnosticChapterService: 所有章节都已摸底,返回第一章', [
  463. 'textbook_id' => $textbookId,
  464. 'student_id' => $studentId,
  465. 'chapter_id' => $firstChapter->id,
  466. ]);
  467. $firstPayload['is_restart'] = true;
  468. return $firstPayload; // 标记是重新开始
  469. }
  470. /**
  471. * 将传入节点ID(chapter/section/subsection)统一映射为所属 chapter ID 列表。
  472. * 保持传入顺序去重,忽略不属于当前教材的节点。
  473. *
  474. * @param array<int> $nodeIds
  475. * @return array<int>
  476. */
  477. private function normalizeToChapterIds(array $nodeIds): array
  478. {
  479. if (empty($nodeIds)) {
  480. return [];
  481. }
  482. $chapterIds = [];
  483. $seen = [];
  484. foreach ($nodeIds as $nodeId) {
  485. $currentId = (int) $nodeId;
  486. if ($currentId <= 0) {
  487. continue;
  488. }
  489. $guard = 0;
  490. while ($currentId > 0 && $guard++ < 10) {
  491. $node = TextbookCatalog::query()
  492. ->where('id', $currentId)
  493. ->first(['id', 'parent_id', 'node_type']);
  494. if (!$node) {
  495. break;
  496. }
  497. if ($node->node_type === 'chapter') {
  498. if (!isset($seen[$node->id])) {
  499. $seen[$node->id] = true;
  500. $chapterIds[] = (int) $node->id;
  501. }
  502. break;
  503. }
  504. $currentId = (int) ($node->parent_id ?? 0);
  505. }
  506. }
  507. if (count($chapterIds) !== count($nodeIds)) {
  508. Log::info('DiagnosticChapterService: 章节参数已自动映射到chapter节点', [
  509. 'input_ids' => $nodeIds,
  510. 'resolved_chapter_ids' => $chapterIds,
  511. ]);
  512. }
  513. return $chapterIds;
  514. }
  515. /**
  516. * 根据 chapter_id 生成摸底章节载荷,若章节无可用题目知识点则返回 null。
  517. */
  518. private function buildChapterPayload(int $chapterId, $chapter = null, ?array &$payloadCache = null): ?array
  519. {
  520. if (is_array($payloadCache) && array_key_exists($chapterId, $payloadCache)) {
  521. return $payloadCache[$chapterId];
  522. }
  523. if ($chapter === null) {
  524. $chapter = TextbookCatalog::query()
  525. ->where('id', $chapterId)
  526. ->where('node_type', 'chapter')
  527. ->first(['id', 'title']);
  528. }
  529. if (!$chapter) {
  530. if (is_array($payloadCache)) {
  531. $payloadCache[$chapterId] = null;
  532. }
  533. return null;
  534. }
  535. $chapterData = $this->getChapterKnowledgePointsSimple($chapterId);
  536. $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);
  537. if (empty($kpCodesWithQuestions)) {
  538. if (is_array($payloadCache)) {
  539. $payloadCache[$chapterId] = null;
  540. }
  541. return null;
  542. }
  543. $payload = [
  544. 'chapter_id' => $chapterId,
  545. 'chapter_name' => $chapter->name ?? $chapter->title ?? '',
  546. 'section_ids' => $chapterData['section_ids'],
  547. 'kp_codes' => $kpCodesWithQuestions,
  548. ];
  549. if (is_array($payloadCache)) {
  550. $payloadCache[$chapterId] = $payload;
  551. }
  552. return $payload;
  553. }
  554. /**
  555. * 批量获取学生在指定章节中的已摸底集合,避免循环 exists N+1 查询。
  556. *
  557. * @param array<int> $chapterIds
  558. * @return array<int, bool>
  559. */
  560. private function getDiagnosedChapterIdSet(int $studentId, array $chapterIds): array
  561. {
  562. $chapterIds = array_values(array_unique(array_filter(array_map('intval', $chapterIds), fn ($id) => $id > 0)));
  563. if (empty($chapterIds)) {
  564. return [];
  565. }
  566. $ids = \App\Models\Paper::query()
  567. ->where('student_id', $studentId)
  568. ->where('paper_type', 0)
  569. ->whereIn('diagnostic_chapter_id', $chapterIds)
  570. ->pluck('diagnostic_chapter_id')
  571. ->map(fn ($id) => (int) $id)
  572. ->unique()
  573. ->values()
  574. ->all();
  575. $set = [];
  576. foreach ($ids as $id) {
  577. $set[$id] = true;
  578. }
  579. return $set;
  580. }
  581. /**
  582. * 获取当前应该学习的章节(第一个有未达标知识点的章节)
  583. * 用于智能组卷流程
  584. */
  585. public function getCurrentLearningChapter(int $textbookId, int $studentId, float $threshold = 0.9): ?array
  586. {
  587. $chapters = TextbookCatalog::query()
  588. ->where('textbook_id', $textbookId)
  589. ->where('node_type', 'chapter')
  590. ->orderBy('sort_order')
  591. ->orderBy('display_no')
  592. ->orderBy('id')
  593. ->get();
  594. if ($chapters->isEmpty()) {
  595. return null;
  596. }
  597. foreach ($chapters as $chapter) {
  598. $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
  599. $kpCodes = $chapterData['kp_codes'];
  600. if (empty($kpCodes)) {
  601. continue;
  602. }
  603. // 使用新方法判断是否达标(跳过无题知识点)
  604. $allMastered = StudentKnowledgeMastery::allAtLeastSkipNoQuestions($studentId, $kpCodes, $threshold);
  605. if (!$allMastered) {
  606. // 检查是否已摸底
  607. $hasDiagnostic = $this->hasChapterDiagnostic($studentId, $chapter->id);
  608. Log::info('DiagnosticChapterService: 找到当前学习章节', [
  609. 'textbook_id' => $textbookId,
  610. 'student_id' => $studentId,
  611. 'student_id_type' => gettype($studentId),
  612. 'chapter_id' => $chapter->id,
  613. 'chapter_name' => $chapter->name ?? '',
  614. 'has_diagnostic' => $hasDiagnostic,
  615. 'kp_codes' => $kpCodes, // 显示实际的知识点列表
  616. 'kp_count' => count($kpCodes),
  617. ]);
  618. return [
  619. 'chapter_id' => $chapter->id,
  620. 'chapter_name' => $chapter->name ?? '',
  621. 'section_ids' => $chapterData['section_ids'],
  622. 'kp_codes' => $kpCodes,
  623. 'has_diagnostic' => $hasDiagnostic,
  624. ];
  625. }
  626. }
  627. // 所有章节都达标
  628. Log::info('DiagnosticChapterService: 所有章节都达标', [
  629. 'textbook_id' => $textbookId,
  630. 'student_id' => $studentId,
  631. ]);
  632. return null;
  633. }
  634. /**
  635. * 获取下一个章节
  636. */
  637. public function getNextChapter(int $textbookId, int $currentChapterId): ?array
  638. {
  639. $chapters = TextbookCatalog::query()
  640. ->where('textbook_id', $textbookId)
  641. ->where('node_type', 'chapter')
  642. ->orderBy('sort_order')
  643. ->orderBy('display_no')
  644. ->orderBy('id')
  645. ->get();
  646. $foundCurrent = false;
  647. foreach ($chapters as $chapter) {
  648. if ($foundCurrent) {
  649. $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
  650. $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);
  651. if (!empty($kpCodesWithQuestions)) {
  652. return [
  653. 'chapter_id' => $chapter->id,
  654. 'chapter_name' => $chapter->name ?? '',
  655. 'section_ids' => $chapterData['section_ids'],
  656. 'kp_codes' => $kpCodesWithQuestions,
  657. ];
  658. }
  659. }
  660. if ($chapter->id === $currentChapterId) {
  661. $foundCurrent = true;
  662. }
  663. }
  664. return null; // 没有下一章
  665. }
  666. /**
  667. * 过滤出有题目的知识点
  668. */
  669. public function filterKpCodesWithQuestions(array $kpCodes): array
  670. {
  671. if (empty($kpCodes)) {
  672. return [];
  673. }
  674. $kpCodesWithQuestions = \App\Models\Question::query()
  675. ->where('audit_status', 0) // 只获取审核通过的题目
  676. ->whereIn('kp_code', $kpCodes)
  677. ->distinct()
  678. ->pluck('kp_code')
  679. ->toArray();
  680. // 保持原有顺序
  681. return array_values(array_intersect($kpCodes, $kpCodesWithQuestions));
  682. }
  683. /**
  684. * 按顺序获取未达标的知识点(用于智能组卷)
  685. *
  686. * @param int $studentId 学生ID
  687. * @param array $kpCodes 知识点列表(按顺序)
  688. * @param float $threshold 达标阈值
  689. * @param int $maxCount 最多返回几个知识点
  690. * @param int $minQuestions 每个知识点最少需要的题目数
  691. * @return array 未达标的知识点列表
  692. */
  693. public function getUnmasteredKpCodesInOrder(
  694. int $studentId,
  695. array $kpCodes,
  696. float $threshold = 0.9,
  697. int $maxCount = 2,
  698. int $minQuestions = 20
  699. ): array {
  700. if (empty($kpCodes)) {
  701. return [];
  702. }
  703. // 获取掌握度(使用 DB::table 避免 Eloquent accessor 把数字转成文字标签)
  704. // 【新增】同时获取 direct_mastery_level 和 mastery_level,判断时优先使用 direct_mastery_level
  705. $masteryRecords = \Illuminate\Support\Facades\DB::table('student_knowledge_mastery')
  706. ->where('student_id', $studentId)
  707. ->whereIn('kp_code', $kpCodes)
  708. ->get(['kp_code', 'mastery_level', 'direct_mastery_level'])
  709. ->keyBy('kp_code');
  710. // 构建有效掌握度映射:取 direct_mastery_level 和 mastery_level 的最大值
  711. // 避免"学了之后反而从达标变成未达标"的问题
  712. $levels = [];
  713. foreach ($masteryRecords as $kpCode => $record) {
  714. $direct = $record->direct_mastery_level;
  715. $mastery = (float) $record->mastery_level;
  716. if ($direct !== null) {
  717. // 取两者最大值:直接学习达标或聚合值达标,都算达标
  718. $levels[$kpCode] = max((float) $direct, $mastery);
  719. } else {
  720. $levels[$kpCode] = $mastery;
  721. }
  722. }
  723. // 【调试】记录查询到的掌握度
  724. Log::info('DiagnosticChapterService: 查询掌握度结果', [
  725. 'student_id' => $studentId,
  726. 'student_id_type' => gettype($studentId),
  727. 'input_kp_codes' => $kpCodes,
  728. 'found_levels' => $levels,
  729. 'raw_records' => $masteryRecords->toArray(),
  730. ]);
  731. // 获取每个知识点的题目数量(只统计审核通过的题目)
  732. $questionCounts = \App\Models\Question::query()
  733. ->where('audit_status', 0) // 只获取审核通过的题目
  734. ->whereIn('kp_code', $kpCodes)
  735. ->selectRaw('kp_code, COUNT(*) as count')
  736. ->groupBy('kp_code')
  737. ->pluck('count', 'kp_code')
  738. ->toArray();
  739. $result = [];
  740. $totalQuestions = 0;
  741. foreach ($kpCodes as $kpCode) {
  742. // 跳过没有题目的知识点
  743. $count = $questionCounts[$kpCode] ?? 0;
  744. if ($count === 0) {
  745. continue;
  746. }
  747. // 检查是否达标
  748. $level = isset($levels[$kpCode]) ? (float) $levels[$kpCode] : 0.0;
  749. $isMastered = $level >= $threshold;
  750. Log::info("DiagnosticChapterService: 检查知识点", [
  751. 'kp_code' => $kpCode,
  752. 'level' => $level,
  753. 'threshold' => $threshold,
  754. 'is_mastered' => $isMastered,
  755. 'level_found_in_db' => isset($levels[$kpCode]),
  756. ]);
  757. if ($level >= $threshold) {
  758. continue;
  759. }
  760. // 添加到结果
  761. $result[] = $kpCode;
  762. $totalQuestions += $count;
  763. // 检查是否达到最大数量
  764. if (count($result) >= $maxCount) {
  765. break;
  766. }
  767. // 检查题目数量是否足够
  768. if ($totalQuestions >= $minQuestions) {
  769. break;
  770. }
  771. }
  772. Log::info('DiagnosticChapterService: 获取未达标知识点', [
  773. 'student_id' => $studentId,
  774. 'input_kp_codes' => $kpCodes,
  775. 'result_kp_codes' => $result,
  776. 'levels_found' => $levels,
  777. 'total_questions' => $totalQuestions,
  778. 'threshold' => $threshold,
  779. ]);
  780. return $result;
  781. }
  782. }