feat: submenu tactico (camaras, rastreo OSM/CartoDB), comunicacion, consola datos SQLite, clientes tipo_servicio y documentacion estandar
This commit is contained in:
@@ -21,6 +21,26 @@ class CacheClientesDao {
|
||||
return result.first['c'] as int;
|
||||
}
|
||||
|
||||
// Comentario explicativo: Inserta o actualiza un nuevo cliente en la tabla cache_clientes de SQLite local
|
||||
Future<int> insertar(Map<String, dynamic> cliente) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('cache_clientes', cliente, conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Elimina un cliente por su identificador primario
|
||||
Future<int> eliminar(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.delete('cache_clientes', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Calcula el siguiente ID disponible para registrar clientes locales offline
|
||||
Future<int> obtenerSiguienteId() async {
|
||||
final db = await _db.db;
|
||||
final res = await db.rawQuery('SELECT MAX(id) as max_id FROM cache_clientes');
|
||||
final maxId = (res.first['max_id'] as int?) ?? 100;
|
||||
return maxId + 1;
|
||||
}
|
||||
|
||||
Future<void> reemplazarTodos(List<Map<String, dynamic>> clientes) async {
|
||||
final db = await _db.db;
|
||||
await db.delete('cache_clientes');
|
||||
|
||||
@@ -25,7 +25,16 @@ class DatabaseHelper {
|
||||
}
|
||||
|
||||
final path = await _dbPath();
|
||||
return openDatabase(path, version: _dbVersion, onCreate: _onCreate);
|
||||
final database = await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
|
||||
|
||||
// Comentario explicativo: Migración progresiva para garantizar la columna 'tipo_servicio' en cache_clientes si la base de datos ya existía en disco
|
||||
try {
|
||||
await database.execute("ALTER TABLE cache_clientes ADD COLUMN tipo_servicio TEXT DEFAULT 'Monitoreo de Alarmas'");
|
||||
} catch (_) {
|
||||
// Ignorar si la columna ya existe en la tabla
|
||||
}
|
||||
|
||||
return database;
|
||||
}
|
||||
|
||||
Future<String> _dbPath() async {
|
||||
@@ -65,6 +74,7 @@ class DatabaseHelper {
|
||||
estado TEXT NOT NULL DEFAULT 'normal',
|
||||
alarmas_activas INTEGER NOT NULL DEFAULT 0,
|
||||
alarmas_criticas INTEGER NOT NULL DEFAULT 0,
|
||||
tipo_servicio TEXT NOT NULL DEFAULT 'Monitoreo de Alarmas',
|
||||
ultima_actualizacion TEXT
|
||||
)
|
||||
''');
|
||||
@@ -148,6 +158,8 @@ class DatabaseHelper {
|
||||
'estado': 'critica',
|
||||
'alarmas_activas': 2,
|
||||
'alarmas_criticas': 1,
|
||||
// Comentario explicativo: Servicio integral asignado al cliente bancario con alarmas y video
|
||||
'tipo_servicio': 'Servicio Integral 360',
|
||||
'ultima_actualizacion': nowIso,
|
||||
},
|
||||
{
|
||||
@@ -156,6 +168,8 @@ class DatabaseHelper {
|
||||
'estado': 'alerta',
|
||||
'alarmas_activas': 1,
|
||||
'alarmas_criticas': 0,
|
||||
// Comentario explicativo: Servicio de videovigilancia CCTV asociado al centro comercial
|
||||
'tipo_servicio': 'CCTV / Video-vigilancia',
|
||||
'ultima_actualizacion': nowIso,
|
||||
},
|
||||
{
|
||||
@@ -164,6 +178,8 @@ class DatabaseHelper {
|
||||
'estado': 'normal',
|
||||
'alarmas_activas': 0,
|
||||
'alarmas_criticas': 0,
|
||||
// Comentario explicativo: Servicio de control de acceso corporativo
|
||||
'tipo_servicio': 'Control de Acceso',
|
||||
'ultima_actualizacion': nowIso,
|
||||
},
|
||||
{
|
||||
@@ -172,6 +188,8 @@ class DatabaseHelper {
|
||||
'estado': 'alerta',
|
||||
'alarmas_activas': 1,
|
||||
'alarmas_criticas': 0,
|
||||
// Comentario explicativo: Servicio de rastreo vehicular GPS para la flota logística
|
||||
'tipo_servicio': 'Rastreo Satelital GPS',
|
||||
'ultima_actualizacion': nowIso,
|
||||
},
|
||||
{
|
||||
@@ -180,6 +198,8 @@ class DatabaseHelper {
|
||||
'estado': 'normal',
|
||||
'alarmas_activas': 0,
|
||||
'alarmas_criticas': 0,
|
||||
// Comentario explicativo: Servicio clásico de monitoreo de alarmas perimetrales
|
||||
'tipo_servicio': 'Monitoreo de Alarmas',
|
||||
'ultima_actualizacion': nowIso,
|
||||
},
|
||||
];
|
||||
@@ -344,6 +364,80 @@ class DatabaseHelper {
|
||||
};
|
||||
}
|
||||
|
||||
// Comentario explicativo: Obtiene métricas ampliadas de todas las tablas de SQLite para el panel de Administrar Datos
|
||||
Future<Map<String, int>> getMetricasDetalladasDb() async {
|
||||
final dbInstance = await db;
|
||||
final alarmasRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM cache_alarmas');
|
||||
final clientesRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM cache_clientes');
|
||||
final incidentesRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM incidentes');
|
||||
final syncLogsRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM sync_log');
|
||||
final operadoresRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM operadores');
|
||||
final sesionesRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM sesiones_operador');
|
||||
final configRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM configuracion');
|
||||
|
||||
return {
|
||||
'alarmas': (alarmasRes.isNotEmpty ? alarmasRes.first['c'] as int? : 0) ?? 0,
|
||||
'clientes': (clientesRes.isNotEmpty ? clientesRes.first['c'] as int? : 0) ?? 0,
|
||||
'incidentes': (incidentesRes.isNotEmpty ? incidentesRes.first['c'] as int? : 0) ?? 0,
|
||||
'sync_logs': (syncLogsRes.isNotEmpty ? syncLogsRes.first['c'] as int? : 0) ?? 0,
|
||||
'operadores': (operadoresRes.isNotEmpty ? operadoresRes.first['c'] as int? : 0) ?? 0,
|
||||
'sesiones': (sesionesRes.isNotEmpty ? sesionesRes.first['c'] as int? : 0) ?? 0,
|
||||
'config': (configRes.isNotEmpty ? configRes.first['c'] as int? : 0) ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Comentario explicativo: Reinicializa completamente la base de datos local SQLite, vaciando todas las tablas
|
||||
// operativas y restableciendo los parámetros por defecto del sistema
|
||||
Future<void> reinicializarBaseDatos() async {
|
||||
final dbInstance = await db;
|
||||
final batch = dbInstance.batch();
|
||||
|
||||
// Vaciado de tablas operativas
|
||||
batch.delete('cache_alarmas');
|
||||
batch.delete('cache_clientes');
|
||||
batch.delete('incidentes');
|
||||
batch.delete('operadores');
|
||||
batch.delete('sesiones_operador');
|
||||
batch.delete('sync_log');
|
||||
|
||||
// Restablecimiento de configuración por defecto
|
||||
batch.delete('configuracion');
|
||||
batch.insert('configuracion', {'clave': 'poll_interval_seg', 'valor': '30'});
|
||||
batch.insert('configuracion', {'clave': 'sonido_alerta', 'valor': '1'});
|
||||
batch.insert('configuracion', {'clave': 'alerta_prioritaria','valor': '1'});
|
||||
|
||||
// Registro de auditoría del evento de reinicio
|
||||
batch.insert('sync_log', {
|
||||
'tipo': 'db_init_reset',
|
||||
'estado': 'ok',
|
||||
'detalle': 'Base de datos reinicializada manualmente a estado de fábrica',
|
||||
'timestamp': DateTime.now().toIso8601String(),
|
||||
});
|
||||
|
||||
await batch.commit(noResult: true);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Vacía únicamente las tablas de caché temporal (alarmas y clientes) sin alterar incidentes ni operadores
|
||||
Future<void> vaciarCacheOperativo() async {
|
||||
final dbInstance = await db;
|
||||
final batch = dbInstance.batch();
|
||||
batch.delete('cache_alarmas');
|
||||
batch.delete('cache_clientes');
|
||||
batch.insert('sync_log', {
|
||||
'tipo': 'cache_clear',
|
||||
'estado': 'ok',
|
||||
'detalle': 'Caché operativo de alarmas y clientes vaciado manualmente',
|
||||
'timestamp': DateTime.now().toIso8601String(),
|
||||
});
|
||||
await batch.commit(noResult: true);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Vacía la tabla de incidentes locales para reiniciar el registro de eventos de turno
|
||||
Future<void> limpiarIncidentes() async {
|
||||
final dbInstance = await db;
|
||||
await dbInstance.delete('incidentes');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Limpia el historial de sincronización local conservando la integridad de las demás tablas
|
||||
Future<void> limpiarSyncLogs() async {
|
||||
final dbInstance = await db;
|
||||
|
||||
@@ -0,0 +1,768 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
// Comentario explicativo: Importamos CacheClientesDao para persistir nuevos clientes agregados desde monitoreo de cámaras en la base de datos SQLite
|
||||
import '../db/dao/cache_clientes_dao.dart';
|
||||
|
||||
// Comentario explicativo: Pantalla de Cámaras y Video-verificación CCTV.
|
||||
// Expone grilla de monitoreo en vivo (1x1, 2x2, 3x3) para cámaras Hikvision ISAPI y Tuya IoT,
|
||||
// permitiendo a los operadores verificar visualmente si una intrusión es real antes del despacho.
|
||||
class CamarasPage extends StatefulWidget {
|
||||
const CamarasPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<CamarasPage> createState() => _CamarasPageState();
|
||||
}
|
||||
|
||||
class _CamarasPageState extends State<CamarasPage> {
|
||||
final _clientesDao = CacheClientesDao();
|
||||
int _cuadricula = 4; // 1, 4 (2x2), 9 (3x3)
|
||||
int? _camaraSeleccionada;
|
||||
String _filtroCliente = 'todos';
|
||||
List<String> _listaClientes = [
|
||||
'todos',
|
||||
'Banco Metropolitano',
|
||||
'Centro Comercial Gran Plaza',
|
||||
'Torre Empresarial Sigma',
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarClientesDb();
|
||||
}
|
||||
|
||||
// Comentario explicativo: Carga los clientes desde la base de datos SQLite y los unifica con los clientes de las cámaras
|
||||
Future<void> _cargarClientesDb() async {
|
||||
try {
|
||||
final clientesDb = await _clientesDao.getTodos();
|
||||
final setNombres = <String>{'todos'};
|
||||
for (final cam in _camaras) {
|
||||
final cli = cam['cliente'] as String?;
|
||||
if (cli != null && cli.isNotEmpty) setNombres.add(cli);
|
||||
}
|
||||
for (final c in clientesDb) {
|
||||
final nom = c['nombre'] as String?;
|
||||
if (nom != null && nom.isNotEmpty) setNombres.add(nom);
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_listaClientes = setNombres.toList();
|
||||
});
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// Canales de cámaras simulados / en vivo
|
||||
final List<Map<String, dynamic>> _camaras = [
|
||||
{
|
||||
'id': 1,
|
||||
'nombre': 'CAM 01 - Bóveda Principal',
|
||||
'cliente': 'Banco Metropolitano',
|
||||
'zona': 'Bóveda Subterránea',
|
||||
'ip': '192.168.10.201',
|
||||
'estado': 'online',
|
||||
'fps': 25,
|
||||
'resolucion': '4K (3840x2160)',
|
||||
'tipo': 'Hikvision ISAPI PTZ',
|
||||
'conAlarma': true,
|
||||
},
|
||||
{
|
||||
'id': 2,
|
||||
'nombre': 'CAM 02 - Acceso Principal Peatonal',
|
||||
'cliente': 'Banco Metropolitano',
|
||||
'zona': 'Lobby Entrada',
|
||||
'ip': '192.168.10.202',
|
||||
'estado': 'online',
|
||||
'fps': 30,
|
||||
'resolucion': '1080p (1920x1080)',
|
||||
'tipo': 'Hikvision Domo IR',
|
||||
'conAlarma': false,
|
||||
},
|
||||
{
|
||||
'id': 3,
|
||||
'nombre': 'CAM 03 - Pasillo Central Comercial',
|
||||
'cliente': 'Centro Comercial Gran Plaza',
|
||||
'zona': 'Pasillo Nivel 1',
|
||||
'ip': '192.168.10.205',
|
||||
'estado': 'online',
|
||||
'fps': 20,
|
||||
'resolucion': '1080p (1920x1080)',
|
||||
'tipo': 'Tuya Smart Bullet',
|
||||
'conAlarma': true,
|
||||
},
|
||||
{
|
||||
'id': 4,
|
||||
'nombre': 'CAM 04 - Estacionamiento Subterráneo',
|
||||
'cliente': 'Centro Comercial Gran Plaza',
|
||||
'zona': 'Sótano -2',
|
||||
'ip': '192.168.10.206',
|
||||
'estado': 'online',
|
||||
'fps': 25,
|
||||
'resolucion': '1080p (1920x1080)',
|
||||
'tipo': 'Hikvision ISAPI LPR',
|
||||
'conAlarma': false,
|
||||
},
|
||||
{
|
||||
'id': 5,
|
||||
'nombre': 'CAM 05 - Recepción y Molinetes',
|
||||
'cliente': 'Torre Empresarial Sigma',
|
||||
'zona': 'Ingreso Torre A',
|
||||
'ip': '192.168.10.210',
|
||||
'estado': 'online',
|
||||
'fps': 30,
|
||||
'resolucion': '2K (2560x1440)',
|
||||
'tipo': 'Hikvision Reconocimiento Facial',
|
||||
'conAlarma': false,
|
||||
},
|
||||
{
|
||||
'id': 6,
|
||||
'nombre': 'CAM 06 - Perímetro Posterior',
|
||||
'cliente': 'Torre Empresarial Sigma',
|
||||
'zona': 'Cerca Perimetral',
|
||||
'ip': '192.168.10.211',
|
||||
'estado': 'offline',
|
||||
'fps': 0,
|
||||
'resolucion': 'Sin señal',
|
||||
'tipo': 'Tuya Smart Térmica',
|
||||
'conAlarma': false,
|
||||
},
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final camarasVisibles = _filtroCliente == 'todos'
|
||||
? _camaras
|
||||
: _camaras.where((c) => c['cliente'] == _filtroCliente).toList();
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Barra de controles de video-verificación
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text('Video-Verificación y Circuito Cerrado (CCTV)',
|
||||
style: appHeadline(size: 20, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
const SizedBox(width: 10),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF1B382B),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text('LIVE STREAM',
|
||||
style: appLabel(size: 10, weight: FontWeight.bold, color: AppColors.clienteOk)),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text('Feeds en vivo Hikvision ISAPI y Tuya Smart IoT con soporte de snapshot y PTZ',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
// Selector de layout de cuadrícula
|
||||
Container(
|
||||
height: 38,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
_btnLayout(1, Icons.crop_square),
|
||||
_btnLayout(4, Icons.grid_view),
|
||||
_btnLayout(9, Icons.grid_on),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// Comentario explicativo: Columna que ubica el botón de agregar (+add) en la parte superior del select de clientes
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Botón (+add) para registrar un nuevo cliente desde la vista de cámaras
|
||||
InkWell(
|
||||
onTap: _mostrarDialogoNuevoCliente,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
margin: const EdgeInsets.only(bottom: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primaryContainer.withValues(alpha: 0.4),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: AppColors.primary.withValues(alpha: 0.5)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.add_circle, size: 14, color: AppColors.primary),
|
||||
const SizedBox(width: 5),
|
||||
Text(
|
||||
'(+add) Agregar Cliente',
|
||||
style: appLabel(size: 11, weight: FontWeight.w700, color: AppColors.primary),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
// Dropdown dinámico para filtrar por cliente seleccionado
|
||||
Container(
|
||||
height: 38,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<String>(
|
||||
value: _listaClientes.contains(_filtroCliente) ? _filtroCliente : 'todos',
|
||||
dropdownColor: AppColors.surfaceHigh,
|
||||
style: appLabel(size: 12, color: AppColors.onSurface),
|
||||
items: _listaClientes.map((nombre) {
|
||||
return DropdownMenuItem(
|
||||
value: nombre,
|
||||
child: Text(nombre == 'todos' ? 'Todos los clientes' : nombre),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (v) {
|
||||
if (v != null) setState(() => _filtroCliente = v);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Grilla de Cámaras
|
||||
Expanded(
|
||||
child: _cuadricula == 1 && _camaraSeleccionada != null
|
||||
? _buildVistaDetallada(
|
||||
_camaras.firstWhere((c) => c['id'] == _camaraSeleccionada, orElse: () => _camaras.first))
|
||||
: GridView.builder(
|
||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: _cuadricula == 1 ? 1 : (_cuadricula == 4 ? 2 : 3),
|
||||
crossAxisSpacing: 14,
|
||||
mainAxisSpacing: 14,
|
||||
childAspectRatio: 16 / 10,
|
||||
),
|
||||
itemCount: camarasVisibles.length,
|
||||
itemBuilder: (ctx, i) => _buildTarjetaCamara(camarasVisibles[i]),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Botón selector de disposición de cuadrícula de video (1x1, 2x2, 3x3)
|
||||
Widget _btnLayout(int count, IconData icono) {
|
||||
final activo = _cuadricula == count;
|
||||
return InkWell(
|
||||
onTap: () => setState(() => _cuadricula = count),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
color: activo ? AppColors.primaryContainer : Colors.transparent,
|
||||
child: Icon(icono, size: 18, color: activo ? AppColors.primary : AppColors.outline),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Tarjeta de cámara individual con overlay de estado, alarma y datos de stream
|
||||
Widget _buildTarjetaCamara(Map<String, dynamic> cam) {
|
||||
final conAlarma = cam['conAlarma'] == true;
|
||||
final online = cam['estado'] == 'online';
|
||||
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_cuadricula = 1;
|
||||
_camaraSeleccionada = cam['id'] as int;
|
||||
});
|
||||
},
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF0F141A),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: conAlarma ? AppColors.alarmaActiva : AppColors.outlineVariant,
|
||||
width: conAlarma ? 2 : 1,
|
||||
),
|
||||
),
|
||||
child: Stack(
|
||||
children: [
|
||||
// Feed simulado
|
||||
Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
online ? Icons.videocam : Icons.videocam_off_outlined,
|
||||
size: 40,
|
||||
color: online ? (conAlarma ? AppColors.alarmaActiva : AppColors.outline) : AppColors.error,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
online ? 'CANAL EN VIVO RTSP' : 'SEÑAL PERDIDA (OFFLINE)',
|
||||
style: appLabel(
|
||||
size: 11,
|
||||
weight: FontWeight.bold,
|
||||
color: online ? AppColors.outline : AppColors.error,
|
||||
),
|
||||
),
|
||||
if (online)
|
||||
Text('${cam['resolucion']} @ ${cam['fps']} FPS',
|
||||
style: appLabel(size: 10, color: AppColors.outlineVariant)),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Header con nombre de cámara y badge
|
||||
Positioned(
|
||||
top: 10,
|
||||
left: 12,
|
||||
right: 12,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(cam['nombre'],
|
||||
style: appHeadline(size: 13, weight: FontWeight.w700, color: Colors.white),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis),
|
||||
Text('${cam['cliente']} • ${cam['zona']}',
|
||||
style: appLabel(size: 10, color: Colors.white70),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (conAlarma)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.alarmaActiva,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Text('ALARMA', style: appLabel(size: 9, weight: FontWeight.bold, color: Colors.white)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Barra inferior con IP y tipo de cámara
|
||||
Positioned(
|
||||
bottom: 8,
|
||||
left: 12,
|
||||
right: 12,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(cam['ip'], style: appLabel(size: 10, color: Colors.white54)),
|
||||
Text(cam['tipo'], style: appLabel(size: 10, color: Colors.white54)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Vista de cámara ampliada en pantalla completa con controles de paneo, zoom y snapshot
|
||||
Widget _buildVistaDetallada(Map<String, dynamic> cam) {
|
||||
return Column(
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.surfaceLow,
|
||||
foregroundColor: AppColors.onSurface,
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
icon: const Icon(Icons.arrow_back, size: 16),
|
||||
label: Text('Volver a cuadrícula', style: appLabel(size: 12)),
|
||||
onPressed: () => setState(() => _cuadricula = 4),
|
||||
),
|
||||
Text('${cam['nombre']} (${cam['cliente']})',
|
||||
style: appHeadline(size: 16, weight: FontWeight.w700, color: AppColors.onSurface)),
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.camera_alt_outlined, color: AppColors.primary, size: 20),
|
||||
tooltip: 'Tomar instantánea (Snapshot)',
|
||||
onPressed: () {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
content: Text('Instantánea capturada y guardada en auditoría.', style: appLabel()),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.videocam_outlined, color: AppColors.clienteOk, size: 20),
|
||||
tooltip: 'Grabación manual',
|
||||
onPressed: () {},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Expanded(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF0A0E14),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Stack(
|
||||
children: [
|
||||
Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.videocam, size: 80, color: AppColors.outline),
|
||||
const SizedBox(height: 12),
|
||||
Text('STREAM EN DIRECTO RTSP / ISAPI HIKVISION',
|
||||
style: appHeadline(size: 14, color: AppColors.onSurfaceVariant)),
|
||||
const SizedBox(height: 4),
|
||||
Text('${cam['resolucion']} • Protocolo Seguro H.265+',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Controles PTZ virtuales sobreimpresos
|
||||
Positioned(
|
||||
bottom: 20,
|
||||
right: 20,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.7),
|
||||
borderRadius: BorderRadius.circular(30),
|
||||
border: Border.all(color: Colors.white24),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
IconButton(icon: const Icon(Icons.arrow_drop_up, color: Colors.white), onPressed: () {}),
|
||||
Row(
|
||||
children: [
|
||||
IconButton(icon: const Icon(Icons.arrow_left, color: Colors.white), onPressed: () {}),
|
||||
const Icon(Icons.control_camera, color: AppColors.primary, size: 20),
|
||||
IconButton(icon: const Icon(Icons.arrow_right, color: Colors.white), onPressed: () {}),
|
||||
],
|
||||
),
|
||||
IconButton(icon: const Icon(Icons.arrow_drop_down, color: Colors.white), onPressed: () {}),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Abre un diálogo modal para registrar un nuevo cliente y asociarle un canal de cámara CCTV
|
||||
Future<void> _mostrarDialogoNuevoCliente() async {
|
||||
final clienteCtrl = TextEditingController();
|
||||
final camaraCtrl = TextEditingController(text: 'CAM 0${_camaras.length + 1} - Entrada Principal');
|
||||
final zonaCtrl = TextEditingController(text: 'Acceso Peatonal');
|
||||
final ipCtrl = TextEditingController(text: '192.168.10.${212 + _camaras.length}');
|
||||
String servicio = 'CCTV / Video-vigilancia';
|
||||
String tipoCam = 'Hikvision ISAPI PTZ';
|
||||
const resolucion = '1080p (1920x1080)';
|
||||
bool conAlarma = false;
|
||||
|
||||
await showDialog(
|
||||
context: context,
|
||||
builder: (ctx) {
|
||||
return StatefulBuilder(
|
||||
builder: (dialogCtx, setDialogState) {
|
||||
return AlertDialog(
|
||||
backgroundColor: AppColors.surface,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Icon(Icons.videocam, color: AppColors.primary, size: 20),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text('Agregar Cliente / Feed CCTV',
|
||||
style: appHeadline(size: 16, weight: FontWeight.bold, color: AppColors.onSurface)),
|
||||
],
|
||||
),
|
||||
content: SizedBox(
|
||||
width: 480,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Nombre del Cliente / Empresa *', style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 6),
|
||||
TextField(
|
||||
controller: clienteCtrl,
|
||||
style: appLabel(color: AppColors.onSurface),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Ej. Corporación Andina / Edificio Central',
|
||||
hintStyle: appLabel(color: AppColors.outline),
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceLow,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: AppColors.outlineVariant)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Text('Tipo de Servicio Asociado', style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 6),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<String>(
|
||||
value: servicio,
|
||||
isExpanded: true,
|
||||
dropdownColor: AppColors.surfaceHigh,
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'CCTV / Video-vigilancia', child: Text('CCTV / Video-vigilancia')),
|
||||
DropdownMenuItem(value: 'Monitoreo de Alarmas', child: Text('Monitoreo de Alarmas')),
|
||||
DropdownMenuItem(value: 'Rastreo Satelital GPS', child: Text('Rastreo Satelital GPS')),
|
||||
DropdownMenuItem(value: 'Control de Acceso', child: Text('Control de Acceso')),
|
||||
DropdownMenuItem(value: 'Servicio Integral 360', child: Text('Servicio Integral 360')),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v != null) setDialogState(() => servicio = v);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Nombre de Cámara', style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 6),
|
||||
TextField(
|
||||
controller: camaraCtrl,
|
||||
style: appLabel(color: AppColors.onSurface),
|
||||
decoration: InputDecoration(
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceLow,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: AppColors.outlineVariant)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Zona / Sede', style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 6),
|
||||
TextField(
|
||||
controller: zonaCtrl,
|
||||
style: appLabel(color: AppColors.onSurface),
|
||||
decoration: InputDecoration(
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceLow,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: AppColors.outlineVariant)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('IP de Cámara / Host ISAPI', style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 6),
|
||||
TextField(
|
||||
controller: ipCtrl,
|
||||
style: appLabel(color: AppColors.onSurface),
|
||||
decoration: InputDecoration(
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceLow,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: AppColors.outlineVariant)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Tecnología / Marca', style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 6),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<String>(
|
||||
value: tipoCam,
|
||||
isExpanded: true,
|
||||
dropdownColor: AppColors.surfaceHigh,
|
||||
style: appLabel(size: 11, color: AppColors.onSurface),
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'Hikvision ISAPI PTZ', child: Text('Hikvision PTZ')),
|
||||
DropdownMenuItem(value: 'Hikvision Domo IR', child: Text('Hikvision Domo')),
|
||||
DropdownMenuItem(value: 'Tuya Smart Bullet', child: Text('Tuya Bullet')),
|
||||
DropdownMenuItem(value: 'Hikvision ISAPI LPR', child: Text('Hikvision LPR')),
|
||||
DropdownMenuItem(value: 'Tuya Smart Térmica', child: Text('Tuya Térmica')),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v != null) setDialogState(() => tipoCam = v);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
CheckboxListTile(
|
||||
value: conAlarma,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text('Vincular con alarma activa inmediata', style: appLabel(size: 12, color: AppColors.onSurface)),
|
||||
subtitle: Text('Simula un disparo perimetral en la zona de video para pruebas de verificación', style: appLabel(size: 10, color: AppColors.outline)),
|
||||
onChanged: (val) {
|
||||
setDialogState(() => conAlarma = val ?? false);
|
||||
},
|
||||
activeColor: AppColors.alarmaActiva,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogCtx),
|
||||
child: Text('Cancelar', style: appLabel(color: AppColors.outline)),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: const Color(0xFF002F6C),
|
||||
),
|
||||
icon: const Icon(Icons.add, size: 16),
|
||||
label: const Text('Guardar Cliente'),
|
||||
onPressed: () async {
|
||||
final nombre = clienteCtrl.text.trim();
|
||||
if (nombre.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Por favor ingresa el nombre del cliente.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Comentario explicativo: Registrar cliente en la base de datos SQLite local
|
||||
final nuevoId = await _clientesDao.obtenerSiguienteId();
|
||||
await _clientesDao.insertar({
|
||||
'id': nuevoId,
|
||||
'nombre': nombre,
|
||||
'estado': conAlarma ? 'alerta' : 'normal',
|
||||
'alarmas_activas': conAlarma ? 1 : 0,
|
||||
'alarmas_criticas': 0,
|
||||
'tipo_servicio': servicio,
|
||||
'ultima_actualizacion': DateTime.now().toIso8601String(),
|
||||
});
|
||||
|
||||
// Comentario explicativo: Insertar nueva cámara en el listado reactivo de video
|
||||
final nuevaCam = {
|
||||
'id': _camaras.length + 1,
|
||||
'nombre': camaraCtrl.text.trim().isNotEmpty ? camaraCtrl.text.trim() : 'CAM - $nombre',
|
||||
'cliente': nombre,
|
||||
'zona': zonaCtrl.text.trim().isNotEmpty ? zonaCtrl.text.trim() : 'Sede Principal',
|
||||
'ip': ipCtrl.text.trim().isNotEmpty ? ipCtrl.text.trim() : '192.168.10.220',
|
||||
'estado': 'online',
|
||||
'fps': 25,
|
||||
'resolucion': resolucion,
|
||||
'tipo': tipoCam,
|
||||
'conAlarma': conAlarma,
|
||||
};
|
||||
|
||||
setState(() {
|
||||
_camaras.add(nuevaCam);
|
||||
_filtroCliente = nombre;
|
||||
});
|
||||
|
||||
await _cargarClientesDb();
|
||||
if (mounted) {
|
||||
Navigator.pop(dialogCtx);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
content: Text('Cliente "$nombre" y canal de cámara registrados con éxito.',
|
||||
style: appLabel(color: AppColors.clienteOk)),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
+427
-12
@@ -3,8 +3,8 @@ import '../theme.dart';
|
||||
import '../db/dao/cache_clientes_dao.dart';
|
||||
|
||||
// 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.
|
||||
// Permite listar, filtrar por tipo de servicio y registrar nuevos clientes con su tipo de servicio asociado
|
||||
// (Alarmas, CCTV, Rastreo GPS, Control de Acceso, Servicio Integral 360) garantizando funcionamiento offline.
|
||||
class ClientesPage extends StatefulWidget {
|
||||
const ClientesPage({Key? key}) : super(key: key);
|
||||
|
||||
@@ -16,6 +16,7 @@ class _ClientesPageState extends State<ClientesPage> {
|
||||
final _clientesDao = CacheClientesDao();
|
||||
List<Map<String, dynamic>> _clientes = [];
|
||||
bool _cargando = true;
|
||||
String _filtroServicio = 'todos';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -23,6 +24,7 @@ class _ClientesPageState extends State<ClientesPage> {
|
||||
_cargarClientes();
|
||||
}
|
||||
|
||||
// Comentario explicativo: Carga los clientes desde la base de datos local SQLite
|
||||
Future<void> _cargarClientes() async {
|
||||
final lista = await _clientesDao.getTodos();
|
||||
if (!mounted) return;
|
||||
@@ -43,12 +45,298 @@ class _ClientesPageState extends State<ClientesPage> {
|
||||
}
|
||||
}
|
||||
|
||||
// Comentario explicativo: Devuelve el ícono correspondiente según el tipo de servicio asociado
|
||||
IconData _iconoServicio(String servicio) {
|
||||
final s = servicio.toLowerCase();
|
||||
if (s.contains('cctv') || s.contains('video') || s.contains('camara')) {
|
||||
return Icons.videocam_outlined;
|
||||
} else if (s.contains('gps') || s.contains('satelital') || s.contains('rastreo')) {
|
||||
return Icons.gps_fixed;
|
||||
} else if (s.contains('acceso')) {
|
||||
return Icons.badge_outlined;
|
||||
} else if (s.contains('integral') || s.contains('360')) {
|
||||
return Icons.verified_user_outlined;
|
||||
} else {
|
||||
return Icons.notifications_active_outlined;
|
||||
}
|
||||
}
|
||||
|
||||
// Comentario explicativo: Devuelve el color temático para el tipo de servicio asociado
|
||||
Color _colorServicio(String servicio) {
|
||||
final s = servicio.toLowerCase();
|
||||
if (s.contains('cctv') || s.contains('video') || s.contains('camara')) {
|
||||
return const Color(0xFF26A69A); // Verde Teal
|
||||
} else if (s.contains('gps') || s.contains('satelital') || s.contains('rastreo')) {
|
||||
return const Color(0xFF42A5F5); // Azul satelital
|
||||
} else if (s.contains('acceso')) {
|
||||
return const Color(0xFFAB47BC); // Púrpura
|
||||
} else if (s.contains('integral') || s.contains('360')) {
|
||||
return const Color(0xFFFFB300); // Ámbar dorado
|
||||
} else {
|
||||
return AppColors.primary; // Primario para Alarmas
|
||||
}
|
||||
}
|
||||
|
||||
// Comentario explicativo: Chip interactivo para filtrar clientes por su tipo de servicio
|
||||
Widget _chipFiltro(String key, String etiqueta, IconData icono) {
|
||||
final activo = _filtroServicio == key;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: FilterChip(
|
||||
selected: activo,
|
||||
showCheckmark: false,
|
||||
avatar: Icon(icono, size: 14, color: activo ? const Color(0xFF002F6C) : AppColors.outline),
|
||||
label: Text(etiqueta),
|
||||
labelStyle: appLabel(
|
||||
size: 11,
|
||||
weight: activo ? FontWeight.bold : FontWeight.normal,
|
||||
color: activo ? const Color(0xFF002F6C) : AppColors.onSurface,
|
||||
),
|
||||
backgroundColor: AppColors.surfaceLow,
|
||||
selectedColor: AppColors.primary,
|
||||
side: BorderSide(color: activo ? AppColors.primary : AppColors.outlineVariant),
|
||||
onSelected: (_) {
|
||||
setState(() => _filtroServicio = key);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Abre el diálogo modal para dar de alta un nuevo cliente y asociar su tipo de servicio
|
||||
Future<void> _mostrarDialogoNuevoCliente() async {
|
||||
final nombreCtrl = TextEditingController();
|
||||
final alarmasActivasCtrl = TextEditingController(text: '0');
|
||||
final alarmasCriticasCtrl = TextEditingController(text: '0');
|
||||
String servicioSeleccionado = 'Monitoreo de Alarmas';
|
||||
String estadoSeleccionado = 'normal';
|
||||
|
||||
await showDialog(
|
||||
context: context,
|
||||
builder: (dialogCtx) {
|
||||
return StatefulBuilder(
|
||||
builder: (ctx, setDialogState) {
|
||||
return AlertDialog(
|
||||
backgroundColor: AppColors.surface,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Icon(Icons.person_add_alt_1, color: AppColors.primary, size: 20),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text('Agregar Cliente',
|
||||
style: appHeadline(size: 16, weight: FontWeight.bold, color: AppColors.onSurface)),
|
||||
],
|
||||
),
|
||||
content: SizedBox(
|
||||
width: 480,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Nombre de la Empresa / Cliente *',
|
||||
style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 6),
|
||||
TextField(
|
||||
controller: nombreCtrl,
|
||||
style: appLabel(color: AppColors.onSurface),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Ej. Hospital San Rafael / Corporación Norte',
|
||||
hintStyle: appLabel(color: AppColors.outline),
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceLow,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Text('Tipo de Servicio Asociado *',
|
||||
style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 6),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<String>(
|
||||
value: servicioSeleccionado,
|
||||
isExpanded: true,
|
||||
dropdownColor: AppColors.surfaceHigh,
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'Monitoreo de Alarmas', child: Text('Monitoreo de Alarmas')),
|
||||
DropdownMenuItem(value: 'CCTV / Video-vigilancia', child: Text('CCTV / Video-vigilancia')),
|
||||
DropdownMenuItem(value: 'Rastreo Satelital GPS', child: Text('Rastreo Satelital GPS')),
|
||||
DropdownMenuItem(value: 'Control de Acceso', child: Text('Control de Acceso')),
|
||||
DropdownMenuItem(value: 'Servicio Integral 360', child: Text('Servicio Integral 360')),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v != null) setDialogState(() => servicioSeleccionado = v);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Estado Inicial',
|
||||
style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 6),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<String>(
|
||||
value: estadoSeleccionado,
|
||||
isExpanded: true,
|
||||
dropdownColor: AppColors.surfaceHigh,
|
||||
style: appLabel(size: 12, color: AppColors.onSurface),
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'normal', child: Text('Normal (Verde)')),
|
||||
DropdownMenuItem(value: 'alerta', child: Text('Alerta (Ámbar)')),
|
||||
DropdownMenuItem(value: 'critica', child: Text('Crítica (Rojo)')),
|
||||
],
|
||||
onChanged: (v) {
|
||||
if (v != null) setDialogState(() => estadoSeleccionado = v);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Alarmas Activas',
|
||||
style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 6),
|
||||
TextField(
|
||||
controller: alarmasActivasCtrl,
|
||||
keyboardType: TextInputType.number,
|
||||
style: appLabel(color: AppColors.onSurface),
|
||||
decoration: InputDecoration(
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceLow,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogCtx),
|
||||
child: Text('Cancelar', style: appLabel(color: AppColors.outline)),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: const Color(0xFF002F6C),
|
||||
),
|
||||
icon: const Icon(Icons.check, size: 16),
|
||||
label: const Text('Registrar'),
|
||||
onPressed: () async {
|
||||
final nombre = nombreCtrl.text.trim();
|
||||
if (nombre.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Por favor ingresa el nombre de la empresa o cliente.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final activas = int.tryParse(alarmasActivasCtrl.text.trim()) ?? 0;
|
||||
final criticas = int.tryParse(alarmasCriticasCtrl.text.trim()) ?? 0;
|
||||
|
||||
// Comentario explicativo: Registrar el nuevo cliente con su tipo de servicio asociado en SQLite
|
||||
final nuevoId = await _clientesDao.obtenerSiguienteId();
|
||||
await _clientesDao.insertar({
|
||||
'id': nuevoId,
|
||||
'nombre': nombre,
|
||||
'estado': estadoSeleccionado,
|
||||
'alarmas_activas': activas,
|
||||
'alarmas_criticas': criticas,
|
||||
'tipo_servicio': servicioSeleccionado,
|
||||
'ultima_actualizacion': DateTime.now().toIso8601String(),
|
||||
});
|
||||
|
||||
await _cargarClientes();
|
||||
if (mounted) {
|
||||
Navigator.pop(dialogCtx);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
content: Text(
|
||||
'Cliente "$nombre" registrado con servicio "$servicioSeleccionado".',
|
||||
style: appLabel(color: AppColors.clienteOk),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Filtrado reactivo por tipo de servicio
|
||||
final clientesFiltrados = _clientes.where((c) {
|
||||
if (_filtroServicio == 'todos') return true;
|
||||
final serv = ((c['tipo_servicio'] as String?) ?? 'Monitoreo de Alarmas').toLowerCase();
|
||||
if (_filtroServicio == 'alarma') return serv.contains('alarma');
|
||||
if (_filtroServicio == 'cctv') return serv.contains('cctv') || serv.contains('video');
|
||||
if (_filtroServicio == 'gps') return serv.contains('gps') || serv.contains('satelital') || serv.contains('rastreo');
|
||||
if (_filtroServicio == 'acceso') return serv.contains('acceso');
|
||||
if (_filtroServicio == 'integral') return serv.contains('integral') || serv.contains('360');
|
||||
return true;
|
||||
}).toList();
|
||||
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
// Comentario explicativo: Cabecera con título descriptivo y botón de refrescar; la creación de clientes se centraliza en la fila interactiva para evitar duplicidad visual
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
@@ -56,7 +344,7 @@ class _ClientesPageState extends State<ClientesPage> {
|
||||
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',
|
||||
Text('Monitoreo del estado perimetral y central de cada sede con su tipo de servicio',
|
||||
style: appLabel(size: 13, color: AppColors.outline)),
|
||||
]),
|
||||
IconButton(
|
||||
@@ -66,35 +354,137 @@ class _ClientesPageState extends State<ClientesPage> {
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Filtro horizontal por tipo de servicio
|
||||
SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: [
|
||||
_chipFiltro('todos', 'Todos los servicios', Icons.apps),
|
||||
_chipFiltro('alarma', 'Monitoreo Alarmas', Icons.notifications_active_outlined),
|
||||
_chipFiltro('cctv', 'CCTV / Video-vigilancia', Icons.videocam_outlined),
|
||||
_chipFiltro('gps', 'Rastreo GPS', Icons.gps_fixed),
|
||||
_chipFiltro('acceso', 'Control de Acceso', Icons.badge_outlined),
|
||||
_chipFiltro('integral', 'Integral 360', Icons.verified_user_outlined),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Comentario explicativo: Fila interactiva para agregar cliente y su tipo de servicio asociado
|
||||
Container(
|
||||
margin: const EdgeInsets.only(bottom: 16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.primary.withValues(alpha: 0.35), width: 1.2),
|
||||
),
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
onTap: _mostrarDialogoNuevoCliente,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: const Icon(Icons.person_add_alt_1, color: AppColors.primary, size: 22),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
'Agregar Cliente',
|
||||
style: appHeadline(size: 15, weight: FontWeight.w800, color: AppColors.primary),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primary.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Text(
|
||||
'+ REGISTRO',
|
||||
style: appLabel(size: 9, weight: FontWeight.w800, color: AppColors.primary),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Alta de cuenta con su tipo de servicio asociado (Alarmas, CCTV, Rastreo GPS, Control de Acceso o Integral 360)',
|
||||
style: appLabel(size: 12, color: AppColors.outline),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
ElevatedButton.icon(
|
||||
onPressed: _mostrarDialogoNuevoCliente,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: const Color(0xFF002F6C),
|
||||
elevation: 0,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
icon: const Icon(Icons.add, size: 16),
|
||||
label: Text('Agregar Cliente', style: appLabel(size: 12, weight: FontWeight.bold, color: const Color(0xFF002F6C))),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
if (_cargando)
|
||||
const Center(child: CircularProgressIndicator())
|
||||
else if (_clientes.isEmpty)
|
||||
else if (clientesFiltrados.isEmpty)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(32),
|
||||
alignment: Alignment.center,
|
||||
child: Text('No hay clientes en caché local.', style: appLabel(color: AppColors.outline)),
|
||||
child: Text(
|
||||
_filtroServicio == 'todos'
|
||||
? 'No hay clientes en caché local.'
|
||||
: 'No hay clientes registrados con este tipo de servicio.',
|
||||
style: appLabel(color: AppColors.outline),
|
||||
),
|
||||
)
|
||||
else
|
||||
ListView.separated(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: _clientes.length,
|
||||
itemCount: clientesFiltrados.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 12),
|
||||
itemBuilder: (_, i) {
|
||||
final c = _clientes[i];
|
||||
final c = clientesFiltrados[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;
|
||||
final servicio = (c['tipo_servicio'] as String?) ?? 'Monitoreo de Alarmas';
|
||||
final iconoServicio = _iconoServicio(servicio);
|
||||
final colorServicio = _colorServicio(servicio);
|
||||
|
||||
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),
|
||||
border: Border.all(color: color.withValues(alpha: 0.4), width: 1.2),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
@@ -106,9 +496,34 @@ class _ClientesPageState extends State<ClientesPage> {
|
||||
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),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
c['nombre'] as String? ?? 'Cliente',
|
||||
style: appHeadline(size: 14, weight: FontWeight.w700, color: AppColors.onSurface),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
// Comentario explicativo: Badge que visualiza el tipo de servicio asociado al cliente
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: colorServicio.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: colorServicio.withValues(alpha: 0.35)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(iconoServicio, size: 12, color: colorServicio),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
servicio,
|
||||
style: appLabel(size: 11, weight: FontWeight.w600, color: colorServicio),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
// Comentario explicativo: Pantalla de Estado de Comunicación y Diagnóstico de Enlaces.
|
||||
// Reemplaza el firewall genérico por una consola especializada de telemetría de red y enlaces
|
||||
// (Canal IP/Fibra, Respaldo Celular 4G/LTE, Túnel VPN MikroTik y Heartbeats). Permite verificar
|
||||
// de inmediato por qué un panel de alarmas no reporta antes de despachar soporte técnico.
|
||||
class ComunicacionPage extends StatefulWidget {
|
||||
final int? clienteIdInicial;
|
||||
|
||||
const ComunicacionPage({Key? key, this.clienteIdInicial}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<ComunicacionPage> createState() => _ComunicacionPageState();
|
||||
}
|
||||
|
||||
class _ComunicacionPageState extends State<ComunicacionPage> {
|
||||
String _filtroEstado = 'todos'; // todos | online | advertencia | desconectado
|
||||
final Map<int, bool> _probandoEnlace = {};
|
||||
|
||||
final List<Map<String, dynamic>> _enlaces = [
|
||||
{
|
||||
'id': 101,
|
||||
'cliente': 'Banco Metropolitano - Sede Central',
|
||||
'ip': '192.168.10.201',
|
||||
'canalPrincipal': 'Fibra Óptica Dedicada (Ethernet)',
|
||||
'canalPrincipalEstado': 'online',
|
||||
'canalRespaldo': 'Módem 4G LTE Banda 28',
|
||||
'canalRespaldoEstado': 'online',
|
||||
'senalRssi': '-68 dBm (Excelente)',
|
||||
'latencia': '18 ms',
|
||||
'ultimoHeartbeat': 'Hace 12 seg',
|
||||
'estadoGeneral': 'online',
|
||||
'tunelVpn': 'WireGuard CHR #01 (Activo)',
|
||||
'firewallDrops': '0 drops',
|
||||
},
|
||||
{
|
||||
'id': 102,
|
||||
'cliente': 'Centro Comercial Gran Plaza',
|
||||
'ip': '192.168.10.205',
|
||||
'canalPrincipal': 'Enlace IP Corporativo',
|
||||
'canalPrincipalEstado': 'online',
|
||||
'canalRespaldo': 'SIM 4G Multicarrier',
|
||||
'canalRespaldoEstado': 'advertencia',
|
||||
'senalRssi': '-89 dBm (Señal Débil)',
|
||||
'latencia': '42 ms',
|
||||
'ultimoHeartbeat': 'Hace 45 seg',
|
||||
'estadoGeneral': 'advertencia',
|
||||
'tunelVpn': 'WireGuard CHR #02 (Activo)',
|
||||
'firewallDrops': '2 reintentos',
|
||||
},
|
||||
{
|
||||
'id': 103,
|
||||
'cliente': 'Torre Empresarial Sigma',
|
||||
'ip': '192.168.10.210',
|
||||
'canalPrincipal': 'FTTH Red Local',
|
||||
'canalPrincipalEstado': 'online',
|
||||
'canalRespaldo': 'Backup Celular M2M',
|
||||
'canalRespaldoEstado': 'online',
|
||||
'senalRssi': '-74 dBm (Buena)',
|
||||
'latencia': '24 ms',
|
||||
'ultimoHeartbeat': 'Hace 20 seg',
|
||||
'estadoGeneral': 'online',
|
||||
'tunelVpn': 'SSTP MikroTik (Activo)',
|
||||
'firewallDrops': '0 drops',
|
||||
},
|
||||
{
|
||||
'id': 104,
|
||||
'cliente': 'Almacenes El Ahorro - Sucursal Norte',
|
||||
'ip': '192.168.10.215',
|
||||
'canalPrincipal': 'ADSL Cobre (Intermitente)',
|
||||
'canalPrincipalEstado': 'desconectado',
|
||||
'canalRespaldo': 'GPRS 2G/3G Antiguo',
|
||||
'canalRespaldoEstado': 'desconectado',
|
||||
'senalRssi': 'Sin señal',
|
||||
'latencia': 'Timeout (>3000 ms)',
|
||||
'ultimoHeartbeat': 'Hace 38 min (FALLO TEST 24H)',
|
||||
'estadoGeneral': 'desconectado',
|
||||
'tunelVpn': 'Túnel caído (Handshake expirado)',
|
||||
'firewallDrops': '14 paquetes bloqueados / NAT timeout',
|
||||
},
|
||||
];
|
||||
|
||||
// Comentario explicativo: Realiza un ping y test de diagnóstico en vivo hacia el canal de comunicación del cliente
|
||||
Future<void> _ejecutarDiagnostico(int id, String cliente) async {
|
||||
setState(() => _probandoEnlace[id] = true);
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
if (!mounted) return;
|
||||
setState(() => _probandoEnlace[id] = false);
|
||||
|
||||
final enlace = _enlaces.firstWhere((e) => e['id'] == id);
|
||||
final esCaido = enlace['estadoGeneral'] == 'desconectado';
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: esCaido ? AppColors.alarmaActiva : AppColors.surfaceHigh,
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(esCaido ? Icons.error_outline : Icons.check_circle,
|
||||
color: esCaido ? Colors.white : AppColors.clienteOk, size: 18),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
esCaido
|
||||
? 'Fallo de enlace: El panel de $cliente no responde por IP ni Respaldo Celular.'
|
||||
: 'Diagnóstico OK: $cliente respondió con latencia de ${enlace['latencia']}.',
|
||||
style: appLabel(color: Colors.white, weight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final enlacesFiltrados = _filtroEstado == 'todos'
|
||||
? _enlaces
|
||||
: _enlaces.where((e) => e['estadoGeneral'] == _filtroEstado).toList();
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Header
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text('Estado de Comunicación y Enlaces Perimetrales',
|
||||
style: appHeadline(size: 20, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
const SizedBox(width: 10),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text('TELEMETRÍA RED',
|
||||
style: appLabel(size: 10, weight: FontWeight.bold, color: AppColors.primary)),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text('Supervisión de canales IP, respaldo celular 4G, túneles VPN y diagnóstico ante alarmas sin reporte',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
// Filtro por estado
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
_filtroChip('todos', 'Todos'),
|
||||
_filtroChip('online', 'En Línea'),
|
||||
_filtroChip('advertencia', 'Degradados'),
|
||||
_filtroChip('desconectado', 'Caídos'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Tarjetas KPI de Red
|
||||
Row(
|
||||
children: [
|
||||
_buildKpiCard('Total Enlaces Monitoreados', '${_enlaces.length}', Icons.router_outlined, AppColors.primary),
|
||||
const SizedBox(width: 14),
|
||||
_buildKpiCard('Operando 100% en Línea',
|
||||
'${_enlaces.where((e) => e['estadoGeneral'] == 'online').length}', Icons.check_circle_outlined, AppColors.clienteOk),
|
||||
const SizedBox(width: 14),
|
||||
_buildKpiCard('Enlace Degradado / Respaldo',
|
||||
'${_enlaces.where((e) => e['estadoGeneral'] == 'advertencia').length}', Icons.warning_amber_rounded, AppColors.clienteAlerta),
|
||||
const SizedBox(width: 14),
|
||||
_buildKpiCard('Paneles Sin Comunicación',
|
||||
'${_enlaces.where((e) => e['estadoGeneral'] == 'desconectado').length}', Icons.portable_wifi_off, AppColors.alarmaActiva),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Lista de Canales por Cliente
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
itemCount: enlacesFiltrados.length,
|
||||
itemBuilder: (ctx, i) => _buildTarjetaEnlace(enlacesFiltrados[i]),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _filtroChip(String estado, String label) {
|
||||
final activo = _filtroEstado == estado;
|
||||
return InkWell(
|
||||
onTap: () => setState(() => _filtroEstado = estado),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
color: activo ? AppColors.primaryContainer : Colors.transparent,
|
||||
child: Text(
|
||||
label,
|
||||
style: appLabel(
|
||||
size: 11,
|
||||
weight: activo ? FontWeight.bold : FontWeight.normal,
|
||||
color: activo ? AppColors.primary : AppColors.outline,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildKpiCard(String titulo, String valor, IconData icono, Color color) {
|
||||
return Expanded(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.12),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(icono, color: color, size: 20),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(valor, style: appHeadline(size: 18, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
Text(titulo, style: appLabel(size: 11, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTarjetaEnlace(Map<String, dynamic> e) {
|
||||
final id = e['id'] as int;
|
||||
final probando = _probandoEnlace[id] == true;
|
||||
final estado = e['estadoGeneral'] as String;
|
||||
final esCaido = estado == 'desconectado';
|
||||
final esDegradado = estado == 'advertencia';
|
||||
|
||||
Color colorBorde = AppColors.outlineVariant;
|
||||
if (esCaido) colorBorde = AppColors.alarmaActiva;
|
||||
if (esDegradado) colorBorde = AppColors.clienteAlerta;
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: colorBorde, width: (esCaido || esDegradado) ? 1.5 : 1.0),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 10,
|
||||
height: 10,
|
||||
decoration: BoxDecoration(
|
||||
color: esCaido ? AppColors.alarmaActiva : (esDegradado ? AppColors.clienteAlerta : AppColors.clienteOk),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Text(e['cliente'],
|
||||
style: appHeadline(size: 15, weight: FontWeight.w700, color: AppColors.onSurface)),
|
||||
const SizedBox(width: 10),
|
||||
Text('IP: ${e['ip']}', style: appLabel(size: 12, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
// Botón de test de comunicación
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
foregroundColor: AppColors.primary,
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
),
|
||||
icon: probando
|
||||
? const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.primary),
|
||||
)
|
||||
: const Icon(Icons.network_ping, size: 16),
|
||||
label: Text(probando ? 'Probando...' : 'Diagnóstico en Vivo',
|
||||
style: appLabel(size: 11, weight: FontWeight.bold)),
|
||||
onPressed: probando ? null : () => _ejecutarDiagnostico(id, e['cliente']),
|
||||
),
|
||||
],
|
||||
),
|
||||
const Divider(height: 20, color: AppColors.outlineVariant),
|
||||
// Canales y Métricas de Conectividad
|
||||
Row(
|
||||
children: [
|
||||
// Canal Principal
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Canal Principal:', style: appLabel(size: 10, color: AppColors.outline)),
|
||||
const SizedBox(height: 2),
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.settings_ethernet,
|
||||
size: 14,
|
||||
color: e['canalPrincipalEstado'] == 'online' ? AppColors.clienteOk : AppColors.alarmaActiva),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(e['canalPrincipal'],
|
||||
style: appLabel(size: 12, color: AppColors.onSurface, weight: FontWeight.w600),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Canal Respaldo Celular
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Respaldo Celular (SIM):', style: appLabel(size: 10, color: AppColors.outline)),
|
||||
const SizedBox(height: 2),
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.signal_cellular_alt,
|
||||
size: 14,
|
||||
color: e['canalRespaldoEstado'] == 'online' ? AppColors.clienteOk : AppColors.clienteAlerta),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text('${e['canalRespaldo']} • ${e['senalRssi']}',
|
||||
style: appLabel(size: 12, color: AppColors.onSurface, weight: FontWeight.w600),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Túnel VPN y Latencia
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Túnel VPN & Latencia:', style: appLabel(size: 10, color: AppColors.outline)),
|
||||
const SizedBox(height: 2),
|
||||
Text('${e['tunelVpn']} (${e['latencia']})',
|
||||
style: appLabel(size: 12, color: AppColors.primary, weight: FontWeight.w600),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Último Heartbeat
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Último Heartbeat / Drops:', style: appLabel(size: 10, color: AppColors.outline)),
|
||||
const SizedBox(height: 2),
|
||||
Text('${e['ultimoHeartbeat']} • ${e['firewallDrops']}',
|
||||
style: appLabel(
|
||||
size: 11,
|
||||
color: esCaido ? AppColors.alarmaActiva : AppColors.outline,
|
||||
weight: esCaido ? FontWeight.bold : FontWeight.normal,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import '../services/api_auth_service.dart';
|
||||
import '../services/sincronizador.dart';
|
||||
import '../db/database_helper.dart';
|
||||
import '../db/dao/configuracion_dao.dart';
|
||||
// Comentario explicativo: Importación de la pantalla dedicada de Datos y Parámetros para administración avanzada de SQLite
|
||||
import 'datos_parametros_page.dart';
|
||||
|
||||
// Comentario explicativo: Pantalla de Configuración del Sistema conectada a ConfiguracionDao,
|
||||
// Sincronizador, ApiAuthService y DatabaseHelper. Permite gestionar parámetros operativos,
|
||||
@@ -386,37 +388,43 @@ class _ConfiguracionPageState extends State<ConfiguracionPage> {
|
||||
),
|
||||
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,
|
||||
// Comentario explicativo: Envoltura Material para que SwitchListTile pinte el splash y fondo sin advertencias de maquetación
|
||||
Material(
|
||||
color: Colors.transparent,
|
||||
child: 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,
|
||||
// Comentario explicativo: Envoltura Material para SwitchListTile de prioridad visual
|
||||
Material(
|
||||
color: Colors.transparent,
|
||||
child: 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
|
||||
// Sección 4: Base de Datos Local y Administrar Datos
|
||||
_buildSectionHeader('ALMACENAMIENTO LOCAL SQLITE', Icons.storage_outlined),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
@@ -438,6 +446,61 @@ class _ConfiguracionPageState extends State<ConfiguracionPage> {
|
||||
],
|
||||
),
|
||||
const Divider(height: 28, color: AppColors.outlineVariant),
|
||||
// Comentario explicativo: Acceso directo a la consola dedicada de Administrar Datos y Parámetros
|
||||
Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceHigh,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: const Icon(Icons.tune_outlined, color: AppColors.primary, size: 20),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Administrar Datos y Parámetros',
|
||||
style: appHeadline(size: 13, weight: FontWeight.w700, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 2),
|
||||
Text('Reinicializar SQLite, poblar datos demo y gestionar parámetros operativos',
|
||||
style: appLabel(size: 11, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: AppColors.primaryContainer,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
icon: const Icon(Icons.launch, size: 16),
|
||||
label: Text('ABRIR CONSOLA',
|
||||
style: appLabel(size: 12, weight: FontWeight.bold, color: AppColors.primaryContainer)),
|
||||
onPressed: () async {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => const DatosParametrosPage()),
|
||||
);
|
||||
await _cargarAjustes();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
|
||||
@@ -0,0 +1,706 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/database_helper.dart';
|
||||
import '../db/dao/configuracion_dao.dart';
|
||||
import '../services/sincronizador.dart';
|
||||
|
||||
// Comentario explicativo: Pantalla dedicada para Administrar Datos y Parámetros del Sistema.
|
||||
// Permite la reinicialización de SQLite, carga del dataset demo para revisión/tienda,
|
||||
// vaciado selectivo de cachés operativos y control centralizado de parámetros operativos.
|
||||
class DatosParametrosPage extends StatefulWidget {
|
||||
const DatosParametrosPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<DatosParametrosPage> createState() => _DatosParametrosPageState();
|
||||
}
|
||||
|
||||
class _DatosParametrosPageState extends State<DatosParametrosPage> {
|
||||
final _dbHelper = DatabaseHelper.instance;
|
||||
final _configDao = ConfiguracionDao();
|
||||
final _sincronizador = Sincronizador.instance;
|
||||
|
||||
bool _cargando = true;
|
||||
bool _procesandoAccion = false;
|
||||
|
||||
// Métricas de tablas
|
||||
Map<String, int> _metricas = {
|
||||
'alarmas': 0,
|
||||
'clientes': 0,
|
||||
'incidentes': 0,
|
||||
'sync_logs': 0,
|
||||
'operadores': 0,
|
||||
'sesiones': 0,
|
||||
'config': 0,
|
||||
};
|
||||
|
||||
// Parámetros de la app
|
||||
int _intervaloSegundos = 30;
|
||||
bool _sonidoAlerta = true;
|
||||
bool _alertaPrioritaria = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarTodo();
|
||||
}
|
||||
|
||||
// Comentario explicativo: Carga concurrente de métricas de base de datos y parámetros guardados
|
||||
Future<void> _cargarTodo() async {
|
||||
setState(() => _cargando = true);
|
||||
|
||||
final metricas = await _dbHelper.getMetricasDetalladasDb();
|
||||
final intervalStr = await _configDao.get('poll_interval_seg');
|
||||
final sonidoStr = await _configDao.get('sonido_alerta');
|
||||
final alertPriorStr = await _configDao.get('alerta_prioritaria');
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_metricas = metricas;
|
||||
_intervaloSegundos = int.tryParse(intervalStr ?? '') ?? _sincronizador.intervaloSegundos;
|
||||
_sonidoAlerta = (sonidoStr ?? '1') == '1';
|
||||
_alertaPrioritaria = (alertPriorStr ?? '1') == '1';
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
|
||||
// Comentario explicativo: Muestra feedback al operador mediante SnackBar tematizado
|
||||
void _mostrarAviso(String mensaje, {bool esError = false, Color? color}) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
backgroundColor: color ?? (esError ? AppColors.alarmaActiva : AppColors.surfaceHigh),
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(
|
||||
esError ? Icons.error_outline : Icons.check_circle_outline,
|
||||
color: esError ? Colors.white : AppColors.clienteOk,
|
||||
size: 18,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(mensaje, style: appLabel(color: Colors.white, weight: FontWeight.w600)),
|
||||
),
|
||||
],
|
||||
),
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Ejecuta la reinicialización completa de la base de datos previa confirmación estricta
|
||||
Future<void> _ejecutarReinicioTotal() async {
|
||||
final confirmar = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceLow,
|
||||
title: Row(
|
||||
children: [
|
||||
const Icon(Icons.warning_amber_rounded, color: AppColors.alarmaActiva, size: 24),
|
||||
const SizedBox(width: 8),
|
||||
Text('¿Reinicializar Base de Datos?', style: appHeadline(size: 16, color: AppColors.onSurface)),
|
||||
],
|
||||
),
|
||||
content: Text(
|
||||
'Esta acción borrará todas las alarmas en caché, clientes, incidentes locales, operadores y logs de sincronización.\n\nLa base de datos volverá a su estado inicial en blanco.',
|
||||
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.alarmaActiva,
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
child: Text('SÍ, REINICIALIZAR TODO', style: appLabel(weight: FontWeight.bold, color: Colors.white)),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmar != true) return;
|
||||
|
||||
setState(() => _procesandoAccion = true);
|
||||
await _dbHelper.reinicializarBaseDatos();
|
||||
await _cargarTodo();
|
||||
setState(() => _procesandoAccion = false);
|
||||
_mostrarAviso('Base de datos reinicializada a estado limpio.');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Carga el dataset completo de demostración para evaluación de tienda o pruebas locales
|
||||
Future<void> _cargarDatasetDemo() async {
|
||||
setState(() => _procesandoAccion = true);
|
||||
await _dbHelper.poblarDatosDemo(force: true);
|
||||
await _cargarTodo();
|
||||
setState(() => _procesandoAccion = false);
|
||||
_mostrarAviso('Dataset Demo cargado exitosamente.');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Vacía únicamente las tablas temporales de caché operativo
|
||||
Future<void> _vaciarCache() async {
|
||||
final confirmar = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceLow,
|
||||
title: Text('¿Vaciar Caché Operativo?', style: appHeadline(size: 16, color: AppColors.onSurface)),
|
||||
content: Text(
|
||||
'Se vaciarán las tablas cache_alarmas y cache_clientes.\nLos incidentes auditados y la configuración no se verán afectados.',
|
||||
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.clienteAlerta,
|
||||
foregroundColor: Colors.black,
|
||||
),
|
||||
child: Text('VACIAR CACHÉ', style: appLabel(weight: FontWeight.bold, color: Colors.black)),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmar != true) return;
|
||||
|
||||
setState(() => _procesandoAccion = true);
|
||||
await _dbHelper.vaciarCacheOperativo();
|
||||
await _cargarTodo();
|
||||
setState(() => _procesandoAccion = false);
|
||||
_mostrarAviso('Caché operativo de alarmas y clientes vaciado.');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Vacía los registros locales de incidentes
|
||||
Future<void> _vaciarIncidentes() async {
|
||||
final confirmar = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceLow,
|
||||
title: Text('¿Limpiar Registro de Incidentes?', style: appHeadline(size: 16, color: AppColors.onSurface)),
|
||||
content: Text(
|
||||
'Se eliminarán todos los incidentes locales registrados en este terminal.',
|
||||
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('LIMPIAR INCIDENTES', style: appLabel(weight: FontWeight.bold, color: AppColors.primary)),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmar != true) return;
|
||||
|
||||
setState(() => _procesandoAccion = true);
|
||||
await _dbHelper.limpiarIncidentes();
|
||||
await _cargarTodo();
|
||||
setState(() => _procesandoAccion = false);
|
||||
_mostrarAviso('Registro de incidentes locales limpiado.');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Vacía la tabla de logs de sincronización
|
||||
Future<void> _vaciarSyncLogs() async {
|
||||
setState(() => _procesandoAccion = true);
|
||||
await _dbHelper.limpiarSyncLogs();
|
||||
await _cargarTodo();
|
||||
setState(() => _procesandoAccion = false);
|
||||
_mostrarAviso('Bitácora de sincronización vaciada.');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Modifica el intervalo de sincronización periódica
|
||||
Future<void> _actualizarIntervalo(int nuevosSegundos) async {
|
||||
setState(() => _intervaloSegundos = nuevosSegundos);
|
||||
await _configDao.set('poll_interval_seg', nuevosSegundos.toString());
|
||||
_sincronizador.cambiarIntervalo(nuevosSegundos);
|
||||
_mostrarAviso('Intervalo de sincronización ajustado a $nuevosSegundos s');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Modifica y persiste la preferencia de sonido ante pánico
|
||||
Future<void> _toggleSonido(bool valor) async {
|
||||
setState(() => _sonidoAlerta = valor);
|
||||
await _configDao.set('sonido_alerta', valor ? '1' : '0');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Modifica y persiste la preferencia de prioridad visual
|
||||
Future<void> _toggleAlertaPrioritaria(bool valor) async {
|
||||
setState(() => _alertaPrioritaria = valor);
|
||||
await _configDao.set('alerta_prioritaria', valor ? '1' : '0');
|
||||
}
|
||||
|
||||
// Comentario explicativo: Restablece todos los parámetros operativos a sus valores originales recomendados
|
||||
Future<void> _restablecerParametrosDefaults() async {
|
||||
setState(() => _procesandoAccion = true);
|
||||
await _configDao.set('poll_interval_seg', '30');
|
||||
await _configDao.set('sonido_alerta', '1');
|
||||
await _configDao.set('alerta_prioritaria', '1');
|
||||
_sincronizador.cambiarIntervalo(30);
|
||||
await _cargarTodo();
|
||||
setState(() => _procesandoAccion = false);
|
||||
_mostrarAviso('Parámetros operativos restablecidos a valores por defecto.');
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.surfaceLowest,
|
||||
appBar: AppBar(
|
||||
backgroundColor: AppColors.surfaceLow,
|
||||
elevation: 0,
|
||||
title: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(6),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Icon(Icons.tune_outlined, color: AppColors.primary, size: 20),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Datos y Parámetros del Sistema',
|
||||
style: appHeadline(size: 16, weight: FontWeight.w700, color: AppColors.onSurface)),
|
||||
Text('Consola de SQLite local, datos demo y configuración de la app',
|
||||
style: appLabel(size: 11, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh, color: AppColors.outline),
|
||||
tooltip: 'Refrescar datos',
|
||||
onPressed: _cargando || _procesandoAccion ? null : _cargarTodo,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
),
|
||||
body: _cargando
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: Stack(
|
||||
children: [
|
||||
SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// SECCIÓN 1: Métricas de Almacenamiento SQLite
|
||||
_buildHeader('ESTADO DEL ALMACENAMIENTO LOCAL (SQLITE)', Icons.storage_outlined),
|
||||
const SizedBox(height: 12),
|
||||
_buildMetricsGrid(),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// SECCIÓN 2: Gestión y Limpieza de Base de Datos
|
||||
_buildHeader('ACCIONES DE BASE DE DATOS Y LIMPIEZA', Icons.cleaning_services_outlined),
|
||||
const SizedBox(height: 12),
|
||||
_buildDatabaseActionsCard(),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// SECCIÓN 3: Gestión de Dataset Demo
|
||||
_buildHeader('DATASET DEMO (EVALUACIÓN OFFLINE)', Icons.play_circle_outline),
|
||||
const SizedBox(height: 12),
|
||||
_buildDemoDatasetCard(),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// SECCIÓN 4: Parámetros Operativos de la App
|
||||
_buildHeader('PARÁMETROS OPERATIVOS', Icons.settings_suggest_outlined),
|
||||
const SizedBox(height: 12),
|
||||
_buildParametrosCard(),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// SECCIÓN 5: Topología de Conexiones
|
||||
_buildHeader('ENLACES DEL ECOSISTEMA', Icons.hub_outlined),
|
||||
const SizedBox(height: 12),
|
||||
_buildEndpointsCard(),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_procesandoAccion)
|
||||
Container(
|
||||
color: Colors.black54,
|
||||
child: const Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CircularProgressIndicator(),
|
||||
SizedBox(height: 16),
|
||||
Text('Procesando operación en SQLite...', style: TextStyle(color: Colors.white)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Encabezado de sección con icono y tipografía estándar
|
||||
Widget _buildHeader(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: Grilla adaptativa con conteos de registros por cada tabla en SQLite
|
||||
Widget _buildMetricsGrid() {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final isDesktop = constraints.maxWidth > 700;
|
||||
return Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 16,
|
||||
children: [
|
||||
_buildMetricTile('Alarmas en Caché', '${_metricas['alarmas']}', Icons.notifications_active_outlined, isDesktop),
|
||||
_buildMetricTile('Clientes Locales', '${_metricas['clientes']}', Icons.business_outlined, isDesktop),
|
||||
_buildMetricTile('Incidentes Auditados', '${_metricas['incidentes']}', Icons.shield_outlined, isDesktop),
|
||||
_buildMetricTile('Operadores Registrados', '${_metricas['operadores']}', Icons.badge_outlined, isDesktop),
|
||||
_buildMetricTile('Logs de Sincronización', '${_metricas['sync_logs']}', Icons.history_outlined, isDesktop),
|
||||
_buildMetricTile('Sesiones de Turno', '${_metricas['sesiones']}', Icons.login_outlined, isDesktop),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Casilla individual de métrica SQLite con estilo visual del Design System
|
||||
Widget _buildMetricTile(String titulo, String valor, IconData icono, bool isDesktop) {
|
||||
final width = isDesktop ? 180.0 : 140.0;
|
||||
return Container(
|
||||
width: width,
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceHigh,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Icon(icono, size: 18, color: AppColors.primary),
|
||||
Text(valor, style: appHeadline(size: 18, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(titulo, style: appLabel(size: 11, color: AppColors.outline), maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Tarjeta contenedora de operaciones de mantenimiento y limpieza de base de datos
|
||||
Widget _buildDatabaseActionsCard() {
|
||||
return 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: [
|
||||
Text('Mantenimiento y Vaciado Selectivo',
|
||||
style: appHeadline(size: 14, color: AppColors.onSurface, weight: FontWeight.w700)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Operaciones directas sobre el motor SQLite embebido del dispositivo',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
const Divider(height: 24, color: AppColors.outlineVariant),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
// Botón 1: Reinicialización Total
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.surfaceHighest,
|
||||
foregroundColor: AppColors.alarmaActiva,
|
||||
side: const BorderSide(color: AppColors.alarmaActiva),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
),
|
||||
icon: const Icon(Icons.delete_forever_outlined, size: 18),
|
||||
label: Text('Reinicializar BD (Limpieza Total)', style: appLabel(weight: FontWeight.bold)),
|
||||
onPressed: _procesandoAccion ? null : _ejecutarReinicioTotal,
|
||||
),
|
||||
// Botón 2: Vaciar Caché Operativo
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: AppColors.clienteAlerta,
|
||||
side: const BorderSide(color: AppColors.clienteAlerta),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
),
|
||||
icon: const Icon(Icons.cleaning_services_outlined, size: 18),
|
||||
label: Text('Vaciar Caché Operativo', style: appLabel(weight: FontWeight.bold)),
|
||||
onPressed: _procesandoAccion ? null : _vaciarCache,
|
||||
),
|
||||
// Botón 3: Limpiar Incidentes
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: AppColors.onSurfaceVariant,
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
),
|
||||
icon: const Icon(Icons.rule_folder_outlined, size: 18),
|
||||
label: Text('Limpiar Incidentes', style: appLabel()),
|
||||
onPressed: _procesandoAccion ? null : _vaciarIncidentes,
|
||||
),
|
||||
// Botón 4: Limpiar Logs de Sync
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: AppColors.outline,
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
),
|
||||
icon: const Icon(Icons.history_outlined, size: 18),
|
||||
label: Text('Limpiar Logs de Sync', style: appLabel()),
|
||||
onPressed: _procesandoAccion ? null : _vaciarSyncLogs,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Tarjeta para inicializar o recargar el Dataset Demo para auditoría de tienda
|
||||
Widget _buildDemoDatasetCard() {
|
||||
final tieneDatos = (_metricas['clientes'] ?? 0) > 0 || (_metricas['alarmas'] ?? 0) > 0;
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text('Conjunto de Datos de Demostración',
|
||||
style: appHeadline(size: 14, color: AppColors.onSurface, weight: FontWeight.w700)),
|
||||
const SizedBox(width: 10),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: tieneDatos ? const Color(0xFF1B382B) : AppColors.surfaceHighest,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
tieneDatos ? 'POBLADO' : 'VACÍO',
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: tieneDatos ? AppColors.clienteOk : AppColors.outline,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Carga clientes (Bancos, Centros Comerciales), eventos de pánico crítico, operadores e incidentes simulados para probar la app sin conexión.',
|
||||
style: appLabel(size: 12, color: AppColors.outline),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.primaryContainer,
|
||||
foregroundColor: AppColors.primary,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
),
|
||||
icon: const Icon(Icons.restart_alt, size: 18),
|
||||
label: Text('Cargar Dataset Demo', style: appLabel(weight: FontWeight.bold, color: AppColors.primary)),
|
||||
onPressed: _procesandoAccion ? null : _cargarDatasetDemo,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Tarjeta de configuración y modificación en vivo de parámetros operativos de la app
|
||||
Widget _buildParametrosCard() {
|
||||
return 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: [
|
||||
// Selector de Intervalo de Polling
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Cadencia de Sincronización Automática',
|
||||
style: appHeadline(size: 14, color: AppColors.onSurface)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Frecuencia con que la central sincroniza incidentes y 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),
|
||||
|
||||
// Switch de Alerta Acústica envuelto en Material para evitar advertencias de splash
|
||||
Material(
|
||||
color: Colors.transparent,
|
||||
child: SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text('Señalización Acústica ante Pánico y Alarmas Críticas',
|
||||
style: appHeadline(size: 14, color: AppColors.onSurface)),
|
||||
subtitle: Text('Emite una señal sonora de emergencia al recibir eventos con severidad ≥ 4',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
value: _sonidoAlerta,
|
||||
activeThumbColor: AppColors.primary,
|
||||
activeTrackColor: AppColors.primaryContainer,
|
||||
onChanged: _toggleSonido,
|
||||
),
|
||||
),
|
||||
const Divider(height: 16, color: AppColors.outlineVariant),
|
||||
|
||||
// Switch de Prioridad Visual envuelto en Material
|
||||
Material(
|
||||
color: Colors.transparent,
|
||||
child: SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text('Resaltado Visual Prioritario en Pantalla',
|
||||
style: appHeadline(size: 14, color: AppColors.onSurface)),
|
||||
subtitle: Text('Destaca la cabecera superior y muestra badge de alerta ante eventos no gestionados',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
value: _alertaPrioritaria,
|
||||
activeThumbColor: AppColors.primary,
|
||||
activeTrackColor: AppColors.primaryContainer,
|
||||
onChanged: _toggleAlertaPrioritaria,
|
||||
),
|
||||
),
|
||||
const Divider(height: 24, color: AppColors.outlineVariant),
|
||||
|
||||
// Botón Restablecer Defaults
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: AppColors.outline,
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
icon: const Icon(Icons.restore, size: 16),
|
||||
label: Text('Restablecer Parámetros por Defecto', style: appLabel(size: 12)),
|
||||
onPressed: _procesandoAccion ? null : _restablecerParametrosDefaults,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Visualizador de endpoints del ecosistema configurados en el proyecto
|
||||
Widget _buildEndpointsCard() {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
_buildEndpointItem('API Centinel Security (Dispositivos & Alarmas)', 'https://api.telcotronics.com', 'Producción Activa'),
|
||||
const Divider(height: 16, color: AppColors.outlineVariant),
|
||||
_buildEndpointItem('WebControl Ecosistema (Clientes & Contratos)', 'https://api.siax-system.net', 'WebControl Cloud'),
|
||||
const Divider(height: 16, color: AppColors.outlineVariant),
|
||||
_buildEndpointItem('Sigma-Robot Gateway (IA & Coordinación)', 'https://sigma-bot.telcotronics.com', 'Agente ID 61'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEndpointItem(String titulo, String url, String estado) {
|
||||
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)),
|
||||
],
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceHighest,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(estado, style: appLabel(size: 11, color: AppColors.outline)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import '../db/dao/cache_alarmas_dao.dart';
|
||||
import '../db/dao/cache_clientes_dao.dart';
|
||||
import '../db/dao/incidentes_dao.dart';
|
||||
import '../services/api_auth_service.dart';
|
||||
// Comentario explicativo: Importación de ShellPage para habilitar salto directo hacia la sección de Estado de Comunicación
|
||||
import '../shell_page.dart';
|
||||
|
||||
class MonitoreoPage extends StatefulWidget {
|
||||
const MonitoreoPage({Key? key}) : super(key: key);
|
||||
@@ -481,6 +483,18 @@ class _MonitoreoPageState extends State<MonitoreoPage> {
|
||||
Text('Cliente:', style: appLabel(size: 11, color: AppColors.outline)),
|
||||
_dropdownCliente(),
|
||||
],
|
||||
const SizedBox(width: 8),
|
||||
// Comentario explicativo: Botón directo para verificar el canal de comunicación y enlaces perimetrales si una alarma no reporta
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: AppColors.secondary,
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
),
|
||||
icon: const Icon(Icons.cell_tower_outlined, size: 14),
|
||||
label: Text('Estado de Comunicación', style: appLabel(size: 11, color: AppColors.secondary)),
|
||||
onPressed: () => ShellPage.irA(context, 8),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -582,7 +596,7 @@ class _MonitoreoPageState extends State<MonitoreoPage> {
|
||||
width: 80,
|
||||
child: Text('', style: TextStyle()), // tiempo — no label para ahorrar espacio
|
||||
),
|
||||
const SizedBox(width: 110),
|
||||
const SizedBox(width: 145),
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -671,7 +685,7 @@ class _MonitoreoPageState extends State<MonitoreoPage> {
|
||||
),
|
||||
// Acciones
|
||||
SizedBox(
|
||||
width: 110,
|
||||
width: 145,
|
||||
child: esActiva
|
||||
? Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
_accionBtn(
|
||||
@@ -694,6 +708,14 @@ class _MonitoreoPageState extends State<MonitoreoPage> {
|
||||
color: AppColors.primary,
|
||||
onTap: () => _registrarIncidente(a),
|
||||
),
|
||||
const SizedBox(width: 2),
|
||||
// Comentario explicativo: Botón de diagnóstico directo para verificar estado de comunicación de la alarma
|
||||
_accionBtn(
|
||||
icon: Icons.cell_tower_outlined,
|
||||
tooltip: 'Verificar Comunicación',
|
||||
color: AppColors.secondary,
|
||||
onTap: () => ShellPage.irA(context, 8),
|
||||
),
|
||||
])
|
||||
: Text('Silenciada',
|
||||
style: appLabel(size: 11, color: AppColors.outline)),
|
||||
|
||||
@@ -0,0 +1,544 @@
|
||||
import 'package:flutter/material.dart';
|
||||
// Comentario explicativo: Importación de flutter_map y latlong2 para integración de cartografía real basada en OpenStreetMap (OSM) y CartoDB
|
||||
import 'package:flutter_map/flutter_map.dart';
|
||||
import 'package:latlong2/latlong.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
// Comentario explicativo: Pantalla de Rastreo y Despacho Táctico con mapa cartográfico real OpenStreetMap / CartoDB.
|
||||
// Ofrece geolocalización satelital precisa de sedes monitoreadas, centrado automático de cámara,
|
||||
// seguimiento de patrullas móviles en ruta y conmutación de capas (Modo Oscuro SOC / OSM Estándar).
|
||||
class RastreoPage extends StatefulWidget {
|
||||
const RastreoPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<RastreoPage> createState() => _RastreoPageState();
|
||||
}
|
||||
|
||||
class _RastreoPageState extends State<RastreoPage> {
|
||||
final MapController _mapController = MapController();
|
||||
String _filtroTipo = 'todos'; // todos | sedes | patrullas
|
||||
int? _seleccionadoId;
|
||||
bool _modoOscuro = true; // true: CartoDB Dark Matter, false: OpenStreetMap Standard
|
||||
|
||||
// Puntos de interés y unidades con coordenadas reales en Quito, Ecuador
|
||||
final List<Map<String, dynamic>> _puntos = [
|
||||
{
|
||||
'id': 101,
|
||||
'tipo': 'sede',
|
||||
'nombre': 'Banco Metropolitano - Sede Central',
|
||||
'direccion': 'Av. Amazonas y Naciones Unidas',
|
||||
'lat': -0.1806,
|
||||
'lng': -78.4842,
|
||||
'estado': 'critica',
|
||||
'alarmaActiva': 'Pánico SOS en Bóveda',
|
||||
'operador': 'Operador Demo',
|
||||
},
|
||||
{
|
||||
'id': 102,
|
||||
'tipo': 'sede',
|
||||
'nombre': 'Centro Comercial Gran Plaza',
|
||||
'direccion': 'Av. 6 de Diciembre y Eloy Alfaro',
|
||||
'lat': -0.1912,
|
||||
'lng': -78.4790,
|
||||
'estado': 'alerta',
|
||||
'alarmaActiva': 'Sensor PIR Pasillo 1',
|
||||
'operador': 'Carlos Mendoza',
|
||||
},
|
||||
{
|
||||
'id': 103,
|
||||
'tipo': 'sede',
|
||||
'nombre': 'Torre Empresarial Sigma',
|
||||
'direccion': 'Av. República y Shyris',
|
||||
'lat': -0.1850,
|
||||
'lng': -78.4810,
|
||||
'estado': 'normal',
|
||||
'alarmaActiva': null,
|
||||
'operador': null,
|
||||
},
|
||||
{
|
||||
'id': 201,
|
||||
'tipo': 'patrulla',
|
||||
'nombre': 'Patrulla Móvil Alfa-1',
|
||||
'conductor': 'Sgt. Gómez / Cbo. Paredes',
|
||||
'vehiculo': 'Camioneta Blindada #12',
|
||||
'lat': -0.1830,
|
||||
'lng': -78.4825,
|
||||
'velocidad': '48 km/h',
|
||||
'rumbo': 'NE hacia Sede Central',
|
||||
'estado': 'en_despacho',
|
||||
'bateria': 94,
|
||||
'ultimaTransmision': 'Hace 5 seg',
|
||||
},
|
||||
{
|
||||
'id': 202,
|
||||
'tipo': 'patrulla',
|
||||
'nombre': 'Patrulla Móvil Bravo-2',
|
||||
'conductor': 'Guardia Téc. Morales',
|
||||
'vehiculo': 'Motocicleta Táctica #04',
|
||||
'lat': -0.1918,
|
||||
'lng': -78.4785,
|
||||
'velocidad': '0 km/h (Punto Fijo)',
|
||||
'rumbo': 'Perímetro Gran Plaza',
|
||||
'estado': 'disponible',
|
||||
'bateria': 88,
|
||||
'ultimaTransmision': 'Hace 12 seg',
|
||||
},
|
||||
{
|
||||
'id': 203,
|
||||
'tipo': 'patrulla',
|
||||
'nombre': 'Unidad Táctica Charlie-3',
|
||||
'conductor': 'Sup. Rivas',
|
||||
'vehiculo': 'Patrulla Rápida #07',
|
||||
'lat': -0.1872,
|
||||
'lng': -78.4835,
|
||||
'velocidad': '32 km/h',
|
||||
'rumbo': 'Ronda de Prevención',
|
||||
'estado': 'disponible',
|
||||
'bateria': 76,
|
||||
'ultimaTransmision': 'Hace 8 seg',
|
||||
},
|
||||
];
|
||||
|
||||
// Comentario explicativo: Centra suavemente la cámara del mapa sobre las coordenadas del elemento seleccionado
|
||||
void _centrarEn(double lat, double lng, int id) {
|
||||
setState(() => _seleccionadoId = id);
|
||||
_mapController.move(LatLng(lat, lng), 16.0);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final filtrados = _filtroTipo == 'todos'
|
||||
? _puntos
|
||||
: _puntos.where((p) => p['tipo'] == _filtroTipo).toList();
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Header con selector de segmento y conmutador de capas de mapa
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text('Rastreo y Mapa Táctico de Despacho',
|
||||
style: appHeadline(size: 20, weight: FontWeight.w800, color: AppColors.onSurface)),
|
||||
const SizedBox(width: 10),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(_modoOscuro ? 'MAPA OSCURO SOC' : 'OPENSTREETMAP',
|
||||
style: appLabel(size: 10, weight: FontWeight.bold, color: AppColors.primary)),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text('Cartografía satelital real OpenStreetMap, posicionamiento GPS de sedes y patrullas de reacción',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
// Botón de alternar capa de mapa (Dark SOC / OSM Clásico)
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: AppColors.onSurface,
|
||||
side: const BorderSide(color: AppColors.outlineVariant),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
),
|
||||
icon: Icon(_modoOscuro ? Icons.light_mode_outlined : Icons.dark_mode_outlined, size: 16),
|
||||
label: Text(_modoOscuro ? 'Ver OSM Estándar' : 'Ver Modo Oscuro SOC',
|
||||
style: appLabel(size: 11)),
|
||||
onPressed: () => setState(() => _modoOscuro = !_modoOscuro),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
// Segmented selector de tipo
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
_filtroBtn('todos', 'Todos'),
|
||||
_filtroBtn('sedes', 'Sedes Clientes'),
|
||||
_filtroBtn('patrullas', 'Patrullas GPS'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Contenedor principal: Mapa real OpenStreetMap a la izquierda + Panel de Unidades a la derecha
|
||||
Expanded(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Mapa interactivo real basado en FlutterMap + OpenStreetMap
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF0C1017),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Stack(
|
||||
children: [
|
||||
FlutterMap(
|
||||
mapController: _mapController,
|
||||
options: const MapOptions(
|
||||
initialCenter: LatLng(-0.1850, -78.4820),
|
||||
initialZoom: 14.5,
|
||||
minZoom: 5.0,
|
||||
maxZoom: 18.5,
|
||||
),
|
||||
children: [
|
||||
// Comentario explicativo: Capa de teselas (Tiles) de mapa real.
|
||||
// Modo Oscuro: CartoDB Dark Matter. Modo Claro: OpenStreetMap Tile Server estándar.
|
||||
TileLayer(
|
||||
urlTemplate: _modoOscuro
|
||||
? 'https://basemaps.cartocdn.com/rastertiles/dark_all/{z}/{x}/{y}.png'
|
||||
: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
|
||||
userAgentPackageName: 'net.telcotronics.central_monitoreo',
|
||||
),
|
||||
// Comentario explicativo: Marcadores geográficos interactivos ubicados en coordenadas reales
|
||||
MarkerLayer(
|
||||
markers: filtrados.map((p) => _crearMarcador(p)).toList(),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
// Controles de zoom y centrado flotantes en el mapa
|
||||
Positioned(
|
||||
top: 16,
|
||||
right: 16,
|
||||
child: Column(
|
||||
children: [
|
||||
_btnControlMapa(Icons.add, 'Acercar Zoom', () {
|
||||
final zoom = _mapController.camera.zoom + 1;
|
||||
_mapController.move(_mapController.camera.center, zoom);
|
||||
}),
|
||||
const SizedBox(height: 6),
|
||||
_btnControlMapa(Icons.remove, 'Alejar Zoom', () {
|
||||
final zoom = _mapController.camera.zoom - 1;
|
||||
_mapController.move(_mapController.camera.center, zoom);
|
||||
}),
|
||||
const SizedBox(height: 10),
|
||||
_btnControlMapa(Icons.my_location, 'Centrar Vista General', () {
|
||||
_mapController.move(const LatLng(-0.1850, -78.4820), 14.5);
|
||||
}),
|
||||
const SizedBox(height: 6),
|
||||
_btnControlMapa(Icons.warning_amber_rounded, 'Centrar en Pánico Activo', () {
|
||||
_mapController.move(const LatLng(-0.1806, -78.4842), 16.5);
|
||||
setState(() => _seleccionadoId = 101);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Leyenda de colores del mapa en esquina inferior izquierda
|
||||
Positioned(
|
||||
bottom: 16,
|
||||
left: 16,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow.withOpacity(0.92),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
_leyendaItem(AppColors.alarmaActiva, 'Sede con Pánico / Alarma'),
|
||||
const SizedBox(width: 14),
|
||||
_leyendaItem(AppColors.primary, 'Patrulla Móvil en Ruta'),
|
||||
const SizedBox(width: 14),
|
||||
_leyendaItem(AppColors.clienteOk, 'Unidad Disponible'),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 18),
|
||||
|
||||
// Panel lateral de lista y telemetría de unidades
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text('Unidades y Puntos de Interés',
|
||||
style: appHeadline(size: 14, weight: FontWeight.w700, color: AppColors.onSurface)),
|
||||
Text('${filtrados.length} puntos',
|
||||
style: appLabel(size: 11, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text('Toca una unidad para centrar el mapa y visualizar su telemetría GPS',
|
||||
style: appLabel(size: 11, color: AppColors.outline)),
|
||||
const Divider(height: 20, color: AppColors.outlineVariant),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
itemCount: filtrados.length,
|
||||
itemBuilder: (ctx, i) {
|
||||
final p = filtrados[i];
|
||||
final esSeleccionado = _seleccionadoId == p['id'];
|
||||
final esPatrulla = p['tipo'] == 'patrulla';
|
||||
|
||||
return InkWell(
|
||||
onTap: () => _centrarEn(p['lat'] as double, p['lng'] as double, p['id'] as int),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: esSeleccionado ? AppColors.surfaceHigh : AppColors.surfaceLowest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color: esSeleccionado ? AppColors.primary : AppColors.outlineVariant,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
esPatrulla ? Icons.directions_car : Icons.location_city,
|
||||
size: 16,
|
||||
color: esPatrulla ? AppColors.primary : AppColors.secondary,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(p['nombre'],
|
||||
style: appHeadline(
|
||||
size: 12, weight: FontWeight.w700, color: AppColors.onSurface)),
|
||||
],
|
||||
),
|
||||
_badgeEstado(p),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
if (esPatrulla) ...[
|
||||
Text('Personal: ${p['conductor']}',
|
||||
style: appLabel(size: 11, color: AppColors.outline)),
|
||||
Text('Velocidad: ${p['velocidad']} • ${p['rumbo']}',
|
||||
style: appLabel(size: 11, color: AppColors.primary)),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.battery_charging_full, size: 12, color: AppColors.clienteOk),
|
||||
const SizedBox(width: 4),
|
||||
Text('${p['bateria']}% Batería',
|
||||
style: appLabel(size: 10, color: AppColors.outline)),
|
||||
const SizedBox(width: 10),
|
||||
Text('Fix: ${p['ultimaTransmision']}',
|
||||
style: appLabel(size: 10, color: AppColors.outlineVariant)),
|
||||
const Spacer(),
|
||||
const Icon(Icons.gps_fixed, size: 12, color: AppColors.primary),
|
||||
const SizedBox(width: 2),
|
||||
Text('GPS', style: appLabel(size: 9, color: AppColors.primary)),
|
||||
],
|
||||
),
|
||||
] else ...[
|
||||
Text(p['direccion'], style: appLabel(size: 11, color: AppColors.outline)),
|
||||
if (p['alarmaActiva'] != null)
|
||||
Text('Alerta: ${p['alarmaActiva']}',
|
||||
style: appLabel(size: 11, color: AppColors.alarmaActiva)),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Genera un marcador Marker compatible con flutter_map 8.x
|
||||
Marker _crearMarcador(Map<String, dynamic> p) {
|
||||
final esPatrulla = p['tipo'] == 'patrulla';
|
||||
final id = p['id'] as int;
|
||||
final esSeleccionado = _seleccionadoId == id;
|
||||
final lat = p['lat'] as double;
|
||||
final lng = p['lng'] as double;
|
||||
|
||||
Color colorPin = AppColors.secondary;
|
||||
if (esPatrulla) {
|
||||
colorPin = AppColors.primary;
|
||||
} else {
|
||||
if (p['estado'] == 'critica') colorPin = AppColors.alarmaActiva;
|
||||
if (p['estado'] == 'alerta') colorPin = AppColors.clienteAlerta;
|
||||
}
|
||||
|
||||
return Marker(
|
||||
point: LatLng(lat, lng),
|
||||
width: 140,
|
||||
height: 70,
|
||||
alignment: Alignment.center,
|
||||
child: GestureDetector(
|
||||
onTap: () => _centrarEn(lat, lng, id),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withOpacity(0.85),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
border: Border.all(color: esSeleccionado ? colorPin : Colors.white24),
|
||||
),
|
||||
child: Text(
|
||||
p['nombre'],
|
||||
style: appLabel(size: 9, color: Colors.white, weight: FontWeight.w600),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(7),
|
||||
decoration: BoxDecoration(
|
||||
color: colorPin,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: colorPin.withOpacity(0.4),
|
||||
blurRadius: 8,
|
||||
spreadRadius: 2,
|
||||
),
|
||||
],
|
||||
border: Border.all(color: Colors.white, width: esSeleccionado ? 2.0 : 1.0),
|
||||
),
|
||||
child: Icon(
|
||||
esPatrulla ? Icons.local_police : Icons.business,
|
||||
size: 15,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _btnControlMapa(IconData icono, String tooltip, VoidCallback onTap) {
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow.withOpacity(0.9),
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: IconButton(
|
||||
icon: Icon(icono, size: 16, color: AppColors.onSurface),
|
||||
tooltip: tooltip,
|
||||
onPressed: onTap,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _filtroBtn(String tipo, String label) {
|
||||
final activo = _filtroTipo == tipo;
|
||||
return InkWell(
|
||||
onTap: () => setState(() => _filtroTipo = tipo),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
|
||||
color: activo ? AppColors.primaryContainer : Colors.transparent,
|
||||
child: Text(
|
||||
label,
|
||||
style: appLabel(
|
||||
size: 12,
|
||||
weight: activo ? FontWeight.bold : FontWeight.normal,
|
||||
color: activo ? AppColors.primary : AppColors.outline,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _leyendaItem(Color color, String texto) {
|
||||
return Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(texto, style: appLabel(size: 10, color: AppColors.outline)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _badgeEstado(Map<String, dynamic> p) {
|
||||
final esPatrulla = p['tipo'] == 'patrulla';
|
||||
final estado = p['estado'] as String?;
|
||||
Color color = AppColors.clienteOk;
|
||||
String label = 'NORMAL';
|
||||
|
||||
if (esPatrulla) {
|
||||
if (estado == 'en_despacho') {
|
||||
color = AppColors.alarmaActiva;
|
||||
label = 'EN RUTA';
|
||||
} else {
|
||||
color = AppColors.clienteOk;
|
||||
label = 'DISPONIBLE';
|
||||
}
|
||||
} else {
|
||||
if (estado == 'critica') {
|
||||
color = AppColors.alarmaActiva;
|
||||
label = 'PÁNICO';
|
||||
} else if (estado == 'alerta') {
|
||||
color = AppColors.clienteAlerta;
|
||||
label = 'ALERTA';
|
||||
}
|
||||
}
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(color: color.withOpacity(0.15), borderRadius: BorderRadius.circular(4)),
|
||||
child: Text(label, style: appLabel(size: 9, weight: FontWeight.bold, color: color)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:math' as math;
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/dao/incidentes_dao.dart';
|
||||
@@ -160,9 +161,14 @@ class _ReportesPageState extends State<ReportesPage> {
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Tarjetas KPI de resumen
|
||||
// Comentario explicativo: Cálculo responsivo con protección contra anchos negativos (math.max) para evitar errores BoxConstraints en primer renderizado
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
if (constraints.maxWidth <= 0) return const SizedBox.shrink();
|
||||
final isDesktop = constraints.maxWidth > 700;
|
||||
final cardWidth = isDesktop
|
||||
? math.max(0.0, (constraints.maxWidth - 36) / 4)
|
||||
: math.max(0.0, (constraints.maxWidth - 12) / 2);
|
||||
return Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
@@ -172,28 +178,28 @@ class _ReportesPageState extends State<ReportesPage> {
|
||||
valor: '$total',
|
||||
icono: Icons.analytics_outlined,
|
||||
color: AppColors.primary,
|
||||
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
||||
width: cardWidth,
|
||||
),
|
||||
_buildStatCard(
|
||||
title: 'Resueltos ($tasaEfectividad%)',
|
||||
valor: '$resueltos',
|
||||
icono: Icons.task_alt,
|
||||
color: AppColors.clienteOk,
|
||||
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
||||
width: cardWidth,
|
||||
),
|
||||
_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,
|
||||
width: cardWidth,
|
||||
),
|
||||
_buildStatCard(
|
||||
title: 'Falsas Alarmas',
|
||||
valor: '$falsas',
|
||||
icono: Icons.verified_user_outlined,
|
||||
color: AppColors.secondary,
|
||||
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
||||
width: cardWidth,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
+301
-62
@@ -4,6 +4,10 @@ import 'services/api_auth_service.dart';
|
||||
import 'db/dao/sesiones_dao.dart';
|
||||
import 'pages/dashboard_page.dart';
|
||||
import 'pages/monitoreo_page.dart';
|
||||
// Comentario explicativo: Importaciones de las sub-vistas tácticas de Monitoreo (Cámaras y Rastreo) y la consola de Estado de Comunicación
|
||||
import 'pages/camaras_page.dart';
|
||||
import 'pages/rastreo_page.dart';
|
||||
import 'pages/comunicacion_page.dart';
|
||||
import 'pages/clientes_page.dart';
|
||||
import 'pages/operadores_page.dart';
|
||||
import 'pages/incidentes_page.dart';
|
||||
@@ -15,6 +19,11 @@ import 'services/sincronizador.dart';
|
||||
class ShellPage extends StatefulWidget {
|
||||
const ShellPage({Key? key}) : super(key: key);
|
||||
|
||||
// Comentario explicativo: Método estático público para permitir saltos de navegación cruzada desde cualquier sub-pantalla (ej: Monitoreo -> Comunicación)
|
||||
static void irA(BuildContext context, int nuevoIndice) {
|
||||
context.findAncestorStateOfType<_ShellPageState>()?.cambiarIndice(nuevoIndice);
|
||||
}
|
||||
|
||||
@override
|
||||
State<ShellPage> createState() => _ShellPageState();
|
||||
}
|
||||
@@ -23,30 +32,39 @@ class _ShellPageState extends State<ShellPage> {
|
||||
int _indice = 0;
|
||||
String _operadorNombre = 'Operador';
|
||||
bool _apiConectada = false;
|
||||
bool _monitoreoExpandido = true;
|
||||
|
||||
final _sesionesDao = SesionesDao();
|
||||
|
||||
// Comentario explicativo: Lista de páginas indexadas en ShellPage.
|
||||
// 0: Dashboard, 1: Alarmas, 2: Cámaras, 3: Rastreo, 4: Clientes, 5: Operadores,
|
||||
// 6: Incidentes, 7: Dispositivos, 8: Comunicación, 9: Reportes, 10: Configuración
|
||||
static const _paginas = [
|
||||
DashboardPage(),
|
||||
MonitoreoPage(),
|
||||
ClientesPage(),
|
||||
OperadoresPage(),
|
||||
IncidentesPage(),
|
||||
DispositivosPage(),
|
||||
ReportesPage(),
|
||||
ConfiguracionPage(),
|
||||
DashboardPage(), // 0
|
||||
MonitoreoPage(), // 1 (Alarmas)
|
||||
CamarasPage(), // 2 (Cámaras)
|
||||
RastreoPage(), // 3 (Rastreo)
|
||||
ClientesPage(), // 4
|
||||
OperadoresPage(), // 5
|
||||
IncidentesPage(), // 6
|
||||
DispositivosPage(), // 7
|
||||
ComunicacionPage(), // 8 (Estado de Comunicación)
|
||||
ReportesPage(), // 9
|
||||
ConfiguracionPage(),// 10
|
||||
];
|
||||
|
||||
static const _navItems = [
|
||||
_NavItem(Icons.dashboard_outlined, Icons.dashboard, 'Dashboard'),
|
||||
_NavItem(Icons.track_changes_outlined, Icons.track_changes, 'Monitoreo'),
|
||||
_NavItem(Icons.business_outlined, Icons.business, 'Clientes'),
|
||||
_NavItem(Icons.group_outlined, Icons.group, 'Operadores'),
|
||||
_NavItem(Icons.assignment_outlined, Icons.assignment, 'Incidentes'),
|
||||
_NavItem(Icons.devices_outlined, Icons.devices, 'Dispositivos'),
|
||||
_NavItem(Icons.bar_chart_outlined, Icons.bar_chart, 'Reportes'),
|
||||
_NavItem(Icons.settings_outlined, Icons.settings, 'Configuración'),
|
||||
];
|
||||
// Comentario explicativo: Actualiza el índice activo y mantiene expandido el acordeón si se navega a una sub-vista de Monitoreo
|
||||
void cambiarIndice(int nuevoIndice) {
|
||||
setState(() {
|
||||
_indice = nuevoIndice;
|
||||
if (nuevoIndice >= 1 && nuevoIndice <= 3) {
|
||||
_monitoreoExpandido = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Comentario explicativo: La navegación ahora se gestiona directamente en _buildNavigationList para
|
||||
// soportar la estructura jerárquica con acordeón de Monitoreo (Alarmas, Cámaras, Rastreo) y Estado de Comunicación.
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -148,11 +166,7 @@ class _ShellPageState extends State<ShellPage> {
|
||||
),
|
||||
const Divider(color: AppColors.outlineVariant, height: 1),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
itemCount: _navItems.length,
|
||||
itemBuilder: (_, i) => _navTile(i, cerrarDrawerAlTocar: true),
|
||||
),
|
||||
child: _buildNavigationList(cerrarDrawerAlTocar: true),
|
||||
),
|
||||
]),
|
||||
),
|
||||
@@ -185,8 +199,8 @@ class _ShellPageState extends State<ShellPage> {
|
||||
bottomNavigationBar: esMovil
|
||||
? BottomNavigationBar(
|
||||
// Comentario explicativo: Mapeo de índices de navegación móvil:
|
||||
// 0: Dashboard, 1: Monitoreo, 2: Clientes, 4: Incidentes
|
||||
currentIndex: _indice == 4 ? 3 : (_indice < 3 ? _indice : 0),
|
||||
// 0: Dashboard, 1: Monitoreo (Alarmas), 4: Clientes, 6: Incidentes, 8: Comunicación
|
||||
currentIndex: _indice == 8 ? 4 : (_indice == 6 ? 3 : (_indice == 4 ? 2 : (_indice >= 1 && _indice <= 3 ? 1 : 0))),
|
||||
backgroundColor: AppColors.surfaceLow,
|
||||
selectedItemColor: AppColors.primary,
|
||||
unselectedItemColor: AppColors.onSurfaceVariant,
|
||||
@@ -194,8 +208,8 @@ class _ShellPageState extends State<ShellPage> {
|
||||
selectedFontSize: 11,
|
||||
unselectedFontSize: 10,
|
||||
onTap: (i) {
|
||||
const indicesMovil = [0, 1, 2, 4];
|
||||
setState(() => _indice = indicesMovil[i]);
|
||||
const indicesMovil = [0, 1, 4, 6, 8];
|
||||
cambiarIndice(indicesMovil[i]);
|
||||
},
|
||||
items: const [
|
||||
BottomNavigationBarItem(
|
||||
@@ -218,6 +232,11 @@ class _ShellPageState extends State<ShellPage> {
|
||||
activeIcon: Icon(Icons.assignment),
|
||||
label: 'Incidentes',
|
||||
),
|
||||
BottomNavigationBarItem(
|
||||
icon: Icon(Icons.cell_tower_outlined),
|
||||
activeIcon: Icon(Icons.cell_tower),
|
||||
label: 'Comunicación',
|
||||
),
|
||||
],
|
||||
)
|
||||
: null,
|
||||
@@ -285,7 +304,7 @@ class _ShellPageState extends State<ShellPage> {
|
||||
),
|
||||
]),
|
||||
),
|
||||
// Comentario explicativo: Indicador visual prioritario de alarmas críticas en el header con salto directo a Monitoreo
|
||||
// Comentario explicativo: Indicador visual prioritario de alarmas críticas en el header con salto directo a Monitoreo (Alarmas)
|
||||
ValueListenableBuilder<int>(
|
||||
valueListenable: Sincronizador.instance.criticalAlarmsCount,
|
||||
builder: (ctx, count, _) {
|
||||
@@ -293,7 +312,7 @@ class _ShellPageState extends State<ShellPage> {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 6),
|
||||
child: InkWell(
|
||||
onTap: () => setState(() => _indice = 1),
|
||||
onTap: () => cambiarIndice(1),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
@@ -366,24 +385,251 @@ class _ShellPageState extends State<ShellPage> {
|
||||
);
|
||||
|
||||
// ── Sidebar ─────────────────────────────────────────────────────────────────
|
||||
// Comentario explicativo: Sidebar lateral fijo para escritorio con menú interactivo y acordeón en Monitoreo
|
||||
Widget _sidebar() => Container(
|
||||
width: 220,
|
||||
color: AppColors.surfaceLow,
|
||||
child: Column(children: [
|
||||
const SizedBox(height: 8),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
|
||||
itemCount: _navItems.length,
|
||||
itemBuilder: (_, i) => _navTile(i),
|
||||
),
|
||||
child: _buildNavigationList(cerrarDrawerAlTocar: false),
|
||||
),
|
||||
]),
|
||||
);
|
||||
|
||||
Widget _navTile(int i, {bool cerrarDrawerAlTocar = false}) {
|
||||
final item = _navItems[i];
|
||||
final activo = _indice == i;
|
||||
// Comentario explicativo: Construye la lista de navegación compartida entre el Sidebar de escritorio y el Drawer móvil
|
||||
Widget _buildNavigationList({bool cerrarDrawerAlTocar = false}) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
children: [
|
||||
// 0: Dashboard
|
||||
_navItemTile(
|
||||
indice: 0,
|
||||
label: 'Dashboard',
|
||||
icon: Icons.dashboard_outlined,
|
||||
iconActivo: Icons.dashboard,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
|
||||
// Acordeón Monitoreo con submenú (Alarmas, Cámaras, Rastreo)
|
||||
_monitoreoAccordionTile(cerrarDrawerAlTocar: cerrarDrawerAlTocar),
|
||||
const SizedBox(height: 2),
|
||||
|
||||
// 4: Clientes
|
||||
_navItemTile(
|
||||
indice: 4,
|
||||
label: 'Clientes',
|
||||
icon: Icons.business_outlined,
|
||||
iconActivo: Icons.business,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
// 5: Operadores
|
||||
_navItemTile(
|
||||
indice: 5,
|
||||
label: 'Operadores',
|
||||
icon: Icons.group_outlined,
|
||||
iconActivo: Icons.group,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
// 6: Incidentes
|
||||
_navItemTile(
|
||||
indice: 6,
|
||||
label: 'Incidentes',
|
||||
icon: Icons.assignment_outlined,
|
||||
iconActivo: Icons.assignment,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
// 7: Dispositivos
|
||||
_navItemTile(
|
||||
indice: 7,
|
||||
label: 'Dispositivos',
|
||||
icon: Icons.devices_outlined,
|
||||
iconActivo: Icons.devices,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
// 8: Estado de Comunicación
|
||||
_navItemTile(
|
||||
indice: 8,
|
||||
label: 'Comunicación',
|
||||
icon: Icons.cell_tower_outlined,
|
||||
iconActivo: Icons.cell_tower,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
// 9: Reportes
|
||||
_navItemTile(
|
||||
indice: 9,
|
||||
label: 'Reportes',
|
||||
icon: Icons.bar_chart_outlined,
|
||||
iconActivo: Icons.bar_chart,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
// 10: Configuración
|
||||
_navItemTile(
|
||||
indice: 10,
|
||||
label: 'Configuración',
|
||||
icon: Icons.settings_outlined,
|
||||
iconActivo: Icons.settings,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Acordeón desplegable para la sección de Monitoreo con submenú: Alarmas, Cámaras y Rastreo
|
||||
Widget _monitoreoAccordionTile({bool cerrarDrawerAlTocar = false}) {
|
||||
final estaEnSubMenu = _indice >= 1 && _indice <= 3;
|
||||
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Material(
|
||||
color: Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
onTap: () {
|
||||
setState(() {
|
||||
if (!_monitoreoExpandido) {
|
||||
_monitoreoExpandido = true;
|
||||
if (!estaEnSubMenu) cambiarIndice(1);
|
||||
} else {
|
||||
if (estaEnSubMenu) {
|
||||
_monitoreoExpandido = false;
|
||||
} else {
|
||||
cambiarIndice(1);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 160),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: estaEnSubMenu ? AppColors.primaryContainer.withOpacity(0.35) : Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: estaEnSubMenu ? AppColors.primary.withOpacity(0.3) : Colors.transparent,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
estaEnSubMenu ? Icons.track_changes : Icons.track_changes_outlined,
|
||||
size: 20,
|
||||
color: estaEnSubMenu ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Monitoreo',
|
||||
style: appLabel(
|
||||
size: 13,
|
||||
weight: estaEnSubMenu ? FontWeight.w700 : FontWeight.normal,
|
||||
color: estaEnSubMenu ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
Icon(
|
||||
_monitoreoExpandido ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
|
||||
size: 16,
|
||||
color: AppColors.outline,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_monitoreoExpandido) ...[
|
||||
const SizedBox(height: 2),
|
||||
// Sub-ítem 1: Alarmas
|
||||
_subItemTile(
|
||||
indice: 1,
|
||||
label: 'Alarmas',
|
||||
icon: Icons.notifications_active_outlined,
|
||||
iconActivo: Icons.notifications_active,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
// Sub-ítem 2: Cámaras
|
||||
_subItemTile(
|
||||
indice: 2,
|
||||
label: 'Cámaras',
|
||||
icon: Icons.videocam_outlined,
|
||||
iconActivo: Icons.videocam,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
// Sub-ítem 3: Rastreo
|
||||
_subItemTile(
|
||||
indice: 3,
|
||||
label: 'Rastreo',
|
||||
icon: Icons.near_me_outlined,
|
||||
iconActivo: Icons.near_me,
|
||||
cerrarDrawerAlTocar: cerrarDrawerAlTocar,
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Sub-ítem sangrado para las opciones internas de Monitoreo
|
||||
Widget _subItemTile({
|
||||
required int indice,
|
||||
required String label,
|
||||
required IconData icon,
|
||||
required IconData iconActivo,
|
||||
bool cerrarDrawerAlTocar = false,
|
||||
}) {
|
||||
final activo = _indice == indice;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 20, right: 2, top: 2, bottom: 2),
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: () {
|
||||
cambiarIndice(indice);
|
||||
if (cerrarDrawerAlTocar) Navigator.of(context).pop();
|
||||
},
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: activo ? AppColors.primaryContainer : Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
activo ? iconActivo : icon,
|
||||
size: 17,
|
||||
color: activo ? AppColors.primary : AppColors.outline,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
label,
|
||||
style: appLabel(
|
||||
size: 12,
|
||||
weight: activo ? FontWeight.w700 : FontWeight.normal,
|
||||
color: activo ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Comentario explicativo: Ítem de nivel principal en el menú de navegación lateral
|
||||
Widget _navItemTile({
|
||||
required int indice,
|
||||
required String label,
|
||||
required IconData icon,
|
||||
required IconData iconActivo,
|
||||
bool cerrarDrawerAlTocar = false,
|
||||
}) {
|
||||
final activo = _indice == indice;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
||||
child: Material(
|
||||
@@ -392,10 +638,8 @@ class _ShellPageState extends State<ShellPage> {
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
onTap: () {
|
||||
setState(() => _indice = i);
|
||||
if (cerrarDrawerAlTocar) {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
cambiarIndice(indice);
|
||||
if (cerrarDrawerAlTocar) Navigator.of(context).pop();
|
||||
},
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 160),
|
||||
@@ -404,32 +648,27 @@ class _ShellPageState extends State<ShellPage> {
|
||||
color: activo ? AppColors.primaryContainer : Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Row(children: [
|
||||
Icon(
|
||||
activo ? item.iconActivo : item.icon,
|
||||
size: 20,
|
||||
color: activo ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
item.label,
|
||||
style: appLabel(
|
||||
size: 13,
|
||||
weight: activo ? FontWeight.w600 : FontWeight.normal,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
activo ? iconActivo : icon,
|
||||
size: 20,
|
||||
color: activo ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
]),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
label,
|
||||
style: appLabel(
|
||||
size: 13,
|
||||
weight: activo ? FontWeight.w600 : FontWeight.normal,
|
||||
color: activo ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _NavItem {
|
||||
final IconData icon;
|
||||
final IconData iconActivo;
|
||||
final String label;
|
||||
const _NavItem(this.icon, this.iconActivo, this.label);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user