9 Commits

Author SHA1 Message Date
Moisés Méndez
af5d086cf9 chore: eliminar tarjeta de agregar direcciones en la pantalla de inicio 2026-05-23 09:48:27 -06:00
Moisés Méndez
f6463307da fix: permitir acceso directo a la pantalla de inicio y direcciones sin redirección 2026-05-23 09:32:50 -06:00
Moisés Méndez
211e14cef5 feat: agregar pantalla de gestión de direcciones y navegación 2026-05-23 09:17:36 -06:00
Moisés Méndez
218ad84991 feat: agregar clase PasswordHasher para el hash de contraseñas 2026-05-23 08:32:45 -06:00
25030248hasel
649752a6a4 feat: creacion de interfaz xon simulacion de rutas 2026-05-23 08:22:39 -06:00
25030248hasel
7d07cc101d fix login con database 2026-05-23 06:52:42 -06:00
25030248hasel
1709a51ecc funcion base de datos y registro 2026-05-23 06:03:29 -06:00
25030248hasel
6638f471e1 Resuelto conflicto de fusión 2026-05-23 04:29:05 -06:00
25030248hasel
9fdb51f622 version 2.1 2026-05-23 03:52:03 -06:00
10 changed files with 1056 additions and 632 deletions

13
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,13 @@
{
"yaml.customTags": [
"!upload scalar",
"!remove scalar",
"!keep scalar",
"!erase scalar",
"!jwt scalar"
],
"yaml.schemas": {
"https://raw.githubusercontent.com/doanthuanthanh88/testapi6/main/schema.json": "*.yaml"
},
"cmake.sourceDirectory": "C:/Users/Mendez/Documents/Practicas de programacion/Proyecto-Hackathon (ITC)/hackathon-sfc-a9a4cee23109413188ee35ceac01dc07/windows"
}

View File

@@ -0,0 +1,38 @@
import 'package:mysql_client/mysql_client.dart';
class MySqlService {
MySQLConnection? _connection;
// Instancia única (Singleton)
static final MySqlService _instance = MySqlService._internal();
factory MySqlService() => _instance;
MySqlService._internal();
/// Inicializa y abre la conexión con MySQL
Future<MySQLConnection> getConnection() async {
if (_connection != null && _connection!.connected) {
return _connection!;
}
// ⚠️ CONFIGURACIÓN OBLIGATORIA PARA EL PUENTE USB
//(Valido solamente en el entorno de desarrollo local con MySQL Workbench)
_connection = await MySQLConnection.createConnection(
host: '127.0.0.1', // El cable USB mapea esta dirección local
port: 3306, // Puerto estándar de tu MySQL
userName: 'root', // Tu usuario administrador
password: '123456789', // Tu contraseña de MySQL
databaseName: 'recolect_trackingdb', // Tu esquema real de Workbench
);
await _connection!.connect();
return _connection!;
}
/// Cierra la conexión de forma segura
Future<void> closeConnection() async {
if (_connection != null && _connection!.connected) {
await _connection!.close();
_connection = null;
}
}
}

View File

@@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart';
import '../../features/auth/presentation/bloc/auth_bloc.dart'; import '../../features/auth/presentation/bloc/auth_bloc.dart';
import '../../features/auth/presentation/bloc/auth_state.dart'; import '../../features/auth/presentation/bloc/auth_state.dart';
import '../../features/auth/presentation/screens/address_manager_screen.dart';
import '../../features/auth/presentation/screens/login_screen.dart'; import '../../features/auth/presentation/screens/login_screen.dart';
import '../../features/auth/presentation/screens/register_screen.dart'; import '../../features/auth/presentation/screens/register_screen.dart';
import '../../features/auth/presentation/screens/home_screen_placeholder.dart'; import '../../features/auth/presentation/screens/home_screen_placeholder.dart';
@@ -12,8 +13,9 @@ import '../../features/auth/presentation/screens/home_screen_placeholder.dart';
abstract final class AppRoutes { abstract final class AppRoutes {
static const String splash = '/'; static const String splash = '/';
static const String login = '/login'; static const String login = '/login';
static const String register = '/register'; // 📍 Agregada constante oficial static const String register = '/register';
static const String home = '/home'; static const String home = '/home';
static const String addresses = '/addresses';
} }
/// Configuración central de navegación con go_router. /// Configuración central de navegación con go_router.
@@ -24,7 +26,8 @@ GoRouter createRouter(AuthBloc authBloc) {
redirect: (BuildContext context, GoRouterState state) { redirect: (BuildContext context, GoRouterState state) {
final authState = authBloc.state; final authState = authBloc.state;
final isAuthenticated = authState is AuthAuthenticated; final isAuthenticated = authState is AuthAuthenticated;
final isCheckingSession = authState is AuthCheckingSession || authState is AuthInitial; final isCheckingSession =
authState is AuthCheckingSession || authState is AuthInitial;
final currentLocation = state.uri.path; final currentLocation = state.uri.path;
// Mientras se verifica la sesión, mostrar splash. // Mientras se verifica la sesión, mostrar splash.
@@ -32,7 +35,14 @@ GoRouter createRouter(AuthBloc authBloc) {
return currentLocation == AppRoutes.splash ? null : AppRoutes.splash; return currentLocation == AppRoutes.splash ? null : AppRoutes.splash;
} }
// 📍 SOLUCCIÓN: Permitir acceso a rutas públicas sin estar autenticado // 📍 SOLUCIÓN HACKATÓN: Si la app intenta ir al Home o a Direcciones,
// ignoramos el candado de seguridad para no rebotar al login.
if (currentLocation == AppRoutes.home ||
currentLocation == AppRoutes.addresses) {
return null;
}
// Permitir acceso a rutas públicas sin estar autenticado
final publicRoutes = [AppRoutes.login, AppRoutes.register]; final publicRoutes = [AppRoutes.login, AppRoutes.register];
final isPublicRoute = publicRoutes.contains(currentLocation); final isPublicRoute = publicRoutes.contains(currentLocation);
@@ -58,13 +68,17 @@ GoRouter createRouter(AuthBloc authBloc) {
builder: (context, state) => const LoginScreen(), builder: (context, state) => const LoginScreen(),
), ),
GoRoute( GoRoute(
path: AppRoutes.register, // 📍 Usando la constante limpia path: AppRoutes.register,
builder: (context, state) => const RegisterScreen(), builder: (context, state) => const RegisterScreen(),
), ),
GoRoute( GoRoute(
path: AppRoutes.home, path: AppRoutes.home,
builder: (context, state) => const HomeScreenPlaceholder(), builder: (context, state) => const HomeScreenPlaceholder(),
), ),
GoRoute(
path: AppRoutes.addresses,
builder: (context, state) => const AddressManagerScreen(),
),
], ],
); );
} }

View File

@@ -0,0 +1,13 @@
import 'dart:convert';
import 'package:crypto/crypto.dart';
class PasswordHasher {
static const String _salt = 'waste-notify-local-salt-v1';
static String hash(String password) {
final normalized = password.trim();
final bytes = utf8.encode('$_salt:$normalized');
return sha256.convert(bytes).toString();
}
}

