Files
Central_monitoreo/lib/pages/monitoreo_page.dart
T
PablinuxandClaude Sonnet 4.6 21d2c20525 feat: commit inicial — Central Monitoreo v1.0.0
- OperadorLoginPage con auth WebControl 2 pasos (empresas → login)
- ShellPage: sidebar 220px + IndexedStack + header con estado API
- DashboardPage: stat cards, feed alarmas, clientes, incidentes (timer 30s)
- ApiAuthService: flujo real con email + paswd + dba → token + apiKey
- DB SQLite v1: 7 tablas + 7 DAOs completos
- theme.dart: AppColors, appHeadline (Manrope), appLabel (Inter)
- Logo app: escudo radar neón (SVG + PNG 512px) en lib/recursos/
- desplegar.sh: build release Linux + upload a siax-system.net
- agents.md: estado completo + objetivos futuros documentados

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 22:11:12 -05:00

747 lines
26 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import '../theme.dart';
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';
class MonitoreoPage extends StatefulWidget {
const MonitoreoPage({Key? key}) : super(key: key);
@override
State<MonitoreoPage> createState() => _MonitoreoPageState();
}
class _MonitoreoPageState extends State<MonitoreoPage> {
final _alarmasDao = CacheAlarmasDao();
final _clientesDao = CacheClientesDao();
final _incidentesDao = IncidentesDao();
List<Map<String, dynamic>> _todasAlarmas = [];
List<Map<String, dynamic>> _alarmasFiltradas = [];
List<Map<String, dynamic>> _clientes = [];
String _filtroEstado = 'activa'; // 'todas' | 'activa' | 'silenciada'
int _filtroSeveridad = 0; // 0=todas, 3=alta, 4=critica
int? _filtroClienteId; // null = todos
bool _cargando = true;
String _operador = '';
Timer? _timer;
static const _tiposIncidenteId = [
'verificacion',
'contacto_cliente',
'despacho_patrulla',
'llamada_policia',
'falsa_alarma',
'otro',
];
static const _tiposIncidenteLabel = [
'Verificación',
'Contacto con cliente',
'Despacho de patrulla',
'Llamada a policía',
'Falsa alarma',
'Otro',
];
@override
void initState() {
super.initState();
_cargarOperador();
_cargar();
_timer = Timer.periodic(const Duration(seconds: 30), (_) => _cargar());
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
Future<void> _cargarOperador() async {
final u = await ApiAuthService.instance.getUsuario();
if (mounted) setState(() => _operador = u ?? '');
}
Future<void> _cargar() async {
if (!mounted) return;
setState(() => _cargando = true);
final results = await Future.wait([
_alarmasDao.getTodas(limit: 200),
_clientesDao.getTodos(),
]);
if (!mounted) return;
_todasAlarmas = (results[0] as List).cast<Map<String, dynamic>>();
_clientes = (results[1] as List).cast<Map<String, dynamic>>();
_aplicarFiltros();
setState(() => _cargando = false);
}
void _aplicarFiltros() {
var lista = List<Map<String, dynamic>>.from(_todasAlarmas);
if (_filtroEstado != 'todas') {
lista = lista.where((a) => a['estado'] == _filtroEstado).toList();
}
if (_filtroSeveridad > 0) {
lista = lista.where((a) => ((a['severidad'] as int?) ?? 0) >= _filtroSeveridad).toList();
}
if (_filtroClienteId != null) {
lista = lista.where((a) => a['cliente_id'] == _filtroClienteId).toList();
}
lista.sort((a, b) {
final sevCmp = ((b['severidad'] as int?) ?? 0)
.compareTo((a['severidad'] as int?) ?? 0);
if (sevCmp != 0) return sevCmp;
return ((b['timestamp'] as String?) ?? '')
.compareTo((a['timestamp'] as String?) ?? '');
});
setState(() => _alarmasFiltradas = lista);
}
// ── Helpers ──────────────────────────────────────────────────────────────────
String _timeAgo(String? iso) {
if (iso == null) return '';
final dt = DateTime.tryParse(iso);
if (dt == null) return '';
final diff = DateTime.now().difference(dt);
if (diff.inSeconds < 60) return 'ahora';
if (diff.inMinutes < 60) return '${diff.inMinutes} min';
if (diff.inHours < 24) return '${diff.inHours} h';
return '${diff.inDays} d';
}
Color _colorSev(int sev) {
if (sev >= 4) return AppColors.alarmaActiva;
if (sev == 3) return AppColors.clienteAlerta;
return AppColors.alarmaSilenciada;
}
String _labelSev(int sev) {
if (sev >= 5) return 'MAX';
if (sev == 4) return 'CRIT';
if (sev == 3) return 'ALTA';
if (sev == 2) return 'MED';
return 'BAJA';
}
int get _countActivas => _todasAlarmas.where((a) => a['estado'] == 'activa').length;
int get _countCriticas => _todasAlarmas.where((a) => a['estado'] == 'activa' && ((a['severidad'] as int?) ?? 0) >= 4).length;
int get _countSilenciadas => _todasAlarmas.where((a) => a['estado'] == 'silenciada').length;
// ── Acciones inline ───────────────────────────────────────────────────────────
Future<void> _escalar(Map<String, dynamic> alarma) async {
final ok = await showDialog<bool>(
context: context,
builder: (_) => _dialogConfirmar(
titulo: 'Escalar alarma',
cuerpo: 'Se registrará la escalación de esta alarma.\n'
'Un supervisor recibirá la notificación.',
labelBoton: 'ESCALAR',
colorBoton: AppColors.alarmaActiva,
),
);
if (ok != true || !mounted) return;
await _incidentesDao.registrar(
alarmaId: alarma['id'] as int?,
clienteId: alarma['cliente_id'] as int?,
clienteNombre: alarma['cliente_nombre'] as String?,
tipo: 'escalacion',
operador: _operador,
notas: 'Alarma escalada desde Monitoreo. '
'Severidad: ${_labelSev((alarma['severidad'] as int?) ?? 0)}',
);
_mostrarSnack('Alarma escalada y registrada.', AppColors.alarmaActiva);
}
Future<void> _silenciar(Map<String, dynamic> alarma) async {
final ok = await showDialog<bool>(
context: context,
builder: (_) => _dialogConfirmar(
titulo: 'Silenciar alarma',
cuerpo: 'La alarma dejará de aparecer en alarmas activas.\n'
'Queda registrada en el historial.',
labelBoton: 'SILENCIAR',
colorBoton: AppColors.clienteAlerta,
),
);
if (ok != true || !mounted) return;
final id = alarma['id'] as int?;
if (id != null) await _alarmasDao.actualizarEstado(id, 'silenciada');
await _incidentesDao.registrar(
alarmaId: id,
clienteId: alarma['cliente_id'] as int?,
clienteNombre: alarma['cliente_nombre'] as String?,
tipo: 'silenciado',
operador: _operador,
);
_mostrarSnack('Alarma silenciada.', AppColors.clienteAlerta);
_cargar();
}
Future<void> _registrarIncidente(Map<String, dynamic> alarma) async {
String tipoSeleccionado = _tiposIncidenteId[0];
final ctrlNotas = TextEditingController();
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => StatefulBuilder(
builder: (ctx, setDlg) => AlertDialog(
backgroundColor: AppColors.surfaceHigh,
title: Text('Registrar incidente',
style: appHeadline(size: 16, weight: FontWeight.w700)),
content: SizedBox(
width: 420,
child: Column(mainAxisSize: MainAxisSize.min, children: [
// Info de alarma
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppColors.surfaceHighest,
borderRadius: BorderRadius.circular(8),
),
child: Row(children: [
const Icon(Icons.notifications_active_outlined,
size: 16, color: AppColors.outline),
const SizedBox(width: 8),
Expanded(
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(alarma['tipo'] as String? ?? '—',
style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
if (alarma['cliente_nombre'] != null)
Text(alarma['cliente_nombre'] as String,
style: appLabel(size: 11, color: AppColors.primary)),
]),
),
]),
),
const SizedBox(height: 16),
// Tipo incidente
DropdownButtonFormField<String>(
value: tipoSeleccionado,
dropdownColor: AppColors.surfaceHighest,
style: appLabel(size: 13, color: AppColors.onSurface),
decoration: _inputDecoration('Tipo de incidente'),
items: List.generate(
_tiposIncidenteId.length,
(i) => DropdownMenuItem(
value: _tiposIncidenteId[i],
child: Text(_tiposIncidenteLabel[i]),
),
),
onChanged: (v) {
if (v != null) setDlg(() => tipoSeleccionado = v);
},
),
const SizedBox(height: 12),
// Notas
TextField(
controller: ctrlNotas,
maxLines: 3,
style: appLabel(size: 13, color: AppColors.onSurface),
decoration: _inputDecoration('Notas (opcional)'),
),
]),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: Text('Cancelar', style: appLabel(color: AppColors.onSurfaceVariant)),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: AppColors.primary,
onPrimary: AppColors.primaryContainer,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
onPressed: () => Navigator.pop(ctx, true),
child: Text('REGISTRAR',
style: appLabel(weight: FontWeight.bold, color: AppColors.primaryContainer)),
),
],
),
),
);
ctrlNotas.dispose();
if (ok != true || !mounted) return;
await _incidentesDao.registrar(
alarmaId: alarma['id'] as int?,
clienteId: alarma['cliente_id'] as int?,
clienteNombre: alarma['cliente_nombre'] as String?,
tipo: tipoSeleccionado,
operador: _operador,
notas: ctrlNotas.text.trim().isEmpty ? null : ctrlNotas.text.trim(),
);
_mostrarSnack('Incidente registrado.', AppColors.primary);
}
Widget _dialogConfirmar({
required String titulo,
required String cuerpo,
required String labelBoton,
required Color colorBoton,
}) =>
AlertDialog(
backgroundColor: AppColors.surfaceHigh,
title: Text(titulo, style: appHeadline(size: 16, weight: FontWeight.w700)),
content: Text(cuerpo, style: appLabel(size: 13, color: AppColors.onSurface)),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text('Cancelar', style: appLabel(color: AppColors.onSurfaceVariant)),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: Text(labelBoton,
style: appLabel(weight: FontWeight.bold, color: colorBoton)),
),
],
);
InputDecoration _inputDecoration(String label) => InputDecoration(
labelText: label,
labelStyle: appLabel(size: 12, color: AppColors.outline),
filled: true,
fillColor: AppColors.surfaceHighest,
contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: AppColors.outlineVariant)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: AppColors.outlineVariant)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: AppColors.primary, width: 1.5)),
);
void _mostrarSnack(String msg, Color color) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(msg, style: appLabel(color: AppColors.surfaceLowest)),
backgroundColor: color,
duration: const Duration(seconds: 3),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
margin: const EdgeInsets.all(16),
));
}
// ── Build ────────────────────────────────────────────────────────────────────
@override
Widget build(BuildContext context) {
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
// ── Sección fija: header + filtros + cabecera de tabla ──────────────────
Container(
color: AppColors.surfaceLowest,
padding: const EdgeInsets.fromLTRB(28, 20, 28, 0),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
_headerRow(),
const SizedBox(height: 14),
_barraFiltros(),
const SizedBox(height: 14),
_tablaHeader(),
const Divider(color: AppColors.outlineVariant, height: 1),
]),
),
// ── Cuerpo scrollable de la tabla ───────────────────────────────────────
Expanded(
child: _cargando
? const Center(
child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.primary))
: _alarmasFiltradas.isEmpty
? _emptyState()
: ListView.separated(
primary: false,
padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 4),
itemCount: _alarmasFiltradas.length,
separatorBuilder: (_, __) =>
const Divider(color: AppColors.outlineVariant, height: 1),
itemBuilder: (_, i) => _alarmaRow(_alarmasFiltradas[i]),
),
),
]);
}
// ── Header ───────────────────────────────────────────────────────────────────
Widget _headerRow() => Row(children: [
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text('Monitoreo', style: appHeadline(size: 22, weight: FontWeight.w800)),
const SizedBox(height: 2),
RichText(
text: TextSpan(children: [
TextSpan(
text: '$_countActivas activas',
style: appLabel(size: 12, color: AppColors.clienteAlerta),
),
if (_countCriticas > 0) ...[
TextSpan(text: ' · ', style: appLabel(size: 12, color: AppColors.outline)),
TextSpan(
text: '$_countCriticas críticas',
style: appLabel(size: 12, color: AppColors.alarmaActiva, weight: FontWeight.bold),
),
],
if (_countSilenciadas > 0) ...[
TextSpan(text: ' · ', style: appLabel(size: 12, color: AppColors.outline)),
TextSpan(
text: '$_countSilenciadas silenciadas',
style: appLabel(size: 12, color: AppColors.outline),
),
],
]),
),
]),
const Spacer(),
if (_cargando)
const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.primary),
)
else
IconButton(
tooltip: 'Actualizar',
icon: const Icon(Icons.refresh, color: AppColors.outline, size: 20),
onPressed: _cargar,
),
]);
// ── Filtros ──────────────────────────────────────────────────────────────────
static const _estadoIds = ['todas', 'activa', 'silenciada'];
static const _estadoLabels = ['Todas', 'Activas', 'Silenciadas'];
static const _sevIds = [0, 4, 3, 1];
static const _sevLabels = ['Todas', 'Críticas', 'Altas', 'Medias/Bajas'];
Widget _barraFiltros() {
final chipEstado = <Widget>[];
for (int i = 0; i < _estadoIds.length; i++) {
final id = _estadoIds[i];
final label = _estadoLabels[i];
chipEstado.add(_chip(
label: label,
seleccionado: _filtroEstado == id,
onTap: () {
setState(() => _filtroEstado = id);
_aplicarFiltros();
},
));
}
final chipSev = <Widget>[];
for (int i = 0; i < _sevIds.length; i++) {
final id = _sevIds[i];
final label = _sevLabels[i];
Color? color;
if (id >= 4) { color = AppColors.alarmaActiva; }
else if (id == 3) { color = AppColors.clienteAlerta; }
chipSev.add(_chip(
label: label,
seleccionado: _filtroSeveridad == id,
color: color,
onTap: () {
setState(() => _filtroSeveridad = id);
_aplicarFiltros();
},
));
}
return Wrap(
spacing: 8,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text('Estado:', style: appLabel(size: 11, color: AppColors.outline)),
...chipEstado,
const SizedBox(width: 12),
Text('Severidad:', style: appLabel(size: 11, color: AppColors.outline)),
...chipSev,
const SizedBox(width: 12),
if (_clientes.isNotEmpty) ...[
Text('Cliente:', style: appLabel(size: 11, color: AppColors.outline)),
_dropdownCliente(),
],
],
);
}
Widget _chip({
required String label,
required bool seleccionado,
required VoidCallback onTap,
Color? color,
}) {
final efectivoColor = color ?? AppColors.primary;
return GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 120),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
decoration: BoxDecoration(
color: seleccionado ? efectivoColor.withOpacity(0.15) : AppColors.surfaceHighest,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: seleccionado ? efectivoColor.withOpacity(0.5) : AppColors.outlineVariant,
),
),
child: Text(
label,
style: appLabel(
size: 11,
weight: seleccionado ? FontWeight.w600 : FontWeight.normal,
color: seleccionado ? efectivoColor : AppColors.onSurfaceVariant,
),
),
),
);
}
Widget _dropdownCliente() => Container(
height: 28,
padding: const EdgeInsets.symmetric(horizontal: 10),
decoration: BoxDecoration(
color: _filtroClienteId != null
? AppColors.primaryContainer
: AppColors.surfaceHighest,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: _filtroClienteId != null
? AppColors.primary.withOpacity(0.5)
: AppColors.outlineVariant,
),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<int?>(
value: _filtroClienteId,
isDense: true,
dropdownColor: AppColors.surfaceHigh,
style: appLabel(size: 11, color: AppColors.onSurfaceVariant),
icon: const Icon(Icons.keyboard_arrow_down, size: 14, color: AppColors.outline),
items: [
DropdownMenuItem<int?>(
value: null,
child: Text('Todos', style: appLabel(size: 11)),
),
..._clientes.map((c) => DropdownMenuItem<int?>(
value: c['id'] as int?,
child: Text(
c['nombre'] as String? ?? '—',
style: appLabel(size: 11),
overflow: TextOverflow.ellipsis,
),
)),
],
onChanged: (v) {
setState(() => _filtroClienteId = v);
_aplicarFiltros();
},
),
),
);
// ── Tabla ────────────────────────────────────────────────────────────────────
Widget _tablaHeader() => Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(children: [
const SizedBox(width: 62),
Expanded(
flex: 3,
child: Text('Tipo / Descripción',
style: appLabel(size: 11, color: AppColors.outline)),
),
Expanded(
flex: 2,
child: Text('Cliente', style: appLabel(size: 11, color: AppColors.outline)),
),
Expanded(
flex: 2,
child: Text('Zona', style: appLabel(size: 11, color: AppColors.outline)),
),
const SizedBox(
width: 80,
child: Text('', style: TextStyle()), // tiempo — no label para ahorrar espacio
),
const SizedBox(width: 110),
]),
);
Widget _alarmaRow(Map<String, dynamic> a) {
final sev = (a['severidad'] as int?) ?? 1;
final color = _colorSev(sev);
final label = _labelSev(sev);
final estado = a['estado'] as String? ?? 'activa';
final esActiva = estado == 'activa';
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(children: [
// Badge severidad
Container(
width: 52,
padding: const EdgeInsets.symmetric(vertical: 4),
decoration: BoxDecoration(
color: color.withOpacity(esActiva ? 0.15 : 0.06),
borderRadius: BorderRadius.circular(6),
border: Border.all(color: color.withOpacity(esActiva ? 0.35 : 0.15)),
),
child: Center(
child: Text(
label,
style: appLabel(
size: 10,
weight: FontWeight.bold,
color: color.withOpacity(esActiva ? 1.0 : 0.5)),
),
),
),
const SizedBox(width: 10),
// Tipo
Expanded(
flex: 3,
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(
a['tipo'] as String? ?? '—',
style: appLabel(
size: 12,
weight: FontWeight.w600,
color: esActiva ? AppColors.onSurface : AppColors.outline,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (a['notas'] != null && (a['notas'] as String).isNotEmpty)
Text(
a['notas'] as String,
style: appLabel(size: 11, color: AppColors.onSurfaceVariant),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
]),
),
// Cliente
Expanded(
flex: 2,
child: Text(
a['cliente_nombre'] as String? ?? '—',
style: appLabel(
size: 12,
color: esActiva ? AppColors.primary : AppColors.outline),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
// Zona
Expanded(
flex: 2,
child: Text(
a['zona_nombre'] as String? ?? '—',
style: appLabel(size: 12, color: AppColors.onSurfaceVariant),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
// Tiempo
SizedBox(
width: 80,
child: Text(
_timeAgo(a['timestamp'] as String?),
style: appLabel(size: 11, color: AppColors.outline),
),
),
// Acciones
SizedBox(
width: 110,
child: esActiva
? Row(mainAxisSize: MainAxisSize.min, children: [
_accionBtn(
icon: Icons.arrow_upward,
tooltip: 'Escalar',
color: AppColors.alarmaActiva,
onTap: () => _escalar(a),
),
const SizedBox(width: 2),
_accionBtn(
icon: Icons.volume_off_outlined,
tooltip: 'Silenciar',
color: AppColors.clienteAlerta,
onTap: () => _silenciar(a),
),
const SizedBox(width: 2),
_accionBtn(
icon: Icons.note_add_outlined,
tooltip: 'Registrar incidente',
color: AppColors.primary,
onTap: () => _registrarIncidente(a),
),
])
: Text('Silenciada',
style: appLabel(size: 11, color: AppColors.outline)),
),
]),
);
}
Widget _accionBtn({
required IconData icon,
required String tooltip,
required Color color,
required VoidCallback onTap,
}) =>
Tooltip(
message: tooltip,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(6),
child: Container(
width: 30,
height: 30,
decoration: BoxDecoration(
color: color.withOpacity(0.1),
borderRadius: BorderRadius.circular(6),
),
child: Icon(icon, size: 15, color: color),
),
),
);
// ── Empty state ──────────────────────────────────────────────────────────────
Widget _emptyState() => Center(
child: Column(mainAxisSize: MainAxisSize.min, children: [
const Icon(Icons.notifications_none, size: 48, color: AppColors.outlineVariant),
const SizedBox(height: 14),
Text(
_filtroEstado == 'activa'
? 'Sin alarmas activas'
: 'Sin resultados con los filtros actuales',
style: appLabel(size: 14, color: AppColors.outline),
),
const SizedBox(height: 6),
Text(
'El sistema sincroniza con Centinel cada 30 segundos',
style: appLabel(size: 12, color: AppColors.outlineVariant),
),
]),
);
}