diff --git a/lib/core/network/mysql_service.dart b/lib/core/network/mysql_service.dart new file mode 100644 index 0000000..a86da5b --- /dev/null +++ b/lib/core/network/mysql_service.dart @@ -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 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 closeConnection() async { + if (_connection != null && _connection!.connected) { + await _connection!.close(); + _connection = null; + } + } +} diff --git a/lib/features/auth/presentation/screens/login_screen.dart b/lib/features/auth/presentation/screens/login_screen.dart index 808bf71..46d31a5 100644 --- a/lib/features/auth/presentation/screens/login_screen.dart +++ b/lib/features/auth/presentation/screens/login_screen.dart @@ -16,7 +16,8 @@ class LoginScreen extends StatefulWidget { State createState() => _LoginScreenState(); } -class _LoginScreenState extends State with SingleTickerProviderStateMixin { +class _LoginScreenState extends State + with SingleTickerProviderStateMixin { final _formKey = GlobalKey(); final _identifierController = TextEditingController(); final _passwordController = TextEditingController(); @@ -251,8 +252,8 @@ class _LoginScreenState extends State with SingleTickerProviderStat ], ), ); - } + } // 📍 Cierre de la función _buildForm // Placeholders para evitar errores si no están definidos Widget _buildDemoHint() => const SizedBox.shrink(); -} +} // 📍 diff --git a/lib/features/auth/presentation/screens/register_screen.dart b/lib/features/auth/presentation/screens/register_screen.dart index 8b01016..0a55b4e 100644 --- a/lib/features/auth/presentation/screens/register_screen.dart +++ b/lib/features/auth/presentation/screens/register_screen.dart @@ -1,3 +1,4 @@ +import '../../../../core/network/mysql_service.dart'; // 📍 Ajusta las carpetas '../' según tu proyecto import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:flutter_application_1/features/auth/data/models/mock_waste_data.dart'; @@ -11,20 +12,18 @@ class RegisterScreen extends StatefulWidget { class _RegisterScreenState extends State { final _formKey = GlobalKey(); - late String _selectedColonia; // 📍 Se mantiene late pero se inicializa abajo + late String _selectedColonia; final _nameController = TextEditingController(); final _emailController = TextEditingController(); final _passwordController = TextEditingController(); - // 📍 CORRECCIÓN CRÍTICA: Asignar el valor inicial antes del método build @override void initState() { super.initState(); if (MockWasteData.schedules.isNotEmpty) { - // Evita problemas de aserción tomando el primer valor real de tus mocks _selectedColonia = MockWasteData.schedules.first.colonia; } else { - _selectedColonia = ''; // Respaldo por si la lista estuviera vacía + _selectedColonia = ''; } } @@ -39,81 +38,149 @@ class _RegisterScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar(title: const Text('Crear Cuenta Ciudadana')), - body: SingleChildScrollView( - padding: const EdgeInsets.all(24.0), - child: Form( - key: _formKey, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const Icon(Icons.assignment_ind_outlined, size: 80, color: Colors.green), - const SizedBox(height: 16), - Text( - 'Regístrate para recibir avisos de recolección en tu zona', - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodyLarge, - ), - const SizedBox(height: 24), - TextFormField( - controller: _nameController, - decoration: const InputDecoration(labelText: 'Nombre Completo', border: OutlineInputBorder()), - validator: (v) => v == null || v.isEmpty ? 'Ingresa tu nombre' : null, - ), - const SizedBox(height: 16), - TextFormField( - controller: _emailController, - decoration: const InputDecoration(labelText: 'Correo o Teléfono', border: OutlineInputBorder()), - validator: (v) => v == null || v.isEmpty ? 'Ingresa tus datos' : null, - ), - const SizedBox(height: 16), - TextFormField( - controller: _passwordController, - obscureText: true, - decoration: const InputDecoration(labelText: 'Contraseña', border: OutlineInputBorder()), - validator: (v) => v == null || v.length < 6 ? 'Mínimo 6 caracteres' : null, - ), - const SizedBox(height: 16), - - // Dropdown para seleccionar la Colonia - DropdownButtonFormField( - value: _selectedColonia, - decoration: const InputDecoration(labelText: 'Selecciona tu Colonia / Domicilio', border: OutlineInputBorder()), - items: MockWasteData.schedules.map((zone) { - return DropdownMenuItem(value: zone.colonia, child: Text(zone.colonia)); - }).toList(), - onChanged: (val) => setState(() => _selectedColonia = val!), - ), - const SizedBox(height: 24), - - // Mensajería Preventiva Legal - Card( - color: Colors.amber.shade50, - child: Padding( - padding: const EdgeInsets.all(12.0), - 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.', - style: TextStyle(color: Colors.amber.shade900, fontSize: 13, fontWeight: FontWeight.bold), + appBar: AppBar(title: const Text('Crear Cuenta Ciudadana')), + body: SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Icon(Icons.assignment_ind_outlined, + size: 80, color: Colors.green), + const SizedBox(height: 16), + Text( + 'Regístrate para recibir avisos de recolección en tu zona', + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyLarge, + ), + const SizedBox(height: 24), + TextFormField( + controller: _nameController, + decoration: const InputDecoration( + labelText: 'Nombre Completo', + border: OutlineInputBorder()), + validator: (v) => + v == null || v.isEmpty ? 'Ingresa tu nombre' : null, + ), + const SizedBox(height: 16), + TextFormField( + controller: _emailController, + decoration: const InputDecoration( + labelText: 'Correo o Teléfono', + border: OutlineInputBorder()), + validator: (v) => + v == null || v.isEmpty ? 'Ingresa tus datos' : null, + ), + const SizedBox(height: 16), + TextFormField( + controller: _passwordController, + obscureText: true, + decoration: const InputDecoration( + labelText: 'Contraseña', border: OutlineInputBorder()), + validator: (v) => + v == null || v.length < 6 ? 'Mínimo 6 caracteres' : null, + ), + const SizedBox(height: 16), + DropdownButtonFormField( + value: _selectedColonia, + decoration: const InputDecoration( + labelText: 'Selecciona tu Colonia / Domicilio', + border: OutlineInputBorder()), + items: MockWasteData.schedules.map((zone) { + return DropdownMenuItem( + value: zone.colonia, child: Text(zone.colonia)); + }).toList(), + onChanged: (val) => setState(() => _selectedColonia = val!), + ), + const SizedBox(height: 24), + Card( + color: Colors.amber.shade50, + child: Padding( + padding: const EdgeInsets.all(12.0), + 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.', + style: TextStyle( + color: Colors.amber.shade900, + fontSize: 13, + fontWeight: FontWeight.bold), + ), ), ), - ), - const SizedBox(height: 24), - ElevatedButton( - style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16), backgroundColor: Colors.green), - onPressed: () { - if (_formKey.currentState!.validate()) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Cuenta creada con éxito (Modo Simulación)')), - ); - context.go('/home?colonia=$_selectedColonia'); - } - }, - child: const Text('Registrarse', style: TextStyle(color: Colors.white, fontSize: 16)), - ), - ], + const SizedBox(height: 24), + ElevatedButton( + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 16), + backgroundColor: Colors.green), + onPressed: () async { + if (_formKey.currentState!.validate()) { + try { + print( + '=== DEPURACIÓN: Iniciando proceso de registro ==='); + + ScaffoldMessenger.of(context).showSnackBar( + 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 result = await conn.execute( + "INSERT INTO usuarios (email, telefono, contrasena_hash, rol, is_verified) VALUES (:email, :telefono, :contrasena_hash, :rol, :is_verified)", + { + "email": _emailController.text.trim(), + "telefono": "4611234567", + "contrasena_hash": _passwordController.text, + "rol": + "Ciudadano", // 📍 CORRECCIÓN: Cambia "ciudadano" por "Ciudadano" (con mayúscula) + "is_verified": 1, + }, + ); + + 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'); + } 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)), + ), + ], + ), ), - ), - ), - ); + )); } } diff --git a/pubspec.lock b/pubspec.lock index dbb28a7..6832470 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -33,30 +33,46 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.1" + buffer: + dependency: transitive + description: + name: buffer + sha256: "389da2ec2c16283c8787e0adaede82b1842102f8c8aae2f49003a766c5c6b3d1" + url: "https://pub.dev" + source: hosted + version: "1.2.3" characters: dependency: transitive description: name: characters - sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" url: "https://pub.dev" source: hosted - version: "1.4.1" + version: "1.3.0" clock: dependency: transitive description: name: clock - sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf url: "https://pub.dev" source: hosted - version: "1.1.2" + version: "1.1.1" collection: dependency: transitive description: name: collection - sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf url: "https://pub.dev" 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: dependency: "direct main" description: @@ -85,10 +101,10 @@ packages: dependency: transitive description: name: fake_async - sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" url: "https://pub.dev" source: hosted - version: "1.3.3" + version: "1.3.1" ffi: dependency: transitive description: @@ -220,26 +236,26 @@ packages: dependency: transitive description: name: leak_tracker - sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + sha256: "7bb2830ebd849694d1ec25bf1f44582d6ac531a57a365a803a6034ff751d2d06" url: "https://pub.dev" source: hosted - version: "11.0.2" + version: "10.0.7" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + sha256: "9491a714cca3667b60b5c420da8217e6de0d1ba7a5ec322fab01758f6998f379" url: "https://pub.dev" source: hosted - version: "3.0.10" + version: "3.0.8" leak_tracker_testing: dependency: transitive description: name: leak_tracker_testing - sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" url: "https://pub.dev" source: hosted - version: "3.0.2" + version: "3.0.1" lints: dependency: transitive description: @@ -276,26 +292,26 @@ packages: dependency: transitive description: name: matcher - sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb url: "https://pub.dev" source: hosted - version: "0.12.19" + version: "0.12.16+1" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec url: "https://pub.dev" source: hosted - version: "0.13.0" + version: "0.11.1" meta: dependency: transitive description: name: meta - sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" + sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7 url: "https://pub.dev" source: hosted - version: "1.18.0" + version: "1.15.0" mgrs_dart: dependency: transitive description: @@ -304,6 +320,14 @@ packages: url: "https://pub.dev" source: hosted 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: dependency: transitive description: @@ -316,10 +340,10 @@ packages: dependency: transitive description: name: path - sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" url: "https://pub.dev" source: hosted - version: "1.9.1" + version: "1.9.0" path_provider_linux: dependency: transitive description: @@ -465,18 +489,18 @@ packages: dependency: transitive description: name: stack_trace - sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + sha256: "9f47fd3630d76be3ab26f0ee06d213679aa425996925ff3feffdec504931c377" url: "https://pub.dev" source: hosted - version: "1.12.1" + version: "1.12.0" stream_channel: dependency: transitive description: name: stream_channel - sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 url: "https://pub.dev" source: hosted - version: "2.1.4" + version: "2.1.2" string_scanner: dependency: transitive description: @@ -497,10 +521,10 @@ packages: dependency: transitive description: name: test_api - sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" + sha256: "664d3a9a64782fcdeb83ce9c6b39e78fd2971d4e37827b9b06c3aa1edc5e760c" url: "https://pub.dev" source: hosted - version: "0.7.11" + version: "0.7.3" timezone: dependency: transitive description: @@ -509,6 +533,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.10.1" + tuple: + dependency: transitive + description: + name: tuple + sha256: a97ce2013f240b2f3807bcbaf218765b6f301c3eff91092bcfa23a039e7dd151 + url: "https://pub.dev" + source: hosted + version: "2.0.2" typed_data: dependency: transitive description: @@ -529,10 +561,10 @@ packages: dependency: transitive description: name: vector_math - sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.1.4" vm_service: dependency: transitive description: @@ -574,5 +606,5 @@ packages: source: hosted version: "6.5.0" sdks: - dart: ">=3.10.0-0 <4.0.0" + dart: ">=3.6.0 <4.0.0" flutter: ">=3.27.0" diff --git a/pubspec.yaml b/pubspec.yaml index 491a838..8d8bbe2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -32,6 +32,7 @@ dependencies: flutter_map: ^6.2.1 latlong2: ^0.9.1 flutter_local_notifications: ^19.5.0 + mysql_client: ^0.0.27