View File

@@ -0,0 +1,309 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/router/app_router.dart';
class AddressManagerScreen extends StatefulWidget {
const AddressManagerScreen({super.key});
@override
State<AddressManagerScreen> createState() => _AddressManagerScreenState();
}
class _AddressManagerScreenState extends State<AddressManagerScreen> {
final _formKey = GlobalKey<FormState>();
final _aliasController = TextEditingController();
final _streetController = TextEditingController();
final _coloniaController = TextEditingController();
final Map<String, _RouteInfo> _routeCatalog = {
'zona centro': _RouteInfo(routeId: 'RUTA-01', schedule: 'Matutino (06:30 - 07:15)'),
'las arboledas': _RouteInfo(routeId: 'RUTA-01', schedule: 'Matutino (07:00 - 07:30)'),
'trojes': _RouteInfo(routeId: 'RUTA-13', schedule: 'Matutino (06:40 - 07:10)'),
'san juanico': _RouteInfo(routeId: 'RUTA-03', schedule: 'Matutino (06:45 - 07:15)'),
'los olivos': _RouteInfo(routeId: 'RUTA-04', schedule: 'Matutino (07:00 - 07:40)'),
'rancho seco': _RouteInfo(routeId: 'RUTA-05', schedule: 'Vespertino (14:15 - 15:00)'),
'las insurgentes': _RouteInfo(routeId: 'RUTA-12', schedule: 'Matutino (06:35 - 07:10)'),
};
final List<_SavedAddress> _savedAddresses = [
_SavedAddress(
alias: 'Casa',
street: 'Av. Siempre Viva 123',
colonia: 'Zona Centro',
routeId: 'RUTA-01',
schedule: 'Matutino (06:30 - 07:15)',
),
];
@override
void dispose() {
_aliasController.dispose();
_streetController.dispose();
_coloniaController.dispose();
super.dispose();
}
void _saveAddress() {
if (!_formKey.currentState!.validate()) {
return;
}
final colonia = _coloniaController.text.trim();
final routeInfo = _routeCatalog[colonia.toLowerCase()];
setState(() {
_savedAddresses.insert(
0,
_SavedAddress(
alias: _aliasController.text.trim(),
street: _streetController.text.trim(),
colonia: colonia,
routeId: routeInfo?.routeId ?? 'Ruta no encontrada',
schedule: routeInfo?.schedule ?? 'Horario no disponible',
),
);
_aliasController.clear();
_streetController.clear();
_coloniaController.clear();
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Dirección guardada correctamente')),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF5F7F5),
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0,
title: const Text(
'Mis direcciones',
style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
),
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.black),
onPressed: () => context.go(AppRoutes.home),
),
),
bottomNavigationBar: NavigationBar(
selectedIndex: 1,
onDestinationSelected: (index) {
if (index == 0) {
context.go(AppRoutes.home);
}
},
destinations: const [
NavigationDestination(
icon: Icon(Icons.home_outlined),
selectedIcon: Icon(Icons.home),
label: 'Inicio',
),
NavigationDestination(
icon: Icon(Icons.location_on_outlined),
selectedIcon: Icon(Icons.location_on),
label: 'Direcciones',
),
],
),
body: ListView(
padding: const EdgeInsets.all(20),
children: [
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF1B5E20), Color(0xFF2E7D32)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(24),
),
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.place, color: Colors.white, size: 34),
SizedBox(height: 12),
Text(
'Agrega tus direcciones',
style: TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.bold),
),
SizedBox(height: 8),
Text(
'Guarda uno o varios domicilios para relacionarlos con tus rutas de recolección.',
style: TextStyle(color: Colors.white70, fontSize: 14, height: 1.4),
),
],
),
),
const SizedBox(height: 20),
Card(
elevation: 1,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
child: Padding(
padding: const EdgeInsets.all(18),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _aliasController,
decoration: const InputDecoration(
labelText: 'Alias',
prefixIcon: Icon(Icons.badge_outlined),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Escribe un alias';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _streetController,
decoration: const InputDecoration(
labelText: 'Calle y número',
prefixIcon: Icon(Icons.home_outlined),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Escribe la dirección';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _coloniaController,
decoration: const InputDecoration(
labelText: 'Colonia',
prefixIcon: Icon(Icons.map_outlined),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Escribe la colonia';
}
return null;
},
),
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: _saveAddress,
icon: const Icon(Icons.add_location_alt, color: Colors.white),
label: const Text('Guardar dirección'),
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF2E7D32),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
),
),
),
],
),
),
),
),
const SizedBox(height: 20),
Text(
'Mis direcciones',
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 12),
..._savedAddresses.map(
(address) => Card(
margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: ListTile(
leading: const CircleAvatar(
backgroundColor: Color(0xFFE8F5E9),
child: Icon(Icons.route, color: Color(0xFF2E7D32)),
),
title: Text(address.alias, style: const TextStyle(fontWeight: FontWeight.bold)),
subtitle: Padding(
padding: const EdgeInsets.only(top: 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(address.street),
const SizedBox(height: 4),
Text(address.colonia),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
_InfoChip(label: address.routeId, icon: Icons.local_shipping),
_InfoChip(label: address.schedule, icon: Icons.access_time),
],
),
],
),
),
isThreeLine: true,
),
),
),
],
),
);
}
}
class _SavedAddress {
final String alias;
final String street;
final String colonia;
final String routeId;
final String schedule;
_SavedAddress({
required this.alias,
required this.street,
required this.colonia,
required this.routeId,
required this.schedule,
});
}
class _RouteInfo {
final String routeId;
final String schedule;
const _RouteInfo({required this.routeId, required this.schedule});
}
class _InfoChip extends StatelessWidget {
final String label;
final IconData icon;
const _InfoChip({required this.label, required this.icon});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFFF1F8E9),
borderRadius: BorderRadius.circular(999),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 14, color: const Color(0xFF2E7D32)),
const SizedBox(width: 6),
Text(
label,
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
),
],
),
);
}
}

View File

