ExamAnswerAnalysisService.php 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256
  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);
  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): array
  570. {
  571. if (empty($questionIds)) {
  572. return [];
  573. }
  574. $difficulties = [];
  575. try {
  576. $questions = DB::connection('mysql')
  577. ->table('questions')
  578. ->whereIn('id', $questionIds)
  579. ->select(['id', 'difficulty'])
  580. ->get();
  581. foreach ($questions as $question) {
  582. $difficulty = $question->difficulty !== null ? floatval($question->difficulty) : 0.6;
  583. // 统一按 questions.id 作为唯一键,避免 question_code 映射歧义
  584. $difficulties[$question->id] = $difficulty;
  585. }
  586. } catch (\Exception $e) {
  587. Log::warning('批量获取题目难度失败', [
  588. 'question_ids' => $questionIds,
  589. 'error' => $e->getMessage(),
  590. ]);
  591. }
  592. return $difficulties;
  593. }
  594. /**
  595. * 【公司要求】计算知识点掌握度向量
  596. *
  597. * 公司要求的核心算法:
  598. * 1. 难度映射:将题目中0.0-1.0的浮点数难度映射为 1-4 等级
  599. * 2. 权重计算:
  600. * - 越级(Question > {学案基准难度}):对 +0.15 / 错 -0.05
  601. * - 适应(Question = {学案基准难度}):对 +0.10 / 错 -0.10
  602. * - 降级(Question < {学案基准难度}):对 +0.05 / 错 -0.15
  603. * 3. 数值更新:newMastery = oldMastery + change,并做 0.0 ~ 1.0 的边界限制
  604. *
  605. * 核心算法说明:
  606. * 1. 从考试答题中提取每个知识点的答题记录
  607. * 2. 调用MasteryCalculator计算掌握度(包含:难度映射、权重计算、数值更新)
  608. * 3. 返回包含掌握度、置信度、趋势等完整信息的向量
  609. *
  610. * @param array $questions 题目列表
  611. * @param array $questionMappings 题目知识点映射
  612. * @param int|null $examBaseDifficulty 学案基准难度(1-4级)
  613. * @param string|null $studentId 学生ID
  614. * @return array 知识点掌握度向量
  615. */
  616. private function calculateKnowledgeMasteryVector(array $questions, array $questionMappings, ?int $examBaseDifficulty = null, ?string $studentId = null): array
  617. {
  618. // 按知识点聚合答题记录
  619. $knowledgeAttempts = [];
  620. // 批量获取所有题目的难度(减少数据库查询次数)
  621. $questionIds = array_filter(array_map(fn ($q) => $q['question_id'] ?? $q['question_bank_id'] ?? null, $questions));
  622. $questionDifficulties = $this->batchGetQuestionDifficulties($questionIds);
  623. foreach ($questions as $question) {
  624. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  625. if (empty($questionId)) {
  626. Log::warning('calculateKnowledgeMasteryVector: 题目缺少ID', ['question' => $question]);
  627. continue;
  628. }
  629. $score = floatval($question['score_obtained'] ?? 0);
  630. $maxScore = floatval($question['score'] ?? $score);
  631. // is_correct 是数组,如 [0,1,1],表示每个步骤的正误
  632. $isCorrectArray = $question['is_correct'] ?? [];
  633. if (! is_array($isCorrectArray)) {
  634. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  635. }
  636. $mapping = $questionMappings[$questionId] ?? null;
  637. if (! $mapping || ! isset($mapping['kp_mapping'])) {
  638. Log::debug('calculateKnowledgeMasteryVector: 题目无知识点映射', ['question_id' => $questionId]);
  639. continue;
  640. }
  641. // 从批量查询结果获取题目难度
  642. $questionDifficulty = $questionDifficulties[$questionId] ?? 0.6;
  643. $stepCount = count($isCorrectArray);
  644. $scorePerStep = $maxScore / max($stepCount, 1);
  645. // 根据 is_correct 数组生成步骤级答题记录
  646. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  647. $isCorrectBool = (int) $isCorrect === 1;
  648. // 为该题目关联的每个知识点创建答题记录
  649. foreach ($mapping['kp_mapping'] as $kpMapping) {
  650. $kpId = $kpMapping['kp_id'];
  651. if (! isset($knowledgeAttempts[$kpId])) {
  652. $knowledgeAttempts[$kpId] = [
  653. 'attempts' => [],
  654. 'step_details' => [],
  655. ];
  656. }
  657. // 构建答题记录(用于MasteryCalculator)
  658. $attemptRecord = [
  659. 'question_id' => $questionId,
  660. 'is_correct' => $isCorrectBool,
  661. 'step_index' => $stepIndex,
  662. 'question_difficulty' => $questionDifficulty,
  663. 'created_at' => now()->toISOString(),
  664. ];
  665. $knowledgeAttempts[$kpId]['attempts'][] = $attemptRecord;
  666. $knowledgeAttempts[$kpId]['step_details'][] = [
  667. 'question_id' => $questionId,
  668. 'step_index' => $stepIndex,
  669. 'score' => $isCorrectBool ? $scorePerStep : 0,
  670. 'max_score' => $scorePerStep,
  671. 'is_correct' => $isCorrectBool,
  672. ];
  673. }
  674. }
  675. }
  676. // 【公司要求】【核心】使用MasteryCalculator计算每个知识点的掌握度
  677. // 性能优化:批量读取历史 + 批量upsert,避免逐知识点查询与写入
  678. $baseDifficulty = $examBaseDifficulty ?? 2;
  679. $batchMasteryResults = $this->masteryCalculator->calculateMasteryLevelsBatch(
  680. $studentId ?? '',
  681. $knowledgeAttempts,
  682. $baseDifficulty
  683. );
  684. $masteryVector = [];
  685. foreach ($knowledgeAttempts as $kpId => $data) {
  686. $masteryResult = $batchMasteryResults[$kpId] ?? null;
  687. if ($masteryResult === null) {
  688. continue;
  689. }
  690. $masteryVector[$kpId] = [
  691. 'kp_id' => $kpId,
  692. 'mastery' => $masteryResult['mastery'],
  693. 'previous_mastery' => $masteryResult['old_mastery'] ?? null,
  694. 'change' => $masteryResult['change'] ?? null,
  695. 'total_attempts' => $masteryResult['total_attempts'],
  696. 'correct_attempts' => $masteryResult['correct_attempts'],
  697. 'accuracy_rate' => $masteryResult['accuracy_rate'],
  698. 'step_details' => $data['step_details'],
  699. // 计算细节(用于调试和分析)
  700. 'calculation_details' => $masteryResult['details'] ?? [],
  701. ];
  702. }
  703. Log::info('知识点掌握度向量计算完成', [
  704. 'knowledge_points_count' => count($masteryVector),
  705. 'sample' => array_slice($masteryVector, 0, 3, true),
  706. ]);
  707. return $masteryVector;
  708. }
  709. /**
  710. * 更新学生掌握度(优化版:批量查询+批量upsert)
  711. */
  712. private function updateStudentMastery(string $studentId, array $knowledgeMasteryVector): array
  713. {
  714. if (empty($knowledgeMasteryVector)) {
  715. return [];
  716. }
  717. $updatedMastery = [];
  718. $kpIds = array_keys($knowledgeMasteryVector);
  719. // 子节点掌握度已在 MasteryCalculator 内部写库,这里只生成返回数据,避免二次写入与重复统计
  720. foreach ($knowledgeMasteryVector as $kpId => $data) {
  721. $previousMastery = $data['previous_mastery'] ?? 0.0;
  722. $updatedMastery[$kpId] = [
  723. 'kp_id' => $kpId,
  724. 'current_mastery' => $data['mastery'],
  725. 'previous_mastery' => $previousMastery,
  726. 'change' => $data['mastery'] - $previousMastery,
  727. 'weight' => 1,
  728. 'is_parent' => false,
  729. ];
  730. }
  731. // 【修复】计算并更新父节点掌握度,同时添加到返回数组中
  732. $parentMasteryData = $this->updateParentMasteryLevels($studentId, $kpIds);
  733. // 合并父节点数据到返回数组
  734. $updatedMastery = array_merge($updatedMastery, $parentMasteryData);
  735. return $updatedMastery;
  736. }
  737. /**
  738. * 更新父节点掌握度(优化版:批量查询+批量upsert)
  739. * 父节点掌握度 = 所有子节点掌握度的算术平均数,支持多级递归
  740. */
  741. private function updateParentMasteryLevels(string $studentId, array $childKpCodes, int $maxDepth = 2): array
  742. {
  743. $allParentMasteryData = [];
  744. $currentLevelChildCodes = $childKpCodes;
  745. $processedNodes = new \ArrayObject;
  746. $now = now();
  747. try {
  748. for ($level = 0; $level < $maxDepth; $level++) {
  749. if (empty($currentLevelChildCodes)) {
  750. break;
  751. }
  752. // 获取当前层子节点的直接父节点
  753. $parentKpCodes = DB::connection('mysql')
  754. ->table('knowledge_points')
  755. ->whereIn('kp_code', $currentLevelChildCodes)
  756. ->whereNotNull('parent_kp_code')
  757. ->distinct()
  758. ->pluck('parent_kp_code')
  759. ->toArray();
  760. if (empty($parentKpCodes)) {
  761. break;
  762. }
  763. // 过滤已处理的节点
  764. $parentKpCodesToProcess = [];
  765. foreach ($parentKpCodes as $code) {
  766. if (! isset($processedNodes[$code])) {
  767. $processedNodes[$code] = true;
  768. $parentKpCodesToProcess[] = $code;
  769. }
  770. }
  771. if (empty($parentKpCodesToProcess)) {
  772. $currentLevelChildCodes = $parentKpCodes;
  773. continue;
  774. }
  775. // 批量获取父节点的直接子节点
  776. $childRelations = DB::connection('mysql')
  777. ->table('knowledge_points')
  778. ->whereIn('parent_kp_code', $parentKpCodesToProcess)
  779. ->get(['kp_code', 'parent_kp_code']);
  780. $childrenByParent = [];
  781. $allChildCodes = [];
  782. foreach ($childRelations as $relation) {
  783. $childrenByParent[$relation->parent_kp_code][] = $relation->kp_code;
  784. $allChildCodes[$relation->kp_code] = true;
  785. }
  786. // 批量获取子节点掌握度
  787. $childMasteryMap = [];
  788. if (! empty($allChildCodes)) {
  789. $childMasteryMap = DB::connection('mysql')
  790. ->table('student_knowledge_mastery')
  791. ->where('student_id', $studentId)
  792. ->whereIn('kp_code', array_keys($allChildCodes))
  793. ->pluck('mastery_level', 'kp_code')
  794. ->toArray();
  795. }
  796. // 批量查询父节点历史掌握度
  797. $historyRecords = DB::connection('mysql')
  798. ->table('student_knowledge_mastery')
  799. ->where('student_id', $studentId)
  800. ->whereIn('kp_code', $parentKpCodesToProcess)
  801. ->get()
  802. ->keyBy('kp_code');
  803. // 计算每个父节点的掌握度并收集upsert数据
  804. $upsertData = [];
  805. $currentLevelParentData = [];
  806. foreach ($parentKpCodesToProcess as $parentKpCode) {
  807. $children = $childrenByParent[$parentKpCode] ?? [];
  808. $sum = 0.0;
  809. $count = 0;
  810. foreach ($children as $childCode) {
  811. if (isset($childMasteryMap[$childCode])) {
  812. $sum += (float) $childMasteryMap[$childCode];
  813. $count++;
  814. }
  815. }
  816. $parentMastery = $count > 0 ? round($sum / $count, 4) : 0.0;
  817. $historyMastery = $historyRecords->get($parentKpCode);
  818. $previousMastery = $historyMastery->mastery_level ?? 0.0;
  819. $upsertData[] = [
  820. 'student_id' => $studentId,
  821. 'kp_code' => $parentKpCode,
  822. 'mastery_level' => $parentMastery,
  823. 'confidence_level' => 0.0,
  824. 'total_attempts' => 1,
  825. 'correct_attempts' => 0,
  826. 'mastery_trend' => 'stable',
  827. 'last_mastery_update' => $now,
  828. 'updated_at' => $now,
  829. ];
  830. $currentLevelParentData[$parentKpCode] = [
  831. 'kp_id' => $parentKpCode,
  832. 'current_mastery' => $parentMastery,
  833. 'previous_mastery' => $previousMastery,
  834. 'change' => $parentMastery - $previousMastery,
  835. 'weight' => 1,
  836. 'is_parent' => true,
  837. 'level' => $level + 1,
  838. ];
  839. }
  840. // 【优化】批量upsert(1次查询代替N次updateOrInsert)
  841. if (! empty($upsertData)) {
  842. DB::connection('mysql')
  843. ->table('student_knowledge_mastery')
  844. ->upsert(
  845. $upsertData,
  846. ['student_id', 'kp_code'],
  847. ['mastery_level', 'confidence_level', 'total_attempts', 'correct_attempts', 'mastery_trend', 'last_mastery_update', 'updated_at']
  848. );
  849. }
  850. $allParentMasteryData = array_merge($allParentMasteryData, $currentLevelParentData);
  851. $currentLevelChildCodes = $parentKpCodes;
  852. }
  853. if (! empty($allParentMasteryData)) {
  854. Log::info('多级父节点掌握度计算完成', [
  855. 'student_id' => $studentId,
  856. 'child_count' => count($childKpCodes),
  857. 'total_parent_count' => count($allParentMasteryData),
  858. ]);
  859. }
  860. } catch (\Exception $e) {
  861. Log::error('计算多级父节点掌握度失败', [
  862. 'student_id' => $studentId,
  863. 'error' => $e->getMessage(),
  864. ]);
  865. }
  866. return $allParentMasteryData;
  867. }
  868. /**
  869. * 生成题目维度分析(包含AI分析和解题思路)
  870. */
  871. private function analyzeQuestions(array $questions, array $questionMappings): array
  872. {
  873. $analysis = [];
  874. foreach ($questions as $question) {
  875. $questionId = $question['question_id'];
  876. $score = floatval($question['score_obtained'] ?? 0);
  877. $maxScore = floatval($question['score'] ?? $score);
  878. $steps = $question['steps'] ?? [];
  879. $isCorrect = $question['is_correct'] ?? ($score >= $maxScore);
  880. $mapping = $questionMappings[$questionId] ?? ['kp_mapping' => []];
  881. if (empty($mapping['kp_mapping'])) {
  882. Log::warning('ExamAnswerAnalysisService: 题目无知识点映射', ['question_id' => $questionId]);
  883. continue;
  884. }
  885. $kpCode = $mapping['kp_mapping'][0]['kp_id'];
  886. // 步骤分析
  887. $stepAnalysis = [];
  888. if (! empty($steps)) {
  889. foreach ($steps as $step) {
  890. $kpId = $step['kp_id'];
  891. if (empty($kpId)) {
  892. Log::warning('ExamAnswerAnalysisService: 步骤缺少知识点ID', [
  893. 'question_id' => $questionId,
  894. 'step_index' => $step['step_index'] ?? 'unknown',
  895. ]);
  896. continue;
  897. }
  898. $stepAnalysis[] = [
  899. 'step_index' => $step['step_index'],
  900. 'is_correct' => $step['is_correct'],
  901. 'kp_id' => $kpId,
  902. 'description' => $step['description'] ?? '',
  903. ];
  904. }
  905. }
  906. // 知识点关联
  907. $knowledgePoints = array_map(function ($kp) {
  908. return [
  909. 'kp_id' => $kp['kp_id'],
  910. 'kp_name' => $kp['kp_name'] ?? $kp['kp_id'],
  911. 'weight' => $kp['weight'] ?? 1.0,
  912. ];
  913. }, $mapping['kp_mapping']);
  914. // 【集成】调用AI分析服务,获取解题思路和错误分析
  915. $aiAnalysis = $this->getQuestionAIAnalysis($question, $mapping);
  916. $analysis[] = [
  917. 'question_id' => $questionId,
  918. 'score_obtained' => $score,
  919. 'max_score' => $maxScore,
  920. 'accuracy_rate' => $maxScore > 0 ? $score / $maxScore : 0,
  921. 'is_correct' => $isCorrect,
  922. 'step_analysis' => $stepAnalysis,
  923. 'knowledge_points' => $knowledgePoints,
  924. 'performance_summary' => $this->generateQuestionPerformanceSummary($question, $stepAnalysis),
  925. // 【新增】解题思路和错误分析
  926. 'solution_process' => $aiAnalysis['solution_process'] ?? '',
  927. 'error_analysis' => $aiAnalysis['error_analysis'] ?? '',
  928. 'mistake_type' => $aiAnalysis['mistake_type'] ?? '',
  929. 'suggestions' => $aiAnalysis['suggestions'] ?? '',
  930. 'next_steps' => $aiAnalysis['next_steps'] ?? [],
  931. ];
  932. }
  933. return $analysis;
  934. }
  935. /**
  936. * 获取题目的AI分析(解题思路、错误分析)
  937. */
  938. private function getQuestionAIAnalysis(array $question, array $mapping): array
  939. {
  940. $isCorrect = $question['is_correct'] ?? false;
  941. $score = floatval($question['score_obtained'] ?? 0);
  942. $maxScore = floatval($question['score'] ?? 10);
  943. $kpCode = $mapping['kp_mapping'][0]['kp_id'] ?? null;
  944. if (empty($kpCode)) {
  945. Log::warning('ExamAnswerAnalysisService: getQuestionAIAnalysis缺少知识点ID', [
  946. 'question_id' => $question['question_id'] ?? 'unknown',
  947. 'mapping' => $mapping,
  948. ]);
  949. $kpCode = 'UNKNOWN_KP';
  950. }
  951. // 调用LocalAIAnalysisService进行分析
  952. try {
  953. $analysisResult = $this->aiAnalysisService->analyzeAnswer([
  954. 'question_id' => $question['question_id'],
  955. 'question_text' => $question['question_text'] ?? '',
  956. 'student_answer' => $question['student_answer'] ?? '',
  957. 'correct_answer' => $question['correct_answer'] ?? '',
  958. 'score' => $score,
  959. 'max_score' => $maxScore,
  960. 'kp_code' => $kpCode,
  961. ]);
  962. $data = $analysisResult['data'] ?? [];
  963. // 根据正确性生成不同的解题思路
  964. if ($isCorrect) {
  965. return [
  966. 'solution_process' => $data['correct_solution'] ?? '该题作答正确,解题思路清晰',
  967. 'error_analysis' => '',
  968. 'mistake_type' => '',
  969. 'suggestions' => $data['suggestions'] ?? '继续保持良好的解题习惯',
  970. 'next_steps' => $data['next_steps'] ?? ['尝试更高难度的同类题目'],
  971. ];
  972. }
  973. // 错误题目:返回详细分析
  974. return [
  975. 'solution_process' => $data['correct_solution'] ?? '请参考标准解题步骤',
  976. 'error_analysis' => $data['reason'] ?? '解题过程中存在错误',
  977. 'mistake_type' => $data['mistake_type'] ?? '计算或理解错误',
  978. 'suggestions' => $data['suggestions'] ?? '建议针对薄弱知识点进行专项练习',
  979. 'next_steps' => $data['next_steps'] ?? ['复习相关知识点', '做同类型练习题'],
  980. ];
  981. } catch (\Exception $e) {
  982. Log::warning('AI分析失败,使用默认分析', [
  983. 'question_id' => $question['question_id'],
  984. 'error' => $e->getMessage(),
  985. ]);
  986. // 回退到基础分析
  987. return $this->getFallbackAnalysis($question, $isCorrect);
  988. }
  989. }
  990. /**
  991. * 回退分析(当AI分析失败时)
  992. */
  993. private function getFallbackAnalysis(array $question, bool $isCorrect): array
  994. {
  995. if ($isCorrect) {
  996. return [
  997. 'solution_process' => '该题作答正确',
  998. 'error_analysis' => '',
  999. 'mistake_type' => '',
  1000. 'suggestions' => '继续保持',
  1001. 'next_steps' => ['尝试更高难度的题目'],
  1002. ];
  1003. }
  1004. $scoreRatio = floatval($question['score_obtained'] ?? 0) / max(floatval($question['score'] ?? 1), 1);
  1005. return [
  1006. 'solution_process' => '请参考标准答案和解题步骤',
  1007. 'error_analysis' => $scoreRatio < 0.3 ? '知识点理解存在偏差' : '解题过程中出现错误',
  1008. 'mistake_type' => $scoreRatio < 0.3 ? '概念错误' : '计算/步骤错误',
  1009. 'suggestions' => '建议复习相关知识点,加强练习',
  1010. 'next_steps' => ['复习基础概念', '做同类型练习题', '请教老师或同学'],
  1011. ];
  1012. }
  1013. /**
  1014. * 生成知识点维度分析
  1015. */
  1016. private function analyzeKnowledgePoints(array $knowledgeMasteryVector, array $questionMappings): array
  1017. {
  1018. $analysis = [];
  1019. foreach ($knowledgeMasteryVector as $kpId => $data) {
  1020. $totalAttempts = intval($data['total_attempts'] ?? 0);
  1021. $correctAttempts = intval($data['correct_attempts'] ?? 0);
  1022. $examAccuracyRatio = $totalAttempts > 0 ? ($correctAttempts / $totalAttempts) : null;
  1023. $historicalMastery = floatval($data['mastery'] ?? 0);
  1024. // 收敛规则(最小影响):
  1025. // 仅调整“报告展示口径”,不改 student_knowledge_mastery 的历史累计值。
  1026. // 当次有错题时,采用“历史掌握度 + 当次正确率”的证据加权融合:
  1027. // display = (historical*PRIOR_WEIGHT + examAccuracy*evidenceWeight) / (PRIOR_WEIGHT + evidenceWeight)
  1028. // 这样避免一次异常把 100% 直接打到 0%,同时保证有错会下调。
  1029. $displayMastery = $historicalMastery;
  1030. if ($examAccuracyRatio !== null && $correctAttempts < $totalAttempts) {
  1031. $priorWeight = 8.0; // 历史先验权重(固定,保证历史连续性)
  1032. $evidenceWeight = max(1.0, min(10.0, floatval($totalAttempts))); // 当次证据权重(随作答量提升)
  1033. $displayMastery = (
  1034. ($historicalMastery * $priorWeight) + ($examAccuracyRatio * $evidenceWeight)
  1035. ) / ($priorWeight + $evidenceWeight);
  1036. }
  1037. $displayData = $data;
  1038. $displayData['mastery'] = round($displayMastery, 4);
  1039. // 【公司要求】移除置信度,只保留核心掌握度分析
  1040. $analysis[] = [
  1041. 'kp_id' => $kpId,
  1042. 'mastery_level' => round($displayMastery, 4),
  1043. 'historical_mastery_level' => round($historicalMastery, 4),
  1044. 'exam_accuracy_rate' => $examAccuracyRatio !== null ? round($examAccuracyRatio, 4) : null,
  1045. 'performance_in_exam' => $this->evaluatePerformanceLevel($displayMastery),
  1046. 'evidence_count' => count($data['step_details']),
  1047. 'step_evidence' => $data['step_details'],
  1048. 'recommendation' => $this->generateKnowledgePointRecommendation($displayData),
  1049. ];
  1050. }
  1051. return $analysis;
  1052. }
  1053. /**
  1054. * 生成整体掌握度总结
  1055. */
  1056. private function generateOverallSummary(array $updatedMastery): array
  1057. {
  1058. $knowledgePoints = array_values($updatedMastery);
  1059. if (empty($knowledgePoints)) {
  1060. return [
  1061. 'total_knowledge_points' => 0,
  1062. 'average_mastery' => 0,
  1063. 'mastery_distribution' => [
  1064. 'mastered' => 0,
  1065. 'good' => 0,
  1066. 'weak' => 0,
  1067. ],
  1068. 'top_strengths' => [],
  1069. 'top_weaknesses' => [],
  1070. ];
  1071. }
  1072. // 计算平均掌握度(只计算子节点,不包括父节点)
  1073. $childNodes = array_filter($knowledgePoints, fn ($kp) => ! ($kp['is_parent'] ?? false));
  1074. $totalChildNodes = count($childNodes);
  1075. if ($totalChildNodes === 0) {
  1076. // 如果没有子节点,只计算所有节点
  1077. $averageMastery = array_sum(array_column($knowledgePoints, 'current_mastery')) / count($knowledgePoints);
  1078. } else {
  1079. // 计算所有节点的平均掌握度(包括父节点)
  1080. $allMastery = array_column($knowledgePoints, 'current_mastery');
  1081. $averageMastery = array_sum($allMastery) / count($allMastery);
  1082. }
  1083. // 掌握度分布(只统计子节点)
  1084. $mastered = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] >= 0.85);
  1085. $good = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] >= 0.70 && $kp['current_mastery'] < 0.85);
  1086. $weak = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] < 0.70);
  1087. // 排序找出优势和薄弱点(只包括子节点)
  1088. usort($childNodes, fn ($a, $b) => $b['current_mastery'] <=> $a['current_mastery']);
  1089. $topStrengths = array_slice($childNodes, 0, 3);
  1090. $topWeaknesses = array_slice(array_reverse($childNodes), 0, 3);
  1091. // 统计父子节点数量
  1092. $childCount = count(array_filter($knowledgePoints, fn ($kp) => ! ($kp['is_parent'] ?? false)));
  1093. $parentCount = count(array_filter($knowledgePoints, fn ($kp) => $kp['is_parent'] ?? false));
  1094. return [
  1095. 'total_knowledge_points' => $totalChildNodes, // 只统计子节点数量
  1096. 'child_nodes_count' => $childCount,
  1097. 'parent_nodes_count' => $parentCount,
  1098. 'average_mastery' => round($averageMastery, 4),
  1099. 'mastery_distribution' => [
  1100. 'mastered' => count($mastered),
  1101. 'good' => count($good),
  1102. 'weak' => count($weak),
  1103. ],
  1104. 'top_strengths' => $topStrengths,
  1105. 'top_weaknesses' => $topWeaknesses,
  1106. 'overall_performance' => $this->evaluateOverallPerformance($averageMastery),
  1107. ];
  1108. }
  1109. /**
  1110. * 生成智能出卷推荐依据
  1111. * 基于文档中的推荐优先级算法
  1112. */
  1113. private function generateSmartQuizRecommendation(array $updatedMastery): array
  1114. {
  1115. $recommendations = [];
  1116. // 只对子节点生成推荐,忽略父节点
  1117. foreach ($updatedMastery as $kpId => $data) {
  1118. // 跳过父节点
  1119. if ($data['is_parent'] ?? false) {
  1120. continue;
  1121. }
  1122. $mastery = $data['current_mastery'];
  1123. // 【公司要求】移除置信度,只使用掌握度计算推荐
  1124. $weight = $data['weight'];
  1125. // 推荐优先级 = (1 - 掌握度) * 重要性 * 覆盖需求
  1126. // 重要性可以根据知识点在中考/阶段考试中的权重,这里简化为1.0
  1127. $importance = 1.0;
  1128. // 覆盖需求:最近没考过或考得少,值大
  1129. $coverageNeed = max(1.0, 1.5 - ($weight / 10));
  1130. $priority = (1 - $mastery) * $importance * $coverageNeed;
  1131. $recommendations[] = [
  1132. 'kp_id' => $kpId,
  1133. 'current_mastery' => $mastery,
  1134. 'priority' => $priority,
  1135. 'recommended_questions' => $this->calculateRecommendedQuestions($mastery),
  1136. 'focus_type' => $this->determineFocusType($mastery),
  1137. ];
  1138. }
  1139. // 按优先级排序
  1140. usort($recommendations, fn ($a, $b) => $b['priority'] <=> $a['priority']);
  1141. // 控制难度节奏:40%巩固型 + 40%修补型 + 20%挑战型
  1142. $totalRecommendations = count($recommendations);
  1143. $consolidation = array_slice($recommendations, 0, intval($totalRecommendations * 0.4));
  1144. $remediation = array_slice($recommendations, intval($totalRecommendations * 0.4), intval($totalRecommendations * 0.4));
  1145. $challenge = array_slice($recommendations, intval($totalRecommendations * 0.8));
  1146. return [
  1147. 'priority_list' => $recommendations,
  1148. 'quiz_structure' => [
  1149. 'consolidation_type' => $consolidation,
  1150. 'remediation_type' => $remediation,
  1151. 'challenge_type' => $challenge,
  1152. ],
  1153. 'total_recommended_questions' => array_sum(array_column($recommendations, 'recommended_questions')),
  1154. ];
  1155. }
  1156. /**
  1157. * 保存考试答题记录
  1158. *
  1159. * 入参格式示例:
  1160. * {
  1161. * "question_bank_id": "12979",
  1162. * "student_answer": "C",
  1163. * "is_correct": [0], // 数组长度决定步骤数,0=错误,1=正确
  1164. * "teacher_comment": null
  1165. * }
  1166. *
  1167. * is_correct 数组说明:
  1168. * - 单选题:[1] 或 [0],长度为1
  1169. * - 填空题:[1, 0, 1],每个空一个元素
  1170. * - 简答题:[1, 1, 0, 1],每个得分步骤一个元素
  1171. */
  1172. /**
  1173. * 保存错题记录
  1174. *
  1175. * @param string $studentId 学生ID
  1176. * @param string $questionId 题目ID
  1177. * @param string $examId 考试ID
  1178. * @param array $question 题目数据
  1179. * @param array|null $kpMapping 知识点映射(数组格式:[kp_id1, kp_id2] 或 null)
  1180. */
  1181. private function saveMistakeRecord(string $studentId, string $questionId, string $examId, array $question, ?array $kpMapping): void
  1182. {
  1183. try {
  1184. // 如果 $kpMapping 是数组,说明是多个 kp_id
  1185. // 如果是关联数组,说明是单个 kpMapping(兼容旧调用)
  1186. $kpIds = null;
  1187. if (is_array($kpMapping)) {
  1188. // 检查是数组的数组(多个kp_id)还是关联数组(单个kpMapping)
  1189. if (isset($kpMapping[0])) {
  1190. // 数组的数组:[[kp_id: '...'], [kp_id: '...']]
  1191. $kpIds = array_column($kpMapping, 'kp_id');
  1192. } else {
  1193. // 关联数组:[kp_id: '...']
  1194. $kpIds = [$kpMapping['kp_id']];
  1195. }
  1196. }
  1197. $payload = [
  1198. 'student_id' => $studentId,
  1199. 'question_id' => $questionId,
  1200. 'paper_id' => $examId,
  1201. 'my_answer' => $question['student_answer'] ?? null,
  1202. 'correct_answer' => null, // 可以从题目表获取
  1203. 'question_text' => null, // 可以从题目表获取
  1204. 'knowledge_point' => null, // 不保存name,只保存kp_ids
  1205. 'kp_ids' => $kpIds, // 保存为数组格式
  1206. 'source' => $examId, // 来源标记使用卷子ID
  1207. 'happened_at' => now(),
  1208. ];
  1209. $result = $this->mistakeBookService->createMistake($payload);
  1210. if (($result['duplicate'] ?? false) === false) {
  1211. Log::debug('错题记录保存成功', [
  1212. 'student_id' => $studentId,
  1213. 'question_id' => $questionId,
  1214. 'mistake_id' => $result['mistake_id'] ?? null,
  1215. ]);
  1216. }
  1217. } catch (\Exception $e) {
  1218. Log::warning('错题记录保存失败(不中断主流程)', [
  1219. 'student_id' => $studentId,
  1220. 'question_id' => $questionId,
  1221. 'exam_id' => $examId,
  1222. 'error' => $e->getMessage(),
  1223. ]);
  1224. }
  1225. }
  1226. /**
  1227. * 保存答题记录(优化版:批量INSERT)
  1228. *
  1229. * @param array $examData 考试数据
  1230. * @param array $questionMappings 已批量查询的知识点映射,避免N+1
  1231. */
  1232. private function saveExamAnswerRecords(array $examData, array $questionMappings = []): array
  1233. {
  1234. // 【修复】确保类型正确,避免 SQL 类型转换问题
  1235. $studentId = (string) $examData['student_id'];
  1236. $examId = (string) $examData['paper_id'];
  1237. $now = now();
  1238. // 【优化】收集所有要插入的记录,最后批量INSERT
  1239. $stepsToInsert = [];
  1240. $questionsToInsert = [];
  1241. $mistakesToSave = []; // 收集错题记录
  1242. foreach ($examData['questions'] as $question) {
  1243. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1244. if (empty($questionId)) {
  1245. continue;
  1246. }
  1247. // 【优化】使用传入的映射,不再查询数据库
  1248. $kpMappings = $questionMappings[$questionId]['kp_mapping'] ?? [];
  1249. $isCorrectArray = $question['is_correct'] ?? [];
  1250. if (! is_array($isCorrectArray)) {
  1251. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  1252. }
  1253. $stepCount = count($isCorrectArray);
  1254. if ($stepCount > 1 || ! empty($kpMappings)) {
  1255. // 多步骤题目:收集步骤记录
  1256. $scorePerStep = ($question['score'] ?? 0) / max($stepCount, 1);
  1257. $hasMistake = false;
  1258. $allErrorKpCodes = [];
  1259. foreach ($isCorrectArray as $stepIndex => $isCorrect) {
  1260. $isCorrectBool = (int) $isCorrect === 1;
  1261. if (! empty($kpMappings)) {
  1262. foreach ($kpMappings as $kpMapping) {
  1263. $stepsToInsert[] = [
  1264. 'student_id' => $studentId,
  1265. 'exam_id' => $examId,
  1266. 'question_id' => $questionId,
  1267. 'step_index' => $stepIndex,
  1268. 'kp_id' => $kpMapping['kp_id'],
  1269. 'is_correct' => $isCorrectBool ? 1 : 0,
  1270. 'step_score' => $isCorrectBool ? $scorePerStep : 0,
  1271. 'created_at' => $now,
  1272. 'updated_at' => $now,
  1273. ];
  1274. if (! $isCorrectBool) {
  1275. $hasMistake = true;
  1276. $allErrorKpCodes[] = $kpMapping['kp_id'];
  1277. }
  1278. }
  1279. } else {
  1280. $stepsToInsert[] = [
  1281. 'student_id' => $studentId,
  1282. 'exam_id' => $examId,
  1283. 'question_id' => $questionId,
  1284. 'step_index' => $stepIndex,
  1285. 'kp_id' => null,
  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. }
  1294. }
  1295. }
  1296. // 收集错题记录
  1297. if ($hasMistake) {
  1298. $uniqueKpCodes = array_values(array_unique($allErrorKpCodes));
  1299. $mistakesToSave[] = [
  1300. 'questionId' => $questionId,
  1301. 'question' => $question,
  1302. 'kpMappings' => array_map(fn ($code) => ['kp_id' => $code], $uniqueKpCodes),
  1303. ];
  1304. }
  1305. } else {
  1306. // 单步骤题目:收集题目级记录
  1307. $questionsToInsert[] = [
  1308. 'student_id' => $studentId,
  1309. 'exam_id' => $examId,
  1310. 'question_id' => $questionId,
  1311. 'score_obtained' => $question['score_obtained'] ?? 0,
  1312. 'max_score' => $question['score'] ?? 0,
  1313. 'created_at' => $now,
  1314. 'updated_at' => $now,
  1315. ];
  1316. // 收集错题记录
  1317. if (($question['score_obtained'] ?? 0) <= 0) {
  1318. $mistakesToSave[] = [
  1319. 'questionId' => $questionId,
  1320. 'question' => $question,
  1321. 'kpMappings' => ! empty($kpMappings)
  1322. ? array_map(fn ($m) => ['kp_id' => $m['kp_id']], $kpMappings)
  1323. : null,
  1324. ];
  1325. }
  1326. }
  1327. }
  1328. // 判断是否有变更,避免重复删除/插入
  1329. $stepsChanged = $this->hasAnswerStepsChanged($studentId, $examId, $stepsToInsert);
  1330. $questionsChanged = $this->hasAnswerQuestionsChanged($studentId, $examId, $questionsToInsert);
  1331. if ($stepsChanged || $questionsChanged) {
  1332. // 先清理该考试的所有答题记录(支持重复提交)
  1333. try {
  1334. if ($questionsChanged) {
  1335. DB::connection('mysql')->table('student_answer_questions')
  1336. ->where('student_id', '=', $studentId)
  1337. ->where('exam_id', '=', $examId)
  1338. ->delete();
  1339. }
  1340. if ($stepsChanged) {
  1341. DB::connection('mysql')->table('student_answer_steps')
  1342. ->where('student_id', '=', $studentId)
  1343. ->where('exam_id', '=', $examId)
  1344. ->delete();
  1345. }
  1346. Log::info('清理旧答题记录成功', [
  1347. 'student_id' => $studentId,
  1348. 'exam_id' => $examId,
  1349. 'steps_changed' => $stepsChanged,
  1350. 'questions_changed' => $questionsChanged,
  1351. ]);
  1352. } catch (\Exception $e) {
  1353. // 清理失败时抛出异常,避免后续插入重复数据
  1354. Log::error('清理旧答题记录失败', [
  1355. 'student_id' => $studentId,
  1356. 'exam_id' => $examId,
  1357. 'error' => $e->getMessage(),
  1358. ]);
  1359. throw $e;
  1360. }
  1361. // 【优化】批量 INSERT(每500条一批,避免超过MySQL限制)
  1362. try {
  1363. if ($stepsChanged && ! empty($stepsToInsert)) {
  1364. foreach (array_chunk($stepsToInsert, 500) as $chunk) {
  1365. DB::connection('mysql')->table('student_answer_steps')->insert($chunk);
  1366. }
  1367. }
  1368. if ($questionsChanged && ! empty($questionsToInsert)) {
  1369. foreach (array_chunk($questionsToInsert, 500) as $chunk) {
  1370. DB::connection('mysql')->table('student_answer_questions')->insert($chunk);
  1371. }
  1372. }
  1373. } catch (\Exception $e) {
  1374. Log::error('批量保存答题记录失败', [
  1375. 'student_id' => $studentId,
  1376. 'exam_id' => $examId,
  1377. 'error' => $e->getMessage(),
  1378. ]);
  1379. }
  1380. }
  1381. // 保存错题记录(批量处理,避免逐条写入)
  1382. if (! empty($mistakesToSave)) {
  1383. $payloads = [];
  1384. foreach ($mistakesToSave as $mistake) {
  1385. $kpIds = null;
  1386. if (is_array($mistake['kpMappings'])) {
  1387. $kpIds = isset($mistake['kpMappings'][0])
  1388. ? array_column($mistake['kpMappings'], 'kp_id')
  1389. : [$mistake['kpMappings']['kp_id'] ?? null];
  1390. }
  1391. $payloads[] = [
  1392. 'student_id' => $studentId,
  1393. 'question_id' => $mistake['questionId'],
  1394. 'paper_id' => $examId,
  1395. 'my_answer' => $mistake['question']['student_answer'] ?? null,
  1396. 'correct_answer' => null,
  1397. 'question_text' => null,
  1398. 'knowledge_point' => null,
  1399. 'kp_ids' => $kpIds,
  1400. 'source' => $examId,
  1401. 'happened_at' => now(),
  1402. ];
  1403. }
  1404. $this->mistakeBookService->createMistakesBatch($payloads);
  1405. }
  1406. Log::info('答题记录保存完成', [
  1407. 'student_id' => $studentId,
  1408. 'exam_id' => $examId,
  1409. 'total_questions' => count($examData['questions']),
  1410. 'steps_saved' => count($stepsToInsert),
  1411. 'questions_saved' => count($questionsToInsert),
  1412. 'steps_changed' => $stepsChanged,
  1413. 'questions_changed' => $questionsChanged,
  1414. ]);
  1415. return [
  1416. 'steps_changed' => $stepsChanged,
  1417. 'questions_changed' => $questionsChanged,
  1418. ];
  1419. }
  1420. /**
  1421. * 同步更新 paper_questions 的判分字段
  1422. * 适配 /api/exam-answer-analysis:保持题目判分与分析数据一致
  1423. */
  1424. private function syncPaperQuestionGrading(array $examData): void
  1425. {
  1426. $paperId = (string) ($examData['paper_id'] ?? '');
  1427. if ($paperId === '' || empty($examData['questions']) || !is_array($examData['questions'])) {
  1428. return;
  1429. }
  1430. $now = now();
  1431. $updated = 0;
  1432. $processedQuestionIds = [];
  1433. foreach ($examData['questions'] as $question) {
  1434. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1435. if (empty($questionId)) {
  1436. continue;
  1437. }
  1438. $questionId = (string) $questionId;
  1439. // 同一题只更新一次,避免双字段命中导致重复更新
  1440. if (isset($processedQuestionIds[$questionId])) {
  1441. continue;
  1442. }
  1443. $processedQuestionIds[$questionId] = true;
  1444. $isCorrectArray = $question['is_correct'] ?? [];
  1445. if (! is_array($isCorrectArray)) {
  1446. $isCorrectArray = [$isCorrectArray ? 1 : 0];
  1447. }
  1448. $totalSteps = count($isCorrectArray);
  1449. $correctSteps = array_sum(array_map(fn ($v) => (int) $v === 1 ? 1 : 0, $isCorrectArray));
  1450. $scoreRatio = $totalSteps > 0 ? round($correctSteps / $totalSteps, 4) : null;
  1451. $isFullyCorrect = $totalSteps > 0 ? ($correctSteps === $totalSteps ? 1 : 0) : null;
  1452. $scoreObtained = $question['score_obtained'] ?? null;
  1453. $payload = [
  1454. 'graded_at' => $now,
  1455. ];
  1456. if ($isFullyCorrect !== null) {
  1457. $payload['is_correct'] = $isFullyCorrect;
  1458. }
  1459. if ($scoreRatio !== null) {
  1460. $payload['score_ratio'] = $scoreRatio;
  1461. }
  1462. if ($scoreObtained !== null) {
  1463. $payload['score_obtained'] = $scoreObtained;
  1464. }
  1465. if (array_key_exists('student_answer', $question)) {
  1466. $payload['student_answer'] = $question['student_answer'];
  1467. }
  1468. if (array_key_exists('teacher_comment', $question)) {
  1469. $payload['teacher_comment'] = $question['teacher_comment'];
  1470. }
  1471. // 关键:不再依赖 paper_questions.id(部分库该字段为空),改为业务键匹配更新
  1472. $affected = DB::connection('mysql')->table('paper_questions')
  1473. ->where('paper_id', $paperId)
  1474. ->where(function ($q) use ($questionId) {
  1475. $q->where('question_bank_id', $questionId)
  1476. ->orWhere('question_id', $questionId);
  1477. })
  1478. ->update($payload);
  1479. $updated += $affected;
  1480. }
  1481. if ($updated > 0) {
  1482. DB::connection('mysql')->table('papers')
  1483. ->where('paper_id', $paperId)
  1484. ->update([
  1485. 'status' => 'completed',
  1486. 'completed_at' => $now,
  1487. 'updated_at' => $now,
  1488. ]);
  1489. }
  1490. Log::info('paper_questions 判分同步完成', [
  1491. 'paper_id' => $paperId,
  1492. 'input_question_count' => count($examData['questions']),
  1493. 'processed_question_count' => count($processedQuestionIds),
  1494. 'updated_rows' => $updated,
  1495. ]);
  1496. }
  1497. /**
  1498. * 判断答题步骤记录是否发生变化
  1499. */
  1500. private function hasAnswerStepsChanged(string $studentId, string $examId, array $newSteps): bool
  1501. {
  1502. $existing = DB::connection('mysql')
  1503. ->table('student_answer_steps')
  1504. ->where('student_id', $studentId)
  1505. ->where('exam_id', $examId)
  1506. ->get(['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'])
  1507. ->map(fn ($row) => (array) $row)
  1508. ->toArray();
  1509. return $this->buildRecordsHash($existing, ['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'], ['step_score'])
  1510. !== $this->buildRecordsHash($newSteps, ['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'], ['step_score']);
  1511. }
  1512. /**
  1513. * 判断题目级答题记录是否发生变化
  1514. */
  1515. private function hasAnswerQuestionsChanged(string $studentId, string $examId, array $newQuestions): bool
  1516. {
  1517. $existing = DB::connection('mysql')
  1518. ->table('student_answer_questions')
  1519. ->where('student_id', $studentId)
  1520. ->where('exam_id', $examId)
  1521. ->get(['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'])
  1522. ->map(fn ($row) => (array) $row)
  1523. ->toArray();
  1524. return $this->buildRecordsHash($existing, ['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'], ['score_obtained', 'max_score'])
  1525. !== $this->buildRecordsHash($newQuestions, ['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'], ['score_obtained', 'max_score']);
  1526. }
  1527. /**
  1528. * 构建记录哈希,用于判断是否变化
  1529. */
  1530. private function buildRecordsHash(array $rows, array $fields, array $numericFields = []): string
  1531. {
  1532. if (empty($rows)) {
  1533. return '[]';
  1534. }
  1535. $normalized = [];
  1536. $numericFieldMap = array_fill_keys($numericFields, true);
  1537. foreach ($rows as $row) {
  1538. $item = [];
  1539. foreach ($fields as $field) {
  1540. $value = $row[$field] ?? null;
  1541. if ($value !== null && isset($numericFieldMap[$field]) && is_numeric($value)) {
  1542. $value = sprintf('%.4F', (float) $value);
  1543. }
  1544. $item[$field] = $value;
  1545. }
  1546. $normalized[] = $item;
  1547. }
  1548. usort($normalized, fn ($a, $b) => json_encode($a) <=> json_encode($b));
  1549. return md5(json_encode($normalized));
  1550. }
  1551. /**
  1552. * 保存分析结果并创建掌握度快照
  1553. */
  1554. private function saveAnalysisResult(string $studentId, string $paperId, array $result, array $difficultyCalibrationQuestions = []): void
  1555. {
  1556. // 【修复】支持重复分析:先删除旧的分析结果
  1557. DB::connection('mysql')->table('exam_analysis_results')
  1558. ->where('student_id', $studentId)
  1559. ->where('paper_id', $paperId)
  1560. ->delete();
  1561. // 插入新的分析结果
  1562. DB::connection('mysql')->table('exam_analysis_results')->insert([
  1563. 'student_id' => $studentId,
  1564. 'paper_id' => $paperId,
  1565. 'analysis_data' => json_encode($result),
  1566. 'created_at' => now(),
  1567. 'updated_at' => now(),
  1568. ]);
  1569. Log::info('分析结果保存完成', [
  1570. 'student_id' => $studentId,
  1571. 'paper_id' => $paperId,
  1572. 'data_size' => strlen(json_encode($result)),
  1573. ]);
  1574. // 【新增】异步生成学情分析PDF
  1575. try {
  1576. Log::info('开始异步生成学情分析PDF', [
  1577. 'student_id' => $studentId,
  1578. 'paper_id' => $paperId,
  1579. ]);
  1580. // 使用队列异步生成PDF,避免阻塞主流程
  1581. dispatch(new \App\Jobs\GenerateAnalysisPdfJob($paperId, $studentId, null));
  1582. Log::info('PDF生成任务已加入队列', [
  1583. 'student_id' => $studentId,
  1584. 'paper_id' => $paperId,
  1585. ]);
  1586. if (! empty($difficultyCalibrationQuestions)) {
  1587. dispatch(new \App\Jobs\ProcessQuestionDifficultyCalibrationJob(
  1588. $paperId,
  1589. $studentId,
  1590. $difficultyCalibrationQuestions
  1591. ));
  1592. Log::warning('在线题目难度校准任务已加入队列(PDF生成后执行)', [
  1593. 'student_id' => $studentId,
  1594. 'paper_id' => $paperId,
  1595. 'question_count' => count($difficultyCalibrationQuestions),
  1596. 'queue' => 'pdf',
  1597. ]);
  1598. }
  1599. } catch (\Exception $e) {
  1600. Log::error('PDF/难度校准任务加入队列失败', [
  1601. 'student_id' => $studentId,
  1602. 'paper_id' => $paperId,
  1603. 'error' => $e->getMessage(),
  1604. ]);
  1605. }
  1606. }
  1607. /**
  1608. * 创建知识点掌握度快照
  1609. * 【集成】使用LocalAIAnalysisService的快照功能
  1610. *
  1611. * 快照用途:
  1612. * 1. 追踪学生掌握度变化趋势
  1613. * 2. 生成学情报告时对比历史数据
  1614. * 3. 为智能出卷提供决策依据
  1615. */
  1616. private function createMasterySnapshot(string $studentId, string $paperId, array $analysisResult): ?array
  1617. {
  1618. try {
  1619. // 计算快照数据
  1620. $masteryVector = $analysisResult['mastery_vector'] ?? [];
  1621. $overallMastery = 0;
  1622. $weakCount = 0;
  1623. $strongCount = 0;
  1624. foreach ($masteryVector as $kpData) {
  1625. $mastery = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1626. $overallMastery += $mastery;
  1627. if ($mastery < 0.6) {
  1628. $weakCount++;
  1629. } elseif ($mastery >= 0.85) {
  1630. $strongCount++;
  1631. }
  1632. }
  1633. $kpCount = count($masteryVector);
  1634. $overallMastery = $kpCount > 0 ? round($overallMastery / $kpCount, 4) : 0;
  1635. // Get all existing mastery records from database (as baseline)
  1636. // Use DB::table to avoid Eloquent accessor converting numbers to strings
  1637. $studentMasteries = DB::table('student_knowledge_mastery')
  1638. ->where('student_id', $studentId)
  1639. ->get(['kp_code', 'mastery_level']);
  1640. $currentMastery = [];
  1641. foreach ($studentMasteries as $record) {
  1642. $currentMastery[$record->kp_code] = (float) ($record->mastery_level ?? 0);
  1643. }
  1644. // Update with newly calculated mastery values from analysis result
  1645. foreach ($masteryVector as $kpData) {
  1646. $kpCode = $kpData['kp_id'] ?? null;
  1647. if (! $kpCode) {
  1648. continue;
  1649. }
  1650. $analysisLevel = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  1651. // Use new analysis value if it's higher, or if there was no previous value
  1652. if (! isset($currentMastery[$kpCode]) || $analysisLevel > $currentMastery[$kpCode]) {
  1653. $currentMastery[$kpCode] = $analysisLevel;
  1654. }
  1655. }
  1656. // 生成快照ID
  1657. $snapshotId = 'snap_'.$paperId.'_'.now()->format('YmdHis').'_'.substr(uniqid(), -4);
  1658. // 保存到快照表
  1659. DB::connection('mysql')->table('knowledge_point_mastery_snapshots')->insert([
  1660. 'snapshot_id' => $snapshotId,
  1661. 'student_id' => $studentId,
  1662. 'paper_id' => $paperId,
  1663. 'answer_record_id' => null,
  1664. 'mastery_data' => json_encode($masteryVector),
  1665. 'current_mastery' => json_encode($currentMastery),
  1666. 'overall_mastery' => $overallMastery,
  1667. 'weak_knowledge_points_count' => $weakCount,
  1668. 'strong_knowledge_points_count' => $strongCount,
  1669. 'snapshot_time' => now(),
  1670. 'analysis_id' => null,
  1671. 'created_at' => now(),
  1672. 'updated_at' => now(),
  1673. ]);
  1674. Log::info('掌握度快照创建成功', [
  1675. 'snapshot_id' => $snapshotId,
  1676. 'student_id' => $studentId,
  1677. 'paper_id' => $paperId,
  1678. 'overall_mastery' => $overallMastery,
  1679. 'weak_count' => $weakCount,
  1680. 'strong_count' => $strongCount,
  1681. ]);
  1682. // 计算变化
  1683. $lastSnapshot = DB::connection('mysql')->table('knowledge_point_mastery_snapshots')
  1684. ->where('student_id', $studentId)
  1685. ->where('snapshot_id', '<>', $snapshotId)
  1686. ->orderBy('snapshot_time', 'desc')
  1687. ->first();
  1688. $gainCount = $lossCount = 0;
  1689. $overallChange = 0;
  1690. $compareCount = 0;
  1691. $changeAverage = 0;
  1692. if ($lastSnapshot && ! empty($lastSnapshot->current_mastery)) {
  1693. $lastCurrentMastery = json_decode($lastSnapshot->current_mastery, true);
  1694. if (is_array($lastCurrentMastery)) {
  1695. foreach ($currentMastery as $kp => $value) {
  1696. $prev = $lastCurrentMastery[$kp] ?? null;
  1697. if ($prev === null) {
  1698. $gainCount++;
  1699. } elseif ($value > $prev) {
  1700. $gainCount++;
  1701. } elseif ($value < $prev) {
  1702. $lossCount++;
  1703. }
  1704. if ($prev !== null) {
  1705. $overallChange += $value - $prev;
  1706. $compareCount++;
  1707. }
  1708. }
  1709. $changeAverage = $compareCount > 0 ? round($overallChange / $compareCount, 4) : 0;
  1710. Log::info('掌握度变化', [
  1711. 'student_id' => $studentId,
  1712. 'paper_id' => $paperId,
  1713. 'snapshot_id' => $snapshotId,
  1714. 'gain_count' => $gainCount,
  1715. 'loss_count' => $lossCount,
  1716. 'overall_change' => $changeAverage,
  1717. ]);
  1718. }
  1719. }
  1720. return [
  1721. 'snapshot_id' => $snapshotId,
  1722. 'current_mastery' => $currentMastery,
  1723. 'overall_mastery' => $overallMastery,
  1724. 'gain_count' => $gainCount,
  1725. 'loss_count' => $lossCount,
  1726. 'overall_change' => $changeAverage,
  1727. ];
  1728. } catch (\Exception $e) {
  1729. // 快照创建失败不影响主流程
  1730. Log::warning('掌握度快照创建失败', [
  1731. 'student_id' => $studentId,
  1732. 'paper_id' => $paperId,
  1733. 'error' => $e->getMessage(),
  1734. ]);
  1735. return null;
  1736. }
  1737. }
  1738. /**
  1739. * 判断掌握度趋势
  1740. */
  1741. /**
  1742. * 评估表现水平
  1743. */
  1744. private function evaluatePerformanceLevel(float $mastery): string
  1745. {
  1746. if ($mastery >= 0.85) {
  1747. return 'excellent';
  1748. } elseif ($mastery >= 0.70) {
  1749. return 'good';
  1750. } elseif ($mastery >= 0.50) {
  1751. return 'fair';
  1752. } else {
  1753. return 'poor';
  1754. }
  1755. }
  1756. /**
  1757. * 生成题目表现总结
  1758. */
  1759. private function generateQuestionPerformanceSummary(array $question, array $stepAnalysis): string
  1760. {
  1761. if (empty($stepAnalysis)) {
  1762. return '整题作答';
  1763. }
  1764. $correctSteps = count(array_filter($stepAnalysis, fn ($s) => $s['is_correct']));
  1765. $totalSteps = count($stepAnalysis);
  1766. if ($correctSteps === $totalSteps) {
  1767. return '所有步骤正确';
  1768. } elseif ($correctSteps > 0) {
  1769. return "部分正确 ({$correctSteps}/{$totalSteps} 步骤正确)";
  1770. } else {
  1771. return '所有步骤错误';
  1772. }
  1773. }
  1774. /**
  1775. * 生成知识点建议
  1776. */
  1777. private function generateKnowledgePointRecommendation(array $data): string
  1778. {
  1779. $mastery = $data['mastery'];
  1780. if ($mastery >= 0.85) {
  1781. return '掌握良好,可安排综合练习';
  1782. } elseif ($mastery >= 0.70) {
  1783. return '基本掌握,建议加强练习';
  1784. } elseif ($mastery >= 0.50) {
  1785. return '需要重点练习,建议安排专项训练';
  1786. } else {
  1787. return '薄弱知识点,建议系统学习和大量练习';
  1788. }
  1789. }
  1790. /**
  1791. * 评估整体表现
  1792. */
  1793. private function evaluateOverallPerformance(float $averageMastery): string
  1794. {
  1795. if ($averageMastery >= 0.85) {
  1796. return '优秀';
  1797. } elseif ($averageMastery >= 0.70) {
  1798. return '良好';
  1799. } elseif ($averageMastery >= 0.50) {
  1800. return '一般';
  1801. } else {
  1802. return '需加强';
  1803. }
  1804. }
  1805. /**
  1806. * 计算推荐题目数量
  1807. */
  1808. private function calculateRecommendedQuestions(float $mastery): int
  1809. {
  1810. if ($mastery >= 0.85) {
  1811. return 1; // 巩固型:1题
  1812. } elseif ($mastery >= 0.50) {
  1813. return 2; // 修补型:2题
  1814. } else {
  1815. return 3; // 挑战型:3题
  1816. }
  1817. }
  1818. /**
  1819. * 确定重点类型
  1820. */
  1821. private function determineFocusType(float $mastery): string
  1822. {
  1823. if ($mastery >= 0.70 && $mastery < 0.85) {
  1824. return 'consolidation'; // 巩固型
  1825. } elseif ($mastery < 0.70) {
  1826. return 'remediation'; // 修补型
  1827. } else {
  1828. return 'challenge'; // 挑战型
  1829. }
  1830. }
  1831. /**
  1832. * 自动计算题目分数并补充未提交的题目
  1833. *
  1834. * 功能:
  1835. * 1. 从 paper_questions 表获取卷子的所有题目
  1836. * 2. 补充未提交的题目(is_correct 默认为 [0],表示错误)
  1837. * 3. 自动计算 score 和 score_obtained
  1838. *
  1839. * @param array $questions 用户提交的题目列表
  1840. * @param string $paperId 卷子ID
  1841. * @return array 完整的题目列表(包含未提交的题目)
  1842. */
  1843. private function autoCalculateScores(array $questions, string $paperId = ''): array
  1844. {
  1845. // 获取已提交题目的ID集合
  1846. $submittedQuestionIds = [];
  1847. foreach ($questions as $question) {
  1848. $qid = $question['question_id'] ?? $question['question_bank_id'] ?? null;
  1849. if ($qid) {
  1850. $submittedQuestionIds[$qid] = true;
  1851. }
  1852. }
  1853. // 从 paper_questions 表获取卷子的所有题目
  1854. if (! empty($paperId)) {
  1855. try {
  1856. $paperQuestions = DB::connection('mysql')
  1857. ->table('paper_questions')
  1858. ->where('paper_id', $paperId)
  1859. ->get(['question_bank_id', 'question_id', 'score']);
  1860. foreach ($paperQuestions as $pq) {
  1861. // 优先用 question_bank_id,其次用 question_id
  1862. $questionId = $pq->question_bank_id ?? $pq->question_id ?? null;
  1863. if (empty($questionId)) {
  1864. continue;
  1865. }
  1866. if (isset($pq->score)) {
  1867. $scoreMap[$questionId] = (float) $pq->score;
  1868. }
  1869. // 如果该题目未提交,补充进去
  1870. if (! isset($submittedQuestionIds[$questionId])) {
  1871. $defaultScore = $pq->score ? floatval($pq->score) : 2.0;
  1872. $questions[] = [
  1873. 'question_id' => $questionId,
  1874. 'student_answer' => null,
  1875. 'is_correct' => [1], // 未提交默认为正确
  1876. 'teacher_comment' => null,
  1877. 'score' => $defaultScore,
  1878. 'score_obtained' => $defaultScore, // 正确则得满分
  1879. ];
  1880. Log::debug('补充未提交的题目', [
  1881. 'paper_id' => $paperId,
  1882. 'question_id' => $questionId,
  1883. 'default_score' => $pq->score ?? 2.0,
  1884. ]);
  1885. }
  1886. }
  1887. } catch (\Exception $e) {
  1888. Log::warning('获取卷子题目列表失败', [
  1889. 'paper_id' => $paperId,
  1890. 'error' => $e->getMessage(),
  1891. ]);
  1892. }
  1893. }
  1894. // 为已提交的题目计算分数
  1895. foreach ($questions as &$question) {
  1896. $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? '';
  1897. // 如果用户没有提供 score,尝试从数据库获取或使用默认值
  1898. if (! isset($question['score'])) {
  1899. $question['score'] = $scoreMap[$questionId] ?? 2.0;
  1900. }
  1901. // 如果用户没有提供 score_obtained,根据 is_correct 计算
  1902. if (! isset($question['score_obtained'])) {
  1903. $question['score_obtained'] = $this->calculateScoreObtained(
  1904. $question['score'] ?? 0,
  1905. $question['is_correct'] ?? []
  1906. );
  1907. }
  1908. if (config('app.debug')) {
  1909. Log::debug('自动计算分数', [
  1910. 'question_id' => $questionId,
  1911. 'default_score' => $question['score'],
  1912. 'score_obtained' => $question['score_obtained'],
  1913. 'is_correct' => $question['is_correct'] ?? [],
  1914. ]);
  1915. }
  1916. }
  1917. return $questions;
  1918. }
  1919. /**
  1920. * 获取题目默认分数
  1921. */
  1922. private function getQuestionDefaultScore(string $questionId): float
  1923. {
  1924. if (empty($questionId)) {
  1925. return 2.0; // 默认分数
  1926. }
  1927. try {
  1928. // 尝试从题库获取题目分数
  1929. $question = DB::connection('mysql')
  1930. ->table('questions')
  1931. ->where('id', $questionId)
  1932. ->first();
  1933. if ($question && isset($question->score)) {
  1934. return (float) $question->score;
  1935. }
  1936. // 如果没有找到,根据题目ID生成一个合理的默认分数
  1937. // 这里可以根据需要调整默认分数逻辑
  1938. return 2.0;
  1939. } catch (\Exception $e) {
  1940. Log::warning('获取题目默认分数失败,使用默认值', [
  1941. 'question_id' => $questionId,
  1942. 'error' => $e->getMessage(),
  1943. ]);
  1944. return 2.0;
  1945. }
  1946. }
  1947. /**
  1948. * 根据 is_correct 数组计算得分
  1949. *
  1950. * @param float $totalScore 总分
  1951. * @param array $isCorrect 正确性数组 [0, 1, 1] 表示第1题错误,第2、3题正确
  1952. * @return float 得分
  1953. */
  1954. private function calculateScoreObtained(float $totalScore, array $isCorrect): float
  1955. {
  1956. if (empty($isCorrect)) {
  1957. return 0.0;
  1958. }
  1959. $correctCount = array_sum($isCorrect);
  1960. $totalCount = count($isCorrect);
  1961. if ($totalCount === 0) {
  1962. return 0.0;
  1963. }
  1964. // 按正确率计算得分
  1965. $scoreRatio = $correctCount / $totalCount;
  1966. return round($totalScore * $scoreRatio, 2);
  1967. }
  1968. }