ExamAnswerAnalysisService.php 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Log;
  5. /**
  6. * 考试答题分析服务(步骤级分析)
  7. * 基于卷子分析思考文档的思路实现
  8. *
  9. * 核心流程:
  10. * 1. 接收卷子ID和每道题的对错、简答题的分步骤对错
  11. * 2. 将原子信息映射到知识点/技能
  12. * 3. 计算知识点掌握度向量
  13. * 4. 生成详细分析报告
  14. * 5. 提供智能出卷推荐依据
  15. */
  16. class ExamAnswerAnalysisService
  17. {
  18. /**
  19. * 缓存知识点信息,减少重复查询
  20. *
  21. * @var array<string, object|null>
  22. */
  23. private array $kpInfoCache = [];
  24. public function __construct(
  25. private readonly MasteryCalculator $masteryCalculator,
  26. private readonly KnowledgeMasteryService $knowledgeMasteryService,
  27. private readonly LocalAIAnalysisService $aiAnalysisService,
  28. private readonly MistakeBookService $mistakeBookService
  29. ) {}
  30. /**
  31. * 分析考试答题数据
  32. *
  33. * @param array $examData 考试数据
  34. * @return array 分析结果
  35. */
  36. public function analyzeExamAnswers(array $examData): array
  37. {
  38. Log::info('开始分析考试答题', [
  39. 'paper_id' => $examData['paper_id'] ?? 'unknown',
  40. 'student_id' => $examData['student_id'] ?? 'unknown',
  41. 'question_count' => count($examData['questions'] ?? []),
  42. ]);
  43. $studentId = $examData['student_id'];
  44. $paperId = $examData['paper_id'] ?? '';
  45. $questions = $examData['questions'] ?? [];
  46. // 0. 自动计算分数并补充未提交的题目
  47. $questions = $this->autoCalculateScores($questions, $paperId);
  48. // 更新 examData 中的 questions(包含补充的题目)
  49. $examData['questions'] = $questions;
  50. // 【公司要求】1. 获取学案基准难度(取自学案的difficulty_category)
  51. $examBaseDifficulty = $this->getExamBaseDifficulty($examData['paper_id'] ?? '');
  52. // 2. 获取题目知识点映射(批量查询,避免N+1)
  53. $questionMappings = $this->getQuestionKnowledgeMappings($questions);
  54. // 3. 保存答题记录到数据库(复用已查询的知识点映射)
  55. $this->saveExamAnswerRecords($examData, $questionMappings);
  56. // 【公司要求】4. 计算每个知识点的加权掌握度(传入学案基准难度)
  57. // 核心算法:难度映射 → 权重计算 → 数值更新(newMastery = oldMastery + change)
  58. $knowledgeMasteryVector = $this->calculateKnowledgeMasteryVector($questions, $questionMappings, $examBaseDifficulty, $studentId);
  59. // 【公司要求】5. 更新学生掌握度(包含多级父节点掌握度计算)
  60. $updatedMastery = $this->updateStudentMastery($studentId, $knowledgeMasteryVector);
  61. // 5. 生成题目维度分析
  62. $questionAnalysis = $this->analyzeQuestions($questions, $questionMappings);
  63. // 6. 生成知识点维度分析
  64. $knowledgePointAnalysis = $this->analyzeKnowledgePoints($knowledgeMasteryVector, $questionMappings);
  65. // 7. 生成整体掌握度总结
  66. $overallSummary = $this->generateOverallSummary($updatedMastery);
  67. // 8. 生成智能出卷推荐依据
  68. $smartQuizRecommendation = $this->generateSmartQuizRecommendation($updatedMastery);
  69. // 9. 保存分析结果
  70. $analysisResult = [
  71. 'paper_id' => $examData['paper_id'],
  72. 'student_id' => $studentId,
  73. 'timestamp' => now()->toISOString(),
  74. 'question_analysis' => $questionAnalysis,
  75. 'knowledge_point_analysis' => $knowledgePointAnalysis,
  76. 'overall_summary' => $overallSummary,
  77. 'smart_quiz_recommendation' => $smartQuizRecommendation,
  78. 'mastery_vector' => $updatedMastery,
  79. ];
  80. // 【新增】创建掌握度快照,并返回 current_mastery(仅kp->mastery)
  81. $snapshotInfo = $this->createMasterySnapshot($studentId, $paperId, $analysisResult);
  82. $analysisResult['current_mastery'] = $snapshotInfo['current_mastery'] ?? [];
  83. $this->saveAnalysisResult($studentId, $examData['paper_id'], $analysisResult);
  84. Log::info('考试答题分析完成', [
  85. 'student_id' => $studentId,
  86. 'paper_id' => $examData['paper_id'],
  87. 'analyzed_knowledge_points' => count($knowledgeMasteryVector),
  88. ]);
  89. return $analysisResult;
  90. }
  91. /**
  92. * 【公司要求】获取学案基准难度(取自学案的difficulty_category)
  93. *
  94. * 公司要求:
  95. * 入参需要增加 {学案基准难度}(取自学案的 difficulty_category)
  96. *
  97. * @param string $paperId 试卷ID
  98. * @return int|null 学案基准难度(1-4级),失败返回null
  99. */
  100. private function getExamBaseDifficulty(string $paperId): ?int
  101. {
  102. if (empty($paperId)) {
  103. return null;
  104. }
  105. try {
  106. // 【公司要求】入参需要增加 {学案基准难度}(取自学案的 difficulty_category)
  107. // 从试卷表获取difficulty_category
  108. $paper = DB::table('papers')
  109. ->where('paper_id', $paperId)
  110. ->first();
  111. if (! $paper) {
  112. Log::warning('未找到试卷,尝试从缓存获取', ['paper_id' => $paperId]);
  113. return 2;
  114. }
  115. return $paper->difficulty_category ?? 2;
  116. } catch (\Exception $e) {
  117. Log::warning('获取学案基准难度失败,使用默认2级', [
  118. 'paper_id' => $paperId,
  119. 'error' => $e->getMessage(),
  120. ]);
  121. return 2; // 默认中等难度
  122. }
  123. }
  124. /**
  125. * 获取题目知识点映射
  126. * 【优化】优先使用批量查询,失败时降级到单条查询
  127. */
  128. private function getQuestionKnowledgeMappings(array $questions): array
  129. {
  130. $mappings = [];
  131. $failedQuestions = [];
  132. // 收集所有题目ID
  133. $questionIds = [];
  134. foreach ($questions as $question) {
  135. $questionId = $question['question_id'] ?? null;
  136. if ($questionId) {
  137. $questionIds[] = $questionId;
  138. }
  139. }
  140. // 【优化】尝试批量查询
  141. $batchResult = [];
  142. if (! empty($questionIds)) {
  143. $batchResult = $this->batchGetQuestionKnowledgePoints($questionIds);
  144. }
  145. // 【优化】对批量未命中的题目再做一次批量补偿,减少单条查询
  146. $missingQuestionIds = [];
  147. if (! empty($questionIds)) {
  148. foreach ($questionIds as $qid) {
  149. if (! isset($batchResult[$qid])) {
  150. $missingQuestionIds[] = $qid;
  151. }
  152. }
  153. }
  154. $fallbackBatchResult = [];
  155. if (! empty($missingQuestionIds)) {
  156. $fallbackBatchResult = $this->batchGetQuestionKnowledgePoints($missingQuestionIds);
  157. }
  158. // 遍历题目,优先使用批量结果,否则降级到单条查询
  159. foreach ($questions as $question) {
  160. $questionId = $question['question_id'] ?? null;
  161. if (! $questionId) {
  162. continue;
  163. }
  164. $kpMapping = [];
  165. // 优先使用批量查询结果
  166. if (isset($batchResult[$questionId])) {
  167. $kpMapping = $batchResult[$questionId];
  168. Log::debug('使用批量查询结果', [
  169. 'question_id' => $questionId,
  170. 'kp_count' => count($kpMapping),
  171. ]);
  172. } elseif (isset($fallbackBatchResult[$questionId])) {
  173. $kpMapping = $fallbackBatchResult[$questionId];
  174. Log::debug('使用补偿批量查询结果', [
  175. 'question_id' => $questionId,
  176. 'kp_count' => count($kpMapping),
  177. ]);
  178. } else {
  179. // 降级:使用单条查询(批量查询可能遗漏的题目)
  180. $dbKpMappings = $this->getQuestionKnowledgePointsFromDb($questionId);
  181. if (! empty($dbKpMappings)) {
  182. $kpMapping = $dbKpMappings;
  183. Log::debug('降级到单条查询', [
  184. 'question_id' => $questionId,
  185. 'kp_count' => count($dbKpMappings),
  186. ]);
  187. }
  188. }
  189. // 如果仍然没有知识点信息,跳过该题目
  190. if (empty($kpMapping)) {
  191. $failedQuestions[] = $questionId;
  192. Log::warning('跳过无法获取知识点的题目', [
  193. 'question_id' => $questionId,
  194. ]);
  195. continue;
  196. }
  197. $mappings[$questionId] = [
  198. 'question_id' => $questionId,
  199. 'kp_mapping' => $kpMapping,
  200. ];
  201. }
  202. if (! empty($failedQuestions)) {
  203. Log::warning('部分题目无法获取知识点信息', [
  204. 'failed_questions' => $failedQuestions,
  205. 'total_questions' => count($questions),
  206. 'mapped_questions' => count($mappings),
  207. ]);
  208. }
  209. Log::info('题目知识点映射构建完成', [
  210. 'total_questions' => count($questions),
  211. 'mapped_questions' => count($mappings),
  212. 'failed_questions' => count($failedQuestions),
  213. 'batch_hit_count' => count($batchResult),
  214. ]);
  215. return $mappings;
  216. }
  217. /**
  218. * 从数据库获取题目的知识点信息(支持多知识点)
  219. * 如果题目没有直接的知识点,通过目录ID匹配知识点
  220. */
  221. private function getQuestionKnowledgePointsFromDb(string $questionId): array
  222. {
  223. $allKpMappings = [];
  224. try {
  225. // 【第一步】从 questions 表直接获取知识点字段(可能有多个)
  226. $question = DB::connection('mysql')
  227. ->table('questions')
  228. ->where('id', $questionId)
  229. ->orWhere('question_code', $questionId)
  230. ->first();
  231. if ($question) {
  232. // 检查题目的直接知识点字段
  233. $directKpCodes = [];
  234. $kpCode1 = $question->kp_code;
  235. if ($kpCode1) {
  236. $directKpCodes[] = $kpCode1;
  237. }
  238. // 获取每个知识点的详细信息
  239. foreach ($directKpCodes as $kpCode) {
  240. $kpInfo = $this->getKnowledgePointInfo($kpCode);
  241. if ($kpInfo) {
  242. $allKpMappings[] = [
  243. 'kp_id' => $kpCode,
  244. 'kp_name' => $kpInfo->name,
  245. 'weight' => 1.0,
  246. ];
  247. } else {
  248. // 如果knowledge_points表中没有记录,仍然添加
  249. $allKpMappings[] = [
  250. 'kp_id' => $kpCode,
  251. 'kp_name' => $kpCode,
  252. 'weight' => 1.0,
  253. ];
  254. }
  255. }
  256. if (! empty($directKpCodes)) {
  257. Log::debug('从题目直接字段获取知识点', [
  258. 'question_id' => $questionId,
  259. 'kp_codes' => $directKpCodes,
  260. 'mapped_count' => count($allKpMappings),
  261. ]);
  262. }
  263. }
  264. // 【第二步】如果题目没有直接的知识点,通过目录ID匹配知识点
  265. if (empty($allKpMappings) && $question) {
  266. $catalogKpMappings = $this->findKpCodesByCatalog($question);
  267. if (! empty($catalogKpMappings)) {
  268. $allKpMappings = $catalogKpMappings;
  269. Log::debug('通过目录ID匹配到知识点', [
  270. 'question_id' => $questionId,
  271. 'matched_kp_codes' => array_column($catalogKpMappings, 'kp_id'),
  272. 'matched_count' => count($catalogKpMappings),
  273. ]);
  274. }
  275. }
  276. if (empty($allKpMappings)) {
  277. Log::warning('未找到题目的知识点信息', [
  278. 'question_id' => $questionId,
  279. ]);
  280. }
  281. } catch (\Exception $e) {
  282. Log::error('获取题目知识点信息失败', [
  283. 'question_id' => $questionId,
  284. 'error' => $e->getMessage(),
  285. ]);
  286. }
  287. return $allKpMappings;
  288. }
  289. /**
  290. * 通过题目的目录信息匹配知识点
  291. * 使用 textbook_catalog_nodes_id -> textbook_chapter_knowledge_relation 表查询
  292. */
  293. private function findKpCodesByCatalog(object $question): array
  294. {
  295. $kpMappings = [];
  296. try {
  297. // 获取题目的教材目录节点ID
  298. $catalogNodesId = $question->textbook_catalog_nodes_id;
  299. if (! $catalogNodesId) {
  300. Log::debug('题目没有关联的教材目录节点', [
  301. 'question_id' => $question->id,
  302. ]);
  303. return $kpMappings;
  304. }
  305. // 通过 catalog_chapter_id 查询关联的知识点
  306. $relations = DB::connection('mysql')
  307. ->table('textbook_chapter_knowledge_relation')
  308. ->where('catalog_chapter_id', $catalogNodesId)
  309. ->where('is_deleted', 0) // 只查询未删除的关联
  310. ->get();
  311. if ($relations->isNotEmpty()) {
  312. foreach ($relations as $relation) {
  313. $kpCode = $relation->kp_code;
  314. $kpInfo = $this->getKnowledgePointInfo($kpCode);
  315. $kpMappings[] = [
  316. 'kp_id' => $kpCode,
  317. 'kp_name' => $kpInfo->name ?? $kpCode,
  318. 'weight' => 1.0,
  319. ];
  320. }
  321. Log::debug('通过教材目录节点匹配到知识点', [
  322. 'question_id' => $question->id,
  323. 'catalog_nodes_id' => $catalogNodesId,
  324. 'matched_kp_count' => count($kpMappings),
  325. 'matched_kp_codes' => array_column($kpMappings, 'kp_id'),
  326. ]);
  327. } else {
  328. Log::debug('教材目录节点没有关联的知识点', [
  329. 'question_id' => $question->id,
  330. 'catalog_nodes_id' => $catalogNodesId,
  331. ]);
  332. }
  333. } catch (\Exception $e) {
  334. Log::error('通过目录匹配知识点失败', [
  335. 'question_id' => $question->id,
  336. 'error' => $e->getMessage(),
  337. ]);
  338. }
  339. return $kpMappings;
  340. }
  341. /**
  342. * 保留原有方法用于向后兼容,但标记为废弃
  343. */
  344. private function getQuestionKnowledgePointFromDb(string $questionId): ?array
  345. {
  346. $kpMappings = $this->getQuestionKnowledgePointsFromDb($questionId);
  347. return ! empty($kpMappings) ? $kpMappings[0] : null;
  348. }
  349. /**
  350. * 获取知识点信息(带进程内缓存)
  351. */
  352. private function getKnowledgePointInfo(string $kpCode): ?object
  353. {
  354. if (isset($this->kpInfoCache[$kpCode])) {
  355. return $this->kpInfoCache[$kpCode];
  356. }
  357. $kpInfo = DB::connection('mysql')
  358. ->table('knowledge_points')
  359. ->where('kp_code', $kpCode)
  360. ->select(['kp_code', 'name'])
  361. ->first();
  362. $this->kpInfoCache[$kpCode] = $kpInfo ?: null;
  363. return $kpInfo;
  364. }
  365. /**
  366. * 【优化】批量获取题目的知识点信息
  367. * 将 N+1 查询优化为 2-3 次批量查询
  368. *
  369. * @param array $questionIds 题目ID数组
  370. * @return array [questionId => [kpMappings...]] 映射
  371. */
  372. private function batchGetQuestionKnowledgePoints(array $questionIds): array
  373. {
  374. if (empty($questionIds)) {
  375. return [];
  376. }
  377. $result = [];
  378. $questionsNeedCatalogLookup = []; // 需要通过目录查找知识点的题目
  379. try {
  380. // 【第1步】批量查询 questions 表(1次查询)
  381. $questionsData = DB::connection('mysql')
  382. ->table('questions')
  383. ->whereIn('id', $questionIds)
  384. ->orWhereIn('question_code', $questionIds)
  385. ->get();
  386. // 建立 ID 到题目数据的映射
  387. $questionMap = [];
  388. foreach ($questionsData as $q) {
  389. $questionMap[$q->id] = $q;
  390. if ($q->question_code) {
  391. $questionMap[$q->question_code] = $q;
  392. }
  393. }
  394. // 【第2步】收集所有直接关联的 kp_code
  395. $allKpCodes = [];
  396. foreach ($questionsData as $q) {
  397. if (! empty($q->kp_code)) {
  398. $allKpCodes[] = $q->kp_code;
  399. }
  400. }
  401. // 【第3步】批量查询 knowledge_points 表(1次查询)
  402. $kpInfoMap = [];
  403. if (! empty($allKpCodes)) {
  404. $kpInfos = DB::connection('mysql')
  405. ->table('knowledge_points')
  406. ->whereIn('kp_code', array_unique($allKpCodes))
  407. ->get();
  408. foreach ($kpInfos as $kp) {
  409. $kpInfoMap[$kp->kp_code] = $kp;
  410. }
  411. }
  412. // 【第4步】收集需要通过目录查找的题目
  413. $catalogNodeIds = [];
  414. foreach ($questionsData as $q) {
  415. if (empty($q->kp_code) && ! empty($q->textbook_catalog_nodes_id)) {
  416. $catalogNodeIds[] = $q->textbook_catalog_nodes_id;
  417. $questionsNeedCatalogLookup[$q->id] = $q;
  418. }
  419. }
  420. // 【第5步】批量查询目录-知识点关系(1次查询)
  421. $catalogKpMap = [];
  422. if (! empty($catalogNodeIds)) {
  423. $catalogRelations = DB::connection('mysql')
  424. ->table('textbook_chapter_knowledge_relation')
  425. ->whereIn('catalog_chapter_id', array_unique($catalogNodeIds))
  426. ->where('is_deleted', 0)
  427. ->get();
  428. // 收集目录关联的 kp_code
  429. $catalogKpCodes = [];
  430. foreach ($catalogRelations as $rel) {
  431. $catalogKpCodes[] = $rel->kp_code;
  432. if (! isset($catalogKpMap[$rel->catalog_chapter_id])) {
  433. $catalogKpMap[$rel->catalog_chapter_id] = [];
  434. }
  435. $catalogKpMap[$rel->catalog_chapter_id][] = $rel->kp_code;
  436. }
  437. // 批量查询这些知识点的信息
  438. if (! empty($catalogKpCodes)) {
  439. $catalogKpInfos = DB::connection('mysql')
  440. ->table('knowledge_points')
  441. ->whereIn('kp_code', array_unique($catalogKpCodes))
  442. ->get();
  443. foreach ($catalogKpInfos as $kp) {
  444. $kpInfoMap[$kp->kp_code] = $kp;
  445. }
  446. }
  447. }
  448. // 【第6步】组装结果
  449. foreach ($questionIds as $questionId) {
  450. $qData = $questionMap[$questionId] ?? null;
  451. if (! $qData) {
  452. Log::debug('批量查询未找到题目', ['question_id' => $questionId]);
  453. continue;
  454. }
  455. $kpMappings = [];
  456. // 方式1:直接从 kp_code 字段获取
  457. if (! empty($qData->kp_code)) {
  458. $kpCode = $qData->kp_code;
  459. $kpInfo = $kpInfoMap[$kpCode] ?? null;
  460. $kpMappings[] = [
  461. 'kp_id' => $kpCode,
  462. 'kp_name' => $kpInfo->name ?? $kpCode,
  463. 'weight' => 1.0,
  464. ];
  465. }
  466. // 方式2:通过目录关系获取
  467. elseif (! empty($qData->textbook_catalog_nodes_id)) {
  468. $catalogId = $qData->textbook_catalog_nodes_id;
  469. $catalogKpCodes = $catalogKpMap[$catalogId] ?? [];
  470. foreach ($catalogKpCodes as $kpCode) {
  471. $kpInfo = $kpInfoMap[$kpCode] ?? null;
  472. $kpMappings[] = [
  473. 'kp_id' => $kpCode,
  474. 'kp_name' => $kpInfo->name ?? $kpCode,
  475. 'weight' => 1.0,
  476. ];
  477. }
  478. }
  479. if (! empty($kpMappings)) {
  480. $result[$questionId] = $kpMappings;
  481. }
  482. }
  483. Log::info('批量获取题目知识点完成', [
  484. 'input_count' => count($questionIds),
  485. 'output_count' => count($result),
  486. 'query_count' => '2-4次(优化后)',
  487. ]);
  488. } catch (\Exception $e) {
  489. Log::error('批量获取题目知识点失败,将降级到单条查询', [
  490. 'question_ids' => $questionIds,
  491. 'error' => $e->getMessage(),
  492. ]);
  493. // 降级:返回空,让调用方使用单条查询
  494. return [];
  495. }
  496. return $result;
  497. }
  498. /**
  499. * 从 QuestionBank API 获取题目信息
  500. */
  501. private function getQuestionFromQuestionBank(string $questionId): ?array
  502. {
  503. try {
  504. $baseUrl = config('services.question_bank_api.base_url', 'http://question-bank-api:5015');
  505. $response = Http::timeout(10)->get($baseUrl.'/questions/'.$questionId);
  506. if ($response->successful()) {
  507. $data = $response->json();
  508. return $data['data'] ?? null;
  509. }
  510. return null;
  511. } catch (\Exception $e) {
  512. Log::warning('从QuestionBank获取题目信息失败', [
  513. 'question_id' => $questionId,
  514. 'error' => $e->getMessage(),
  515. ]);
  516. return null;
  517. }
  518. }
  519. /**
  520. * 批量获取题目难度
  521. *
  522. * @param array $questionIds 题目ID数组
  523. * @return array [questionId => difficulty] 映射
  524. */
  525. private function batchGetQuestionDifficulties(array $questionIds): array
  526. {
  527. if (empty($questionIds)) {
  528. return [];
  529. }
  530. $difficulties = [];
  531. try {
  532. $questions = DB::connection('mysql')
  533. ->table('questions')
  534. ->whereIn('id', $questionIds)
  535. ->orWhereIn('question_code', $questionIds)
  536. ->select(['id', 'question_code', 'difficulty'])
  537. ->get();
  538. foreach ($questions as $question) {
  539. $difficulty = $question->difficulty !== null ? floatval($question->difficulty) : 0.6;
  540. // 同时用 id 和 question_code 作为键,确保能匹配到
  541. $difficulties[$question->id] = $difficulty;
  542. if ($question->question_code) {
  543. $difficulties[$question->question_code] = $difficulty;
  544. }
  545. }
  546. } catch (\Exception $e) {
  547. Log::warning('批量获取题目难度失败', [
  548. 'question_ids' => $questionIds,
  549. 'error' => $e->getMessage(),
  550. ]);
  551. }
  552. return $difficulties;
  553. }
  554. /**
  555. * 【公司要求】计算知识点掌握度向量
  556. *
  557. * 公司要求的核心算法:
  558. * 1. 难度映射:将题目中0.0-1.0的浮点数难度映射为 1-4 等级
  559. * 2. 权重计算:
  560. * - 越级(Question > {学案基准难度}):对 +0.15 / 错 -0.05
  561. * - 适应(Question = {学案基准难度}):对 +0.10 / 错 -0.10
  562. * - 降级(Question < {学案基准难度}):对 +0.05 / 错 -0.15
  563. * 3. 数值更新:newMastery = oldMastery + change,并做 0.0 ~ 1.0 的边界限制
  564. *
  565. * 核心算法说明:
  566. * 1. 从考试答题中提取每个知识点的答题记录
  567. * 2. 调用MasteryCalculator计算掌握度(包含:难度映射、权重计算、数值更新)
  568. * 3. 返回包含掌握度、置信度、趋势等完整信息的向量
  569. *
  570. * @param array $questions 题目列表
  571. * @param array $questionMappings 题目知识点映射
  572. * @param int|null $examBaseDifficulty 学案基准难度(1-4级)
  573. * @param string|null $studentId 学生ID
  574. * @return array 知识点掌握度向量
  575. */
  576. private function calculateKnowledgeMasteryVector(array $questions, array $questionMappings, ?int $examBaseDifficulty = null, ?string $studentId = null): array
  577. {
  578. // 按知识点聚合答题记录
  579. $knowledgeAttempts = [];
  580. // 批量获取所有题目的难度(减少数据库查询次数)
  581. $questionIds = array_filter(array_map(fn ($q) => $q['question_id'] ?? $q['question_bank_id'] ?? null, $questions));
  582. $questionDifficulties = $this->batchGetQuestionDifficulties($questionIds);
  583. foreach ($questions as $question) {
  584. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  585. if (empty($questionId)) {
  586. Log::warning('calculateKnowledgeMasteryVector: 题目缺少ID', ['question' => $question]);
  587. continue;
  588. }
  589. $score = floatval($question['score_obtained'] ?? 0);
  590. $maxScore = floatval($question['score'] ?? $score);
  591. // is_correct 是数组,如 [0,1,1],表示每个步骤的正误
  592. $isCorrectArray = $question['is_correct'] ?? [];
  593. if (! is_array($isCorrectArray)) {
  594. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  595. }
  596. $mapping = $questionMappings[$questionId] ?? null;
  597. if (! $mapping || ! isset($mapping['kp_mapping'])) {
  598. Log::debug('calculateKnowledgeMasteryVector: 题目无知识点映射', ['question_id' => $questionId]);
  599. continue;
  600. }
  601. // 从批量查询结果获取题目难度
  602. $questionDifficulty = $questionDifficulties[$questionId] ?? 0.6;
  603. $stepCount = count($isCorrectArray);
  604. $scorePerStep = $maxScore / max($stepCount, 1);
  605. // 根据 is_correct 数组生成步骤级答题记录
  606. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  607. $isCorrectBool = (int) $isCorrect === 1;
  608. // 为该题目关联的每个知识点创建答题记录
  609. foreach ($mapping['kp_mapping'] as $kpMapping) {
  610. $kpId = $kpMapping['kp_id'];
  611. if (! isset($knowledgeAttempts[$kpId])) {
  612. $knowledgeAttempts[$kpId] = [
  613. 'attempts' => [],
  614. 'step_details' => [],
  615. ];
  616. }
  617. // 构建答题记录(用于MasteryCalculator)
  618. $attemptRecord = [
  619. 'question_id' => $questionId,
  620. 'is_correct' => $isCorrectBool,
  621. 'step_index' => $stepIndex,
  622. 'question_difficulty' => $questionDifficulty,
  623. 'created_at' => now()->toISOString(),
  624. ];
  625. $knowledgeAttempts[$kpId]['attempts'][] = $attemptRecord;
  626. $knowledgeAttempts[$kpId]['step_details'][] = [
  627. 'question_id' => $questionId,
  628. 'step_index' => $stepIndex,
  629. 'score' => $isCorrectBool ? $scorePerStep : 0,
  630. 'max_score' => $scorePerStep,
  631. 'is_correct' => $isCorrectBool,
  632. ];
  633. }
  634. }
  635. }
  636. // 【公司要求】【核心】使用MasteryCalculator计算每个知识点的掌握度
  637. $masteryVector = [];
  638. foreach ($knowledgeAttempts as $kpId => $data) {
  639. $attempts = $data['attempts'];
  640. // 如果没有学案基准难度,使用默认值2(提分)
  641. $baseDifficulty = $examBaseDifficulty ?? 2;
  642. // 【公司要求】调用MasteryCalculator的核心算法(传入学案基准难度)
  643. // 该算法包含:难度映射、权重计算、数值更新(newMastery = oldMastery + change)
  644. $masteryResult = $this->masteryCalculator->calculateMasteryLevel(
  645. $studentId ?? '', // 传递学生ID,用于保存掌握度到数据库
  646. $kpId,
  647. $attempts,
  648. $baseDifficulty
  649. );
  650. // 【公司要求】只保留核心掌握度数据
  651. $masteryVector[$kpId] = [
  652. 'kp_id' => $kpId,
  653. 'mastery' => $masteryResult['mastery'],
  654. 'previous_mastery' => $masteryResult['old_mastery'] ?? null,
  655. 'change' => $masteryResult['change'] ?? null,
  656. 'total_attempts' => $masteryResult['total_attempts'],
  657. 'correct_attempts' => $masteryResult['correct_attempts'],
  658. 'accuracy_rate' => $masteryResult['accuracy_rate'],
  659. 'step_details' => $data['step_details'],
  660. // 计算细节(用于调试和分析)
  661. 'calculation_details' => $masteryResult['details'] ?? [],
  662. ];
  663. }
  664. Log::info('知识点掌握度向量计算完成', [
  665. 'knowledge_points_count' => count($masteryVector),
  666. 'sample' => array_slice($masteryVector, 0, 3, true),
  667. ]);
  668. return $masteryVector;
  669. }
  670. /**
  671. * 更新学生掌握度(优化版:批量查询+批量upsert)
  672. */
  673. private function updateStudentMastery(string $studentId, array $knowledgeMasteryVector): array
  674. {
  675. if (empty($knowledgeMasteryVector)) {
  676. return [];
  677. }
  678. $updatedMastery = [];
  679. $kpIds = array_keys($knowledgeMasteryVector);
  680. // 子节点掌握度已在 MasteryCalculator 内部写库,这里只生成返回数据,避免二次写入与重复统计
  681. foreach ($knowledgeMasteryVector as $kpId => $data) {
  682. $previousMastery = $data['previous_mastery'] ?? 0.0;
  683. $updatedMastery[$kpId] = [
  684. 'kp_id' => $kpId,
  685. 'current_mastery' => $data['mastery'],
  686. 'previous_mastery' => $previousMastery,
  687. 'change' => $data['mastery'] - $previousMastery,
  688. 'weight' => 1,
  689. 'is_parent' => false,
  690. ];
  691. }
  692. // 【修复】计算并更新父节点掌握度,同时添加到返回数组中
  693. $parentMasteryData = $this->updateParentMasteryLevels($studentId, $kpIds);
  694. // 合并父节点数据到返回数组
  695. $updatedMastery = array_merge($updatedMastery, $parentMasteryData);
  696. return $updatedMastery;
  697. }
  698. /**
  699. * 更新父节点掌握度(优化版:批量查询+批量upsert)
  700. * 父节点掌握度 = 所有子节点掌握度的算术平均数,支持多级递归
  701. */
  702. private function updateParentMasteryLevels(string $studentId, array $childKpCodes, int $maxDepth = 2): array
  703. {
  704. $allParentMasteryData = [];
  705. $currentLevelChildCodes = $childKpCodes;
  706. $processedNodes = new \ArrayObject;
  707. $now = now();
  708. try {
  709. for ($level = 0; $level < $maxDepth; $level++) {
  710. if (empty($currentLevelChildCodes)) {
  711. break;
  712. }
  713. // 获取当前层子节点的直接父节点
  714. $parentKpCodes = DB::connection('mysql')
  715. ->table('knowledge_points')
  716. ->whereIn('kp_code', $currentLevelChildCodes)
  717. ->whereNotNull('parent_kp_code')
  718. ->distinct()
  719. ->pluck('parent_kp_code')
  720. ->toArray();
  721. if (empty($parentKpCodes)) {
  722. break;
  723. }
  724. // 过滤已处理的节点
  725. $parentKpCodesToProcess = [];
  726. foreach ($parentKpCodes as $code) {
  727. if (! isset($processedNodes[$code])) {
  728. $processedNodes[$code] = true;
  729. $parentKpCodesToProcess[] = $code;
  730. }
  731. }
  732. if (empty($parentKpCodesToProcess)) {
  733. $currentLevelChildCodes = $parentKpCodes;
  734. continue;
  735. }
  736. // 批量获取父节点的直接子节点
  737. $childRelations = DB::connection('mysql')
  738. ->table('knowledge_points')
  739. ->whereIn('parent_kp_code', $parentKpCodesToProcess)
  740. ->get(['kp_code', 'parent_kp_code']);
  741. $childrenByParent = [];
  742. $allChildCodes = [];
  743. foreach ($childRelations as $relation) {
  744. $childrenByParent[$relation->parent_kp_code][] = $relation->kp_code;
  745. $allChildCodes[$relation->kp_code] = true;
  746. }
  747. // 批量获取子节点掌握度
  748. $childMasteryMap = [];
  749. if (! empty($allChildCodes)) {
  750. $childMasteryMap = DB::connection('mysql')
  751. ->table('student_knowledge_mastery')
  752. ->where('student_id', $studentId)
  753. ->whereIn('kp_code', array_keys($allChildCodes))
  754. ->pluck('mastery_level', 'kp_code')
  755. ->toArray();
  756. }
  757. // 批量查询父节点历史掌握度
  758. $historyRecords = DB::connection('mysql')
  759. ->table('student_knowledge_mastery')
  760. ->where('student_id', $studentId)
  761. ->whereIn('kp_code', $parentKpCodesToProcess)
  762. ->get()
  763. ->keyBy('kp_code');
  764. // 计算每个父节点的掌握度并收集upsert数据
  765. $upsertData = [];
  766. $currentLevelParentData = [];
  767. foreach ($parentKpCodesToProcess as $parentKpCode) {
  768. $children = $childrenByParent[$parentKpCode] ?? [];
  769. $sum = 0.0;
  770. $count = 0;
  771. foreach ($children as $childCode) {
  772. if (isset($childMasteryMap[$childCode])) {
  773. $sum += (float) $childMasteryMap[$childCode];
  774. $count++;
  775. }
  776. }
  777. $parentMastery = $count > 0 ? round($sum / $count, 4) : 0.0;
  778. $historyMastery = $historyRecords->get($parentKpCode);
  779. $previousMastery = $historyMastery->mastery_level ?? 0.0;
  780. $upsertData[] = [
  781. 'student_id' => $studentId,
  782. 'kp_code' => $parentKpCode,
  783. 'mastery_level' => $parentMastery,
  784. 'confidence_level' => 0.0,
  785. 'total_attempts' => 1,
  786. 'correct_attempts' => 0,
  787. 'mastery_trend' => 'stable',
  788. 'last_mastery_update' => $now,
  789. 'updated_at' => $now,
  790. ];
  791. $currentLevelParentData[$parentKpCode] = [
  792. 'kp_id' => $parentKpCode,
  793. 'current_mastery' => $parentMastery,
  794. 'previous_mastery' => $previousMastery,
  795. 'change' => $parentMastery - $previousMastery,
  796. 'weight' => 1,
  797. 'is_parent' => true,
  798. 'level' => $level + 1,
  799. ];
  800. }
  801. // 【优化】批量upsert(1次查询代替N次updateOrInsert)
  802. if (! empty($upsertData)) {
  803. DB::connection('mysql')
  804. ->table('student_knowledge_mastery')
  805. ->upsert(
  806. $upsertData,
  807. ['student_id', 'kp_code'],
  808. ['mastery_level', 'confidence_level', 'total_attempts', 'correct_attempts', 'mastery_trend', 'last_mastery_update', 'updated_at']
  809. );
  810. }
  811. $allParentMasteryData = array_merge($allParentMasteryData, $currentLevelParentData);
  812. $currentLevelChildCodes = $parentKpCodes;
  813. }
  814. if (! empty($allParentMasteryData)) {
  815. Log::info('多级父节点掌握度计算完成', [
  816. 'student_id' => $studentId,
  817. 'child_count' => count($childKpCodes),
  818. 'total_parent_count' => count($allParentMasteryData),
  819. ]);
  820. }
  821. } catch (\Exception $e) {
  822. Log::error('计算多级父节点掌握度失败', [
  823. 'student_id' => $studentId,
  824. 'error' => $e->getMessage(),
  825. ]);
  826. }
  827. return $allParentMasteryData;
  828. }
  829. /**
  830. * 生成题目维度分析(包含AI分析和解题思路)
  831. */
  832. private function analyzeQuestions(array $questions, array $questionMappings): array
  833. {
  834. $analysis = [];
  835. foreach ($questions as $question) {
  836. $questionId = $question['question_id'];
  837. $score = floatval($question['score_obtained'] ?? 0);
  838. $maxScore = floatval($question['score'] ?? $score);
  839. $steps = $question['steps'] ?? [];
  840. $isCorrect = $question['is_correct'] ?? ($score >= $maxScore);
  841. $mapping = $questionMappings[$questionId] ?? ['kp_mapping' => []];
  842. if (empty($mapping['kp_mapping'])) {
  843. Log::warning('ExamAnswerAnalysisService: 题目无知识点映射', ['question_id' => $questionId]);
  844. continue;
  845. }
  846. $kpCode = $mapping['kp_mapping'][0]['kp_id'];
  847. // 步骤分析
  848. $stepAnalysis = [];
  849. if (! empty($steps)) {
  850. foreach ($steps as $step) {
  851. $kpId = $step['kp_id'];
  852. if (empty($kpId)) {
  853. Log::warning('ExamAnswerAnalysisService: 步骤缺少知识点ID', [
  854. 'question_id' => $questionId,
  855. 'step_index' => $step['step_index'] ?? 'unknown',
  856. ]);
  857. continue;
  858. }
  859. $stepAnalysis[] = [
  860. 'step_index' => $step['step_index'],
  861. 'is_correct' => $step['is_correct'],
  862. 'kp_id' => $kpId,
  863. 'description' => $step['description'] ?? '',
  864. ];
  865. }
  866. }
  867. // 知识点关联
  868. $knowledgePoints = array_map(function ($kp) {
  869. return [
  870. 'kp_id' => $kp['kp_id'],
  871. 'kp_name' => $kp['kp_name'] ?? $kp['kp_id'],
  872. 'weight' => $kp['weight'] ?? 1.0,
  873. ];
  874. }, $mapping['kp_mapping']);
  875. // 【集成】调用AI分析服务,获取解题思路和错误分析
  876. $aiAnalysis = $this->getQuestionAIAnalysis($question, $mapping);
  877. $analysis[] = [
  878. 'question_id' => $questionId,
  879. 'score_obtained' => $score,
  880. 'max_score' => $maxScore,
  881. 'accuracy_rate' => $maxScore > 0 ? $score / $maxScore : 0,
  882. 'is_correct' => $isCorrect,
  883. 'step_analysis' => $stepAnalysis,
  884. 'knowledge_points' => $knowledgePoints,
  885. 'performance_summary' => $this->generateQuestionPerformanceSummary($question, $stepAnalysis),
  886. // 【新增】解题思路和错误分析
  887. 'solution_process' => $aiAnalysis['solution_process'] ?? '',
  888. 'error_analysis' => $aiAnalysis['error_analysis'] ?? '',
  889. 'mistake_type' => $aiAnalysis['mistake_type'] ?? '',
  890. 'suggestions' => $aiAnalysis['suggestions'] ?? '',
  891. 'next_steps' => $aiAnalysis['next_steps'] ?? [],
  892. ];
  893. }
  894. return $analysis;
  895. }
  896. /**
  897. * 获取题目的AI分析(解题思路、错误分析)
  898. */
  899. private function getQuestionAIAnalysis(array $question, array $mapping): array
  900. {
  901. $isCorrect = $question['is_correct'] ?? false;
  902. $score = floatval($question['score_obtained'] ?? 0);
  903. $maxScore = floatval($question['score'] ?? 10);
  904. $kpCode = $mapping['kp_mapping'][0]['kp_id'] ?? null;
  905. if (empty($kpCode)) {
  906. Log::warning('ExamAnswerAnalysisService: getQuestionAIAnalysis缺少知识点ID', [
  907. 'question_id' => $question['question_id'] ?? 'unknown',
  908. 'mapping' => $mapping,
  909. ]);
  910. $kpCode = 'UNKNOWN_KP';
  911. }
  912. // 调用LocalAIAnalysisService进行分析
  913. try {
  914. $analysisResult = $this->aiAnalysisService->analyzeAnswer([
  915. 'question_id' => $question['question_id'],
  916. 'question_text' => $question['question_text'] ?? '',
  917. 'student_answer' => $question['student_answer'] ?? '',
  918. 'correct_answer' => $question['correct_answer'] ?? '',
  919. 'score' => $score,
  920. 'max_score' => $maxScore,
  921. 'kp_code' => $kpCode,
  922. ]);
  923. $data = $analysisResult['data'] ?? [];
  924. // 根据正确性生成不同的解题思路
  925. if ($isCorrect) {
  926. return [
  927. 'solution_process' => $data['correct_solution'] ?? '该题作答正确,解题思路清晰',
  928. 'error_analysis' => '',
  929. 'mistake_type' => '',
  930. 'suggestions' => $data['suggestions'] ?? '继续保持良好的解题习惯',
  931. 'next_steps' => $data['next_steps'] ?? ['尝试更高难度的同类题目'],
  932. ];
  933. }
  934. // 错误题目:返回详细分析
  935. return [
  936. 'solution_process' => $data['correct_solution'] ?? '请参考标准解题步骤',
  937. 'error_analysis' => $data['reason'] ?? '解题过程中存在错误',
  938. 'mistake_type' => $data['mistake_type'] ?? '计算或理解错误',
  939. 'suggestions' => $data['suggestions'] ?? '建议针对薄弱知识点进行专项练习',
  940. 'next_steps' => $data['next_steps'] ?? ['复习相关知识点', '做同类型练习题'],
  941. ];
  942. } catch (\Exception $e) {
  943. Log::warning('AI分析失败,使用默认分析', [
  944. 'question_id' => $question['question_id'],
  945. 'error' => $e->getMessage(),
  946. ]);
  947. // 回退到基础分析
  948. return $this->getFallbackAnalysis($question, $isCorrect);
  949. }
  950. }
  951. /**
  952. * 回退分析(当AI分析失败时)
  953. */
  954. private function getFallbackAnalysis(array $question, bool $isCorrect): array
  955. {
  956. if ($isCorrect) {
  957. return [
  958. 'solution_process' => '该题作答正确',
  959. 'error_analysis' => '',
  960. 'mistake_type' => '',
  961. 'suggestions' => '继续保持',
  962. 'next_steps' => ['尝试更高难度的题目'],
  963. ];
  964. }
  965. $scoreRatio = floatval($question['score_obtained'] ?? 0) / max(floatval($question['score'] ?? 1), 1);
  966. return [
  967. 'solution_process' => '请参考标准答案和解题步骤',
  968. 'error_analysis' => $scoreRatio < 0.3 ? '知识点理解存在偏差' : '解题过程中出现错误',
  969. 'mistake_type' => $scoreRatio < 0.3 ? '概念错误' : '计算/步骤错误',
  970. 'suggestions' => '建议复习相关知识点,加强练习',
  971. 'next_steps' => ['复习基础概念', '做同类型练习题', '请教老师或同学'],
  972. ];
  973. }
  974. /**
  975. * 生成知识点维度分析
  976. */
  977. private function analyzeKnowledgePoints(array $knowledgeMasteryVector, array $questionMappings): array
  978. {
  979. $analysis = [];
  980. foreach ($knowledgeMasteryVector as $kpId => $data) {
  981. // 【公司要求】移除置信度,只保留核心掌握度分析
  982. $analysis[] = [
  983. 'kp_id' => $kpId,
  984. 'mastery_level' => $data['mastery'],
  985. 'performance_in_exam' => $this->evaluatePerformanceLevel($data['mastery']),
  986. 'evidence_count' => count($data['step_details']),
  987. 'step_evidence' => $data['step_details'],
  988. 'recommendation' => $this->generateKnowledgePointRecommendation($data),
  989. ];
  990. }
  991. return $analysis;
  992. }
  993. /**
  994. * 生成整体掌握度总结
  995. */
  996. private function generateOverallSummary(array $updatedMastery): array
  997. {
  998. $knowledgePoints = array_values($updatedMastery);
  999. if (empty($knowledgePoints)) {
  1000. return [
  1001. 'total_knowledge_points' => 0,
  1002. 'average_mastery' => 0,
  1003. 'mastery_distribution' => [
  1004. 'mastered' => 0,
  1005. 'good' => 0,
  1006. 'weak' => 0,
  1007. ],
  1008. 'top_strengths' => [],
  1009. 'top_weaknesses' => [],
  1010. ];
  1011. }
  1012. // 计算平均掌握度(只计算子节点,不包括父节点)
  1013. $childNodes = array_filter($knowledgePoints, fn ($kp) => ! ($kp['is_parent'] ?? false));
  1014. $totalChildNodes = count($childNodes);
  1015. if ($totalChildNodes === 0) {
  1016. // 如果没有子节点,只计算所有节点
  1017. $averageMastery = array_sum(array_column($knowledgePoints, 'current_mastery')) / count($knowledgePoints);
  1018. } else {
  1019. // 计算所有节点的平均掌握度(包括父节点)
  1020. $allMastery = array_column($knowledgePoints, 'current_mastery');
  1021. $averageMastery = array_sum($allMastery) / count($allMastery);
  1022. }
  1023. // 掌握度分布(只统计子节点)
  1024. $mastered = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] >= 0.85);
  1025. $good = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] >= 0.70 && $kp['current_mastery'] < 0.85);
  1026. $weak = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] < 0.70);
  1027. // 排序找出优势和薄弱点(只包括子节点)
  1028. usort($childNodes, fn ($a, $b) => $b['current_mastery'] <=> $a['current_mastery']);
  1029. $topStrengths = array_slice($childNodes, 0, 3);
  1030. $topWeaknesses = array_slice(array_reverse($childNodes), 0, 3);
  1031. // 统计父子节点数量
  1032. $childCount = count(array_filter($knowledgePoints, fn ($kp) => ! ($kp['is_parent'] ?? false)));
  1033. $parentCount = count(array_filter($knowledgePoints, fn ($kp) => $kp['is_parent'] ?? false));
  1034. return [
  1035. 'total_knowledge_points' => $totalChildNodes, // 只统计子节点数量
  1036. 'child_nodes_count' => $childCount,
  1037. 'parent_nodes_count' => $parentCount,
  1038. 'average_mastery' => round($averageMastery, 4),
  1039. 'mastery_distribution' => [
  1040. 'mastered' => count($mastered),
  1041. 'good' => count($good),
  1042. 'weak' => count($weak),
  1043. ],
  1044. 'top_strengths' => $topStrengths,
  1045. 'top_weaknesses' => $topWeaknesses,
  1046. 'overall_performance' => $this->evaluateOverallPerformance($averageMastery),
  1047. ];
  1048. }
  1049. /**
  1050. * 生成智能出卷推荐依据
  1051. * 基于文档中的推荐优先级算法
  1052. */
  1053. private function generateSmartQuizRecommendation(array $updatedMastery): array
  1054. {
  1055. $recommendations = [];
  1056. // 只对子节点生成推荐,忽略父节点
  1057. foreach ($updatedMastery as $kpId => $data) {
  1058. // 跳过父节点
  1059. if ($data['is_parent'] ?? false) {
  1060. continue;
  1061. }
  1062. $mastery = $data['current_mastery'];
  1063. // 【公司要求】移除置信度,只使用掌握度计算推荐
  1064. $weight = $data['weight'];
  1065. // 推荐优先级 = (1 - 掌握度) * 重要性 * 覆盖需求
  1066. // 重要性可以根据知识点在中考/阶段考试中的权重,这里简化为1.0
  1067. $importance = 1.0;
  1068. // 覆盖需求:最近没考过或考得少,值大
  1069. $coverageNeed = max(1.0, 1.5 - ($weight / 10));
  1070. $priority = (1 - $mastery) * $importance * $coverageNeed;
  1071. $recommendations[] = [
  1072. 'kp_id' => $kpId,
  1073. 'current_mastery' => $mastery,
  1074. 'priority' => $priority,
  1075. 'recommended_questions' => $this->calculateRecommendedQuestions($mastery),
  1076. 'focus_type' => $this->determineFocusType($mastery),
  1077. ];
  1078. }
  1079. // 按优先级排序
  1080. usort($recommendations, fn ($a, $b) => $b['priority'] <=> $a['priority']);
  1081. // 控制难度节奏:40%巩固型 + 40%修补型 + 20%挑战型
  1082. $totalRecommendations = count($recommendations);
  1083. $consolidation = array_slice($recommendations, 0, intval($totalRecommendations * 0.4));
  1084. $remediation = array_slice($recommendations, intval($totalRecommendations * 0.4), intval($totalRecommendations * 0.4));
  1085. $challenge = array_slice($recommendations, intval($totalRecommendations * 0.8));
  1086. return [
  1087. 'priority_list' => $recommendations,
  1088. 'quiz_structure' => [
  1089. 'consolidation_type' => $consolidation,
  1090. 'remediation_type' => $remediation,
  1091. 'challenge_type' => $challenge,
  1092. ],
  1093. 'total_recommended_questions' => array_sum(array_column($recommendations, 'recommended_questions')),
  1094. ];
  1095. }
  1096. /**
  1097. * 保存考试答题记录
  1098. *
  1099. * 入参格式示例:
  1100. * {
  1101. * "question_bank_id": "12979",
  1102. * "student_answer": "C",
  1103. * "is_correct": [0], // 数组长度决定步骤数,0=错误,1=正确
  1104. * "teacher_comment": null
  1105. * }
  1106. *
  1107. * is_correct 数组说明:
  1108. * - 单选题:[1] 或 [0],长度为1
  1109. * - 填空题:[1, 0, 1],每个空一个元素
  1110. * - 简答题:[1, 1, 0, 1],每个得分步骤一个元素
  1111. */
  1112. /**
  1113. * 保存错题记录
  1114. *
  1115. * @param string $studentId 学生ID
  1116. * @param string $questionId 题目ID
  1117. * @param string $examId 考试ID
  1118. * @param array $question 题目数据
  1119. * @param array|null $kpMapping 知识点映射(数组格式:[kp_id1, kp_id2] 或 null)
  1120. */
  1121. private function saveMistakeRecord(string $studentId, string $questionId, string $examId, array $question, ?array $kpMapping): void
  1122. {
  1123. try {
  1124. // 如果 $kpMapping 是数组,说明是多个 kp_id
  1125. // 如果是关联数组,说明是单个 kpMapping(兼容旧调用)
  1126. $kpIds = null;
  1127. if (is_array($kpMapping)) {
  1128. // 检查是数组的数组(多个kp_id)还是关联数组(单个kpMapping)
  1129. if (isset($kpMapping[0])) {
  1130. // 数组的数组:[[kp_id: '...'], [kp_id: '...']]
  1131. $kpIds = array_column($kpMapping, 'kp_id');
  1132. } else {
  1133. // 关联数组:[kp_id: '...']
  1134. $kpIds = [$kpMapping['kp_id']];
  1135. }
  1136. }
  1137. $payload = [
  1138. 'student_id' => $studentId,
  1139. 'question_id' => $questionId,
  1140. 'paper_id' => $examId,
  1141. 'my_answer' => $question['student_answer'] ?? null,
  1142. 'correct_answer' => null, // 可以从题目表获取
  1143. 'question_text' => null, // 可以从题目表获取
  1144. 'knowledge_point' => null, // 不保存name,只保存kp_ids
  1145. 'kp_ids' => $kpIds, // 保存为数组格式
  1146. 'source' => $examId, // 来源标记使用卷子ID
  1147. 'happened_at' => now(),
  1148. ];
  1149. $result = $this->mistakeBookService->createMistake($payload);
  1150. if (($result['duplicate'] ?? false) === false) {
  1151. Log::debug('错题记录保存成功', [
  1152. 'student_id' => $studentId,
  1153. 'question_id' => $questionId,
  1154. 'mistake_id' => $result['mistake_id'] ?? null,
  1155. ]);
  1156. }
  1157. } catch (\Exception $e) {
  1158. Log::warning('错题记录保存失败(不中断主流程)', [
  1159. 'student_id' => $studentId,
  1160. 'question_id' => $questionId,
  1161. 'exam_id' => $examId,
  1162. 'error' => $e->getMessage(),
  1163. ]);
  1164. }
  1165. }
  1166. /**
  1167. * 保存答题记录(优化版:批量INSERT)
  1168. *
  1169. * @param array $examData 考试数据
  1170. * @param array $questionMappings 已批量查询的知识点映射,避免N+1
  1171. */
  1172. private function saveExamAnswerRecords(array $examData, array $questionMappings = []): void
  1173. {
  1174. // 【修复】确保类型正确,避免 SQL 类型转换问题
  1175. $studentId = (string) $examData['student_id'];
  1176. $examId = (string) $examData['paper_id'];
  1177. $now = now();
  1178. // 【优化】收集所有要插入的记录,最后批量INSERT
  1179. $stepsToInsert = [];
  1180. $questionsToInsert = [];
  1181. $mistakesToSave = []; // 收集错题记录
  1182. foreach ($examData['questions'] as $question) {
  1183. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1184. if (empty($questionId)) {
  1185. continue;
  1186. }
  1187. // 【优化】使用传入的映射,不再查询数据库
  1188. $kpMappings = $questionMappings[$questionId]['kp_mapping'] ?? [];
  1189. $isCorrectArray = $question['is_correct'] ?? [];
  1190. if (! is_array($isCorrectArray)) {
  1191. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  1192. }
  1193. $stepCount = count($isCorrectArray);
  1194. if ($stepCount > 1 || ! empty($kpMappings)) {
  1195. // 多步骤题目:收集步骤记录
  1196. $scorePerStep = ($question['score'] ?? 0) / max($stepCount, 1);
  1197. $hasMistake = false;
  1198. $allErrorKpCodes = [];
  1199. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  1200. $isCorrectBool = (int) $isCorrect === 1;
  1201. if (! empty($kpMappings)) {
  1202. foreach ($kpMappings as $kpMapping) {
  1203. $stepsToInsert[] = [
  1204. 'student_id' => $studentId,
  1205. 'exam_id' => $examId,
  1206. 'question_id' => $questionId,
  1207. 'step_index' => $stepIndex,
  1208. 'kp_id' => $kpMapping['kp_id'],
  1209. 'is_correct' => $isCorrectBool ? 1 : 0,
  1210. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1211. 'created_at' => $now,
  1212. 'updated_at' => $now,
  1213. ];
  1214. if (! $isCorrectBool) {
  1215. $hasMistake = true;
  1216. $allErrorKpCodes[] = $kpMapping['kp_id'];
  1217. }
  1218. }
  1219. } else {
  1220. $stepsToInsert[] = [
  1221. 'student_id' => $studentId,
  1222. 'exam_id' => $examId,
  1223. 'question_id' => $questionId,
  1224. 'step_index' => $stepIndex,
  1225. 'kp_id' => null,
  1226. 'is_correct' => $isCorrectBool ? 1 : 0,
  1227. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1228. 'created_at' => $now,
  1229. 'updated_at' => $now,
  1230. ];
  1231. if (! $isCorrectBool) {
  1232. $hasMistake = true;
  1233. }
  1234. }
  1235. }
  1236. // 收集错题记录
  1237. if ($hasMistake) {
  1238. $uniqueKpCodes = array_values(array_unique($allErrorKpCodes));
  1239. $mistakesToSave[] = [
  1240. 'questionId' => $questionId,
  1241. 'question' => $question,
  1242. 'kpMappings' => array_map(fn ($code) => ['kp_id' => $code], $uniqueKpCodes),
  1243. ];
  1244. }
  1245. } else {
  1246. // 单步骤题目:收集题目级记录
  1247. $questionsToInsert[] = [
  1248. 'student_id' => $studentId,
  1249. 'exam_id' => $examId,
  1250. 'question_id' => $questionId,
  1251. 'score_obtained' => $question['score_obtained'] ?? 0,
  1252. 'max_score' => $question['score'] ?? 0,
  1253. 'created_at' => $now,
  1254. 'updated_at' => $now,
  1255. ];
  1256. // 收集错题记录
  1257. if (($question['score_obtained'] ?? 0) <= 0) {
  1258. $mistakesToSave[] = [
  1259. 'questionId' => $questionId,
  1260. 'question' => $question,
  1261. 'kpMappings' => ! empty($kpMappings)
  1262. ? array_map(fn ($m) => ['kp_id' => $m['kp_id']], $kpMappings)
  1263. : null,
  1264. ];
  1265. }
  1266. }
  1267. }
  1268. // 判断是否有变更,避免重复删除/插入
  1269. $stepsChanged = $this->hasAnswerStepsChanged($studentId, $examId, $stepsToInsert);
  1270. $questionsChanged = $this->hasAnswerQuestionsChanged($studentId, $examId, $questionsToInsert);
  1271. if ($stepsChanged || $questionsChanged) {
  1272. // 先清理该考试的所有答题记录(支持重复提交)
  1273. try {
  1274. if ($questionsChanged) {
  1275. DB::connection('mysql')->table('student_answer_questions')
  1276. ->where('student_id', '=', $studentId)
  1277. ->where('exam_id', '=', $examId)
  1278. ->delete();
  1279. }
  1280. if ($stepsChanged) {
  1281. DB::connection('mysql')->table('student_answer_steps')
  1282. ->where('student_id', '=', $studentId)
  1283. ->where('exam_id', '=', $examId)
  1284. ->delete();
  1285. }
  1286. Log::info('清理旧答题记录成功', [
  1287. 'student_id' => $studentId,
  1288. 'exam_id' => $examId,
  1289. 'steps_changed' => $stepsChanged,
  1290. 'questions_changed' => $questionsChanged,
  1291. ]);
  1292. } catch (\Exception $e) {
  1293. // 清理失败时抛出异常,避免后续插入重复数据
  1294. Log::error('清理旧答题记录失败', [
  1295. 'student_id' => $studentId,
  1296. 'exam_id' => $examId,
  1297. 'error' => $e->getMessage(),
  1298. ]);
  1299. throw $e;
  1300. }
  1301. // 【优化】批量 INSERT(每500条一批,避免超过MySQL限制)
  1302. try {
  1303. if ($stepsChanged && ! empty($stepsToInsert)) {
  1304. foreach (array_chunk($stepsToInsert, 500) as $chunk) {
  1305. DB::connection('mysql')->table('student_answer_steps')->insert($chunk);
  1306. }
  1307. }
  1308. if ($questionsChanged && ! empty($questionsToInsert)) {
  1309. foreach (array_chunk($questionsToInsert, 500) as $chunk) {
  1310. DB::connection('mysql')->table('student_answer_questions')->insert($chunk);
  1311. }
  1312. }
  1313. } catch (\Exception $e) {
  1314. Log::error('批量保存答题记录失败', [
  1315. 'student_id' => $studentId,
  1316. 'exam_id' => $examId,
  1317. 'error' => $e->getMessage(),
  1318. ]);
  1319. }
  1320. }
  1321. // 保存错题记录(批量处理,避免逐条写入)
  1322. if (! empty($mistakesToSave)) {
  1323. $payloads = [];
  1324. foreach ($mistakesToSave as $mistake) {
  1325. $kpIds = null;
  1326. if (is_array($mistake['kpMappings'])) {
  1327. $kpIds = isset($mistake['kpMappings'][0])
  1328. ? array_column($mistake['kpMappings'], 'kp_id')
  1329. : [$mistake['kpMappings']['kp_id'] ?? null];
  1330. }
  1331. $payloads[] = [
  1332. 'student_id' => $studentId,
  1333. 'question_id' => $mistake['questionId'],
  1334. 'paper_id' => $examId,
  1335. 'my_answer' => $mistake['question']['student_answer'] ?? null,
  1336. 'correct_answer' => null,
  1337. 'question_text' => null,
  1338. 'knowledge_point' => null,
  1339. 'kp_ids' => $kpIds,
  1340. 'source' => $examId,
  1341. 'happened_at' => now(),
  1342. ];
  1343. }
  1344. $this->mistakeBookService->createMistakesBatch($payloads);
  1345. }
  1346. Log::info('答题记录保存完成', [
  1347. 'student_id' => $studentId,
  1348. 'exam_id' => $examId,
  1349. 'total_questions' => count($examData['questions']),
  1350. 'steps_saved' => count($stepsToInsert),
  1351. 'questions_saved' => count($questionsToInsert),
  1352. ]);
  1353. }
  1354. /**
  1355. * 判断答题步骤记录是否发生变化
  1356. */
  1357. private function hasAnswerStepsChanged(string $studentId, string $examId, array $newSteps): bool
  1358. {
  1359. $existing = DB::connection('mysql')
  1360. ->table('student_answer_steps')
  1361. ->where('student_id', $studentId)
  1362. ->where('exam_id', $examId)
  1363. ->get(['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'])
  1364. ->map(fn ($row) => (array) $row)
  1365. ->toArray();
  1366. return $this->buildRecordsHash($existing, ['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'], ['step_score'])
  1367. !== $this->buildRecordsHash($newSteps, ['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'], ['step_score']);
  1368. }
  1369. /**
  1370. * 判断题目级答题记录是否发生变化
  1371. */
  1372. private function hasAnswerQuestionsChanged(string $studentId, string $examId, array $newQuestions): bool
  1373. {
  1374. $existing = DB::connection('mysql')
  1375. ->table('student_answer_questions')
  1376. ->where('student_id', $studentId)
  1377. ->where('exam_id', $examId)
  1378. ->get(['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'])
  1379. ->map(fn ($row) => (array) $row)
  1380. ->toArray();
  1381. return $this->buildRecordsHash($existing, ['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'], ['score_obtained', 'max_score'])
  1382. !== $this->buildRecordsHash($newQuestions, ['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'], ['score_obtained', 'max_score']);
  1383. }
  1384. /**
  1385. * 构建记录哈希,用于判断是否变化
  1386. */
  1387. private function buildRecordsHash(array $rows, array $fields, array $numericFields = []): string
  1388. {
  1389. if (empty($rows)) {
  1390. return '[]';
  1391. }
  1392. $normalized = [];
  1393. $numericFieldMap = array_fill_keys($numericFields, true);
  1394. foreach ($rows as $row) {
  1395. $item = [];
  1396. foreach ($fields as $field) {
  1397. $value = $row[$field] ?? null;
  1398. if ($value !== null && isset($numericFieldMap[$field]) && is_numeric($value)) {
  1399. $value = sprintf('%.4F', (float) $value);
  1400. }
  1401. $item[$field] = $value;
  1402. }
  1403. $normalized[] = $item;
  1404. }
  1405. usort($normalized, fn ($a, $b) => json_encode($a) <=> json_encode($b));
  1406. return md5(json_encode($normalized));
  1407. }
  1408. /**
  1409. * 保存分析结果并创建掌握度快照
  1410. */
  1411. private function saveAnalysisResult(string $studentId, string $paperId, array $result): void
  1412. {
  1413. // 【修复】支持重复分析:先删除旧的分析结果
  1414. DB::connection('mysql')->table('exam_analysis_results')
  1415. ->where('student_id', $studentId)
  1416. ->where('paper_id', $paperId)
  1417. ->delete();
  1418. // 插入新的分析结果
  1419. DB::connection('mysql')->table('exam_analysis_results')->insert([
  1420. 'student_id' => $studentId,
  1421. 'paper_id' => $paperId,
  1422. 'analysis_data' => json_encode($result),
  1423. 'created_at' => now(),
  1424. 'updated_at' => now(),
  1425. ]);
  1426. Log::info('分析结果保存完成', [
  1427. 'student_id' => $studentId,
  1428. 'paper_id' => $paperId,
  1429. 'data_size' => strlen(json_encode($result)),
  1430. ]);
  1431. // 【新增】异步生成学情分析PDF
  1432. try {
  1433. Log::info('开始异步生成学情分析PDF', [
  1434. 'student_id' => $studentId,
  1435. 'paper_id' => $paperId,
  1436. ]);
  1437. // 使用队列异步生成PDF,避免阻塞主流程
  1438. dispatch(new \App\Jobs\GenerateAnalysisPdfJob($paperId, $studentId, null));
  1439. Log::info('PDF生成任务已加入队列', [
  1440. 'student_id' => $studentId,
  1441. 'paper_id' => $paperId,
  1442. ]);
  1443. } catch (\Exception $e) {
  1444. Log::error('PDF生成任务加入队列失败', [
  1445. 'student_id' => $studentId,
  1446. 'paper_id' => $paperId,
  1447. 'error' => $e->getMessage(),
  1448. ]);
  1449. }
  1450. }
  1451. /**
  1452. * 创建知识点掌握度快照
  1453. * 【集成】使用LocalAIAnalysisService的快照功能
  1454. *
  1455. * 快照用途:
  1456. * 1. 追踪学生掌握度变化趋势
  1457. * 2. 生成学情报告时对比历史数据
  1458. * 3. 为智能出卷提供决策依据
  1459. */
  1460. private function createMasterySnapshot(string $studentId, string $paperId, array $analysisResult): ?array
  1461. {
  1462. try {
  1463. // 计算快照数据
  1464. $masteryVector = $analysisResult['mastery_vector'] ?? [];
  1465. $overallMastery = 0;
  1466. $weakCount = 0;
  1467. $strongCount = 0;
  1468. foreach ($masteryVector as $kpData) {
  1469. $mastery = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1470. $overallMastery += $mastery;
  1471. if ($mastery < 0.6) {
  1472. $weakCount++;
  1473. } elseif ($mastery >= 0.85) {
  1474. $strongCount++;
  1475. }
  1476. }
  1477. $kpCount = count($masteryVector);
  1478. $overallMastery = $kpCount > 0 ? round($overallMastery / $kpCount, 4) : 0;
  1479. // Get all existing mastery records from database (as baseline)
  1480. // Use DB::table to avoid Eloquent accessor converting numbers to strings
  1481. $studentMasteries = DB::table('student_knowledge_mastery')
  1482. ->where('student_id', $studentId)
  1483. ->get(['kp_code', 'mastery_level']);
  1484. $currentMastery = [];
  1485. foreach ($studentMasteries as $record) {
  1486. $currentMastery[$record->kp_code] = (float) ($record->mastery_level ?? 0);
  1487. }
  1488. // Update with newly calculated mastery values from analysis result
  1489. foreach ($masteryVector as $kpData) {
  1490. $kpCode = $kpData['kp_id'] ?? null;
  1491. if (! $kpCode) {
  1492. continue;
  1493. }
  1494. $analysisLevel = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1495. // Use new analysis value if it's higher, or if there was no previous value
  1496. if (! isset($currentMastery[$kpCode]) || $analysisLevel > $currentMastery[$kpCode]) {
  1497. $currentMastery[$kpCode] = $analysisLevel;
  1498. }
  1499. }
  1500. // 生成快照ID
  1501. $snapshotId = 'snap_'.$paperId.'_'.now()->format('YmdHis').'_'.substr(uniqid(), -4);
  1502. // 保存到快照表
  1503. DB::connection('mysql')->table('knowledge_point_mastery_snapshots')->insert([
  1504. 'snapshot_id' => $snapshotId,
  1505. 'student_id' => $studentId,
  1506. 'paper_id' => $paperId,
  1507. 'answer_record_id' => null,
  1508. 'mastery_data' => json_encode($masteryVector),
  1509. 'current_mastery' => json_encode($currentMastery),
  1510. 'overall_mastery' => $overallMastery,
  1511. 'weak_knowledge_points_count' => $weakCount,
  1512. 'strong_knowledge_points_count' => $strongCount,
  1513. 'snapshot_time' => now(),
  1514. 'analysis_id' => null,
  1515. 'created_at' => now(),
  1516. 'updated_at' => now(),
  1517. ]);
  1518. Log::info('掌握度快照创建成功', [
  1519. 'snapshot_id' => $snapshotId,
  1520. 'student_id' => $studentId,
  1521. 'paper_id' => $paperId,
  1522. 'overall_mastery' => $overallMastery,
  1523. 'weak_count' => $weakCount,
  1524. 'strong_count' => $strongCount,
  1525. ]);
  1526. // 计算变化
  1527. $lastSnapshot = DB::connection('mysql')->table('knowledge_point_mastery_snapshots')
  1528. ->where('student_id', $studentId)
  1529. ->where('snapshot_id', '<>', $snapshotId)
  1530. ->orderBy('snapshot_time', 'desc')
  1531. ->first();
  1532. $gainCount = $lossCount = 0;
  1533. $overallChange = 0;
  1534. $compareCount = 0;
  1535. $changeAverage = 0;
  1536. if ($lastSnapshot && ! empty($lastSnapshot->current_mastery)) {
  1537. $lastCurrentMastery = json_decode($lastSnapshot->current_mastery, true);
  1538. if (is_array($lastCurrentMastery)) {
  1539. foreach ($currentMastery as $kp => $value) {
  1540. $prev = $lastCurrentMastery[$kp] ?? null;
  1541. if ($prev === null) {
  1542. $gainCount++;
  1543. } elseif ($value > $prev) {
  1544. $gainCount++;
  1545. } elseif ($value < $prev) {
  1546. $lossCount++;
  1547. }
  1548. if ($prev !== null) {
  1549. $overallChange += $value - $prev;
  1550. $compareCount++;
  1551. }
  1552. }
  1553. $changeAverage = $compareCount > 0 ? round($overallChange / $compareCount, 4) : 0;
  1554. Log::info('掌握度变化', [
  1555. 'student_id' => $studentId,
  1556. 'paper_id' => $paperId,
  1557. 'snapshot_id' => $snapshotId,
  1558. 'gain_count' => $gainCount,
  1559. 'loss_count' => $lossCount,
  1560. 'overall_change' => $changeAverage,
  1561. ]);
  1562. }
  1563. }
  1564. return [
  1565. 'snapshot_id' => $snapshotId,
  1566. 'current_mastery' => $currentMastery,
  1567. 'overall_mastery' => $overallMastery,
  1568. 'gain_count' => $gainCount,
  1569. 'loss_count' => $lossCount,
  1570. 'overall_change' => $changeAverage,
  1571. ];
  1572. } catch (\Exception $e) {
  1573. // 快照创建失败不影响主流程
  1574. Log::warning('掌握度快照创建失败', [
  1575. 'student_id' => $studentId,
  1576. 'paper_id' => $paperId,
  1577. 'error' => $e->getMessage(),
  1578. ]);
  1579. return null;
  1580. }
  1581. /**
  1582. * 判断掌握度趋势
  1583. */
  1584. /**
  1585. * 评估表现水平
  1586. */
  1587. private function evaluatePerformanceLevel(float $mastery): string
  1588. {
  1589. if ($mastery >= 0.85) {
  1590. return 'excellent';
  1591. } elseif ($mastery >= 0.70) {
  1592. return 'good';
  1593. } elseif ($mastery >= 0.50) {
  1594. return 'fair';
  1595. } else {
  1596. return 'poor';
  1597. }
  1598. }
  1599. /**
  1600. * 生成题目表现总结
  1601. */
  1602. private function generateQuestionPerformanceSummary(array $question, array $stepAnalysis): string
  1603. {
  1604. if (empty($stepAnalysis)) {
  1605. return '整题作答';
  1606. }
  1607. $correctSteps = count(array_filter($stepAnalysis, fn ($s) => $s['is_correct']));
  1608. $totalSteps = count($stepAnalysis);
  1609. if ($correctSteps === $totalSteps) {
  1610. return '所有步骤正确';
  1611. } elseif ($correctSteps > 0) {
  1612. return "部分正确 ({$correctSteps}/{$totalSteps} 步骤正确)";
  1613. } else {
  1614. return '所有步骤错误';
  1615. }
  1616. }
  1617. /**
  1618. * 生成知识点建议
  1619. */
  1620. private function generateKnowledgePointRecommendation(array $data): string
  1621. {
  1622. $mastery = $data['mastery'];
  1623. if ($mastery >= 0.85) {
  1624. return '掌握良好,可安排综合练习';
  1625. } elseif ($mastery >= 0.70) {
  1626. return '基本掌握,建议加强练习';
  1627. } elseif ($mastery >= 0.50) {
  1628. return '需要重点练习,建议安排专项训练';
  1629. } else {
  1630. return '薄弱知识点,建议系统学习和大量练习';
  1631. }
  1632. }
  1633. /**
  1634. * 评估整体表现
  1635. */
  1636. private function evaluateOverallPerformance(float $averageMastery): string
  1637. {
  1638. if ($averageMastery >= 0.85) {
  1639. return '优秀';
  1640. } elseif ($averageMastery >= 0.70) {
  1641. return '良好';
  1642. } elseif ($averageMastery >= 0.50) {
  1643. return '一般';
  1644. } else {
  1645. return '需加强';
  1646. }
  1647. }
  1648. /**
  1649. * 计算推荐题目数量
  1650. */
  1651. private function calculateRecommendedQuestions(float $mastery): int
  1652. {
  1653. if ($mastery >= 0.85) {
  1654. return 1; // 巩固型:1题
  1655. } elseif ($mastery >= 0.50) {
  1656. return 2; // 修补型:2题
  1657. } else {
  1658. return 3; // 挑战型:3题
  1659. }
  1660. }
  1661. /**
  1662. * 确定重点类型
  1663. */
  1664. private function determineFocusType(float $mastery): string
  1665. {
  1666. if ($mastery >= 0.70 && $mastery < 0.85) {
  1667. return 'consolidation'; // 巩固型
  1668. } elseif ($mastery < 0.70) {
  1669. return 'remediation'; // 修补型
  1670. } else {
  1671. return 'challenge'; // 挑战型
  1672. }
  1673. }
  1674. /**
  1675. * 自动计算题目分数并补充未提交的题目
  1676. *
  1677. * 功能:
  1678. * 1. 从 paper_questions 表获取卷子的所有题目
  1679. * 2. 补充未提交的题目(is_correct 默认为 [0],表示错误)
  1680. * 3. 自动计算 score 和 score_obtained
  1681. *
  1682. * @param array $questions 用户提交的题目列表
  1683. * @param string $paperId 卷子ID
  1684. * @return array 完整的题目列表(包含未提交的题目)
  1685. */
  1686. private function autoCalculateScores(array $questions, string $paperId = ''): array
  1687. {
  1688. // 获取已提交题目的ID集合
  1689. $submittedQuestionIds = [];
  1690. foreach ($questions as $question) {
  1691. $qid = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1692. if ($qid) {
  1693. $submittedQuestionIds[$qid] = true;
  1694. }
  1695. }
  1696. // 从 paper_questions 表获取卷子的所有题目
  1697. if (! empty($paperId)) {
  1698. try {
  1699. $paperQuestions = DB::connection('mysql')
  1700. ->table('paper_questions')
  1701. ->where('paper_id', $paperId)
  1702. ->get(['question_bank_id', 'question_id', 'score']);
  1703. foreach ($paperQuestions as $pq) {
  1704. // 优先用 question_bank_id,其次用 question_id
  1705. $questionId = $pq->question_bank_id ?? $pq->question_id ?? null;
  1706. if (empty($questionId)) {
  1707. continue;
  1708. }
  1709. if (isset($pq->score)) {
  1710. $scoreMap[$questionId] = (float) $pq->score;
  1711. }
  1712. // 如果该题目未提交,补充进去
  1713. if (! isset($submittedQuestionIds[$questionId])) {
  1714. $defaultScore = $pq->score ? floatval($pq->score) : 2.0;
  1715. $questions[] = [
  1716. 'question_id' => $questionId,
  1717. 'student_answer' => null,
  1718. 'is_correct' => [1], // 未提交默认为正确
  1719. 'teacher_comment' => null,
  1720. 'score' => $defaultScore,
  1721. 'score_obtained' => $defaultScore, // 正确则得满分
  1722. ];
  1723. Log::debug('补充未提交的题目', [
  1724. 'paper_id' => $paperId,
  1725. 'question_id' => $questionId,
  1726. 'default_score' => $pq->score ?? 2.0,
  1727. ]);
  1728. }
  1729. }
  1730. } catch (\Exception $e) {
  1731. Log::warning('获取卷子题目列表失败', [
  1732. 'paper_id' => $paperId,
  1733. 'error' => $e->getMessage(),
  1734. ]);
  1735. }
  1736. }
  1737. // 为已提交的题目计算分数
  1738. foreach ($questions as &$question) {
  1739. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? '';
  1740. // 如果用户没有提供 score,尝试从数据库获取或使用默认值
  1741. if (! isset($question['score'])) {
  1742. $question['score'] = $scoreMap[$questionId] ?? 2.0;
  1743. }
  1744. // 如果用户没有提供 score_obtained,根据 is_correct 计算
  1745. if (! isset($question['score_obtained'])) {
  1746. $question['score_obtained'] = $this->calculateScoreObtained(
  1747. $question['score'] ?? 0,
  1748. $question['is_correct'] ?? []
  1749. );
  1750. }
  1751. Log::debug('自动计算分数', [
  1752. 'question_id' => $questionId,
  1753. 'default_score' => $question['score'],
  1754. 'score_obtained' => $question['score_obtained'],
  1755. 'is_correct' => $question['is_correct'] ?? [],
  1756. ]);
  1757. }
  1758. return $questions;
  1759. }
  1760. /**
  1761. * 获取题目默认分数
  1762. */
  1763. private function getQuestionDefaultScore(string $questionId): float
  1764. {
  1765. if (empty($questionId)) {
  1766. return 2.0; // 默认分数
  1767. }
  1768. try {
  1769. // 尝试从题库获取题目分数
  1770. $question = DB::connection('mysql')
  1771. ->table('questions')
  1772. ->where('id', $questionId)
  1773. ->orWhere('question_code', $questionId)
  1774. ->first();
  1775. if ($question && isset($question->score)) {
  1776. return (float) $question->score;
  1777. }
  1778. // 如果没有找到,根据题目ID生成一个合理的默认分数
  1779. // 这里可以根据需要调整默认分数逻辑
  1780. return 2.0;
  1781. } catch (\Exception $e) {
  1782. Log::warning('获取题目默认分数失败,使用默认值', [
  1783. 'question_id' => $questionId,
  1784. 'error' => $e->getMessage(),
  1785. ]);
  1786. return 2.0;
  1787. }
  1788. }
  1789. /**
  1790. * 根据 is_correct 数组计算得分
  1791. *
  1792. * @param float $totalScore 总分
  1793. * @param array $isCorrect 正确性数组 [0, 1, 1] 表示第1题错误,第2、3题正确
  1794. * @return float 得分
  1795. */
  1796. private function calculateScoreObtained(float $totalScore, array $isCorrect): float
  1797. {
  1798. if (empty($isCorrect)) {
  1799. return 0.0;
  1800. }
  1801. $correctCount = array_sum($isCorrect);
  1802. $totalCount = count($isCorrect);
  1803. if ($totalCount === 0) {
  1804. return 0.0;
  1805. }
  1806. // 按正确率计算得分
  1807. $scoreRatio = $correctCount / $totalCount;
  1808. return round($totalScore * $scoreRatio, 2);
  1809. }
  1810. }