ExamAnswerAnalysisService.php 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  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. // 【公司要求】移除置信度,只保留核心掌握度分析
  1009. $analysis[] = [
  1010. 'kp_id' => $kpId,
  1011. 'mastery_level' => $data['mastery'],
  1012. 'performance_in_exam' => $this->evaluatePerformanceLevel($data['mastery']),
  1013. 'evidence_count' => count($data['step_details']),
  1014. 'step_evidence' => $data['step_details'],
  1015. 'recommendation' => $this->generateKnowledgePointRecommendation($data),
  1016. ];
  1017. }
  1018. return $analysis;
  1019. }
  1020. /**
  1021. * 生成整体掌握度总结
  1022. */
  1023. private function generateOverallSummary(array $updatedMastery): array
  1024. {
  1025. $knowledgePoints = array_values($updatedMastery);
  1026. if (empty($knowledgePoints)) {
  1027. return [
  1028. 'total_knowledge_points' => 0,
  1029. 'average_mastery' => 0,
  1030. 'mastery_distribution' => [
  1031. 'mastered' => 0,
  1032. 'good' => 0,
  1033. 'weak' => 0,
  1034. ],
  1035. 'top_strengths' => [],
  1036. 'top_weaknesses' => [],
  1037. ];
  1038. }
  1039. // 计算平均掌握度(只计算子节点,不包括父节点)
  1040. $childNodes = array_filter($knowledgePoints, fn ($kp) => ! ($kp['is_parent'] ?? false));
  1041. $totalChildNodes = count($childNodes);
  1042. if ($totalChildNodes === 0) {
  1043. // 如果没有子节点,只计算所有节点
  1044. $averageMastery = array_sum(array_column($knowledgePoints, 'current_mastery')) / count($knowledgePoints);
  1045. } else {
  1046. // 计算所有节点的平均掌握度(包括父节点)
  1047. $allMastery = array_column($knowledgePoints, 'current_mastery');
  1048. $averageMastery = array_sum($allMastery) / count($allMastery);
  1049. }
  1050. // 掌握度分布(只统计子节点)
  1051. $mastered = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] >= 0.85);
  1052. $good = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] >= 0.70 && $kp['current_mastery'] < 0.85);
  1053. $weak = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] < 0.70);
  1054. // 排序找出优势和薄弱点(只包括子节点)
  1055. usort($childNodes, fn ($a, $b) => $b['current_mastery'] <=> $a['current_mastery']);
  1056. $topStrengths = array_slice($childNodes, 0, 3);
  1057. $topWeaknesses = array_slice(array_reverse($childNodes), 0, 3);
  1058. // 统计父子节点数量
  1059. $childCount = count(array_filter($knowledgePoints, fn ($kp) => ! ($kp['is_parent'] ?? false)));
  1060. $parentCount = count(array_filter($knowledgePoints, fn ($kp) => $kp['is_parent'] ?? false));
  1061. return [
  1062. 'total_knowledge_points' => $totalChildNodes, // 只统计子节点数量
  1063. 'child_nodes_count' => $childCount,
  1064. 'parent_nodes_count' => $parentCount,
  1065. 'average_mastery' => round($averageMastery, 4),
  1066. 'mastery_distribution' => [
  1067. 'mastered' => count($mastered),
  1068. 'good' => count($good),
  1069. 'weak' => count($weak),
  1070. ],
  1071. 'top_strengths' => $topStrengths,
  1072. 'top_weaknesses' => $topWeaknesses,
  1073. 'overall_performance' => $this->evaluateOverallPerformance($averageMastery),
  1074. ];
  1075. }
  1076. /**
  1077. * 生成智能出卷推荐依据
  1078. * 基于文档中的推荐优先级算法
  1079. */
  1080. private function generateSmartQuizRecommendation(array $updatedMastery): array
  1081. {
  1082. $recommendations = [];
  1083. // 只对子节点生成推荐,忽略父节点
  1084. foreach ($updatedMastery as $kpId => $data) {
  1085. // 跳过父节点
  1086. if ($data['is_parent'] ?? false) {
  1087. continue;
  1088. }
  1089. $mastery = $data['current_mastery'];
  1090. // 【公司要求】移除置信度,只使用掌握度计算推荐
  1091. $weight = $data['weight'];
  1092. // 推荐优先级 = (1 - 掌握度) * 重要性 * 覆盖需求
  1093. // 重要性可以根据知识点在中考/阶段考试中的权重,这里简化为1.0
  1094. $importance = 1.0;
  1095. // 覆盖需求:最近没考过或考得少,值大
  1096. $coverageNeed = max(1.0, 1.5 - ($weight / 10));
  1097. $priority = (1 - $mastery) * $importance * $coverageNeed;
  1098. $recommendations[] = [
  1099. 'kp_id' => $kpId,
  1100. 'current_mastery' => $mastery,
  1101. 'priority' => $priority,
  1102. 'recommended_questions' => $this->calculateRecommendedQuestions($mastery),
  1103. 'focus_type' => $this->determineFocusType($mastery),
  1104. ];
  1105. }
  1106. // 按优先级排序
  1107. usort($recommendations, fn ($a, $b) => $b['priority'] <=> $a['priority']);
  1108. // 控制难度节奏:40%巩固型 + 40%修补型 + 20%挑战型
  1109. $totalRecommendations = count($recommendations);
  1110. $consolidation = array_slice($recommendations, 0, intval($totalRecommendations * 0.4));
  1111. $remediation = array_slice($recommendations, intval($totalRecommendations * 0.4), intval($totalRecommendations * 0.4));
  1112. $challenge = array_slice($recommendations, intval($totalRecommendations * 0.8));
  1113. return [
  1114. 'priority_list' => $recommendations,
  1115. 'quiz_structure' => [
  1116. 'consolidation_type' => $consolidation,
  1117. 'remediation_type' => $remediation,
  1118. 'challenge_type' => $challenge,
  1119. ],
  1120. 'total_recommended_questions' => array_sum(array_column($recommendations, 'recommended_questions')),
  1121. ];
  1122. }
  1123. /**
  1124. * 保存考试答题记录
  1125. *
  1126. * 入参格式示例:
  1127. * {
  1128. * "question_bank_id": "12979",
  1129. * "student_answer": "C",
  1130. * "is_correct": [0], // 数组长度决定步骤数,0=错误,1=正确
  1131. * "teacher_comment": null
  1132. * }
  1133. *
  1134. * is_correct 数组说明:
  1135. * - 单选题:[1] 或 [0],长度为1
  1136. * - 填空题:[1, 0, 1],每个空一个元素
  1137. * - 简答题:[1, 1, 0, 1],每个得分步骤一个元素
  1138. */
  1139. /**
  1140. * 保存错题记录
  1141. *
  1142. * @param string $studentId 学生ID
  1143. * @param string $questionId 题目ID
  1144. * @param string $examId 考试ID
  1145. * @param array $question 题目数据
  1146. * @param array|null $kpMapping 知识点映射(数组格式:[kp_id1, kp_id2] 或 null)
  1147. */
  1148. private function saveMistakeRecord(string $studentId, string $questionId, string $examId, array $question, ?array $kpMapping): void
  1149. {
  1150. try {
  1151. // 如果 $kpMapping 是数组,说明是多个 kp_id
  1152. // 如果是关联数组,说明是单个 kpMapping(兼容旧调用)
  1153. $kpIds = null;
  1154. if (is_array($kpMapping)) {
  1155. // 检查是数组的数组(多个kp_id)还是关联数组(单个kpMapping)
  1156. if (isset($kpMapping[0])) {
  1157. // 数组的数组:[[kp_id: '...'], [kp_id: '...']]
  1158. $kpIds = array_column($kpMapping, 'kp_id');
  1159. } else {
  1160. // 关联数组:[kp_id: '...']
  1161. $kpIds = [$kpMapping['kp_id']];
  1162. }
  1163. }
  1164. $payload = [
  1165. 'student_id' => $studentId,
  1166. 'question_id' => $questionId,
  1167. 'paper_id' => $examId,
  1168. 'my_answer' => $question['student_answer'] ?? null,
  1169. 'correct_answer' => null, // 可以从题目表获取
  1170. 'question_text' => null, // 可以从题目表获取
  1171. 'knowledge_point' => null, // 不保存name,只保存kp_ids
  1172. 'kp_ids' => $kpIds, // 保存为数组格式
  1173. 'source' => $examId, // 来源标记使用卷子ID
  1174. 'happened_at' => now(),
  1175. ];
  1176. $result = $this->mistakeBookService->createMistake($payload);
  1177. if (($result['duplicate'] ?? false) === false) {
  1178. Log::debug('错题记录保存成功', [
  1179. 'student_id' => $studentId,
  1180. 'question_id' => $questionId,
  1181. 'mistake_id' => $result['mistake_id'] ?? null,
  1182. ]);
  1183. }
  1184. } catch (\Exception $e) {
  1185. Log::warning('错题记录保存失败(不中断主流程)', [
  1186. 'student_id' => $studentId,
  1187. 'question_id' => $questionId,
  1188. 'exam_id' => $examId,
  1189. 'error' => $e->getMessage(),
  1190. ]);
  1191. }
  1192. }
  1193. /**
  1194. * 保存答题记录(优化版:批量INSERT)
  1195. *
  1196. * @param array $examData 考试数据
  1197. * @param array $questionMappings 已批量查询的知识点映射,避免N+1
  1198. */
  1199. private function saveExamAnswerRecords(array $examData, array $questionMappings = []): array
  1200. {
  1201. // 【修复】确保类型正确,避免 SQL 类型转换问题
  1202. $studentId = (string) $examData['student_id'];
  1203. $examId = (string) $examData['paper_id'];
  1204. $now = now();
  1205. // 【优化】收集所有要插入的记录,最后批量INSERT
  1206. $stepsToInsert = [];
  1207. $questionsToInsert = [];
  1208. $mistakesToSave = []; // 收集错题记录
  1209. foreach ($examData['questions'] as $question) {
  1210. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1211. if (empty($questionId)) {
  1212. continue;
  1213. }
  1214. // 【优化】使用传入的映射,不再查询数据库
  1215. $kpMappings = $questionMappings[$questionId]['kp_mapping'] ?? [];
  1216. $isCorrectArray = $question['is_correct'] ?? [];
  1217. if (! is_array($isCorrectArray)) {
  1218. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  1219. }
  1220. $stepCount = count($isCorrectArray);
  1221. if ($stepCount > 1 || ! empty($kpMappings)) {
  1222. // 多步骤题目:收集步骤记录
  1223. $scorePerStep = ($question['score'] ?? 0) / max($stepCount, 1);
  1224. $hasMistake = false;
  1225. $allErrorKpCodes = [];
  1226. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  1227. $isCorrectBool = (int) $isCorrect === 1;
  1228. if (! empty($kpMappings)) {
  1229. foreach ($kpMappings as $kpMapping) {
  1230. $stepsToInsert[] = [
  1231. 'student_id' => $studentId,
  1232. 'exam_id' => $examId,
  1233. 'question_id' => $questionId,
  1234. 'step_index' => $stepIndex,
  1235. 'kp_id' => $kpMapping['kp_id'],
  1236. 'is_correct' => $isCorrectBool ? 1 : 0,
  1237. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1238. 'created_at' => $now,
  1239. 'updated_at' => $now,
  1240. ];
  1241. if (! $isCorrectBool) {
  1242. $hasMistake = true;
  1243. $allErrorKpCodes[] = $kpMapping['kp_id'];
  1244. }
  1245. }
  1246. } else {
  1247. $stepsToInsert[] = [
  1248. 'student_id' => $studentId,
  1249. 'exam_id' => $examId,
  1250. 'question_id' => $questionId,
  1251. 'step_index' => $stepIndex,
  1252. 'kp_id' => null,
  1253. 'is_correct' => $isCorrectBool ? 1 : 0,
  1254. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1255. 'created_at' => $now,
  1256. 'updated_at' => $now,
  1257. ];
  1258. if (! $isCorrectBool) {
  1259. $hasMistake = true;
  1260. }
  1261. }
  1262. }
  1263. // 收集错题记录
  1264. if ($hasMistake) {
  1265. $uniqueKpCodes = array_values(array_unique($allErrorKpCodes));
  1266. $mistakesToSave[] = [
  1267. 'questionId' => $questionId,
  1268. 'question' => $question,
  1269. 'kpMappings' => array_map(fn ($code) => ['kp_id' => $code], $uniqueKpCodes),
  1270. ];
  1271. }
  1272. } else {
  1273. // 单步骤题目:收集题目级记录
  1274. $questionsToInsert[] = [
  1275. 'student_id' => $studentId,
  1276. 'exam_id' => $examId,
  1277. 'question_id' => $questionId,
  1278. 'score_obtained' => $question['score_obtained'] ?? 0,
  1279. 'max_score' => $question['score'] ?? 0,
  1280. 'created_at' => $now,
  1281. 'updated_at' => $now,
  1282. ];
  1283. // 收集错题记录
  1284. if (($question['score_obtained'] ?? 0) <= 0) {
  1285. $mistakesToSave[] = [
  1286. 'questionId' => $questionId,
  1287. 'question' => $question,
  1288. 'kpMappings' => ! empty($kpMappings)
  1289. ? array_map(fn ($m) => ['kp_id' => $m['kp_id']], $kpMappings)
  1290. : null,
  1291. ];
  1292. }
  1293. }
  1294. }
  1295. // 判断是否有变更,避免重复删除/插入
  1296. $stepsChanged = $this->hasAnswerStepsChanged($studentId, $examId, $stepsToInsert);
  1297. $questionsChanged = $this->hasAnswerQuestionsChanged($studentId, $examId, $questionsToInsert);
  1298. if ($stepsChanged || $questionsChanged) {
  1299. // 先清理该考试的所有答题记录(支持重复提交)
  1300. try {
  1301. if ($questionsChanged) {
  1302. DB::connection('mysql')->table('student_answer_questions')
  1303. ->where('student_id', '=', $studentId)
  1304. ->where('exam_id', '=', $examId)
  1305. ->delete();
  1306. }
  1307. if ($stepsChanged) {
  1308. DB::connection('mysql')->table('student_answer_steps')
  1309. ->where('student_id', '=', $studentId)
  1310. ->where('exam_id', '=', $examId)
  1311. ->delete();
  1312. }
  1313. Log::info('清理旧答题记录成功', [
  1314. 'student_id' => $studentId,
  1315. 'exam_id' => $examId,
  1316. 'steps_changed' => $stepsChanged,
  1317. 'questions_changed' => $questionsChanged,
  1318. ]);
  1319. } catch (\Exception $e) {
  1320. // 清理失败时抛出异常,避免后续插入重复数据
  1321. Log::error('清理旧答题记录失败', [
  1322. 'student_id' => $studentId,
  1323. 'exam_id' => $examId,
  1324. 'error' => $e->getMessage(),
  1325. ]);
  1326. throw $e;
  1327. }
  1328. // 【优化】批量 INSERT(每500条一批,避免超过MySQL限制)
  1329. try {
  1330. if ($stepsChanged && ! empty($stepsToInsert)) {
  1331. foreach (array_chunk($stepsToInsert, 500) as $chunk) {
  1332. DB::connection('mysql')->table('student_answer_steps')->insert($chunk);
  1333. }
  1334. }
  1335. if ($questionsChanged && ! empty($questionsToInsert)) {
  1336. foreach (array_chunk($questionsToInsert, 500) as $chunk) {
  1337. DB::connection('mysql')->table('student_answer_questions')->insert($chunk);
  1338. }
  1339. }
  1340. } catch (\Exception $e) {
  1341. Log::error('批量保存答题记录失败', [
  1342. 'student_id' => $studentId,
  1343. 'exam_id' => $examId,
  1344. 'error' => $e->getMessage(),
  1345. ]);
  1346. }
  1347. }
  1348. // 保存错题记录(批量处理,避免逐条写入)
  1349. if (! empty($mistakesToSave)) {
  1350. $payloads = [];
  1351. foreach ($mistakesToSave as $mistake) {
  1352. $kpIds = null;
  1353. if (is_array($mistake['kpMappings'])) {
  1354. $kpIds = isset($mistake['kpMappings'][0])
  1355. ? array_column($mistake['kpMappings'], 'kp_id')
  1356. : [$mistake['kpMappings']['kp_id'] ?? null];
  1357. }
  1358. $payloads[] = [
  1359. 'student_id' => $studentId,
  1360. 'question_id' => $mistake['questionId'],
  1361. 'paper_id' => $examId,
  1362. 'my_answer' => $mistake['question']['student_answer'] ?? null,
  1363. 'correct_answer' => null,
  1364. 'question_text' => null,
  1365. 'knowledge_point' => null,
  1366. 'kp_ids' => $kpIds,
  1367. 'source' => $examId,
  1368. 'happened_at' => now(),
  1369. ];
  1370. }
  1371. $this->mistakeBookService->createMistakesBatch($payloads);
  1372. }
  1373. Log::info('答题记录保存完成', [
  1374. 'student_id' => $studentId,
  1375. 'exam_id' => $examId,
  1376. 'total_questions' => count($examData['questions']),
  1377. 'steps_saved' => count($stepsToInsert),
  1378. 'questions_saved' => count($questionsToInsert),
  1379. 'steps_changed' => $stepsChanged,
  1380. 'questions_changed' => $questionsChanged,
  1381. ]);
  1382. return [
  1383. 'steps_changed' => $stepsChanged,
  1384. 'questions_changed' => $questionsChanged,
  1385. ];
  1386. }
  1387. /**
  1388. * 同步更新 paper_questions 的判分字段
  1389. * 适配 /api/exam-answer-analysis:保持题目判分与分析数据一致
  1390. */
  1391. private function syncPaperQuestionGrading(array $examData): void
  1392. {
  1393. $paperId = (string) ($examData['paper_id'] ?? '');
  1394. if ($paperId === '' || empty($examData['questions']) || !is_array($examData['questions'])) {
  1395. return;
  1396. }
  1397. $now = now();
  1398. $updated = 0;
  1399. $questionIds = [];
  1400. foreach ($examData['questions'] as $question) {
  1401. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1402. if (!empty($questionId)) {
  1403. $questionIds[] = (string) $questionId;
  1404. }
  1405. }
  1406. $questionIds = array_values(array_unique($questionIds));
  1407. if (empty($questionIds)) {
  1408. return;
  1409. }
  1410. $paperQuestionRows = DB::connection('mysql')->table('paper_questions')
  1411. ->where('paper_id', $paperId)
  1412. ->where(function ($q) use ($questionIds) {
  1413. $q->whereIn('question_bank_id', $questionIds)
  1414. ->orWhereIn('question_id', $questionIds);
  1415. })
  1416. ->get(['id', 'question_bank_id', 'question_id']);
  1417. $rowIdsByQuestionId = [];
  1418. foreach ($paperQuestionRows as $row) {
  1419. if (!empty($row->question_bank_id)) {
  1420. $rowIdsByQuestionId[(string) $row->question_bank_id][] = (int) $row->id;
  1421. }
  1422. if (!empty($row->question_id)) {
  1423. $rowIdsByQuestionId[(string) $row->question_id][] = (int) $row->id;
  1424. }
  1425. }
  1426. $updateRowsById = [];
  1427. foreach ($examData['questions'] as $question) {
  1428. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1429. if (empty($questionId)) {
  1430. continue;
  1431. }
  1432. $questionId = (string) $questionId;
  1433. $targetRowIds = $rowIdsByQuestionId[$questionId] ?? [];
  1434. if (empty($targetRowIds)) {
  1435. continue;
  1436. }
  1437. $isCorrectArray = $question['is_correct'] ?? [];
  1438. if (!is_array($isCorrectArray)) {
  1439. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  1440. }
  1441. $totalSteps = count($isCorrectArray);
  1442. $correctSteps = array_sum(array_map(fn ($v) => (int) $v === 1 ? 1 : 0, $isCorrectArray));
  1443. $scoreRatio = $totalSteps > 0 ? round($correctSteps / $totalSteps, 4) : null;
  1444. $isFullyCorrect = $totalSteps > 0 ? ($correctSteps === $totalSteps ? 1 : 0) : null;
  1445. $scoreObtained = $question['score_obtained'] ?? null;
  1446. foreach ($targetRowIds as $rowId) {
  1447. $payload = [
  1448. 'id' => $rowId,
  1449. 'graded_at' => $now,
  1450. ];
  1451. if ($isFullyCorrect !== null) {
  1452. $payload['is_correct'] = $isFullyCorrect;
  1453. }
  1454. if ($scoreRatio !== null) {
  1455. $payload['score_ratio'] = $scoreRatio;
  1456. }
  1457. if ($scoreObtained !== null) {
  1458. $payload['score_obtained'] = $scoreObtained;
  1459. }
  1460. if (array_key_exists('student_answer', $question)) {
  1461. $payload['student_answer'] = $question['student_answer'];
  1462. }
  1463. if (array_key_exists('teacher_comment', $question)) {
  1464. $payload['teacher_comment'] = $question['teacher_comment'];
  1465. }
  1466. $updateRowsById[$rowId] = $payload;
  1467. }
  1468. }
  1469. if (!empty($updateRowsById)) {
  1470. $updateRows = array_values($updateRowsById);
  1471. $fields = ['graded_at', 'is_correct', 'score_ratio', 'score_obtained', 'student_answer', 'teacher_comment'];
  1472. $cases = [];
  1473. $bindings = [];
  1474. foreach ($fields as $field) {
  1475. $caseSql = "`{$field}` = CASE `id`";
  1476. $hasValue = false;
  1477. foreach ($updateRows as $row) {
  1478. if (!array_key_exists($field, $row)) {
  1479. continue;
  1480. }
  1481. $hasValue = true;
  1482. $caseSql .= ' WHEN ? THEN ?';
  1483. $bindings[] = $row['id'];
  1484. $bindings[] = $row[$field];
  1485. }
  1486. $caseSql .= " ELSE `{$field}` END";
  1487. if ($hasValue) {
  1488. $cases[] = $caseSql;
  1489. }
  1490. }
  1491. if (!empty($cases)) {
  1492. $ids = array_column($updateRows, 'id');
  1493. $idPlaceholders = implode(',', array_fill(0, count($ids), '?'));
  1494. $sql = 'UPDATE `paper_questions` SET '.implode(', ', $cases)." WHERE `id` IN ({$idPlaceholders})";
  1495. foreach ($ids as $id) {
  1496. $bindings[] = $id;
  1497. }
  1498. $updated = DB::connection('mysql')->update($sql, $bindings);
  1499. }
  1500. }
  1501. if ($updated > 0) {
  1502. DB::connection('mysql')->table('papers')
  1503. ->where('paper_id', $paperId)
  1504. ->update([
  1505. 'status' => 'completed',
  1506. 'completed_at' => $now,
  1507. 'updated_at' => $now,
  1508. ]);
  1509. }
  1510. Log::info('paper_questions 判分同步完成', [
  1511. 'paper_id' => $paperId,
  1512. 'input_question_count' => count($examData['questions']),
  1513. 'updated_rows' => $updated,
  1514. ]);
  1515. }
  1516. /**
  1517. * 判断答题步骤记录是否发生变化
  1518. */
  1519. private function hasAnswerStepsChanged(string $studentId, string $examId, array $newSteps): bool
  1520. {
  1521. $existing = DB::connection('mysql')
  1522. ->table('student_answer_steps')
  1523. ->where('student_id', $studentId)
  1524. ->where('exam_id', $examId)
  1525. ->get(['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'])
  1526. ->map(fn ($row) => (array) $row)
  1527. ->toArray();
  1528. return $this->buildRecordsHash($existing, ['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'], ['step_score'])
  1529. !== $this->buildRecordsHash($newSteps, ['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'], ['step_score']);
  1530. }
  1531. /**
  1532. * 判断题目级答题记录是否发生变化
  1533. */
  1534. private function hasAnswerQuestionsChanged(string $studentId, string $examId, array $newQuestions): bool
  1535. {
  1536. $existing = DB::connection('mysql')
  1537. ->table('student_answer_questions')
  1538. ->where('student_id', $studentId)
  1539. ->where('exam_id', $examId)
  1540. ->get(['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'])
  1541. ->map(fn ($row) => (array) $row)
  1542. ->toArray();
  1543. return $this->buildRecordsHash($existing, ['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'], ['score_obtained', 'max_score'])
  1544. !== $this->buildRecordsHash($newQuestions, ['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'], ['score_obtained', 'max_score']);
  1545. }
  1546. /**
  1547. * 构建记录哈希,用于判断是否变化
  1548. */
  1549. private function buildRecordsHash(array $rows, array $fields, array $numericFields = []): string
  1550. {
  1551. if (empty($rows)) {
  1552. return '[]';
  1553. }
  1554. $normalized = [];
  1555. $numericFieldMap = array_fill_keys($numericFields, true);
  1556. foreach ($rows as $row) {
  1557. $item = [];
  1558. foreach ($fields as $field) {
  1559. $value = $row[$field] ?? null;
  1560. if ($value !== null && isset($numericFieldMap[$field]) && is_numeric($value)) {
  1561. $value = sprintf('%.4F', (float) $value);
  1562. }
  1563. $item[$field] = $value;
  1564. }
  1565. $normalized[] = $item;
  1566. }
  1567. usort($normalized, fn ($a, $b) => json_encode($a) <=> json_encode($b));
  1568. return md5(json_encode($normalized));
  1569. }
  1570. /**
  1571. * 保存分析结果并创建掌握度快照
  1572. */
  1573. private function saveAnalysisResult(string $studentId, string $paperId, array $result): void
  1574. {
  1575. // 【修复】支持重复分析:先删除旧的分析结果
  1576. DB::connection('mysql')->table('exam_analysis_results')
  1577. ->where('student_id', $studentId)
  1578. ->where('paper_id', $paperId)
  1579. ->delete();
  1580. // 插入新的分析结果
  1581. DB::connection('mysql')->table('exam_analysis_results')->insert([
  1582. 'student_id' => $studentId,
  1583. 'paper_id' => $paperId,
  1584. 'analysis_data' => json_encode($result),
  1585. 'created_at' => now(),
  1586. 'updated_at' => now(),
  1587. ]);
  1588. Log::info('分析结果保存完成', [
  1589. 'student_id' => $studentId,
  1590. 'paper_id' => $paperId,
  1591. 'data_size' => strlen(json_encode($result)),
  1592. ]);
  1593. // 【新增】异步生成学情分析PDF
  1594. try {
  1595. Log::info('开始异步生成学情分析PDF', [
  1596. 'student_id' => $studentId,
  1597. 'paper_id' => $paperId,
  1598. ]);
  1599. // 使用队列异步生成PDF,避免阻塞主流程
  1600. dispatch(new \App\Jobs\GenerateAnalysisPdfJob($paperId, $studentId, null));
  1601. Log::info('PDF生成任务已加入队列', [
  1602. 'student_id' => $studentId,
  1603. 'paper_id' => $paperId,
  1604. ]);
  1605. } catch (\Exception $e) {
  1606. Log::error('PDF生成任务加入队列失败', [
  1607. 'student_id' => $studentId,
  1608. 'paper_id' => $paperId,
  1609. 'error' => $e->getMessage(),
  1610. ]);
  1611. }
  1612. }
  1613. /**
  1614. * 创建知识点掌握度快照
  1615. * 【集成】使用LocalAIAnalysisService的快照功能
  1616. *
  1617. * 快照用途:
  1618. * 1. 追踪学生掌握度变化趋势
  1619. * 2. 生成学情报告时对比历史数据
  1620. * 3. 为智能出卷提供决策依据
  1621. */
  1622. private function createMasterySnapshot(string $studentId, string $paperId, array $analysisResult): ?array
  1623. {
  1624. try {
  1625. // 计算快照数据
  1626. $masteryVector = $analysisResult['mastery_vector'] ?? [];
  1627. $overallMastery = 0;
  1628. $weakCount = 0;
  1629. $strongCount = 0;
  1630. foreach ($masteryVector as $kpData) {
  1631. $mastery = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1632. $overallMastery += $mastery;
  1633. if ($mastery < 0.6) {
  1634. $weakCount++;
  1635. } elseif ($mastery >= 0.85) {
  1636. $strongCount++;
  1637. }
  1638. }
  1639. $kpCount = count($masteryVector);
  1640. $overallMastery = $kpCount > 0 ? round($overallMastery / $kpCount, 4) : 0;
  1641. // Get all existing mastery records from database (as baseline)
  1642. // Use DB::table to avoid Eloquent accessor converting numbers to strings
  1643. $studentMasteries = DB::table('student_knowledge_mastery')
  1644. ->where('student_id', $studentId)
  1645. ->get(['kp_code', 'mastery_level']);
  1646. $currentMastery = [];
  1647. foreach ($studentMasteries as $record) {
  1648. $currentMastery[$record->kp_code] = (float) ($record->mastery_level ?? 0);
  1649. }
  1650. // Update with newly calculated mastery values from analysis result
  1651. foreach ($masteryVector as $kpData) {
  1652. $kpCode = $kpData['kp_id'] ?? null;
  1653. if (! $kpCode) {
  1654. continue;
  1655. }
  1656. $analysisLevel = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1657. // Use new analysis value if it's higher, or if there was no previous value
  1658. if (! isset($currentMastery[$kpCode]) || $analysisLevel > $currentMastery[$kpCode]) {
  1659. $currentMastery[$kpCode] = $analysisLevel;
  1660. }
  1661. }
  1662. // 生成快照ID
  1663. $snapshotId = 'snap_'.$paperId.'_'.now()->format('YmdHis').'_'.substr(uniqid(), -4);
  1664. // 保存到快照表
  1665. DB::connection('mysql')->table('knowledge_point_mastery_snapshots')->insert([
  1666. 'snapshot_id' => $snapshotId,
  1667. 'student_id' => $studentId,
  1668. 'paper_id' => $paperId,
  1669. 'answer_record_id' => null,
  1670. 'mastery_data' => json_encode($masteryVector),
  1671. 'current_mastery' => json_encode($currentMastery),
  1672. 'overall_mastery' => $overallMastery,
  1673. 'weak_knowledge_points_count' => $weakCount,
  1674. 'strong_knowledge_points_count' => $strongCount,
  1675. 'snapshot_time' => now(),
  1676. 'analysis_id' => null,
  1677. 'created_at' => now(),
  1678. 'updated_at' => now(),
  1679. ]);
  1680. Log::info('掌握度快照创建成功', [
  1681. 'snapshot_id' => $snapshotId,
  1682. 'student_id' => $studentId,
  1683. 'paper_id' => $paperId,
  1684. 'overall_mastery' => $overallMastery,
  1685. 'weak_count' => $weakCount,
  1686. 'strong_count' => $strongCount,
  1687. ]);
  1688. // 计算变化
  1689. $lastSnapshot = DB::connection('mysql')->table('knowledge_point_mastery_snapshots')
  1690. ->where('student_id', $studentId)
  1691. ->where('snapshot_id', '<>', $snapshotId)
  1692. ->orderBy('snapshot_time', 'desc')
  1693. ->first();
  1694. $gainCount = $lossCount = 0;
  1695. $overallChange = 0;
  1696. $compareCount = 0;
  1697. $changeAverage = 0;
  1698. if ($lastSnapshot && ! empty($lastSnapshot->current_mastery)) {
  1699. $lastCurrentMastery = json_decode($lastSnapshot->current_mastery, true);
  1700. if (is_array($lastCurrentMastery)) {
  1701. foreach ($currentMastery as $kp => $value) {
  1702. $prev = $lastCurrentMastery[$kp] ?? null;
  1703. if ($prev === null) {
  1704. $gainCount++;
  1705. } elseif ($value > $prev) {
  1706. $gainCount++;
  1707. } elseif ($value < $prev) {
  1708. $lossCount++;
  1709. }
  1710. if ($prev !== null) {
  1711. $overallChange += $value - $prev;
  1712. $compareCount++;
  1713. }
  1714. }
  1715. $changeAverage = $compareCount > 0 ? round($overallChange / $compareCount, 4) : 0;
  1716. Log::info('掌握度变化', [
  1717. 'student_id' => $studentId,
  1718. 'paper_id' => $paperId,
  1719. 'snapshot_id' => $snapshotId,
  1720. 'gain_count' => $gainCount,
  1721. 'loss_count' => $lossCount,
  1722. 'overall_change' => $changeAverage,
  1723. ]);
  1724. }
  1725. }
  1726. return [
  1727. 'snapshot_id' => $snapshotId,
  1728. 'current_mastery' => $currentMastery,
  1729. 'overall_mastery' => $overallMastery,
  1730. 'gain_count' => $gainCount,
  1731. 'loss_count' => $lossCount,
  1732. 'overall_change' => $changeAverage,
  1733. ];
  1734. } catch (\Exception $e) {
  1735. // 快照创建失败不影响主流程
  1736. Log::warning('掌握度快照创建失败', [
  1737. 'student_id' => $studentId,
  1738. 'paper_id' => $paperId,
  1739. 'error' => $e->getMessage(),
  1740. ]);
  1741. return null;
  1742. }
  1743. }
  1744. /**
  1745. * 判断掌握度趋势
  1746. */
  1747. /**
  1748. * 评估表现水平
  1749. */
  1750. private function evaluatePerformanceLevel(float $mastery): string
  1751. {
  1752. if ($mastery >= 0.85) {
  1753. return 'excellent';
  1754. } elseif ($mastery >= 0.70) {
  1755. return 'good';
  1756. } elseif ($mastery >= 0.50) {
  1757. return 'fair';
  1758. } else {
  1759. return 'poor';
  1760. }
  1761. }
  1762. /**
  1763. * 生成题目表现总结
  1764. */
  1765. private function generateQuestionPerformanceSummary(array $question, array $stepAnalysis): string
  1766. {
  1767. if (empty($stepAnalysis)) {
  1768. return '整题作答';
  1769. }
  1770. $correctSteps = count(array_filter($stepAnalysis, fn ($s) => $s['is_correct']));
  1771. $totalSteps = count($stepAnalysis);
  1772. if ($correctSteps === $totalSteps) {
  1773. return '所有步骤正确';
  1774. } elseif ($correctSteps > 0) {
  1775. return "部分正确 ({$correctSteps}/{$totalSteps} 步骤正确)";
  1776. } else {
  1777. return '所有步骤错误';
  1778. }
  1779. }
  1780. /**
  1781. * 生成知识点建议
  1782. */
  1783. private function generateKnowledgePointRecommendation(array $data): string
  1784. {
  1785. $mastery = $data['mastery'];
  1786. if ($mastery >= 0.85) {
  1787. return '掌握良好,可安排综合练习';
  1788. } elseif ($mastery >= 0.70) {
  1789. return '基本掌握,建议加强练习';
  1790. } elseif ($mastery >= 0.50) {
  1791. return '需要重点练习,建议安排专项训练';
  1792. } else {
  1793. return '薄弱知识点,建议系统学习和大量练习';
  1794. }
  1795. }
  1796. /**
  1797. * 评估整体表现
  1798. */
  1799. private function evaluateOverallPerformance(float $averageMastery): string
  1800. {
  1801. if ($averageMastery >= 0.85) {
  1802. return '优秀';
  1803. } elseif ($averageMastery >= 0.70) {
  1804. return '良好';
  1805. } elseif ($averageMastery >= 0.50) {
  1806. return '一般';
  1807. } else {
  1808. return '需加强';
  1809. }
  1810. }
  1811. /**
  1812. * 计算推荐题目数量
  1813. */
  1814. private function calculateRecommendedQuestions(float $mastery): int
  1815. {
  1816. if ($mastery >= 0.85) {
  1817. return 1; // 巩固型:1题
  1818. } elseif ($mastery >= 0.50) {
  1819. return 2; // 修补型:2题
  1820. } else {
  1821. return 3; // 挑战型:3题
  1822. }
  1823. }
  1824. /**
  1825. * 确定重点类型
  1826. */
  1827. private function determineFocusType(float $mastery): string
  1828. {
  1829. if ($mastery >= 0.70 && $mastery < 0.85) {
  1830. return 'consolidation'; // 巩固型
  1831. } elseif ($mastery < 0.70) {
  1832. return 'remediation'; // 修补型
  1833. } else {
  1834. return 'challenge'; // 挑战型
  1835. }
  1836. }
  1837. /**
  1838. * 自动计算题目分数并补充未提交的题目
  1839. *
  1840. * 功能:
  1841. * 1. 从 paper_questions 表获取卷子的所有题目
  1842. * 2. 补充未提交的题目(is_correct 默认为 [0],表示错误)
  1843. * 3. 自动计算 score 和 score_obtained
  1844. *
  1845. * @param array $questions 用户提交的题目列表
  1846. * @param string $paperId 卷子ID
  1847. * @return array 完整的题目列表(包含未提交的题目)
  1848. */
  1849. private function autoCalculateScores(array $questions, string $paperId = ''): array
  1850. {
  1851. // 获取已提交题目的ID集合
  1852. $submittedQuestionIds = [];
  1853. foreach ($questions as $question) {
  1854. $qid = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1855. if ($qid) {
  1856. $submittedQuestionIds[$qid] = true;
  1857. }
  1858. }
  1859. // 从 paper_questions 表获取卷子的所有题目
  1860. if (! empty($paperId)) {
  1861. try {
  1862. $paperQuestions = DB::connection('mysql')
  1863. ->table('paper_questions')
  1864. ->where('paper_id', $paperId)
  1865. ->get(['question_bank_id', 'question_id', 'score']);
  1866. foreach ($paperQuestions as $pq) {
  1867. // 优先用 question_bank_id,其次用 question_id
  1868. $questionId = $pq->question_bank_id ?? $pq->question_id ?? null;
  1869. if (empty($questionId)) {
  1870. continue;
  1871. }
  1872. if (isset($pq->score)) {
  1873. $scoreMap[$questionId] = (float) $pq->score;
  1874. }
  1875. // 如果该题目未提交,补充进去
  1876. if (! isset($submittedQuestionIds[$questionId])) {
  1877. $defaultScore = $pq->score ? floatval($pq->score) : 2.0;
  1878. $questions[] = [
  1879. 'question_id' => $questionId,
  1880. 'student_answer' => null,
  1881. 'is_correct' => [1], // 未提交默认为正确
  1882. 'teacher_comment' => null,
  1883. 'score' => $defaultScore,
  1884. 'score_obtained' => $defaultScore, // 正确则得满分
  1885. ];
  1886. Log::debug('补充未提交的题目', [
  1887. 'paper_id' => $paperId,
  1888. 'question_id' => $questionId,
  1889. 'default_score' => $pq->score ?? 2.0,
  1890. ]);
  1891. }
  1892. }
  1893. } catch (\Exception $e) {
  1894. Log::warning('获取卷子题目列表失败', [
  1895. 'paper_id' => $paperId,
  1896. 'error' => $e->getMessage(),
  1897. ]);
  1898. }
  1899. }
  1900. // 为已提交的题目计算分数
  1901. foreach ($questions as &$question) {
  1902. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? '';
  1903. // 如果用户没有提供 score,尝试从数据库获取或使用默认值
  1904. if (! isset($question['score'])) {
  1905. $question['score'] = $scoreMap[$questionId] ?? 2.0;
  1906. }
  1907. // 如果用户没有提供 score_obtained,根据 is_correct 计算
  1908. if (! isset($question['score_obtained'])) {
  1909. $question['score_obtained'] = $this->calculateScoreObtained(
  1910. $question['score'] ?? 0,
  1911. $question['is_correct'] ?? []
  1912. );
  1913. }
  1914. if (config('app.debug')) {
  1915. Log::debug('自动计算分数', [
  1916. 'question_id' => $questionId,
  1917. 'default_score' => $question['score'],
  1918. 'score_obtained' => $question['score_obtained'],
  1919. 'is_correct' => $question['is_correct'] ?? [],
  1920. ]);
  1921. }
  1922. }
  1923. return $questions;
  1924. }
  1925. /**
  1926. * 获取题目默认分数
  1927. */
  1928. private function getQuestionDefaultScore(string $questionId): float
  1929. {
  1930. if (empty($questionId)) {
  1931. return 2.0; // 默认分数
  1932. }
  1933. try {
  1934. // 尝试从题库获取题目分数
  1935. $question = DB::connection('mysql')
  1936. ->table('questions')
  1937. ->where('id', $questionId)
  1938. ->orWhere('question_code', $questionId)
  1939. ->first();
  1940. if ($question && isset($question->score)) {
  1941. return (float) $question->score;
  1942. }
  1943. // 如果没有找到,根据题目ID生成一个合理的默认分数
  1944. // 这里可以根据需要调整默认分数逻辑
  1945. return 2.0;
  1946. } catch (\Exception $e) {
  1947. Log::warning('获取题目默认分数失败,使用默认值', [
  1948. 'question_id' => $questionId,
  1949. 'error' => $e->getMessage(),
  1950. ]);
  1951. return 2.0;
  1952. }
  1953. }
  1954. /**
  1955. * 根据 is_correct 数组计算得分
  1956. *
  1957. * @param float $totalScore 总分
  1958. * @param array $isCorrect 正确性数组 [0, 1, 1] 表示第1题错误,第2、3题正确
  1959. * @return float 得分
  1960. */
  1961. private function calculateScoreObtained(float $totalScore, array $isCorrect): float
  1962. {
  1963. if (empty($isCorrect)) {
  1964. return 0.0;
  1965. }
  1966. $correctCount = array_sum($isCorrect);
  1967. $totalCount = count($isCorrect);
  1968. if ($totalCount === 0) {
  1969. return 0.0;
  1970. }
  1971. // 按正确率计算得分
  1972. $scoreRatio = $correctCount / $totalCount;
  1973. return round($totalScore * $scoreRatio, 2);
  1974. }
  1975. }