ExamAnswerAnalysisService.php 88 KB

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