ExamAnswerAnalysisService.php 91 KB

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