DiagnosticChapterService.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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. $widePayload = $this->buildTextbookWideChapterPayload($chaptersInTextbook);
  359. if ($widePayload !== null) {
  360. $widePayload['is_restart'] = true;
  361. Log::info('DiagnosticChapterService: 全教材已摸底且单章无有效题,合并全教材知识点重启', [
  362. 'textbook_id' => $anchorTextbookId,
  363. 'student_id' => $studentId,
  364. 'diagnostic_chapter_id' => $widePayload['chapter_id'],
  365. 'kp_count' => count($widePayload['kp_codes']),
  366. 'section_count' => count($widePayload['section_ids']),
  367. ]);
  368. return $widePayload;
  369. }
  370. return null;
  371. }
  372. // 未全教材摸底:优先检查锚点章,未达标就仍以该章摸底
  373. if ($anchorPayload !== null) {
  374. $allMastered = StudentKnowledgeMastery::allAtLeastSkipNoQuestions(
  375. $studentId,
  376. $anchorPayload['kp_codes'],
  377. 0.9
  378. );
  379. if (!$allMastered) {
  380. Log::info('DiagnosticChapterService: 锚点章节未达标,继续以该章摸底', [
  381. 'textbook_id' => $anchorTextbookId,
  382. 'student_id' => $studentId,
  383. 'anchor_chapter_id' => $anchorChapter->id,
  384. 'kp_count' => count($anchorPayload['kp_codes']),
  385. ]);
  386. return $anchorPayload;
  387. }
  388. }
  389. // 锚点达标后,按教材顺序向后找第一个未摸底章节
  390. $anchorIndex = $chaptersInTextbook->search(fn ($c) => (int) $c->id === (int) $anchorChapter->id);
  391. $anchorIndex = $anchorIndex === false ? 0 : (int) $anchorIndex;
  392. for ($i = $anchorIndex + 1; $i < $chaptersInTextbook->count(); $i++) {
  393. $chapter = $chaptersInTextbook[$i];
  394. if (isset($diagnosedSet[(int) $chapter->id])) {
  395. continue;
  396. }
  397. $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
  398. if ($payload === null) {
  399. continue;
  400. }
  401. Log::info('DiagnosticChapterService: 锚点章节已达标,向后推进到未摸底章节', [
  402. 'textbook_id' => $anchorTextbookId,
  403. 'student_id' => $studentId,
  404. 'anchor_chapter_id' => $anchorChapter->id,
  405. 'next_chapter_id' => $chapter->id,
  406. ]);
  407. return $payload;
  408. }
  409. // 若后续没有可用未摸底章,再从教材起点补找未摸底章
  410. for ($i = 0; $i <= $anchorIndex; $i++) {
  411. $chapter = $chaptersInTextbook[$i];
  412. if (isset($diagnosedSet[(int) $chapter->id])) {
  413. continue;
  414. }
  415. $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
  416. if ($payload !== null) {
  417. Log::info('DiagnosticChapterService: 锚点后无未摸底章,回到教材前序未摸底章节', [
  418. 'textbook_id' => $anchorTextbookId,
  419. 'student_id' => $studentId,
  420. 'anchor_chapter_id' => $anchorChapter->id,
  421. 'fallback_chapter_id' => $chapter->id,
  422. ]);
  423. return $payload;
  424. }
  425. }
  426. // 理论兜底:返回输入章并重启
  427. if ($anchorPayload !== null) {
  428. $anchorPayload['is_restart'] = true;
  429. Log::info('DiagnosticChapterService: 指定章节流程兜底返回输入章节重启', [
  430. 'textbook_id' => $anchorTextbookId,
  431. 'student_id' => $studentId,
  432. 'anchor_chapter_id' => $anchorChapter->id,
  433. ]);
  434. return $anchorPayload;
  435. }
  436. return null;
  437. }
  438. $chapters = TextbookCatalog::query()
  439. ->where('textbook_id', $textbookId)
  440. ->where('node_type', 'chapter')
  441. ->orderBy('sort_order')
  442. ->orderBy('display_no')
  443. ->orderBy('id')
  444. ->get();
  445. if ($chapters->isEmpty()) {
  446. return null;
  447. }
  448. $chapterIds = $chapters->pluck('id')->map(fn ($id) => (int) $id)->all();
  449. $diagnosedSet = $this->getDiagnosedChapterIdSet($studentId, $chapterIds);
  450. foreach ($chapters as $chapter) {
  451. // 检查是否已摸底
  452. if (!isset($diagnosedSet[(int) $chapter->id])) {
  453. $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
  454. if ($payload === null) {
  455. // 这个章节没有题目,跳过
  456. continue;
  457. }
  458. Log::info('DiagnosticChapterService: 找到第一个未摸底的章节', [
  459. 'textbook_id' => $textbookId,
  460. 'student_id' => $studentId,
  461. 'chapter_id' => $chapter->id,
  462. 'chapter_name' => $chapter->name ?? $chapter->title ?? '',
  463. 'kp_count' => count($payload['kp_codes']),
  464. ]);
  465. return $payload;
  466. }
  467. }
  468. // 所有章节都已摸底,返回第一章(重新开始)
  469. $firstChapter = $chapters->first();
  470. $firstPayload = $firstChapter ? $this->buildChapterPayload((int) $firstChapter->id, $firstChapter, $payloadCache) : null;
  471. if ($firstPayload !== null) {
  472. Log::info('DiagnosticChapterService: 所有章节都已摸底,返回第一章', [
  473. 'textbook_id' => $textbookId,
  474. 'student_id' => $studentId,
  475. 'chapter_id' => $firstChapter->id,
  476. ]);
  477. $firstPayload['is_restart'] = true;
  478. return $firstPayload;
  479. }
  480. $widePayload = $this->buildTextbookWideChapterPayload($chapters);
  481. if ($widePayload !== null) {
  482. $widePayload['is_restart'] = true;
  483. Log::info('DiagnosticChapterService: 所有章节已摸底且第一章无有效题,合并全教材知识点重启', [
  484. 'textbook_id' => $textbookId,
  485. 'student_id' => $studentId,
  486. 'diagnostic_chapter_id' => $widePayload['chapter_id'],
  487. 'kp_count' => count($widePayload['kp_codes']),
  488. 'section_count' => count($widePayload['section_ids']),
  489. ]);
  490. return $widePayload;
  491. }
  492. return null;
  493. }
  494. /**
  495. * 将传入节点ID(chapter/section/subsection)统一映射为所属 chapter ID 列表。
  496. * 保持传入顺序去重,忽略不属于当前教材的节点。
  497. *
  498. * @param array<int> $nodeIds
  499. * @return array<int>
  500. */
  501. private function normalizeToChapterIds(array $nodeIds): array
  502. {
  503. if (empty($nodeIds)) {
  504. return [];
  505. }
  506. $chapterIds = [];
  507. $seen = [];
  508. foreach ($nodeIds as $nodeId) {
  509. $currentId = (int) $nodeId;
  510. if ($currentId <= 0) {
  511. continue;
  512. }
  513. $guard = 0;
  514. while ($currentId > 0 && $guard++ < 10) {
  515. $node = TextbookCatalog::query()
  516. ->where('id', $currentId)
  517. ->first(['id', 'parent_id', 'node_type']);
  518. if (!$node) {
  519. break;
  520. }
  521. if ($node->node_type === 'chapter') {
  522. if (!isset($seen[$node->id])) {
  523. $seen[$node->id] = true;
  524. $chapterIds[] = (int) $node->id;
  525. }
  526. break;
  527. }
  528. $currentId = (int) ($node->parent_id ?? 0);
  529. }
  530. }
  531. if (count($chapterIds) !== count($nodeIds)) {
  532. Log::info('DiagnosticChapterService: 章节参数已自动映射到chapter节点', [
  533. 'input_ids' => $nodeIds,
  534. 'resolved_chapter_ids' => $chapterIds,
  535. ]);
  536. }
  537. return $chapterIds;
  538. }
  539. /**
  540. * 按教材章节顺序合并全部 section 与知识点,再过滤有题知识点。
  541. * 用于「全章已摸底」且单章(含第一章)无可用题时的兜底。
  542. *
  543. * @param iterable<int, \App\Models\TextbookCatalog> $chapters
  544. */
  545. private function buildTextbookWideChapterPayload(iterable $chapters): ?array
  546. {
  547. $firstChapter = null;
  548. $allSectionIds = [];
  549. $seenSection = [];
  550. $orderedKp = [];
  551. $seenKp = [];
  552. foreach ($chapters as $chapter) {
  553. if ($firstChapter === null) {
  554. $firstChapter = $chapter;
  555. }
  556. $chapterId = (int) $chapter->id;
  557. $chapterData = $this->getChapterKnowledgePointsSimple($chapterId);
  558. foreach ($chapterData['section_ids'] as $sid) {
  559. $sid = (int) $sid;
  560. if ($sid <= 0 || isset($seenSection[$sid])) {
  561. continue;
  562. }
  563. $seenSection[$sid] = true;
  564. $allSectionIds[] = $sid;
  565. }
  566. foreach ($chapterData['kp_codes'] as $kpCode) {
  567. if ($kpCode === null || $kpCode === '') {
  568. continue;
  569. }
  570. if (isset($seenKp[$kpCode])) {
  571. continue;
  572. }
  573. $seenKp[$kpCode] = true;
  574. $orderedKp[] = $kpCode;
  575. }
  576. }
  577. if ($firstChapter === null) {
  578. return null;
  579. }
  580. $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($orderedKp);
  581. if (empty($kpCodesWithQuestions)) {
  582. return null;
  583. }
  584. return [
  585. 'chapter_id' => (int) $firstChapter->id,
  586. 'chapter_name' => $firstChapter->name ?? $firstChapter->title ?? '',
  587. 'section_ids' => $allSectionIds,
  588. 'kp_codes' => $kpCodesWithQuestions,
  589. ];
  590. }
  591. /**
  592. * 根据 chapter_id 生成摸底章节载荷,若章节无可用题目知识点则返回 null。
  593. */
  594. private function buildChapterPayload(int $chapterId, $chapter = null, ?array &$payloadCache = null): ?array
  595. {
  596. if (is_array($payloadCache) && array_key_exists($chapterId, $payloadCache)) {
  597. return $payloadCache[$chapterId];
  598. }
  599. if ($chapter === null) {
  600. $chapter = TextbookCatalog::query()
  601. ->where('id', $chapterId)
  602. ->where('node_type', 'chapter')
  603. ->first(['id', 'title']);
  604. }
  605. if (!$chapter) {
  606. if (is_array($payloadCache)) {
  607. $payloadCache[$chapterId] = null;
  608. }
  609. return null;
  610. }
  611. $chapterData = $this->getChapterKnowledgePointsSimple($chapterId);
  612. $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);
  613. if (empty($kpCodesWithQuestions)) {
  614. if (is_array($payloadCache)) {
  615. $payloadCache[$chapterId] = null;
  616. }
  617. return null;
  618. }
  619. $payload = [
  620. 'chapter_id' => $chapterId,
  621. 'chapter_name' => $chapter->name ?? $chapter->title ?? '',
  622. 'section_ids' => $chapterData['section_ids'],
  623. 'kp_codes' => $kpCodesWithQuestions,
  624. ];
  625. if (is_array($payloadCache)) {
  626. $payloadCache[$chapterId] = $payload;
  627. }
  628. return $payload;
  629. }
  630. /**
  631. * 批量获取学生在指定章节中的已摸底集合,避免循环 exists N+1 查询。
  632. *
  633. * @param array<int> $chapterIds
  634. * @return array<int, bool>
  635. */
  636. private function getDiagnosedChapterIdSet(int $studentId, array $chapterIds): array
  637. {
  638. $chapterIds = array_values(array_unique(array_filter(array_map('intval', $chapterIds), fn ($id) => $id > 0)));
  639. if (empty($chapterIds)) {
  640. return [];
  641. }
  642. $ids = \App\Models\Paper::query()
  643. ->where('student_id', $studentId)
  644. ->where('paper_type', 0)
  645. ->whereIn('diagnostic_chapter_id', $chapterIds)
  646. ->pluck('diagnostic_chapter_id')
  647. ->map(fn ($id) => (int) $id)
  648. ->unique()
  649. ->values()
  650. ->all();
  651. $set = [];
  652. foreach ($ids as $id) {
  653. $set[$id] = true;
  654. }
  655. return $set;
  656. }
  657. /**
  658. * 获取当前应该学习的章节(第一个有未达标知识点的章节)
  659. * 用于智能组卷流程
  660. */
  661. public function getCurrentLearningChapter(int $textbookId, int $studentId, float $threshold = 0.9): ?array
  662. {
  663. $chapters = TextbookCatalog::query()
  664. ->where('textbook_id', $textbookId)
  665. ->where('node_type', 'chapter')
  666. ->orderBy('sort_order')
  667. ->orderBy('display_no')
  668. ->orderBy('id')
  669. ->get();
  670. if ($chapters->isEmpty()) {
  671. return null;
  672. }
  673. foreach ($chapters as $chapter) {
  674. $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
  675. $kpCodes = $chapterData['kp_codes'];
  676. if (empty($kpCodes)) {
  677. continue;
  678. }
  679. // 使用新方法判断是否达标(跳过无题知识点)
  680. $allMastered = StudentKnowledgeMastery::allAtLeastSkipNoQuestions($studentId, $kpCodes, $threshold);
  681. if (!$allMastered) {
  682. // 检查是否已摸底
  683. $hasDiagnostic = $this->hasChapterDiagnostic($studentId, $chapter->id);
  684. Log::info('DiagnosticChapterService: 找到当前学习章节', [
  685. 'textbook_id' => $textbookId,
  686. 'student_id' => $studentId,
  687. 'student_id_type' => gettype($studentId),
  688. 'chapter_id' => $chapter->id,
  689. 'chapter_name' => $chapter->name ?? '',
  690. 'has_diagnostic' => $hasDiagnostic,
  691. 'kp_codes' => $kpCodes, // 显示实际的知识点列表
  692. 'kp_count' => count($kpCodes),
  693. ]);
  694. return [
  695. 'chapter_id' => $chapter->id,
  696. 'chapter_name' => $chapter->name ?? '',
  697. 'section_ids' => $chapterData['section_ids'],
  698. 'kp_codes' => $kpCodes,
  699. 'has_diagnostic' => $hasDiagnostic,
  700. ];
  701. }
  702. }
  703. // 所有章节都达标
  704. Log::info('DiagnosticChapterService: 所有章节都达标', [
  705. 'textbook_id' => $textbookId,
  706. 'student_id' => $studentId,
  707. ]);
  708. return null;
  709. }
  710. /**
  711. * 获取下一个章节
  712. */
  713. public function getNextChapter(int $textbookId, int $currentChapterId): ?array
  714. {
  715. $chapters = TextbookCatalog::query()
  716. ->where('textbook_id', $textbookId)
  717. ->where('node_type', 'chapter')
  718. ->orderBy('sort_order')
  719. ->orderBy('display_no')
  720. ->orderBy('id')
  721. ->get();
  722. $foundCurrent = false;
  723. foreach ($chapters as $chapter) {
  724. if ($foundCurrent) {
  725. $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
  726. $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);
  727. if (!empty($kpCodesWithQuestions)) {
  728. return [
  729. 'chapter_id' => $chapter->id,
  730. 'chapter_name' => $chapter->name ?? '',
  731. 'section_ids' => $chapterData['section_ids'],
  732. 'kp_codes' => $kpCodesWithQuestions,
  733. ];
  734. }
  735. }
  736. if ($chapter->id === $currentChapterId) {
  737. $foundCurrent = true;
  738. }
  739. }
  740. return null; // 没有下一章
  741. }
  742. /**
  743. * 过滤出有题目的知识点
  744. */
  745. public function filterKpCodesWithQuestions(array $kpCodes): array
  746. {
  747. if (empty($kpCodes)) {
  748. return [];
  749. }
  750. $kpCodesWithQuestions = \App\Models\Question::query()
  751. ->where('audit_status', 0) // 只获取审核通过的题目
  752. ->whereIn('kp_code', $kpCodes)
  753. ->distinct()
  754. ->pluck('kp_code')
  755. ->toArray();
  756. // 保持原有顺序
  757. return array_values(array_intersect($kpCodes, $kpCodesWithQuestions));
  758. }
  759. /**
  760. * 按顺序获取未达标的知识点(用于智能组卷)
  761. *
  762. * @param int $studentId 学生ID
  763. * @param array $kpCodes 知识点列表(按顺序)
  764. * @param float $threshold 达标阈值
  765. * @param int $maxCount 最多返回几个知识点
  766. * @param int $minQuestions 每个知识点最少需要的题目数
  767. * @return array 未达标的知识点列表
  768. */
  769. public function getUnmasteredKpCodesInOrder(
  770. int $studentId,
  771. array $kpCodes,
  772. float $threshold = 0.9,
  773. int $maxCount = 2,
  774. int $minQuestions = 20
  775. ): array {
  776. if (empty($kpCodes)) {
  777. return [];
  778. }
  779. // 获取掌握度(使用 DB::table 避免 Eloquent accessor 把数字转成文字标签)
  780. // 【新增】同时获取 direct_mastery_level 和 mastery_level,判断时优先使用 direct_mastery_level
  781. $masteryRecords = \Illuminate\Support\Facades\DB::table('student_knowledge_mastery')
  782. ->where('student_id', $studentId)
  783. ->whereIn('kp_code', $kpCodes)
  784. ->get(['kp_code', 'mastery_level', 'direct_mastery_level'])
  785. ->keyBy('kp_code');
  786. // 构建有效掌握度映射:取 direct_mastery_level 和 mastery_level 的最大值
  787. // 避免"学了之后反而从达标变成未达标"的问题
  788. $levels = [];
  789. foreach ($masteryRecords as $kpCode => $record) {
  790. $direct = $record->direct_mastery_level;
  791. $mastery = (float) $record->mastery_level;
  792. if ($direct !== null) {
  793. // 取两者最大值:直接学习达标或聚合值达标,都算达标
  794. $levels[$kpCode] = max((float) $direct, $mastery);
  795. } else {
  796. $levels[$kpCode] = $mastery;
  797. }
  798. }
  799. // 【调试】记录查询到的掌握度
  800. Log::info('DiagnosticChapterService: 查询掌握度结果', [
  801. 'student_id' => $studentId,
  802. 'student_id_type' => gettype($studentId),
  803. 'input_kp_codes' => $kpCodes,
  804. 'found_levels' => $levels,
  805. 'raw_records' => $masteryRecords->toArray(),
  806. ]);
  807. // 获取每个知识点的题目数量(只统计审核通过的题目)
  808. $questionCounts = \App\Models\Question::query()
  809. ->where('audit_status', 0) // 只获取审核通过的题目
  810. ->whereIn('kp_code', $kpCodes)
  811. ->selectRaw('kp_code, COUNT(*) as count')
  812. ->groupBy('kp_code')
  813. ->pluck('count', 'kp_code')
  814. ->toArray();
  815. $result = [];
  816. $totalQuestions = 0;
  817. foreach ($kpCodes as $kpCode) {
  818. // 跳过没有题目的知识点
  819. $count = $questionCounts[$kpCode] ?? 0;
  820. if ($count === 0) {
  821. continue;
  822. }
  823. // 检查是否达标
  824. $level = isset($levels[$kpCode]) ? (float) $levels[$kpCode] : 0.0;
  825. $isMastered = $level >= $threshold;
  826. Log::info("DiagnosticChapterService: 检查知识点", [
  827. 'kp_code' => $kpCode,
  828. 'level' => $level,
  829. 'threshold' => $threshold,
  830. 'is_mastered' => $isMastered,
  831. 'level_found_in_db' => isset($levels[$kpCode]),
  832. ]);
  833. if ($level >= $threshold) {
  834. continue;
  835. }
  836. // 添加到结果
  837. $result[] = $kpCode;
  838. $totalQuestions += $count;
  839. // 检查是否达到最大数量
  840. if (count($result) >= $maxCount) {
  841. break;
  842. }
  843. // 检查题目数量是否足够
  844. if ($totalQuestions >= $minQuestions) {
  845. break;
  846. }
  847. }
  848. Log::info('DiagnosticChapterService: 获取未达标知识点', [
  849. 'student_id' => $studentId,
  850. 'input_kp_codes' => $kpCodes,
  851. 'result_kp_codes' => $result,
  852. 'levels_found' => $levels,
  853. 'total_questions' => $totalQuestions,
  854. 'threshold' => $threshold,
  855. ]);
  856. return $result;
  857. }
  858. }