diff --git a/lib/app.dart b/lib/app.dart index 3bd243c..5d4fab1 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -3,6 +3,8 @@ import 'package:provider/provider.dart'; import 'providers/app_provider.dart'; import 'theme/app_theme.dart'; import 'screens/login/login_screen.dart'; +import 'screens/login/registro_screen.dart'; +import 'screens/login/registro_cloud_screen.dart'; import 'screens/main_shell.dart'; class PedidosApp extends StatelessWidget { @@ -17,6 +19,11 @@ class PedidosApp extends StatelessWidget { debugShowCheckedModeBanner: false, theme: AppTheme.light, navigatorKey: navigatorKey, + routes: { + '/login': (_) => const LoginScreen(), + '/registro': (_) => const RegistroScreen(), + '/registro_cloud': (_) => const RegistroCloudScreen(), + }, home: Consumer( builder: (_, provider, __) { if (provider.loading) return const _LoadingScreen(); diff --git a/lib/screens/login/login_screen.dart b/lib/screens/login/login_screen.dart index 38e66a5..64f9a49 100644 --- a/lib/screens/login/login_screen.dart +++ b/lib/screens/login/login_screen.dart @@ -1,7 +1,16 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../../providers/app_provider.dart'; -import '../../theme/app_theme.dart'; + +// Paleta exclusiva de pantallas de autenticación (spec estructura_login.md §7) +const _kBg = Color(0xFF0A1E3C); +const _kTopBar = Color(0xFF0D2D6B); +const _kPanel = Color(0xFF0F2A4A); +const _kCard = Color(0xFF163558); +const _kBorder = Color(0xFF1E4070); +const _kAccent = Color(0xFF1976D2); +const _kTextMuted = Color(0xFFAABBCC); +const _kError = Color(0xFFFF6B6B); class LoginScreen extends StatefulWidget { const LoginScreen({Key? key}) : super(key: key); @@ -10,240 +19,533 @@ class LoginScreen extends StatefulWidget { State createState() => _LoginScreenState(); } -class _LoginScreenState extends State { - final _emailCtrl = TextEditingController(text: 'admin@telcotronics.com'); - final _passCtrl = TextEditingController(text: 'Microbot%'); - bool _obscure = true; - bool _loading = false; - String? _error; +class _LoginScreenState extends State + with SingleTickerProviderStateMixin { + final _formKey = GlobalKey(); + final _emailCtrl = TextEditingController(); + final _passCtrl = TextEditingController(); + + bool _obscure = true; + bool _rememberMe = true; + bool _modoCloud = true; + + late final AnimationController _toggleAnim; + late final Animation _toggleSlide; + + @override + void initState() { + super.initState(); + _toggleAnim = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 240), + value: 1.0, // arranca en Cloud (posición derecha) + ); + _toggleSlide = CurvedAnimation( + parent: _toggleAnim, curve: Curves.easeInOut); + } @override void dispose() { _emailCtrl.dispose(); _passCtrl.dispose(); + _toggleAnim.dispose(); super.dispose(); } - Future _login() async { - setState(() { _loading = true; _error = null; }); - final ok = await context.read().login( - _emailCtrl.text.trim(), _passCtrl.text); - if (!ok && mounted) { - setState(() { - _loading = false; - _error = context.read().loginError; - }); + void _switchModo(bool cloud) { + if (_modoCloud == cloud) return; + setState(() => _modoCloud = cloud); + if (cloud) { + _toggleAnim.forward(); + } else { + _toggleAnim.reverse(); } } + Future _ingresar() async { + if (!(_formKey.currentState?.validate() ?? false)) return; + final provider = context.read(); + if (_modoCloud) { + await provider.login( + _emailCtrl.text.trim(), + _passCtrl.text, + rememberMe: _rememberMe, + ); + } else { + await provider.loginLocal( + _emailCtrl.text.trim(), + _passCtrl.text, + rememberMe: _rememberMe, + ); + } + // Si ok, el Consumer en main.dart navega a HomeScreen automáticamente + } + @override Widget build(BuildContext context) { + final provider = context.watch(); return Scaffold( - body: Container( - decoration: const BoxDecoration( - gradient: LinearGradient( - colors: [Color(0xFF1E3A8A), Color(0xFF1E40AF), Color(0xFF2563EB)], - begin: Alignment.topLeft, - end: Alignment.bottomRight, - ), - ), - child: SafeArea( - child: Center( - child: SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 28), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - _buildLogo(), - const SizedBox(height: 40), - _buildCard(), - const SizedBox(height: 24), - _buildVersion(), - ], + backgroundColor: _kBg, + body: Stack( + children: [ + // Degradado superior + Container( + height: MediaQuery.of(context).size.height * 0.44, + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [_kTopBar, _kBg], + begin: Alignment.topCenter, + end: Alignment.bottomCenter, ), ), ), + SafeArea( + child: Column( + children: [ + Expanded(child: _buildLogoZone()), + _buildFormPanel(provider), + ], + ), + ), + ], + ), + ); + } + + // ── Zona logo ──────────────────────────────────────────────── + + Widget _buildLogoZone() { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 80, + height: 80, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.38), + blurRadius: 18, + offset: const Offset(0, 7), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(20), + child: Image.asset( + 'assets/icon/icon.png', + fit: BoxFit.cover, + errorBuilder: (_, __, ___) => Container( + color: _kAccent, + child: const Icon(Icons.storefront, + size: 40, color: Colors.white), + ), + ), + ), + ), + const SizedBox(height: 16), + const Text( + 'AGENTE VENTAS', + style: TextStyle( + color: Colors.white, + fontSize: 22, + fontWeight: FontWeight.bold, + letterSpacing: 5, + ), + ), + const SizedBox(height: 5), + const Text( + 'SIGMAC · Telcotronics', + style: TextStyle( + color: _kTextMuted, + fontSize: 12, + letterSpacing: 2, + ), + ), + ], + ), + ); + } + + // ── Panel formulario ───────────────────────────────────────── + + Widget _buildFormPanel(AppProvider provider) { + return Container( + decoration: const BoxDecoration( + color: _kPanel, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(32), + topRight: Radius.circular(32), + ), + ), + padding: const EdgeInsets.fromLTRB(24, 28, 24, 36), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + const Text( + 'Bienvenido', + style: TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 3), + const Text( + 'Ingresa tus credenciales para continuar', + style: TextStyle(color: _kTextMuted, fontSize: 13), + ), + const SizedBox(height: 20), + _buildToggle(), + const SizedBox(height: 18), + _buildField( + controller: _emailCtrl, + label: _modoCloud ? 'Correo electrónico' : 'Usuario', + icon: _modoCloud ? Icons.email_outlined : Icons.person_outline, + keyboardType: _modoCloud + ? TextInputType.emailAddress + : TextInputType.text, + validator: _modoCloud + ? (v) { + if (v == null || v.trim().isEmpty) return 'Ingresa tu correo'; + if (!v.contains('@') || !v.contains('.')) { + return 'Correo inválido'; + } + return null; + } + : (v) { + if (v == null || v.trim().isEmpty) return 'Ingresa tu usuario'; + return null; + }, + ), + const SizedBox(height: 13), + _buildField( + controller: _passCtrl, + label: 'Contraseña', + icon: Icons.lock_outline, + obscure: _obscure, + suffix: IconButton( + icon: Icon( + _obscure + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + color: _kTextMuted, + size: 20, + ), + onPressed: () => setState(() => _obscure = !_obscure), + ), + validator: (v) { + if (v == null || v.isEmpty) return 'Ingresa tu contraseña'; + if (v.length < 6) return 'Mínimo 6 caracteres'; + return null; + }, + ), + const SizedBox(height: 12), + _buildRememberRow(), + if (provider.loginError != null) ...[ + const SizedBox(height: 12), + _buildErrorBox(provider.loginError!), + ], + const SizedBox(height: 16), + _buildButton(provider.loading), + const SizedBox(height: 12), + _buildRegistroLinks(), + const SizedBox(height: 12), + Center( + child: Text( + 'v1.0.0 · SIGMAC', + style: TextStyle( + color: _kTextMuted.withOpacity(0.55), fontSize: 11), + ), + ), + ], + ), + ), + ); + } + + // ── Toggle Local / Cloud ───────────────────────────────────── + + Widget _buildToggle() { + return LayoutBuilder( + builder: (_, constraints) { + final halfW = constraints.maxWidth / 2; + return Container( + height: 40, + decoration: BoxDecoration( + color: _kCard, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: _kBorder), + ), + child: AnimatedBuilder( + animation: _toggleSlide, + builder: (_, __) => Stack( + children: [ + // Indicador deslizante + Positioned( + left: _toggleSlide.value * halfW + 3, + top: 3, + bottom: 3, + width: halfW - 6, + child: Container( + decoration: BoxDecoration( + color: _kAccent, + borderRadius: BorderRadius.circular(7), + ), + ), + ), + // Labels + Row( + children: [ + _toggleOption('Cuenta local', !_modoCloud, + onTap: () => _switchModo(false)), + _toggleOption('Cloud', _modoCloud, + onTap: () => _switchModo(true)), + ], + ), + ], + ), + ), + ); + }, + ); + } + + Widget _toggleOption(String label, bool active, {required VoidCallback onTap}) { + return Expanded( + child: GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Center( + child: Text( + label, + style: TextStyle( + color: active ? Colors.white : _kTextMuted, + fontSize: 13, + fontWeight: active ? FontWeight.w600 : FontWeight.normal, + ), + ), ), ), ); } - Widget _buildLogo() { - return Column( + // ── Campo de texto ─────────────────────────────────────────── + + Widget _buildField({ + required TextEditingController controller, + required String label, + required IconData icon, + TextInputType? keyboardType, + bool obscure = false, + Widget? suffix, + String? Function(String?)? validator, + }) { + return TextFormField( + controller: controller, + obscureText: obscure, + keyboardType: keyboardType, + validator: validator, + style: const TextStyle(color: Colors.white, fontSize: 14), + decoration: InputDecoration( + labelText: label, + labelStyle: const TextStyle(color: _kTextMuted, fontSize: 13), + prefixIcon: Icon(icon, color: _kTextMuted, size: 20), + suffixIcon: suffix, + filled: true, + fillColor: _kCard, + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kBorder), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kAccent, width: 2), + ), + errorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kError), + ), + focusedErrorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kError, width: 2), + ), + errorStyle: const TextStyle(color: _kError, fontSize: 11), + ), + ); + } + + // ── Fila "Mantener sesión" ─────────────────────────────────── + + Widget _buildRememberRow() { + return Row( children: [ - Container( - width: 96, - height: 96, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(24), - boxShadow: [ - BoxShadow( - color: Colors.black.withOpacity(0.25), - blurRadius: 20, - offset: const Offset(0, 8), - ), - ], + SizedBox( + width: 20, + height: 20, + child: Checkbox( + value: _rememberMe, + onChanged: (v) => setState(() => _rememberMe = v ?? true), + activeColor: _kAccent, + side: const BorderSide(color: _kBorder, width: 1.5), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(4)), ), - child: ClipRRect( - borderRadius: BorderRadius.circular(24), - child: Image.asset( - 'assets/icon/icon.png', - width: 96, - height: 96, - fit: BoxFit.cover, + ), + const SizedBox(width: 8), + const Text('Mantener sesión', + style: TextStyle(color: _kTextMuted, fontSize: 13)), + const Spacer(), + if (_modoCloud) + GestureDetector( + onTap: () {}, + child: const Text( + '¿Olvidaste tu contraseña?', + style: TextStyle( + color: _kAccent, + fontSize: 13, + fontWeight: FontWeight.w500, + ), ), ), - ), - const SizedBox(height: 20), - const Text( - 'Agente Ventas', - style: TextStyle( - fontSize: 32, - fontWeight: FontWeight.bold, - color: Colors.white, - letterSpacing: 1.0, - ), - ), - const SizedBox(height: 4), - Text( - 'by SIGMAC', - style: TextStyle( - fontSize: 13, - color: Colors.white.withOpacity(0.65), - letterSpacing: 2.0, - fontWeight: FontWeight.w500, - ), - ), - const SizedBox(height: 6), - Text( - 'Gestión de rutas y pedidos de campo', - style: TextStyle( - fontSize: 13, - color: Colors.white.withOpacity(0.8), + ], + ); + } + + // ── Caja de error ──────────────────────────────────────────── + + Widget _buildErrorBox(String msg) { + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: _kError.withOpacity(0.10), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: _kError.withOpacity(0.35)), + ), + child: Row( + children: [ + const Icon(Icons.error_outline, color: _kError, size: 16), + const SizedBox(width: 8), + Expanded( + child: Text(msg, + style: const TextStyle(fontSize: 12, color: _kError)), ), + ], + ), + ); + } + + // ── Links de registro ──────────────────────────────────────── + + Widget _buildRegistroLinks() { + return Column( + children: [ + const Divider(color: _kBorder, height: 24), + const Text('¿No tienes cuenta?', + style: TextStyle(color: _kTextMuted, fontSize: 13)), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: OutlinedButton.icon( + onPressed: () => + Navigator.pushNamed(context, '/registro'), + icon: const Icon(Icons.smartphone, size: 16), + label: const Text('Cuenta local', + style: TextStyle(fontSize: 12)), + style: OutlinedButton.styleFrom( + primary: _kTextMuted, + side: const BorderSide(color: _kBorder), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + padding: const EdgeInsets.symmetric(vertical: 10), + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: OutlinedButton.icon( + onPressed: () => + Navigator.pushNamed(context, '/registro_cloud'), + icon: const Icon(Icons.cloud_outlined, size: 16), + label: const Text('Nueva Cloud', + style: TextStyle(fontSize: 12)), + style: OutlinedButton.styleFrom( + primary: _kAccent, + side: const BorderSide(color: _kAccent), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + padding: const EdgeInsets.symmetric(vertical: 10), + ), + ), + ), + ], ), ], ); } - Widget _buildCard() { - return Container( - padding: const EdgeInsets.all(28), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(20), - boxShadow: [ - BoxShadow( - color: Colors.black.withOpacity(0.2), - blurRadius: 20, - offset: const Offset(0, 8), - ), - ], - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Text( - 'Iniciar sesión', - style: TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - color: AppTheme.textPrimary, - ), - ), - const SizedBox(height: 6), - const Text( - 'Ingresa tus credenciales para continuar', - style: TextStyle(fontSize: 13, color: AppTheme.textSecondary), - ), - const SizedBox(height: 24), - TextField( - controller: _emailCtrl, - keyboardType: TextInputType.emailAddress, - decoration: const InputDecoration( - labelText: 'Correo electrónico', - prefixIcon: Icon(Icons.email_outlined), - ), - ), - const SizedBox(height: 14), - TextField( - controller: _passCtrl, - obscureText: _obscure, - decoration: InputDecoration( - labelText: 'Contraseña', - prefixIcon: const Icon(Icons.lock_outline), - suffixIcon: IconButton( - icon: Icon(_obscure ? Icons.visibility_outlined : Icons.visibility_off_outlined), - onPressed: () => setState(() => _obscure = !_obscure), - ), - ), - ), - const SizedBox(height: 8), - Align( - alignment: Alignment.centerRight, - child: TextButton( - onPressed: () {}, - child: const Text('¿Olvidaste tu contraseña?'), - ), - ), - if (_error != null) ...[ - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), - decoration: BoxDecoration( - color: AppTheme.dangerColor.withOpacity(0.08), - borderRadius: BorderRadius.circular(8), - border: Border.all(color: AppTheme.dangerColor.withOpacity(0.3)), - ), - child: Row( - children: [ - const Icon(Icons.error_outline, color: AppTheme.dangerColor, size: 16), - const SizedBox(width: 8), - Expanded( - child: Text( - _error!, - style: const TextStyle(fontSize: 12, color: AppTheme.dangerColor), - ), + // ── Botón ──────────────────────────────────────────────────── + + Widget _buildButton(bool loading) { + return SizedBox( + width: double.infinity, + height: 52, + child: DecoratedBox( + decoration: BoxDecoration( + gradient: loading + ? null + : const LinearGradient( + colors: [_kTopBar, _kAccent], + begin: Alignment.centerLeft, + end: Alignment.centerRight, + ), + color: loading ? _kBorder : null, + borderRadius: BorderRadius.circular(12), + boxShadow: loading + ? const [] + : [ + BoxShadow( + color: _kAccent.withOpacity(0.4), + blurRadius: 12, + offset: const Offset(0, 4), ), ], - ), - ), - const SizedBox(height: 8), - ], - const SizedBox(height: 8), - SizedBox( - width: double.infinity, - height: 50, - child: ElevatedButton( - onPressed: _loading ? null : _login, - child: _loading - ? const SizedBox( - width: 22, - height: 22, - child: CircularProgressIndicator( - strokeWidth: 2.5, - color: Colors.white, - ), - ) - : Row( - mainAxisAlignment: MainAxisAlignment.center, - children: const [ - Icon(Icons.login, size: 20), - SizedBox(width: 8), - Text('Ingresar', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), - ], - ), - ), + ), + child: ElevatedButton( + onPressed: loading ? null : _ingresar, + style: ElevatedButton.styleFrom( + primary: Colors.transparent, + onPrimary: Colors.white, + shadowColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), ), - ], + child: loading + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + strokeWidth: 2.5, color: Colors.white), + ) + : Text( + _modoCloud ? 'INGRESAR CON CLOUD' : 'INGRESAR', + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.bold, + letterSpacing: 1.2, + ), + ), + ), ), ); } - - Widget _buildVersion() { - return Text( - 'v1.0.0 • SIGMAC • Telcotronics', - style: TextStyle(fontSize: 12, color: Colors.white.withOpacity(0.6)), - ); - } } diff --git a/lib/screens/login/registro_cloud_screen.dart b/lib/screens/login/registro_cloud_screen.dart new file mode 100644 index 0000000..161c9c8 --- /dev/null +++ b/lib/screens/login/registro_cloud_screen.dart @@ -0,0 +1,860 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import '../../services/auth_service.dart'; +import '../../widgets/password_strength_indicator.dart'; + +const _kBg = Color(0xFF0A1E3C); +const _kTopBar = Color(0xFF0D2D6B); +const _kPanel = Color(0xFF0F2A4A); +const _kCard = Color(0xFF163558); +const _kBorder = Color(0xFF1E4070); +const _kAccent = Color(0xFF1976D2); +const _kTextMuted = Color(0xFFAABBCC); +const _kError = Color(0xFFFF6B6B); +const _kSuccess = Color(0xFF2E7D32); + +class RegistroCloudScreen extends StatefulWidget { + const RegistroCloudScreen({Key? key}) : super(key: key); + + @override + State createState() => _RegistroCloudScreenState(); +} + +class _RegistroCloudScreenState extends State { + int _paso = 0; // 0=Datos, 1=OTP, 2=Cuenta, 3=Creando, 4=Éxito + + // Paso 1 + final _form1Key = GlobalKey(); + final _nombreCtrl = TextEditingController(); + final _ciCtrl = TextEditingController(); + final _emailCtrl = TextEditingController(); + final _telCtrl = TextEditingController(); + final _ciudadCtrl = TextEditingController(); + final _dirCtrl = TextEditingController(); + + // Paso 2 + final _otpCtrl = TextEditingController(); + int _cooldown = 60; + Timer? _timer; + String _usrToken = ''; + + // Paso 3 + final _form3Key = GlobalKey(); + final _empresaCtrl = TextEditingController(); + final _usuarioCtrl = TextEditingController(); + final _passCtrl = TextEditingController(); + final _confirmCtrl = TextEditingController(); + bool _obscurePass = true; + bool _obscureConfirm = true; + + // Animación creación + int _creandoPaso = 0; + double _creandoProgress = 0; + final _creandoPasos = [ + 'Registrando usuario...', + 'Creando empresa en la nube...', + 'Construyendo base de datos...', + 'Configurando tablas...', + 'Aplicando configuración...', + 'Finalizando...', + ]; + final _creandoDuraciones = [2, 3, 10, 7, 5, 3]; + + bool _loading = false; + String? _error; + + @override + void dispose() { + _nombreCtrl.dispose(); _ciCtrl.dispose(); _emailCtrl.dispose(); + _telCtrl.dispose(); _ciudadCtrl.dispose(); _dirCtrl.dispose(); + _otpCtrl.dispose(); + _empresaCtrl.dispose(); _usuarioCtrl.dispose(); + _passCtrl.dispose(); _confirmCtrl.dispose(); + _timer?.cancel(); + super.dispose(); + } + + // ── Paso 1: pre-register ────────────────────────────────────── + + Future _continuar() async { + if (!(_form1Key.currentState?.validate() ?? false)) return; + setState(() { _loading = true; _error = null; }); + try { + await AuthService.preRegister( + nombre: _nombreCtrl.text.trim(), + email: _emailCtrl.text.trim(), + telefono: _telCtrl.text.trim(), + direccion: _dirCtrl.text.trim(), + ci: _ciCtrl.text.trim(), + ciudad: _ciudadCtrl.text.trim(), + ); + _startCooldown(); + setState(() { _paso = 1; _loading = false; }); + } on AuthException catch (e) { + setState(() { _error = e.message; _loading = false; }); + } catch (_) { + setState(() { + _error = 'Sin conexión. Verifica tu internet e intenta de nuevo.'; + _loading = false; + }); + } + } + + // ── Paso 2: verificar OTP ───────────────────────────────────── + + void _startCooldown() { + _cooldown = 60; + _timer?.cancel(); + _timer = Timer.periodic(const Duration(seconds: 1), (t) { + if (!mounted) { t.cancel(); return; } + setState(() { + if (_cooldown > 0) { + _cooldown--; + } else { + t.cancel(); + } + }); + }); + } + + Future _verificarOtp() async { + final code = _otpCtrl.text.trim(); + if (code.length != 6) { + setState(() => _error = 'Ingresa el código de 6 dígitos.'); + return; + } + setState(() { _loading = true; _error = null; }); + try { + _usrToken = await AuthService.verifyOtpRegistro( + email: _emailCtrl.text.trim(), + codigo: code, + ); + setState(() { _paso = 2; _loading = false; }); + } on AuthException catch (e) { + setState(() { _error = e.message; _loading = false; }); + } catch (_) { + setState(() { + _error = 'Error de conexión al verificar.'; + _loading = false; + }); + } + } + + Future _reenviar() async { + if (_cooldown > 0) return; + setState(() { _loading = true; _error = null; }); + try { + await AuthService.preRegister( + nombre: _nombreCtrl.text.trim(), + email: _emailCtrl.text.trim(), + telefono: _telCtrl.text.trim(), + direccion: _dirCtrl.text.trim(), + ); + _startCooldown(); + } catch (_) { + setState(() => _error = 'Error al reenviar el código.'); + } + setState(() => _loading = false); + } + + // ── Paso 3: register ────────────────────────────────────────── + + Future _crearCuenta() async { + if (!(_form3Key.currentState?.validate() ?? false)) return; + setState(() { _paso = 3; _loading = true; _error = null; }); + _animarCreacion(); + try { + await AuthService.register( + nombre: _nombreCtrl.text.trim(), + usuario: _usuarioCtrl.text.trim().toLowerCase(), + password: _passCtrl.text, + dba: _empresaCtrl.text.trim(), + email: _emailCtrl.text.trim(), + usrToken: _usrToken.isNotEmpty ? _usrToken : null, + ); + if (mounted) setState(() { _paso = 4; _loading = false; }); + } on AuthException catch (e) { + if (mounted) { + setState(() { _paso = 2; _error = e.message; _loading = false; }); + } + } catch (_) { + if (mounted) { + setState(() { + _paso = 2; + _error = 'Error de conexión al crear la cuenta.'; + _loading = false; + }); + } + } + } + + void _animarCreacion() async { + double total = _creandoDuraciones.fold(0, (s, d) => s + d).toDouble(); + double elapsed = 0; + for (int i = 0; i < _creandoDuraciones.length; i++) { + if (!mounted) return; + setState(() => _creandoPaso = i); + await Future.delayed(Duration(seconds: _creandoDuraciones[i])); + elapsed += _creandoDuraciones[i]; + if (!mounted) return; + setState(() => _creandoProgress = elapsed / total); + } + } + + // ── Build ───────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: _kBg, + body: Stack( + children: [ + Container( + height: 160, + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [_kTopBar, _kBg], + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + ), + ), + ), + SafeArea( + child: Column( + children: [ + _buildTopBar(), + if (_paso < 3) _buildStepper(), + Expanded( + child: SingleChildScrollView( + child: _buildContent(), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildTopBar() { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: _paso == 0 || _paso >= 3 + ? () => Navigator.pop(context) + : () => setState(() { _paso--; _error = null; }), + ), + const Text( + 'Crear cuenta en la nube', + style: TextStyle( + color: Colors.white, + fontSize: 17, + fontWeight: FontWeight.w600), + ), + ], + ), + ); + } + + Widget _buildStepper() { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 8), + child: Row( + children: List.generate(3, (i) { + final done = _paso > i; + final active = _paso == i; + return Expanded( + child: Row( + children: [ + _stepCircle(i + 1, done, active), + if (i < 2) + Expanded( + child: Container( + height: 2, + color: done ? _kAccent : _kBorder, + ), + ), + ], + ), + ); + }), + ), + ); + } + + Widget _stepCircle(int num, bool done, bool active) { + return Column( + children: [ + Container( + width: 28, + height: 28, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: done || active ? _kAccent : Colors.transparent, + border: done || active + ? null + : Border.all(color: _kBorder, width: 1.5), + ), + child: Center( + child: done + ? const Icon(Icons.check, color: Colors.white, size: 14) + : Text( + '$num', + style: TextStyle( + color: active ? Colors.white : _kTextMuted, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + const SizedBox(height: 2), + Text( + ['Datos', 'Verificar', 'Cuenta'][num - 1], + style: TextStyle( + color: active ? Colors.white : _kTextMuted, + fontSize: 10, + ), + ), + ], + ); + } + + Widget _buildContent() { + return Container( + width: double.infinity, + constraints: BoxConstraints( + minHeight: MediaQuery.of(context).size.height - 160, + ), + decoration: const BoxDecoration( + color: _kPanel, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(32), + topRight: Radius.circular(32), + ), + ), + padding: const EdgeInsets.fromLTRB(24, 28, 24, 40), + child: () { + switch (_paso) { + case 0: return _buildPaso1(); + case 1: return _buildPaso2(); + case 2: return _buildPaso3(); + case 3: return _buildCreando(); + case 4: return _buildExito(); + default: return const SizedBox.shrink(); + } + }(), + ); + } + + // ── Paso 1 UI ───────────────────────────────────────────────── + + Widget _buildPaso1() { + return Form( + key: _form1Key, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _sectionLabel('DATOS PERSONALES'), + const SizedBox(height: 14), + _field(_nombreCtrl, 'Nombre completo *', Icons.person_outline, + validator: _req), + const SizedBox(height: 13), + _field(_ciCtrl, 'Cédula / RUC', Icons.tag_outlined, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly]), + const SizedBox(height: 13), + _field(_emailCtrl, 'Correo electrónico *', Icons.email_outlined, + keyboardType: TextInputType.emailAddress, + validator: _emailVal), + const SizedBox(height: 13), + _field(_telCtrl, 'Teléfono / Celular *', Icons.phone_outlined, + keyboardType: TextInputType.phone, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + validator: _req), + const SizedBox(height: 13), + _field(_ciudadCtrl, 'Ciudad', Icons.location_city_outlined), + const SizedBox(height: 13), + _field(_dirCtrl, 'Dirección *', Icons.home_outlined, + validator: _req), + if (_error != null) ...[ + const SizedBox(height: 14), + _errorBox(_error!), + ], + const SizedBox(height: 24), + _boton('CONTINUAR →', _loading ? null : _continuar), + ], + ), + ); + } + + // ── Paso 2 UI ───────────────────────────────────────────────── + + Widget _buildPaso2() { + final email = _emailCtrl.text.trim(); + final masked = email.contains('@') + ? '${email.substring(0, 2)}***@${email.split('@').last}' + : email; + + return Column( + children: [ + const SizedBox(height: 16), + const Icon(Icons.mark_email_unread_outlined, + size: 64, color: _kAccent), + const SizedBox(height: 16), + const Text( + 'Revisa tu correo', + style: TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + Text( + 'Enviamos un código de 6 dígitos a\n$masked', + textAlign: TextAlign.center, + style: const TextStyle(color: _kTextMuted, fontSize: 13), + ), + const SizedBox(height: 28), + TextFormField( + controller: _otpCtrl, + keyboardType: TextInputType.number, + textAlign: TextAlign.center, + maxLength: 6, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + style: const TextStyle( + color: Colors.white, + fontSize: 28, + letterSpacing: 12, + fontWeight: FontWeight.bold), + decoration: InputDecoration( + hintText: '------', + hintStyle: const TextStyle( + color: _kBorder, fontSize: 28, letterSpacing: 12), + counterText: '', + filled: true, + fillColor: _kCard, + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 16), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kBorder)), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kAccent, width: 2)), + ), + ), + if (_error != null) ...[ + const SizedBox(height: 14), + _errorBox(_error!), + ], + const SizedBox(height: 24), + _boton('VERIFICAR CÓDIGO ✓', _loading ? null : _verificarOtp), + const SizedBox(height: 16), + GestureDetector( + onTap: _cooldown == 0 ? _reenviar : null, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.refresh, + color: _cooldown == 0 ? _kAccent : _kTextMuted, size: 16), + const SizedBox(width: 6), + Text( + _cooldown == 0 + ? 'Reenviar código' + : 'Reenviar en ${_cooldown}s', + style: TextStyle( + color: _cooldown == 0 ? _kAccent : _kTextMuted, + fontSize: 13, + ), + ), + ], + ), + ), + ], + ); + } + + // ── Paso 3 UI ───────────────────────────────────────────────── + + Widget _buildPaso3() { + return Form( + key: _form3Key, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _sectionLabel('DATOS DE LA EMPRESA'), + const SizedBox(height: 14), + TextFormField( + controller: _empresaCtrl, + validator: _req, + style: const TextStyle(color: Colors.white, fontSize: 14), + inputFormatters: [_EmpresaFormatter()], + decoration: _deco('Nombre de la empresa *', Icons.business_outlined), + ), + const SizedBox(height: 22), + _sectionLabel('USUARIO Y CONTRASEÑA'), + const SizedBox(height: 14), + _field(_usuarioCtrl, 'Nombre de usuario *', Icons.alternate_email, + validator: (v) { + if (v == null || v.trim().isEmpty) return 'Obligatorio'; + if (v.trim().length < 3) return 'Mínimo 3 caracteres'; + if (v.trim().length > 16) return 'Máximo 16 caracteres'; + if (v.contains(' ')) return 'Sin espacios'; + return null; + }), + const SizedBox(height: 13), + TextFormField( + controller: _passCtrl, + obscureText: _obscurePass, + validator: (v) { + if (v == null || v.isEmpty) return 'Obligatorio'; + if (v.length < 8) return 'Mínimo 8 caracteres'; + return null; + }, + style: const TextStyle(color: Colors.white, fontSize: 14), + decoration: _deco('Contraseña *', Icons.lock_outline).copyWith( + suffixIcon: IconButton( + icon: Icon( + _obscurePass + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + color: _kTextMuted, + size: 20, + ), + onPressed: () => + setState(() => _obscurePass = !_obscurePass), + ), + ), + ), + ValueListenableBuilder( + valueListenable: _passCtrl, + builder: (_, val, __) => + PasswordStrengthIndicator(password: val.text), + ), + const SizedBox(height: 13), + TextFormField( + controller: _confirmCtrl, + obscureText: _obscureConfirm, + validator: (v) { + if (v == null || v.isEmpty) return 'Obligatorio'; + if (v != _passCtrl.text) return 'Las contraseñas no coinciden'; + return null; + }, + style: const TextStyle(color: Colors.white, fontSize: 14), + decoration: + _deco('Confirmar contraseña *', Icons.lock_outline).copyWith( + suffixIcon: IconButton( + icon: Icon( + _obscureConfirm + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + color: _kTextMuted, + size: 20, + ), + onPressed: () => + setState(() => _obscureConfirm = !_obscureConfirm), + ), + ), + ), + if (_error != null) ...[ + const SizedBox(height: 14), + _errorBox(_error!), + ], + const SizedBox(height: 24), + _boton('CREAR CUENTA EN LA NUBE ☁', _loading ? null : _crearCuenta), + const SizedBox(height: 12), + Center( + child: TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancelar', + style: TextStyle(color: _kTextMuted, fontSize: 13)), + ), + ), + ], + ), + ); + } + + // ── Pantalla "Creando" ──────────────────────────────────────── + + Widget _buildCreando() { + return Column( + children: [ + const SizedBox(height: 16), + ClipRRect( + borderRadius: BorderRadius.circular(8), + child: LinearProgressIndicator( + value: _creandoProgress, + backgroundColor: _kBorder, + valueColor: const AlwaysStoppedAnimation(_kAccent), + minHeight: 6, + ), + ), + const SizedBox(height: 4), + Align( + alignment: Alignment.centerRight, + child: Text( + '${(_creandoProgress * 100).toInt()}%', + style: const TextStyle(color: _kTextMuted, fontSize: 11), + ), + ), + const SizedBox(height: 28), + const Icon(Icons.cloud_outlined, size: 64, color: _kAccent), + const SizedBox(height: 16), + Text( + _creandoPasos[_creandoPaso], + style: const TextStyle( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w600), + ), + const SizedBox(height: 6), + const Text( + 'Esto puede tomar un minuto.\nNo cierres la aplicación.', + textAlign: TextAlign.center, + style: TextStyle(color: _kTextMuted, fontSize: 13), + ), + const SizedBox(height: 28), + ...List.generate(_creandoPasos.length, (i) { + final done = i < _creandoPaso; + final active = i == _creandoPaso; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + SizedBox( + width: 20, + height: 20, + child: done + ? const Icon(Icons.check_circle, + color: _kSuccess, size: 18) + : active + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator( + strokeWidth: 2, color: _kAccent)) + : const Icon(Icons.circle_outlined, + color: _kBorder, size: 18), + ), + const SizedBox(width: 10), + Text( + _creandoPasos[i], + style: TextStyle( + color: done + ? _kSuccess + : active + ? Colors.white + : _kTextMuted, + fontSize: 13, + ), + ), + ], + ), + ); + }), + ], + ); + } + + // ── Pantalla Éxito ──────────────────────────────────────────── + + Widget _buildExito() { + return Column( + children: [ + const SizedBox(height: 32), + Container( + width: 80, + height: 80, + decoration: const BoxDecoration( + shape: BoxShape.circle, color: _kSuccess), + child: const Icon(Icons.cloud_done_outlined, + color: Colors.white, size: 40), + ), + const SizedBox(height: 24), + const Text( + '¡Cuenta creada!', + style: TextStyle( + color: Colors.white, + fontSize: 22, + fontWeight: FontWeight.bold), + ), + const SizedBox(height: 10), + const Text( + 'Tu empresa ya está activa\nen la nube. Ya puedes\niniciar sesión.', + textAlign: TextAlign.center, + style: TextStyle(color: _kTextMuted, fontSize: 14, height: 1.5), + ), + const SizedBox(height: 36), + _boton('IR AL LOGIN', () { + Navigator.pushNamedAndRemoveUntil( + context, '/login', (_) => false); + }), + ], + ); + } + + // ── Helpers UI ──────────────────────────────────────────────── + + Widget _sectionLabel(String text) => Text( + text, + style: const TextStyle( + color: _kAccent, + fontSize: 11, + fontWeight: FontWeight.bold, + letterSpacing: 1.5, + ), + ); + + Widget _field( + TextEditingController ctrl, + String label, + IconData icon, { + TextInputType? keyboardType, + List? inputFormatters, + String? Function(String?)? validator, + }) { + return TextFormField( + controller: ctrl, + keyboardType: keyboardType, + inputFormatters: inputFormatters, + validator: validator, + style: const TextStyle(color: Colors.white, fontSize: 14), + decoration: _deco(label, icon), + ); + } + + InputDecoration _deco(String label, IconData icon) => InputDecoration( + labelText: label, + labelStyle: const TextStyle(color: _kTextMuted, fontSize: 13), + prefixIcon: Icon(icon, color: _kTextMuted, size: 20), + filled: true, + fillColor: _kCard, + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kBorder)), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kAccent, width: 2)), + errorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kError)), + focusedErrorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kError, width: 2)), + errorStyle: const TextStyle(color: _kError, fontSize: 11), + ); + + Widget _errorBox(String msg) => Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: _kError.withOpacity(0.10), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: _kError.withOpacity(0.35)), + ), + child: Row( + children: [ + const Icon(Icons.error_outline, color: _kError, size: 16), + const SizedBox(width: 8), + Expanded( + child: Text(msg, + style: const TextStyle(fontSize: 12, color: _kError))), + ], + ), + ); + + Widget _boton(String label, VoidCallback? onPressed) => SizedBox( + width: double.infinity, + height: 52, + child: DecoratedBox( + decoration: BoxDecoration( + gradient: onPressed == null + ? null + : const LinearGradient( + colors: [_kTopBar, _kAccent], + begin: Alignment.centerLeft, + end: Alignment.centerRight), + color: onPressed == null ? _kBorder : null, + borderRadius: BorderRadius.circular(12), + boxShadow: onPressed == null + ? const [] + : [ + BoxShadow( + color: _kAccent.withOpacity(0.4), + blurRadius: 12, + offset: const Offset(0, 4)) + ], + ), + child: ElevatedButton( + onPressed: onPressed, + style: ElevatedButton.styleFrom( + primary: Colors.transparent, + onPrimary: Colors.white, + shadowColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + ), + child: _loading && onPressed == null + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + strokeWidth: 2.5, color: Colors.white)) + : Text( + label, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + letterSpacing: 1.0), + ), + ), + ), + ); + + String? _req(String? v) => + (v == null || v.trim().isEmpty) ? 'Obligatorio' : null; + + String? _emailVal(String? v) { + if (v == null || v.trim().isEmpty) return 'Obligatorio'; + if (!v.contains('@') || !v.contains('.')) return 'Correo inválido'; + return null; + } +} + +// ── Formatter: normaliza nombre de empresa en tiempo real ──────── + +class _EmpresaFormatter extends TextInputFormatter { + static const _map = { + 'á': 'A', 'à': 'A', 'ä': 'A', 'â': 'A', 'Á': 'A', 'À': 'A', 'Ä': 'A', + 'é': 'E', 'è': 'E', 'ë': 'E', 'ê': 'E', 'É': 'E', 'È': 'E', 'Ë': 'E', + 'í': 'I', 'ì': 'I', 'ï': 'I', 'î': 'I', 'Í': 'I', 'Ì': 'I', 'Ï': 'I', + 'ó': 'O', 'ò': 'O', 'ö': 'O', 'ô': 'O', 'Ó': 'O', 'Ò': 'O', 'Ö': 'O', + 'ú': 'U', 'ù': 'U', 'ü': 'U', 'û': 'U', 'Ú': 'U', 'Ù': 'U', 'Ü': 'U', + 'ñ': 'N', 'Ñ': 'N', + ' ': '_', '-': '_', + }; + + @override + TextEditingValue formatEditUpdate( + TextEditingValue oldValue, TextEditingValue newValue) { + final buf = StringBuffer(); + for (final ch in newValue.text.characters) { + final mapped = _map[ch] ?? ch.toUpperCase(); + if (RegExp(r'^[A-Z0-9_]$').hasMatch(mapped)) buf.write(mapped); + } + final result = buf.toString(); + return newValue.copyWith( + text: result, + selection: TextSelection.collapsed(offset: result.length), + ); + } +} diff --git a/lib/screens/login/registro_screen.dart b/lib/screens/login/registro_screen.dart new file mode 100644 index 0000000..e9deabe --- /dev/null +++ b/lib/screens/login/registro_screen.dart @@ -0,0 +1,365 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import '../../database/database_helper.dart'; +import '../../widgets/password_strength_indicator.dart'; + +const _kBg = Color(0xFF0A1E3C); +const _kTopBar = Color(0xFF0D2D6B); +const _kPanel = Color(0xFF0F2A4A); +const _kCard = Color(0xFF163558); +const _kBorder = Color(0xFF1E4070); +const _kAccent = Color(0xFF1976D2); +const _kTextMuted = Color(0xFFAABBCC); +const _kError = Color(0xFFFF6B6B); + +class RegistroScreen extends StatefulWidget { + const RegistroScreen({Key? key}) : super(key: key); + + @override + State createState() => _RegistroScreenState(); +} + +class _RegistroScreenState extends State { + final _formKey = GlobalKey(); + final _nombreCtrl = TextEditingController(); + final _emailCtrl = TextEditingController(); + final _telCtrl = TextEditingController(); + final _empresaCtrl = TextEditingController(); + final _rucCtrl = TextEditingController(); + final _passCtrl = TextEditingController(); + final _confirmCtrl = TextEditingController(); + + bool _obscurePass = true; + bool _obscureConfirm = true; + bool _loading = false; + String? _error; + + @override + void dispose() { + _nombreCtrl.dispose(); + _emailCtrl.dispose(); + _telCtrl.dispose(); + _empresaCtrl.dispose(); + _rucCtrl.dispose(); + _passCtrl.dispose(); + _confirmCtrl.dispose(); + super.dispose(); + } + + Future _crear() async { + if (!(_formKey.currentState?.validate() ?? false)) return; + setState(() { _loading = true; _error = null; }); + + final ok = await DatabaseHelper().registerUsuario( + nombre: _nombreCtrl.text.trim(), + email: _emailCtrl.text.trim(), + telefono: _telCtrl.text.trim(), + empresa: _empresaCtrl.text.trim(), + ruc: _rucCtrl.text.trim(), + password: _passCtrl.text, + ); + + if (!mounted) return; + setState(() => _loading = false); + + if (ok) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Cuenta creada. Ya puedes iniciar sesión.'), + backgroundColor: Color(0xFF2E7D32), + ), + ); + Navigator.pop(context); + } else { + setState(() => _error = 'Ya existe una cuenta con ese correo electrónico.'); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: _kBg, + body: Stack( + children: [ + Container( + height: 160, + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [_kTopBar, _kBg], + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + ), + ), + ), + SafeArea( + child: Column( + children: [ + _buildTopBar(), + Expanded( + child: SingleChildScrollView( + child: _buildPanel(), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildTopBar() { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_back, color: Colors.white), + onPressed: () => Navigator.pop(context), + ), + const Text( + 'Crear cuenta local', + style: TextStyle( + color: Colors.white, + fontSize: 17, + fontWeight: FontWeight.w600), + ), + ], + ), + ); + } + + Widget _buildPanel() { + return Container( + width: double.infinity, + constraints: BoxConstraints( + minHeight: MediaQuery.of(context).size.height - 120, + ), + decoration: const BoxDecoration( + color: _kPanel, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(32), + topRight: Radius.circular(32), + ), + ), + padding: const EdgeInsets.fromLTRB(24, 28, 24, 40), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _sectionLabel('DATOS PERSONALES'), + const SizedBox(height: 14), + _field(_nombreCtrl, 'Nombre completo', Icons.person_outline, + validator: _notEmpty), + const SizedBox(height: 13), + _field(_emailCtrl, 'Correo electrónico', Icons.email_outlined, + keyboardType: TextInputType.emailAddress, + validator: (v) { + if (v == null || v.trim().isEmpty) return 'Obligatorio'; + if (!v.contains('@') || !v.contains('.')) { + return 'Correo inválido'; + } + return null; + }), + const SizedBox(height: 13), + _field(_telCtrl, 'Teléfono', Icons.phone_outlined, + keyboardType: TextInputType.phone), + const SizedBox(height: 22), + _sectionLabel('EMPRESA'), + const SizedBox(height: 14), + _field(_empresaCtrl, 'Nombre empresa', Icons.business_outlined, + validator: _notEmpty), + const SizedBox(height: 13), + _field(_rucCtrl, 'RUC / Cédula', Icons.tag_outlined, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly]), + const SizedBox(height: 22), + _sectionLabel('SEGURIDAD'), + const SizedBox(height: 14), + _passwordField(_passCtrl, 'Contraseña', _obscurePass, + onToggle: () => setState(() => _obscurePass = !_obscurePass), + validator: (v) { + if (v == null || v.isEmpty) return 'Obligatorio'; + if (v.length < 8) return 'Mínimo 8 caracteres'; + return null; + }), + ValueListenableBuilder( + valueListenable: _passCtrl, + builder: (_, val, __) => + PasswordStrengthIndicator(password: val.text), + ), + const SizedBox(height: 13), + _passwordField(_confirmCtrl, 'Confirmar contraseña', _obscureConfirm, + onToggle: () => + setState(() => _obscureConfirm = !_obscureConfirm), + validator: (v) { + if (v == null || v.isEmpty) return 'Obligatorio'; + if (v != _passCtrl.text) return 'Las contraseñas no coinciden'; + return null; + }), + if (_error != null) ...[ + const SizedBox(height: 14), + _errorBox(_error!), + ], + const SizedBox(height: 24), + _buildButton(), + ], + ), + ), + ); + } + + Widget _sectionLabel(String text) { + return Text( + text, + style: const TextStyle( + color: _kAccent, + fontSize: 11, + fontWeight: FontWeight.bold, + letterSpacing: 1.5, + ), + ); + } + + Widget _field( + TextEditingController ctrl, + String label, + IconData icon, { + TextInputType? keyboardType, + List? inputFormatters, + String? Function(String?)? validator, + }) { + return TextFormField( + controller: ctrl, + keyboardType: keyboardType, + inputFormatters: inputFormatters, + validator: validator, + style: const TextStyle(color: Colors.white, fontSize: 14), + decoration: _deco(label, icon), + ); + } + + Widget _passwordField( + TextEditingController ctrl, + String label, + bool obscure, { + required VoidCallback onToggle, + String? Function(String?)? validator, + }) { + return TextFormField( + controller: ctrl, + obscureText: obscure, + validator: validator, + style: const TextStyle(color: Colors.white, fontSize: 14), + decoration: _deco(label, Icons.lock_outline).copyWith( + suffixIcon: IconButton( + icon: Icon( + obscure ? Icons.visibility_outlined : Icons.visibility_off_outlined, + color: _kTextMuted, + size: 20, + ), + onPressed: onToggle, + ), + ), + ); + } + + InputDecoration _deco(String label, IconData icon) { + return InputDecoration( + labelText: label, + labelStyle: const TextStyle(color: _kTextMuted, fontSize: 13), + prefixIcon: Icon(icon, color: _kTextMuted, size: 20), + filled: true, + fillColor: _kCard, + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kBorder)), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kAccent, width: 2)), + errorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kError)), + focusedErrorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: _kError, width: 2)), + errorStyle: const TextStyle(color: _kError, fontSize: 11), + ); + } + + Widget _errorBox(String msg) { + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: _kError.withOpacity(0.10), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: _kError.withOpacity(0.35)), + ), + child: Row( + children: [ + const Icon(Icons.error_outline, color: _kError, size: 16), + const SizedBox(width: 8), + Expanded( + child: Text(msg, + style: const TextStyle(fontSize: 12, color: _kError))), + ], + ), + ); + } + + Widget _buildButton() { + return SizedBox( + width: double.infinity, + height: 52, + child: DecoratedBox( + decoration: BoxDecoration( + gradient: _loading + ? null + : const LinearGradient( + colors: [_kTopBar, _kAccent], + begin: Alignment.centerLeft, + end: Alignment.centerRight), + color: _loading ? _kBorder : null, + borderRadius: BorderRadius.circular(12), + boxShadow: _loading + ? const [] + : [ + BoxShadow( + color: _kAccent.withOpacity(0.4), + blurRadius: 12, + offset: const Offset(0, 4)) + ], + ), + child: ElevatedButton( + onPressed: _loading ? null : _crear, + style: ElevatedButton.styleFrom( + primary: Colors.transparent, + onPrimary: Colors.white, + shadowColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + ), + child: _loading + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + strokeWidth: 2.5, color: Colors.white)) + : const Text( + 'CREAR CUENTA', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.bold, + letterSpacing: 1.2), + ), + ), + ), + ); + } + + String? _notEmpty(String? v) => + (v == null || v.trim().isEmpty) ? 'Obligatorio' : null; +} diff --git a/lib/services/auth_service.dart b/lib/services/auth_service.dart index 51c2d59..8852222 100644 --- a/lib/services/auth_service.dart +++ b/lib/services/auth_service.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'dart:typed_data'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; @@ -117,9 +118,10 @@ class AuthService { } } - /// Guarda la sesión en SharedPreferences. - /// Mismas claves que usa sigmac_app para compatibilidad futura. - static Future saveSession(AuthSession s, String email) async { + /// Guarda la sesión cloud en SharedPreferences. + /// [rememberMe] controla el checkbox "Mantener sesión" — si false, no hay auto-login. + static Future saveSession(AuthSession s, String email, + {bool rememberMe = true}) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString('auth_token', s.token); await prefs.setString('auth_usuario', s.usuario); @@ -128,6 +130,7 @@ class AuthService { await prefs.setString('auth_rol', s.rol); await prefs.setString('auth_empresa', s.dbTenant); await prefs.setBool('auth_es_cloud', true); + await prefs.setBool('pref_remember_me', rememberMe); if (s.apiKey.isNotEmpty) { await prefs.setString('auth_api_key', s.apiKey); } @@ -136,6 +139,24 @@ class AuthService { } } + /// Guarda una sesión local (sin cloud) en SharedPreferences. + static Future saveLocalSession( + {required String usuario, + required String nombre, + required String email, + required String empresa, + required String rol, + bool rememberMe = true}) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('auth_usuario', usuario); + await prefs.setString('auth_email', email.toLowerCase()); + await prefs.setString('auth_nombre', nombre); + await prefs.setString('auth_empresa', empresa); + await prefs.setString('auth_rol', rol); + await prefs.setBool('auth_es_cloud', false); + await prefs.setBool('pref_remember_me', rememberMe); + } + /// Borra la sesión de SharedPreferences al hacer logout. static Future clearSession() async { final prefs = await SharedPreferences.getInstance(); @@ -146,7 +167,132 @@ class AuthService { await prefs.remove('auth_rol'); await prefs.remove('auth_api_key'); await prefs.remove('auth_empresa'); - await prefs.setBool('auth_es_cloud', false); + await prefs.setBool('auth_es_cloud', false); + await prefs.setBool('pref_remember_me', false); + } + + /// Verifica que el JWT no ha expirado decodificando el payload Base64. + /// Mismo algoritmo que sigmac_app/login_screen.dart → _jwtVigente(). + static bool isJwtVigente(String token) { + try { + final parts = token.split('.'); + if (parts.length != 3) return false; + var payload = parts[1]; + switch (payload.length % 4) { + case 2: payload += '=='; break; + case 3: payload += '='; break; + } + final decoded = utf8.decode( + Uint8List.fromList(base64Url.decode(payload))); + final json = jsonDecode(decoded) as Map; + final exp = json['exp'] as int?; + if (exp == null) return true; + return DateTime.now().millisecondsSinceEpoch < exp * 1000; + } catch (_) { + return false; + } + } + + /// Paso 1 registro cloud — envía datos y dispara OTP al correo. + /// Lanza [AuthException] si el email ya existe (409). + static Future preRegister({ + required String nombre, + required String email, + required String telefono, + required String direccion, + String? ci, + String? ciudad, + }) async { + final res = await http + .post( + Uri.parse('$_kBase/api/auth/pre-register'), + headers: _headersJson, + body: jsonEncode({ + 'nombre': nombre, + 'email': email, + 'telefono': telefono, + 'direccion': direccion, + if (ci != null && ci.isNotEmpty) 'ci': ci, + if (ciudad != null && ciudad.isNotEmpty) 'ciudad': ciudad, + }), + ) + .timeout(const Duration(seconds: 20)); + + if (res.statusCode == 409) { + throw const AuthException('Ya existe una cuenta con este correo.'); + } + if (res.statusCode != 200 && res.statusCode != 201) { + final msg = _extractMsg(res.body); + throw AuthException(msg.isNotEmpty ? msg : 'Error al enviar el código (${res.statusCode})'); + } + } + + /// Paso 2 registro cloud — verifica OTP. + /// Retorna el token temporal para el paso 3. + static Future verifyOtpRegistro({ + required String email, + required String codigo, + }) async { + final res = await http + .post( + Uri.parse('$_kBase/api/auth/verify-otp-registro'), + headers: _headersJson, + body: jsonEncode({'email': email, 'codigo': codigo}), + ) + .timeout(const Duration(seconds: 20)); + + if (res.statusCode == 400 || res.statusCode == 401) { + throw const AuthException('Código incorrecto o expirado.'); + } + if (res.statusCode != 200) { + final msg = _extractMsg(res.body); + throw AuthException(msg.isNotEmpty ? msg : 'Error al verificar (${res.statusCode})'); + } + + final body = jsonDecode(res.body) as Map; + final token = body['token'] as String? ?? ''; + if (token.isEmpty) throw const AuthException('Respuesta inesperada del servidor.'); + return token; + } + + /// Paso 3 registro cloud — crea empresa y usuario en el cloud. + /// Timeout largo (120s) porque el servidor crea el tenant. + static Future register({ + required String nombre, + required String usuario, + required String password, + required String dba, + required String email, + String? usrToken, + }) async { + final res = await http + .post( + Uri.parse('$_kBase/api/auth/register'), + headers: _headersJson, + body: jsonEncode({ + 'nombre': nombre, + 'usuario': usuario.toLowerCase(), + 'paswd': password, + 'rol': 'admin', + 'dba': dba, + 'idEmp': 1, + 'panel': 'agente_ventas', + 'correo': email, + if (usrToken != null) 'usr_token': usrToken, + }), + ) + .timeout(const Duration(seconds: 120)); + + if (res.statusCode == 409) { + throw const AuthException('El nombre de empresa ya está en uso.'); + } + if (res.statusCode != 200 && res.statusCode != 201) { + final msg = _extractMsg(res.body); + throw AuthException(msg.isNotEmpty ? msg : 'Error al crear la cuenta (${res.statusCode})'); + } + + final body = jsonDecode(res.body) as Map; + return AuthSession.fromMap(body); } static String _extractMsg(String body) { diff --git a/lib/widgets/password_strength_indicator.dart b/lib/widgets/password_strength_indicator.dart new file mode 100644 index 0000000..f3f8f60 --- /dev/null +++ b/lib/widgets/password_strength_indicator.dart @@ -0,0 +1,56 @@ +import 'package:flutter/material.dart'; + +class PasswordStrengthIndicator extends StatelessWidget { + final String password; + + const PasswordStrengthIndicator({Key? key, required this.password}) + : super(key: key); + + static int _score(String p) { + int s = 0; + if (p.length >= 8) s++; + if (p.contains(RegExp(r'[A-Z]'))) s++; + if (p.contains(RegExp(r'[0-9]'))) s++; + if (p.contains(RegExp(r'[!@#\$%^&*(),.?":{}|<>_\-]'))) s++; + return s; + } + + static const _labels = ['Muy débil', 'Débil', 'Regular', 'Buena', 'Fuerte']; + static const _colors = [ + Color(0xFF7B0000), + Color(0xFFB71C1C), + Color(0xFFE65100), + Color(0xFFF9A825), + Color(0xFF2E7D32), + ]; + + @override + Widget build(BuildContext context) { + if (password.isEmpty) return const SizedBox.shrink(); + final score = _score(password); + final fraction = (score + 1) / 5; + final color = _colors[score]; + final label = _labels[score]; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 6), + ClipRRect( + borderRadius: BorderRadius.circular(4), + child: LinearProgressIndicator( + value: fraction, + backgroundColor: const Color(0xFF1E4070), + valueColor: AlwaysStoppedAnimation(color), + minHeight: 5, + ), + ), + const SizedBox(height: 4), + Text( + label, + style: TextStyle(color: color, fontSize: 11), + ), + ], + ); + } +} diff --git a/pubspec.lock b/pubspec.lock index 26074ba..17e31d1 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -65,7 +65,7 @@ packages: source: hosted version: "3.1.0" crypto: - dependency: transitive + dependency: "direct main" description: name: crypto url: "https://pub.dartlang.org" diff --git a/pubspec.yaml b/pubspec.yaml index 076cb65..b603491 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -18,6 +18,7 @@ dependencies: mobile_scanner: ^0.2.0 http: ^0.13.0 shared_preferences: ^2.0.0 + crypto: ^3.0.0 dev_dependencies: flutter_test: