ExamAnswerAnalysisService.php 86 KB

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