@@ -1,533 +1,408 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/router/app_router.dart';
import '../bloc/auth_bloc.dart';
import '../bloc/auth_event.dart';
import '../bloc/auth_state.dart';
/// Pantalla principal post-login — MVP WasteNotify. class HomeScreenPlaceholder extends StatefulWidget {
///
/// Cascarón de la pantalla de inicio. En fases futuras contendrá:
/// - ETA de llegada del camión (sin mapa, solo tiempo estimado)
/// - Notificaciones programadas
/// - Historial de recolecciones
/// - Panel de operador (si role == 'operator')
///
/// RESTRICCIÓN DE PRIVACIDAD: Esta pantalla NO mostrará mapas de rutas
/// ni la posición GPS del vehículo. Solo tiempo estimado de llegada.
class HomeScreenPlaceholder extends StatelessWidget {
const HomeScreenPlaceholder({super.key}); const HomeScreenPlaceholder({super.key});
@override @override
Widget build(BuildContext context) { State<HomeScreenPlaceholder> createState() => _HomeScreenPlaceholderState();
return BlocBuilder<AuthBloc, AuthState>( }
builder: (context, state) {
final user = state is AuthAuthenticated ? state.user : null;
final isOperator = user?.role == 'operator';
return Scaffold( class _HomeScreenPlaceholderState extends State<HomeScreenPlaceholder> {
backgroundColor: AppTheme.warmWhite, // 1. Catálogo de Colonias tipado fuertemente con tu nuevo modelo (Mapeo de tu JSON)
appBar: AppBar( final List<ColoniaModel> _coloniasData = [
title: Row( ColoniaModel(colonia: "Zona Centro", routeId: "RUTA-01", horarioEstimado: "Matutino (06:30 - 07:15)"),
children: [ ColoniaModel(colonia: "Las Arboledas", routeId: "RUTA-01", horarioEstimado: "Matutino (07:00 - 07:30)"),
const Icon(Icons.recycling_rounded, ColoniaModel(colonia: "Trojes", routeId: "RUTA-13", horarioEstimado: "Matutino (06:40 - 07:10)"),
color: AppTheme.leafGreen, size: 22), ColoniaModel(colonia: "San Juanico", routeId: "RUTA-03", horarioEstimado: "Matutino (06:45 - 07:15)"),
const SizedBox(width: 8), ColoniaModel(colonia: "Los Olivos", routeId: "RUTA-04", horarioEstimado: "Matutino (07:00 - 07:40)"),
RichText( ColoniaModel(colonia: "Rancho Seco", routeId: "RUTA-05", horarioEstimado: "Vespertino (14:15 - 15:00)"),
text: const TextSpan( ColoniaModel(colonia: "Las Insurgentes", routeId: "RUTA-12", horarioEstimado: "Matutino (06:35 - 07:10)")
style: TextStyle( ];
fontSize: 18,
fontWeight: FontWeight.w700, // 2. Diccionario de Telemetría Satelital de Celaya (Mapeo de tus imágenes)
color: AppTheme.charcoal, final Map<String, Map<String, dynamic>> _routesTelemetry = {
), "RUTA-01": {
children: [ "name": "Zona Centro - Las Arboledas",
TextSpan(text: 'Waste'), "truckId": 101,
TextSpan( "positions": [
text: 'Notify', {"positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "desc": "Salida Relleno Sanitario", "mins": "45"},
style: TextStyle(color: AppTheme.leafGreen), {"positionId": 2, "lat": 20.5185, "lng": -100.8450, "speed": 45, "desc": "En trayecto principal", "mins": "30"},
), {"positionId": 3, "lat": 20.5215, "lng": -100.8142, "speed": 22, "desc": "Ingresando a zona Centro", "mins": "20"},
], {"positionId": 4, "lat": 20.5212, "lng": -100.8175, "speed": 15, "desc": "Punto Previo Destino (<15 min)", "mins": "12"},
), {"positionId": 5, "lat": 20.5210, "lng": -100.8210, "speed": 0, "desc": "Recolección Activa de Residuos", "mins": "5"},
), {"positionId": 6, "lat": 20.5235, "lng": -100.8212, "speed": 18, "desc": "Avanzando sector Arboledas", "mins": "3"},
], {"positionId": 7, "lat": 20.5260, "lng": -100.8215, "speed": 20, "desc": "Última parada del circuito", "mins": "1"},
), {"positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 40, "desc": "Retorno al Basurero Municipal", "mins": "0"}
actions: [ ]
IconButton(
icon: const Icon(Icons.logout_rounded),
tooltip: 'Cerrar sesión',
onPressed: () {
context.read<AuthBloc>().add(const AuthLogoutRequested());
}, },
), "RUTA-03": {
], "name": "Sector Poniente - San Juanico",
), "truckId": 103,
body: CustomScrollView( "positions": [
slivers: [ {"positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "desc": "Salida Base de Monitoreo", "mins": "40"},
SliverPadding( {"positionId": 2, "lat": 20.5250, "lng": -100.8510, "speed": 42, "desc": "Vía Rápida Poniente", "mins": "25"},
padding: const EdgeInsets.all(20), {"positionId": 3, "lat": 20.5290, "lng": -100.8320, "speed": 20, "desc": "Eje Norponiente", "mins": "18"},
sliver: SliverList( {"positionId": 4, "lat": 20.5315, "lng": -100.8355, "speed": 15, "desc": "Avenida San Juanico", "mins": "10"},
delegate: SliverChildListDelegate([ {"positionId": 5, "lat": 20.5340, "lng": -100.8390, "speed": 0, "desc": "Vaciado de Contenedores Urbano", "mins": "6"},
// --- Bienvenida --- {"positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 35, "desc": "Retorno General", "mins": "0"}
_WelcomeCard(user: user), ]
const SizedBox(height: 20), },
"RUTA-04": {
"name": "Oriente - Los Olivos",
"truckId": 104,
"positions": [
{"positionId": 1, "lat": 20.5111, "lng": -100.9037, "speed": 0, "desc": "Encendido de Unidad", "mins": "50"},
{"positionId": 4, "lat": 20.5320, "lng": -100.7850, "speed": 12, "desc": "Proximidad Los Olivos", "mins": "14"},
{"positionId": 5, "lat": 20.5350, "lng": -100.7790, "speed": 0, "desc": "Recolección Casa por Casa", "mins": "8"},
{"positionId": 8, "lat": 20.5111, "lng": -100.9037, "speed": 48, "desc": "Retorno a Relleno Sanitario", "mins": "0"}
]
}
};
// --- ETA Principal (cascarón) --- int _activePositionIndex = 0;
const _EtaCard(),
const SizedBox(height: 20),
// --- Mensaje preventivo --- // 📍 Historial tipado de forma segura con el modelo de notificaciones push
const _PreventiveMessageCard(), final List<NotificationModel> _pushNotificationsLog = [];
const SizedBox(height: 20),
// --- Próximas funcionalidades --- String _userColonia = "Zona Centro";
_UpcomingFeatures(isOperator: isOperator), bool _isInitialized = false;
const SizedBox(height: 20),
// --- Info de sesión (debug MVP) --- @override
if (user != null) _SessionDebugCard(user: user), void initState() {
]), super.initState();
), _userColonia = "Zona Centro"; // Forzado de respaldo seguro
), _isInitialized = true;
],
), WidgetsBinding.instance.addPostFrameCallback((_) {
_triggerNotificationCheck();
});
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
try {
final uri = GoRouterState.of(context).uri;
final String? coloniaParam = uri.queryParameters['colonia'];
if (coloniaParam != null &&
coloniaParam.isNotEmpty &&
_coloniasData.any((e) => e.colonia.toLowerCase() == coloniaParam.toLowerCase())) {
final elementoEncontrado = _coloniasData.firstWhere(
(e) => e.colonia.toLowerCase() == coloniaParam.toLowerCase()
); );
}, setState(() {
_userColonia = elementoEncontrado.colonia;
});
}
} catch (e) {
// Manejo silencioso de GoRouter
}
}
// Lógica interactiva que dispara las notificaciones basadas en tu modelo real
void _triggerNotificationCheck() {
final String currentRouteId = _getColoniaInfo().routeId;
if (!_routesTelemetry.containsKey(currentRouteId)) return;
final telemetry = _routesTelemetry[currentRouteId]!;
final currentPos = (telemetry["positions"] as List)[_activePositionIndex];
final int pId = currentPos["positionId"];
NotificationModel? newAlert;
if (pId == 2) {
newAlert = NotificationModel(
triggerEvent: "ROUTE_START",
condition: "Cuando positionId cambia de 1 a 2",
pushPayload: PushPayloadModel(
title: "¡Ruta Iniciada!",
body: "El camión recolector ha salido del Relleno Sanitario rumbo a tu sector. Asegúrate de tener listos tus residuos."
)
);
} else if (pId == 4) {
newAlert = NotificationModel(
triggerEvent: "TRUCK_PROXIMITY",
condition: "Cuando positionId llega a 4 (punto previo al destino)",
pushPayload: PushPayloadModel(
title: "Camión Cercano",
body: "El camión está a menos de 15 minutos de tu domicilio. Es momento de sacar tus bolsas a la acera."
)
);
} else if (pId == 8) {
newAlert = NotificationModel(
triggerEvent: "ROUTE_COMPLETED",
condition: "Cuando positionId llega a 8 (retorno al basurero)",
pushPayload: PushPayloadModel(
title: "Servicio Finalizado",
body: "El camión de tu sector ha concluido su jornada de recolección diaria."
)
);
}
if (newAlert != null) {
setState(() {
_pushNotificationsLog.insert(0, newAlert!);
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('🔔 Push: ${newAlert.pushPayload.title}'),
backgroundColor: pId == 4 ? Colors.amber.shade900 : (pId == 8 ? Colors.blue.shade700 : Colors.green.shade700),
duration: const Duration(seconds: 2),
),
); );
} }
} }
// --------------------------------------------------------------------------- ColoniaModel _getColoniaInfo() {
// Sub-widgets de la pantalla home return _coloniasData.firstWhere(
// --------------------------------------------------------------------------- (element) => element.colonia == _userColonia,
orElse: () => _coloniasData.first,
);
}
class _WelcomeCard extends StatelessWidget { void _nextSimulationStep() {
final dynamic user; final String currentRouteId = _getColoniaInfo().routeId;
if (!_routesTelemetry.containsKey(currentRouteId)) return;
const _WelcomeCard({required this.user}); final positionsList = _routesTelemetry[currentRouteId]!["positions"] as List;
if (_activePositionIndex < positionsList.length - 1) {
setState(() {
_activePositionIndex++;
});
_triggerNotificationCheck();
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final roleLabel = user?.role == 'operator' ? 'Operador' : 'Ciudadano'; final coloniaInfo = _getColoniaInfo();
final identifier = user?.email ?? ''; final String routeId = coloniaInfo.routeId;
return Container( final telemetry = _routesTelemetry[routeId]!;
padding: const EdgeInsets.all(20), final currentPositionData = (telemetry["positions"] as List)[_activePositionIndex];
decoration: BoxDecoration(
gradient: const LinearGradient( return Scaffold(
colors: [AppTheme.leafGreen, AppTheme.forestGreen], backgroundColor: const Color(0xFFF5F5F5),
begin: Alignment.topLeft, appBar: AppBar(
end: Alignment.bottomRight, title: Row(
children: const [
Icon(Icons.recycling, color: Color(0xFF2E7D32)),
SizedBox(width: 8),
Text('WasteNotify', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: Colors.black)),
],
), ),
borderRadius: BorderRadius.circular(16), backgroundColor: Colors.white,
boxShadow: [ elevation: 0,
BoxShadow( actions: [
color: AppTheme.leafGreen.withValues(alpha: 0.3), IconButton(
blurRadius: 16, icon: const Icon(Icons.logout, color: Colors.black),
offset: const Offset(0, 6), onPressed: () => context.go('/login'),
)
],
),
bottomNavigationBar: NavigationBar(
selectedIndex: 0,
onDestinationSelected: (index) {
if (index == 1) {
context.go(AppRoutes.addresses);
}
},
destinations: const [
NavigationDestination(
icon: Icon(Icons.home_outlined),
selectedIcon: Icon(Icons.home),
label: 'Inicio',
),
NavigationDestination(
icon: Icon(Icons.location_on_outlined),
selectedIcon: Icon(Icons.location_on),
label: 'Direcciones',
), ),
], ],
), ),
body: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// --- 1. TARJETA DE BIENVENIDA ---
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: const Color(0xFF1B5E20),
borderRadius: BorderRadius.circular(20),
),
child: Row( child: Row(
children: [ children: [
Container( const CircleAvatar(
width: 52, backgroundColor: Colors.white24,
height: 52, radius: 24,
decoration: BoxDecoration( child: Icon(Icons.person, color: Colors.white, size: 28),
color: Colors.white.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(13),
),
child: const Icon(
Icons.person_rounded,
color: Colors.white,
size: 30,
),
), ),
const SizedBox(width: 16), const SizedBox(width: 16),
Expanded( Column(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( const Text('¡Bienvenido!', style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold)),
'¡Bienvenido!', const SizedBox(height: 6),
style: const TextStyle(
color: Colors.white70,
fontSize: 13,
),
),
Text(
identifier,
style: const TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.w700,
),
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Container( Container(
padding: padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
const EdgeInsets.symmetric(horizontal: 10, vertical: 3), decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(12)),
decoration: BoxDecoration( child: const Text('Ciudadano', style: TextStyle(color: Colors.white, fontSize: 12)),
color: Colors.white.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(20),
), ),
child: Text( ],
roleLabel, ),
style: const TextStyle( ],
),
),
const SizedBox(height: 16),
// --- 2. RELOJ DE TIEMPO ESTIMADO INTERACTIVO ---
Card(
color: Colors.white, color: Colors.white,
fontSize: 11, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
fontWeight: FontWeight.w600, elevation: 1,
),
),
),
],
),
),
],
),
);
}
}
class _EtaCard extends StatelessWidget {
const _EtaCard();
@override
Widget build(BuildContext context) {
return Card(
child: Padding( child: Padding(
padding: const EdgeInsets.all(20), padding: const EdgeInsets.all(20.0),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Row( Row(
children: [ children: const [
Container( Icon(Icons.access_time, color: Color(0xFF2E7D32)),
padding: const EdgeInsets.all(8), SizedBox(width: 10),
decoration: BoxDecoration( Text('Tiempo estimado de llegada', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.black)),
color: AppTheme.lightMint,
borderRadius: BorderRadius.circular(10),
),
child: const Icon(
Icons.schedule_rounded,
color: AppTheme.leafGreen,
size: 22,
),
),
const SizedBox(width: 12),
const Expanded(
child: Text(
'Tiempo estimado de llegada',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
color: AppTheme.charcoal,
),
),
),
], ],
), ),
const SizedBox(height: 20), const SizedBox(height: 16),
Center(
child: Column(
children: [
Container( Container(
width: 110, width: 110,
height: 110, height: 110,
decoration: BoxDecoration( decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: const Color(0xFFE0E0E0), width: 3)),
shape: BoxShape.circle, child: Column(
border: Border.all(
color: AppTheme.lightMint,
width: 6,
),
color: Colors.white,
),
child: const Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Icon( Text('${currentPositionData["mins"]}', style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold, color: Colors.black)),
Icons.hourglass_empty_rounded, Text('— min', style: TextStyle(fontSize: 14, color: Colors.grey.shade600)),
color: AppTheme.midGray,
size: 28,
),
SizedBox(height: 4),
Text(
'— min',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w800,
color: AppTheme.midGray,
),
),
], ],
), ),
), ),
const SizedBox(height: 14),
Text(
'Notificaciones activas próximamente',
style: TextStyle(
fontSize: 13,
color: AppTheme.midGray,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 5),
decoration: BoxDecoration(
color: AppTheme.lightMint,
borderRadius: BorderRadius.circular(20),
),
child: const Text(
'Fase 2 — En desarrollo',
style: TextStyle(
fontSize: 11,
color: AppTheme.leafGreen,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
],
),
),
);
}
}
class _PreventiveMessageCard extends StatelessWidget {
const _PreventiveMessageCard();
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: AppTheme.alertAmber.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: AppTheme.alertAmber.withValues(alpha: 0.3),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Row(
children: [
Icon(Icons.campaign_outlined,
color: AppTheme.alertAmber, size: 18),
SizedBox(width: 8),
Text(
'Recuerda siempre',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 13,
color: AppTheme.earthBrown,
),
),
],
),
const SizedBox(height: 10),
_ReminderItem(
'🚮',
'Saca la basura SOLO cuando recibas la alerta de "próxima llegada".',
),
_ReminderItem(
'🚫',
'Nunca persigas ni te acerques al camión. El sistema te avisará a tiempo.',
),
_ReminderItem(
'🌱',
'Separar tus residuos hace más eficiente la recolección. ¡Gracias!',
),
],
),
);
}
}
class _ReminderItem extends StatelessWidget {
final String emoji;
final String text;
const _ReminderItem(this.emoji, this.text);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(emoji, style: const TextStyle(fontSize: 14)),
const SizedBox(width: 8),
Expanded(
child: Text(
text,
style: const TextStyle(
fontSize: 12.5,
color: AppTheme.earthBrown,
height: 1.4,
),
),
),
],
),
);
}
}
class _UpcomingFeatures extends StatelessWidget {
final bool isOperator;
const _UpcomingFeatures({required this.isOperator});
@override
Widget build(BuildContext context) {
final features = [
(Icons.notifications_active_outlined, 'Alertas push de recolección',
'Fase 2'),
(Icons.history_rounded, 'Historial de notificaciones', 'Fase 2'),
(Icons.settings_outlined, 'Configurar zona y horario', 'Fase 3'),
if (isOperator) ...[
(Icons.bar_chart_rounded, 'Panel de rutas completadas', 'Fase 3'),
(Icons.group_outlined, 'Gestión de sectores', 'Fase 4'),
],
];
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Próximamente en WasteNotify',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: AppTheme.charcoal,
),
),
const SizedBox(height: 12), const SizedBox(height: 12),
...features.map((f) => _FeatureRow( Text('Estado GPS: ${currentPositionData["desc"]}', textAlign: TextAlign.center, style: TextStyle(fontSize: 13, color: Colors.grey.shade600, fontStyle: FontStyle.italic)),
icon: f.$1,
label: f.$2,
phase: f.$3,
)),
], ],
), ),
), ),
),
const SizedBox(height: 16),
// --- 3. BOTÓN DE SIMULACIÓN PARA EL MVP ---
ElevatedButton.icon(
style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF2E7D32), padding: const EdgeInsets.symmetric(vertical: 14), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14))),
onPressed: _activePositionIndex < (telemetry['positions'] as List).length - 1 ? _nextSimulationStep : null,
icon: const Icon(Icons.play_arrow, color: Colors.white),
label: const Text('Simular Avance del Camión (GPS)', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
),
const SizedBox(height: 16),
// --- 4. BANDEJA DE ALERTAS REALES RECIBIDAS (PARSED) ---
if (_pushNotificationsLog.isNotEmpty) ...[
const Text('🔔 Alertas Push en Vivo', style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold, color: Colors.black)),
const SizedBox(height: 8),
..._pushNotificationsLog.map((log) {
final bool isWarning = log.triggerEvent == 'TRUCK_PROXIMITY';
final bool isDone = log.triggerEvent == 'ROUTE_COMPLETED';
final Color cardColor = isWarning ? Colors.amber.shade900 : (isDone ? Colors.blue.shade700 : Colors.green.shade700);
return Card(
margin: const EdgeInsets.symmetric(vertical: 4),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: ListTile(
leading: CircleAvatar(backgroundColor: cardColor.withOpacity(0.12), child: Icon(isWarning ? Icons.notification_important : (isDone ? Icons.check_circle : Icons.local_shipping), color: cardColor)),
title: Text(log.pushPayload.title, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14)),
subtitle: Text(log.pushPayload.body, style: const TextStyle(fontSize: 12)),
),
); );
} }).toList(),
} const SizedBox(height: 16),
],
class _FeatureRow extends StatelessWidget { // --- 5. PANEL DE RECOMENDACIONES ---
final IconData icon;
final String label;
final String phase;
const _FeatureRow({
required this.icon,
required this.label,
required this.phase,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
children: [
Icon(icon, size: 18, color: AppTheme.mintGreen),
const SizedBox(width: 12),
Expanded(
child: Text(
label,
style: const TextStyle(fontSize: 13, color: AppTheme.charcoal),
),
),
Container( Container(
padding: padding: const EdgeInsets.all(16),
const EdgeInsets.symmetric(horizontal: 8, vertical: 3), decoration: BoxDecoration(color: const Color(0xFFFFF3E0), borderRadius: BorderRadius.circular(16), border: Border.all(color: const Color(0xFFFFE0B2))),
decoration: BoxDecoration(
color: AppTheme.lightGray,
borderRadius: BorderRadius.circular(20),
),
child: Text(
phase,
style: const TextStyle(
fontSize: 10,
color: AppTheme.midGray,
fontWeight: FontWeight.w600,
),
),
),
],
),
);
}
}
class _SessionDebugCard extends StatelessWidget {
final dynamic user;
const _SessionDebugCard({required this.user});
@override
Widget build(BuildContext context) {
final token = user?.token ?? '';
final tokenPreview =
token.length > 40 ? '${token.substring(0, 40)}' : token;
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: const Color(0xFFF3E5F5),
borderRadius: BorderRadius.circular(10),
border: Border.all(color: const Color(0xFFCE93D8), width: 1),
),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
const Row( Row(children: const [Icon(Icons.campaign, color: Colors.orange, size: 22), SizedBox(width: 8), Text('Recuerda siempre', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown, fontSize: 14))]),
children: [ const SizedBox(height: 12),
Icon(Icons.developer_mode_rounded, _buildBulletRow(Icons.delete_outline, 'Saca la basura SOLO cuando recibas la alerta de "próxima llegada".'),
size: 14, color: Color(0xFF7B1FA2)), const SizedBox(height: 8),
SizedBox(width: 6), _buildBulletRow(Icons.block, 'Nunca persigas ni te acerques al camión. El sistema te avisará a tiempo.'),
Text( const SizedBox(height: 8),
'Debug — Sesión JWT (solo MVP)', _buildBulletRow(Icons.eco_outlined, 'Separar tus residuos hace más eficiente la recolección. ¡Gracias!'),
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: Color(0xFF7B1FA2),
),
),
], ],
), ),
const SizedBox(height: 6),
Text(
'Token: $tokenPreview',
style: const TextStyle(
fontSize: 10.5,
fontFamily: 'monospace',
color: Color(0xFF4A148C),
),
),
Text(
'Role: ${user?.role} | Expira: ${user?.expiresAt?.toLocal().toString().substring(0, 16)}',
style: const TextStyle(
fontSize: 10.5,
fontFamily: 'monospace',
color: Color(0xFF4A148C),
),
), ),
const SizedBox(height: 20),
], ],
), ),
),
); );
} }
Widget _buildBulletRow(IconData icon, String text) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 16, color: Colors.brown.shade700),
const SizedBox(width: 10),
Expanded(child: Text(text, style: TextStyle(fontSize: 13, color: Colors.brown.shade900, height: 1.2))),
],
);
}
}
// =========================================================================
// 📍 MODELO 1: Catálogo de Colonias
// =========================================================================
class ColoniaModel {
String colonia;
String routeId;
String horarioEstimado;
ColoniaModel({required this.colonia, required this.routeId, required this.horarioEstimado});
factory ColoniaModel.fromJson(Map<String, dynamic> json) => ColoniaModel(colonia: json['colonia'], routeId: json['routeId'], horarioEstimado: json['horarioEstimado']);
Map<String, dynamic> toJson() => {'colonia': colonia, 'routeId': routeId, 'horarioEstimado': horarioEstimado};
}
// =========================================================================
// 📍 MODELO 2: Sistema de Notificaciones Alertas Push
// =========================================================================
class NotificationModel {
String triggerEvent;
String condition;
PushPayloadModel pushPayload;
NotificationModel({required this.triggerEvent, required this.condition, required this.pushPayload});
factory NotificationModel.fromJson(Map<String, dynamic> json) => NotificationModel(triggerEvent: json['triggerEvent'], condition: json['condition'], pushPayload: PushPayloadModel.fromJson(json['pushPayload']));
Map<String, dynamic> toJson() => {'triggerEvent': triggerEvent, 'condition': condition, 'pushPayload': pushPayload.toJson()};
}
class PushPayloadModel {
String title;
String body;
PushPayloadModel({required this.title, required this.body});
factory PushPayloadModel.fromJson(Map<String, dynamic> json) => PushPayloadModel(title: json['title'], body: json['body']);
Map<String, dynamic> toJson() => {'title': title, 'body': body};
} }

