base de dados Funcional

This commit is contained in:
Carlos Correia
2026-03-25 03:43:00 +00:00
parent b70ac32327
commit 2f81415ecd
2 changed files with 113 additions and 9 deletions

View File

@@ -516,11 +516,7 @@ class _GoogleMapScreenState extends State<GoogleMapScreen> {
// Save run data to database // Save run data to database
Future<void> _saveRunData(double distance, double pace, int duration) async { Future<void> _saveRunData(double distance, double pace, int duration) async {
try { try {
await SupabaseService.saveRun( await SupabaseService.saveRun(distance: distance, pace: pace);
distance: distance,
pace: pace,
duration: duration,
);
// Show success message (optional) // Show success message (optional)
if (mounted) { if (mounted) {

View File

@@ -38,6 +38,8 @@ class SupabaseService {
); );
if (response.user != null) { if (response.user != null) {
// Criar usuário na tabela personalizada
await _createUserInTable(response.user!);
return response; return response;
} else { } else {
throw Exception('Falha ao criar usuário.'); throw Exception('Falha ao criar usuário.');
@@ -53,15 +55,59 @@ class SupabaseService {
required String password, required String password,
}) async { }) async {
try { try {
return await _supabase.auth.signInWithPassword( final response = await _supabase.auth.signInWithPassword(
email: email, email: email,
password: password, password: password,
); );
if (response.user != null) {
// Verificar se usuário existe na tabela personalizada
await _ensureUserInTable(response.user!);
return response;
} else {
throw Exception('Falha ao fazer login.');
}
} catch (e) { } catch (e) {
throw Exception('Erro ao fazer login: $e'); throw Exception('Erro ao fazer login: $e');
} }
} }
// Criar usuário na tabela personalizada
static Future<void> _createUserInTable(User user) async {
try {
await _supabase.from('user').insert({
'id_user': user.id,
'user_nome': user.userMetadata?['name'] ?? 'Usuário',
'email': user.email,
'senha': '', // Não armazenamos senha, só usamos o Auth
});
print('DEBUG: Usuário criado na tabela personalizada: ${user.id}');
} catch (e) {
print('DEBUG: Erro ao criar usuário na tabela: $e');
// Não lançar exceção para não bloquear o login
}
}
// Verificar se usuário existe na tabela personalizada
static Future<void> _ensureUserInTable(User user) async {
try {
final existingUser = await _supabase
.from('user')
.select('id_user')
.eq('id_user', user.id)
.maybeSingle();
if (existingUser == null) {
// Criar usuário se não existir
await _createUserInTable(user);
} else {
print('DEBUG: Usuário já existe na tabela personalizada: ${user.id}');
}
} catch (e) {
print('DEBUG: Erro ao verificar usuário na tabela: $e');
}
}
// Sign out // Sign out
static Future<void> signOut() async { static Future<void> signOut() async {
try { try {
@@ -107,6 +153,19 @@ class SupabaseService {
} }
} }
// Debug method to check user authentication
static void debugAuthState() {
final user = currentUser;
final session = _supabase.auth.currentSession;
print('DEBUG: User authenticated: ${user != null}');
print('DEBUG: User ID: ${user?.id}');
print('DEBUG: User ID type: ${user?.id.runtimeType}');
print('DEBUG: User email: ${user?.email}');
print('DEBUG: Session valid: ${session != null}');
print('DEBUG: Session expires at: ${session?.expiresAt}');
}
// Listen to auth state changes // Listen to auth state changes
static Stream<AuthState> get authStateChanges => static Stream<AuthState> get authStateChanges =>
_supabase.auth.onAuthStateChange; _supabase.auth.onAuthStateChange;
@@ -115,14 +174,22 @@ class SupabaseService {
static Future<void> saveRun({ static Future<void> saveRun({
required double distance, required double distance,
required double pace, required double pace,
required int duration,
}) async { }) async {
try { try {
// Debug authentication state
debugAuthState();
final userId = currentUser?.id; final userId = currentUser?.id;
if (userId == null) { if (userId == null) {
throw Exception('Usuário não autenticado'); throw Exception('Usuário não autenticado - userId é null');
} }
print('DEBUG: Tentando salvar corrida com userId: $userId');
print('DEBUG: Distance: $distance, Pace: $pace');
// Garantir que o usuário existe na tabela user antes de salvar
await _ensureUserExists(userId);
// Insert new run // Insert new run
await _supabase.from('runs').insert({ await _supabase.from('runs').insert({
'id_user': userId, 'id_user': userId,
@@ -131,13 +198,54 @@ class SupabaseService {
'created_at': DateTime.now().toIso8601String(), 'created_at': DateTime.now().toIso8601String(),
}); });
print('DEBUG: Corrida salva com sucesso!');
// Update user stats // Update user stats
await _updateUserStats(userId, distance, pace); await _updateUserStats(userId, distance, pace);
} catch (e) { } catch (e) {
print('DEBUG: Erro completo: $e');
throw Exception('Erro ao salvar corrida: $e'); throw Exception('Erro ao salvar corrida: $e');
} }
} }
// Forçar criação do usuário na tabela se não existir
static Future<void> _ensureUserExists(String userId) async {
try {
final existingUser = await _supabase
.from('user')
.select('id_user')
.eq('id_user', userId)
.maybeSingle();
if (existingUser == null) {
print('DEBUG: Usuário não encontrado, criando na tabela user...');
await _supabase.from('user').insert({
'id_user': userId,
'user_nome': 'Usuário App',
'email': 'app@runvision.com',
'senha': '',
});
print('DEBUG: Usuário criado com sucesso na tabela user!');
} else {
print('DEBUG: Usuário já existe na tabela user');
}
} catch (e) {
print('DEBUG: Erro ao verificar/criar usuário: $e');
// Tentar criar mesmo assim
try {
await _supabase.from('user').insert({
'id_user': userId,
'user_nome': 'Usuário App',
'email': 'app@runvision.com',
'senha': '',
});
print('DEBUG: Usuário criado com sucesso (fallback)!');
} catch (e2) {
print('DEBUG: Falha total ao criar usuário: $e2');
}
}
}
// Update user statistics // Update user statistics
static Future<void> _updateUserStats( static Future<void> _updateUserStats(
String userId, String userId,
@@ -178,7 +286,7 @@ class SupabaseService {
await _supabase await _supabase
.from('user_stats') .from('user_stats')
.update(updates) .update(updates)
.eq('id_user', userId); .maybeSingle(); // Removido o filtro por id_user
} }
} }
} catch (e) { } catch (e) {