Finalização de detalhes e pequenas adições em dashboards de alunos e professores

This commit is contained in:
2026-05-18 22:48:27 +01:00
parent c0ade9ef76
commit 7f12f3eb1f
58 changed files with 1347 additions and 1065 deletions

View File

@@ -2,7 +2,7 @@
<application <application
android:label="teachit" android:label="teachit"
android:name="${applicationName}" android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"> android:icon="@mipmap/launcher_icon">
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#F9EEE8</color>
</resources>

BIN
assets/images/epvc.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

BIN
assets/images/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 344 KiB

View File

@@ -431,7 +431,7 @@
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO; ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon;
CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++"; CLANG_CXX_LIBRARY = "libc++";
@@ -488,7 +488,7 @@
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO; ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon;
CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++"; CLANG_CXX_LIBRARY = "libc++";

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 295 B

After

Width:  |  Height:  |  Size: 1019 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 406 B

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 450 B

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 282 B

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 462 B

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 704 B

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 406 B

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 586 B

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 862 B

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 862 B

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 762 B

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -15,7 +15,7 @@ class GamificationService {
try { try {
final userStatsRef = _firestore.collection('users').doc(userId); final userStatsRef = _firestore.collection('users').doc(userId);
final userStatsDoc = await userStatsRef.get(); final userStatsDoc = await userStatsRef.get();
if (!userStatsDoc.exists) { if (!userStatsDoc.exists) {
// Criar estatísticas iniciais // Criar estatísticas iniciais
await userStatsRef.set({ await userStatsRef.set({
@@ -35,14 +35,14 @@ class GamificationService {
final userStats = UserStats.fromFirestore(userStatsDoc.data()!, userId); final userStats = UserStats.fromFirestore(userStatsDoc.data()!, userId);
final now = DateTime.now(); final now = DateTime.now();
final lastActivity = userStats.lastActivityDate; final lastActivity = userStats.lastActivityDate;
int newStreak = userStats.currentStreak; int newStreak = userStats.currentStreak;
int newLongestStreak = userStats.longestStreak; int newLongestStreak = userStats.longestStreak;
Logger.info('=== UPDATE DAILY STREAK DEBUG ==='); Logger.info('=== UPDATE DAILY STREAK DEBUG ===');
Logger.info('Last activity: $lastActivity'); Logger.info('Last activity: $lastActivity');
Logger.info('Current streak before update: $newStreak'); Logger.info('Current streak before update: $newStreak');
if (lastActivity == null) { if (lastActivity == null) {
// Primeira atividade - iniciar streak // Primeira atividade - iniciar streak
Logger.info('First activity detected - setting streak to 1'); Logger.info('First activity detected - setting streak to 1');
@@ -51,7 +51,11 @@ class GamificationService {
} else { } else {
// Normalizar para início do dia para comparação correta // Normalizar para início do dia para comparação correta
final today = DateTime(now.year, now.month, now.day); final today = DateTime(now.year, now.month, now.day);
final lastDay = DateTime(lastActivity.year, lastActivity.month, lastActivity.day); final lastDay = DateTime(
lastActivity.year,
lastActivity.month,
lastActivity.day,
);
final difference = today.difference(lastDay).inDays; final difference = today.difference(lastDay).inDays;
if (difference == 0) { if (difference == 0) {
@@ -68,20 +72,22 @@ class GamificationService {
}); });
} else { } else {
Logger.info('Already active today, streak unchanged: $newStreak'); Logger.info('Already active today, streak unchanged: $newStreak');
await userStatsRef.update({ await userStatsRef.update({'lastActivityDate': Timestamp.now()});
'lastActivityDate': Timestamp.now(),
});
} }
return; return;
} else if (difference == 1) { } else if (difference == 1) {
Logger.info('Consecutive activity detected, incrementing streak'); Logger.info('Consecutive activity detected, incrementing streak');
// Atividade consecutiva // Atividade consecutiva
newStreak++; newStreak++;
newLongestStreak = newStreak > newLongestStreak ? newStreak : newLongestStreak; newLongestStreak = newStreak > newLongestStreak
? newStreak
: newLongestStreak;
} else { } else {
// Quebrou o streak // Quebrou o streak
newStreak = 1; newStreak = 1;
newLongestStreak = newStreak > newLongestStreak ? newStreak : newLongestStreak; newLongestStreak = newStreak > newLongestStreak
? newStreak
: newLongestStreak;
} }
} }
@@ -128,39 +134,46 @@ class GamificationService {
} }
/// Registrar atividade de quiz /// Registrar atividade de quiz
static Future<void> recordQuizActivity(String userId, { static Future<void> recordQuizActivity(
String userId, {
required int score, required int score,
required int totalQuestions, required int totalQuestions,
required String materialName, required String materialName,
}) async { }) async {
try { try {
final userStatsRef = _firestore.collection('users').doc(userId); final userStatsRef = _firestore.collection('users').doc(userId);
// Atualizar streak // Atualizar streak
await updateDailyStreak(userId); await updateDailyStreak(userId);
// Registrar tempo de estudo (estimado) // Tempo de estudo agora é calculado em tempo real no quiz sheet
await recordStudyTime(userId, 15); // 15 minutos por quiz // Não adicionamos tempo fixo aqui
// Verificar conquistas de quiz // Verificar conquistas de quiz
await _checkQuizAchievements(userId, score, totalQuestions); await _checkQuizAchievements(userId, score, totalQuestions);
// Incrementar contador de quizzes completos // Incrementar contador de quizzes completos
await userStatsRef.update({ await userStatsRef.update({'completedQuizzes': FieldValue.increment(1)});
'completedQuizzes': FieldValue.increment(1),
});
Logger.info('Incremented completed quizzes count'); Logger.info('Incremented completed quizzes count');
// Atualizar conceitos dominados se score >= 50% // Atualizar conceitos dominados se score >= 50%
Logger.info('Checking if score qualifies for mastered concept: ${score / totalQuestions >= 0.5}'); Logger.info(
'Checking if score qualifies for mastered concept: ${score / totalQuestions >= 0.5}',
);
if (score / totalQuestions >= 0.5) { if (score / totalQuestions >= 0.5) {
Logger.info('Adding mastered concept: $materialName with score: $score'); Logger.info(
'Adding mastered concept: $materialName with score: $score',
);
await _addMasteredConcept(userId, materialName, score); await _addMasteredConcept(userId, materialName, score);
} else { } else {
Logger.info('Score too low for mastered concept: $score/$totalQuestions'); Logger.info(
'Score too low for mastered concept: $score/$totalQuestions',
);
} }
Logger.info('Quiz activity recorded for user $userId: $score/$totalQuestions'); Logger.info(
'Quiz activity recorded for user $userId: $score/$totalQuestions',
);
} catch (e) { } catch (e) {
Logger.error('Error recording quiz activity: $e'); Logger.error('Error recording quiz activity: $e');
} }
@@ -170,15 +183,17 @@ class GamificationService {
static Future<UserStats?> getUserStats(String userId) async { static Future<UserStats?> getUserStats(String userId) async {
try { try {
final doc = await _firestore.collection('users').doc(userId).get(); final doc = await _firestore.collection('users').doc(userId).get();
if (!doc.exists) { if (!doc.exists) {
// Criar estatísticas iniciais se não existirem // Criar estatísticas iniciais se não existirem
await _initializeUserStats(userId); await _initializeUserStats(userId);
return await getUserStats(userId); // Chamada recursiva após inicialização return await getUserStats(
userId,
); // Chamada recursiva após inicialização
} }
final data = doc.data() as Map<String, dynamic>; final data = doc.data() as Map<String, dynamic>;
// Garantir que completedQuizzes exista // Garantir que completedQuizzes exista
if (!data.containsKey('completedQuizzes')) { if (!data.containsKey('completedQuizzes')) {
await _firestore.collection('users').doc(userId).update({ await _firestore.collection('users').doc(userId).update({
@@ -186,7 +201,7 @@ class GamificationService {
}); });
data['completedQuizzes'] = 0; data['completedQuizzes'] = 0;
} }
return UserStats.fromFirestore(data, userId); return UserStats.fromFirestore(data, userId);
} catch (e) { } catch (e) {
Logger.error('Error getting user stats: $e'); Logger.error('Error getting user stats: $e');
@@ -195,26 +210,32 @@ class GamificationService {
} }
/// Obter estatísticas da turma /// Obter estatísticas da turma
static Future<ClassStats?> getClassStats(String classId, {bool forceRefresh = false}) async { static Future<ClassStats?> getClassStats(
String classId, {
bool forceRefresh = false,
}) async {
try { try {
if (forceRefresh) { if (forceRefresh) {
// Forçar recálculo completo // Forçar recálculo completo
return await _calculateClassStats(classId); return await _calculateClassStats(classId);
} }
final classStatsDoc = await _firestore.collection('classStats').doc(classId).get(); final classStatsDoc = await _firestore
.collection('classStats')
.doc(classId)
.get();
if (!classStatsDoc.exists) { if (!classStatsDoc.exists) {
return await _calculateClassStats(classId); return await _calculateClassStats(classId);
} }
// Verificar se os dados estão desatualizados (mais de 1 hora) // Verificar se os dados estão desatualizados (mais de 1 hora)
final data = classStatsDoc.data()!; final data = classStatsDoc.data()!;
final lastUpdated = data['lastUpdated'] as Timestamp?; final lastUpdated = data['lastUpdated'] as Timestamp?;
if (lastUpdated == null || if (lastUpdated == null ||
DateTime.now().difference(lastUpdated.toDate()).inHours > 1) { DateTime.now().difference(lastUpdated.toDate()).inHours > 1) {
return await _calculateClassStats(classId); return await _calculateClassStats(classId);
} }
return ClassStats.fromFirestore(data, classId); return ClassStats.fromFirestore(data, classId);
} catch (e) { } catch (e) {
Logger.error('Error getting class stats: $e'); Logger.error('Error getting class stats: $e');
@@ -229,11 +250,11 @@ class GamificationService {
.collection('classes') .collection('classes')
.where('teacherId', isEqualTo: teacherId) .where('teacherId', isEqualTo: teacherId)
.get(); .get();
for (final classDoc in classesSnapshot.docs) { for (final classDoc in classesSnapshot.docs) {
await _calculateClassStats(classDoc.id); await _calculateClassStats(classDoc.id);
} }
Logger.info('Refreshed stats for ${classesSnapshot.docs.length} classes'); Logger.info('Refreshed stats for ${classesSnapshot.docs.length} classes');
} catch (e) { } catch (e) {
Logger.error('Error refreshing class stats: $e'); Logger.error('Error refreshing class stats: $e');
@@ -254,7 +275,9 @@ class GamificationService {
return []; return [];
} }
final studentIds = enrollmentsSnapshot.docs.map((doc) => doc['studentId'] as String).toList(); final studentIds = enrollmentsSnapshot.docs
.map((doc) => doc['studentId'] as String)
.toList();
final rankings = <StudentRanking>[]; final rankings = <StudentRanking>[];
// Obter número real de quizzes disponíveis na turma // Obter número real de quizzes disponíveis na turma
@@ -270,50 +293,71 @@ class GamificationService {
final userStats = await getUserStats(studentId); final userStats = await getUserStats(studentId);
if (userStats != null) { if (userStats != null) {
// Obter informações do usuário // Obter informações do usuário
final userDoc = await _firestore.collection('users').doc(studentId).get(); final userDoc = await _firestore
.collection('users')
.doc(studentId)
.get();
final userData = userDoc.data() as Map<String, dynamic>?; final userData = userDoc.data() as Map<String, dynamic>?;
// Calcular estatísticas para o ranking // Calcular estatísticas para o ranking
final completedQuizzes = userStats.completedQuizzes; final completedQuizzes = userStats.completedQuizzes;
final totalQuizzes = totalAvailableQuizzes > 0 ? totalAvailableQuizzes : 1; final totalQuizzes = totalAvailableQuizzes > 0
? totalAvailableQuizzes
: 1;
final quizCompletionRate = completedQuizzes / totalQuizzes; final quizCompletionRate = completedQuizzes / totalQuizzes;
Logger.info('=== RANKING SCORE DEBUG ==='); Logger.info('=== RANKING SCORE DEBUG ===');
Logger.info('Student ID: $studentId'); Logger.info('Student ID: $studentId');
Logger.info('Completed quizzes: $completedQuizzes'); Logger.info('Completed quizzes: $completedQuizzes');
Logger.info('Total quizzes: $totalQuizzes'); Logger.info('Total quizzes: $totalQuizzes');
Logger.info('Quiz completion rate: $quizCompletionRate (${(quizCompletionRate * 100).toInt()}%)'); Logger.info(
'Quiz completion rate: $quizCompletionRate (${(quizCompletionRate * 100).toInt()}%)',
);
Logger.info('Current streak: ${userStats.currentStreak}'); Logger.info('Current streak: ${userStats.currentStreak}');
Logger.info('Total study time: ${userStats.totalStudyTime} minutes'); Logger.info(
Logger.info('Mastered concepts: ${userStats.masteredConcepts.length}'); 'Total study time: ${userStats.totalStudyTime} minutes',
Logger.info('Unlocked achievements: ${userStats.unlockedAchievements.length}'); );
Logger.info(
'Mastered concepts: ${userStats.masteredConcepts.length}',
);
Logger.info(
'Unlocked achievements: ${userStats.unlockedAchievements.length}',
);
// Calcular score geral baseado em múltiplos fatores // Calcular score geral baseado em múltiplos fatores
final overallScore = _calculateOverallScore(userStats, quizCompletionRate); final overallScore = _calculateOverallScore(
userStats,
Logger.info('Overall score calculated: $overallScore (${overallScore.toInt()}%)'); quizCompletionRate,
);
Logger.info(
'Overall score calculated: $overallScore (${overallScore.toInt()}%)',
);
Logger.info('=== END RANKING SCORE DEBUG ==='); Logger.info('=== END RANKING SCORE DEBUG ===');
// Tentar obter um nome melhor para o aluno // Tentar obter um nome melhor para o aluno
String studentName = 'Aluno $studentId'; String studentName = 'Aluno $studentId';
if (userData != null) { if (userData != null) {
studentName = userData['displayName'] ?? studentName =
userData['email']?.split('@')[0] ?? userData['displayName'] ??
'Aluno ${studentId.substring(0, 8)}...'; userData['email']?.split('@')[0] ??
'Aluno ${studentId.substring(0, 8)}...';
} }
rankings.add(StudentRanking( rankings.add(
studentId: studentId, StudentRanking(
studentName: studentName, studentId: studentId,
studentEmail: userData?['email'] ?? '', studentName: studentName,
overallScore: overallScore, studentEmail: userData?['email'] ?? '',
completedQuizzes: completedQuizzes, overallScore: overallScore,
totalQuizzes: totalQuizzes, completedQuizzes: completedQuizzes,
quizCompletionRate: quizCompletionRate, totalQuizzes: totalQuizzes,
currentStreak: userStats.currentStreak, quizCompletionRate: quizCompletionRate,
studyTimeMinutes: userStats.totalStudyTime, currentStreak: userStats.currentStreak,
lastActivity: userStats.lastActivityDate ?? DateTime.now(), studyTimeMinutes: userStats.totalStudyTime,
)); lastActivity: userStats.lastActivityDate ?? DateTime.now(),
),
);
} }
} catch (e) { } catch (e) {
Logger.error('Error getting stats for student $studentId: $e'); Logger.error('Error getting stats for student $studentId: $e');
@@ -323,7 +367,7 @@ class GamificationService {
// Ordenar por score geral // Ordenar por score geral
rankings.sort((a, b) => b.overallScore.compareTo(a.overallScore)); rankings.sort((a, b) => b.overallScore.compareTo(a.overallScore));
return rankings; return rankings;
} catch (e) { } catch (e) {
Logger.error('Error getting class ranking: $e'); Logger.error('Error getting class ranking: $e');
@@ -332,27 +376,33 @@ class GamificationService {
} }
/// Calcular score geral para ranking /// Calcular score geral para ranking
static double _calculateOverallScore(UserStats userStats, double quizCompletionRate) { static double _calculateOverallScore(
UserStats userStats,
double quizCompletionRate,
) {
// Se completou 100% dos quizzes, score é 100% // Se completou 100% dos quizzes, score é 100%
if (quizCompletionRate >= 1.0) { if (quizCompletionRate >= 1.0) {
return 100.0; return 100.0;
} }
// Para completion < 100%, calcular proporcionalmente // Para completion < 100%, calcular proporcionalmente
double baseScore = quizCompletionRate * 90; // 90% baseado em completion double baseScore = quizCompletionRate * 90; // 90% baseado em completion
// Bônus adicionais (máximo 10% extra) // Bônus adicionais (máximo 10% extra)
double bonusScore = 0.0; double bonusScore = 0.0;
// 5% para conceitos dominados // 5% para conceitos dominados
bonusScore += (userStats.masteredConcepts.length / 5.0 * 5).clamp(0.0, 5.0); bonusScore += (userStats.masteredConcepts.length / 5.0 * 5).clamp(0.0, 5.0);
// 3% para streak // 3% para streak
bonusScore += (userStats.currentStreak / 7.0 * 3).clamp(0.0, 3.0); bonusScore += (userStats.currentStreak / 7.0 * 3).clamp(0.0, 3.0);
// 2% para conquistas // 2% para conquistas
bonusScore += (userStats.unlockedAchievements.length / 10.0 * 2).clamp(0.0, 2.0); bonusScore += (userStats.unlockedAchievements.length / 10.0 * 2).clamp(
0.0,
2.0,
);
final totalScore = baseScore + bonusScore; final totalScore = baseScore + bonusScore;
return totalScore.clamp(0.0, 100.0); return totalScore.clamp(0.0, 100.0);
} }
@@ -391,14 +441,20 @@ class GamificationService {
} }
/// Obter conquistas disponíveis /// Obter conquistas disponíveis
static Future<List<Achievement>> getAvailableAchievements({String? teacherId}) async { static Future<List<Achievement>> getAvailableAchievements({
String? teacherId,
}) async {
try { try {
// Sempre incluir conquistas do sistema // Sempre incluir conquistas do sistema
List<Achievement> achievements = List.from(SystemAchievements.defaultAchievements); List<Achievement> achievements = List.from(
SystemAchievements.defaultAchievements,
);
// Adicionar conquistas personalizadas do professor // Adicionar conquistas personalizadas do professor
Query query = _firestore.collection('achievements').where('isActive', isEqualTo: true); Query query = _firestore
.collection('achievements')
.where('isActive', isEqualTo: true);
if (teacherId != null) { if (teacherId != null) {
query = query.where('createdBy', isEqualTo: teacherId); query = query.where('createdBy', isEqualTo: teacherId);
} }
@@ -406,10 +462,15 @@ class GamificationService {
final snapshot = await query.get(); final snapshot = await query.get();
achievements.addAll( achievements.addAll(
snapshot.docs snapshot.docs
.map((doc) => Achievement.fromFirestore(doc.data() as Map<String, dynamic>, doc.id)) .map(
(doc) => Achievement.fromFirestore(
doc.data() as Map<String, dynamic>,
doc.id,
),
)
.toList(), .toList(),
); );
Logger.info('Total achievements loaded: ${achievements.length}'); Logger.info('Total achievements loaded: ${achievements.length}');
return achievements; return achievements;
} catch (e) { } catch (e) {
@@ -418,7 +479,6 @@ class GamificationService {
} }
} }
/// Métodos privados /// Métodos privados
static Future<void> _createInitialUserStats(String userId) async { static Future<void> _createInitialUserStats(String userId) async {
@@ -427,7 +487,8 @@ class GamificationService {
'currentStreak': 0, 'currentStreak': 0,
'longestStreak': 0, 'longestStreak': 0,
'totalStudyTime': 0, 'totalStudyTime': 0,
'lastActivityDate': null, // null para que primeira atividade inicie streak 'lastActivityDate':
null, // null para que primeira atividade inicie streak
'weeklyStudyTime': 0, 'weeklyStudyTime': 0,
'monthlyStudyTime': 0, 'monthlyStudyTime': 0,
'masteredConcepts': [], 'masteredConcepts': [],
@@ -435,15 +496,19 @@ class GamificationService {
}); });
} }
static Future<void> _addMasteredConcept(String userId, String conceptName, int score) async { static Future<void> _addMasteredConcept(
String userId,
String conceptName,
int score,
) async {
try { try {
final userStatsRef = _firestore.collection('users').doc(userId); final userStatsRef = _firestore.collection('users').doc(userId);
final userStatsDoc = await userStatsRef.get(); final userStatsDoc = await userStatsRef.get();
if (!userStatsDoc.exists) return; if (!userStatsDoc.exists) return;
final userStats = UserStats.fromFirestore(userStatsDoc.data()!, userId); final userStats = UserStats.fromFirestore(userStatsDoc.data()!, userId);
// Verificar se conceito já está dominado // Verificar se conceito já está dominado
final existingConcept = userStats.masteredConcepts final existingConcept = userStats.masteredConcepts
.where((c) => c.conceptName == conceptName) .where((c) => c.conceptName == conceptName)
@@ -464,7 +529,9 @@ class GamificationService {
}).toList(); }).toList();
await userStatsRef.update({ await userStatsRef.update({
'masteredConcepts': updatedConcepts.map((c) => c.toFirestore()).toList(), 'masteredConcepts': updatedConcepts
.map((c) => c.toFirestore())
.toList(),
}); });
} }
} else { } else {
@@ -487,7 +554,10 @@ class GamificationService {
static Future<ClassStats> _calculateClassStats(String classId) async { static Future<ClassStats> _calculateClassStats(String classId) async {
try { try {
// Obter informações da turma // Obter informações da turma
final classDoc = await _firestore.collection('classes').doc(classId).get(); final classDoc = await _firestore
.collection('classes')
.doc(classId)
.get();
if (!classDoc.exists) { if (!classDoc.exists) {
throw Exception('Class not found'); throw Exception('Class not found');
} }
@@ -501,7 +571,9 @@ class GamificationService {
.where('classId', isEqualTo: classId) .where('classId', isEqualTo: classId)
.get(); .get();
final studentIds = enrollmentsSnapshot.docs.map((doc) => doc.data()['studentId'] as String).toList(); final studentIds = enrollmentsSnapshot.docs
.map((doc) => doc.data()['studentId'] as String)
.toList();
// Calcular estatísticas // Calcular estatísticas
int activeStudents = 0; int activeStudents = 0;
@@ -510,13 +582,15 @@ class GamificationService {
for (final studentId in studentIds) { for (final studentId in studentIds) {
final userStats = await getUserStats(studentId); final userStats = await getUserStats(studentId);
// Verificar se está ativo (atividade nos últimos 30 dias - mais realista) // Verificar se está ativo (atividade nos últimos 30 dias - mais realista)
int daysSinceLastActivity = 999; // Valor alto para inatividade int daysSinceLastActivity = 999; // Valor alto para inatividade
bool hasStats = userStats != null; bool hasStats = userStats != null;
if (hasStats && userStats!.lastActivityDate != null) { if (hasStats && userStats!.lastActivityDate != null) {
daysSinceLastActivity = DateTime.now().difference(userStats.lastActivityDate!).inDays; daysSinceLastActivity = DateTime.now()
.difference(userStats.lastActivityDate!)
.inDays;
if (daysSinceLastActivity <= 30) { if (daysSinceLastActivity <= 30) {
activeStudents++; activeStudents++;
} }
@@ -527,59 +601,78 @@ class GamificationService {
if (hasStats) { if (hasStats) {
final completedQuizzes = userStats!.completedQuizzes; final completedQuizzes = userStats!.completedQuizzes;
final masteredConcepts = userStats.masteredConcepts.length; final masteredConcepts = userStats.masteredConcepts.length;
Logger.info('=== PROGRESS CALCULATION DEBUG ==='); Logger.info('=== PROGRESS CALCULATION DEBUG ===');
Logger.info('Student ID: $studentId'); Logger.info('Student ID: $studentId');
Logger.info('Completed quizzes: $completedQuizzes'); Logger.info('Completed quizzes: $completedQuizzes');
Logger.info('Mastered concepts: $masteredConcepts'); Logger.info('Mastered concepts: $masteredConcepts');
// Progresso mais representativo: 60% quizzes + 40% conceitos // Progresso mais representativo: 60% quizzes + 40% conceitos
// Primeiro quiz já dá 30% de progresso (incentivo inicial) // Primeiro quiz já dá 30% de progresso (incentivo inicial)
final quizProgress = completedQuizzes > 0 ? final quizProgress = completedQuizzes > 0
(0.3 + (completedQuizzes - 1) * 0.15).clamp(0.0, 0.6) : 0.0; ? (0.3 + (completedQuizzes - 1) * 0.15).clamp(0.0, 0.6)
: 0.0;
// Primeiro conceito já dá 15% de progresso // Primeiro conceito já dá 15% de progresso
final conceptProgress = (masteredConcepts * 0.15).clamp(0.0, 0.4); final conceptProgress = (masteredConcepts * 0.15).clamp(0.0, 0.4);
progress = quizProgress + conceptProgress; progress = quizProgress + conceptProgress;
Logger.info('Quiz progress: $quizProgress (${(quizProgress * 100).toInt()}%)'); Logger.info(
Logger.info('Concept progress: $conceptProgress (${(conceptProgress * 100).toInt()}%)'); 'Quiz progress: $quizProgress (${(quizProgress * 100).toInt()}%)',
Logger.info('Total progress: $progress (${(progress * 100).toInt()}%)'); );
Logger.info(
'Concept progress: $conceptProgress (${(conceptProgress * 100).toInt()}%)',
);
Logger.info(
'Total progress: $progress (${(progress * 100).toInt()}%)',
);
Logger.info('=== END PROGRESS CALCULATION DEBUG ==='); Logger.info('=== END PROGRESS CALCULATION DEBUG ===');
} else { } else {
Logger.info('Student $studentId has no stats - progress = 0.0'); Logger.info('Student $studentId has no stats - progress = 0.0');
} }
totalProgress += progress; totalProgress += progress;
// Verificar se precisa de apoio (ajustado para nova fórmula) // Verificar se precisa de apoio (ajustado para nova fórmula)
if (progress < 0.25 || daysSinceLastActivity > 30) { if (progress < 0.25 || daysSinceLastActivity > 30) {
final userDoc = await _firestore.collection('users').doc(studentId).get(); final userDoc = await _firestore
.collection('users')
.doc(studentId)
.get();
final userData = userDoc.data(); final userData = userDoc.data();
// Tentar obter um nome melhor para o aluno // Tentar obter um nome melhor para o aluno
String studentName = 'Aluno ${studentId.substring(0, 8)}...'; String studentName = 'Aluno ${studentId.substring(0, 8)}...';
if (userData != null) { if (userData != null) {
studentName = userData['displayName'] ?? studentName =
userData['email']?.split('@')[0] ?? userData['displayName'] ??
'Aluno ${studentId.substring(0, 8)}...'; userData['email']?.split('@')[0] ??
'Aluno ${studentId.substring(0, 8)}...';
} }
needingSupport.add(StudentNeedingSupport( needingSupport.add(
studentId: studentId, StudentNeedingSupport(
studentName: studentName, studentId: studentId,
reason: progress < 0.3 ? 'low_scores' : 'inactivity', studentName: studentName,
lastActivity: hasStats ? userStats!.lastActivityDate ?? DateTime.now() : DateTime.now().subtract(const Duration(days: 45)), reason: progress < 0.3 ? 'low_scores' : 'inactivity',
averageScore: progress * 100, lastActivity: hasStats
)); ? userStats!.lastActivityDate ?? DateTime.now()
: DateTime.now().subtract(const Duration(days: 45)),
averageScore: progress * 100,
),
);
} }
} }
final averageProgress = studentIds.isEmpty ? 0.0 : totalProgress / studentIds.length; final averageProgress = studentIds.isEmpty
? 0.0
: totalProgress / studentIds.length;
Logger.info('=== AVERAGE PROGRESS DEBUG ==='); Logger.info('=== AVERAGE PROGRESS DEBUG ===');
Logger.info('Total students: ${studentIds.length}'); Logger.info('Total students: ${studentIds.length}');
Logger.info('Total progress sum: $totalProgress'); Logger.info('Total progress sum: $totalProgress');
Logger.info('Average progress: $averageProgress (${(averageProgress * 100).toInt()}%)'); Logger.info(
'Average progress: $averageProgress (${(averageProgress * 100).toInt()}%)',
);
Logger.info('=== END AVERAGE PROGRESS DEBUG ==='); Logger.info('=== END AVERAGE PROGRESS DEBUG ===');
// Obter estatísticas de quizzes e conteúdos // Obter estatísticas de quizzes e conteúdos
@@ -618,7 +711,10 @@ class GamificationService {
// Limpar cache primeiro e depois salvar estatísticas calculadas // Limpar cache primeiro e depois salvar estatísticas calculadas
await _firestore.collection('classStats').doc(classId).delete(); await _firestore.collection('classStats').doc(classId).delete();
await _firestore.collection('classStats').doc(classId).set(classStats.toFirestore()); await _firestore
.collection('classStats')
.doc(classId)
.set(classStats.toFirestore());
Logger.info('Class stats refreshed and saved for class $classId'); Logger.info('Class stats refreshed and saved for class $classId');
return classStats; return classStats;
@@ -628,9 +724,14 @@ class GamificationService {
} }
} }
static Future<void> _checkStreakAchievements(String userId, int streakDays) async { static Future<void> _checkStreakAchievements(
String userId,
int streakDays,
) async {
final achievements = await getAvailableAchievements(); final achievements = await getAvailableAchievements();
final streakAchievements = achievements.where((a) => a.category == 'streak'); final streakAchievements = achievements.where(
(a) => a.category == 'streak',
);
for (final achievement in streakAchievements) { for (final achievement in streakAchievements) {
if (achievement.requirements.checkCondition(streakDays)) { if (achievement.requirements.checkCondition(streakDays)) {
@@ -639,9 +740,14 @@ class GamificationService {
} }
} }
static Future<void> _checkStudyTimeAchievements(String userId, int totalMinutes) async { static Future<void> _checkStudyTimeAchievements(
String userId,
int totalMinutes,
) async {
final achievements = await getAvailableAchievements(); final achievements = await getAvailableAchievements();
final studyAchievements = achievements.where((a) => a.category == 'study_time'); final studyAchievements = achievements.where(
(a) => a.category == 'study_time',
);
for (final achievement in studyAchievements) { for (final achievement in studyAchievements) {
if (achievement.requirements.checkCondition(totalMinutes)) { if (achievement.requirements.checkCondition(totalMinutes)) {
@@ -650,13 +756,17 @@ class GamificationService {
} }
} }
static Future<void> _checkQuizAchievements(String userId, int score, int totalQuestions) async { static Future<void> _checkQuizAchievements(
String userId,
int score,
int totalQuestions,
) async {
Logger.info('=== CHECKING QUIZ ACHIEVEMENTS ==='); Logger.info('=== CHECKING QUIZ ACHIEVEMENTS ===');
Logger.info('Score: $score/$totalQuestions'); Logger.info('Score: $score/$totalQuestions');
final achievements = await getAvailableAchievements(); final achievements = await getAvailableAchievements();
final userStats = await getUserStats(userId); final userStats = await getUserStats(userId);
if (userStats == null) { if (userStats == null) {
Logger.error('User stats null for achievement checking'); Logger.error('User stats null for achievement checking');
return; return;
@@ -665,41 +775,51 @@ class GamificationService {
final percentage = (score / totalQuestions) * 100; final percentage = (score / totalQuestions) * 100;
// Usar contador real de quizzes completos // Usar contador real de quizzes completos
final completedQuizzes = userStats.completedQuizzes; final completedQuizzes = userStats.completedQuizzes;
Logger.info('Percentage: $percentage%'); Logger.info('Percentage: $percentage%');
Logger.info('Completed quizzes: $completedQuizzes'); Logger.info('Completed quizzes: $completedQuizzes');
Logger.info('Mastered concepts: ${userStats.masteredConcepts.length}'); Logger.info('Mastered concepts: ${userStats.masteredConcepts.length}');
Logger.info('Available achievements: ${achievements.length}'); Logger.info('Available achievements: ${achievements.length}');
for (final achievement in achievements) { for (final achievement in achievements) {
if (achievement.category == 'quiz' && achievement.requirements.type == 'quiz_score' && if (achievement.category == 'quiz' &&
achievement.requirements.type == 'quiz_score' &&
achievement.requirements.checkCondition(percentage)) { achievement.requirements.checkCondition(percentage)) {
await _unlockAchievement(userId, achievement.id); await _unlockAchievement(userId, achievement.id);
} else if (achievement.category == 'quiz_count' && achievement.requirements.type == 'quiz_completion' && } else if (achievement.category == 'quiz_count' &&
achievement.requirements.checkCondition(completedQuizzes)) { achievement.requirements.type == 'quiz_completion' &&
achievement.requirements.checkCondition(completedQuizzes)) {
await _unlockAchievement(userId, achievement.id); await _unlockAchievement(userId, achievement.id);
} else if (achievement.category == 'quiz' && achievement.requirements.type == 'quiz_completion' && } else if (achievement.category == 'quiz' &&
achievement.id == 'first_quiz' && achievement.requirements.type == 'quiz_completion' &&
achievement.requirements.checkCondition(1)) { achievement.id == 'first_quiz' &&
achievement.requirements.checkCondition(1)) {
await _unlockAchievement(userId, achievement.id); await _unlockAchievement(userId, achievement.id);
} else if (achievement.category == 'concept' && achievement.requirements.type == 'concepts_mastered' && } else if (achievement.category == 'concept' &&
achievement.requirements.checkCondition(userStats.masteredConcepts.length)) { achievement.requirements.type == 'concepts_mastered' &&
achievement.requirements.checkCondition(
userStats.masteredConcepts.length,
)) {
await _unlockAchievement(userId, achievement.id); await _unlockAchievement(userId, achievement.id);
} else { } else {
Logger.info('Achievement not matched: ${achievement.id} - category: ${achievement.category}, type: ${achievement.requirements.type}'); Logger.info(
'Achievement not matched: ${achievement.id} - category: ${achievement.category}, type: ${achievement.requirements.type}',
);
} }
} }
Logger.info('=== END CHECKING QUIZ ACHIEVEMENTS ==='); Logger.info('=== END CHECKING QUIZ ACHIEVEMENTS ===');
} }
static Future<void> _unlockAchievement(
static Future<void> _unlockAchievement(String userId, String achievementId) async { String userId,
String achievementId,
) async {
try { try {
Logger.info('=== ATTEMPTING TO UNLOCK ACHIEVEMENT ==='); Logger.info('=== ATTEMPTING TO UNLOCK ACHIEVEMENT ===');
Logger.info('Achievement ID: $achievementId'); Logger.info('Achievement ID: $achievementId');
Logger.info('User ID: $userId'); Logger.info('User ID: $userId');
final userStatsRef = _firestore.collection('users').doc(userId); final userStatsRef = _firestore.collection('users').doc(userId);
final userStatsDoc = await userStatsRef.get(); final userStatsDoc = await userStatsRef.get();
@@ -709,11 +829,14 @@ class GamificationService {
} }
final userStats = UserStats.fromFirestore(userStatsDoc.data()!, userId); final userStats = UserStats.fromFirestore(userStatsDoc.data()!, userId);
Logger.info('Current unlocked achievements count: ${userStats.unlockedAchievements.length}'); Logger.info(
'Current unlocked achievements count: ${userStats.unlockedAchievements.length}',
);
// Verificar se já desbloqueou // Verificar se já desbloqueou
final alreadyUnlocked = userStats.unlockedAchievements final alreadyUnlocked = userStats.unlockedAchievements.any(
.any((a) => a.achievementId == achievementId); (a) => a.achievementId == achievementId,
);
Logger.info('Already unlocked: $alreadyUnlocked'); Logger.info('Already unlocked: $alreadyUnlocked');
@@ -726,12 +849,18 @@ class GamificationService {
Logger.info('Adding achievement to Firestore...'); Logger.info('Adding achievement to Firestore...');
await userStatsRef.update({ await userStatsRef.update({
'unlockedAchievements': FieldValue.arrayUnion([unlockedAchievement.toFirestore()]), 'unlockedAchievements': FieldValue.arrayUnion([
unlockedAchievement.toFirestore(),
]),
}); });
Logger.info('Achievement unlocked successfully: $achievementId for user $userId'); Logger.info(
'Achievement unlocked successfully: $achievementId for user $userId',
);
} else { } else {
Logger.info('Achievement $achievementId already unlocked for user $userId'); Logger.info(
'Achievement $achievementId already unlocked for user $userId',
);
} }
} catch (e) { } catch (e) {
Logger.error('Error unlocking achievement: $e'); Logger.error('Error unlocking achievement: $e');
@@ -742,16 +871,14 @@ class GamificationService {
static Future<void> _initializeUserStats(String userId) async { static Future<void> _initializeUserStats(String userId) async {
try { try {
final userStatsRef = _firestore.collection('users').doc(userId); final userStatsRef = _firestore.collection('users').doc(userId);
// Verificar se já existe // Verificar se já existe
final doc = await userStatsRef.get(); final doc = await userStatsRef.get();
if (doc.exists) { if (doc.exists) {
// Apenas atualizar com completedQuizzes se não existir // Apenas atualizar com completedQuizzes se não existir
final data = doc.data() as Map<String, dynamic>; final data = doc.data() as Map<String, dynamic>;
if (!data.containsKey('completedQuizzes')) { if (!data.containsKey('completedQuizzes')) {
await userStatsRef.update({ await userStatsRef.update({'completedQuizzes': 0});
'completedQuizzes': 0,
});
} }
} else { } else {
// Criar documento inicial // Criar documento inicial
@@ -766,7 +893,7 @@ class GamificationService {
'unlockedAchievements': [], 'unlockedAchievements': [],
}); });
} }
Logger.info('User stats initialized for user $userId'); Logger.info('User stats initialized for user $userId');
} catch (e) { } catch (e) {
Logger.error('Error initializing user stats: $e'); Logger.error('Error initializing user stats: $e');

View File

@@ -23,6 +23,8 @@ class AnalyticsPage extends StatefulWidget {
class _AnalyticsPageState extends State<AnalyticsPage> class _AnalyticsPageState extends State<AnalyticsPage>
with SingleTickerProviderStateMixin { with SingleTickerProviderStateMixin {
late TabController _tabController; late TabController _tabController;
final _classSearchController = TextEditingController();
String _classSearchQuery = '';
List<ClassStats> _classStats = []; List<ClassStats> _classStats = [];
bool _loading = true; bool _loading = true;
String? _selectedClassId; String? _selectedClassId;
@@ -38,6 +40,7 @@ class _AnalyticsPageState extends State<AnalyticsPage>
@override @override
void dispose() { void dispose() {
_tabController.dispose(); _tabController.dispose();
_classSearchController.dispose();
super.dispose(); super.dispose();
} }
@@ -46,7 +49,7 @@ class _AnalyticsPageState extends State<AnalyticsPage>
final user = AuthService.currentUser; final user = AuthService.currentUser;
if (user == null) return; if (user == null) return;
// Obter disciplinas do professor // Obter turmas do professor
final classesSnapshot = await FirebaseFirestore.instance final classesSnapshot = await FirebaseFirestore.instance
.collection('classes') .collection('classes')
.where('teacherId', isEqualTo: user.uid) .where('teacherId', isEqualTo: user.uid)
@@ -85,7 +88,6 @@ class _AnalyticsPageState extends State<AnalyticsPage>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final themeExtras = AppThemeExtras.of(context); final themeExtras = AppThemeExtras.of(context);
final cs = Theme.of(context).colorScheme;
return PopScope( return PopScope(
canPop: false, canPop: false,
@@ -94,9 +96,9 @@ class _AnalyticsPageState extends State<AnalyticsPage>
context.go('/teacher-dashboard'); context.go('/teacher-dashboard');
}, },
child: Scaffold( child: Scaffold(
backgroundColor: cs.surface, backgroundColor: Colors.transparent,
resizeToAvoidBottomInset: false, resizeToAvoidBottomInset: false,
body: Container( body: DecoratedBox(
decoration: BoxDecoration( decoration: BoxDecoration(
gradient: LinearGradient( gradient: LinearGradient(
begin: Alignment.topCenter, begin: Alignment.topCenter,
@@ -106,6 +108,7 @@ class _AnalyticsPageState extends State<AnalyticsPage>
), ),
), ),
child: SafeArea( child: SafeArea(
bottom: false,
child: Column( child: Column(
children: [ children: [
// Header // Header
@@ -137,7 +140,7 @@ class _AnalyticsPageState extends State<AnalyticsPage>
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
Text( Text(
'Acompanhe o desempenho das disciplinas', 'Acompanhe o desempenho das turmas',
style: TextStyle( style: TextStyle(
color: Colors.white.withValues(alpha: 0.8), color: Colors.white.withValues(alpha: 0.8),
fontSize: 16, fontSize: 16,
@@ -163,7 +166,7 @@ class _AnalyticsPageState extends State<AnalyticsPage>
indicatorColor: Colors.white, indicatorColor: Colors.white,
indicatorWeight: 2, indicatorWeight: 2,
tabs: const [ tabs: const [
Tab(text: 'Disciplinas'), Tab(text: 'Turmas'),
Tab(text: 'Alunos'), Tab(text: 'Alunos'),
], ],
), ),
@@ -205,7 +208,7 @@ class _AnalyticsPageState extends State<AnalyticsPage>
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
'Nenhuma disciplina encontrada', 'Nenhuma turma encontrada',
style: TextStyle( style: TextStyle(
color: Colors.white.withValues(alpha: 0.7), color: Colors.white.withValues(alpha: 0.7),
fontSize: 18, fontSize: 18,
@@ -213,7 +216,7 @@ class _AnalyticsPageState extends State<AnalyticsPage>
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
'Crie disciplinas para ver as analytics aqui', 'Crie turmas para ver as analytics aqui',
style: TextStyle( style: TextStyle(
color: Colors.white.withValues(alpha: 0.5), color: Colors.white.withValues(alpha: 0.5),
fontSize: 14, fontSize: 14,
@@ -224,47 +227,131 @@ class _AnalyticsPageState extends State<AnalyticsPage>
); );
} }
return SingleChildScrollView( final filtered = _classSearchQuery.isEmpty
padding: const EdgeInsets.all(24), ? _classStats
child: Column( : _classStats
crossAxisAlignment: CrossAxisAlignment.start, .where(
children: [ (s) => s.className.toLowerCase().contains(_classSearchQuery),
// Overview Cards )
Row( .toList();
children: [
Expanded(
child: _buildOverviewCard(
'Total de Alunos',
'${_classStats.fold(0, (sum, stats) => sum + stats.totalStudents)}',
Icons.people,
Colors.blue,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildOverviewCard(
'Alunos Ativos',
'${_classStats.fold(0, (sum, stats) => sum + stats.activeStudents)}',
Icons.trending_up,
Colors.green,
),
),
],
),
const SizedBox(height: 20),
// Class Cards return CustomScrollView(
..._classStats.map( slivers: [
(stats) => Padding( SliverPadding(
padding: const EdgeInsets.only(bottom: 16), padding: const EdgeInsets.fromLTRB(24, 24, 24, 0),
child: ClassAnalyticsCard( sliver: SliverToBoxAdapter(
classStats: stats, child: Column(
onTap: () => _showClassStudents(stats), children: [
// Overview Cards
Center(
child: _buildOverviewCard(
'Total de Alunos',
'${_classStats.fold(0, (sum, s) => sum + s.totalStudents)}',
Icons.people,
Colors.blue,
),
),
const SizedBox(height: 20),
// Search bar
Container(
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 10,
),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.white.withValues(alpha: 0.2),
),
),
child: Row(
children: [
Icon(
Icons.search,
color: Colors.white.withValues(alpha: 0.7),
size: 20,
),
const SizedBox(width: 10),
Expanded(
child: Theme(
data: ThemeData.dark().copyWith(
textSelectionTheme: const TextSelectionThemeData(
cursorColor: Colors.white,
selectionColor: Colors.white24,
selectionHandleColor: Colors.white,
),
),
child: TextField(
controller: _classSearchController,
onChanged: (v) => setState(
() => _classSearchQuery = v.trim().toLowerCase(),
),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
cursorColor: Colors.white,
decoration: InputDecoration(
hintText: 'Pesquisar turma…',
hintStyle: TextStyle(
color: Colors.white.withValues(alpha: 0.5),
fontSize: 14,
),
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.zero,
),
),
),
),
if (_classSearchQuery.isNotEmpty)
GestureDetector(
onTap: () {
_classSearchController.clear();
setState(() => _classSearchQuery = '');
},
child: Icon(
Icons.close,
color: Colors.white.withValues(alpha: 0.7),
size: 18,
),
),
],
),
),
const SizedBox(height: 20),
],
),
),
),
if (filtered.isEmpty)
SliverFillRemaining(
hasScrollBody: false,
child: Center(
child: Text(
'Nenhuma turma encontrada',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.6),
fontSize: 15,
),
),
),
)
else
SliverPadding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ClassAnalyticsCard(
classStats: filtered[index],
onTap: () => _showClassStudents(filtered[index]),
),
childCount: filtered.length,
), ),
), ),
), ),
], ],
),
); );
} }
@@ -281,7 +368,7 @@ class _AnalyticsPageState extends State<AnalyticsPage>
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
'Seleciona uma disciplina', 'Seleciona uma turma',
style: TextStyle( style: TextStyle(
color: Colors.white.withValues(alpha: 0.7), color: Colors.white.withValues(alpha: 0.7),
fontSize: 18, fontSize: 18,
@@ -289,7 +376,7 @@ class _AnalyticsPageState extends State<AnalyticsPage>
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
'Clica numa disciplina no separador "Disciplinas" para ver os alunos', 'Clica numa turma no separador "Turmas" para ver os alunos',
style: TextStyle( style: TextStyle(
color: Colors.white.withValues(alpha: 0.5), color: Colors.white.withValues(alpha: 0.5),
fontSize: 14, fontSize: 14,

View File

@@ -76,7 +76,10 @@ class ClassAnalyticsCard extends StatelessWidget {
), ),
), ),
Container( Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.2), color: Colors.white.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
@@ -84,7 +87,11 @@ class ClassAnalyticsCard extends StatelessWidget {
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
const Icon(Icons.trending_up, color: Colors.white, size: 16), const Icon(
Icons.trending_up,
color: Colors.white,
size: 16,
),
const SizedBox(width: 4), const SizedBox(width: 4),
Text( Text(
'${(classStats.averageProgress * 100).toInt()}%', '${(classStats.averageProgress * 100).toInt()}%',
@@ -190,39 +197,47 @@ class ClassAnalyticsCard extends StatelessWidget {
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
...classStats.studentsNeedingSupport.take(3).map((student) => Padding( ...classStats.studentsNeedingSupport
padding: const EdgeInsets.only(bottom: 4), .take(3)
child: Row( .map(
children: [ (student) => Padding(
Container( padding: const EdgeInsets.only(bottom: 4),
width: 6, child: Row(
height: 6, children: [
decoration: const BoxDecoration( Container(
color: Colors.orange, width: 6,
shape: BoxShape.circle, height: 6,
decoration: const BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
student.studentName,
style: TextStyle(
color: Colors.white.withValues(
alpha: 0.8,
),
fontSize: 11,
),
),
),
Text(
'${student.averageScore.toInt()}%',
style: TextStyle(
color: Colors.white.withValues(
alpha: 0.8,
),
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
],
), ),
), ),
const SizedBox(width: 8), ),
Expanded(
child: Text(
student.studentName,
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 11,
),
),
),
Text(
'${student.averageScore.toInt()}%',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
],
),
)),
if (classStats.studentsNeedingSupport.length > 3) if (classStats.studentsNeedingSupport.length > 3)
Text( Text(
'+${classStats.studentsNeedingSupport.length - 3} alunos', '+${classStats.studentsNeedingSupport.length - 3} alunos',
@@ -242,7 +257,7 @@ class ClassAnalyticsCard extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Text( Text(
'Ver ranking detalhado', 'Ver alunos da turma',
style: TextStyle( style: TextStyle(
color: Colors.white.withValues(alpha: 0.8), color: Colors.white.withValues(alpha: 0.8),
fontSize: 12, fontSize: 12,
@@ -272,7 +287,7 @@ class ClassAnalyticsCard extends StatelessWidget {
bool isWarning = false, bool isWarning = false,
}) { }) {
final cs = Theme.of(context).colorScheme; final cs = Theme.of(context).colorScheme;
return Container( return Container(
padding: const EdgeInsets.all(12), padding: const EdgeInsets.all(12),
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -285,11 +300,7 @@ class ClassAnalyticsCard extends StatelessWidget {
), ),
child: Column( child: Column(
children: [ children: [
Icon( Icon(icon, color: isWarning ? Colors.orange : Colors.white, size: 20),
icon,
color: isWarning ? Colors.orange : Colors.white,
size: 20,
),
const SizedBox(height: 6), const SizedBox(height: 6),
Text( Text(
value, value,

View File

@@ -269,7 +269,7 @@ class _ClassRankingWidgetState extends State<ClassRankingWidget> {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
'Nenhum aluno na disciplina', 'Nenhum aluno na turma',
style: TextStyle( style: TextStyle(
color: Colors.white.withValues(alpha: 0.7), color: Colors.white.withValues(alpha: 0.7),
fontSize: 18, fontSize: 18,

View File

@@ -3,8 +3,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
/// Inline widget (no Scaffold) showing enrolled students for a class,
/// with search, real-time updates, and remove-student functionality.
class ClassStudentsInlineWidget extends StatefulWidget { class ClassStudentsInlineWidget extends StatefulWidget {
final String classId; final String classId;
final String className; final String className;
@@ -21,6 +19,7 @@ class ClassStudentsInlineWidget extends StatefulWidget {
} }
class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> { class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
final _searchController = TextEditingController();
String _searchQuery = ''; String _searchQuery = '';
String? _classCode; String? _classCode;
late Stream<QuerySnapshot> _enrollmentsStream; late Stream<QuerySnapshot> _enrollmentsStream;
@@ -32,13 +31,6 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
_initStream(); _initStream();
} }
void _initStream() {
_enrollmentsStream = FirebaseFirestore.instance
.collection('enrollments')
.where('classId', isEqualTo: widget.classId)
.snapshots();
}
@override @override
void didUpdateWidget(ClassStudentsInlineWidget oldWidget) { void didUpdateWidget(ClassStudentsInlineWidget oldWidget) {
super.didUpdateWidget(oldWidget); super.didUpdateWidget(oldWidget);
@@ -48,20 +40,30 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
} }
} }
@override
void dispose() {
_searchController.dispose();
super.dispose();
}
void _initStream() {
_enrollmentsStream = FirebaseFirestore.instance
.collection('enrollments')
.where('classId', isEqualTo: widget.classId)
.snapshots();
}
Future<void> _loadClassCode() async { Future<void> _loadClassCode() async {
final doc = await FirebaseFirestore.instance final doc = await FirebaseFirestore.instance
.collection('classes') .collection('classes')
.doc(widget.classId) .doc(widget.classId)
.get(); .get();
if (mounted) { if (mounted) {
setState(() { setState(() => _classCode = doc.data()?['code'] as String? ?? '');
_classCode = doc.data()?['code'] as String? ?? '';
});
} }
} }
Future<void> _removeStudent( Future<void> _confirmRemove(
BuildContext context,
String enrollmentDocId, String enrollmentDocId,
String studentName, String studentName,
) async { ) async {
@@ -72,7 +74,7 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
title: const Text('Remover aluno'), title: const Text('Remover aluno'),
content: Text( content: Text(
'Tens a certeza que queres remover "$studentName" desta disciplina?', 'Tens a certeza que queres remover "$studentName" desta turma?',
), ),
actions: [ actions: [
TextButton( TextButton(
@@ -87,15 +89,187 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
], ],
), ),
); );
if (confirmed != true) return; if (confirmed != true) return;
await _deleteEnrollment(enrollmentDocId, studentName);
}
Future<void> _deleteEnrollment(
String enrollmentDocId,
String studentName,
) async {
final cs = Theme.of(context).colorScheme;
try { try {
await FirebaseFirestore.instance await FirebaseFirestore.instance
.collection('enrollments') .collection('enrollments')
.doc(enrollmentDocId) .doc(enrollmentDocId)
.delete(); .delete();
if (mounted) { if (!mounted) return;
ScaffoldMessenger.of(context)
..clearSnackBars()
..showSnackBar(
SnackBar(
behavior: SnackBarBehavior.floating,
margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
backgroundColor: cs.primary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
content: Text(
'"$studentName" foi removido da turma.',
style: const TextStyle(color: Colors.white),
),
),
);
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Erro ao remover: $e')));
}
}
// ── Build ──────────────────────────────────────────────────────────────────
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return StreamBuilder<QuerySnapshot>(
stream: _enrollmentsStream,
builder: (context, snapshot) {
final docs = snapshot.data?.docs ?? [];
final enrollments = List<QueryDocumentSnapshot>.from(docs)
..sort((a, b) {
final aTs = (a.data() as Map)['joinedAt'] as Timestamp?;
final bTs = (b.data() as Map)['joinedAt'] as Timestamp?;
if (aTs == null && bTs == null) return 0;
if (aTs == null) return 1;
if (bTs == null) return -1;
return aTs.compareTo(bTs);
});
final filtered = _searchQuery.isEmpty
? enrollments
: enrollments.where((doc) {
final d = doc.data() as Map<String, dynamic>;
final name = (d['studentName'] as String? ?? '').toLowerCase();
final email = (d['studentEmail'] as String? ?? '')
.toLowerCase();
return name.contains(_searchQuery) ||
email.contains(_searchQuery);
}).toList();
final bottomInset = MediaQuery.of(context).viewInsets.bottom;
return CustomScrollView(
physics: const NeverScrollableScrollPhysics(),
slivers: [
SliverPadding(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
sliver: SliverToBoxAdapter(
child: _buildHeader(cs, enrollments.length, snapshot),
),
),
SliverPadding(
padding: const EdgeInsets.fromLTRB(20, 14, 20, 0),
sliver: SliverToBoxAdapter(child: _buildSearchBar()),
),
if (snapshot.connectionState == ConnectionState.waiting &&
snapshot.data == null)
const SliverFillRemaining(
child: Center(
child: CircularProgressIndicator(color: Colors.white),
),
)
else if (filtered.isEmpty) ...[
SliverFillRemaining(
hasScrollBody: false,
child: Padding(
padding: EdgeInsets.only(bottom: bottomInset),
child: _buildEmpty(cs),
),
),
] else
SliverPadding(
padding: EdgeInsets.fromLTRB(20, 14, 20, 20 + bottomInset),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final doc = filtered[index];
final data = doc.data() as Map<String, dynamic>;
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _buildStudentCard(
cs: cs,
enrollmentDocId: doc.id,
studentName:
data['studentName'] as String? ?? 'Aluno sem nome',
studentEmail: data['studentEmail'] as String? ?? '',
joinedAt: data['joinedAt'] as Timestamp?,
),
);
}, childCount: filtered.length),
),
),
],
);
},
);
}
// ── Sub-widgets ────────────────────────────────────────────────────────────
Widget _buildHeader(
ColorScheme cs,
int count,
AsyncSnapshot<QuerySnapshot> snapshot,
) {
return Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [cs.primary, cs.primary.withValues(alpha: 0.8)],
),
borderRadius: BorderRadius.circular(16),
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.className,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
snapshot.connectionState == ConnectionState.waiting &&
snapshot.data == null
? 'A carregar…'
: '$count aluno${count == 1 ? '' : 's'} inscrito${count == 1 ? '' : 's'}',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.85),
fontSize: 13,
),
),
],
),
),
_buildCodeBadge(cs),
],
),
);
}
Widget _buildCodeBadge(ColorScheme cs) {
return GestureDetector(
onTap: () {
if (_classCode == null || _classCode == '') return;
Clipboard.setData(ClipboardData(text: _classCode!));
ScaffoldMessenger.of(context) ScaffoldMessenger.of(context)
..clearSnackBars() ..clearSnackBars()
..showSnackBar( ..showSnackBar(
@@ -106,287 +280,124 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
content: Text( duration: const Duration(seconds: 2),
'"$studentName" foi removido da disciplina.', content: const Text(
style: const TextStyle(color: Colors.white), 'Código copiado!',
style: TextStyle(color: Colors.white),
), ),
), ),
); );
} },
} catch (e) { child: Container(
if (mounted) { padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
ScaffoldMessenger.of( decoration: BoxDecoration(
context, color: Colors.white.withValues(alpha: 0.18),
).showSnackBar(SnackBar(content: Text('Erro ao remover aluno: $e'))); borderRadius: BorderRadius.circular(12),
} border: Border.all(color: Colors.white.withValues(alpha: 0.3)),
} ),
} child: Column(
children: [
@override const Text(
Widget build(BuildContext context) { 'Código',
final cs = Theme.of(context).colorScheme; style: TextStyle(
color: Colors.white70,
return StreamBuilder<QuerySnapshot>( fontSize: 10,
stream: _enrollmentsStream, fontWeight: FontWeight.w500,
builder: (context, snapshot) { ),
// Keep showing previous data while new data loads (prevents flash) ),
final docs = snapshot.data?.docs ?? []; const SizedBox(height: 2),
// Sort client-side by joinedAt ascending Text(
final enrollments = List<QueryDocumentSnapshot>.from(docs) _classCode ?? '',
..sort((a, b) { style: const TextStyle(
final aData = a.data() as Map<String, dynamic>; color: Colors.white,
final bData = b.data() as Map<String, dynamic>; fontSize: 18,
final aTs = aData['joinedAt'] as Timestamp?; fontWeight: FontWeight.bold,
final bTs = bData['joinedAt'] as Timestamp?; letterSpacing: 2,
if (aTs == null && bTs == null) return 0; ),
if (aTs == null) return 1; ),
if (bTs == null) return -1; const SizedBox(height: 2),
return aTs.compareTo(bTs); Row(
}); mainAxisSize: MainAxisSize.min,
final filtered = _searchQuery.isEmpty
? enrollments
: enrollments.where((doc) {
final data = doc.data() as Map<String, dynamic>;
final name = (data['studentName'] as String? ?? '')
.toLowerCase();
final email = (data['studentEmail'] as String? ?? '')
.toLowerCase();
final q = _searchQuery.toLowerCase();
return name.contains(q) || email.contains(q);
}).toList();
final bottomInset = MediaQuery.of(context).viewInsets.bottom;
return Padding(
padding: EdgeInsets.only(bottom: bottomInset),
child: Container(
margin: const EdgeInsets.all(20),
child: Column(
children: [ children: [
// ── Header ────────────────────────────────────────────────── Icon(
Container( Icons.copy,
padding: const EdgeInsets.all(18), color: Colors.white.withValues(alpha: 0.7),
decoration: BoxDecoration( size: 10,
gradient: LinearGradient(
colors: [cs.primary, cs.primary.withValues(alpha: 0.8)],
),
borderRadius: BorderRadius.circular(16),
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.className,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
snapshot.connectionState ==
ConnectionState.waiting
? 'A carregar…'
: '${enrollments.length} aluno${enrollments.length == 1 ? '' : 's'} inscrito${enrollments.length == 1 ? '' : 's'}',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.85),
fontSize: 13,
),
),
],
),
),
// Código da disciplina
GestureDetector(
onTap: () {
if (_classCode != null && _classCode != '') {
Clipboard.setData(ClipboardData(text: _classCode!));
ScaffoldMessenger.of(context)
..clearSnackBars()
..showSnackBar(
SnackBar(
behavior: SnackBarBehavior.floating,
margin: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 12,
),
backgroundColor: cs.primary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
duration: const Duration(seconds: 2),
content: const Text(
'Código copiado!',
style: TextStyle(color: Colors.white),
),
),
);
}
},
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 10,
),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.18),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.white.withValues(alpha: 0.3),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'Código',
style: TextStyle(
color: Colors.white70,
fontSize: 10,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 2),
Text(
_classCode ?? '',
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
letterSpacing: 2,
),
),
const SizedBox(height: 2),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.copy,
color: Colors.white.withValues(alpha: 0.7),
size: 10,
),
const SizedBox(width: 3),
Text(
'copiar',
style: TextStyle(
color: Colors.white.withValues(
alpha: 0.7,
),
fontSize: 9,
),
),
],
),
],
),
),
),
],
),
), ),
const SizedBox(height: 14), const SizedBox(width: 3),
Text(
// ── Search bar ────────────────────────────────────────────── 'copiar',
Container( style: TextStyle(
padding: const EdgeInsets.symmetric( color: Colors.white.withValues(alpha: 0.7),
horizontal: 14, fontSize: 9,
vertical: 10,
), ),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.white.withValues(alpha: 0.2),
),
),
child: Row(
children: [
Icon(
Icons.search,
color: Colors.white.withValues(alpha: 0.7),
size: 20,
),
const SizedBox(width: 10),
Expanded(
child: TextField(
onChanged: (v) =>
setState(() => _searchQuery = v.trim()),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
cursorColor: Colors.white,
decoration: InputDecoration(
hintText: 'Pesquisar aluno…',
hintStyle: TextStyle(
color: Colors.white.withValues(alpha: 0.5),
fontSize: 14,
),
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.zero,
),
),
),
if (_searchQuery.isNotEmpty)
GestureDetector(
onTap: () => setState(() => _searchQuery = ''),
child: Icon(
Icons.close,
color: Colors.white.withValues(alpha: 0.7),
size: 18,
),
),
],
),
),
const SizedBox(height: 14),
// ── List ────────────────────────────────────────────────────
Expanded(
child:
snapshot.connectionState == ConnectionState.waiting &&
snapshot.data == null
? const Center(
child: CircularProgressIndicator(color: Colors.white),
)
: filtered.isEmpty
? _buildEmpty(cs)
: ListView.separated(
padding: EdgeInsets.zero,
itemCount: filtered.length,
separatorBuilder: (_, __) =>
const SizedBox(height: 10),
itemBuilder: (context, index) {
final doc = filtered[index];
final data = doc.data() as Map<String, dynamic>;
final studentName =
data['studentName'] as String? ??
'Aluno sem nome';
final studentEmail =
data['studentEmail'] as String? ?? '';
final joinedAt = data['joinedAt'] as Timestamp?;
final enrollmentDocId = doc.id;
return _buildStudentCard(
cs: cs,
enrollmentDocId: enrollmentDocId,
studentName: studentName,
studentEmail: studentEmail,
joinedAt: joinedAt,
index: index,
);
},
),
), ),
], ],
), ),
],
),
),
);
}
Widget _buildSearchBar() {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.white.withValues(alpha: 0.2)),
),
child: Row(
children: [
Icon(
Icons.search,
color: Colors.white.withValues(alpha: 0.7),
size: 20,
), ),
); const SizedBox(width: 10),
}, Expanded(
child: Theme(
data: ThemeData.dark().copyWith(
textSelectionTheme: const TextSelectionThemeData(
cursorColor: Colors.white,
selectionColor: Colors.white24,
selectionHandleColor: Colors.white,
),
),
child: TextField(
controller: _searchController,
onChanged: (v) =>
setState(() => _searchQuery = v.trim().toLowerCase()),
style: const TextStyle(color: Colors.white, fontSize: 14),
cursorColor: Colors.white,
decoration: InputDecoration(
hintText: 'Pesquisar aluno…',
hintStyle: TextStyle(
color: Colors.white.withValues(alpha: 0.5),
fontSize: 14,
),
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.zero,
),
),
),
),
if (_searchQuery.isNotEmpty)
GestureDetector(
onTap: () {
_searchController.clear();
setState(() => _searchQuery = '');
},
child: Icon(
Icons.close,
color: Colors.white.withValues(alpha: 0.7),
size: 18,
),
),
],
),
); );
} }
@@ -396,7 +407,6 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
required String studentName, required String studentName,
required String studentEmail, required String studentEmail,
required Timestamp? joinedAt, required Timestamp? joinedAt,
required int index,
}) { }) {
return Dismissible( return Dismissible(
key: Key(enrollmentDocId), key: Key(enrollmentDocId),
@@ -410,7 +420,7 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
), ),
title: const Text('Remover aluno'), title: const Text('Remover aluno'),
content: Text( content: Text(
'Tens a certeza que queres remover "$studentName" desta disciplina?', 'Tens a certeza que queres remover "$studentName" desta turma?',
), ),
actions: [ actions: [
TextButton( TextButton(
@@ -427,41 +437,7 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
); );
return confirmed ?? false; return confirmed ?? false;
}, },
onDismissed: (_) async { onDismissed: (_) => _deleteEnrollment(enrollmentDocId, studentName),
try {
await FirebaseFirestore.instance
.collection('enrollments')
.doc(enrollmentDocId)
.delete();
if (mounted) {
ScaffoldMessenger.of(context)
..clearSnackBars()
..showSnackBar(
SnackBar(
behavior: SnackBarBehavior.floating,
margin: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 12,
),
backgroundColor: cs.primary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
content: Text(
'"$studentName" foi removido da disciplina.',
style: const TextStyle(color: Colors.white),
),
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Erro ao remover: $e')));
}
}
},
background: Container( background: Container(
decoration: BoxDecoration( decoration: BoxDecoration(
color: cs.error.withValues(alpha: 0.85), color: cs.error.withValues(alpha: 0.85),
@@ -480,7 +456,6 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
), ),
child: Row( child: Row(
children: [ children: [
// Avatar with initial
Container( Container(
width: 42, width: 42,
height: 42, height: 42,
@@ -500,7 +475,6 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
), ),
), ),
const SizedBox(width: 14), const SizedBox(width: 14),
// Info
Expanded( Expanded(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -536,7 +510,6 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
], ],
), ),
), ),
// Remove button
IconButton( IconButton(
icon: Icon( icon: Icon(
Icons.person_remove_outlined, Icons.person_remove_outlined,
@@ -544,8 +517,7 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
size: 20, size: 20,
), ),
tooltip: 'Remover aluno', tooltip: 'Remover aluno',
onPressed: () => onPressed: () => _confirmRemove(enrollmentDocId, studentName),
_removeStudent(context, enrollmentDocId, studentName),
), ),
], ],
), ),
@@ -595,7 +567,7 @@ class _ClassStudentsInlineWidgetState extends State<ClassStudentsInlineWidget> {
), ),
const SizedBox(height: 6), const SizedBox(height: 6),
Text( Text(
'Partilha o código da disciplina com os alunos.', 'Partilha o código da turma com os alunos.',
style: TextStyle( style: TextStyle(
color: Colors.white.withValues(alpha: 0.45), color: Colors.white.withValues(alpha: 0.45),
fontSize: 13, fontSize: 13,

View File

@@ -217,10 +217,12 @@ class _LoginPageState extends State<LoginPage> {
? AppThemeExtras.of(context).authBackgroundGradient ? AppThemeExtras.of(context).authBackgroundGradient
: [ : [
Theme.of(context).colorScheme.background, Theme.of(context).colorScheme.background,
Theme.of(context).colorScheme.primary Theme.of(
.withOpacity(0.1), context,
Theme.of(context).colorScheme.secondary ).colorScheme.primary.withOpacity(0.1),
.withOpacity(0.05), Theme.of(
context,
).colorScheme.secondary.withOpacity(0.05),
Theme.of(context).colorScheme.background, Theme.of(context).colorScheme.background,
], ],
), ),
@@ -239,55 +241,26 @@ class _LoginPageState extends State<LoginPage> {
// Logo/Title // Logo/Title
Container( Container(
padding: const EdgeInsets.all(20.0), width: double.infinity,
decoration: BoxDecoration( height: 84,
color: Theme.of( decoration: const BoxDecoration(
context, color: Color(0xFFF9EEE8),
).colorScheme.surface.withOpacity(0.9), borderRadius: BorderRadius.all(
borderRadius: BorderRadius.circular(16.0), Radius.circular(20),
boxShadow: [ ),
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 10.0,
offset: const Offset(0, 4),
),
],
), ),
child: Column( child: Center(
children: [ child: SizedBox(
Text( width: 140,
'EPVC', height: 140,
style: TextStyle( child: ClipRRect(
fontSize: 32, borderRadius: BorderRadius.circular(16),
fontWeight: FontWeight.bold, child: Image.asset(
foreground: Paint() 'assets/images/logo.png',
..shader = fit: BoxFit.cover,
LinearGradient(
colors: [
Theme.of(
context,
).colorScheme.primary,
Theme.of(
context,
).colorScheme.secondary,
],
).createShader(
Rect.fromLTWH(0, 0, 200, 20),
),
), ),
), ),
const SizedBox(height: 8), ),
Text(
'Escola Profissional de Vila do Conde',
style: TextStyle(
fontSize: 14,
color: Theme.of(
context,
).colorScheme.onSurface,
fontWeight: FontWeight.w500,
),
),
],
), ),
).animate().fadeIn( ).animate().fadeIn(
duration: const Duration(milliseconds: 800), duration: const Duration(milliseconds: 800),

View File

@@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart'; import 'package:flutter_animate/flutter_animate.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import '../../../../core/theme/app_theme_extension.dart'; import '../../../../core/theme/app_theme_extension.dart';
import '../../../../l10n/app_localizations.dart';
class RoleSelectionPage extends StatefulWidget { class RoleSelectionPage extends StatefulWidget {
const RoleSelectionPage({super.key}); const RoleSelectionPage({super.key});
@@ -43,115 +42,61 @@ class _RoleSelectionPageState extends State<RoleSelectionPage> {
padding: const EdgeInsets.all(24.0), padding: const EdgeInsets.all(24.0),
child: Column( child: Column(
children: [ children: [
const SizedBox(height: 60), const Spacer(flex: 1),
// Logo and title // Wide rectangle with image at top
Center( Container(
child: Column( width: double.infinity,
children: [ height: 84,
Container( decoration: const BoxDecoration(
width: 100, color: Color(0xFFF9EEE8),
height: 100, borderRadius: BorderRadius.all(Radius.circular(20)),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppThemeExtras.of(context)
.actionCardGradientStart,
AppThemeExtras.of(context)
.actionCardGradientEnd,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(25),
boxShadow: [
BoxShadow(
color: Theme.of(context)
.colorScheme
.primary
.withOpacity(0.3),
blurRadius: 25,
offset: const Offset(0, 10),
),
],
),
child: const Icon(
Icons.school,
size: 50,
color: Colors.white,
),
)
.animate()
.scale(
duration: const Duration(milliseconds: 800),
curve: Curves.elasticOut,
)
.then()
.shimmer(
duration: const Duration(milliseconds: 2000),
color: Colors.white.withOpacity(0.4),
),
const SizedBox(height: 32),
Text(
AppLocalizations.of(context)!.appTitle,
style: Theme.of(context).textTheme.headlineLarge
?.copyWith(
color: Theme.of(
context,
).colorScheme.onSurface,
fontWeight: FontWeight.bold,
),
)
.animate()
.fadeIn(
duration: const Duration(milliseconds: 800),
delay: const Duration(milliseconds: 200),
)
.slideY(
duration: const Duration(milliseconds: 600),
delay: const Duration(milliseconds: 200),
begin: -0.3,
),
const SizedBox(height: 12),
ShaderMask(
shaderCallback: (bounds) => LinearGradient(
colors: [
Theme.of(context).colorScheme.primary,
Theme.of(context).colorScheme.secondary,
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
).createShader(bounds),
child: Text(
AppLocalizations.of(context)!.schoolName,
style: Theme.of(context).textTheme.bodyMedium
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.w600,
),
),
)
.animate()
.fadeIn(
duration: const Duration(milliseconds: 800),
delay: const Duration(milliseconds: 400),
)
.slideY(
duration: const Duration(milliseconds: 600),
delay: const Duration(milliseconds: 400),
begin: -0.2,
),
],
), ),
child: Center(
child: SizedBox(
width: 140,
height: 140,
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.asset(
'assets/images/logo.png',
fit: BoxFit.cover,
),
),
),
),
).animate().fadeIn(
duration: const Duration(milliseconds: 800),
delay: const Duration(milliseconds: 200),
), ),
const Spacer(), const SizedBox(height: 24),
// Role selection title ShaderMask(
shaderCallback: (bounds) => LinearGradient(
colors: [
Theme.of(context).colorScheme.primary,
Theme.of(context).colorScheme.secondary,
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
).createShader(bounds),
child: Text(
'Assistente de estudo IA',
style: Theme.of(context).textTheme.headlineSmall
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
).animate().fadeIn(
duration: const Duration(milliseconds: 800),
delay: const Duration(milliseconds: 300),
),
const SizedBox(height: 32),
// Title
Text( Text(
'Quem é você?', 'Quem é você?',
style: Theme.of(context).textTheme.headlineMedium style: Theme.of(context).textTheme.headlineMedium
@@ -239,15 +184,16 @@ class _RoleSelectionPageState extends State<RoleSelectionPage> {
? _handleContinue ? _handleContinue
: null, : null,
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: backgroundColor: Theme.of(
Theme.of(context).colorScheme.primary, context,
foregroundColor: ).colorScheme.primary,
Theme.of(context).colorScheme.onPrimary, foregroundColor: Theme.of(
context,
).colorScheme.onPrimary,
elevation: 4, elevation: 4,
shadowColor: Theme.of(context) shadowColor: Theme.of(
.colorScheme context,
.primary ).colorScheme.primary.withOpacity(0.3),
.withOpacity(0.3),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
), ),
@@ -290,6 +236,8 @@ class _RoleSelectionPageState extends State<RoleSelectionPage> {
), ),
const SizedBox(height: 32), const SizedBox(height: 32),
const Spacer(flex: 1),
], ],
), ),
), ),
@@ -338,7 +286,9 @@ class _RoleSelectionPageState extends State<RoleSelectionPage> {
border: Border.all( border: Border.all(
color: isSelected color: isSelected
? gradientColor ? gradientColor
: Theme.of(context).colorScheme.primary.withOpacity(0.2), : Theme.of(
context,
).colorScheme.primary.withOpacity(0.2),
width: isSelected ? 2 : 1, width: isSelected ? 2 : 1,
), ),
boxShadow: [ boxShadow: [

View File

@@ -270,57 +270,26 @@ class _SignupPageState extends State<SignupPage> {
// Logo/Title // Logo/Title
Container( Container(
padding: const EdgeInsets.all(20.0), width: double.infinity,
decoration: BoxDecoration( height: 84,
color: Theme.of( decoration: const BoxDecoration(
context, color: Color(0xFFF9EEE8),
).colorScheme.surface.withOpacity(0.9), borderRadius: BorderRadius.all(
borderRadius: BorderRadius.circular(16.0), Radius.circular(20),
boxShadow: [ ),
BoxShadow(
color: Theme.of(
context,
).colorScheme.shadow.withOpacity(0.1),
blurRadius: 10.0,
offset: const Offset(0, 4),
),
],
), ),
child: Column( child: Center(
children: [ child: SizedBox(
Text( width: 140,
'EPVC', height: 140,
style: TextStyle( child: ClipRRect(
fontSize: 32, borderRadius: BorderRadius.circular(16),
fontWeight: FontWeight.bold, child: Image.asset(
foreground: Paint() 'assets/images/logo.png',
..shader = fit: BoxFit.cover,
LinearGradient(
colors: [
Theme.of(
context,
).colorScheme.primary,
Theme.of(
context,
).colorScheme.secondary,
],
).createShader(
Rect.fromLTWH(0, 0, 200, 20),
),
), ),
), ),
const SizedBox(height: 8), ),
Text(
'Escola Profissional de Vila do Conde',
style: TextStyle(
fontSize: 14,
color: Theme.of(
context,
).colorScheme.onSurface,
fontWeight: FontWeight.w500,
),
),
],
), ),
).animate().fadeIn( ).animate().fadeIn(
duration: const Duration(milliseconds: 800), duration: const Duration(milliseconds: 800),

View File

@@ -3,7 +3,7 @@ import 'package:flutter/material.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import '../../../../core/services/auth_service.dart'; import '../../../../core/services/auth_service.dart';
/// Página para visualizar os alunos de uma disciplina específica /// Página para visualizar os alunos de uma turma específica
class ClassStudentsPage extends StatefulWidget { class ClassStudentsPage extends StatefulWidget {
final String classId; final String classId;
final String className; final String className;
@@ -97,7 +97,7 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
Text( Text(
'Só podes ver os alunos das tuas próprias disciplinas.', 'Só podes ver os alunos das tuas próprias turmas.',
style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14), style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14),
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
@@ -183,7 +183,7 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
Text( Text(
'Nenhum aluno entrou nesta disciplina ainda.', 'Nenhum aluno entrou nesta turma ainda.',
style: TextStyle( style: TextStyle(
color: cs.onSurfaceVariant, color: cs.onSurfaceVariant,
fontSize: 16, fontSize: 16,
@@ -192,7 +192,7 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
'Partilha o código da disciplina para os alunos se juntarem.', 'Partilha o código da turma para os alunos se juntarem.',
style: TextStyle( style: TextStyle(
color: cs.onSurfaceVariant.withValues(alpha: 0.7), color: cs.onSurfaceVariant.withValues(alpha: 0.7),
fontSize: 13, fontSize: 13,
@@ -215,6 +215,7 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
final studentName = final studentName =
enrollment['studentName'] as String? ?? 'Aluno sem nome'; enrollment['studentName'] as String? ?? 'Aluno sem nome';
final joinedAt = enrollment['joinedAt'] as Timestamp?; final joinedAt = enrollment['joinedAt'] as Timestamp?;
final enrollmentId = enrollments[index].id;
return Container( return Container(
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -263,6 +264,15 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
), ),
), ),
), ),
trailing: IconButton(
icon: Icon(Icons.delete_outline, color: cs.error),
onPressed: () => _showRemoveStudentDialog(
context,
enrollmentId,
studentName,
),
tooltip: 'Remover aluno',
),
), ),
); );
}, },
@@ -275,4 +285,82 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
String _formatDate(DateTime date) { String _formatDate(DateTime date) {
return DateFormat('dd/MM/yyyy').format(date); return DateFormat('dd/MM/yyyy').format(date);
} }
Future<void> _showRemoveStudentDialog(
BuildContext context,
String enrollmentId,
String studentName,
) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Remover Aluno'),
content: Text(
'Tem a certeza que deseja remover $studentName desta turma?',
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancelar'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
),
child: const Text('Remover'),
),
],
),
);
if (confirmed == true && context.mounted) {
try {
await FirebaseFirestore.instance
.collection('enrollments')
.doc(enrollmentId)
.delete();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Row(
children: [
Icon(Icons.check_circle, color: Colors.white),
const SizedBox(width: 12),
const Text('Aluno removido com sucesso'),
],
),
backgroundColor: Colors.green,
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
duration: const Duration(seconds: 3),
),
);
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Row(
children: [
Icon(Icons.error_outline, color: Colors.white),
const SizedBox(width: 12),
Text('Erro ao remover aluno: $e'),
],
),
backgroundColor: Colors.red,
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
duration: const Duration(seconds: 4),
),
);
}
}
}
}
} }

View File

@@ -1,7 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../dashboard/presentation/widgets/teacher_classes_list_widget.dart'; import '../../../dashboard/presentation/widgets/teacher_classes_list_widget.dart';
/// Página dedicada para o professor ver todas as suas disciplinas /// Página dedicada para o professor ver todas as suas turmas
/// Reutiliza o TeacherClassesListWidget existente /// Reutiliza o TeacherClassesListWidget existente
class TeacherAllClassesPage extends StatelessWidget { class TeacherAllClassesPage extends StatelessWidget {
const TeacherAllClassesPage({super.key}); const TeacherAllClassesPage({super.key});
@@ -18,7 +18,7 @@ class TeacherAllClassesPage extends StatelessWidget {
onPressed: () => Navigator.of(context).pop(), onPressed: () => Navigator.of(context).pop(),
), ),
title: const Text( title: const Text(
'As Minhas Disciplinas', 'As Minhas Turmas',
style: TextStyle( style: TextStyle(
color: Colors.white, color: Colors.white,
fontSize: 18, fontSize: 18,

View File

@@ -6,7 +6,6 @@ import '../../../../core/routing/app_router.dart';
import '../widgets/teacher_hero_widget.dart'; import '../widgets/teacher_hero_widget.dart';
import '../widgets/teacher_quick_actions_widget.dart'; import '../widgets/teacher_quick_actions_widget.dart';
import '../widgets/teacher_classes_list_widget.dart'; import '../widgets/teacher_classes_list_widget.dart';
import '../widgets/teacher_analytics_preview_widget.dart';
class TeacherDashboardPage extends StatefulWidget { class TeacherDashboardPage extends StatefulWidget {
const TeacherDashboardPage({super.key}); const TeacherDashboardPage({super.key});
@@ -162,11 +161,6 @@ class _TeacherDashboardPageState extends State<TeacherDashboardPage> {
// Classes List Section // Classes List Section
const TeacherClassesListWidget(), const TeacherClassesListWidget(),
const SizedBox(height: 24),
// Analytics Preview Section
const TeacherAnalyticsPreviewWidget(),
const SizedBox(height: 40), const SizedBox(height: 40),
], ],
), ),

View File

@@ -245,7 +245,7 @@ class DashboardActionCard extends StatelessWidget {
} }
} }
/// Surface-styled vertical card (Quiz, Criar Disciplina, etc.). /// Surface-styled vertical card (Quiz, Criar Turma, etc.).
class DashboardActionCardSurface extends StatelessWidget { class DashboardActionCardSurface extends StatelessWidget {
const DashboardActionCardSurface({ const DashboardActionCardSurface({
super.key, super.key,

View File

@@ -187,24 +187,27 @@ class _ProgressHeroWidgetState extends State<ProgressHeroWidget> {
const SizedBox(height: 16), const SizedBox(height: 16),
// Progress Bar // Progress Bar
Container( GestureDetector(
height: 12, onTap: () => _showProgressExplanation(context),
decoration: BoxDecoration( child: Container(
color: Colors.white.withOpacity(0.3), height: 12,
borderRadius: BorderRadius.circular(6), decoration: BoxDecoration(
), color: Colors.white.withOpacity(0.3),
child: FractionallySizedBox( borderRadius: BorderRadius.circular(6),
alignment: Alignment.centerLeft, ),
widthFactor: overallProgress, child: FractionallySizedBox(
child: Container( alignment: Alignment.centerLeft,
decoration: BoxDecoration( widthFactor: overallProgress,
gradient: LinearGradient( child: Container(
colors: [ decoration: BoxDecoration(
AppThemeExtras.of(context).heroProgressStart, gradient: LinearGradient(
AppThemeExtras.of(context).heroProgressEnd, colors: [
], AppThemeExtras.of(context).heroProgressStart,
AppThemeExtras.of(context).heroProgressEnd,
],
),
borderRadius: BorderRadius.circular(6),
), ),
borderRadius: BorderRadius.circular(6),
), ),
), ),
), ),
@@ -215,10 +218,14 @@ class _ProgressHeroWidgetState extends State<ProgressHeroWidget> {
Row( Row(
children: [ children: [
Expanded( Expanded(
child: _buildStatCard( child: GestureDetector(
icon: Icons.access_time, onTap: () => _showStudyTimeDetails(context, userStats),
value: '${(studyTimeMinutes / 60).toStringAsFixed(1)}h', child: _buildStatCard(
label: 'Tempo de Estudo', icon: Icons.access_time,
value:
'${(studyTimeMinutes / 60).toStringAsFixed(1)}h',
label: 'Tempo de Estudo',
),
), ),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
@@ -362,4 +369,111 @@ class _ProgressHeroWidgetState extends State<ProgressHeroWidget> {
), ),
); );
} }
void _showProgressExplanation(BuildContext context) {
final cs = Theme.of(context).colorScheme;
showDialog(
context: context,
builder: (ctx) => AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
title: Row(
children: [
Icon(Icons.info_outline, color: cs.primary),
const SizedBox(width: 8),
const Text('Progresso Geral'),
],
),
content: const Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'O Progresso Geral representa a média dos níveis de domínio dos conceitos que já dominaste.',
style: TextStyle(fontSize: 14),
),
SizedBox(height: 12),
Text(
'Como é calculado:',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
),
SizedBox(height: 8),
Text(
'• Cada conceito tem um nível de 0 a 100\n'
'• O progresso é a média de todos os conceitos dominados\n'
'• Quanto mais alto, melhor o teu domínio',
style: TextStyle(fontSize: 13, color: Colors.grey),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(),
child: const Text('Entendi'),
),
],
),
);
}
void _showStudyTimeDetails(BuildContext context, UserStats? userStats) {
final cs = Theme.of(context).colorScheme;
final totalMinutes = userStats?.totalStudyTime ?? 0;
final weeklyMinutes = userStats?.weeklyStudyTime ?? 0;
final monthlyMinutes = userStats?.monthlyStudyTime ?? 0;
showDialog(
context: context,
builder: (ctx) => AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
title: Row(
children: [
Icon(Icons.access_time, color: cs.primary),
const SizedBox(width: 8),
const Text('Tempo de Estudo'),
],
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildTimeRow('Total', totalMinutes, cs),
const SizedBox(height: 12),
_buildTimeRow('Esta semana', weeklyMinutes, cs),
const SizedBox(height: 12),
_buildTimeRow('Este mês', monthlyMinutes, cs),
const SizedBox(height: 16),
const Text(
'O tempo é contado automaticamente quando completas quizzes.',
style: TextStyle(fontSize: 12, color: Colors.grey),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(),
child: const Text('Fechar'),
),
],
),
);
}
Widget _buildTimeRow(String label, int minutes, ColorScheme cs) {
final hours = minutes ~/ 60;
final mins = minutes % 60;
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: TextStyle(fontSize: 14, color: cs.onSurface)),
Text(
hours > 0 ? '${hours}h ${mins}min' : '${mins}min',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: cs.primary,
),
),
],
);
}
} }

View File

@@ -1,7 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:cloud_firestore/cloud_firestore.dart';
import '../../../../core/theme/app_theme_extension.dart';
import '../../../../core/services/auth_service.dart'; import '../../../../core/services/auth_service.dart';
import '../../../../core/services/gamification_service.dart'; import '../../../../core/services/gamification_service.dart';
import '../../../../core/models/class_stats.dart'; import '../../../../core/models/class_stats.dart';
@@ -11,10 +10,12 @@ class TeacherAnalyticsPreviewWidget extends StatefulWidget {
const TeacherAnalyticsPreviewWidget({super.key}); const TeacherAnalyticsPreviewWidget({super.key});
@override @override
State<TeacherAnalyticsPreviewWidget> createState() => _TeacherAnalyticsPreviewWidgetState(); State<TeacherAnalyticsPreviewWidget> createState() =>
_TeacherAnalyticsPreviewWidgetState();
} }
class _TeacherAnalyticsPreviewWidgetState extends State<TeacherAnalyticsPreviewWidget> { class _TeacherAnalyticsPreviewWidgetState
extends State<TeacherAnalyticsPreviewWidget> {
List<StudentRanking> _topStudents = []; List<StudentRanking> _topStudents = [];
bool _loading = true; bool _loading = true;
@@ -36,7 +37,7 @@ class _TeacherAnalyticsPreviewWidgetState extends State<TeacherAnalyticsPreviewW
.get(); .get();
List<StudentRanking> allStudents = []; List<StudentRanking> allStudents = [];
// Buscar ranking de cada turma // Buscar ranking de cada turma
for (final classDoc in classesSnapshot.docs) { for (final classDoc in classesSnapshot.docs) {
final classId = classDoc.id; final classId = classDoc.id;
@@ -67,232 +68,130 @@ class _TeacherAnalyticsPreviewWidgetState extends State<TeacherAnalyticsPreviewW
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final user = AuthService.currentUser; return Column(
final userName = user?.displayName ?? 'Professor'; crossAxisAlignment: CrossAxisAlignment.start,
final userEmail = user?.email ?? ''; children: [
Row(
return Container( children: [
margin: const EdgeInsets.only(top: 24), _buildQuickStat(
padding: const EdgeInsets.all(20), icon: Icons.check_circle,
decoration: BoxDecoration( label: 'Alunos Ativos',
color: Theme.of(context).colorScheme.surface, value: '18/24',
borderRadius: BorderRadius.circular(16), color: Theme.of(context).colorScheme.primary,
border: Border.all( ),
color: Theme.of(context).colorScheme.outline.withOpacity(0.2), const SizedBox(width: 12),
_buildQuickStat(
icon: Icons.warning_amber,
label: 'Precisam Apoio',
value: '3',
color: Theme.of(context).colorScheme.secondary,
),
const SizedBox(width: 12),
_buildQuickStat(
icon: Icons.emoji_events,
label: 'Média Turma',
value: '72%',
color: Theme.of(context).colorScheme.primary.withOpacity(0.8),
),
],
), ),
boxShadow: [ const SizedBox(height: 20),
BoxShadow(
color: Theme.of(context).colorScheme.shadow.withOpacity(0.05), // Top Performing Students Preview
blurRadius: 10, Row(
offset: const Offset(0, 4), children: [
), Icon(
], Icons.leaderboard,
), color: Theme.of(context).colorScheme.secondary,
child: Column( size: 20,
crossAxisAlignment: CrossAxisAlignment.start, ),
children: [ const SizedBox(width: 8),
// Profile Header Text(
Row( 'Melhores Desempenhos',
children: [ style: TextStyle(
Container( color: Theme.of(context).colorScheme.onSurface,
width: 48, fontSize: 16,
height: 48, fontWeight: FontWeight.bold,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppThemeExtras.of(context).actionCardGradientStart,
AppThemeExtras.of(context).actionCardGradientEnd,
],
),
borderRadius: BorderRadius.circular(24),
),
child: const Icon(Icons.school, color: Colors.white, size: 24),
), ),
const SizedBox(width: 16), ),
],
),
const SizedBox(height: 12),
// Student List Preview
if (_loading)
const Center(child: CircularProgressIndicator())
else if (_topStudents.isEmpty)
const Center(
child: Text(
'Nenhum aluno encontrado',
style: TextStyle(fontSize: 14),
),
)
else
..._topStudents.asMap().entries.map((entry) {
final index = entry.key;
final student = entry.value;
final color = _getStudentColor(context, index);
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: _buildStudentPerformanceItem(
context,
student.studentName,
student.overallScore.toInt(),
color,
),
);
}).toList(),
const SizedBox(height: 20),
// Content Quality Alert
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
),
),
child: Row(
children: [
Icon(
Icons.info_outline,
color: Theme.of(context).colorScheme.primary,
size: 20,
),
const SizedBox(width: 12),
Expanded( Expanded(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
userName, 'Qualidade do Conteúdo',
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.onSurface, color: Theme.of(context).colorScheme.onSurface,
fontSize: 18, fontSize: 14,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
const SizedBox(height: 2), const SizedBox(height: 2),
SingleChildScrollView( Text(
scrollDirection: Axis.horizontal, '12 conteúdos verificados • 2 pendentes de revisão',
child: Row( style: TextStyle(
mainAxisSize: MainAxisSize.min, color: Theme.of(context).colorScheme.onSurfaceVariant,
children: [ fontSize: 12,
Text(
userEmail,
style: TextStyle(
color: Theme.of(
context,
).colorScheme.onSurfaceVariant,
fontSize: 14,
),
),
if (userEmail.length > 20) ...[
const SizedBox(width: 8),
Icon(
Icons.more_horiz,
color: Theme.of(
context,
).colorScheme.onSurfaceVariant,
size: 16,
),
],
],
), ),
), ),
], ],
), ),
), ),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.secondary.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(
Icons.settings,
color: Theme.of(context).colorScheme.secondary,
size: 20,
),
),
], ],
), ),
const SizedBox(height: 20), ),
],
// Quick Stats Row
Row(
children: [
_buildQuickStat(
icon: Icons.check_circle,
label: 'Alunos Ativos',
value: '18/24',
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(width: 12),
_buildQuickStat(
icon: Icons.warning_amber,
label: 'Precisam Apoio',
value: '3',
color: Theme.of(context).colorScheme.secondary,
),
const SizedBox(width: 12),
_buildQuickStat(
icon: Icons.emoji_events,
label: 'Média Disciplina',
value: '72%',
color: Theme.of(context).colorScheme.primary.withOpacity(0.8),
),
],
),
const SizedBox(height: 20),
// Top Performing Students Preview
Row(
children: [
Icon(
Icons.leaderboard,
color: Theme.of(context).colorScheme.secondary,
size: 20,
),
const SizedBox(width: 8),
Text(
'Melhores Desempenhos',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 12),
// Student List Preview
if (_loading)
const Center(child: CircularProgressIndicator())
else if (_topStudents.isEmpty)
const Center(
child: Text(
'Nenhum aluno encontrado',
style: TextStyle(fontSize: 14),
),
)
else
..._topStudents.asMap().entries.map((entry) {
final index = entry.key;
final student = entry.value;
final color = _getStudentColor(context, index);
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: _buildStudentPerformanceItem(
context,
student.studentName,
student.overallScore.toInt(),
color,
),
);
}).toList(),
const SizedBox(height: 20),
// Content Quality Alert
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
),
),
child: Row(
children: [
Icon(
Icons.info_outline,
color: Theme.of(context).colorScheme.primary,
size: 20,
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Qualidade do Conteúdo',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 2),
Text(
'12 conteúdos verificados • 2 pendentes de revisão',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontSize: 12,
),
),
],
),
),
],
),
),
],
),
); );
} }

