ExamAnswerAnalysisService.php 68 KB

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