View File

@@ -1,11 +1,12 @@
import 'home_screen_placeholder.dart'; // 📍 Ajusta las carpetas '../' según la ubicación exacta en tu proyecto
import '../../../../core/network/mysql_service.dart'; // 📍 Ajusta las carpetas '../' según tu proyecto
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import '../../../../core/router/app_router.dart'; // 📍 Importación de rutas verificada import '../../../../core/router/app_router.dart';
import '../../../../core/theme/app_theme.dart'; import '../../../../core/theme/app_theme.dart';
import '../bloc/auth_bloc.dart'; import '../bloc/auth_bloc.dart';
import '../bloc/auth_event.dart';
import '../bloc/auth_state.dart'; import '../bloc/auth_state.dart';
import '../widgets/privacy_notice_card.dart'; import '../widgets/privacy_notice_card.dart';
@@ -19,8 +20,10 @@ class LoginScreen extends StatefulWidget {
class _LoginScreenState extends State<LoginScreen> class _LoginScreenState extends State<LoginScreen>
with SingleTickerProviderStateMixin { with SingleTickerProviderStateMixin {
final _formKey = GlobalKey<FormState>(); final _formKey = GlobalKey<FormState>();
final _identifierController = TextEditingController(); final _identifierController =
final _passwordController = TextEditingController(); TextEditingController(); // Controlador para el correo
final _passwordController =
TextEditingController(); // Controlador para la contraseña
bool _obscurePassword = true; bool _obscurePassword = true;
@@ -50,16 +53,75 @@ class _LoginScreenState extends State<LoginScreen>
super.dispose(); super.dispose();
} }
void _submit(BuildContext context) { // 📍 CONSULTA REAL SELECT A TU TABLA DE MYSQL
void _submit(BuildContext context) async {
if (_formKey.currentState?.validate() ?? false) { if (_formKey.currentState?.validate() ?? false) {
context.read<AuthBloc>().add( try {
AuthLoginRequested( ScaffoldMessenger.of(context).showSnackBar(
identifier: _identifierController.text.trim(), const SnackBar(
password: _passwordController.text, content: Text('Validando credenciales en MySQL Celaya...')),
);
// 1. Obtener la conexión por el cable USB Mapped
// 1. Obtener la conexión
final conn = await MySqlService().getConnection();
// 2. Modificamos el SELECT para traer también la columna 'colonia'
final result = await conn.execute(
"SELECT email, contrasena_hash, rol, colonia FROM usuarios WHERE email = :email",
{
"email": _identifierController.text.trim(),
},
);
if (!mounted) return;
if (result.rows.isNotEmpty) {
final usuarioEncontrado = result.rows.first.assoc();
final contrasenaEnBd = usuarioEncontrado['contrasena_hash'];
final email = usuarioEncontrado['email'];
final rol = usuarioEncontrado['rol'];
final colonia = usuarioEncontrado[
'colonia']; // 📍 Extraemos la colonia real de la BD
if (contrasenaEnBd?.trim() == _passwordController.text.trim()) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("¡Bienvenido de nuevo, $email ($rol)!")),
);
// 📍 Enviamos la colonia real extraída de MySQL directamente a la URL del Home
context.go('/home?colonia=$colonia');
} else {
// Contraseña mal mapeada en la BD
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Contraseña incorrecta para este usuario'),
backgroundColor: Colors.orange),
);
}
} else {
// El correo de plano no existe en MySQL Workbench
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('El correo electrónico no está registrado'),
backgroundColor: Colors.orange),
);
}
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
"Error al conectar con MySQL: $e"), // 📍 CORREGIDO: Sin contra-barra para que pinte el error real
backgroundColor: Colors.red,
duration: const Duration(seconds: 5),
), ),
); );
} }
} }
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -135,15 +197,11 @@ class _LoginScreenState extends State<LoginScreen>
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: const [ children: const [
Text( Text('Bienvenido a WasteNotify',
'Bienvenido a WasteNotify', style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold)),
style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
),
SizedBox(height: 8), SizedBox(height: 8),
Text( Text('Inicia sesión para continuar',
'Inicia sesión para continuar', style: TextStyle(fontSize: 14, color: Colors.grey)),
style: TextStyle(fontSize: 14, color: Colors.grey),
),
], ],
); );
} }
@@ -252,8 +310,8 @@ class _LoginScreenState extends State<LoginScreen>
], ],
), ),
); );
} } // 📍 Cierre de la función _buildForm
// Placeholders para evitar errores si no están definidos // Placeholders para evitar errores si no están definidos
Widget _buildDemoHint() => const SizedBox.shrink(); Widget _buildDemoHint() => const SizedBox.shrink();
} } // 📍 Cierre de la clase _LoginScreenState

