feat: implementacion completa de 8 modulos, sincronizador centinel, mcp y bitacora de errores
This commit is contained in:
@@ -1,18 +1,144 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/dao/cache_clientes_dao.dart';
|
||||
|
||||
class ClientesPage extends StatelessWidget {
|
||||
// Comentario explicativo: Pantalla de Clientes conectada a CacheClientesDao.
|
||||
// Muestra el semáforo de estado (normal, alerta, crítica) y métricas de alarmas por cliente,
|
||||
// garantizando que el revisor de la tienda visualice datos completos offline.
|
||||
class ClientesPage extends StatefulWidget {
|
||||
const ClientesPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<ClientesPage> createState() => _ClientesPageState();
|
||||
}
|
||||
|
||||
class _ClientesPageState extends State<ClientesPage> {
|
||||
final _clientesDao = CacheClientesDao();
|
||||
List<Map<String, dynamic>> _clientes = [];
|
||||
bool _cargando = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarClientes();
|
||||
}
|
||||
|
||||
Future<void> _cargarClientes() async {
|
||||
final lista = await _clientesDao.getTodos();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_clientes = lista;
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
|
||||
Color _colorEstado(String estado) {
|
||||
switch (estado.toLowerCase()) {
|
||||
case 'critica':
|
||||
return AppColors.alarmaActiva;
|
||||
case 'alerta':
|
||||
return AppColors.clienteAlerta;
|
||||
default:
|
||||
return AppColors.clienteOk;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Clientes', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Estado de todos los clientes', style: appLabel(size: 14)),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Clientes Registrados',
|
||||
style: appHeadline(size: 22, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Monitoreo del estado perimetral y central de cada sede',
|
||||
style: appLabel(size: 13, color: AppColors.outline)),
|
||||
]),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh, color: AppColors.primary),
|
||||
onPressed: _cargarClientes,
|
||||
tooltip: 'Refrescar clientes',
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
if (_cargando)
|
||||
const Center(child: CircularProgressIndicator())
|
||||
else if (_clientes.isEmpty)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(32),
|
||||
alignment: Alignment.center,
|
||||
child: Text('No hay clientes en caché local.', style: appLabel(color: AppColors.outline)),
|
||||
)
|
||||
else
|
||||
ListView.separated(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: _clientes.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 12),
|
||||
itemBuilder: (_, i) {
|
||||
final c = _clientes[i];
|
||||
final estado = (c['estado'] as String?) ?? 'normal';
|
||||
final color = _colorEstado(estado);
|
||||
final activas = (c['alarmas_activas'] as int?) ?? 0;
|
||||
final criticas = (c['alarmas_criticas'] as int?) ?? 0;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: color.withOpacity(0.4), width: 1.2),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 12,
|
||||
height: 12,
|
||||
decoration: BoxDecoration(shape: BoxShape.circle, color: color),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(
|
||||
c['nombre'] as String? ?? 'Cliente',
|
||||
style: appHeadline(size: 14, weight: FontWeight.w700, color: AppColors.onSurface),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'ID: #${c['id']} • Estado: ${estado.toUpperCase()}',
|
||||
style: appLabel(size: 12, color: AppColors.outline),
|
||||
),
|
||||
]),
|
||||
),
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: activas > 0 ? AppColors.surfaceHighest : AppColors.surfaceLowest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
'$activas activas ${criticas > 0 ? "($criticas críticas)" : ""}',
|
||||
style: appLabel(
|
||||
size: 11,
|
||||
weight: FontWeight.bold,
|
||||
color: criticas > 0 ? AppColors.alarmaActiva : AppColors.primary,
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,539 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../services/api_auth_service.dart';
|
||||
import '../services/sincronizador.dart';
|
||||
import '../db/database_helper.dart';
|
||||
import '../db/dao/configuracion_dao.dart';
|
||||
|
||||
class ConfiguracionPage extends StatelessWidget {
|
||||
// Comentario explicativo: Pantalla de Configuración del Sistema conectada a ConfiguracionDao,
|
||||
// Sincronizador, ApiAuthService y DatabaseHelper. Permite gestionar parámetros operativos,
|
||||
// cadencia de sincronización en segundo plano, señalización sonora y reinicio del dataset demo.
|
||||
class ConfiguracionPage extends StatefulWidget {
|
||||
const ConfiguracionPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<ConfiguracionPage> createState() => _ConfiguracionPageState();
|
||||
}
|
||||
|
||||
class _ConfiguracionPageState extends State<ConfiguracionPage> {
|
||||
final _configDao = ConfiguracionDao();
|
||||
final _sincronizador = Sincronizador.instance;
|
||||
final _dbHelper = DatabaseHelper.instance;
|
||||
|
||||
bool _cargando = true;
|
||||
String _operadorNombre = '';
|
||||
String _operadorUsuario = '';
|
||||
String _operadorRol = '';
|
||||
bool _modoDemo = false;
|
||||
|
||||
// Ajustes
|
||||
int _intervaloSegundos = 30;
|
||||
bool _sonidoAlerta = true;
|
||||
bool _alertaPrioritaria = true;
|
||||
|
||||
// Métricas de base de datos
|
||||
Map<String, int> _dbStats = {
|
||||
'alarmas': 0,
|
||||
'clientes': 0,
|
||||
'incidentes': 0,
|
||||
'sync_logs': 0,
|
||||
};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarAjustes();
|
||||
}
|
||||
|
||||
// Comentario explicativo: Recupera los valores de configuración persistidos en SQLite y sesión del operador
|
||||
Future<void> _cargarAjustes() async {
|
||||
setState(() => _cargando = true);
|
||||
|
||||
final nombre = await ApiAuthService.instance.getNombre();
|
||||
final usuario = await ApiAuthService.instance.getUsuario();
|
||||
final rol = await ApiAuthService.instance.getRol();
|
||||
final esDemo = await ApiAuthService.instance.isModoDemo();
|
||||
|
||||
final intervalStr = await _configDao.get('poll_interval_seg');
|
||||
final sonidoStr = await _configDao.get('sonido_alerta');
|
||||
final alertPriorStr = await _configDao.get('alerta_prioritaria');
|
||||
|
||||
final dbStats = await _dbHelper.getMetricasDb();
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_operadorNombre = nombre ?? 'Operador Demo';
|
||||
_operadorUsuario = usuario ?? 'demo@empresa.com';
|
||||
_operadorRol = rol ?? 'Supervisor de Central';
|
||||
_modoDemo = esDemo;
|
||||
|
||||
if (intervalStr != null) {
|
||||
_intervaloSegundos = int.tryParse(intervalStr) ?? 30;
|
||||
} else {
|
||||
_intervaloSegundos = _sincronizador.intervaloSegundos;
|
||||
}
|
||||
|
||||
_sonidoAlerta = (sonidoStr ?? '1') == '1';
|
||||
_alertaPrioritaria = (alertPriorStr ?? '1') == '1';
|
||||
_dbStats = dbStats;
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
|
||||
// Comentario explicativo: Guarda el nuevo intervalo de sincronización y actualiza el timer activo
|
||||
Future<void> _actualizarIntervalo(int nuevosSegundos) async {
|
||||
setState(() => _intervaloSegundos = nuevosSegundos);
|
||||
await _configDao.set('poll_interval_seg', nuevosSegundos.toString());
|
||||
_sincronizador.cambiarIntervalo(nuevosSegundos);
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
content: Text('Intervalo actualizado a $nuevosSegundos segundos', style: appLabel(color: AppColors.onSurface)),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Persiste la preferencia de sonido de alarma en SQLite
|
||||
Future<void> _toggleSonido(bool valor) async {
|
||||
setState(() => _sonidoAlerta = valor);
|
||||
await _configDao.set('sonido_alerta', valor ? '1' : '0');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Persiste la preferencia de alerta prioritaria en SQLite
|
||||
Future<void> _toggleAlertaPrioritaria(bool valor) async {
|
||||
setState(() => _alertaPrioritaria = valor);
|
||||
await _configDao.set('alerta_prioritaria', valor ? '1' : '0');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Restaura el conjunto completo de datos de prueba offline para pruebas o revisión de tienda
|
||||
Future<void> _reiniciarDatosDemo() async {
|
||||
final confirmar = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceLow,
|
||||
title: Text('¿Restablecer Datos Demo?', style: appHeadline(size: 16, color: AppColors.onSurface)),
|
||||
content: Text(
|
||||
'Esta acción recargará las alarmas, clientes, operadores e incidentes de prueba iniciales.',
|
||||
style: appLabel(size: 13, color: AppColors.onSurfaceVariant),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
child: Text('Cancelar', style: appLabel(color: AppColors.outline)),
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(backgroundColor: AppColors.primaryContainer),
|
||||
child: Text('Restablecer', style: appLabel(color: AppColors.primary, weight: FontWeight.bold)),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmar != true) return;
|
||||
|
||||
setState(() => _cargando = true);
|
||||
await _dbHelper.poblarDatosDemo(force: true);
|
||||
await _cargarAjustes();
|
||||
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
content: Row(
|
||||
children: [
|
||||
const Icon(Icons.check_circle, color: AppColors.clienteOk, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Text('Datos demo restablecidos con éxito.', style: appLabel(color: AppColors.onSurface)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Vacía la tabla sync_log liberando espacio de almacenamiento local
|
||||
Future<void> _limpiarSyncLog() async {
|
||||
await _dbHelper.limpiarSyncLogs();
|
||||
await _cargarAjustes();
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
content: Text('Bitácora de sincronización vaciada.', style: appLabel(color: AppColors.onSurface)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Configuración', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Parámetros del sistema', style: appLabel(size: 14)),
|
||||
]),
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Encabezado
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Configuración del Sistema',
|
||||
style: appHeadline(size: 24, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Parámetros de enlace, ciclo de sincronización y almacenamiento local',
|
||||
style: appLabel(size: 13, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh, color: AppColors.outline),
|
||||
tooltip: 'Refrescar ajustes',
|
||||
onPressed: _cargarAjustes,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
if (_cargando)
|
||||
const Center(child: Padding(padding: EdgeInsets.all(40), child: CircularProgressIndicator()))
|
||||
else
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Sección 1: Sesión del Operador
|
||||
_buildSectionHeader('SESIÓN Y AUTORIZACIÓN', Icons.account_circle_outlined),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
_operadorNombre.isNotEmpty ? _operadorNombre[0] : 'O',
|
||||
style: appHeadline(size: 20, color: AppColors.primary),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(_operadorNombre,
|
||||
style: appHeadline(size: 16, weight: FontWeight.w700, color: AppColors.onSurface)),
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: _modoDemo ? AppColors.secondaryContainer : const Color(0xFF1B382B),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
_modoDemo ? 'MODO DEMO OFFLINE' : 'EN LÍNEA',
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: _modoDemo ? AppColors.onSecondaryContainer : AppColors.clienteOk,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text('Usuario: $_operadorUsuario • Rol: $_operadorRol',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// Sección 2: Ciclo de Sincronización
|
||||
_buildSectionHeader('SINCRONIZACIÓN Y TELEMETRÍA', Icons.sync),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Cadencia de Polling Automático',
|
||||
style: appHeadline(size: 14, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Frecuencia con que la central empuja incidentes y consulta alarmas',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceHigh,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<int>(
|
||||
value: _intervaloSegundos,
|
||||
dropdownColor: AppColors.surfaceHigh,
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
items: const [
|
||||
DropdownMenuItem(value: 15, child: Text('Cada 15 segundos')),
|
||||
DropdownMenuItem(value: 30, child: Text('Cada 30 segundos (Recomendado)')),
|
||||
DropdownMenuItem(value: 60, child: Text('Cada 1 minuto')),
|
||||
DropdownMenuItem(value: 120, child: Text('Cada 2 minutos')),
|
||||
],
|
||||
onChanged: (val) {
|
||||
if (val != null) _actualizarIntervalo(val);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const Divider(height: 24, color: AppColors.outlineVariant),
|
||||
ValueListenableBuilder<bool>(
|
||||
valueListenable: _sincronizador.isSyncing,
|
||||
builder: (context, syncing, _) {
|
||||
return ValueListenableBuilder<String?>(
|
||||
valueListenable: _sincronizador.lastSyncStatus,
|
||||
builder: (context, status, _) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Estado de última sincronización:',
|
||||
style: appLabel(size: 11, color: AppColors.outline)),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
status ?? 'Sin sincronizaciones registradas aún',
|
||||
style: appLabel(
|
||||
size: 12,
|
||||
color: syncing ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
foregroundColor: AppColors.primary,
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
icon: syncing
|
||||
? const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh, size: 16),
|
||||
label: Text(syncing ? 'Sincronizando...' : 'Sincronizar ahora',
|
||||
style: appLabel(size: 12, weight: FontWeight.bold)),
|
||||
onPressed: syncing ? null : () => _sincronizador.sincronizarAhora(),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// Sección 3: Alertas y Sonido
|
||||
_buildSectionHeader('ALERTAS Y SEÑALIZACIÓN', Icons.volume_up_outlined),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
// Comentario explicativo: Configuración del switch de alerta acústica con activeThumbColor compatible con Flutter moderno
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text('Sonido acústico ante alarmas críticas',
|
||||
style: appHeadline(size: 14, color: AppColors.onSurface)),
|
||||
subtitle: Text('Emite un tono audible al ingresar eventos de severidad alta',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
value: _sonidoAlerta,
|
||||
activeThumbColor: AppColors.primary,
|
||||
activeTrackColor: AppColors.primaryContainer,
|
||||
onChanged: _toggleSonido,
|
||||
),
|
||||
const Divider(height: 1, color: AppColors.outlineVariant),
|
||||
// Comentario explicativo: Configuración del switch de prioridad visual con activeThumbColor
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text('Prioridad visual en pantalla',
|
||||
style: appHeadline(size: 14, color: AppColors.onSurface)),
|
||||
subtitle: Text('Resalta automáticamente la barra superior ante incidentes no atendidos',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
value: _alertaPrioritaria,
|
||||
activeThumbColor: AppColors.primary,
|
||||
activeTrackColor: AppColors.primaryContainer,
|
||||
onChanged: _toggleAlertaPrioritaria,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// Sección 4: Base de Datos Local y Dataset Demo
|
||||
_buildSectionHeader('ALMACENAMIENTO LOCAL SQLITE', Icons.storage_outlined),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
_buildDbMetric('Alarmas en Caché', '${_dbStats['alarmas'] ?? 0}', Icons.notifications_outlined),
|
||||
_buildDbMetric('Clientes Registrados', '${_dbStats['clientes'] ?? 0}', Icons.business_outlined),
|
||||
_buildDbMetric('Incidentes Locales', '${_dbStats['incidentes'] ?? 0}', Icons.shield_outlined),
|
||||
_buildDbMetric('Logs de Sync', '${_dbStats['sync_logs'] ?? 0}', Icons.history_outlined),
|
||||
],
|
||||
),
|
||||
const Divider(height: 28, color: AppColors.outlineVariant),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
icon: const Icon(Icons.delete_sweep_outlined, size: 16, color: AppColors.outline),
|
||||
label: Text('Limpiar logs de sync', style: appLabel(size: 12, color: AppColors.outline)),
|
||||
onPressed: _limpiarSyncLog,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.primaryContainer,
|
||||
foregroundColor: AppColors.primary,
|
||||
),
|
||||
icon: const Icon(Icons.restart_alt, size: 16),
|
||||
label: Text('Restablecer Dataset Demo', style: appLabel(size: 12, weight: FontWeight.bold)),
|
||||
onPressed: _reiniciarDatosDemo,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// Sección 5: Enlaces del Ecosistema e Información
|
||||
_buildSectionHeader('TOPOLOGÍA DEL ECOSISTEMA', Icons.hub_outlined),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
_buildEndpointRow('Gateway Universal AI & Ecosistema', 'https://sigma-bot.telcotronics.com', 'Agente ID 61 (Autorizado)'),
|
||||
const Divider(height: 16, color: AppColors.outlineVariant),
|
||||
_buildEndpointRow('Controladora y Drivers de Hardware', 'https://api.telcotronics.com', 'ISAPI Hikvision + Tuya IoT'),
|
||||
const Divider(height: 16, color: AppColors.outlineVariant),
|
||||
_buildEndpointRow('Servidor Clientes y Contratos', 'https://api.siax-system.net', 'WebControl Sigma'),
|
||||
const Divider(height: 16, color: AppColors.outlineVariant),
|
||||
_buildEndpointRow('Aplicación y Versión de Compilación', 'Central de Monitoreo v1.0.0+1', 'Linux x64 / Android Embed v2'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Widget auxiliar para títulos de sección con icono y tipografía consistente
|
||||
Widget _buildSectionHeader(String titulo, IconData icono) {
|
||||
return Row(
|
||||
children: [
|
||||
Icon(icono, size: 16, color: AppColors.primary),
|
||||
const SizedBox(width: 8),
|
||||
Text(titulo, style: appHeadline(size: 12, weight: FontWeight.bold, color: AppColors.primary)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Widget auxiliar para mostrar tarjetas de conteo de registros en SQLite
|
||||
Widget _buildDbMetric(String titulo, String cantidad, IconData icono) {
|
||||
return Column(
|
||||
children: [
|
||||
Icon(icono, size: 20, color: AppColors.secondary),
|
||||
const SizedBox(height: 6),
|
||||
Text(cantidad, style: appHeadline(size: 18, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 2),
|
||||
Text(titulo, style: appLabel(size: 11, color: AppColors.outline)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Widget auxiliar para listar los endpoints activos del ecosistema
|
||||
Widget _buildEndpointRow(String titulo, String url, String detalle) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(titulo, style: appHeadline(size: 13, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 2),
|
||||
Text(url, style: appLabel(size: 11, color: AppColors.primary)),
|
||||
],
|
||||
),
|
||||
Text(detalle, style: appLabel(size: 11, color: AppColors.outline)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,342 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../services/centinel_service.dart';
|
||||
|
||||
class DispositivosPage extends StatelessWidget {
|
||||
/// Página de gestión y control de dispositivos de seguridad electrónica.
|
||||
/// Soporta terminales Hikvision ISAPI (Digest Auth) y cerraduras Tuya Smart IoT.
|
||||
/// Permite diagnóstico en vivo (test) y apertura remota de puertas.
|
||||
class DispositivosPage extends StatefulWidget {
|
||||
const DispositivosPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<DispositivosPage> createState() => _DispositivosPageState();
|
||||
}
|
||||
|
||||
class _DispositivosPageState extends State<DispositivosPage> {
|
||||
final _centinel = CentinelService.instance;
|
||||
List<Map<String, dynamic>> _dispositivos = [];
|
||||
bool _cargando = true;
|
||||
String _filtroTexto = '';
|
||||
String _filtroEstado = 'todos'; // todos | online | offline
|
||||
|
||||
final Map<int, bool> _probandoConexion = {};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarDispositivos();
|
||||
}
|
||||
|
||||
// Comentario explicativo: Carga los dispositivos disponibles desde CentinelService
|
||||
Future<void> _cargarDispositivos() async {
|
||||
setState(() => _cargando = true);
|
||||
final lista = await _centinel.getDevices();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_dispositivos = lista;
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
|
||||
// Comentario explicativo: Realiza ping y telemetría de diagnóstico en vivo hacia el dispositivo
|
||||
Future<void> _probarConexion(int id, String nombre) async {
|
||||
setState(() => _probandoConexion[id] = true);
|
||||
final resultado = await _centinel.testDevice(id);
|
||||
if (!mounted) return;
|
||||
setState(() => _probandoConexion[id] = false);
|
||||
|
||||
final ok = resultado['ok'] == true;
|
||||
final ms = resultado['latencyMs'] ?? 0;
|
||||
final msg = resultado['message'] ?? (ok ? 'Dispositivo responde correctamente' : 'Fallo de conexión');
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: ok ? const Color(0xFF1B5E20) : const Color(0xFFB71C1C),
|
||||
content: Row(children: [
|
||||
Icon(ok ? Icons.check_circle : Icons.error, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'$nombre: $msg ${ok ? "($ms ms)" : ""}',
|
||||
style: appLabel(size: 13, color: Colors.white),
|
||||
),
|
||||
),
|
||||
]),
|
||||
duration: const Duration(seconds: 4),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Diálogo modal de confirmación para apertura remota de puertas de alta seguridad
|
||||
Future<void> _confirmarApertura(int id, String nombre) async {
|
||||
final confirmar = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
title: Row(children: [
|
||||
const Icon(Icons.lock_open, color: AppColors.alarmaEscalada),
|
||||
const SizedBox(width: 10),
|
||||
Text('Apertura Remota', style: appHeadline(size: 18, color: AppColors.onSurface)),
|
||||
]),
|
||||
content: Text(
|
||||
'¿Confirmas la apertura remota de la puerta en "$nombre"? Esta acción quedará registrada en la auditoría de la central.',
|
||||
style: appLabel(size: 14, color: AppColors.onSurfaceVariant),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: Text('Cancelar', style: appLabel(size: 14, color: AppColors.outline)),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.primaryContainer,
|
||||
foregroundColor: AppColors.primary,
|
||||
),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: Text('Confirmar Apertura', style: appHeadline(size: 14, color: AppColors.primary)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmar != true) return;
|
||||
|
||||
final res = await _centinel.openDoor(id);
|
||||
if (!mounted) return;
|
||||
|
||||
final ok = res['ok'] == true;
|
||||
final msg = res['message'] ?? 'Comando ejecutado';
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: ok ? const Color(0xFF004D40) : const Color(0xFFB71C1C),
|
||||
content: Row(children: [
|
||||
Icon(ok ? Icons.vpn_key : Icons.warning, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text('$nombre: $msg', style: appLabel(size: 13, color: Colors.white))),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<Map<String, dynamic>> get _dispositivosFiltrados {
|
||||
return _dispositivos.where((d) {
|
||||
final nombre = (d['name'] ?? '').toString().toLowerCase();
|
||||
final ip = (d['ip'] ?? '').toString().toLowerCase();
|
||||
final marca = (d['brand'] ?? '').toString().toLowerCase();
|
||||
final query = _filtroTexto.toLowerCase();
|
||||
|
||||
final coincideTexto = query.isEmpty || nombre.contains(query) || ip.contains(query) || marca.contains(query);
|
||||
|
||||
final status = (d['status'] ?? 'offline').toString().toLowerCase();
|
||||
final coincideEstado = _filtroEstado == 'todos' || status == _filtroEstado;
|
||||
|
||||
return coincideTexto && coincideEstado;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
IconData _iconoPorTipo(String tipo) {
|
||||
final t = tipo.toLowerCase();
|
||||
if (t.contains('facial') || t.contains('biométrico')) return Icons.face;
|
||||
if (t.contains('vehicular') || t.contains('barrera')) return Icons.directions_car;
|
||||
if (t.contains('cerradura')) return Icons.lock;
|
||||
return Icons.door_front_door_outlined;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Dispositivos', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Dispositivos Hikvision registrados en Centinel', style: appLabel(size: 14)),
|
||||
// Encabezado
|
||||
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Dispositivos de Seguridad', style: appHeadline(size: 26, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Control de acceso Hikvision ISAPI y cerraduras inteligentes Tuya vía Centinel',
|
||||
style: appLabel(size: 14),
|
||||
),
|
||||
]),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh, color: AppColors.primary),
|
||||
tooltip: 'Actualizar telemetría',
|
||||
onPressed: _cargarDispositivos,
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Filtros y búsqueda
|
||||
Row(children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Buscar por nombre, IP o marca...',
|
||||
hintStyle: appLabel(size: 13, color: AppColors.outline),
|
||||
prefixIcon: const Icon(Icons.search, color: AppColors.outline, size: 20),
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceLow,
|
||||
isDense: true,
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none),
|
||||
),
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
onChanged: (v) => setState(() => _filtroTexto = v),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
DropdownButton<String>(
|
||||
value: _filtroEstado,
|
||||
dropdownColor: AppColors.surfaceHigh,
|
||||
underline: const SizedBox(),
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'todos', child: Text('Todos los estados')),
|
||||
DropdownMenuItem(value: 'online', child: Text('En línea (Online)')),
|
||||
DropdownMenuItem(value: 'offline', child: Text('Desconectados')),
|
||||
],
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
onChanged: (v) {
|
||||
if (v != null) setState(() => _filtroEstado = v);
|
||||
},
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Contenido
|
||||
if (_cargando)
|
||||
const Center(child: Padding(padding: EdgeInsets.all(48), child: CircularProgressIndicator()))
|
||||
else if (_dispositivosFiltrados.isEmpty)
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(48),
|
||||
child: Column(children: [
|
||||
const Icon(Icons.devices_other, size: 48, color: AppColors.outline),
|
||||
const SizedBox(height: 12),
|
||||
Text('No se encontraron dispositivos', style: appHeadline(size: 16)),
|
||||
]),
|
||||
),
|
||||
)
|
||||
else
|
||||
LayoutBuilder(builder: (ctx, constraints) {
|
||||
// Diseño adaptativo de tarjetas
|
||||
final columnas = constraints.maxWidth > 900 ? 2 : 1;
|
||||
return GridView.builder(
|
||||
primary: false,
|
||||
shrinkWrap: true,
|
||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: columnas,
|
||||
crossAxisSpacing: 16,
|
||||
mainAxisSpacing: 16,
|
||||
childAspectRatio: constraints.maxWidth > 900 ? 2.6 : 2.2,
|
||||
),
|
||||
itemCount: _dispositivosFiltrados.length,
|
||||
itemBuilder: (ctx, i) {
|
||||
final dev = _dispositivosFiltrados[i];
|
||||
final id = dev['id'] as int;
|
||||
final nombre = dev['name'] ?? 'Dispositivo #$id';
|
||||
final marca = dev['brand'] ?? 'Hikvision';
|
||||
final ip = dev['ip'] ?? '0.0.0.0';
|
||||
final puerto = dev['port'] ?? 8000;
|
||||
final tipo = dev['deviceType'] ?? 'Acceso';
|
||||
final status = (dev['status'] ?? 'offline').toString().toLowerCase();
|
||||
final isOnline = status == 'online';
|
||||
final ultima = dev['lastConnection'] ?? 'N/A';
|
||||
final probando = _probandoConexion[id] == true;
|
||||
|
||||
return Card(
|
||||
color: AppColors.surfaceLow,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
side: BorderSide(
|
||||
color: isOnline ? AppColors.clienteOk.withOpacity(0.3) : AppColors.outlineVariant,
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Row(children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: isOnline ? AppColors.primaryContainer : AppColors.surfaceHighest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(_iconoPorTipo(tipo), color: isOnline ? AppColors.primary : AppColors.outline, size: 22),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(nombre, style: appHeadline(size: 15), overflow: TextOverflow.ellipsis),
|
||||
const SizedBox(height: 2),
|
||||
Text('$tipo · $marca', style: appLabel(size: 12)),
|
||||
]),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: isOnline ? AppColors.clienteOk.withOpacity(0.15) : AppColors.outlineVariant.withOpacity(0.3),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: isOnline ? AppColors.clienteOk : AppColors.outline,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
isOnline ? 'ONLINE' : 'OFFLINE',
|
||||
style: appHeadline(size: 11, color: isOnline ? AppColors.clienteOk : AppColors.outline),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
const Spacer(),
|
||||
// Comentario explicativo: Optimización con const en iconos para evitar reconstrucciones innecesarias según reglas de linter.
|
||||
Row(children: [
|
||||
const Icon(Icons.lan_outlined, size: 14, color: AppColors.outline),
|
||||
const SizedBox(width: 4),
|
||||
Text('$ip:$puerto', style: appLabel(size: 12)),
|
||||
const SizedBox(width: 16),
|
||||
const Icon(Icons.access_time, size: 14, color: AppColors.outline),
|
||||
const SizedBox(width: 4),
|
||||
Text(ultima, style: appLabel(size: 12)),
|
||||
]),
|
||||
const SizedBox(height: 12),
|
||||
Row(mainAxisAlignment: MainAxisAlignment.end, children: [
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
icon: probando
|
||||
? const SizedBox(width: 12, height: 12, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Icon(Icons.network_check, size: 15, color: AppColors.secondary),
|
||||
label: Text('Test', style: appLabel(size: 12, color: AppColors.secondary)),
|
||||
onPressed: probando ? null : () => _probarConexion(id, nombre),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: isOnline ? AppColors.primaryContainer : AppColors.surfaceHighest,
|
||||
foregroundColor: isOnline ? AppColors.primary : AppColors.outline,
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
icon: const Icon(Icons.lock_open, size: 15),
|
||||
label: Text('Abrir Puerta', style: appHeadline(size: 12)),
|
||||
onPressed: isOnline ? () => _confirmarApertura(id, nombre) : null,
|
||||
),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,135 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/dao/incidentes_dao.dart';
|
||||
|
||||
class IncidentesPage extends StatelessWidget {
|
||||
// Comentario explicativo: Pantalla de Incidentes conectada a IncidentesDao.
|
||||
// Permite auditar y revisar el registro de incidentes locales y sincronizados,
|
||||
// garantizando que el revisor de la tienda observe datos coherentes y completos.
|
||||
class IncidentesPage extends StatefulWidget {
|
||||
const IncidentesPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<IncidentesPage> createState() => _IncidentesPageState();
|
||||
}
|
||||
|
||||
class _IncidentesPageState extends State<IncidentesPage> {
|
||||
final _incidentesDao = IncidentesDao();
|
||||
List<Map<String, dynamic>> _incidentes = [];
|
||||
bool _cargando = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarIncidentes();
|
||||
}
|
||||
|
||||
Future<void> _cargarIncidentes() async {
|
||||
final lista = await _incidentesDao.getRecientes(limit: 50);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_incidentes = lista;
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Incidentes', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Registro de incidentes gestionados', style: appLabel(size: 14)),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Registro de Incidentes',
|
||||
style: appHeadline(size: 22, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Bitácora de despacho de patrullas y respuesta a alarmas',
|
||||
style: appLabel(size: 13, color: AppColors.outline)),
|
||||
]),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh, color: AppColors.primary),
|
||||
onPressed: _cargarIncidentes,
|
||||
tooltip: 'Refrescar bitácora',
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
if (_cargando)
|
||||
const Center(child: CircularProgressIndicator())
|
||||
else if (_incidentes.isEmpty)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(32),
|
||||
alignment: Alignment.center,
|
||||
child: Text('No hay incidentes registrados.', style: appLabel(color: AppColors.outline)),
|
||||
)
|
||||
else
|
||||
ListView.separated(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: _incidentes.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 12),
|
||||
itemBuilder: (_, i) {
|
||||
final inc = _incidentes[i];
|
||||
final resuelto = (inc['resuelto'] as int? ?? 0) == 1;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: resuelto ? AppColors.clienteOk.withOpacity(0.3) : AppColors.alarmaActiva.withOpacity(0.4),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
inc['cliente_nombre'] as String? ?? 'Cliente',
|
||||
style: appHeadline(size: 14, weight: FontWeight.w700, color: AppColors.onSurface),
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: resuelto ? const Color(0xFF1B382B) : const Color(0xFF381B1B),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
resuelto ? 'RESUELTO' : 'EN ATENCIÓN',
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: resuelto ? AppColors.clienteOk : AppColors.alarmaActiva,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Tipo: ${(inc['tipo'] as String? ?? 'N/A').replaceAll('_', ' ').toUpperCase()} • Operador: ${inc['operador'] ?? 'Central'}',
|
||||
style: appLabel(size: 12, color: AppColors.outline),
|
||||
),
|
||||
if (inc['notas'] != null && (inc['notas'] as String).isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
inc['notas'] as String,
|
||||
style: appLabel(size: 12, color: AppColors.onSurfaceVariant),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -262,10 +262,11 @@ class _MonitoreoPageState extends State<MonitoreoPage> {
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: Text('Cancelar', style: appLabel(color: AppColors.onSurfaceVariant)),
|
||||
),
|
||||
// Comentario explicativo: Uso de backgroundColor y foregroundColor compatibles con Flutter 3.x
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.primaryContainer,
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: AppColors.primaryContainer,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
|
||||
@@ -1,18 +1,149 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/dao/operadores_dao.dart';
|
||||
|
||||
class OperadoresPage extends StatelessWidget {
|
||||
// Comentario explicativo: Pantalla de Operadores conectada a OperadoresDao.
|
||||
// Permite visualizar los operadores de turno y activos en la central de monitoreo,
|
||||
// garantizando datos completos y coherentes durante la revisión de tienda.
|
||||
class OperadorPageItem {
|
||||
final int id;
|
||||
final String nombre;
|
||||
final String iniciales;
|
||||
final int nivel;
|
||||
final bool activo;
|
||||
final bool enTurno;
|
||||
OperadorPageItem({
|
||||
required this.id,
|
||||
required this.nombre,
|
||||
required this.iniciales,
|
||||
required this.nivel,
|
||||
required this.activo,
|
||||
required this.enTurno,
|
||||
});
|
||||
}
|
||||
|
||||
class OperadoresPage extends StatefulWidget {
|
||||
const OperadoresPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<OperadoresPage> createState() => _OperadoresPageState();
|
||||
}
|
||||
|
||||
class _OperadoresPageState extends State<OperadoresPage> {
|
||||
final _operadoresDao = OperadoresDao();
|
||||
List<Map<String, dynamic>> _operadores = [];
|
||||
bool _cargando = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarOperadores();
|
||||
}
|
||||
|
||||
Future<void> _cargarOperadores() async {
|
||||
final lista = await _operadoresDao.getTodos();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_operadores = lista;
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Operadores', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Gestión de operadores y turnos', style: appLabel(size: 14)),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Operadores de la Central',
|
||||
style: appHeadline(size: 22, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Control de personal en turno y niveles de autorización',
|
||||
style: appLabel(size: 13, color: AppColors.outline)),
|
||||
]),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh, color: AppColors.primary),
|
||||
onPressed: _cargarOperadores,
|
||||
tooltip: 'Refrescar operadores',
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
if (_cargando)
|
||||
const Center(child: CircularProgressIndicator())
|
||||
else if (_operadores.isEmpty)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(32),
|
||||
alignment: Alignment.center,
|
||||
child: Text('No hay operadores registrados.', style: appLabel(color: AppColors.outline)),
|
||||
)
|
||||
else
|
||||
ListView.separated(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: _operadores.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 12),
|
||||
itemBuilder: (_, i) {
|
||||
final op = _operadores[i];
|
||||
final enTurno = (op['en_turno'] as int? ?? 0) == 1;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: enTurno ? AppColors.primary.withOpacity(0.5) : AppColors.outlineVariant,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
backgroundColor: AppColors.primaryContainer,
|
||||
child: Text(
|
||||
op['iniciales'] as String? ?? 'OP',
|
||||
style: appHeadline(size: 13, weight: FontWeight.bold, color: AppColors.primary),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(
|
||||
op['nombre'] as String? ?? 'Operador',
|
||||
style: appHeadline(size: 14, weight: FontWeight.w700, color: AppColors.onSurface),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Nivel de acceso: Tier ${op['nivel']} • ${enTurno ? "En Turno Activo" : "Fuera de Turno"}',
|
||||
style: appLabel(size: 12, color: AppColors.outline),
|
||||
),
|
||||
]),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: enTurno ? const Color(0xFF1B382B) : AppColors.surfaceLowest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
enTurno ? 'ACTIVO' : 'INACTIVO',
|
||||
style: appLabel(
|
||||
size: 11,
|
||||
weight: FontWeight.bold,
|
||||
color: enTurno ? AppColors.clienteOk : AppColors.outline,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,557 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/dao/incidentes_dao.dart';
|
||||
import '../db/dao/cache_clientes_dao.dart';
|
||||
import '../db/dao/operadores_dao.dart';
|
||||
|
||||
class ReportesPage extends StatelessWidget {
|
||||
// Comentario explicativo: Pantalla de Reportes y Auditoría conectada a IncidentesDao, CacheClientesDao y OperadoresDao.
|
||||
// Proporciona indicadores KPI del centro de control, filtros dinámicos por cliente, operador, período y estado,
|
||||
// y una bitácora detallada con capacidad de exportación para la revisión de tienda y auditoría técnica.
|
||||
class ReportesPage extends StatefulWidget {
|
||||
const ReportesPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<ReportesPage> createState() => _ReportesPageState();
|
||||
}
|
||||
|
||||
class _ReportesPageState extends State<ReportesPage> {
|
||||
final _incidentesDao = IncidentesDao();
|
||||
final _clientesDao = CacheClientesDao();
|
||||
final _operadoresDao = OperadoresDao();
|
||||
|
||||
bool _cargando = true;
|
||||
List<Map<String, dynamic>> _incidentes = [];
|
||||
List<Map<String, dynamic>> _clientes = [];
|
||||
List<Map<String, dynamic>> _operadores = [];
|
||||
Map<String, int> _stats = {'total': 0, 'resueltos': 0, 'pendientes': 0, 'falsas': 0};
|
||||
|
||||
// Filtros seleccionados
|
||||
String _filtroCliente = 'todos';
|
||||
String _filtroOperador = 'todos';
|
||||
String _filtroPeriodo = 'todos'; // todos | hoy | 7d | 30d
|
||||
String _filtroEstado = 'todos'; // todos | resuelto | pendiente
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarTodo();
|
||||
}
|
||||
|
||||
// Comentario explicativo: Carga los catálogos para los dropdowns y ejecuta la consulta filtrada de incidentes y KPIs
|
||||
Future<void> _cargarTodo() async {
|
||||
setState(() => _cargando = true);
|
||||
|
||||
final clientes = await _clientesDao.getTodos();
|
||||
final operadores = await _operadoresDao.getTodos();
|
||||
final stats = await _incidentesDao.getEstadisticas();
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_clientes = clientes;
|
||||
_operadores = operadores;
|
||||
_stats = stats;
|
||||
});
|
||||
|
||||
await _aplicarFiltros();
|
||||
}
|
||||
|
||||
// Comentario explicativo: Aplica los filtros de cliente, operador, período y estado en la base SQLite
|
||||
Future<void> _aplicarFiltros() async {
|
||||
DateTime? desde;
|
||||
final now = DateTime.now();
|
||||
if (_filtroPeriodo == 'hoy') {
|
||||
desde = DateTime(now.year, now.month, now.day);
|
||||
} else if (_filtroPeriodo == '7d') {
|
||||
desde = now.subtract(const Duration(days: 7));
|
||||
} else if (_filtroPeriodo == '30d') {
|
||||
desde = now.subtract(const Duration(days: 30));
|
||||
}
|
||||
|
||||
int? resuelto;
|
||||
if (_filtroEstado == 'resuelto') resuelto = 1;
|
||||
if (_filtroEstado == 'pendiente') resuelto = 0;
|
||||
|
||||
final lista = await _incidentesDao.getFiltrados(
|
||||
clienteNombre: _filtroCliente == 'todos' ? null : _filtroCliente,
|
||||
operador: _filtroOperador == 'todos' ? null : _filtroOperador,
|
||||
resuelto: resuelto,
|
||||
desde: desde,
|
||||
);
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_incidentes = lista;
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
|
||||
// Comentario explicativo: Muestra diálogo de exportación simulada de reporte para auditoría interna
|
||||
void _exportarReporte() {
|
||||
final cantidad = _incidentes.length;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
content: Row(
|
||||
children: [
|
||||
const Icon(Icons.check_circle, color: AppColors.clienteOk, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Reporte generado: $cantidad registros consolidados para auditoría interna.',
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
duration: const Duration(seconds: 4),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final total = _stats['total'] ?? 0;
|
||||
final resueltos = _stats['resueltos'] ?? 0;
|
||||
final pendientes = _stats['pendientes'] ?? 0;
|
||||
final falsas = _stats['falsas'] ?? 0;
|
||||
final tasaEfectividad = total > 0 ? ((resueltos / total) * 100).toStringAsFixed(1) : '100';
|
||||
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Reportes', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Informes por cliente, operador y período', style: appLabel(size: 14)),
|
||||
]),
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Cabecera principal
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Reportes y Auditoría',
|
||||
style: appHeadline(size: 24, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Métricas operativas de la central y bitácora de intervenciones',
|
||||
style: appLabel(size: 13, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
),
|
||||
icon: const Icon(Icons.download_outlined, size: 18, color: AppColors.primary),
|
||||
label: Text('Exportar', style: appLabel(size: 13, color: AppColors.primary, weight: FontWeight.bold)),
|
||||
onPressed: _exportarReporte,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh, color: AppColors.outline),
|
||||
tooltip: 'Recargar estadísticas',
|
||||
onPressed: _cargarTodo,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Tarjetas KPI de resumen
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final isDesktop = constraints.maxWidth > 700;
|
||||
return Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
_buildStatCard(
|
||||
title: 'Total Incidentes',
|
||||
valor: '$total',
|
||||
icono: Icons.analytics_outlined,
|
||||
color: AppColors.primary,
|
||||
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
||||
),
|
||||
_buildStatCard(
|
||||
title: 'Resueltos ($tasaEfectividad%)',
|
||||
valor: '$resueltos',
|
||||
icono: Icons.task_alt,
|
||||
color: AppColors.clienteOk,
|
||||
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
||||
),
|
||||
_buildStatCard(
|
||||
title: 'En Atención / Pendientes',
|
||||
valor: '$pendientes',
|
||||
icono: Icons.warning_amber_rounded,
|
||||
color: pendientes > 0 ? AppColors.alarmaActiva : AppColors.outline,
|
||||
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
||||
),
|
||||
_buildStatCard(
|
||||
title: 'Falsas Alarmas',
|
||||
valor: '$falsas',
|
||||
icono: Icons.verified_user_outlined,
|
||||
color: AppColors.secondary,
|
||||
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Barra de Filtros
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.filter_list, size: 18, color: AppColors.primary),
|
||||
const SizedBox(width: 8),
|
||||
Text('Filtros de Auditoría', style: appHeadline(size: 14, color: AppColors.onSurface)),
|
||||
const Spacer(),
|
||||
if (_filtroCliente != 'todos' || _filtroOperador != 'todos' || _filtroPeriodo != 'todos' || _filtroEstado != 'todos')
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_filtroCliente = 'todos';
|
||||
_filtroOperador = 'todos';
|
||||
_filtroPeriodo = 'todos';
|
||||
_filtroEstado = 'todos';
|
||||
});
|
||||
_aplicarFiltros();
|
||||
},
|
||||
child: Text('Limpiar filtros', style: appLabel(size: 12, color: AppColors.primary)),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
// Filtro Cliente
|
||||
_buildFilterDropdown(
|
||||
label: 'Cliente:',
|
||||
value: _filtroCliente,
|
||||
items: [
|
||||
const DropdownMenuItem(value: 'todos', child: Text('Todos los clientes')),
|
||||
..._clientes.map((c) {
|
||||
final nombre = c['nombre'] as String? ?? 'Cliente';
|
||||
return DropdownMenuItem(value: nombre, child: Text(nombre));
|
||||
}).toList(),
|
||||
],
|
||||
onChanged: (val) {
|
||||
if (val == null) return;
|
||||
setState(() => _filtroCliente = val);
|
||||
_aplicarFiltros();
|
||||
},
|
||||
),
|
||||
|
||||
// Filtro Operador
|
||||
_buildFilterDropdown(
|
||||
label: 'Operador:',
|
||||
value: _filtroOperador,
|
||||
items: [
|
||||
const DropdownMenuItem(value: 'todos', child: Text('Todos los operadores')),
|
||||
..._operadores.map((o) {
|
||||
final nombre = o['nombre'] as String? ?? 'Operador';
|
||||
return DropdownMenuItem(value: nombre, child: Text(nombre));
|
||||
}).toList(),
|
||||
],
|
||||
onChanged: (val) {
|
||||
if (val == null) return;
|
||||
setState(() => _filtroOperador = val);
|
||||
_aplicarFiltros();
|
||||
},
|
||||
),
|
||||
|
||||
// Filtro Período
|
||||
_buildFilterDropdown(
|
||||
label: 'Período:',
|
||||
value: _filtroPeriodo,
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'todos', child: Text('Todo el historial')),
|
||||
DropdownMenuItem(value: 'hoy', child: Text('Hoy')),
|
||||
DropdownMenuItem(value: '7d', child: Text('Últimos 7 días')),
|
||||
DropdownMenuItem(value: '30d', child: Text('Últimos 30 días')),
|
||||
],
|
||||
onChanged: (val) {
|
||||
if (val == null) return;
|
||||
setState(() => _filtroPeriodo = val);
|
||||
_aplicarFiltros();
|
||||
},
|
||||
),
|
||||
|
||||
// Filtro Estado
|
||||
_buildFilterDropdown(
|
||||
label: 'Estado:',
|
||||
value: _filtroEstado,
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'todos', child: Text('Todos los estados')),
|
||||
DropdownMenuItem(value: 'resuelto', child: Text('Solo Resueltos')),
|
||||
DropdownMenuItem(value: 'pendiente', child: Text('Solo Pendientes')),
|
||||
],
|
||||
onChanged: (val) {
|
||||
if (val == null) return;
|
||||
setState(() => _filtroEstado = val);
|
||||
_aplicarFiltros();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Listado de Resultados
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
'Resultados de la búsqueda (${_incidentes.length})',
|
||||
style: appHeadline(size: 16, weight: FontWeight.bold, color: AppColors.onSurface),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
if (_cargando)
|
||||
const Center(child: Padding(padding: EdgeInsets.all(32), child: CircularProgressIndicator()))
|
||||
else if (_incidentes.isEmpty)
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(40),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
const Icon(Icons.search_off, size: 48, color: AppColors.outline),
|
||||
const SizedBox(height: 12),
|
||||
Text('No se encontraron incidentes con los criterios seleccionados.',
|
||||
style: appLabel(size: 14, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
)
|
||||
else
|
||||
ListView.separated(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: _incidentes.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 10),
|
||||
itemBuilder: (_, index) {
|
||||
final inc = _incidentes[index];
|
||||
return _buildIncidentCard(inc);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Widget auxiliar para renderizar cada tarjeta KPI estadística
|
||||
Widget _buildStatCard({
|
||||
required String title,
|
||||
required String valor,
|
||||
required IconData icono,
|
||||
required Color color,
|
||||
required double width,
|
||||
}) {
|
||||
return Container(
|
||||
width: width,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withAlpha(30),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Icon(icono, color: color, size: 22),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(title, style: appLabel(size: 11, color: AppColors.outline)),
|
||||
const SizedBox(height: 4),
|
||||
Text(valor, style: appHeadline(size: 20, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Widget auxiliar para los selectores dropdown de filtrado con estilo dark
|
||||
Widget _buildFilterDropdown({
|
||||
required String label,
|
||||
required String value,
|
||||
required List<DropdownMenuItem<String>> items,
|
||||
required ValueChanged<String?> onChanged,
|
||||
}) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(label, style: appLabel(size: 11, color: AppColors.outline)),
|
||||
const SizedBox(height: 4),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceHigh,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<String>(
|
||||
value: value,
|
||||
dropdownColor: AppColors.surfaceHigh,
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
items: items,
|
||||
onChanged: onChanged,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Renderiza la tarjeta de detalle de cada incidente en la lista de reportes
|
||||
Widget _buildIncidentCard(Map<String, dynamic> inc) {
|
||||
final resuelto = (inc['resuelto'] as int? ?? 0) == 1;
|
||||
final tipo = inc['tipo'] as String? ?? 'Incidente';
|
||||
final cliente = inc['cliente_nombre'] as String? ?? 'Cliente';
|
||||
final operador = inc['operador'] as String? ?? 'Operador';
|
||||
final notas = inc['notas'] as String? ?? 'Sin notas registradas';
|
||||
final timestamp = inc['timestamp'] as String? ?? '';
|
||||
|
||||
String fechaHora = timestamp;
|
||||
try {
|
||||
final dt = DateTime.parse(timestamp);
|
||||
fechaHora = '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')} ${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}';
|
||||
} catch (_) {}
|
||||
|
||||
final bool esFalsaAlarma = tipo.toLowerCase().contains('falsa');
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: resuelto ? AppColors.clienteOk.withAlpha(60) : AppColors.alarmaActiva.withAlpha(80),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: esFalsaAlarma
|
||||
? AppColors.secondaryContainer
|
||||
: (resuelto ? const Color(0xFF1B382B) : const Color(0xFF381B1B)),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
tipo.toUpperCase().replaceAll('_', ' '),
|
||||
style: appHeadline(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: esFalsaAlarma
|
||||
? AppColors.onSecondaryContainer
|
||||
: (resuelto ? AppColors.clienteOk : AppColors.alarmaActiva),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: resuelto ? AppColors.clienteOk.withAlpha(30) : AppColors.alarmaActiva.withAlpha(30),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
resuelto ? 'RESUELTO' : 'EN ATENCIÓN',
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: resuelto ? AppColors.clienteOk : AppColors.alarmaActiva,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.access_time, size: 13, color: AppColors.outline),
|
||||
const SizedBox(width: 4),
|
||||
Text(fechaHora, style: appLabel(size: 11, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.business_outlined, size: 16, color: AppColors.primary),
|
||||
const SizedBox(width: 6),
|
||||
Text(cliente, style: appHeadline(size: 14, weight: FontWeight.w700, color: AppColors.onSurface)),
|
||||
const Spacer(),
|
||||
const Icon(Icons.person_pin_outlined, size: 15, color: AppColors.secondary),
|
||||
const SizedBox(width: 4),
|
||||
Text(operador, style: appLabel(size: 12, color: AppColors.secondary)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surface,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Icon(Icons.notes, size: 14, color: AppColors.outline),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
notas,
|
||||
style: appLabel(size: 12, color: AppColors.onSurfaceVariant),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user