| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595 |
- <?php
- namespace App\Services;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\DB;
- class LearningAnalyticsService
- {
- protected string $baseUrl;
- protected int $timeout = 10;
- protected ?QuestionBankService $questionBankService;
- public function __construct(?QuestionBankService $questionBankService = null)
- {
- $this->baseUrl = config('services.learning_analytics.url', env('LEARNING_ANALYTICS_API_BASE', 'http://localhost:5016'));
- $this->questionBankService = $questionBankService;
- }
- /**
- * 获取学生掌握度
- */
- public function getStudentMastery(string $studentId, string $kpCode = null): array
- {
- try {
- $endpoint = $kpCode
- ? "/api/v1/mastery/student/{$studentId}/kp/{$kpCode}"
- : "/api/v1/mastery/student/{$studentId}";
-
- Log::info('LearningAnalytics Request: Get Student Mastery', [
- 'endpoint' => $endpoint,
- 'student_id' => $studentId,
- 'kp_code' => $kpCode
- ]);
- $response = Http::timeout($this->timeout)->get($this->baseUrl . $endpoint);
-
- Log::info('LearningAnalytics Response: Get Student Mastery', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
-
- if ($response->successful()) {
- return $response->json();
- }
- Log::error('LearningAnalytics API Error', [
- 'endpoint' => $endpoint,
- 'status' => $response->status(),
- 'response' => $response->body()
- ]);
- return [
- 'error' => true,
- 'message' => 'Failed to fetch mastery data'
- ];
- } catch (\Exception $e) {
- Log::error('LearningAnalytics Service Exception', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return [
- 'error' => true,
- 'message' => $e->getMessage()
- ];
- }
- }
- /**
- * 更新学生掌握度
- */
- public function updateMastery(array $data): array
- {
- try {
- Log::info('LearningAnalytics Request: Update Mastery', [
- 'url' => $this->baseUrl . '/api/v1/mastery/student/' . $data['student_id'] . '/update',
- 'data' => $data
- ]);
- $response = Http::timeout($this->timeout)
- ->post($this->baseUrl . '/api/v1/mastery/student/' . $data['student_id'] . '/update', $data);
- Log::info('LearningAnalytics Response: Update Mastery', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- Log::error('LearningAnalytics Update Error', [
- 'data' => $data,
- 'status' => $response->status(),
- 'response' => $response->body()
- ]);
- return [
- 'error' => true,
- 'message' => 'Failed to update mastery'
- ];
- } catch (\Exception $e) {
- Log::error('LearningAnalytics Update Exception', [
- 'error' => $e->getMessage(),
- 'data' => $data
- ]);
- return [
- 'error' => true,
- 'message' => $e->getMessage()
- ];
- }
- }
- /**
- * 获取老师名下的所有学生
- */
- public function getTeacherStudents(string $teacherId): array
- {
- try {
- // 从本地MySQL获取学生
- $students = DB::table('students as s')
- ->leftJoin('users as u', 's.student_id', '=', 'u.user_id')
- ->where('s.teacher_id', $teacherId)
- ->select(
- 's.student_id',
- 's.name',
- 's.grade',
- 's.class_name',
- 'u.username',
- 'u.email'
- )
- ->get()
- ->toArray();
- return $students;
- } catch (\Exception $e) {
- Log::error('Get Teacher Students Error', [
- 'teacher_id' => $teacherId,
- 'error' => $e->getMessage()
- ]);
- return [];
- }
- }
- /**
- * 获取学生学习分析
- */
- public function getStudentAnalysis(string $studentId): array
- {
- // 从LearningAnalytics获取掌握度
- $masteryData = $this->getStudentMastery($studentId);
-
- // 从MySQL获取练习历史
- $exercises = DB::table('student_exercises')
- ->where('student_id', $studentId)
- ->orderBy('created_at', 'desc')
- ->limit(50)
- ->get()
- ->toArray();
- // 从MySQL获取掌握度记录
- $masteryRecords = DB::table('student_mastery')
- ->where('student_id', $studentId)
- ->get()
- ->toArray();
- return [
- 'student_id' => $studentId,
- 'mastery_from_la' => $masteryData,
- 'exercises' => $exercises,
- 'mastery_records' => $masteryRecords,
- 'total_exercises' => count($exercises),
- 'total_mastery_records' => count($masteryRecords),
- ];
- }
- /**
- * 生成学习测试数据
- */
- public function generateLearningData(string $studentId, array $params): array
- {
- $results = [];
-
- foreach ($params as $param) {
- $data = [
- 'student_id' => $studentId,
- 'kp_code' => $param['kp_code'],
- 'is_correct' => $param['is_correct'],
- 'time_spent_seconds' => $param['time_spent_seconds'] ?? 120,
- 'difficulty_level' => $param['difficulty_level'] ?? 3,
- ];
-
- $result = $this->updateMastery($data);
- $results[] = $result;
- }
-
- return $results;
- }
- /**
- * 获取学习推荐
- */
- public function getLearningRecommendations(string $studentId): array
- {
- try {
- Log::info('LearningAnalytics Request: Get Learning Recommendations', [
- 'url' => $this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend"
- ]);
- $response = Http::timeout($this->timeout)
- ->get($this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend");
- Log::info('LearningAnalytics Response: Get Learning Recommendations', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- return ['error' => true, 'message' => 'Failed to fetch recommendations'];
- } catch (\Exception $e) {
- return ['error' => true, 'message' => $e->getMessage()];
- }
- }
- /**
- * 获取知识点列表(从知识图谱API)
- */
- public function getKnowledgePoints(array $filters = []): array
- {
- try {
- $kgBaseUrl = config('services.knowledge_api.base_url', 'http://localhost:5011');
- Log::info('LearningAnalytics Request: Get Knowledge Points', [
- 'url' => $kgBaseUrl . '/knowledge-points/',
- 'filters' => $filters
- ]);
- $response = Http::timeout($this->timeout)
- ->get($kgBaseUrl . '/knowledge-points/', $filters);
- Log::info('LearningAnalytics Response: Get Knowledge Points', [
- 'status' => $response->status(),
- 'count' => count($response->json()['data'] ?? [])
- ]);
- if ($response->successful()) {
- return $response->json()['data'] ?? [];
- }
- return [];
- } catch (\Exception $e) {
- Log::error('LearningAnalytics Knowledge Points Error', [
- 'error' => $e->getMessage()
- ]);
- return [];
- }
- }
- /**
- * 获取学生技能熟练度
- */
- public function getStudentSkillProficiency(string $studentId): array
- {
- try {
- Log::info('LearningAnalytics Request: Get Student Skill Proficiency', [
- 'url' => $this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}"
- ]);
- $response = Http::timeout($this->timeout)
- ->get($this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}");
- Log::info('LearningAnalytics Response: Get Student Skill Proficiency', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('LearningAnalytics Skill Proficiency API Error', [
- 'student_id' => $studentId,
- 'status' => $response->status(),
- 'response' => $response->body()
- ]);
- // API失败时返回空数据,不报错
- return [
- 'student_id' => $studentId,
- 'total_count' => 0,
- 'data' => []
- ];
- } catch (\Exception $e) {
- Log::warning('LearningAnalytics Skill Proficiency API Exception', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- // 发生异常时返回空数据,不报错
- return [
- 'student_id' => $studentId,
- 'total_count' => 0,
- 'data' => []
- ];
- }
- }
- /**
- * 获取学生掌握度列表(别名方法)
- */
- public function getStudentMasteryList(string $studentId): array
- {
- return $this->getStudentMastery($studentId);
- }
- /**
- * 获取知识点依赖关系
- */
- public function getKnowledgeDependencies(): array
- {
- try {
- Log::info('LearningAnalytics Request: Get Knowledge Dependencies', [
- 'url' => $this->baseUrl . '/knowledge-dependencies/'
- ]);
- $response = Http::timeout($this->timeout)
- ->get($this->baseUrl . '/knowledge-dependencies/');
- Log::info('LearningAnalytics Response: Get Knowledge Dependencies', [
- 'status' => $response->status(),
- 'count' => count($response->json()['data'] ?? [])
- ]);
- if ($response->successful()) {
- return $response->json()['data'] ?? [];
- }
- return [];
- } catch (\Exception $e) {
- Log::error('LearningAnalytics Knowledge Dependencies Error', [
- 'error' => $e->getMessage()
- ]);
- return [];
- }
- }
- /**
- * 提交学生答题记录
- */
- public function submitAttempt(string $studentId, array $attemptData): array
- {
- try {
- Log::info('LearningAnalytics Request: Submit Attempt', [
- 'url' => $this->baseUrl . "/api/v1/attempts/student/{$studentId}",
- 'data' => $attemptData
- ]);
- $response = Http::timeout($this->timeout)
- ->post($this->baseUrl . "/api/v1/attempts/student/{$studentId}", $attemptData);
- Log::info('LearningAnalytics Response: Submit Attempt', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- Log::error('Submit Attempt Error', [
- 'student_id' => $studentId,
- 'data' => $attemptData,
- 'status' => $response->status(),
- 'response' => $response->body()
- ]);
- return [
- 'error' => true,
- 'message' => 'Failed to submit attempt'
- ];
- } catch (\Exception $e) {
- Log::error('Submit Attempt Exception', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage(),
- 'data' => $attemptData
- ]);
- return [
- 'error' => true,
- 'message' => $e->getMessage()
- ];
- }
- }
- /**
- * 批量提交学生答题记录
- */
- public function submitBatchAttempts(string $studentId, array $data): array
- {
- try {
- Log::info('LearningAnalytics Request: Submit Batch Attempts', [
- 'url' => $this->baseUrl . "/api/v1/attempts/batch/student/{$studentId}",
- 'data_count' => count($data['answers'] ?? []),
- 'paper_id' => $data['paper_id'] ?? null
- ]);
- $response = Http::timeout($this->timeout)
- ->post($this->baseUrl . "/api/v1/attempts/batch/student/{$studentId}", $data);
- Log::info('LearningAnalytics Response: Submit Batch Attempts', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- Log::error('Submit Batch Attempts Error', [
- 'student_id' => $studentId,
- 'data_count' => count($data['answers'] ?? []),
- 'status' => $response->status(),
- 'response' => $response->body()
- ]);
- return [
- 'error' => true,
- 'message' => 'Failed to submit batch attempts: ' . $response->body()
- ];
- } catch (\Exception $e) {
- Log::error('Submit Batch Attempts Exception', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- return [
- 'error' => true,
- 'message' => $e->getMessage()
- ];
- }
- }
- /**
- * 提交OCR分析请求
- */
- public function submitOCRAnalysis(array $data): array
- {
- try {
- Log::info('Sending OCR results to LearningAnalytics', [
- 'student_id' => $data['student_id'] ?? 'unknown',
- 'exam_id' => $data['exam_id'] ?? 'unknown',
- 'question_count' => count($data['questions'] ?? [])
- ]);
- $response = Http::timeout(30) // 分析可能需要较长时间
- ->post($this->baseUrl . '/api/analysis/process-answers', $data);
- Log::info('LearningAnalytics Response: Submit OCR Analysis', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
- if ($response->successful()) {
- Log::info('Analysis submitted successfully', [
- 'analysis_id' => $response->json('analysis_id')
- ]);
- return $response->json();
- }
- Log::error('Submit OCR Analysis Error', [
- 'status' => $response->status(),
- 'response' => $response->body(),
- 'data_preview' => array_merge($data, ['questions' => count($data['questions'])])
- ]);
- return [
- 'error' => true,
- 'message' => 'Failed to submit analysis: ' . $response->body()
- ];
- } catch (\Exception $e) {
- Log::error('Submit OCR Analysis Exception', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return [
- 'error' => true,
- 'message' => $e->getMessage()
- ];
- }
- }
-
- /**
- * 获取分析结果详情
- */
- public function getAnalysisResult(string $analysisId): array
- {
- try {
- $endpoint = "/api/analysis/analysis/{$analysisId}";
-
- Log::info('LearningAnalytics Request: Get Analysis Result', [
- 'endpoint' => $endpoint,
- 'analysis_id' => $analysisId
- ]);
- $response = Http::timeout($this->timeout)->get($this->baseUrl . $endpoint);
-
- Log::info('LearningAnalytics Response: Get Analysis Result', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
-
- if ($response->successful()) {
- return $response->json();
- }
- Log::error('Get Analysis Result Error', [
- 'analysis_id' => $analysisId,
- 'status' => $response->status(),
- 'response' => $response->body()
- ]);
- return [
- 'error' => true,
- 'message' => 'Failed to fetch analysis result'
- ];
- } catch (\Exception $e) {
- Log::error('Get Analysis Result Exception', [
- 'analysis_id' => $analysisId,
- 'error' => $e->getMessage()
- ]);
- return [
- 'error' => true,
- 'message' => $e->getMessage()
- ];
- }
- }
- /**
- * 检查服务健康状态
- */
- public function checkHealth(): bool
- {
- try {
- $response = Http::timeout(5)->get($this->baseUrl . '/health');
- return $response->successful();
- } catch (\Exception $e) {
- return false;
- }
- }
- /**
- * 获取学生掌握度概览
- */
- public function getStudentMasteryOverview(string $studentId): array
- {
- try {
- $mastery = $this->getStudentMastery($studentId);
- if (isset($mastery['error'])) {
- return [
- 'total_knowledge_points' => 0,
- 'average_mastery_level' => 0,
- 'mastered_knowledge_points' => 0,
- 'good_knowledge_points' => 0,
- 'weak_knowledge_points' => 0,
- 'weak_knowledge_points_list' => [],
- 'details' => []
- ];
- }
- $data = $mastery['data'] ?? [];
- // **修复**:不过滤total_attempts,与薄弱点API保持一致
- // 这样确保数据一致性
- $attemptedData = $data;
- $total = count($data);
- $attemptedCount = count($attemptedData);
- $average = $attemptedCount > 0
- ? array_sum(array_column($attemptedData, 'mastery_level')) / $attemptedCount
- : 0;
- // 分类知识点
- $mastered = [];
- $good = [];
- $weak = [];
- foreach ($attemptedData as $item) {
- $level = $item['mastery_level'] ?? 0;
- if ($level >= 0.85) {
- $mastered[] = $item;
- } elseif ($level >= 0.70) {
- $good[] = $item;
- } else {
- $weak[] = $item;
- }
- }
- return [
- 'total_knowledge_points' => $total,
- 'average_mastery_level' => $average,
- 'mastered_knowledge_points' => count($mastered),
- 'good_knowledge_points' => count($good),
- 'weak_knowledge_points' => count($weak),
- 'weak_knowledge_points_list' => $weak,
- 'details' => $data
- ];
- } catch (\Exception $e) {
- Log::error('Get Student Mastery Overview Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- return [
- 'total_knowledge_points' => 0,
- 'average_mastery_level' => 0,
- 'mastered_knowledge_points' => 0,
- 'good_knowledge_points' => 0,
- 'weak_knowledge_points' => 0,
- 'weak_knowledge_points_list' => [],
- 'details' => []
- ];
- }
- }
- /**
- * 获取学生技能摘要
- */
- public function getStudentSkillSummary(string $studentId): array
- {
- try {
- $proficiency = $this->getStudentSkillProficiency($studentId);
- // 无论是否有error,都继续处理,返回空数据
- $data = $proficiency['data'] ?? [];
- $totalSkills = count($data);
- $averageLevel = $totalSkills > 0 ? array_sum(array_column($data, 'proficiency_level')) / $totalSkills : 0;
- // 计算总答题数
- $totalQuestions = 0;
- foreach ($data as $skill) {
- $totalQuestions += $skill['total_questions_attempted'] ?? 0;
- }
- return [
- 'total_skills' => $totalSkills,
- 'average_proficiency_level' => $averageLevel,
- 'total_questions_attempted' => $totalQuestions,
- 'skill_list' => $data
- ];
- } catch (\Exception $e) {
- Log::warning('Get Student Skill Summary Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- // 发生异常时返回空数据
- return [
- 'total_skills' => 0,
- 'average_proficiency_level' => 0,
- 'total_questions_attempted' => 0,
- 'skill_list' => []
- ];
- }
- }
- /**
- * 获取学生预测数据
- */
- public function getStudentPredictions(string $studentId, int $count = 5): array
- {
- try {
- Log::info('LearningAnalytics Request: Get Student Predictions', [
- 'url' => $this->baseUrl . "/api/v1/prediction/student/{$studentId}?count={$count}"
- ]);
- $response = Http::timeout($this->timeout)
- ->get($this->baseUrl . "/api/v1/prediction/student/{$studentId}?count={$count}");
- Log::info('LearningAnalytics Response: Get Student Predictions', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
- if ($response->successful()) {
- $data = $response->json();
- $predictions = $data['predictions'] ?? $data['data'] ?? [];
- return [
- 'predictions' => $predictions
- ];
- }
- return [
- 'predictions' => []
- ];
- } catch (\Exception $e) {
- Log::error('Get Student Predictions Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- return [
- 'predictions' => []
- ];
- }
- }
- /**
- * 获取学生学习路径
- */
- public function getStudentLearningPaths(string $studentId, int $count = 3): array
- {
- try {
- Log::info('LearningAnalytics Request: Get Student Learning Paths', [
- 'url' => $this->baseUrl . "/api/v1/learning-path/student/{$studentId}?count={$count}"
- ]);
- $response = Http::timeout($this->timeout)
- ->get($this->baseUrl . "/api/v1/learning-path/student/{$studentId}?count={$count}");
- Log::info('LearningAnalytics Response: Get Student Learning Paths', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
- if ($response->successful()) {
- $data = $response->json()['data'] ?? [];
- return [
- 'paths' => $data
- ];
- }
- return [
- 'paths' => []
- ];
- } catch (\Exception $e) {
- Log::error('Get Student Learning Paths Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- return [
- 'paths' => []
- ];
- }
- }
- /**
- * 获取预测分析数据
- */
- public function getPredictionAnalytics(string $studentId): array
- {
- try {
- $predictions = $this->getStudentPredictions($studentId, 10);
- if (empty($predictions)) {
- return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
- }
- $accuracy = 0;
- $confidence = 0;
- if (!empty($predictions)) {
- $accuracy = rand(75, 95); // 模拟准确率
- $confidence = rand(70, 90); // 模拟置信度
- }
- $trend = 'improving'; // improving, stable, declining
- return [
- 'accuracy' => $accuracy,
- 'trend' => $trend,
- 'confidence' => $confidence,
- 'sample_size' => count($predictions)
- ];
- } catch (\Exception $e) {
- Log::error('Get Prediction Analytics Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
- }
- }
- /**
- * 获取学习路径分析数据
- */
- public function getLearningPathAnalytics(string $studentId): array
- {
- try {
- $paths = $this->getStudentLearningPaths($studentId, 5);
- if (empty($paths)) {
- return [
- 'active_paths' => 0,
- 'completed_paths' => 0,
- 'average_efficiency_score' => 0,
- 'completion_rate' => 0,
- 'average_time' => 0,
- 'total_paths' => 0
- ];
- }
- $activePaths = 0;
- $completedPaths = 0;
- $efficiencyScores = [];
- foreach ($paths as $path) {
- if (($path['status'] ?? '') === 'active') {
- $activePaths++;
- }
- if (($path['status'] ?? '') === 'completed') {
- $completedPaths++;
- }
- if (isset($path['efficiency_score'])) {
- $efficiencyScores[] = $path['efficiency_score'];
- }
- }
- $averageEfficiency = !empty($efficiencyScores)
- ? array_sum($efficiencyScores) / count($efficiencyScores)
- : rand(60, 85) / 100;
- $completionRate = count($paths) > 0
- ? ($completedPaths / count($paths)) * 100
- : 0;
- $averageTime = rand(30, 60); // 模拟平均时间(分钟)
- return [
- 'active_paths' => $activePaths,
- 'completed_paths' => $completedPaths,
- 'average_efficiency_score' => $averageEfficiency,
- 'completion_rate' => $completionRate,
- 'average_time' => $averageTime,
- 'total_paths' => count($paths)
- ];
- } catch (\Exception $e) {
- Log::error('Get Learning Path Analytics Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- return [
- 'active_paths' => 0,
- 'completed_paths' => 0,
- 'average_efficiency_score' => 0,
- 'completion_rate' => 0,
- 'average_time' => 0,
- 'total_paths' => 0
- ];
- }
- }
- /**
- * 快速分数预测
- */
- public function quickScorePrediction(string $studentId): array
- {
- Log::info('开始调用快速预测API', ['student_id' => $studentId]);
- try {
- $response = Http::timeout($this->timeout)
- ->post($this->baseUrl . "/api/v1/prediction/student/{$studentId}/quick-prediction", [
- 'student_id' => $studentId
- ]);
- Log::info('快速预测API响应', [
- 'student_id' => $studentId,
- 'status' => $response->status(),
- 'body' => $response->body()
- ]);
- if ($response->successful()) {
- $data = $response->json();
- Log::info('快速预测API返回数据', ['student_id' => $studentId, 'data' => $data]);
- // API直接返回数据,没有嵌套在'data'键中
- $quickPredictionData = $data['quick_prediction'] ?? [];
- return [
- 'quick_prediction' => [
- 'current_score' => $quickPredictionData['current_score'] ?? 70,
- 'predicted_score' => $quickPredictionData['predicted_score'] ?? 75,
- 'improvement_potential' => $quickPredictionData['improvement_potential'] ?? 5,
- 'estimated_study_hours' => $quickPredictionData['estimated_study_hours'] ?? 15,
- 'confidence_level' => $quickPredictionData['confidence_level'] ?? 0.75,
- 'priority_topics' => $quickPredictionData['priority_topics'] ?? [],
- 'recommended_actions' => $quickPredictionData['recommended_actions'] ?? [],
- 'weak_knowledge_points_count' => $quickPredictionData['weak_knowledge_points_count'] ?? 0,
- 'total_knowledge_points' => $quickPredictionData['total_knowledge_points'] ?? 0
- ],
- 'predicted_score' => $quickPredictionData['predicted_score'] ?? 75,
- 'confidence' => $quickPredictionData['confidence_level'] ? $quickPredictionData['confidence_level'] * 100 : 75,
- 'time_estimate' => $quickPredictionData['estimated_study_hours'] ?? 15
- ];
- }
- Log::warning('快速预测API调用失败', [
- 'student_id' => $studentId,
- 'status' => $response->status(),
- 'response' => $response->body()
- ]);
- return [
- 'quick_prediction' => [
- 'improvement_potential' => 0,
- 'estimated_study_hours' => 0,
- 'confidence_level' => 0
- ],
- 'predicted_score' => 0,
- 'confidence' => 0,
- 'time_estimate' => 0
- ];
- } catch (\Exception $e) {
- Log::error('Quick Score Prediction Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- return [
- 'quick_prediction' => [
- 'improvement_potential' => 0,
- 'estimated_study_hours' => 0,
- 'confidence_level' => 0
- ],
- 'predicted_score' => 0,
- 'confidence' => 0,
- 'time_estimate' => 0
- ];
- }
- }
- /**
- * 推荐学习路径
- */
- public function recommendLearningPaths(string $studentId, int $count = 3): array
- {
- try {
- Log::info('LearningAnalytics Request: Recommend Learning Paths', [
- 'url' => $this->baseUrl . "/api/v1/learning-path/recommend/{$studentId}?count={$count}"
- ]);
- $response = Http::timeout($this->timeout)
- ->get($this->baseUrl . "/api/v1/learning-path/recommend/{$studentId}?count={$count}");
- Log::info('LearningAnalytics Response: Recommend Learning Paths', [
- 'status' => $response->status(),
- 'body' => $response->json()
- ]);
- if ($response->successful()) {
- $data = $response->json()['data'] ?? [];
- return [
- 'recommendations' => $data
- ];
- }
- return [
- 'recommendations' => []
- ];
- } catch (\Exception $e) {
- Log::error('Recommend Learning Paths Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- return [
- 'recommendations' => []
- ];
- }
- }
- /**
- * 重新计算掌握度
- */
- public function recalculateMastery(string $studentId, string $kpCode): bool
- {
- try {
- Log::info('LearningAnalytics Request: Recalculate Mastery', [
- 'url' => $this->baseUrl . "/api/v1/mastery/recalculate/{$studentId}",
- 'kp_code' => $kpCode
- ]);
- $response = Http::timeout($this->timeout)
- ->post($this->baseUrl . "/api/v1/mastery/recalculate/{$studentId}", [
- 'student_id' => $studentId,
- 'kp_code' => $kpCode
- ]);
- Log::info('LearningAnalytics Response: Recalculate Mastery', [
- 'status' => $response->status(),
- 'body' => $response->body()
- ]);
- return $response->successful();
- } catch (\Exception $e) {
- Log::error('Recalculate Mastery Error', [
- 'student_id' => $studentId,
- 'kp_code' => $kpCode,
- 'error' => $e->getMessage()
- ]);
- return false;
- }
- }
- /**
- * 批量更新技能熟练度
- */
- public function batchUpdateSkillProficiency(string $studentId): bool
- {
- try {
- $response = Http::timeout($this->timeout)
- ->post($this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}/batch-update", [
- 'student_id' => $studentId
- ]);
- return $response->successful();
- } catch (\Exception $e) {
- Log::error('Batch Update Skill Proficiency Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- return false;
- }
- }
- /**
- * 清空学生所有答题数据
- */
- public function clearStudentData(string $studentId): bool
- {
- try {
- // 清空LearningAnalytics中的数据(通过API)
- $response = Http::timeout($this->timeout)
- ->delete($this->baseUrl . "/api/v1/student/{$studentId}/clear");
- if (!$response->successful()) {
- Log::error('Clear LearningAnalytics Data Failed', [
- 'student_id' => $studentId,
- 'status' => $response->status(),
- 'response' => $response->body()
- ]);
- }
- // 清空MySQL中的数据
- $this->clearStudentMySQLData($studentId);
- Log::info('Student Data Cleared Successfully', [
- 'student_id' => $studentId,
- 'api_success' => $response->successful()
- ]);
- return true;
- } catch (\Exception $e) {
- Log::error('Clear Student Data Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- // 即使API失败,也要尝试清空本地数据
- try {
- $this->clearStudentMySQLData($studentId);
- return true;
- } catch (\Exception $localError) {
- Log::error('Clear Local Data Also Failed', [
- 'student_id' => $studentId,
- 'error' => $localError->getMessage()
- ]);
- return false;
- }
- }
- }
- /**
- * 清空学生MySQL中的答题数据
- */
- private function clearStudentMySQLData(string $studentId): void
- {
- try {
- // 清空student_exercises表
- DB::table('student_exercises')
- ->where('student_id', $studentId)
- ->delete();
- // 清空student_mastery表
- DB::table('student_mastery')
- ->where('student_id', $studentId)
- ->delete();
- Log::info('Student MySQL Data Cleared', [
- 'student_id' => $studentId
- ]);
- } catch (\Exception $e) {
- Log::error('Clear Student MySQL Data Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- throw $e; // 重新抛出异常,让上层处理
- }
- }
- /**
- * 获取学生列表(供智能出卷使用)
- */
- public function getStudentsList(): array
- {
- try {
- $response = Http::timeout($this->timeout)
- ->get($this->baseUrl . '/api/v1/students/list');
- if ($response->successful()) {
- return $response->json('data', []);
- }
- // 如果API失败,尝试从MySQL直接读取
- return $this->getStudentsFromMySQL();
- } catch (\Exception $e) {
- Log::error('Get Students List Error', [
- 'error' => $e->getMessage()
- ]);
- // 返回模拟数据
- return [
- ['student_id' => 'stu_001', 'name' => '张三'],
- ['student_id' => 'stu_002', 'name' => '李四'],
- ['student_id' => 'stu_003', 'name' => '王五'],
- ];
- }
- }
- /**
- * 从MySQL获取学生列表
- */
- private function getStudentsFromMySQL(): array
- {
- try {
- return DB::table('students')
- ->select('student_id', 'name')
- ->limit(100)
- ->get()
- ->toArray();
- } catch (\Exception $e) {
- Log::error('Get Students From MySQL Error', [
- 'error' => $e->getMessage()
- ]);
- return [];
- }
- }
- /**
- * 获取学生薄弱点列表
- */
- public function getStudentWeaknesses(string $studentId, int $limit = 10): array
- {
- try {
- // 使用正确的API路径:/api/v1/student/{student_id}/weak-points
- $response = Http::timeout($this->timeout)
- ->get($this->baseUrl . "/api/v1/student/{$studentId}/weak-points");
- if ($response->successful()) {
- $data = $response->json('data', []);
- $weakPoints = $data['weak_points'] ?? [];
- // 转换为统一的格式
- return array_map(function ($item) use ($studentId) {
- return [
- 'kp_code' => $item['kp'] ?? '',
- 'kp_name' => $item['kp'] ?? '',
- 'mastery' => $item['mastery_level'] ?? 0,
- 'stability' => 0.5, // 默认稳定性
- 'weakness_level' => 1.0 - ($item['mastery_level'] ?? 0.5),
- 'practice_count' => $item['practice_count'] ?? 0,
- 'success_rate' => $item['success_rate'] ?? 0,
- 'priority' => $item['priority'] ?? '中',
- 'suggested_questions' => $item['suggested_questions'] ?? 0
- ];
- }, $weakPoints);
- }
- Log::warning('LearningAnalytics weaknesses API失败,使用本地MySQL数据', [
- 'student_id' => $studentId,
- 'status' => $response->status()
- ]);
- // API失败时,从MySQL直接查询
- return $this->getStudentWeaknessesFromMySQL($studentId, $limit);
- } catch (\Exception $e) {
- Log::error('Get Student Weaknesses Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- // 发生异常时,返回空数组,让前端可以继续使用默认值
- return [];
- }
- }
- /**
- * 从MySQL获取学生薄弱点
- */
- private function getStudentWeaknessesFromMySQL(string $studentId, int $limit = 10): array
- {
- try {
- $weaknesses = DB::table('student_mastery as sm')
- ->join('knowledge_points as kp', 'sm.kp', '=', 'kp.kp')
- ->where('sm.student_id', $studentId)
- ->where('sm.mastery', '<', 0.7) // 掌握度低于70%视为薄弱点
- ->orderBy('sm.mastery', 'asc')
- ->limit($limit)
- ->select([
- 'sm.kp as kp_code',
- 'kp.cn_name as kp_name',
- 'sm.mastery',
- 'sm.stability'
- ])
- ->get()
- ->toArray();
- return array_map(function ($item) {
- return [
- 'kp_code' => $item->kp_code,
- 'kp_name' => $item->kp_name,
- 'mastery' => (float) $item->mastery,
- 'stability' => (float) $item->stability,
- 'weakness_level' => 1.0 - (float) $item->mastery // 薄弱程度
- ];
- }, $weaknesses);
- } catch (\Exception $e) {
- Log::error('Get Student Weaknesses From MySQL Error', [
- 'student_id' => $studentId,
- 'error' => $e->getMessage()
- ]);
- return [];
- }
- }
- /**
- * 智能出卷:根据学生掌握度智能选择题目
- */
- public function generateIntelligentExam(array $params): array
- {
- try {
- $studentId = $params['student_id'] ?? null;
- $totalQuestions = $params['total_questions'] ?? 20;
- $kpCodes = $params['kp_codes'] ?? [];
- $skills = $params['skills'] ?? [];
- $questionTypeRatio = $params['question_type_ratio'] ?? [
- '选择题' => 40,
- '填空题' => 30,
- '解答题' => 30,
- ];
- $difficultyRatio = $params['difficulty_ratio'] ?? [
- '基础' => 50,
- '中等' => 35,
- '拔高' => 15,
- ];
- // 1. 如果指定了学生,获取学生的薄弱点
- $weaknessFilter = [];
- if ($studentId) {
- $weaknesses = $this->getStudentWeaknesses($studentId, 20);
- $weaknessFilter = array_column($weaknesses, 'kp_code');
- // 如果用户没有指定知识点,使用学生的薄弱点
- if (empty($kpCodes)) {
- $kpCodes = $weaknessFilter;
- }
- }
- // 如果仍然没有知识点(例如新学生无薄弱点),根据年级从知识图谱获取知识点
- if (empty($kpCodes)) {
- $filters = [];
- if ($studentId) {
- $student = \App\Models\Student::find($studentId);
- if ($student && $student->grade) {
- $grade = $student->grade;
- $standardizedGrade = $grade;
-
- // 标准化年级名称并更新数据库
- if ($grade === '初一') {
- $standardizedGrade = '七年级';
- } elseif ($grade === '初二') {
- $standardizedGrade = '八年级';
- } elseif ($grade === '初三') {
- $standardizedGrade = '九年级';
- }
- if ($standardizedGrade !== $grade) {
- $student->grade = $standardizedGrade;
- $student->save();
- Log::info('Standardized student grade', ['student_id' => $studentId, 'old' => $grade, 'new' => $standardizedGrade]);
- $grade = $standardizedGrade;
- }
- // 映射年级到学段 (phase)
- if (str_contains($grade, '初') || str_contains($grade, '七年级') || str_contains($grade, '八年级') || str_contains($grade, '九年级')) {
- $filters['phase'] = '初中';
- } elseif (str_contains($grade, '高')) {
- $filters['phase'] = '高中';
- }
- }
- }
- // 调用API获取过滤后的知识点
- $filteredKps = $this->getKnowledgePoints($filters);
-
- if (!empty($filteredKps)) {
- // 随机选择 5 个知识点
- $kpKeys = array_column($filteredKps, 'kp_code');
- if (empty($kpKeys)) {
- $kpKeys = array_column($filteredKps, 'code');
- }
-
- if (!empty($kpKeys)) {
- $randomKeys = array_rand(array_flip($kpKeys), min(5, count($kpKeys)));
- $kpCodes = is_array($randomKeys) ? $randomKeys : [$randomKeys];
-
- Log::info('Randomly selected KPs for student based on grade (API)', [
- 'student_id' => $studentId,
- 'grade' => $student->grade ?? 'unknown',
- 'filters' => $filters,
- 'kps' => $kpCodes
- ]);
- }
- }
- }
- // 2. 调用题库API获取符合条件的所有题目
- $allQuestions = $this->getQuestionsFromBank($kpCodes, $skills, $studentId);
- if (empty($allQuestions)) {
- // 根据是否有选择的知识点给出不同的错误信息
- if (empty($kpCodes)) {
- $message = '未选择知识点,无法生成试卷。请先选择知识点或选择学生以获取薄弱点推荐。';
- } else {
- $message = '题库中暂无可用题目。您可以选择其他知识点,或点击"生成练习题"按钮先补充题库。';
- }
- Log::warning('智能出卷失败 - 未找到题目', [
- 'student_id' => $studentId,
- 'selected_kp_codes' => $kpCodes,
- 'message' => $message
- ]);
- return [
- 'success' => false,
- 'message' => $message,
- 'questions' => []
- ];
- }
- // 3. 根据掌握度对题目进行筛选和排序
- $selectedQuestions = $this->selectQuestionsByMastery(
- $allQuestions,
- $studentId,
- $totalQuestions,
- $questionTypeRatio,
- $difficultyRatio,
- $weaknessFilter
- );
- if (empty($selectedQuestions)) {
- return [
- 'success' => false,
- 'message' => '题目筛选失败',
- 'questions' => []
- ];
- }
- return [
- 'success' => true,
- 'message' => '智能出卷成功',
- 'questions' => $selectedQuestions,
- 'stats' => [
- 'total_selected' => count($selectedQuestions),
- 'source_questions' => count($allQuestions),
- 'weakness_targeted' => $studentId ? count(array_intersect(array_column($selectedQuestions, 'kp_code'), $weaknessFilter)) : 0
- ]
- ];
- } catch (\Exception $e) {
- Log::error('Generate Intelligent Exam Error', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return [
- 'success' => false,
- 'message' => '智能出卷异常: ' . $e->getMessage(),
- 'questions' => []
- ];
- }
- }
- /**
- * 从题库获取题目
- */
- private function getQuestionsFromBank(array $kpCodes, array $skills, ?string $studentId): array
- {
- try {
- // 构建查询参数
- $params = [
- 'kp_codes' => implode(',', $kpCodes),
- 'limit' => 1000 // 获取足够多的题目用于筛选
- ];
- if (!empty($skills)) {
- $params['skills'] = implode(',', $skills);
- }
- if ($studentId) {
- $params['exclude_student_questions'] = $studentId; // 过滤学生做过的题目
- }
- // 调用QuestionBank API
- // 使用 QuestionBankService 获取题目 (使用 filterQuestions 方法以支持 kp_codes)
- // 从容器动态获取实例
- if (!$this->questionBankService) {
- $this->questionBankService = app(QuestionBankService::class);
- }
- $response = $this->questionBankService->filterQuestions($params);
- if (!empty($response['data'])) {
- return $response['data'];
- }
-
- Log::warning('Get Questions From Bank Failed or Empty', [
- 'params' => $params,
- 'response' => $response
- ]);
- return [];
- } catch (\Exception $e) {
- Log::error('Get Questions From Bank Error', [
- 'error' => $e->getMessage()
- ]);
- }
- return [];
- }
- /**
- * 根据学生掌握度筛选题目
- */
- private function selectQuestionsByMastery(
- array $questions,
- ?string $studentId,
- int $totalQuestions,
- array $questionTypeRatio,
- array $difficultyRatio,
- array $weaknessFilter
- ): array {
- // 1. 按知识点分组
- $questionsByKp = [];
- foreach ($questions as $question) {
- $kpCode = $question['kp_code'] ?? '';
- if (!isset($questionsByKp[$kpCode])) {
- $questionsByKp[$kpCode] = [];
- }
- $questionsByKp[$kpCode][] = $question;
- }
- // 2. 为每个知识点计算权重
- $kpWeights = [];
- foreach (array_keys($questionsByKp) as $kpCode) {
- if ($studentId) {
- // 获取学生对该知识点的掌握度
- $mastery = $this->getStudentKpMastery($studentId, $kpCode);
- // 薄弱点权重更高
- if (in_array($kpCode, $weaknessFilter)) {
- $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
- } else {
- // 掌握度越低,权重越高
- $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
- }
- } else {
- $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
- }
- }
- // 3. 按权重分配题目数量
- $totalWeight = array_sum($kpWeights);
- $selectedQuestions = [];
- foreach ($questionsByKp as $kpCode => $kpQuestions) {
- // 计算该知识点应该选择的题目数
- $kpQuestionCount = max(1, round(($totalQuestions * $kpWeights[$kpCode]) / $totalWeight));
- // 打乱题目顺序(避免固定模式)
- shuffle($kpQuestions);
- // 选择题目
- $selectedFromKp = array_slice($kpQuestions, 0, $kpQuestionCount);
- $selectedQuestions = array_merge($selectedQuestions, $selectedFromKp);
- }
- // 4. 如果题目过多,按权重排序后截取
- if (count($selectedQuestions) > $totalQuestions) {
- usort($selectedQuestions, function ($a, $b) use ($kpWeights) {
- $weightA = $kpWeights[$a['kp_code']] ?? 1.0;
- $weightB = $kpWeights[$b['kp_code']] ?? 1.0;
- return $weightB <=> $weightA;
- });
- $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
- }
- // 5. 按题型和难度进行微调
- return $this->adjustQuestionsByRatio($selectedQuestions, $questionTypeRatio, $difficultyRatio);
- }
- /**
- * 获取学生对特定知识点的掌握度
- */
- private function getStudentKpMastery(string $studentId, string $kpCode): float
- {
- try {
- $mastery = DB::table('student_mastery')
- ->where('student_id', $studentId)
- ->where('kp', $kpCode)
- ->value('mastery');
- return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
- } catch (\Exception $e) {
- Log::error('Get Student Kp Mastery Error', [
- 'student_id' => $studentId,
- 'kp_code' => $kpCode,
- 'error' => $e->getMessage()
- ]);
- return 0.5;
- }
- }
- /**
- * 根据题型和难度配比调整题目
- */
- private function adjustQuestionsByRatio(array $questions, array $typeRatio, array $difficultyRatio): array
- {
- // 这里可以实现更精细的调整逻辑
- // 目前先返回原始题目,后续可以基于question_type和difficulty字段进行调整
- return $questions;
- }
-
- /**
- * 提交手动评分结果到 LearningAnalytics
- *
- * @param array $data 包含 student_id, paper_id, grades 的数组
- * @return array
- */
- public function submitManualGrading(array $data): array
- {
- try {
- $response = Http::timeout($this->timeout)
- ->post($this->baseUrl . '/api/ocr/analyze', [
- 'student_id' => $data['student_id'],
- 'paper_id' => $data['paper_id'],
- 'answers' => $data['grades'],
- ]);
- if ($response->successful()) {
- Log::info('Manual grading submitted successfully', [
- 'student_id' => $data['student_id'],
- 'paper_id' => $data['paper_id'],
- 'question_count' => count($data['grades'])
- ]);
-
- return $response->json();
- }
- Log::error('Submit Manual Grading Error', [
- 'data' => $data,
- 'status' => $response->status(),
- 'response' => $response->body()
- ]);
- return [
- 'error' => true,
- 'message' => 'Failed to submit manual grading'
- ];
- } catch (\Exception $e) {
- Log::error('Submit Manual Grading Exception', [
- 'error' => $e->getMessage(),
- 'data' => $data
- ]);
- return [
- 'error' => true,
- 'message' => $e->getMessage()
- ];
- }
- }
- }
|