DiagnosticChapterService.php 36 KB

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