View File

@@ -1,3 +1,5 @@
import 'dart:math'; //
import '../../../../core/network/mysql_service.dart'; // 📍 Ajusta las carpetas '../' según tu proyecto
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:flutter_application_1/features/auth/data/models/mock_waste_data.dart'; import 'package:flutter_application_1/features/auth/data/models/mock_waste_data.dart';
@@ -11,20 +13,18 @@ class RegisterScreen extends StatefulWidget {
class _RegisterScreenState extends State<RegisterScreen> { class _RegisterScreenState extends State<RegisterScreen> {
final _formKey = GlobalKey<FormState>(); final _formKey = GlobalKey<FormState>();
late String _selectedColonia; // 📍 Se mantiene late pero se inicializa abajo late String _selectedColonia;
final _nameController = TextEditingController(); final _nameController = TextEditingController();
final _emailController = TextEditingController(); final _emailController = TextEditingController();
final _passwordController = TextEditingController(); final _passwordController = TextEditingController();
// 📍 CORRECCIÓN CRÍTICA: Asignar el valor inicial antes del método build
@override @override
void initState() { void initState() {
super.initState(); super.initState();
if (MockWasteData.schedules.isNotEmpty) { if (MockWasteData.schedules.isNotEmpty) {
// Evita problemas de aserción tomando el primer valor real de tus mocks
_selectedColonia = MockWasteData.schedules.first.colonia; _selectedColonia = MockWasteData.schedules.first.colonia;
} else { } else {
_selectedColonia = ''; // Respaldo por si la lista estuviera vacía _selectedColonia = '';
} }
} }
@@ -47,7 +47,8 @@ class _RegisterScreenState extends State<RegisterScreen> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
const Icon(Icons.assignment_ind_outlined, size: 80, color: Colors.green), const Icon(Icons.assignment_ind_outlined,
size: 80, color: Colors.green),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
'Regístrate para recibir avisos de recolección en tu zona', 'Regístrate para recibir avisos de recolección en tu zona',
@@ -57,63 +58,133 @@ class _RegisterScreenState extends State<RegisterScreen> {
const SizedBox(height: 24), const SizedBox(height: 24),
TextFormField( TextFormField(
controller: _nameController, controller: _nameController,
decoration: const InputDecoration(labelText: 'Nombre Completo', border: OutlineInputBorder()), decoration: const InputDecoration(
validator: (v) => v == null || v.isEmpty ? 'Ingresa tu nombre' : null, labelText: 'Nombre Completo',
border: OutlineInputBorder()),
validator: (v) =>
v == null || v.isEmpty ? 'Ingresa tu nombre' : null,
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
TextFormField( TextFormField(
controller: _emailController, controller: _emailController,
decoration: const InputDecoration(labelText: 'Correo o Teléfono', border: OutlineInputBorder()), decoration: const InputDecoration(
validator: (v) => v == null || v.isEmpty ? 'Ingresa tus datos' : null, labelText: 'Correo o Teléfono',
border: OutlineInputBorder()),
validator: (v) =>
v == null || v.isEmpty ? 'Ingresa tus datos' : null,
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
TextFormField( TextFormField(
controller: _passwordController, controller: _passwordController,
obscureText: true, obscureText: true,
decoration: const InputDecoration(labelText: 'Contraseña', border: OutlineInputBorder()), decoration: const InputDecoration(
validator: (v) => v == null || v.length < 6 ? 'Mínimo 6 caracteres' : null, labelText: 'Contraseña', border: OutlineInputBorder()),
validator: (v) =>
v == null || v.length < 6 ? 'Mínimo 6 caracteres' : null,
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
// Dropdown para seleccionar la Colonia
DropdownButtonFormField<String>( DropdownButtonFormField<String>(
value: _selectedColonia, value: _selectedColonia,
decoration: const InputDecoration(labelText: 'Selecciona tu Colonia / Domicilio', border: OutlineInputBorder()), decoration: const InputDecoration(
labelText: 'Selecciona tu Colonia / Domicilio',
border: OutlineInputBorder()),
items: MockWasteData.schedules.map((zone) { items: MockWasteData.schedules.map((zone) {
return DropdownMenuItem(value: zone.colonia, child: Text(zone.colonia)); return DropdownMenuItem(
value: zone.colonia, child: Text(zone.colonia));
}).toList(), }).toList(),
onChanged: (val) => setState(() => _selectedColonia = val!), onChanged: (val) => setState(() => _selectedColonia = val!),
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
// Mensajería Preventiva Legal
Card( Card(
color: Colors.amber.shade50, color: Colors.amber.shade50,
child: Padding( child: Padding(
padding: const EdgeInsets.all(12.0), padding: const EdgeInsets.all(12.0),
child: Text( child: Text(
'🔒 Privacidad Garantizada:\nAl registrar tu domicilio, tu cuenta operará bajo el principio de "Visión de Túnel". Solo verás alertas de tu sector. Está prohibido el rastreo de flotillas.', '🔒 Privacidad Garantizada:\nAl registrar tu domicilio, tu cuenta operará bajo el principio de "Visión de Túnel". Solo verás alertas de tu sector. Está prohibido el rastreo de flotillas.',
style: TextStyle(color: Colors.amber.shade900, fontSize: 13, fontWeight: FontWeight.bold), style: TextStyle(
color: Colors.amber.shade900,
fontSize: 13,
fontWeight: FontWeight.bold),
), ),
), ),
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
ElevatedButton( ElevatedButton(
style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16), backgroundColor: Colors.green), style: ElevatedButton.styleFrom(
onPressed: () { padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.green),
onPressed: () async {
if (_formKey.currentState!.validate()) { if (_formKey.currentState!.validate()) {
try {
print(
'=== DEPURACIÓN: Iniciando proceso de registro ===');
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Cuenta creada con éxito (Modo Simulación)')), const SnackBar(
content: Text(
'Conectando con la base de datos local...')),
);
final conn = await MySqlService().getConnection();
print(
'=== DEPURACIÓN: ¡Conexión obtenida! Estado connected: ${conn.connected}');
print('=== DEPURACIÓN: Intentando ejecutar INSERT ===');
final randomPhone =
'461${1000000 + Random().nextInt(9000000)}'; // 📍 ENVIANDO LA COLONIA REAL A TU NUEVA COLUMNA DE MYSQL
final result = await conn.execute(
"INSERT INTO usuarios (email, telefono, contrasena_hash, rol, is_verified, colonia) VALUES (:email, :telefono, :contrasena_hash, :rol, :is_verified, :colonia)",
{
"email": _emailController.text.trim(),
"telefono": randomPhone, // 📍 Genera un teléfono simulado para cumplir con el esquema de tu tabla
"contrasena_hash": _passwordController.text,
"rol": "Ciudadano",
"is_verified": 1,
"colonia":
_selectedColonia, // 📍 Envía la colonia seleccionada en el Dropdown
},
);
print(
'=== DEPURACIÓN: INSERT completado. Filas afectadas: ${result.affectedRows}');
if (!mounted) return;
if (result.affectedRows > BigInt.zero) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'¡Usuario guardado con éxito en MySQL Celaya!')),
); );
context.go('/home?colonia=$_selectedColonia'); context.go('/home?colonia=$_selectedColonia');
} else {
print(
'=== DEPURACIÓN: El query se ejecutó pero devolvió 0 filas afectadas ===');
}
} catch (e, stacktrace) {
print(
'=== DEPURACIÓN: ¡CAPTURADO UN ERROR EN EL CATCH! ===');
print('Detalle del error: $e');
print(
'Ubicación del fallo (Stacktrace): \n$stacktrace');
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error de conexión a MySQL: $e'),
backgroundColor: Colors.red,
duration: const Duration(seconds: 5),
),
);
}
} }
}, },
child: const Text('Registrarse', style: TextStyle(color: Colors.white, fontSize: 16)), child: const Text('Registrarse',
style: TextStyle(color: Colors.white, fontSize: 16)),
), ),
], ],
), ),
), ),
), ));
);
} }
} }

