feat: servicios WhatsApp, Bitácora WebControl, SQLite v4, UI y store listing

This commit is contained in:
Pablinux
2026-11-22 17:40:46 -05:00
parent 7ffb8d3c52
commit 4aaae043fe
47 changed files with 2552 additions and 361 deletions
+9 -6
View File
@@ -156,8 +156,9 @@ class _AlarmasPageState extends State<AlarmasPage>
ElevatedButton(
onPressed: () => Navigator.pop(context, true),
style: ElevatedButton.styleFrom(
primary: AppColors.primary,
onPrimary: AppColors.surfaceLowest,
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
backgroundColor: AppColors.primary,
foregroundColor: AppColors.surfaceLowest,
elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
@@ -197,8 +198,9 @@ class _AlarmasPageState extends State<AlarmasPage>
ElevatedButton(
onPressed: () => Navigator.pop(context, true),
style: ElevatedButton.styleFrom(
primary: AppColors.onSurfaceVariant,
onPrimary: AppColors.surfaceLowest,
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
backgroundColor: AppColors.onSurfaceVariant,
foregroundColor: AppColors.surfaceLowest,
elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
@@ -248,8 +250,9 @@ class _AlarmasPageState extends State<AlarmasPage>
ElevatedButton(
onPressed: () => Navigator.pop(context, true),
style: ElevatedButton.styleFrom(
primary: AppColors.tertiary,
onPrimary: AppColors.surfaceLowest,
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
backgroundColor: AppColors.tertiary,
foregroundColor: AppColors.surfaceLowest,
elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
+5 -3
View File
@@ -199,7 +199,8 @@ class _ConectarProveedorPageState extends State<ConectarProveedorPage> {
letterSpacing: 1.0,
color: AppColors.primaryContainer)),
style: ElevatedButton.styleFrom(
primary: AppColors.primary,
// Compatibilidad Flutter 3+: uso de backgroundColor
backgroundColor: AppColors.primary,
padding: const EdgeInsets.symmetric(vertical: 18),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14)),
@@ -257,8 +258,9 @@ class _ConectarProveedorPageState extends State<ConectarProveedorPage> {
child: ElevatedButton(
onPressed: _guardando ? null : _guardarYContinuar,
style: ElevatedButton.styleFrom(
primary: AppColors.primary,
onPrimary: AppColors.primaryContainer,
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
backgroundColor: AppColors.primary,
foregroundColor: AppColors.primaryContainer,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
+9 -6
View File
@@ -193,8 +193,9 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
weight: FontWeight.bold,
color: AppColors.primaryContainer)),
style: ElevatedButton.styleFrom(
primary: AppColors.primary,
onPrimary: AppColors.primaryContainer,
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
backgroundColor: AppColors.primary,
foregroundColor: AppColors.primaryContainer,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
@@ -234,8 +235,9 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
onPressed: () => setState(
() => _muelleBloqueado = !_muelleBloqueado),
style: ElevatedButton.styleFrom(
primary: AppColors.surfaceHighest,
onPrimary: AppColors.onSurface,
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
backgroundColor: AppColors.surfaceHighest,
foregroundColor: AppColors.onSurface,
padding: const EdgeInsets.symmetric(vertical: 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
@@ -283,8 +285,9 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
onPressed: () => setState(
() => _serverBloqueado = !_serverBloqueado),
style: ElevatedButton.styleFrom(
primary: AppColors.surfaceHighest,
onPrimary: AppColors.onSurface,
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
backgroundColor: AppColors.surfaceHighest,
foregroundColor: AppColors.onSurface,
padding: const EdgeInsets.symmetric(vertical: 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
+6
View File
@@ -3,6 +3,7 @@ import '../theme.dart';
import '../db/dao/mensajes_dao.dart';
import '../db/dao/eventos_dao.dart';
import '../models/mensaje.dart';
import '../services/whatsapp_alert_service.dart';
import 'llamada_page.dart';
// ─── Página ───────────────────────────────────────────────────────────────────
@@ -255,6 +256,11 @@ class _MensajeriaPageState extends State<MensajeriaPage> {
descripcion:
'Operador activó alarma de pánico. Requiere atención inmediata de la central.',
);
// Disparo inmediato de alerta de pánico a WhatsApp vía sigma-robot
WhatsAppAlertService.instance.dispararPanicoSOS(
operador: 'Operador en Turno',
ubicacion: 'Consola Móvil SENTINEL ONE',
);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
+3 -2
View File
@@ -317,8 +317,9 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
builder: (_) => const AlarmasPage()),
).then((_) => _cargar()),
style: ElevatedButton.styleFrom(
primary: color,
onPrimary: Colors.white,
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
backgroundColor: color,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 10),
shape: RoundedRectangleBorder(
+268
View File
@@ -5,6 +5,7 @@ import 'package:file_picker/file_picker.dart';
import '../theme.dart';
import '../models/usuario.dart';
import '../db/dao/usuarios_dao.dart';
import '../services/whatsapp_alert_service.dart';
import '../main.dart' show LoginPage;
import 'settings_page.dart';
import 'seguridad_page.dart';
@@ -123,6 +124,162 @@ class _PerfilUsuarioPageState extends State<PerfilUsuarioPage> {
if (mounted) setState(() => _usuario = _usuario!.copyWith(fotoPath: path));
}
// ── Editar teléfono para WhatsApp de alertas críticas ─────────────────────
// Se valida mediante expresión regular el código de país internacional E.164
Future<void> _editarTelefono() async {
if (_usuario == null) return;
final ctrl = TextEditingController(text: _usuario!.telefono ?? '');
String? errorTexto;
// Función de validación con regex para formato internacional con código de país
String? validarNumero(String valor) {
final normalizado = WhatsAppAlertService.normalizarTelefono(valor);
if (normalizado.isEmpty) {
return null; // Permitir campo vacío para borrar el número
}
if (normalizado.startsWith('0')) {
return 'No debe iniciar con 0. Incluye código de país (ej. +593...)';
}
if (!WhatsAppAlertService.esNumeroValido(normalizado)) {
return 'Código de país obligatorio (ej. +5939XXXXXXXX)';
}
return null;
}
final nuevoTelefono = await showDialog<String?>(
context: context,
builder: (ctx) {
return StatefulBuilder(
builder: (context, setDialogState) {
return AlertDialog(
backgroundColor: AppColors.surfaceHigh,
title: Row(
children: [
const Icon(Icons.phone_android,
color: AppColors.secondary, size: 22),
const SizedBox(width: 8),
Text('WhatsApp de Alertas',
style: appHeadline(size: 16, weight: FontWeight.w700)),
],
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Ingresa tu número con código de país para recibir alertas de intrusión, coacción y botón de pánico vía sigma-robot.',
style:
appLabel(size: 12, color: AppColors.onSurfaceVariant),
),
const SizedBox(height: 16),
TextField(
controller: ctrl,
autofocus: true,
keyboardType: TextInputType.phone,
style: appHeadline(size: 15),
onChanged: (v) {
setDialogState(() {
errorTexto = validarNumero(v);
});
},
decoration: InputDecoration(
prefixIcon: const Icon(Icons.phone_android,
color: AppColors.secondary, size: 20),
hintText: '+5939XXXXXXXX',
hintStyle: appLabel(size: 13, color: AppColors.outline),
errorText: errorTexto,
errorMaxLines: 2,
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide:
const BorderSide(color: AppColors.outlineVariant),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(
color: AppColors.secondary, width: 2),
),
filled: true,
fillColor: AppColors.surfaceHighest,
contentPadding: const EdgeInsets.symmetric(
horizontal: 14, vertical: 12),
),
),
const SizedBox(height: 10),
Text(
'Formato internacional: +[código_país][número]\nEjemplo Ecuador: +593987654321',
style: appLabel(size: 11, color: AppColors.outline),
),
],
),
actions: [
if (_usuario!.telefono != null &&
_usuario!.telefono!.isNotEmpty)
TextButton(
onPressed: () => Navigator.pop(ctx, ''),
child: Text('Eliminar',
style: appLabel(size: 13, color: AppColors.error)),
),
TextButton(
onPressed: () => Navigator.pop(ctx, null),
child: Text('Cancelar',
style: appLabel(
size: 13, color: AppColors.onSurfaceVariant)),
),
TextButton(
onPressed: () {
final err = validarNumero(ctrl.text);
if (err != null) {
setDialogState(() => errorTexto = err);
return;
}
final valorFinal = ctrl.text.trim().isEmpty
? null
: WhatsAppAlertService.normalizarTelefono(ctrl.text);
Navigator.pop(ctx, valorFinal ?? '');
},
child: Text('Guardar',
style: appLabel(
size: 13,
weight: FontWeight.bold,
color: AppColors.secondary)),
),
],
);
},
);
},
);
ctrl.dispose();
if (nuevoTelefono == null) return; // Operación cancelada
final valorPersistir = nuevoTelefono.isEmpty ? null : nuevoTelefono;
final actualizado = _usuario!.copyWith(
telefono: valorPersistir,
sincronizado: false,
);
// Persiste el nuevo número en la tabla usuarios de SQLite
await _dao.update(actualizado);
if (mounted) {
setState(() => _usuario = actualizado);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
valorPersistir != null
? 'Número de WhatsApp registrado: $valorPersistir'
: 'Número de WhatsApp eliminado',
style: appLabel(size: 13, color: AppColors.onSurface),
),
backgroundColor: AppColors.surfaceHigh,
duration: const Duration(seconds: 3),
),
);
}
}
@override
Widget build(BuildContext context) {
if (_cargando) {
@@ -142,6 +299,8 @@ class _PerfilUsuarioPageState extends State<PerfilUsuarioPage> {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_avatarCard(nombre, iniciales, nivel, nivelLabel),
const SizedBox(height: 16),
_whatsappCard(),
const SizedBox(height: 24),
_statsGrid(),
const SizedBox(height: 32),
@@ -153,6 +312,115 @@ class _PerfilUsuarioPageState extends State<PerfilUsuarioPage> {
);
}
// ── Tarjeta de Teléfono / WhatsApp para alertas críticas ──────────────────
Widget _whatsappCard() {
final telefono = _usuario?.telefono;
final tieneTelefono = telefono != null && telefono.trim().isNotEmpty;
return Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: AppColors.surfaceHigh,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: tieneTelefono
? AppColors.secondary.withOpacity(0.35)
: AppColors.outlineVariant,
width: 1,
),
),
child: Row(
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: tieneTelefono
? AppColors.secondary.withOpacity(0.15)
: AppColors.surfaceHighest,
borderRadius: BorderRadius.circular(10),
),
child: Icon(
Icons.phone_android,
color: tieneTelefono ? AppColors.secondary : AppColors.outline,
size: 24,
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'WHATSAPP DE ALERTAS',
style: appLabel(
size: 10,
weight: FontWeight.bold,
color: tieneTelefono
? AppColors.secondary
: AppColors.onSurfaceVariant,
spacing: 1.5,
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: tieneTelefono
? AppColors.secondaryContainer
: AppColors.surfaceLowest,
borderRadius: BorderRadius.circular(4),
),
child: Text(
tieneTelefono ? 'ACTIVO' : 'SIN CONFIGURAR',
style: appLabel(
size: 9,
weight: FontWeight.bold,
color: tieneTelefono
? AppColors.secondary
: AppColors.outline,
),
),
),
],
),
const SizedBox(height: 4),
Text(
tieneTelefono ? telefono : 'Sin número configurado',
style: appHeadline(
size: 14,
weight: FontWeight.w600,
color: tieneTelefono
? AppColors.onSurface
: AppColors.outline,
),
),
const SizedBox(height: 2),
Text(
'Recepción de alertas de pánico y severidad 4-5',
style: appLabel(size: 11, color: AppColors.onSurfaceVariant),
),
],
),
),
IconButton(
icon: Icon(
tieneTelefono ? Icons.edit_outlined : Icons.add_circle_outline,
color: tieneTelefono ? AppColors.secondary : AppColors.primary,
size: 22,
),
onPressed: _editarTelefono,
tooltip: 'Configurar WhatsApp de alertas',
),
],
),
);
}
// ── Avatar + info ──────────────────────────────────────────────────────────
Widget _avatarCard(String nombre, String iniciales, int nivel,
String nivelLabel) =>
+309 -99
View File
@@ -1,6 +1,15 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import '../widgets/app_menu_button.dart';
import 'package:crypto/crypto.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../theme.dart';
import '../db/dao/usuarios_dao.dart';
import '../models/usuario.dart';
import '../services/whatsapp_alert_service.dart';
// ── Pantalla de Registro de Operadores (SENTINEL ONE) ────────────────────────
// Adaptada con el Design System oficial: AppColors, dark theme, tipografías appHeadline/appLabel
// y persistencia local en SQLite (usuarios) con hash SHA-256 del PIN.
class RegisterPage extends StatefulWidget {
const RegisterPage({Key? key}) : super(key: key);
@@ -10,138 +19,294 @@ class RegisterPage extends StatefulWidget {
class _RegisterPageState extends State<RegisterPage> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _confirmPasswordController = TextEditingController();
bool _obscurePassword = true;
final _nombreCtrl = TextEditingController();
// Teléfono del usuario con código de país para alertas por WhatsApp
final _telefonoCtrl = TextEditingController();
final _pinCtrl = TextEditingController();
final _confirmPinCtrl = TextEditingController();
final _dao = UsuariosDao();
int _nivelAcceso = 2; // Nivel 2: Operador estándar por defecto
bool _obscurePin = true;
bool _obscureConfirm = true;
bool _guardando = false;
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
_passwordController.dispose();
_confirmPasswordController.dispose();
_nombreCtrl.dispose();
_telefonoCtrl.dispose();
_pinCtrl.dispose();
_confirmPinCtrl.dispose();
super.dispose();
}
void _handleRegister() {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Registrando usuario...')),
String _extraerIniciales(String nombre) {
final partes = nombre.trim().split(RegExp(r'\s+'));
if (partes.isEmpty || partes.first.isEmpty) return 'OP';
if (partes.length == 1) return partes.first.substring(0, partes.first.length.clamp(1, 2)).toUpperCase();
return '${partes.first[0]}${partes.last[0]}'.toUpperCase();
}
Future<void> _handleRegister() async {
if (!_formKey.currentState!.validate()) return;
setState(() => _guardando = true);
try {
final pin = _pinCtrl.text.trim();
final pinHash = sha256.convert(utf8.encode(pin)).toString();
final nombre = _nombreCtrl.text.trim();
final iniciales = _extraerIniciales(nombre);
final telRaw = _telefonoCtrl.text.trim();
final telefonoNormalizado = telRaw.isEmpty
? null
: WhatsAppAlertService.normalizarTelefono(telRaw);
final nuevoUsuario = Usuario(
id: DateTime.now().millisecondsSinceEpoch ~/ 1000,
nombre: nombre,
iniciales: iniciales,
nivelAcceso: _nivelAcceso,
pinHash: pinHash,
areas: 'Lobby, Perímetro, Monitoreo',
fechaInicio: DateTime.now().toIso8601String(),
telefono: telefonoNormalizado,
activo: true,
sincronizado: false,
);
await _dao.insert(nuevoUsuario);
// Si no hay PIN principal configurado en SharedPreferences, se establece este
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('local_pin_hash')) {
await prefs.setString('local_pin_hash', pinHash);
}
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Operador registrado exitosamente. Ya puedes iniciar sesión.',
style: appLabel(size: 13, color: AppColors.primaryContainer)),
backgroundColor: AppColors.primary,
behavior: SnackBarBehavior.floating,
),
);
Navigator.pop(context);
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error al registrar operador: $e',
style: appLabel(size: 13, color: Colors.white)),
backgroundColor: AppColors.error,
behavior: SnackBarBehavior.floating,
),
);
} finally {
if (mounted) setState(() => _guardando = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.surfaceLowest,
appBar: AppBar(
title: const Text('Registro'),
actions: const [AppMenuButton()],
backgroundColor: AppColors.surfaceLowest,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: AppColors.onSurface),
onPressed: () => Navigator.pop(context),
),
title: Text('REGISTRO DE OPERADOR',
style: appHeadline(size: 16, weight: FontWeight.w700, spacing: 1.5)),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(24.0),
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 16),
const Icon(Icons.person_add, size: 80, color: Colors.blue),
const SizedBox(height: 24),
TextFormField(
controller: _nameController,
decoration: const InputDecoration(
labelText: 'Nombre completo',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Por favor introduce tu nombre';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
labelText: 'Email',
prefixIcon: Icon(Icons.email),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Por favor introduce tu email';
}
if (!value.contains('@')) {
return 'Email no válido';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _passwordController,
obscureText: _obscurePassword,
decoration: InputDecoration(
labelText: 'Contraseña',
prefixIcon: const Icon(Icons.lock),
border: const OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(_obscurePassword
? Icons.visibility
: Icons.visibility_off),
onPressed: () =>
setState(() => _obscurePassword = !_obscurePassword),
// Logo / Icono de cabecera
Center(
child: Container(
width: 72,
height: 72,
decoration: BoxDecoration(
color: AppColors.surfaceHigh,
shape: BoxShape.circle,
border: Border.all(color: AppColors.primary.withValues(alpha: 0.4), width: 1.5),
),
child: const Icon(Icons.shield_outlined, size: 36, color: AppColors.primary),
),
validator: (value) {
if (value == null || value.length < 6) {
return 'La contraseña debe tener al menos 6 caracteres';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _confirmPasswordController,
obscureText: _obscureConfirm,
decoration: InputDecoration(
labelText: 'Confirmar contraseña',
prefixIcon: const Icon(Icons.lock_outline),
border: const OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(_obscureConfirm
? Icons.visibility
: Icons.visibility_off),
onPressed: () =>
setState(() => _obscureConfirm = !_obscureConfirm),
),
),
validator: (value) {
if (value != _passwordController.text) {
return 'Las contraseñas no coinciden';
Center(
child: Text('SENTINEL ONE',
style: appHeadline(size: 18, color: AppColors.primary, spacing: 2.0)),
),
Center(
child: Text('Alta de nuevo operador en base local',
style: appLabel(size: 12, color: AppColors.onSurfaceVariant)),
),
const SizedBox(height: 32),
// Campo Nombre
_inputField(
controller: _nombreCtrl,
label: 'Nombre Completo',
icon: Icons.person_outline,
hint: 'Ej. Carlos Méndez',
validator: (v) {
if (v == null || v.trim().isEmpty) return 'Introduce el nombre del operador';
if (v.trim().length < 3) return 'Mínimo 3 caracteres';
return null;
},
),
const SizedBox(height: 20),
// Campo Teléfono WhatsApp (opcional, validado con regex E.164)
_inputField(
controller: _telefonoCtrl,
label: 'WhatsApp Alertas (opcional)',
icon: Icons.phone_android,
hint: '+5939XXXXXXXX',
keyboardType: TextInputType.phone,
validator: (v) {
if (v == null || v.trim().isEmpty) return null;
final limpio = WhatsAppAlertService.normalizarTelefono(v);
if (limpio.startsWith('0')) {
return 'No debe iniciar con 0. Incluye código país (+593...)';
}
if (!WhatsAppAlertService.esNumeroValido(limpio)) {
return 'Código de país obligatorio (ej. +5939XXXXXXXX)';
}
return null;
},
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: _handleRegister,
style: ElevatedButton.styleFrom(
minimumSize: const Size(double.infinity, 50),
const SizedBox(height: 20),
// Selector Nivel de Acceso
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: AppColors.surfaceLow,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: AppColors.outlineVariant.withValues(alpha: 0.4)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('NIVEL DE ACCESO',
style: appLabel(size: 11, weight: FontWeight.bold, color: AppColors.onSurfaceVariant)),
const SizedBox(height: 12),
Row(
children: [1, 2, 3].map((lvl) {
final seleccionado = _nivelAcceso == lvl;
return Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4.0),
child: InkWell(
onTap: () => setState(() => _nivelAcceso = lvl),
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.symmetric(vertical: 10),
decoration: BoxDecoration(
color: seleccionado ? AppColors.primary : AppColors.surfaceHigh,
borderRadius: BorderRadius.circular(8),
),
alignment: Alignment.center,
child: Text('Nivel $lvl',
style: appLabel(
size: 12,
weight: FontWeight.bold,
color: seleccionado ? AppColors.primaryContainer : AppColors.onSurface)),
),
),
),
);
}).toList(),
),
],
),
child: const Text('Crear cuenta'),
),
const SizedBox(height: 12),
const SizedBox(height: 20),
// PIN de acceso
_inputField(
controller: _pinCtrl,
label: 'PIN de Acceso (4-6 dígitos)',
icon: Icons.pin_outlined,
hint: '123456',
isPassword: _obscurePin,
keyboardType: TextInputType.number,
suffixIcon: IconButton(
icon: Icon(_obscurePin ? Icons.visibility_outlined : Icons.visibility_off_outlined,
color: AppColors.onSurfaceVariant, size: 20),
onPressed: () => setState(() => _obscurePin = !_obscurePin),
),
validator: (v) {
if (v == null || v.isEmpty) return 'Introduce un PIN numérico';
if (v.length < 4 || v.length > 6) return 'Debe tener entre 4 y 6 dígitos';
if (!RegExp(r'^\d+$').hasMatch(v)) return 'Solo se permiten números';
return null;
},
),
const SizedBox(height: 20),
// Confirmar PIN
_inputField(
controller: _confirmPinCtrl,
label: 'Confirmar PIN de Acceso',
icon: Icons.lock_outline,
hint: 'Repite tu PIN',
isPassword: _obscureConfirm,
keyboardType: TextInputType.number,
suffixIcon: IconButton(
icon: Icon(_obscureConfirm ? Icons.visibility_outlined : Icons.visibility_off_outlined,
color: AppColors.onSurfaceVariant, size: 20),
onPressed: () => setState(() => _obscureConfirm = !_obscureConfirm),
),
validator: (v) {
if (v != _pinCtrl.text) return 'Los PIN no coinciden';
return null;
},
),
const SizedBox(height: 32),
// Botón Crear Cuenta
SizedBox(
height: 50,
child: ElevatedButton(
onPressed: _guardando ? null : _handleRegister,
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.primary,
foregroundColor: AppColors.primaryContainer,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
elevation: 0,
),
child: _guardando
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.primaryContainer),
)
: Text('REGISTRAR OPERADOR',
style: appLabel(size: 13, weight: FontWeight.bold, spacing: 1.2)),
),
),
const SizedBox(height: 16),
// Volver a login
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('¿Ya tienes cuenta? Inicia sesión'),
child: Text('¿Ya tienes credenciales? Iniciar Sesión',
style: appLabel(size: 13, color: AppColors.primary)),
),
],
),
@@ -149,4 +314,49 @@ class _RegisterPageState extends State<RegisterPage> {
),
);
}
Widget _inputField({
required TextEditingController controller,
required String label,
required IconData icon,
String? hint,
bool isPassword = false,
TextInputType keyboardType = TextInputType.text,
Widget? suffixIcon,
String? Function(String?)? validator,
}) {
return TextFormField(
controller: controller,
obscureText: isPassword,
keyboardType: keyboardType,
style: appLabel(size: 14, color: AppColors.onSurface),
decoration: InputDecoration(
labelText: label,
labelStyle: appLabel(size: 13, color: AppColors.onSurfaceVariant),
hintText: hint,
hintStyle: appLabel(size: 13, color: AppColors.onSurfaceVariant.withValues(alpha: 0.5)),
prefixIcon: Icon(icon, color: AppColors.primary, size: 20),
suffixIcon: suffixIcon,
filled: true,
fillColor: AppColors.surfaceLow,
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(color: AppColors.outlineVariant.withValues(alpha: 0.4)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: AppColors.primary, width: 1.5),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: AppColors.error),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: AppColors.error, width: 1.5),
),
),
validator: validator,
);
}
}
+36
View File
@@ -6,6 +6,7 @@ import '../theme.dart';
import '../db/dao/usuarios_dao.dart';
import '../db/dao/zonas_dao.dart';
import '../models/zona.dart';
import '../services/whatsapp_alert_service.dart';
class RegistrarUsuarioPage extends StatefulWidget {
const RegistrarUsuarioPage({Key? key}) : super(key: key);
@@ -18,6 +19,8 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
final _formKey = GlobalKey<FormState>();
final _nombreCtrl = TextEditingController();
final _pinCtrl = TextEditingController();
// Controlador para el número de teléfono con código de país para alertas WhatsApp
final _telefonoCtrl = TextEditingController();
final _dao = UsuariosDao();
final _zonasDao = ZonasDao();
@@ -55,6 +58,7 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
void dispose() {
_nombreCtrl.dispose();
_pinCtrl.dispose();
_telefonoCtrl.dispose();
super.dispose();
}
@@ -114,6 +118,12 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
.where((z) => _zonasSeleccionadas.contains(z.id))
.map((z) => z.codigo)
.join(',');
// Normaliza y valida el teléfono según estándar E.164
final telRaw = _telefonoCtrl.text.trim();
final telefonoNormalizado = telRaw.isEmpty
? null
: WhatsAppAlertService.normalizarTelefono(telRaw);
await _dao.registrar(
nombre: _nombreCtrl.text.trim(),
iniciales: _calcularIniciales(_nombreCtrl.text),
@@ -122,6 +132,7 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
areas: areas,
fechaInicio: _fechaInicio.toIso8601String(),
fechaFin: _fechaFin?.toIso8601String(),
telefono: telefonoNormalizado,
);
if (!mounted) return;
Navigator.pop(context, true);
@@ -185,6 +196,9 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
_campoNombre(),
const SizedBox(height: 16),
_campoPin(),
const SizedBox(height: 16),
// Campo para asociar el WhatsApp del usuario con validación Regex de país
_campoTelefono(),
const SizedBox(height: 28),
_seccion('Nivel de acceso'),
const SizedBox(height: 12),
@@ -264,6 +278,28 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
},
);
// ── Campo Teléfono WhatsApp (opcional con validación estricta E.164) ──────
Widget _campoTelefono() => TextFormField(
controller: _telefonoCtrl,
style: appLabel(size: 15, color: AppColors.onSurface),
keyboardType: TextInputType.phone,
decoration: _inputDeco(
label: 'WhatsApp alertas (ej. +5939XXXXXXXX)',
icon: Icons.phone_android,
),
validator: (v) {
if (v == null || v.trim().isEmpty) return null;
final limpio = WhatsAppAlertService.normalizarTelefono(v);
if (limpio.startsWith('0')) {
return 'No debe iniciar con 0. Incluye código país (ej. +593...)';
}
if (!WhatsAppAlertService.esNumeroValido(limpio)) {
return 'Código de país obligatorio (ej. +5939XXXXXXXX)';
}
return null;
},
);
InputDecoration _inputDeco({
required String label,
required IconData icon,
+3 -2
View File
@@ -210,8 +210,9 @@ class _SeguridadPageState extends State<SeguridadPage> {
? _guardar
: null,
style: ElevatedButton.styleFrom(
primary: AppColors.primary,
onPrimary: AppColors.primaryContainer,
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
backgroundColor: AppColors.primary,
foregroundColor: AppColors.primaryContainer,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
+31 -1
View File
@@ -1,8 +1,8 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:path/path.dart' as p;
import 'package:shared_preferences/shared_preferences.dart';
import '../theme.dart';
import '../db/database_helper.dart';
import '../services/sincronizador.dart';
@@ -20,11 +20,28 @@ class _SettingsPageState extends State<SettingsPage> {
bool _notificaciones = true;
bool _sonido = true;
bool _vibracion = true;
// Estado de envío de alertas críticas por WhatsApp vía sigma-robot
bool _alertasWhatsApp = true;
bool _iniciandoBd = false;
bool _sincronizando = false;
bool _cargandoDemo = false;
@override
void initState() {
super.initState();
_cargarPreferencias();
}
Future<void> _cargarPreferencias() async {
final prefs = await SharedPreferences.getInstance();
if (mounted) {
setState(() {
_alertasWhatsApp = prefs.getBool('alertas_whatsapp_activas') ?? true;
});
}
}
// ── Build ──────────────────────────────────────────────────────────────────
@override
Widget build(BuildContext context) {
@@ -70,6 +87,19 @@ class _SettingsPageState extends State<SettingsPage> {
value: _vibracion,
onChanged: (v) => setState(() => _vibracion = v),
),
_divider(),
// Configuración de notificaciones críticas a WhatsApp vía sigma-robot
_switchItem(
icon: Icons.phone_android,
titulo: 'Alertas por WhatsApp',
subtitulo: 'Envío de incidentes críticos y pánico vía sigma-robot',
value: _alertasWhatsApp,
onChanged: (v) async {
setState(() => _alertasWhatsApp = v);
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('alertas_whatsapp_activas', v);
},
),
// ── Sistema ──────────────────────────────────────────────────────
_sectionHeader('SISTEMA'),