nao aparecer para outro utilizador

This commit is contained in:
2026-03-19 10:40:53 +00:00
parent 8adea3f7b6
commit 6c89b7ab8c
6 changed files with 74 additions and 54 deletions

View File

@@ -4,48 +4,49 @@ import '../models/game_model.dart';
class GameController {
final _supabase = Supabase.instance.client;
// 1. LER JOGOS (Stream em Tempo Real)
// 👇 Atalho para apanhar o ID do utilizador logado
String get myUserId => _supabase.auth.currentUser?.id ?? '';
// 1. LER JOGOS (Stream em Tempo Real da tabela original)
Stream<List<Game>> get gamesStream {
return _supabase
.from('games') // 1. Fica à escuta da tabela original (Garante o Tempo Real!)
.from('games')
.stream(primaryKey: ['id'])
.eq('user_id', myUserId) // 🔒 SEGURANÇA: Ouve apenas os jogos deste utilizador
.asyncMap((event) async {
// 2. Sempre que a tabela 'games' mudar (novo jogo, alteração de resultado),
// vamos buscar os dados já misturados com as imagens à nossa View.
final viewData = await _supabase
.from('games_with_logos')
// Lê diretamente da tabela "games" e já não da "games_with_logos"
final data = await _supabase
.from('games')
.select()
.eq('user_id', myUserId) // 🔒 SEGURANÇA
.order('game_date', ascending: false);
// 3. Convertemos para a nossa lista de objetos Game
return viewData.map((json) => Game.fromMap(json)).toList();
return data.map((json) => Game.fromMap(json)).toList();
});
}
// =========================================================================
// 👇 NOVO: LER JOGOS COM FILTROS DE EQUIPA E TEMPORADA (MANTÉM OS LOGOS)
// =========================================================================
// =========================================================================
// 👇 LER JOGOS COM FILTROS DE EQUIPA E TEMPORADA (SEM ERROS DE QUERY)
// 👇 LER JOGOS COM FILTROS DE EQUIPA E TEMPORADA
// =========================================================================
Stream<List<Game>> getFilteredGames({required String teamFilter, required String seasonFilter}) {
return _supabase
.from('games')
.stream(primaryKey: ['id'])
.eq('user_id', myUserId) // 🔒 SEGURANÇA
.asyncMap((event) async {
// 1. Começamos a query APENAS com o select (Sem o order ainda!)
var query = _supabase.from('games_with_logos').select();
// 1. Começamos a query na tabela principal "games"
var query = _supabase.from('games').select().eq('user_id', myUserId); // 🔒 SEGURANÇA
// 2. Se a temporada não for "Todas", aplicamos o filtro AQUI
if (seasonFilter != 'Todas') {
query = query.eq('season', seasonFilter);
}
// 3. Executamos a query e aplicamos o ORDER BY no final
final viewData = await query.order('game_date', ascending: false);
// 3. Executamos a query e ordenamos pela data
final data = await query.order('game_date', ascending: false);
List<Game> games = viewData.map((json) => Game.fromMap(json)).toList();
List<Game> games = data.map((json) => Game.fromMap(json)).toList();
// 4. Filtramos a equipa em memória
if (teamFilter != 'Todas') {
@@ -55,21 +56,22 @@ class GameController {
return games;
});
}
// 2. CRIAR JOGO
// Retorna o ID do jogo criado para podermos navegar para o placar
Future<String?> createGame(String myTeam, String opponent, String season) async {
try {
final response = await _supabase.from('games').insert({
'user_id': myUserId, // 🔒 CARIMBA O JOGO COM O ID DO TREINADOR
'my_team': myTeam,
'opponent_team': opponent,
'season': season,
'my_score': 0,
'opponent_score': 0,
'status': 'Decorrer', // Começa como "Decorrer"
'status': 'Decorrer',
'game_date': DateTime.now().toIso8601String(),
}).select().single(); // .select().single() retorna o objeto criado
}).select().single();
return response['id']; // Retorna o UUID gerado pelo Supabase
return response['id'];
} catch (e) {
print("Erro ao criar jogo: $e");
return null;

View File

@@ -11,32 +11,49 @@ class BasketTrackHeader extends StatelessWidget {
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(
width: 200 * context.sf,
height: 200 * context.sf,
child: Image.asset(
'assets/playmaker-logos.png',
fit: BoxFit.contain,
),
),
Text(
'BasketTrack',
style: TextStyle(
fontSize: 36 * context.sf,
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.onSurface, // 👇 Adaptável ao Modo Escuro
),
),
SizedBox(height: 6 * context.sf),
Text(
'Gere as tuas equipas e estatísticas',
style: TextStyle(
fontSize: 16 * context.sf,
color: Colors.grey, // Mantemos cinza para subtítulo
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
// Usamos um Stack para controlar a sobreposição exata
Stack(
alignment: Alignment.center,
children: [
// 1. A Imagem (Aumentada para 320)
SizedBox(
width: 320 * context.sf,
height: 350 * context.sf,
child: Image.asset(
'assets/playmaker-logos.png',
fit: BoxFit.contain,
),
),
// 2. O Texto "subido" para dentro da área da imagem
Positioned(
bottom: 5 * context.sf, // Ajusta este valor para aproximar/afastar do centro da logo
child: Column(
children: [
Text(
'BasketTrack',
style: TextStyle(
fontSize: 36 * context.sf,
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.onSurface,
),
),
SizedBox(height: 4 * context.sf),
Text(
'Gere as tuas equipas e estatísticas',
style: TextStyle(
fontSize: 16 * context.sf,
color: Colors.grey,
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
),
],
),
),
],
),
// Espaço extra para não bater nos campos de login logo a seguir
SizedBox(height: 10 * context.sf),
],
);
}