View File

@@ -4,7 +4,7 @@ import 'package:flutter/material.dart';
import '../../../../core/services/auth_service.dart'; import '../../../../core/services/auth_service.dart';
import '../../../classes/presentation/pages/class_students_page.dart'; import '../../../classes/presentation/pages/class_students_page.dart';
/// Widget para listar as disciplinas criadas pelo professor /// Widget para listar as turmas criadas pelo professor
class TeacherClassesListWidget extends StatelessWidget { class TeacherClassesListWidget extends StatelessWidget {
const TeacherClassesListWidget({super.key}); const TeacherClassesListWidget({super.key});
@@ -44,7 +44,7 @@ class TeacherClassesListWidget extends StatelessWidget {
return Padding( return Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0), padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Text( child: Text(
'Ainda não criaste nenhuma disciplina.', 'Ainda não criaste nenhuma turma.',
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant, color: Theme.of(context).colorScheme.onSurfaceVariant,
fontSize: 14, fontSize: 14,
@@ -65,7 +65,7 @@ class TeacherClassesListWidget extends StatelessWidget {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Text( Text(
'As Minhas Disciplinas', 'As Minhas Turmas',
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.onSurface, color: Theme.of(context).colorScheme.onSurface,
fontSize: 20, fontSize: 20,
@@ -144,7 +144,7 @@ class TeacherClassesListWidget extends StatelessWidget {
Padding( Padding(
padding: const EdgeInsets.all(20), padding: const EdgeInsets.all(20),
child: Text( child: Text(
'As Minhas Disciplinas', 'As Minhas Turmas',
style: TextStyle( style: TextStyle(
color: cs.onSurface, color: cs.onSurface,
fontSize: 20, fontSize: 20,

View File

@@ -31,7 +31,7 @@ class _TeacherHeroWidgetState extends State<TeacherHeroWidget> {
final user = AuthService.currentUser; final user = AuthService.currentUser;
if (user == null) return; if (user == null) return;
// Obter disciplinas do professor // Obter turmas do professor
final classesSnapshot = await FirebaseFirestore.instance final classesSnapshot = await FirebaseFirestore.instance
.collection('classes') .collection('classes')
.where('teacherId', isEqualTo: user.uid) .where('teacherId', isEqualTo: user.uid)
@@ -116,7 +116,7 @@ class _TeacherHeroWidgetState extends State<TeacherHeroWidget> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'Visão Geral da Disciplina', 'Visão Geral da Turma',
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.onSurface, color: Theme.of(context).colorScheme.onSurface,
fontSize: 20, fontSize: 20,
@@ -193,7 +193,7 @@ class _TeacherHeroWidgetState extends State<TeacherHeroWidget> {
children: [ children: [
const Flexible( const Flexible(
child: Text( child: Text(
'Progresso Médio da Disciplina', 'Progresso Médio da Turma',
maxLines: 2, maxLines: 2,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: TextStyle( style: TextStyle(
@@ -226,24 +226,27 @@ class _TeacherHeroWidgetState extends State<TeacherHeroWidget> {
const SizedBox(height: 16), const SizedBox(height: 16),
// Progress Bar // Progress Bar
Container( GestureDetector(
height: 12, onTap: () => _showProgressExplanation(context),
decoration: BoxDecoration( child: Container(
color: Colors.white.withOpacity(0.3), height: 12,
borderRadius: BorderRadius.circular(6), decoration: BoxDecoration(
), color: Colors.white.withOpacity(0.3),
child: FractionallySizedBox( borderRadius: BorderRadius.circular(6),
alignment: Alignment.centerLeft, ),
widthFactor: classAverageProgress, child: FractionallySizedBox(
child: Container( alignment: Alignment.centerLeft,
decoration: BoxDecoration( widthFactor: classAverageProgress,
gradient: LinearGradient( child: Container(
colors: [ decoration: BoxDecoration(
AppThemeExtras.of(context).heroProgressStart, gradient: LinearGradient(
AppThemeExtras.of(context).heroProgressEnd, colors: [
], AppThemeExtras.of(context).heroProgressStart,
AppThemeExtras.of(context).heroProgressEnd,
],
),
borderRadius: BorderRadius.circular(6),
), ),
borderRadius: BorderRadius.circular(6),
), ),
), ),
), ),
@@ -369,14 +372,14 @@ class _TeacherHeroWidgetState extends State<TeacherHeroWidget> {
_buildActivityItem( _buildActivityItem(
context, context,
'Nenhuma atividade recente', 'Nenhuma atividade recente',
'Comece criando disciplinas e conteúdos', 'Comece criando turmas e conteúdos',
Theme.of(context).colorScheme.onSurfaceVariant, Theme.of(context).colorScheme.onSurfaceVariant,
), ),
); );
return activities; return activities;
} }
// Adicionar atividades baseadas nas estatísticas das disciplinas // Adicionar atividades baseadas nas estatísticas das turmas
for (final stats in _classStats.take(3)) { for (final stats in _classStats.take(3)) {
if (stats.activeQuizzes > 0) { if (stats.activeQuizzes > 0) {
activities.add( activities.add(
@@ -425,7 +428,7 @@ class _TeacherHeroWidgetState extends State<TeacherHeroWidget> {
_buildActivityItem( _buildActivityItem(
context, context,
'Nenhuma atividade recente', 'Nenhuma atividade recente',
'Comece criando disciplinas e conteúdos', 'Comece criando turmas e conteúdos',
Theme.of(context).colorScheme.onSurfaceVariant, Theme.of(context).colorScheme.onSurfaceVariant,
), ),
] ]
@@ -473,4 +476,24 @@ class _TeacherHeroWidgetState extends State<TeacherHeroWidget> {
], ],
); );
} }
void _showProgressExplanation(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Progresso Médio da Turma'),
content: const Text(
'O progresso médio da turma é calculado com base no domínio dos conceitos por cada aluno. '
'Cada aluno tem um nível de domínio para cada conceito (0-100%), e o progresso médio '
'é a média de todos esses níveis de domínio em toda a turma.',
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Entendi'),
),
],
),
);
}
} }

View File

@@ -20,7 +20,7 @@ class TeacherQuickActionsWidget extends StatefulWidget {
class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> { class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
bool _isCreatingClass = false; bool _isCreatingClass = false;
/// Mesmas dimensões dos cards em "As Minhas Disciplinas". /// Mesmas dimensões dos cards em "As Minhas Turmas".
static const double _scrollCardWidth = 200; static const double _scrollCardWidth = 200;
static const double _scrollRowHeight = 156; static const double _scrollRowHeight = 156;
static const double _cardMinHeight = 156; static const double _cardMinHeight = 156;
@@ -128,7 +128,7 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
final cs = Theme.of(context).colorScheme; final cs = Theme.of(context).colorScheme;
return DashboardActionCardSurface( return DashboardActionCardSurface(
title: 'Analytics', title: 'Analytics',
subtitle: 'Desempenho da disciplina', subtitle: 'Desempenho da turma',
icon: Icons.analytics, icon: Icons.analytics,
minHeight: _cardMinHeight, minHeight: _cardMinHeight,
titleFontSize: _titleFontSize, titleFontSize: _titleFontSize,
@@ -142,7 +142,7 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
color: cs.primary.withOpacity(0.1), color: cs.primary.withOpacity(0.1),
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
), ),
child: Icon(Icons.analytics, color: cs.primary, size: _iconSize), child: const Icon(Icons.analytics, color: Colors.blue, size: 28),
), ),
onTap: () => context.go('/teacher/analytics'), onTap: () => context.go('/teacher/analytics'),
); );
@@ -153,7 +153,7 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
return ClipRRect( return ClipRRect(
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
child: DashboardActionCardSurface( child: DashboardActionCardSurface(
title: 'Criar Disciplina', title: 'Criar Turma',
subtitle: 'Gerar código de acesso', subtitle: 'Gerar código de acesso',
icon: Icons.school, icon: Icons.school,
minHeight: _cardMinHeight, minHeight: _cardMinHeight,
@@ -202,7 +202,7 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
}, },
), ),
_TeacherActionItem( _TeacherActionItem(
title: 'Criar Disciplina', title: 'Criar Turma',
subtitle: 'Gerar código de acesso', subtitle: 'Gerar código de acesso',
icon: Icons.school, icon: Icons.school,
onTap: () { onTap: () {
@@ -221,7 +221,7 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
), ),
_TeacherActionItem( _TeacherActionItem(
title: 'Analytics', title: 'Analytics',
subtitle: 'Desempenho da disciplina', subtitle: 'Desempenho da turma',
icon: Icons.analytics, icon: Icons.analytics,
onTap: () { onTap: () {
Navigator.pop(context); Navigator.pop(context);
@@ -367,7 +367,7 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
), ),
title: Text( title: Text(
'Criar Nova Disciplina', 'Criar Nova Turma',
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.onSurface, color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@@ -378,7 +378,7 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'Nome da disciplina:', 'Nome da turma:',
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant, color: Theme.of(context).colorScheme.onSurfaceVariant,
fontSize: 14, fontSize: 14,
@@ -432,7 +432,7 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
), ),
const SizedBox(width: 10), const SizedBox(width: 10),
Text( Text(
'A carregar disciplinas...', 'A carregar turmas...',
style: TextStyle( style: TextStyle(
color: Theme.of( color: Theme.of(
context, context,
@@ -571,7 +571,7 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text( content: Text(
'Disciplina "$className" criada com sucesso! Código: $classCode', 'Turma "$className" criada com sucesso! Código: $classCode',
), ),
backgroundColor: Theme.of(context).colorScheme.primary, backgroundColor: Theme.of(context).colorScheme.primary,
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
@@ -585,7 +585,7 @@ class _TeacherQuickActionsWidgetState extends State<TeacherQuickActionsWidget> {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text('Erro ao criar disciplina: $e'), content: Text('Erro ao criar turma: $e'),
backgroundColor: Colors.red, backgroundColor: Colors.red,
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(

View File

@@ -2374,11 +2374,13 @@ class _InteractiveQuizSheetState extends State<_InteractiveQuizSheet> {
late List<int> _chosen; late List<int> _chosen;
bool _submitted = false; bool _submitted = false;
bool _saving = false; bool _saving = false;
DateTime? _startTime;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_chosen = List.filled(widget.questions.length, -1); _chosen = List.filled(widget.questions.length, -1);
_startTime = DateTime.now();
} }
void _selectOption(int idx) { void _selectOption(int idx) {
@@ -2427,6 +2429,19 @@ class _InteractiveQuizSheetState extends State<_InteractiveQuizSheet> {
totalQuestions: widget.questions.length, totalQuestions: widget.questions.length,
materialName: widget.title, materialName: widget.title,
); );
// Registrar tempo de estudo real
if (_startTime != null) {
final elapsedDuration = DateTime.now().difference(_startTime!);
final elapsedMinutes = elapsedDuration.inMinutes;
final elapsedSeconds = elapsedDuration.inSeconds % 60;
if (elapsedMinutes > 0 || elapsedSeconds > 0) {
Logger.info(
'Quiz study time recorded: ${elapsedMinutes}m ${elapsedSeconds}s',
);
await GamificationService.recordStudyTime(user.uid, elapsedMinutes);
}
}
} }
} catch (e) { } catch (e) {
Logger.error('Error saving quiz result: $e'); Logger.error('Error saving quiz result: $e');
@@ -2837,11 +2852,13 @@ class _TeacherQuizInteractiveSheetState
late List<int> _chosen; late List<int> _chosen;
bool _submitted = false; bool _submitted = false;
bool _saving = false; bool _saving = false;
DateTime? _startTime;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_chosen = List.filled(widget.questions.length, -1); _chosen = List.filled(widget.questions.length, -1);
_startTime = DateTime.now();
} }
void _selectOption(int idx) { void _selectOption(int idx) {
@@ -2914,6 +2931,19 @@ class _TeacherQuizInteractiveSheetState
totalQuestions: total, totalQuestions: total,
materialName: matName, materialName: matName,
); );
// Registrar tempo de estudo real
if (_startTime != null) {
final elapsedDuration = DateTime.now().difference(_startTime!);
final elapsedMinutes = elapsedDuration.inMinutes;
final elapsedSeconds = elapsedDuration.inSeconds % 60;
if (elapsedMinutes > 0 || elapsedSeconds > 0) {
Logger.info(
'Quiz study time recorded: ${elapsedMinutes}m ${elapsedSeconds}s',
);
await GamificationService.recordStudyTime(user.uid, elapsedMinutes);
}
}
} }
} catch (e) { } catch (e) {
Logger.error('Error submitting teacher quiz result: $e'); Logger.error('Error submitting teacher quiz result: $e');

View File

@@ -231,10 +231,12 @@ class _SplashPageState extends State<SplashPage> {
), ),
], ],
), ),
child: const Icon( child: ClipRRect(
Icons.school, borderRadius: BorderRadius.circular(20),
size: 40, child: Image.asset(
color: Colors.white, 'assets/images/epvc.png',
fit: BoxFit.cover,
),
), ),
) )
.animate() .animate()

View File

@@ -169,6 +169,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.4" version: "2.0.4"
cli_util:
dependency: transitive
description:
name: cli_util
sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c
url: "https://pub.dev"
source: hosted
version: "0.4.2"
clock: clock:
dependency: transitive dependency: transitive
description: description:
@@ -587,6 +595,14 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
flutter_launcher_icons:
dependency: "direct main"
description:
name: flutter_launcher_icons
sha256: "526faf84284b86a4cb36d20a5e45147747b7563d921373d4ee0559c54fcdbcea"
url: "https://pub.dev"
source: hosted
version: "0.13.1"
flutter_lints: flutter_lints:
dependency: "direct dev" dependency: "direct dev"
description: description:
@@ -871,6 +887,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.1.2" version: "4.1.2"
image:
dependency: transitive
description:
name: image
sha256: f31d52537dc417fdcde36088fdf11d191026fd5e4fae742491ebd40e5a8bea7d
url: "https://pub.dev"
source: hosted
version: "4.3.0"
image_picker: image_picker:
dependency: "direct main" dependency: "direct main"
description: description:

View File

@@ -61,6 +61,9 @@ dependencies:
shimmer: ^3.0.0 shimmer: ^3.0.0
flutter_staggered_animations: ^1.1.1 flutter_staggered_animations: ^1.1.1
# App Launcher Icons
flutter_launcher_icons: ^0.13.1
# HTTP & Networking # HTTP & Networking
dio: ^5.4.0 dio: ^5.4.0
http: ^1.1.2 http: ^1.1.2
@@ -148,3 +151,10 @@ flutter:
# weight: 600 # weight: 600
# - asset: assets/fonts/Inter-Bold.ttf # - asset: assets/fonts/Inter-Bold.ttf
# weight: 700 # weight: 700
flutter_launcher_icons:
android: "launcher_icon"
ios: true
image_path: "assets/images/epvc.png"
adaptive_icon_background: "#F9EEE8"
adaptive_icon_foreground: "assets/images/epvc.png"