| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908 |
- <?php
- namespace App\Services;
- use Illuminate\Support\Facades\Log;
- use App\Models\KnowledgePoint;
- use App\Models\StudentKnowledgeMastery;
- use App\Models\TextbookCatalog;
- use App\Models\TextbookChapterKnowledgeRelation;
- class DiagnosticChapterService
- {
- public function getTextbookKnowledgePointsInOrder(int $textbookId): array
- {
- $chapters = TextbookCatalog::query()
- ->where('textbook_id', $textbookId)
- ->where('node_type', 'chapter')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->get();
- if ($chapters->isEmpty()) {
- Log::warning('DiagnosticChapterService: 未找到章节节点', [
- 'textbook_id' => $textbookId,
- ]);
- return [];
- }
- $orderedCodes = [];
- $seen = [];
- foreach ($chapters as $chapter) {
- $sectionIds = TextbookCatalog::query()
- ->where('parent_id', $chapter->id)
- ->where('node_type', 'section')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->pluck('id')
- ->toArray();
- if (empty($sectionIds)) {
- continue;
- }
- $kpCodes = TextbookChapterKnowledgeRelation::query()
- ->whereIn('catalog_chapter_id', $sectionIds)
- ->where(function ($q) {
- $q->where('is_deleted', 0)->orWhereNull('is_deleted');
- })
- ->pluck('kp_code')
- ->filter()
- ->unique()
- ->values()
- ->toArray();
- $kpCodes = $this->expandWithChildKnowledgePoints($kpCodes);
- foreach ($kpCodes as $kpCode) {
- if (isset($seen[$kpCode])) {
- continue;
- }
- $seen[$kpCode] = true;
- $orderedCodes[] = $kpCode;
- }
- }
- Log::info('DiagnosticChapterService: 获取教材知识点顺序列表', [
- 'textbook_id' => $textbookId,
- 'kp_count' => count($orderedCodes),
- ]);
- return $orderedCodes;
- }
- public function getInitialChapterKnowledgePoints(int $textbookId): array
- {
- $chapter = TextbookCatalog::query()
- ->where('textbook_id', $textbookId)
- ->where('node_type', 'chapter')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->first();
- if (!$chapter) {
- Log::warning('DiagnosticChapterService: 未找到章节节点', [
- 'textbook_id' => $textbookId,
- ]);
- return [];
- }
- $sectionIds = TextbookCatalog::query()
- ->where('parent_id', $chapter->id)
- ->where('node_type', 'section')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->pluck('id')
- ->toArray();
- if (empty($sectionIds)) {
- Log::warning('DiagnosticChapterService: 章节下未找到section节点', [
- 'textbook_id' => $textbookId,
- 'chapter_id' => $chapter->id,
- ]);
- return [];
- }
- $kpCodes = TextbookChapterKnowledgeRelation::query()
- ->whereIn('catalog_chapter_id', $sectionIds)
- ->where(function ($q) {
- $q->where('is_deleted', 0)->orWhereNull('is_deleted');
- })
- ->pluck('kp_code')
- ->filter()
- ->unique()
- ->values()
- ->toArray();
- $kpCodes = $this->expandWithChildKnowledgePoints($kpCodes);
- Log::info('DiagnosticChapterService: 获取首章知识点', [
- 'textbook_id' => $textbookId,
- 'chapter_id' => $chapter->id,
- 'section_count' => count($sectionIds),
- 'kp_count' => count($kpCodes),
- ]);
- return [
- 'chapter_id' => $chapter->id,
- 'section_ids' => $sectionIds,
- 'kp_codes' => $kpCodes,
- ];
- }
- public function getFirstUnmasteredChapterKnowledgePoints(int $textbookId, int $studentId, float $threshold = 0.9): array
- {
- $chapters = TextbookCatalog::query()
- ->where('textbook_id', $textbookId)
- ->where('node_type', 'chapter')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->get();
- if ($chapters->isEmpty()) {
- Log::warning('DiagnosticChapterService: 未找到章节节点', [
- 'textbook_id' => $textbookId,
- ]);
- return [];
- }
- foreach ($chapters as $chapter) {
- $sectionIds = TextbookCatalog::query()
- ->where('parent_id', $chapter->id)
- ->where('node_type', 'section')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->pluck('id')
- ->toArray();
- if (empty($sectionIds)) {
- continue;
- }
- $kpCodes = TextbookChapterKnowledgeRelation::query()
- ->whereIn('catalog_chapter_id', $sectionIds)
- ->where(function ($q) {
- $q->where('is_deleted', 0)->orWhereNull('is_deleted');
- })
- ->pluck('kp_code')
- ->filter()
- ->unique()
- ->values()
- ->toArray();
- $kpCodes = $this->expandWithChildKnowledgePoints($kpCodes);
- if (empty($kpCodes)) {
- continue;
- }
- $allMastered = StudentKnowledgeMastery::allAtLeast($studentId, $kpCodes, $threshold);
- Log::info('DiagnosticChapterService: 章节掌握度评估', [
- 'student_id' => $studentId,
- 'textbook_id' => $textbookId,
- 'chapter_id' => $chapter->id,
- 'section_count' => count($sectionIds),
- 'kp_count' => count($kpCodes),
- 'all_mastered' => $allMastered,
- 'threshold' => $threshold,
- ]);
- if (!$allMastered) {
- return [
- 'chapter_id' => $chapter->id,
- 'section_ids' => $sectionIds,
- 'kp_codes' => $kpCodes,
- 'all_mastered' => $allMastered,
- ];
- }
- }
- Log::info('DiagnosticChapterService: 所有章节均达到掌握度阈值', [
- 'student_id' => $studentId,
- 'textbook_id' => $textbookId,
- 'threshold' => $threshold,
- ]);
- return [];
- }
- private function expandWithChildKnowledgePoints(array $kpCodes): array
- {
- if (empty($kpCodes)) {
- return [];
- }
- $baseCodes = collect($kpCodes)->filter()->values()->all();
- $children = KnowledgePoint::query()
- ->whereIn('parent_kp_code', $baseCodes)
- ->orderBy('kp_code')
- ->get(['parent_kp_code', 'kp_code']);
- $childrenMap = [];
- foreach ($children as $child) {
- $childrenMap[$child->parent_kp_code][] = $child->kp_code;
- }
- $ordered = [];
- $seen = [];
- foreach ($baseCodes as $kpCode) {
- if (!isset($seen[$kpCode])) {
- $seen[$kpCode] = true;
- $ordered[] = $kpCode;
- }
- foreach ($childrenMap[$kpCode] ?? [] as $childCode) {
- if (isset($seen[$childCode])) {
- continue;
- }
- $seen[$childCode] = true;
- $ordered[] = $childCode;
- }
- }
- return $ordered;
- }
- // ========== 以下是新增的方法(不扩展子知识点)==========
- /**
- * 获取章节的知识点(不扩展子知识点)
- * 直接返回 section 绑定的知识点
- */
- public function getChapterKnowledgePointsSimple(int $chapterId): array
- {
- $sectionIds = TextbookCatalog::query()
- ->where('parent_id', $chapterId)
- ->where('node_type', 'section')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->pluck('id')
- ->toArray();
- if (empty($sectionIds)) {
- return [
- 'section_ids' => [],
- 'kp_codes' => [],
- ];
- }
- $kpCodes = TextbookChapterKnowledgeRelation::query()
- ->whereIn('catalog_chapter_id', $sectionIds)
- ->where(function ($q) {
- $q->where('is_deleted', 0)->orWhereNull('is_deleted');
- })
- ->pluck('kp_code')
- ->filter()
- ->unique()
- ->values()
- ->toArray();
- // 不扩展子知识点,直接返回
- return [
- 'section_ids' => $sectionIds,
- 'kp_codes' => $kpCodes,
- ];
- }
- /**
- * 判断章节是否已经摸底过
- */
- public function hasChapterDiagnostic(int $studentId, int $chapterId): bool
- {
- return \App\Models\Paper::query()
- ->where('student_id', $studentId)
- ->where('paper_type', 0) // 摸底类型
- ->where('diagnostic_chapter_id', $chapterId)
- ->exists();
- }
- /**
- * 获取章节摸底目标章节
- * - 传入 targetChapterIds: 先在指定章节内按顺序找第一个未摸底章节;
- * 若指定章节都已摸底,则在该章节所属教材内继续按顺序找未摸底章节。
- * - 未传 targetChapterIds: 保持原逻辑,找教材内第一个未摸底章节。
- */
- public function getFirstUndiagnosedChapter(int $textbookId, int $studentId, ?array $targetChapterIds = null): ?array
- {
- $targetChapterIds = is_array($targetChapterIds)
- ? array_values(array_unique(array_filter(array_map('intval', $targetChapterIds), fn ($id) => $id > 0)))
- : [];
- $payloadCache = [];
- // 指定章节摸底流程:以传入章节为锚点。
- if (!empty($targetChapterIds)) {
- // 兜底:允许传入 section/subsection,自动向上映射到 chapter
- $targetChapterIds = $this->normalizeToChapterIds($targetChapterIds);
- if (empty($targetChapterIds)) {
- Log::warning('DiagnosticChapterService: 指定章节参数无可解析chapter,终止指定章节摸底', [
- 'textbook_id' => $textbookId,
- 'student_id' => $studentId,
- ]);
- return null;
- }
- // 保持传入顺序,首个有效章作为锚点
- $chapterMap = TextbookCatalog::query()
- ->whereIn('id', $targetChapterIds)
- ->where('node_type', 'chapter')
- ->get(['id', 'textbook_id', 'title', 'parent_id', 'node_type', 'sort_order', 'display_no'])
- ->keyBy('id');
- $anchorChapter = null;
- foreach ($targetChapterIds as $chapterId) {
- $candidate = $chapterMap->get($chapterId);
- if ($candidate) {
- $anchorChapter = $candidate;
- break;
- }
- }
- if (!$anchorChapter) {
- Log::warning('DiagnosticChapterService: 指定章节未找到有效chapter节点', [
- 'student_id' => $studentId,
- 'target_chapter_ids' => $targetChapterIds,
- ]);
- return null;
- }
- $anchorTextbookId = (int) ($anchorChapter->textbook_id ?? $textbookId);
- $chaptersInTextbook = TextbookCatalog::query()
- ->where('textbook_id', $anchorTextbookId)
- ->where('node_type', 'chapter')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->get();
- if ($chaptersInTextbook->isEmpty()) {
- Log::warning('DiagnosticChapterService: 指定章节所属教材无章节', [
- 'textbook_id' => $anchorTextbookId,
- 'student_id' => $studentId,
- 'target_chapter_ids' => $targetChapterIds,
- ]);
- return null;
- }
- $chaptersInTextbookIds = $chaptersInTextbook->pluck('id')->map(fn ($id) => (int) $id)->all();
- $diagnosedSet = $this->getDiagnosedChapterIdSet($studentId, $chaptersInTextbookIds);
- // 全教材都摸底:输入什么章就输出什么章(is_restart=true)
- $allDiagnosed = true;
- foreach ($chaptersInTextbookIds as $chapterId) {
- if (!isset($diagnosedSet[$chapterId])) {
- $allDiagnosed = false;
- break;
- }
- }
- $anchorPayload = $this->buildChapterPayload((int) $anchorChapter->id, $anchorChapter, $payloadCache);
- if ($allDiagnosed) {
- if ($anchorPayload !== null) {
- Log::info('DiagnosticChapterService: 全教材已摸底,返回输入锚点章节并重启', [
- 'textbook_id' => $anchorTextbookId,
- 'student_id' => $studentId,
- 'anchor_chapter_id' => $anchorChapter->id,
- ]);
- $anchorPayload['is_restart'] = true;
- return $anchorPayload;
- }
- // 兜底返回教材第一章(is_restart=true)
- $firstChapter = $chaptersInTextbook->first();
- if ($firstChapter) {
- $firstPayload = $this->buildChapterPayload((int) $firstChapter->id, $firstChapter, $payloadCache);
- if ($firstPayload !== null) {
- $firstPayload['is_restart'] = true;
- Log::info('DiagnosticChapterService: 全教材已摸底且输入章无有效题,兜底第一章重启', [
- 'textbook_id' => $anchorTextbookId,
- 'student_id' => $studentId,
- 'chapter_id' => $firstChapter->id,
- ]);
- return $firstPayload;
- }
- }
- return null;
- }
- // 未全教材摸底:优先检查锚点章,未达标就仍以该章摸底
- if ($anchorPayload !== null) {
- $allMastered = StudentKnowledgeMastery::allAtLeastSkipNoQuestions(
- $studentId,
- $anchorPayload['kp_codes'],
- 0.9
- );
- if (!$allMastered) {
- Log::info('DiagnosticChapterService: 锚点章节未达标,继续以该章摸底', [
- 'textbook_id' => $anchorTextbookId,
- 'student_id' => $studentId,
- 'anchor_chapter_id' => $anchorChapter->id,
- 'kp_count' => count($anchorPayload['kp_codes']),
- ]);
- return $anchorPayload;
- }
- }
- // 锚点达标后,按教材顺序向后找第一个未摸底章节
- $anchorIndex = $chaptersInTextbook->search(fn ($c) => (int) $c->id === (int) $anchorChapter->id);
- $anchorIndex = $anchorIndex === false ? 0 : (int) $anchorIndex;
- for ($i = $anchorIndex + 1; $i < $chaptersInTextbook->count(); $i++) {
- $chapter = $chaptersInTextbook[$i];
- if (isset($diagnosedSet[(int) $chapter->id])) {
- continue;
- }
- $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
- if ($payload === null) {
- continue;
- }
- Log::info('DiagnosticChapterService: 锚点章节已达标,向后推进到未摸底章节', [
- 'textbook_id' => $anchorTextbookId,
- 'student_id' => $studentId,
- 'anchor_chapter_id' => $anchorChapter->id,
- 'next_chapter_id' => $chapter->id,
- ]);
- return $payload;
- }
- // 若后续没有可用未摸底章,再从教材起点补找未摸底章
- for ($i = 0; $i <= $anchorIndex; $i++) {
- $chapter = $chaptersInTextbook[$i];
- if (isset($diagnosedSet[(int) $chapter->id])) {
- continue;
- }
- $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
- if ($payload !== null) {
- Log::info('DiagnosticChapterService: 锚点后无未摸底章,回到教材前序未摸底章节', [
- 'textbook_id' => $anchorTextbookId,
- 'student_id' => $studentId,
- 'anchor_chapter_id' => $anchorChapter->id,
- 'fallback_chapter_id' => $chapter->id,
- ]);
- return $payload;
- }
- }
- // 理论兜底:返回输入章并重启
- if ($anchorPayload !== null) {
- $anchorPayload['is_restart'] = true;
- Log::info('DiagnosticChapterService: 指定章节流程兜底返回输入章节重启', [
- 'textbook_id' => $anchorTextbookId,
- 'student_id' => $studentId,
- 'anchor_chapter_id' => $anchorChapter->id,
- ]);
- return $anchorPayload;
- }
- return null;
- }
- $chapters = TextbookCatalog::query()
- ->where('textbook_id', $textbookId)
- ->where('node_type', 'chapter')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->get();
- if ($chapters->isEmpty()) {
- return null;
- }
- $chapterIds = $chapters->pluck('id')->map(fn ($id) => (int) $id)->all();
- $diagnosedSet = $this->getDiagnosedChapterIdSet($studentId, $chapterIds);
- foreach ($chapters as $chapter) {
- // 检查是否已摸底
- if (!isset($diagnosedSet[(int) $chapter->id])) {
- $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
- if ($payload === null) {
- // 这个章节没有题目,跳过
- continue;
- }
- Log::info('DiagnosticChapterService: 找到第一个未摸底的章节', [
- 'textbook_id' => $textbookId,
- 'student_id' => $studentId,
- 'chapter_id' => $chapter->id,
- 'chapter_name' => $chapter->name ?? $chapter->title ?? '',
- 'kp_count' => count($payload['kp_codes']),
- ]);
- return $payload;
- }
- }
- // 所有章节都已摸底,返回第一章(重新开始)
- $firstChapter = $chapters->first();
- $firstPayload = $firstChapter ? $this->buildChapterPayload((int) $firstChapter->id, $firstChapter, $payloadCache) : null;
- if ($firstPayload === null) {
- return null;
- }
- Log::info('DiagnosticChapterService: 所有章节都已摸底,返回第一章', [
- 'textbook_id' => $textbookId,
- 'student_id' => $studentId,
- 'chapter_id' => $firstChapter->id,
- ]);
- $firstPayload['is_restart'] = true;
- return $firstPayload; // 标记是重新开始
- }
- /**
- * 将传入节点ID(chapter/section/subsection)统一映射为所属 chapter ID 列表。
- * 保持传入顺序去重,忽略不属于当前教材的节点。
- *
- * @param array<int> $nodeIds
- * @return array<int>
- */
- private function normalizeToChapterIds(array $nodeIds): array
- {
- if (empty($nodeIds)) {
- return [];
- }
- $chapterIds = [];
- $seen = [];
- foreach ($nodeIds as $nodeId) {
- $currentId = (int) $nodeId;
- if ($currentId <= 0) {
- continue;
- }
- $guard = 0;
- while ($currentId > 0 && $guard++ < 10) {
- $node = TextbookCatalog::query()
- ->where('id', $currentId)
- ->first(['id', 'parent_id', 'node_type']);
- if (!$node) {
- break;
- }
- if ($node->node_type === 'chapter') {
- if (!isset($seen[$node->id])) {
- $seen[$node->id] = true;
- $chapterIds[] = (int) $node->id;
- }
- break;
- }
- $currentId = (int) ($node->parent_id ?? 0);
- }
- }
- if (count($chapterIds) !== count($nodeIds)) {
- Log::info('DiagnosticChapterService: 章节参数已自动映射到chapter节点', [
- 'input_ids' => $nodeIds,
- 'resolved_chapter_ids' => $chapterIds,
- ]);
- }
- return $chapterIds;
- }
- /**
- * 根据 chapter_id 生成摸底章节载荷,若章节无可用题目知识点则返回 null。
- */
- private function buildChapterPayload(int $chapterId, $chapter = null, ?array &$payloadCache = null): ?array
- {
- if (is_array($payloadCache) && array_key_exists($chapterId, $payloadCache)) {
- return $payloadCache[$chapterId];
- }
- if ($chapter === null) {
- $chapter = TextbookCatalog::query()
- ->where('id', $chapterId)
- ->where('node_type', 'chapter')
- ->first(['id', 'title']);
- }
- if (!$chapter) {
- if (is_array($payloadCache)) {
- $payloadCache[$chapterId] = null;
- }
- return null;
- }
- $chapterData = $this->getChapterKnowledgePointsSimple($chapterId);
- $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);
- if (empty($kpCodesWithQuestions)) {
- if (is_array($payloadCache)) {
- $payloadCache[$chapterId] = null;
- }
- return null;
- }
- $payload = [
- 'chapter_id' => $chapterId,
- 'chapter_name' => $chapter->name ?? $chapter->title ?? '',
- 'section_ids' => $chapterData['section_ids'],
- 'kp_codes' => $kpCodesWithQuestions,
- ];
- if (is_array($payloadCache)) {
- $payloadCache[$chapterId] = $payload;
- }
- return $payload;
- }
- /**
- * 批量获取学生在指定章节中的已摸底集合,避免循环 exists N+1 查询。
- *
- * @param array<int> $chapterIds
- * @return array<int, bool>
- */
- private function getDiagnosedChapterIdSet(int $studentId, array $chapterIds): array
- {
- $chapterIds = array_values(array_unique(array_filter(array_map('intval', $chapterIds), fn ($id) => $id > 0)));
- if (empty($chapterIds)) {
- return [];
- }
- $ids = \App\Models\Paper::query()
- ->where('student_id', $studentId)
- ->where('paper_type', 0)
- ->whereIn('diagnostic_chapter_id', $chapterIds)
- ->pluck('diagnostic_chapter_id')
- ->map(fn ($id) => (int) $id)
- ->unique()
- ->values()
- ->all();
- $set = [];
- foreach ($ids as $id) {
- $set[$id] = true;
- }
- return $set;
- }
- /**
- * 获取当前应该学习的章节(第一个有未达标知识点的章节)
- * 用于智能组卷流程
- */
- public function getCurrentLearningChapter(int $textbookId, int $studentId, float $threshold = 0.9): ?array
- {
- $chapters = TextbookCatalog::query()
- ->where('textbook_id', $textbookId)
- ->where('node_type', 'chapter')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->get();
- if ($chapters->isEmpty()) {
- return null;
- }
- foreach ($chapters as $chapter) {
- $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
- $kpCodes = $chapterData['kp_codes'];
- if (empty($kpCodes)) {
- continue;
- }
- // 使用新方法判断是否达标(跳过无题知识点)
- $allMastered = StudentKnowledgeMastery::allAtLeastSkipNoQuestions($studentId, $kpCodes, $threshold);
- if (!$allMastered) {
- // 检查是否已摸底
- $hasDiagnostic = $this->hasChapterDiagnostic($studentId, $chapter->id);
- Log::info('DiagnosticChapterService: 找到当前学习章节', [
- 'textbook_id' => $textbookId,
- 'student_id' => $studentId,
- 'student_id_type' => gettype($studentId),
- 'chapter_id' => $chapter->id,
- 'chapter_name' => $chapter->name ?? '',
- 'has_diagnostic' => $hasDiagnostic,
- 'kp_codes' => $kpCodes, // 显示实际的知识点列表
- 'kp_count' => count($kpCodes),
- ]);
- return [
- 'chapter_id' => $chapter->id,
- 'chapter_name' => $chapter->name ?? '',
- 'section_ids' => $chapterData['section_ids'],
- 'kp_codes' => $kpCodes,
- 'has_diagnostic' => $hasDiagnostic,
- ];
- }
- }
- // 所有章节都达标
- Log::info('DiagnosticChapterService: 所有章节都达标', [
- 'textbook_id' => $textbookId,
- 'student_id' => $studentId,
- ]);
- return null;
- }
- /**
- * 获取下一个章节
- */
- public function getNextChapter(int $textbookId, int $currentChapterId): ?array
- {
- $chapters = TextbookCatalog::query()
- ->where('textbook_id', $textbookId)
- ->where('node_type', 'chapter')
- ->orderBy('sort_order')
- ->orderBy('display_no')
- ->orderBy('id')
- ->get();
- $foundCurrent = false;
- foreach ($chapters as $chapter) {
- if ($foundCurrent) {
- $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
- $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);
- if (!empty($kpCodesWithQuestions)) {
- return [
- 'chapter_id' => $chapter->id,
- 'chapter_name' => $chapter->name ?? '',
- 'section_ids' => $chapterData['section_ids'],
- 'kp_codes' => $kpCodesWithQuestions,
- ];
- }
- }
- if ($chapter->id === $currentChapterId) {
- $foundCurrent = true;
- }
- }
- return null; // 没有下一章
- }
- /**
- * 过滤出有题目的知识点
- */
- public function filterKpCodesWithQuestions(array $kpCodes): array
- {
- if (empty($kpCodes)) {
- return [];
- }
- $kpCodesWithQuestions = \App\Models\Question::query()
- ->where('audit_status', 0) // 只获取审核通过的题目
- ->whereIn('kp_code', $kpCodes)
- ->distinct()
- ->pluck('kp_code')
- ->toArray();
- // 保持原有顺序
- return array_values(array_intersect($kpCodes, $kpCodesWithQuestions));
- }
- /**
- * 按顺序获取未达标的知识点(用于智能组卷)
- *
- * @param int $studentId 学生ID
- * @param array $kpCodes 知识点列表(按顺序)
- * @param float $threshold 达标阈值
- * @param int $maxCount 最多返回几个知识点
- * @param int $minQuestions 每个知识点最少需要的题目数
- * @return array 未达标的知识点列表
- */
- public function getUnmasteredKpCodesInOrder(
- int $studentId,
- array $kpCodes,
- float $threshold = 0.9,
- int $maxCount = 2,
- int $minQuestions = 20
- ): array {
- if (empty($kpCodes)) {
- return [];
- }
- // 获取掌握度(使用 DB::table 避免 Eloquent accessor 把数字转成文字标签)
- // 【新增】同时获取 direct_mastery_level 和 mastery_level,判断时优先使用 direct_mastery_level
- $masteryRecords = \Illuminate\Support\Facades\DB::table('student_knowledge_mastery')
- ->where('student_id', $studentId)
- ->whereIn('kp_code', $kpCodes)
- ->get(['kp_code', 'mastery_level', 'direct_mastery_level'])
- ->keyBy('kp_code');
- // 构建有效掌握度映射:取 direct_mastery_level 和 mastery_level 的最大值
- // 避免"学了之后反而从达标变成未达标"的问题
- $levels = [];
- foreach ($masteryRecords as $kpCode => $record) {
- $direct = $record->direct_mastery_level;
- $mastery = (float) $record->mastery_level;
- if ($direct !== null) {
- // 取两者最大值:直接学习达标或聚合值达标,都算达标
- $levels[$kpCode] = max((float) $direct, $mastery);
- } else {
- $levels[$kpCode] = $mastery;
- }
- }
- // 【调试】记录查询到的掌握度
- Log::info('DiagnosticChapterService: 查询掌握度结果', [
- 'student_id' => $studentId,
- 'student_id_type' => gettype($studentId),
- 'input_kp_codes' => $kpCodes,
- 'found_levels' => $levels,
- 'raw_records' => $masteryRecords->toArray(),
- ]);
- // 获取每个知识点的题目数量(只统计审核通过的题目)
- $questionCounts = \App\Models\Question::query()
- ->where('audit_status', 0) // 只获取审核通过的题目
- ->whereIn('kp_code', $kpCodes)
- ->selectRaw('kp_code, COUNT(*) as count')
- ->groupBy('kp_code')
- ->pluck('count', 'kp_code')
- ->toArray();
- $result = [];
- $totalQuestions = 0;
- foreach ($kpCodes as $kpCode) {
- // 跳过没有题目的知识点
- $count = $questionCounts[$kpCode] ?? 0;
- if ($count === 0) {
- continue;
- }
- // 检查是否达标
- $level = isset($levels[$kpCode]) ? (float) $levels[$kpCode] : 0.0;
- $isMastered = $level >= $threshold;
- Log::info("DiagnosticChapterService: 检查知识点", [
- 'kp_code' => $kpCode,
- 'level' => $level,
- 'threshold' => $threshold,
- 'is_mastered' => $isMastered,
- 'level_found_in_db' => isset($levels[$kpCode]),
- ]);
- if ($level >= $threshold) {
- continue;
- }
- // 添加到结果
- $result[] = $kpCode;
- $totalQuestions += $count;
- // 检查是否达到最大数量
- if (count($result) >= $maxCount) {
- break;
- }
- // 检查题目数量是否足够
- if ($totalQuestions >= $minQuestions) {
- break;
- }
- }
- Log::info('DiagnosticChapterService: 获取未达标知识点', [
- 'student_id' => $studentId,
- 'input_kp_codes' => $kpCodes,
- 'result_kp_codes' => $result,
- 'levels_found' => $levels,
- 'total_questions' => $totalQuestions,
- 'threshold' => $threshold,
- ]);
- return $result;
- }
- }
|