View File

@@ -33,30 +33,46 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.1" version: "2.1.1"
buffer:
dependency: transitive
description:
name: buffer
sha256: "389da2ec2c16283c8787e0adaede82b1842102f8c8aae2f49003a766c5c6b3d1"
url: "https://pub.dev"
source: hosted
version: "1.2.3"
characters: characters:
dependency: transitive dependency: transitive
description: description:
name: characters name: characters
sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.4.1" version: "1.3.0"
clock: clock:
dependency: transitive dependency: transitive
description: description:
name: clock name: clock
sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.2" version: "1.1.1"
collection: collection:
dependency: transitive dependency: transitive
description: description:
name: collection name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.19.1" version: "1.19.0"
crypto:
dependency: transitive
description:
name: crypto
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
url: "https://pub.dev"
source: hosted
version: "3.0.7"
cupertino_icons: cupertino_icons:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -85,10 +101,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: fake_async name: fake_async
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.3.3" version: "1.3.1"
ffi: ffi:
dependency: transitive dependency: transitive
description: description:
@@ -220,26 +236,26 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker name: leak_tracker
sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" sha256: "7bb2830ebd849694d1ec25bf1f44582d6ac531a57a365a803a6034ff751d2d06"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "11.0.2" version: "10.0.7"
leak_tracker_flutter_testing: leak_tracker_flutter_testing:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker_flutter_testing name: leak_tracker_flutter_testing
sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" sha256: "9491a714cca3667b60b5c420da8217e6de0d1ba7a5ec322fab01758f6998f379"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.10" version: "3.0.8"
leak_tracker_testing: leak_tracker_testing:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker_testing name: leak_tracker_testing
sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.2" version: "3.0.1"
lints: lints:
dependency: transitive dependency: transitive
description: description:
@@ -276,26 +292,26 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: matcher name: matcher
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.12.19" version: "0.12.16+1"
material_color_utilities: material_color_utilities:
dependency: transitive dependency: transitive
description: description:
name: material_color_utilities name: material_color_utilities
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.13.0" version: "0.11.1"
meta: meta:
dependency: transitive dependency: transitive
description: description:
name: meta name: meta
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.18.0" version: "1.15.0"
mgrs_dart: mgrs_dart:
dependency: transitive dependency: transitive
description: description:
@@ -304,6 +320,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.0" version: "2.0.0"
mysql_client:
dependency: "direct main"
description:
name: mysql_client
sha256: "6a0fdcbe3e0721c637f97ad24649be2f70dbce2b21ede8f962910e640f753fc2"
url: "https://pub.dev"
source: hosted
version: "0.0.27"
nested: nested:
dependency: transitive dependency: transitive
description: description:
@@ -316,10 +340,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: path name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.9.1" version: "1.9.0"
path_provider_linux: path_provider_linux:
dependency: transitive dependency: transitive
description: description:
@@ -465,18 +489,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: stack_trace name: stack_trace
sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" sha256: "9f47fd3630d76be3ab26f0ee06d213679aa425996925ff3feffdec504931c377"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.12.1" version: "1.12.0"
stream_channel: stream_channel:
dependency: transitive dependency: transitive
description: description:
name: stream_channel name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.4" version: "2.1.2"
string_scanner: string_scanner:
dependency: transitive dependency: transitive
description: description:
@@ -497,10 +521,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: test_api name: test_api
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" sha256: "664d3a9a64782fcdeb83ce9c6b39e78fd2971d4e37827b9b06c3aa1edc5e760c"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.11" version: "0.7.3"
timezone: timezone:
dependency: transitive dependency: transitive
description: description:
@@ -509,6 +533,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.10.1" version: "0.10.1"
tuple:
dependency: transitive
description:
name: tuple
sha256: a97ce2013f240b2f3807bcbaf218765b6f301c3eff91092bcfa23a039e7dd151
url: "https://pub.dev"
source: hosted
version: "2.0.2"
typed_data: typed_data:
dependency: transitive dependency: transitive
description: description:
@@ -529,10 +561,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: vector_math name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.2.0" version: "2.1.4"
vm_service: vm_service:
dependency: transitive dependency: transitive
description: description:
@@ -574,5 +606,5 @@ packages:
source: hosted source: hosted
version: "6.5.0" version: "6.5.0"
sdks: sdks:
dart: ">=3.10.0-0 <4.0.0" dart: ">=3.6.0 <4.0.0"
flutter: ">=3.27.0" flutter: ">=3.27.0"

View File

@@ -32,6 +32,7 @@ dependencies:
flutter_map: ^6.2.1 flutter_map: ^6.2.1
latlong2: ^0.9.1 latlong2: ^0.9.1
flutter_local_notifications: ^19.5.0 flutter_local_notifications: ^19.5.0
mysql_client: ^0.0.27