ExamAnswerAnalysisService.php 87 KB

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