commit 21d2c20525505dd27154a1bb6cf226d70b2d7287 Author: Pablinux Date: Sun Jun 21 22:11:12 2026 -0500 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..60373df --- /dev/null +++ b/.gitignore @@ -0,0 +1,55 @@ +# Flutter +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +build/ +*.g.dart +*.freezed.dart + +# Android +**/android/**/gradle-wrapper.jar +**/android/.gradle +**/android/captures/ +**/android/gradlew +**/android/gradlew.bat +**/android/local.properties +**/android/**/GeneratedPluginRegistrant.java +**/android/key.properties +*.jks + +# iOS / macOS +**/ios/**/*.mode1v3 +**/ios/**/*.pbxuser +**/ios/**/*.perspectivev3 +**/ios/**/DerivedData/ +**/ios/**/*.ipa +**/ios/**/Flutter/App.framework +**/ios/**/Flutter/Flutter.framework +**/ios/**/Flutter/Generated.xcconfig +**/ios/**/Flutter/ephemeral/ +**/ios/**/Runner/GeneratedPluginRegistrant.* +**/macos/Flutter/GeneratedPluginRegistrant.swift +**/macos/Flutter/ephemeral/ + +# Linux / Windows +**/linux/flutter/generated_plugin_registrant.cc +**/linux/flutter/generated_plugin_registrant.h +**/linux/flutter/generated_plugins.cmake +**/windows/flutter/generated_plugin_registrant.cc +**/windows/flutter/generated_plugin_registrant.h +**/windows/flutter/generated_plugins.cmake + +# Web +lib/generated_plugin_registrant.dart + +# IDE +.idea/ +.vscode/ +*.iml + +# Misc +*.log +pubspec.lock diff --git a/agents.md b/agents.md new file mode 100644 index 0000000..3cdd7a0 --- /dev/null +++ b/agents.md @@ -0,0 +1,320 @@ +# agents.md — Centro de Monitoreo General + +> **Reglas:** +> - Este archivo es el eslabón más importante. Leerlo siempre antes de cualquier tarea. +> - Cada cambio significativo debe reflejarse aquí y en los archivos de `.agente/`. +> - Debe ser técnico, claro y suficiente para que cualquier agente arranque sin explicaciones previas. +> - **Cuando se diga "actualizar proyecto":** commit de cambios pendientes + actualizar `agents.md` y `.agente/proyecto_estructura.md`. + +--- + +## Antecedentes + +Aplicación Flutter de escritorio (Linux PC fija) para operadores de la **central de monitoreo** de seguridad electrónica. Es el **contrapunto de SENTINEL ONE** — donde SENTINEL ONE es la app del cliente final, esta app es la del operador que recibe y gestiona los eventos de todos los clientes. + +No comparte código con SENTINEL ONE pero sí comparte toda la infraestructura: +- Misma auth: WebControl → `apiKey` + `db_tenant` +- Misma API: `API_CENTINEL_SECURITY` (`api.telcotronics.com`) +- Mismo stack de BD: SQLite offline-first con sqflite_common_ffi + +El operador tiene visión **multi-tenant**: ve todos los clientes a la vez. SENTINEL ONE tiene visión de un solo cliente. + +--- + +## Objetivo general + +Proveer a los operadores de la central una plataforma desktop para: + +1. Ver en tiempo real las alarmas de **todos los clientes** agrupadas por severidad y estado. +2. Recibir y atender solicitudes de pánico/soporte enviadas desde SENTINEL ONE. +3. Controlar dispositivos (puertas, sensores) de clientes vía API_CENTINEL_SECURITY. +4. Gestionar operadores en turno y asignaciones. +5. Generar reportes de incidentes por cliente, operador y período. + +--- + +## Stack técnico + +| Componente | Tecnología | +|---|---| +| Lenguaje | Dart 2.17.0-beta | +| Framework | Flutter 2.11.0 | +| UI | Material 2 · Dark Theme · Google Fonts (Manrope + Inter) | +| Layout | Sidebar izquierdo fijo 220px + área de contenido Expanded | +| BD local | SQLite v3 — sqflite + sqflite_common_ffi (Linux desktop) | +| Auth | WebControl 2 pasos: `/api/auth/empresas` → `/api/auth/login` | +| Plataforma principal | Linux desktop (PC fija en central de monitoreo) | +| Resolución objetivo | 1920×1080 mínimo | +| App ID | `net.siaxsystem.centralmonitoreo` | + +> ⚠️ Flutter 2.11 / Dart 2.17-beta: las APIs de Flutter 3.x NO EXISTEN en este proyecto. +> No usar `MaterialState`, `ColorScheme.fromSeed`, `NavigationDrawer`, ni ninguna API de Flutter 3+. +> Consultar `.agente/proyecto_errores.md` antes de usar cualquier API nueva. + +--- + +## Auth y conexión a servicios + +### Flujo de login (2 pasos) + +``` +Paso 1 — POST https://api.siax-system.net/api/auth/empresas + Body: { email, paswd } + Response: { success, usuario, empresas:[{dba, nombre, rol}], unica } + ↓ tomar empresas[0].dba + +Paso 2 — POST https://api.siax-system.net/api/auth/login + Body: { email, paswd, dba } + Response: { success, token, apiKey, db_tenant, usuario:{id,nombre,usuario,rol} } + ↓ guardar en SharedPreferences + +Todas las llamadas a API_CENTINEL_SECURITY: + └─► https://api.telcotronics.com/api/... + accept: application/json + x-api-key: {apiKey} + x-database: {db_tenant} +``` + +> ⚠️ El campo de contraseña en la API es **`paswd`** (sin 'or'), no `password` ni `contraseña`. +> ⚠️ El rate limit es 10 intentos por 15 minutos. No testear con curl repetidamente. + +### SharedPreferences keys +| Key | Valor | +|---|---| +| `webcontrol_token` | JWT de sesión | +| `centinel_api_key` | apiKey para Centinel | +| `centinel_tenant` | db_tenant (ej: `TELCOTRONICS`) | +| `operador_nombre` | Nombre del operador logueado | +| `operador_usuario` | Username del operador | + +--- + +## Layout de la aplicación + +``` +┌─────────────────────────────────────────────────┐ +│ HEADER: logo + operador en sesión + estado API │ +├──────────┬──────────────────────────────────────┤ +│ │ │ +│ SIDEBAR │ ÁREA DE CONTENIDO │ +│ 220px │ (IndexedStack) │ +│ │ │ +└──────────┴──────────────────────────────────────┘ +``` + +--- + +## Deploy — desplegar.sh + +```bash +# Compila, empaqueta y sube a siax-system.net +./desplegar.sh + +# Requiere SIAX_API_KEY en entorno (ya está en ~/.bashrc) +# Sube: build/central_monitoreo_linux_{version}.tar.gz +# Incluye: lib/recursos/logo_app.png como ícono +``` + +CLI Sync endpoint: `POST https://siax-system.net/api/upload_app.php` +Panel: `https://siax-system.net/app/software/index.php?tab=cli-sync` + +--- + +## Módulos del sistema + +### OperadorLoginPage +**Estado: ✅ Completo** +Login email + contraseña WebControl. Flujo 2 pasos vía `ApiAuthService`. +Logo: `lib/recursos/logo_app.png` (escudo radar neón). + +### ShellPage (layout principal) +**Estado: ✅ Completo** +Sidebar 220px custom + `IndexedStack`. Header con logo, nombre operador, indicador API conectada/sin conexión. + +### theme.dart +**Estado: ✅ Completo** +`AppColors`, `appHeadline()` (Manrope), `appLabel()` (Inter). Colores semánticos de alarma incluidos. + +### DB SQLite v1 + DAOs +**Estado: ✅ Completo** +7 tablas: `configuracion`, `sesiones_operador`, `cache_clientes`, `cache_alarmas`, `incidentes`, `operadores`, `sync_log`. +DAOs: `CacheAlarmasDao`, `CacheClientesDao`, `IncidentesDao`, `OperadoresDao`, `SesionesDao`, `ConfiguracionDao`, `SyncLogDao`. + +### ApiAuthService +**Estado: ✅ Completo** +Flujo 2 pasos: `getEmpresas()` + `login()`. Si una sola empresa (`unica:true`), auto-selecciona el `dba`. +Headers para Centinel: `getCentinelHeaders()`. + +### DashboardPage +**Estado: ✅ Completo** +Stat cards (clientes, alarmas activas, críticas, incidentes pendientes). +Feed alarmas activas + estado de clientes + últimos incidentes. Timer auto-refresh cada 30s. + +### MonitoreoPage +**Estado: 🟡 Pendiente — Prioridad ALTA** +Feed tiempo real de todas las alarmas. Vista tabla densa. +- Filtros: por cliente, severidad, tipo +- Acciones inline: responder, escalar, silenciar +- Polling cada N segundos configurable (o WebSocket futuro) +- Integración con `CentinelService` para traer alarmas reales + +### ClientesPage +**Estado: 🟡 Pendiente — Prioridad ALTA** +Lista de clientes con semáforo de estado (verde/amarillo/rojo). +Al seleccionar: panel de detalle con zonas, dispositivos e historial. +Requiere: `GET /api/clients` en Centinel → cachear en `cache_clientes`. + +### OperadoresPage +**Estado: 🔴 Pendiente** +CRUD de operadores de la central. Gestión de turnos (quién está activo). +Campos: nombre, iniciales, nivel, áreas asignadas, en_turno. + +### IncidentesPage +**Estado: 🔴 Pendiente** +Registro de incidentes: fecha, cliente, tipo, operador, resolución, notas. +Creados localmente al responder una alarma → sincronizar a Centinel. +Filtros por fecha, cliente, operador, estado (resuelto/pendiente). + +### DispositivosPage +**Estado: 🔴 Pendiente** +Lista de dispositivos Hikvision (`GET /api/devices`). +Estado online/offline, test de conexión, apertura remota de puertas. + +### ReportesPage +**Estado: 🔴 Pendiente** +Filtros: cliente, operador, período. +Métricas: alarmas atendidas, tiempo de respuesta promedio, incidentes por tipo. +Exportar a PDF (fase 2). + +### ConfiguracionPage +**Estado: 🔴 Pendiente** +- Intervalo de polling (default 30s) +- Notificaciones de sonido +- Limpiar caché BD +- Ver token/apiKey activos (debug) + +--- + +## Sincronizador con Centinel (pendiente) + +Servicio `lib/services/sincronizador.dart` — aún no implementado. + +```dart +// Ciclo de sync cada poll_interval_seg: +// 1. GET /api/clients → cache_clientes +// 2. GET /api/alarms/active → cache_alarmas +// 3. POST /api/incidents → push incidentes no sincronizados +// 4. Registrar en sync_log +``` + +--- + +## Objetivos futuros (fase 2) + +| Objetivo | Descripción | +|---|---| +| **Sincronizador Centinel** | Implementar `sincronizador.dart` con polling real a `api.telcotronics.com` | +| **MonitoreoPage completa** | Tabla densa de alarmas con filtros y acciones inline | +| **ClientesPage completa** | Lista + panel de detalle por cliente | +| **IncidentesPage** | CRUD local + push a Centinel | +| **OperadoresPage** | CRUD + gestión de turnos | +| **DispositivosPage** | Control remoto Hikvision | +| **ReportesPage** | Métricas + exportar PDF | +| **ConfiguracionPage** | Ajustes de sistema | +| **Notificaciones de pánico** | Badge + sonido cuando llega un evento crítico | +| **WebSocket** | Reemplazar polling por conexión en tiempo real | +| **Multi-empresa** | Selector de empresa en login cuando `unica: false` | +| **Exportar PDF** | Reportes exportables desde ReportesPage | +| **Ícono en barra de tareas Linux** | Configurar `.desktop` launcher con logo_app.png | +| **Auto-update** | Detectar nueva versión vía WebControl y auto-actualizar el bundle | +| **Monitoreo de cámaras** | Visor de streams de cámaras Hikvision por cliente — RTSP/HLS embebido en la app. Vista grilla multi-cámara, pantalla completa por cámara, grabación de clip al responder una alarma | +| **Mapa de localización** | Mapa interactivo con ubicación en tiempo real de agentes de campo y dispositivos SENTINEL ONE. Vista de zonas activas, radio de cobertura, trayectoria del agente, estado del sentinel más cercano a una alarma | + +--- + +## BD local — esquema v1 + +| Tabla | Propósito | +|---|---| +| `configuracion` | Clave-valor: `poll_interval_seg`, `sonido_alerta` | +| `sesiones_operador` | Login/logout del operador local | +| `cache_alarmas` | Alarmas traídas de Centinel | +| `cache_clientes` | Clientes traídos de Centinel | +| `incidentes` | Incidentes gestionados (creados localmente) | +| `operadores` | Operadores de la central | +| `sync_log` | Log de cada ciclo de sincronización | + +--- + +## Infraestructura (referencia rápida) + +| Parámetro | Valor | +|---|---| +| Código local | `siax-amd (192.168.10.100)` — `/home/pablinux/Projects/flutter/Central_monitoreo` | +| Plataforma | Linux desktop (Ubuntu 24.04) | +| App ID | `net.siaxsystem.centralmonitoreo` | +| Auth paso 1 | `POST https://api.siax-system.net/api/auth/empresas` | +| Auth paso 2 | `POST https://api.siax-system.net/api/auth/login` | +| API operaciones | `https://api.telcotronics.com` — `x-api-key` + `x-database` | +| BD local | `~/.local/share/central_monitoreo/central_monitoreo.db` | +| Deploy | `./desplegar.sh` → `siax-system.net` | + +--- + +## Relación con SENTINEL ONE + +| Aspecto | SENTINEL ONE | Centro de Monitoreo | +|---|---|---| +| Usuario | Cliente final | Operador de la central | +| Visibilidad | Sus propias alarmas | Todos los clientes | +| Layout | Bottom nav (mobile) | Sidebar 220px (desktop) | +| Auth | WebControl 2 pasos | WebControl 2 pasos (misma) | +| API | API_CENTINEL_SECURITY | API_CENTINEL_SECURITY (misma) | +| Pánico | Activa | Recibe y atiende | +| Código | `/Projects/flutter/seguridad_electronica` | `/Projects/flutter/Central_monitoreo` | + +--- + +## Para arrancar en local + +```bash +sudo apt install libsqlite3-dev +cd /home/pablinux/Projects/flutter/Central_monitoreo +flutter pub get +flutter run -d linux +# Login: admin@telcotronics.com +``` + +--- + +## Índice de archivos actual + +``` +Central_monitoreo/ +├── agents.md ← LEER PRIMERO +├── desplegar.sh ← Deploy a siax-system.net +├── pubspec.yaml +├── lib/ +│ ├── main.dart ← OperadorLoginPage +│ ├── shell_page.dart ← Layout sidebar + IndexedStack +│ ├── theme.dart ← AppColors, appHeadline(), appLabel() +│ ├── recursos/ +│ │ ├── logo_app.png ← Ícono app (escudo radar neón 512px) +│ │ └── logo_app.svg ← Fuente SVG del ícono +│ ├── db/ +│ │ ├── database_helper.dart +│ │ └── dao/ ← 7 DAOs implementados +│ ├── pages/ +│ │ ├── dashboard_page.dart ← ✅ Completo +│ │ ├── monitoreo_page.dart ← 🟡 Estructura inicial +│ │ ├── clientes_page.dart ← 🔴 Placeholder +│ │ ├── operadores_page.dart ← 🔴 Placeholder +│ │ ├── incidentes_page.dart ← 🔴 Placeholder +│ │ ├── dispositivos_page.dart ← 🔴 Placeholder +│ │ ├── reportes_page.dart ← 🔴 Placeholder +│ │ └── configuracion_page.dart ← 🔴 Placeholder +│ └── services/ +│ ├── api_auth_service.dart ← ✅ Flujo 2 pasos completo +│ ├── sincronizador.dart ← 🔴 Pendiente implementar +│ └── centinel_service.dart ← 🔴 Pendiente implementar +``` diff --git a/desplegar.sh b/desplegar.sh new file mode 100755 index 0000000..a36cf3a --- /dev/null +++ b/desplegar.sh @@ -0,0 +1,109 @@ +#!/bin/bash + +# ───────────────────────────────────────────────────────────── +# CENTRO DE MONITOREO — Deploy a producción (siax-system.net) +# Compila el bundle Linux, lo empaqueta y lo sube al registro +# WebControlSigma para que los clientes puedan auto-actualizarse. +# ───────────────────────────────────────────────────────────── + +CYAN='\033[0;36m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +RED='\033[0;31m' +BOLD='\033[1m' +RESET='\033[0m' + +ENDPOINT="https://siax-system.net/api/upload_app.php" +APP_NOMBRE="Central Monitoreo" +APP_VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //' | sed 's/+.*//' | tr -d ' ') + +LINUX_BUNDLE="build/linux/x64/release/bundle" +LINUX_TAR="build/central_monitoreo_linux_${APP_VERSION}.tar.gz" + +echo "" +echo -e "${CYAN}${BOLD}╔══════════════════════════════════════════╗${RESET}" +echo -e "${CYAN}${BOLD}║ CENTRO DE MONITOREO — Deploy Production ║${RESET}" +echo -e "${CYAN}${BOLD}╚══════════════════════════════════════════╝${RESET}" +echo -e " App : ${BOLD}${APP_NOMBRE}${RESET}" +echo -e " Versión : ${BOLD}${APP_VERSION}${RESET}" +echo -e " Destino : ${CYAN}siax-system.net${RESET}" +echo "" + +# ── Compilar ────────────────────────────────────────────────── +echo -e "${YELLOW}▶ Compilando release Linux...${RESET}" +flutter build linux --release +if [ $? -ne 0 ]; then + echo -e "${RED}✗ Error en la compilación. Abortando.${RESET}" + exit 1 +fi +echo -e "${GREEN}✓ Compilación exitosa${RESET}" +echo "" + +# ── Empaquetar ──────────────────────────────────────────────── +echo -e "${YELLOW}▶ Empaquetando bundle → $LINUX_TAR${RESET}" +rm -f "$LINUX_TAR" +tar -czf "$LINUX_TAR" -C "build/linux/x64/release" bundle +if [ $? -ne 0 ]; then + echo -e "${RED}✗ Error al empaquetar.${RESET}" + exit 1 +fi +echo -e "${GREEN}✓ Paquete: $(du -sh "$LINUX_TAR" | cut -f1)${RESET}" +echo "" + +# ── API Key ─────────────────────────────────────────────────── +API_KEY="${SIAX_API_KEY}" +if [ -z "$API_KEY" ]; then + read -p "API Key de WebControlSigma: " API_KEY +fi +if [ -z "$API_KEY" ]; then + echo -e "${RED}✗ API Key requerida. Cancela.${RESET}" + exit 1 +fi + +# ── Changelog ───────────────────────────────────────────────── +read -p "Changelog (opcional, Enter para omitir): " CHANGELOG +FECHA_HOY=$(date +%Y-%m-%d) +echo "" + +# ── Subir ───────────────────────────────────────────────────── +echo -e "${YELLOW}▶ Subiendo LINUX → siax-system.net...${RESET}" + +ICO_PATH="lib/recursos/logo_app.png" + +local_args=( + curl -s -w "\n%{http_code}" + -X POST "$ENDPOINT" + -H "x-api-key: $API_KEY" + -F "nombre=$APP_NOMBRE" + -F "version=$APP_VERSION" + -F "plataforma=LINUX" + -F "fecha_release=$FECHA_HOY" + -F "archivo=@$LINUX_TAR" +) +[ -n "$CHANGELOG" ] && local_args+=(-F "changelog=$CHANGELOG") +[ -f "$ICO_PATH" ] && local_args+=(-F "archivo_ico=@$ICO_PATH") + +resp=$("${local_args[@]}" 2>&1) +http_code=$(echo "$resp" | tail -n 1) +body=$(echo "$resp" | head -n -1) + +if [ "$http_code" = "200" ]; then + db_action=$(echo "$body" | grep -o '"db_action":"[^"]*"' | cut -d'"' -f4) + url_descarga=$(echo "$body" | grep -o '"url_descarga":"[^"]*"' | cut -d'"' -f4) + archivo_md5=$(echo "$body" | grep -o '"archivo_md5":"[^"]*"' | cut -d'"' -f4) + + echo -e "${GREEN}${BOLD}✓ Publicado exitosamente${RESET}" + echo -e " Acción : ${BOLD}${db_action}${RESET}" + [ -n "$url_descarga" ] && echo -e " URL : ${CYAN}${url_descarga}${RESET}" + [ -n "$archivo_md5" ] && echo -e " MD5 : ${archivo_md5}" +else + echo -e "${RED}✗ Error ${http_code} al subir${RESET}" + echo "$body" + exit 1 +fi + +echo "" +echo -e "${CYAN}${BOLD}══════════════════════════════════════════${RESET}" +echo -e "${GREEN}${BOLD} Deploy finalizado — Central Monitoreo${RESET}" +echo -e "${CYAN}${BOLD}══════════════════════════════════════════${RESET}" +echo "" diff --git a/lib/db/dao/cache_alarmas_dao.dart b/lib/db/dao/cache_alarmas_dao.dart new file mode 100644 index 0000000..3b1b702 --- /dev/null +++ b/lib/db/dao/cache_alarmas_dao.dart @@ -0,0 +1,63 @@ +import 'package:sqflite/sqflite.dart'; +import '../database_helper.dart'; + +class CacheAlarmasDao { + final _db = DatabaseHelper.instance; + + Future>> getActivas({int? clienteId}) async { + final db = await _db.db; + if (clienteId != null) { + return db.query( + 'cache_alarmas', + where: "estado = 'activa' AND cliente_id = ?", + whereArgs: [clienteId], + orderBy: 'severidad DESC, timestamp DESC', + ); + } + return db.query( + 'cache_alarmas', + where: "estado = 'activa'", + orderBy: 'severidad DESC, timestamp DESC', + ); + } + + Future>> getTodas({int limit = 100}) async { + final db = await _db.db; + return db.query('cache_alarmas', orderBy: 'severidad DESC, timestamp DESC', limit: limit); + } + + Future contarActivas() async { + final db = await _db.db; + final result = await db.rawQuery("SELECT COUNT(*) as c FROM cache_alarmas WHERE estado = 'activa'"); + return result.first['c'] as int; + } + + Future contarCriticas() async { + final db = await _db.db; + final result = await db.rawQuery("SELECT COUNT(*) as c FROM cache_alarmas WHERE estado = 'activa' AND severidad >= 4"); + return result.first['c'] as int; + } + + Future reemplazarTodas(List> alarmas) async { + final db = await _db.db; + await db.delete('cache_alarmas'); + for (final a in alarmas) { + await db.insert('cache_alarmas', a, conflictAlgorithm: ConflictAlgorithm.replace); + } + } + + Future actualizarEstado(int id, String nuevoEstado) async { + final db = await _db.db; + return db.update( + 'cache_alarmas', + {'estado': nuevoEstado}, + where: 'id = ?', + whereArgs: [id], + ); + } + + Future limpiar() async { + final db = await _db.db; + await db.delete('cache_alarmas'); + } +} diff --git a/lib/db/dao/cache_clientes_dao.dart b/lib/db/dao/cache_clientes_dao.dart new file mode 100644 index 0000000..f469f43 --- /dev/null +++ b/lib/db/dao/cache_clientes_dao.dart @@ -0,0 +1,31 @@ +import 'package:sqflite/sqflite.dart'; +import '../database_helper.dart'; + +class CacheClientesDao { + final _db = DatabaseHelper.instance; + + Future>> getTodos() async { + final db = await _db.db; + return db.query('cache_clientes', orderBy: 'alarmas_criticas DESC, nombre ASC'); + } + + Future?> getById(int id) async { + final db = await _db.db; + final rows = await db.query('cache_clientes', where: 'id = ?', whereArgs: [id]); + return rows.isEmpty ? null : rows.first; + } + + Future contarActivos() async { + final db = await _db.db; + final result = await db.rawQuery('SELECT COUNT(*) as c FROM cache_clientes'); + return result.first['c'] as int; + } + + Future reemplazarTodos(List> clientes) async { + final db = await _db.db; + await db.delete('cache_clientes'); + for (final c in clientes) { + await db.insert('cache_clientes', c, conflictAlgorithm: ConflictAlgorithm.replace); + } + } +} diff --git a/lib/db/dao/configuracion_dao.dart b/lib/db/dao/configuracion_dao.dart new file mode 100644 index 0000000..81624cb --- /dev/null +++ b/lib/db/dao/configuracion_dao.dart @@ -0,0 +1,21 @@ +import 'package:sqflite/sqflite.dart'; +import '../database_helper.dart'; + +class ConfiguracionDao { + final _db = DatabaseHelper.instance; + + Future get(String clave) async { + final db = await _db.db; + final rows = await db.query('configuracion', where: 'clave = ?', whereArgs: [clave]); + return rows.isEmpty ? null : rows.first['valor'] as String?; + } + + Future set(String clave, String valor) async { + final db = await _db.db; + await db.insert( + 'configuracion', + {'clave': clave, 'valor': valor}, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } +} diff --git a/lib/db/dao/incidentes_dao.dart b/lib/db/dao/incidentes_dao.dart new file mode 100644 index 0000000..efb01d9 --- /dev/null +++ b/lib/db/dao/incidentes_dao.dart @@ -0,0 +1,47 @@ +import '../database_helper.dart'; + +class IncidentesDao { + final _db = DatabaseHelper.instance; + + Future registrar({ + int? alarmaId, + int? clienteId, + String? clienteNombre, + required String tipo, + required String operador, + String? notas, + }) async { + final db = await _db.db; + return db.insert('incidentes', { + 'alarma_id': alarmaId, + 'cliente_id': clienteId, + 'cliente_nombre': clienteNombre, + 'tipo': tipo, + 'operador': operador, + 'notas': notas, + 'timestamp': DateTime.now().toIso8601String(), + 'resuelto': 0, + 'sincronizado': 0, + }); + } + + Future>> getRecientes({int limit = 50}) async { + final db = await _db.db; + return db.query('incidentes', orderBy: 'timestamp DESC', limit: limit); + } + + Future>> getPendientes() async { + final db = await _db.db; + return db.query('incidentes', where: 'sincronizado = 0'); + } + + Future marcarResuelto(int id, String notas) async { + final db = await _db.db; + return db.update( + 'incidentes', + {'resuelto': 1, 'notas': notas, 'sincronizado': 0}, + where: 'id = ?', + whereArgs: [id], + ); + } +} diff --git a/lib/db/dao/operadores_dao.dart b/lib/db/dao/operadores_dao.dart new file mode 100644 index 0000000..5f13427 --- /dev/null +++ b/lib/db/dao/operadores_dao.dart @@ -0,0 +1,48 @@ +import '../database_helper.dart'; + +class OperadoresDao { + final _db = DatabaseHelper.instance; + + Future>> getTodos() async { + final db = await _db.db; + return db.query('operadores', where: 'activo = 1', orderBy: 'nombre ASC'); + } + + Future>> getEnTurno() async { + final db = await _db.db; + return db.query('operadores', where: 'activo = 1 AND en_turno = 1'); + } + + Future insertar(String nombre, int nivel) async { + final db = await _db.db; + final iniciales = _calcularIniciales(nombre); + return db.insert('operadores', { + 'nombre': nombre, + 'iniciales': iniciales, + 'nivel': nivel, + 'activo': 1, + 'en_turno': 0, + }); + } + + Future setEnTurno(int id, bool valor) async { + final db = await _db.db; + return db.update( + 'operadores', + {'en_turno': valor ? 1 : 0}, + where: 'id = ?', + whereArgs: [id], + ); + } + + Future desactivar(int id) async { + final db = await _db.db; + return db.update('operadores', {'activo': 0}, where: 'id = ?', whereArgs: [id]); + } + + String _calcularIniciales(String nombre) { + final p = nombre.trim().split(RegExp(r'\s+')); + if (p.length >= 2) return '${p.first[0]}${p.last[0]}'.toUpperCase(); + return nombre.isNotEmpty ? nombre[0].toUpperCase() : '?'; + } +} diff --git a/lib/db/dao/sesiones_dao.dart b/lib/db/dao/sesiones_dao.dart new file mode 100644 index 0000000..41435c5 --- /dev/null +++ b/lib/db/dao/sesiones_dao.dart @@ -0,0 +1,36 @@ +import '../database_helper.dart'; + +class SesionesDao { + final _db = DatabaseHelper.instance; + + Future iniciarSesion(String nombre, String usuario) async { + final db = await _db.db; + await db.update('sesiones_operador', {'activa': 0}); + return db.insert('sesiones_operador', { + 'nombre': nombre, + 'usuario': usuario, + 'inicio': DateTime.now().toIso8601String(), + 'activa': 1, + }); + } + + Future cerrarSesion() async { + final db = await _db.db; + await db.update( + 'sesiones_operador', + {'fin': DateTime.now().toIso8601String(), 'activa': 0}, + where: 'activa = 1', + ); + } + + Future?> getSesionActiva() async { + final db = await _db.db; + final rows = await db.query('sesiones_operador', where: 'activa = 1', limit: 1); + return rows.isEmpty ? null : rows.first; + } + + Future>> getRecientes({int limit = 10}) async { + final db = await _db.db; + return db.query('sesiones_operador', orderBy: 'inicio DESC', limit: limit); + } +} diff --git a/lib/db/dao/sync_log_dao.dart b/lib/db/dao/sync_log_dao.dart new file mode 100644 index 0000000..b412273 --- /dev/null +++ b/lib/db/dao/sync_log_dao.dart @@ -0,0 +1,24 @@ +import '../database_helper.dart'; + +class SyncLogDao { + final _db = DatabaseHelper.instance; + + Future registrar({ + required String tipo, + required String estado, + String? detalle, + }) async { + final db = await _db.db; + await db.insert('sync_log', { + 'tipo': tipo, + 'estado': estado, + 'detalle': detalle, + 'timestamp': DateTime.now().toIso8601String(), + }); + } + + Future>> getRecientes({int limit = 20}) async { + final db = await _db.db; + return db.query('sync_log', orderBy: 'timestamp DESC', limit: limit); + } +} diff --git a/lib/db/database_helper.dart b/lib/db/database_helper.dart new file mode 100644 index 0000000..f65f10a --- /dev/null +++ b/lib/db/database_helper.dart @@ -0,0 +1,126 @@ +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +class DatabaseHelper { + static const _dbName = 'central_monitoreo.db'; + static const _dbVersion = 1; + + DatabaseHelper._(); + static final DatabaseHelper instance = DatabaseHelper._(); + + Database? _db; + + Future get db async { + _db ??= await _initDb(); + return _db!; + } + + Future _initDb() async { + if (!kIsWeb && (Platform.isLinux || Platform.isWindows)) { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + } + + final path = await _dbPath(); + return openDatabase(path, version: _dbVersion, onCreate: _onCreate); + } + + Future _dbPath() async { + if (!kIsWeb && Platform.isLinux) { + final home = Platform.environment['HOME'] ?? ''; + final dir = Directory('$home/.local/share/central_monitoreo'); + if (!dir.existsSync()) dir.createSync(recursive: true); + return join(dir.path, _dbName); + } + final base = await getDatabasesPath(); + return join(base, _dbName); + } + + Future _onCreate(Database db, int version) async { + await db.execute(''' + CREATE TABLE configuracion ( + clave TEXT PRIMARY KEY, + valor TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE sesiones_operador ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + nombre TEXT NOT NULL, + usuario TEXT NOT NULL, + inicio TEXT NOT NULL, + fin TEXT, + activa INTEGER NOT NULL DEFAULT 1 + ) + '''); + + await db.execute(''' + CREATE TABLE cache_clientes ( + id INTEGER PRIMARY KEY, + nombre TEXT NOT NULL, + estado TEXT NOT NULL DEFAULT 'normal', + alarmas_activas INTEGER NOT NULL DEFAULT 0, + alarmas_criticas INTEGER NOT NULL DEFAULT 0, + ultima_actualizacion TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE cache_alarmas ( + id INTEGER PRIMARY KEY, + cliente_id INTEGER NOT NULL, + cliente_nombre TEXT, + tipo TEXT NOT NULL, + severidad INTEGER NOT NULL DEFAULT 1, + estado TEXT NOT NULL DEFAULT 'activa', + zona_nombre TEXT, + timestamp TEXT NOT NULL, + notas TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE incidentes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + alarma_id INTEGER, + cliente_id INTEGER, + cliente_nombre TEXT, + tipo TEXT NOT NULL, + operador TEXT NOT NULL, + notas TEXT, + timestamp TEXT NOT NULL, + resuelto INTEGER NOT NULL DEFAULT 0, + sincronizado INTEGER NOT NULL DEFAULT 0 + ) + '''); + + await db.execute(''' + CREATE TABLE operadores ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + nombre TEXT NOT NULL, + iniciales TEXT NOT NULL, + nivel INTEGER NOT NULL DEFAULT 1, + activo INTEGER NOT NULL DEFAULT 1, + en_turno INTEGER NOT NULL DEFAULT 0 + ) + '''); + + await db.execute(''' + CREATE TABLE sync_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + tipo TEXT NOT NULL, + estado TEXT NOT NULL, + detalle TEXT, + timestamp TEXT NOT NULL + ) + '''); + + // Configuración por defecto + await db.insert('configuracion', {'clave': 'poll_interval_seg', 'valor': '30'}); + await db.insert('configuracion', {'clave': 'sonido_alerta', 'valor': '1'}); + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..5975674 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,266 @@ +import 'package:flutter/material.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; +import 'theme.dart'; +import 'services/api_auth_service.dart'; +import 'shell_page.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + + final autenticado = await ApiAuthService.instance.isAuthenticated(); + runApp(CentroMonitoreoApp(inicioAutenticado: autenticado)); +} + +class CentroMonitoreoApp extends StatelessWidget { + final bool inicioAutenticado; + const CentroMonitoreoApp({Key? key, required this.inicioAutenticado}) + : super(key: key); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Centro de Monitoreo', + debugShowCheckedModeBanner: false, + theme: ThemeData( + brightness: Brightness.dark, + scaffoldBackgroundColor: AppColors.surfaceLowest, + canvasColor: AppColors.surfaceLow, + cardColor: AppColors.surfaceHigh, + dialogBackgroundColor: AppColors.surfaceHigh, + dividerColor: AppColors.outlineVariant, + colorScheme: const ColorScheme.dark( + primary: AppColors.primary, + onPrimary: AppColors.primaryContainer, + secondary: AppColors.secondary, + surface: AppColors.surface, + onSurface: AppColors.onSurface, + error: AppColors.error, + onError: AppColors.onError, + ), + ), + initialRoute: inicioAutenticado ? '/shell' : '/login', + routes: { + '/login': (_) => const OperadorLoginPage(), + '/shell': (_) => const ShellPage(), + }, + ); + } +} + +// ── Login Page ─────────────────────────────────────────────────────────────── + +class OperadorLoginPage extends StatefulWidget { + const OperadorLoginPage({Key? key}) : super(key: key); + + @override + State createState() => _OperadorLoginPageState(); +} + +class _OperadorLoginPageState extends State { + final _formKey = GlobalKey(); + final _ctrlUser = TextEditingController(); + final _ctrlPass = TextEditingController(); + bool _cargando = false; + bool _verPass = false; + String? _error; + + @override + void dispose() { + _ctrlUser.dispose(); + _ctrlPass.dispose(); + super.dispose(); + } + + Future _login() async { + if (!_formKey.currentState!.validate()) return; + setState(() { _cargando = true; _error = null; }); + + final ok = await ApiAuthService.instance.login( + _ctrlUser.text.trim(), + _ctrlPass.text, + ); + + if (!mounted) return; + if (ok) { + Navigator.of(context).pushReplacementNamed('/shell'); + } else { + setState(() { + _cargando = false; + _error = 'Credenciales incorrectas o sin conexión con WebControl.'; + }); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.surfaceLowest, + body: Center( + child: SingleChildScrollView( + primary: false, + padding: const EdgeInsets.all(32), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 400), + child: Column(children: [ + // Logo + Image.asset( + 'lib/recursos/logo_app.png', + width: 96, + height: 96, + ), + const SizedBox(height: 20), + Text('CENTRO DE MONITOREO', + style: appHeadline( + size: 18, + weight: FontWeight.w800, + color: AppColors.primary, + spacing: 2.0)), + const SizedBox(height: 6), + Text('Acceso para operadores autorizados', + style: appLabel(size: 12, color: AppColors.outline)), + const SizedBox(height: 40), + + // Card de login + Container( + padding: const EdgeInsets.all(32), + decoration: BoxDecoration( + color: AppColors.surfaceLow, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: AppColors.outlineVariant, width: 1), + ), + child: Form( + key: _formKey, + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Text('Iniciar sesión', + style: appHeadline(size: 16, weight: FontWeight.w700)), + const SizedBox(height: 24), + + // Usuario + _campo( + controller: _ctrlUser, + label: 'Usuario', + icono: Icons.person_outline, + validator: (v) => + (v == null || v.trim().isEmpty) ? 'Ingresa tu usuario' : null, + ), + const SizedBox(height: 16), + + // Contraseña + _campo( + controller: _ctrlPass, + label: 'Contraseña', + icono: Icons.lock_outline, + obscure: !_verPass, + sufijo: IconButton( + icon: Icon( + _verPass ? Icons.visibility_off : Icons.visibility, + color: AppColors.outline, + size: 18, + ), + onPressed: () => setState(() => _verPass = !_verPass), + ), + validator: (v) => + (v == null || v.isEmpty) ? 'Ingresa tu contraseña' : null, + onSubmit: (_) => _login(), + ), + const SizedBox(height: 12), + + // Error + if (_error != null) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Text(_error!, + style: appLabel(size: 12, color: AppColors.error)), + ), + + // Botón + SizedBox( + height: 48, + child: ElevatedButton( + onPressed: _cargando ? null : _login, + style: ElevatedButton.styleFrom( + primary: AppColors.primary, + onPrimary: AppColors.primaryContainer, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + child: _cargando + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: AppColors.primaryContainer), + ) + : Text('INGRESAR', + style: appHeadline( + size: 13, + weight: FontWeight.w800, + color: AppColors.primaryContainer, + spacing: 1.2)), + ), + ), + ]), + ), + ), + + const SizedBox(height: 32), + Text('Telcotronics · WebControl', + style: appLabel(size: 11, color: AppColors.outlineVariant)), + ]), + ), + ), + ), + ); + } + + Widget _campo({ + required TextEditingController controller, + required String label, + required IconData icono, + bool obscure = false, + Widget? sufijo, + String? Function(String?)? validator, + void Function(String)? onSubmit, + }) => + TextFormField( + controller: controller, + obscureText: obscure, + style: appLabel(size: 13, color: AppColors.onSurface), + onFieldSubmitted: onSubmit, + decoration: InputDecoration( + labelText: label, + labelStyle: appLabel(size: 12, color: AppColors.outline), + prefixIcon: Icon(icono, color: AppColors.outline, size: 18), + suffixIcon: sufijo, + filled: true, + fillColor: AppColors.surfaceHigh, + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: AppColors.outlineVariant), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: AppColors.outlineVariant), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: AppColors.primary, width: 1.5), + ), + errorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: AppColors.error), + ), + focusedErrorBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: AppColors.error, width: 1.5), + ), + ), + validator: validator, + ); +} diff --git a/lib/pages/clientes_page.dart b/lib/pages/clientes_page.dart new file mode 100644 index 0000000..c4a0a26 --- /dev/null +++ b/lib/pages/clientes_page.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; +import '../theme.dart'; + +class ClientesPage extends StatelessWidget { + const ClientesPage({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + primary: false, + padding: const EdgeInsets.all(32), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('Clientes', style: appHeadline(size: 28, weight: FontWeight.w800)), + const SizedBox(height: 8), + Text('Estado de todos los clientes', style: appLabel(size: 14)), + ]), + ); + } +} diff --git a/lib/pages/configuracion_page.dart b/lib/pages/configuracion_page.dart new file mode 100644 index 0000000..3039a4a --- /dev/null +++ b/lib/pages/configuracion_page.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; +import '../theme.dart'; + +class ConfiguracionPage extends StatelessWidget { + const ConfiguracionPage({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + primary: false, + padding: const EdgeInsets.all(32), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('Configuración', style: appHeadline(size: 28, weight: FontWeight.w800)), + const SizedBox(height: 8), + Text('Parámetros del sistema', style: appLabel(size: 14)), + ]), + ); + } +} diff --git a/lib/pages/dashboard_page.dart b/lib/pages/dashboard_page.dart new file mode 100644 index 0000000..381cb0f --- /dev/null +++ b/lib/pages/dashboard_page.dart @@ -0,0 +1,506 @@ +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'; + +class DashboardPage extends StatefulWidget { + const DashboardPage({Key? key}) : super(key: key); + + @override + State createState() => _DashboardPageState(); +} + +class _DashboardPageState extends State { + final _alarmasDao = CacheAlarmasDao(); + final _clientesDao = CacheClientesDao(); + final _incidentesDao = IncidentesDao(); + + List> _alarmas = []; + List> _clientes = []; + List> _incidentes = []; + + int _totalClientes = 0; + int _totalActivas = 0; + int _totalCriticas = 0; + int _totalPendientes = 0; + + bool _cargando = true; + DateTime? _ultimaActualizacion; + Timer? _timer; + + @override + void initState() { + super.initState(); + _cargar(); + _timer = Timer.periodic(const Duration(seconds: 30), (_) => _cargar()); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + Future _cargar() async { + if (!mounted) return; + setState(() => _cargando = true); + + final results = await Future.wait([ + _clientesDao.getTodos(), + _alarmasDao.getActivas(), + _incidentesDao.getRecientes(limit: 8), + _incidentesDao.getPendientes(), + _alarmasDao.contarActivas(), + _alarmasDao.contarCriticas(), + _clientesDao.contarActivos(), + ]); + + if (!mounted) return; + setState(() { + _clientes = List>.from(results[0] as List); + _alarmas = List>.from(results[1] as List); + _incidentes = List>.from(results[2] as List); + _totalPendientes = (results[3] as List).length; + _totalActivas = results[4] as int; + _totalCriticas = results[5] as int; + _totalClientes = results[6] as int; + _cargando = false; + _ultimaActualizacion = DateTime.now(); + }); + } + + // ── 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 'hace ${diff.inMinutes} min'; + if (diff.inHours < 24) return 'hace ${diff.inHours} h'; + return 'hace ${diff.inDays} d'; + } + + String _horaCorta(DateTime dt) { + final h = dt.hour.toString().padLeft(2, '0'); + final m = dt.minute.toString().padLeft(2, '0'); + final s = dt.second.toString().padLeft(2, '0'); + return '$h:$m:$s'; + } + + Color _colorSeveridad(int sev) { + if (sev >= 4) return AppColors.alarmaActiva; + if (sev == 3) return AppColors.clienteAlerta; + return AppColors.alarmaSilenciada; + } + + String _labelSeveridad(int sev) { + if (sev >= 5) return 'MAX'; + if (sev == 4) return 'CRIT'; + if (sev == 3) return 'ALTA'; + if (sev == 2) return 'MED'; + return 'BAJA'; + } + + Color _colorEstadoCliente(String? estado) { + if (estado == 'critico') return AppColors.clienteCritico; + if (estado == 'alerta') return AppColors.clienteAlerta; + return AppColors.clienteOk; + } + + // ── Build ──────────────────────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + primary: false, + padding: const EdgeInsets.fromLTRB(28, 24, 28, 32), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + _headerRow(), + const SizedBox(height: 24), + _statCards(), + const SizedBox(height: 24), + IntrinsicHeight( + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Expanded(flex: 3, child: _alarmasSection()), + const SizedBox(width: 16), + Expanded(flex: 2, child: _clientesSection()), + ]), + ), + const SizedBox(height: 16), + _incidentesSection(), + ]), + ); + } + + // ── Header ─────────────────────────────────────────────────────────────────── + + Widget _headerRow() => Row(children: [ + Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('Dashboard', style: appHeadline(size: 22, weight: FontWeight.w800)), + const SizedBox(height: 2), + Text( + _ultimaActualizacion != null + ? 'Actualizado a las ${_horaCorta(_ultimaActualizacion!)}' + : 'Cargando…', + 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 ahora', + icon: const Icon(Icons.refresh, color: AppColors.outline, size: 20), + onPressed: _cargar, + ), + ]); + + // ── Stat cards ─────────────────────────────────────────────────────────────── + + Widget _statCards() => Row(children: [ + Expanded(child: _statCard( + icono: Icons.business, + color: AppColors.primary, + valor: _totalClientes, + label: 'Clientes activos', + )), + const SizedBox(width: 12), + Expanded(child: _statCard( + icono: Icons.notifications_active, + color: AppColors.clienteAlerta, + valor: _totalActivas, + label: 'Alarmas activas', + )), + const SizedBox(width: 12), + Expanded(child: _statCard( + icono: Icons.warning_amber_rounded, + color: AppColors.alarmaActiva, + valor: _totalCriticas, + label: 'Críticas (sev ≥4)', + highlight: _totalCriticas > 0, + )), + const SizedBox(width: 12), + Expanded(child: _statCard( + icono: Icons.assignment_late_outlined, + color: AppColors.secondary, + valor: _totalPendientes, + label: 'Incidentes pend.', + )), + ]); + + Widget _statCard({ + required IconData icono, + required Color color, + required int valor, + required String label, + bool highlight = false, + }) => + Container( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18), + decoration: BoxDecoration( + color: highlight ? color.withOpacity(0.12) : AppColors.surfaceLow, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: highlight ? color.withOpacity(0.4) : AppColors.outlineVariant, + ), + ), + child: Row(children: [ + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: color.withOpacity(0.15), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(icono, color: color, size: 20), + ), + const SizedBox(width: 14), + Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text( + '$valor', + style: appHeadline( + size: 26, weight: FontWeight.w800, color: highlight ? color : AppColors.onSurface), + ), + Text(label, style: appLabel(size: 11, color: AppColors.outline)), + ]), + ]), + ); + + // ── Alarmas activas ────────────────────────────────────────────────────────── + + Widget _alarmasSection() => _card( + title: 'Alarmas activas', + icono: Icons.notifications_active_outlined, + badge: _totalActivas > 0 ? '$_totalActivas' : null, + badgeColor: _totalCriticas > 0 ? AppColors.alarmaActiva : AppColors.clienteAlerta, + child: _alarmas.isEmpty + ? _emptyState('Sin alarmas activas', Icons.notifications_none) + : Column( + children: _alarmas.take(12).map(_alarmaRow).toList(), + ), + ); + + Widget _alarmaRow(Map a) { + final sev = (a['severidad'] as int?) ?? 1; + final color = _colorSeveridad(sev); + final label = _labelSeveridad(sev); + return Padding( + padding: const EdgeInsets.symmetric(vertical: 5), + child: Row(children: [ + // Badge severidad + Container( + width: 42, + padding: const EdgeInsets.symmetric(vertical: 3), + decoration: BoxDecoration( + color: color.withOpacity(0.15), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: color.withOpacity(0.3)), + ), + child: Center( + child: Text(label, style: appLabel(size: 10, weight: FontWeight.bold, color: color)), + ), + ), + const SizedBox(width: 10), + // Contenido + Expanded( + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text( + a['tipo'] as String? ?? '—', + style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + Row(children: [ + if (a['cliente_nombre'] != null) + Text( + a['cliente_nombre'] as String, + style: appLabel(size: 11, color: AppColors.primary), + ), + if (a['zona_nombre'] != null) ...[ + Text(' · ', style: appLabel(size: 11, color: AppColors.outline)), + Text( + a['zona_nombre'] as String, + style: appLabel(size: 11, color: AppColors.onSurfaceVariant), + ), + ], + ]), + ]), + ), + const SizedBox(width: 8), + Text( + _timeAgo(a['timestamp'] as String?), + style: appLabel(size: 11, color: AppColors.outline), + ), + ]), + ); + } + + // ── Clientes ───────────────────────────────────────────────────────────────── + + Widget _clientesSection() => _card( + title: 'Estado de clientes', + icono: Icons.business_outlined, + badge: _totalClientes > 0 ? '$_totalClientes' : null, + badgeColor: AppColors.primary, + child: _clientes.isEmpty + ? _emptyState('Sin clientes en caché', Icons.business_outlined) + : Column( + children: _clientes.take(10).map(_clienteRow).toList(), + ), + ); + + Widget _clienteRow(Map c) { + final estado = c['estado'] as String? ?? 'normal'; + final color = _colorEstadoCliente(estado); + final criticas = (c['alarmas_criticas'] as int?) ?? 0; + final activas = (c['alarmas_activas'] as int?) ?? 0; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 5), + child: Row(children: [ + Container( + width: 8, + height: 8, + decoration: BoxDecoration(shape: BoxShape.circle, color: color), + ), + const SizedBox(width: 10), + Expanded( + child: Text( + c['nombre'] as String? ?? '—', + style: appLabel( + size: 12, + weight: FontWeight.w500, + color: criticas > 0 ? AppColors.onSurface : AppColors.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 8), + if (criticas > 0) + _pillCount('$criticas', AppColors.alarmaActiva) + else if (activas > 0) + _pillCount('$activas', AppColors.clienteAlerta) + else + Text('OK', style: appLabel(size: 11, color: AppColors.clienteOk)), + ]), + ); + } + + Widget _pillCount(String text, Color color) => Container( + padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2), + decoration: BoxDecoration( + color: color.withOpacity(0.15), + borderRadius: BorderRadius.circular(20), + ), + child: Text(text, style: appLabel(size: 11, weight: FontWeight.bold, color: color)), + ); + + // ── Incidentes recientes ───────────────────────────────────────────────────── + + Widget _incidentesSection() => _card( + title: 'Últimos incidentes', + icono: Icons.assignment_outlined, + child: _incidentes.isEmpty + ? _emptyState('Sin incidentes registrados', Icons.assignment_outlined) + : Column(children: [ + _incidenteHeader(), + const Divider(color: AppColors.outlineVariant, height: 12), + ..._incidentes.map(_incidenteRow), + ]), + ); + + Widget _incidenteHeader() => Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Row(children: [ + Expanded(flex: 2, child: Text('Tipo', 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('Operador', style: appLabel(size: 11, color: AppColors.outline))), + SizedBox(width: 80, child: Text('Cuándo', style: appLabel(size: 11, color: AppColors.outline))), + SizedBox(width: 70, child: Text('Estado', style: appLabel(size: 11, color: AppColors.outline))), + ]), + ); + + Widget _incidenteRow(Map inc) { + final resuelto = (inc['resuelto'] as int?) == 1; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 5), + child: Row(children: [ + Expanded( + flex: 2, + child: Text( + inc['tipo'] as String? ?? '—', + style: appLabel(size: 12, weight: FontWeight.w500, color: AppColors.onSurface), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + Expanded( + flex: 2, + child: Text( + inc['cliente_nombre'] as String? ?? '—', + style: appLabel(size: 12, color: AppColors.primary), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + Expanded( + flex: 2, + child: Text( + inc['operador'] as String? ?? '—', + style: appLabel(size: 12, color: AppColors.onSurfaceVariant), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + SizedBox( + width: 80, + child: Text( + _timeAgo(inc['timestamp'] as String?), + style: appLabel(size: 11, color: AppColors.outline), + ), + ), + SizedBox( + width: 70, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: resuelto + ? AppColors.clienteOk.withOpacity(0.12) + : AppColors.clienteAlerta.withOpacity(0.12), + borderRadius: BorderRadius.circular(20), + ), + child: Text( + resuelto ? 'Resuelto' : 'Pendiente', + style: appLabel( + size: 10, + weight: FontWeight.w600, + color: resuelto ? AppColors.clienteOk : AppColors.clienteAlerta, + ), + ), + ), + ), + ]), + ); + } + + // ── Shared widgets ─────────────────────────────────────────────────────────── + + Widget _card({ + required String title, + required IconData icono, + required Widget child, + String? badge, + Color badgeColor = AppColors.primary, + }) => + Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: AppColors.surfaceLow, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: AppColors.outlineVariant), + ), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Row(children: [ + Icon(icono, size: 16, color: AppColors.outline), + const SizedBox(width: 8), + Text(title, style: appHeadline(size: 13, weight: FontWeight.w700)), + if (badge != null) ...[ + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: badgeColor.withOpacity(0.15), + borderRadius: BorderRadius.circular(20), + ), + child: Text(badge, style: appLabel(size: 11, weight: FontWeight.bold, color: badgeColor)), + ), + ], + ]), + const SizedBox(height: 14), + child, + ]), + ); + + Widget _emptyState(String texto, IconData icono) => Padding( + padding: const EdgeInsets.symmetric(vertical: 24), + child: Center( + child: Column(mainAxisSize: MainAxisSize.min, children: [ + Icon(icono, size: 32, color: AppColors.outlineVariant), + const SizedBox(height: 10), + Text(texto, style: appLabel(size: 12, color: AppColors.outline)), + const SizedBox(height: 4), + Text('Esperando sincronización con Centinel', + style: appLabel(size: 11, color: AppColors.outlineVariant)), + ]), + ), + ); +} diff --git a/lib/pages/dispositivos_page.dart b/lib/pages/dispositivos_page.dart new file mode 100644 index 0000000..c9315d3 --- /dev/null +++ b/lib/pages/dispositivos_page.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; +import '../theme.dart'; + +class DispositivosPage extends StatelessWidget { + const DispositivosPage({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + primary: false, + padding: const EdgeInsets.all(32), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('Dispositivos', style: appHeadline(size: 28, weight: FontWeight.w800)), + const SizedBox(height: 8), + Text('Dispositivos Hikvision registrados en Centinel', style: appLabel(size: 14)), + ]), + ); + } +} diff --git a/lib/pages/incidentes_page.dart b/lib/pages/incidentes_page.dart new file mode 100644 index 0000000..a8f781d --- /dev/null +++ b/lib/pages/incidentes_page.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; +import '../theme.dart'; + +class IncidentesPage extends StatelessWidget { + const IncidentesPage({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + primary: false, + padding: const EdgeInsets.all(32), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('Incidentes', style: appHeadline(size: 28, weight: FontWeight.w800)), + const SizedBox(height: 8), + Text('Registro de incidentes gestionados', style: appLabel(size: 14)), + ]), + ); + } +} diff --git a/lib/pages/monitoreo_page.dart b/lib/pages/monitoreo_page.dart new file mode 100644 index 0000000..db29634 --- /dev/null +++ b/lib/pages/monitoreo_page.dart @@ -0,0 +1,746 @@ +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 createState() => _MonitoreoPageState(); +} + +class _MonitoreoPageState extends State { + final _alarmasDao = CacheAlarmasDao(); + final _clientesDao = CacheClientesDao(); + final _incidentesDao = IncidentesDao(); + + List> _todasAlarmas = []; + List> _alarmasFiltradas = []; + List> _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 _cargarOperador() async { + final u = await ApiAuthService.instance.getUsuario(); + if (mounted) setState(() => _operador = u ?? ''); + } + + Future _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>(); + _clientes = (results[1] as List).cast>(); + _aplicarFiltros(); + setState(() => _cargando = false); + } + + void _aplicarFiltros() { + var lista = List>.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 _escalar(Map alarma) async { + final ok = await showDialog( + 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 _silenciar(Map alarma) async { + final ok = await showDialog( + 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 _registrarIncidente(Map alarma) async { + String tipoSeleccionado = _tiposIncidenteId[0]; + final ctrlNotas = TextEditingController(); + + final ok = await showDialog( + 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( + 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 = []; + 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 = []; + 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( + 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( + value: null, + child: Text('Todos', style: appLabel(size: 11)), + ), + ..._clientes.map((c) => DropdownMenuItem( + 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 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), + ), + ]), + ); +} diff --git a/lib/pages/operadores_page.dart b/lib/pages/operadores_page.dart new file mode 100644 index 0000000..31a4d82 --- /dev/null +++ b/lib/pages/operadores_page.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; +import '../theme.dart'; + +class OperadoresPage extends StatelessWidget { + const OperadoresPage({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + primary: false, + padding: const EdgeInsets.all(32), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('Operadores', style: appHeadline(size: 28, weight: FontWeight.w800)), + const SizedBox(height: 8), + Text('Gestión de operadores y turnos', style: appLabel(size: 14)), + ]), + ); + } +} diff --git a/lib/pages/reportes_page.dart b/lib/pages/reportes_page.dart new file mode 100644 index 0000000..69d61af --- /dev/null +++ b/lib/pages/reportes_page.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; +import '../theme.dart'; + +class ReportesPage extends StatelessWidget { + const ReportesPage({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + primary: false, + padding: const EdgeInsets.all(32), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('Reportes', style: appHeadline(size: 28, weight: FontWeight.w800)), + const SizedBox(height: 8), + Text('Informes por cliente, operador y período', style: appLabel(size: 14)), + ]), + ); + } +} diff --git a/lib/recursos/logo_app.png b/lib/recursos/logo_app.png new file mode 100644 index 0000000..f58ec35 Binary files /dev/null and b/lib/recursos/logo_app.png differ diff --git a/lib/recursos/logo_app.svg b/lib/recursos/logo_app.svg new file mode 100644 index 0000000..e959a1a --- /dev/null +++ b/lib/recursos/logo_app.svg @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/services/api_auth_service.dart b/lib/services/api_auth_service.dart new file mode 100644 index 0000000..33f0ddf --- /dev/null +++ b/lib/services/api_auth_service.dart @@ -0,0 +1,142 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Flujo de autenticación WebControl (2 pasos): +/// +/// Paso 1 — POST /api/auth/empresas { email, paswd } +/// → { success, usuario, empresas:[{dba,nombre,rol}], unica } +/// +/// Paso 2 — POST /api/auth/login { email, paswd, dba } +/// → { success, token, apiKey, db_tenant, usuario:{id,nombre,usuario,rol} } +/// +/// Uso posterior (llamadas a api.telcotronics.com): +/// final h = await ApiAuthService.instance.getCentinelHeaders(); +class ApiAuthService { + static const _base = 'https://api.siax-system.net'; + + static const _keyToken = 'webcontrol_token'; + static const _keyApiKey = 'centinel_api_key'; + static const _keyTenant = 'centinel_tenant'; + static const _keyNombre = 'operador_nombre'; + static const _keyUsuario = 'operador_usuario'; + + ApiAuthService._(); + static final ApiAuthService instance = ApiAuthService._(); + + // ── Paso 1: obtener empresas del usuario ────────────────────── + Future>?> getEmpresas( + String email, String paswd) async { + try { + final resp = await http.post( + Uri.parse('$_base/api/auth/empresas'), + headers: { + 'Content-Type': 'application/json', + 'accept': 'application/json', + }, + body: jsonEncode({'email': email, 'paswd': paswd}), + ).timeout(const Duration(seconds: 10)); + + if (resp.statusCode != 200) return null; + final body = jsonDecode(resp.body) as Map; + if (body['success'] != true) return null; + + return List>.from( + body['empresas'] as List? ?? []); + } catch (_) { + return null; + } + } + + // ── Paso 2: login completo con dba ──────────────────────────── + Future login(String email, String paswd, {String? dba}) async { + try { + // Paso 1: obtener dba si no se pasó + String? dbaTenant = dba; + if (dbaTenant == null) { + final empresas = await getEmpresas(email, paswd); + if (empresas == null || empresas.isEmpty) return false; + dbaTenant = empresas.first['dba'] as String?; + if (dbaTenant == null) return false; + } + + // Paso 2: login real + final resp = await http.post( + Uri.parse('$_base/api/auth/login'), + headers: { + 'Content-Type': 'application/json', + 'accept': 'application/json', + }, + body: jsonEncode({'email': email, 'paswd': paswd, 'dba': dbaTenant}), + ).timeout(const Duration(seconds: 10)); + + if (resp.statusCode != 200) return false; + + final body = jsonDecode(resp.body) as Map; + if (body['success'] != true) return false; + + final token = body['token'] as String?; + final apiKey = body['apiKey'] as String?; + final tenant = body['db_tenant'] as String?; + final usr = body['usuario'] as Map?; + final nombre = usr?['nombre'] as String? ?? email; + final usuario = usr?['usuario'] as String? ?? email; + + if (apiKey == null || tenant == null) return false; + + final prefs = await SharedPreferences.getInstance(); + if (token != null) await prefs.setString(_keyToken, token); + await prefs.setString(_keyApiKey, apiKey); + await prefs.setString(_keyTenant, tenant); + await prefs.setString(_keyNombre, nombre); + await prefs.setString(_keyUsuario, usuario); + return true; + } catch (_) { + return false; + } + } + + // ── Logout ──────────────────────────────────────────────────── + Future logout() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_keyToken); + await prefs.remove(_keyApiKey); + await prefs.remove(_keyTenant); + await prefs.remove(_keyNombre); + await prefs.remove(_keyUsuario); + } + + // ── Estado ──────────────────────────────────────────────────── + Future isAuthenticated() async { + final prefs = await SharedPreferences.getInstance(); + final apiKey = prefs.getString(_keyApiKey); + return apiKey != null && apiKey.isNotEmpty; + } + + // ── Headers para api.telcotronics.com ───────────────────────── + Future?> getCentinelHeaders() async { + final prefs = await SharedPreferences.getInstance(); + final apiKey = prefs.getString(_keyApiKey); + final tenant = prefs.getString(_keyTenant); + if (apiKey == null || apiKey.isEmpty) return null; + return { + 'Content-Type': 'application/json', + 'accept': 'application/json', + 'x-api-key': apiKey, + 'x-database': tenant ?? '', + }; + } + + // ── Getters ─────────────────────────────────────────────────── + Future getNombre() async => + (await SharedPreferences.getInstance()).getString(_keyNombre); + + Future getUsuario() async => + (await SharedPreferences.getInstance()).getString(_keyUsuario); + + Future getApiKey() async => + (await SharedPreferences.getInstance()).getString(_keyApiKey); + + Future getToken() async => + (await SharedPreferences.getInstance()).getString(_keyToken); +} diff --git a/lib/shell_page.dart b/lib/shell_page.dart new file mode 100644 index 0000000..83bdf5a --- /dev/null +++ b/lib/shell_page.dart @@ -0,0 +1,263 @@ +import 'package:flutter/material.dart'; +import 'theme.dart'; +import 'services/api_auth_service.dart'; +import 'db/dao/sesiones_dao.dart'; +import 'pages/dashboard_page.dart'; +import 'pages/monitoreo_page.dart'; +import 'pages/clientes_page.dart'; +import 'pages/operadores_page.dart'; +import 'pages/incidentes_page.dart'; +import 'pages/dispositivos_page.dart'; +import 'pages/reportes_page.dart'; +import 'pages/configuracion_page.dart'; + +class ShellPage extends StatefulWidget { + const ShellPage({Key? key}) : super(key: key); + + @override + State createState() => _ShellPageState(); +} + +class _ShellPageState extends State { + int _indice = 0; + String _operadorNombre = 'Operador'; + bool _apiConectada = false; + + final _sesionesDao = SesionesDao(); + + static const _paginas = [ + DashboardPage(), + MonitoreoPage(), + ClientesPage(), + OperadoresPage(), + IncidentesPage(), + DispositivosPage(), + ReportesPage(), + ConfiguracionPage(), + ]; + + 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'), + ]; + + @override + void initState() { + super.initState(); + _cargarOperador(); + } + + Future _cargarOperador() async { + final nombre = await ApiAuthService.instance.getNombre(); + final usuario = await ApiAuthService.instance.getUsuario() ?? ''; + if (!mounted) return; + setState(() => _operadorNombre = nombre ?? usuario); + await _sesionesDao.iniciarSesion(_operadorNombre, usuario); + _verificarApi(); + } + + Future _verificarApi() async { + final ok = await ApiAuthService.instance.isAuthenticated(); + if (!mounted) return; + setState(() => _apiConectada = ok); + } + + Future _cerrarSesion() async { + final ok = await showDialog( + context: context, + builder: (_) => AlertDialog( + backgroundColor: AppColors.surfaceHigh, + title: Text('Cerrar sesión', + style: appHeadline(size: 16, weight: FontWeight.w700)), + content: Text('¿Finalizar el turno y cerrar sesión?', + 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('CERRAR', style: appLabel(weight: FontWeight.bold, color: AppColors.error)), + ), + ], + ), + ); + if (ok != true) return; + await _sesionesDao.cerrarSesion(); + await ApiAuthService.instance.logout(); + if (!mounted) return; + Navigator.of(context).pushReplacementNamed('/login'); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.surfaceLowest, + body: Column(children: [ + _header(), + Expanded( + child: Row(children: [ + _sidebar(), + const VerticalDivider(width: 1, color: AppColors.outlineVariant), + Expanded( + child: IndexedStack( + index: _indice, + children: _paginas, + ), + ), + ]), + ), + ]), + ); + } + + // ── Header ────────────────────────────────────────────────────────────────── + Widget _header() => Container( + height: 56, + color: AppColors.surfaceLow, + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Row(children: [ + // Logo + nombre app + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: AppColors.primaryContainer, + ), + child: const Icon(Icons.shield, color: AppColors.primary, size: 18), + ), + const SizedBox(width: 12), + Text('CENTRO DE MONITOREO', + style: appHeadline( + size: 14, + weight: FontWeight.w800, + color: AppColors.primary, + spacing: 1.5)), + const Spacer(), + // Estado API + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: (_apiConectada ? AppColors.primaryContainer : AppColors.surfaceHighest), + borderRadius: BorderRadius.circular(20), + ), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Container( + width: 7, + height: 7, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: _apiConectada + ? const Color(0xFF4CAF50) + : AppColors.outline, + ), + ), + const SizedBox(width: 6), + Text( + _apiConectada ? 'API conectada' : 'Sin conexión', + style: appLabel( + size: 11, + color: _apiConectada ? AppColors.primary : AppColors.outline), + ), + ]), + ), + const SizedBox(width: 20), + // Operador + Row(children: [ + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: AppColors.primaryContainer, + ), + child: Center( + child: Text( + _operadorNombre.isNotEmpty ? _operadorNombre[0].toUpperCase() : 'O', + style: appHeadline(size: 14, weight: FontWeight.bold, color: AppColors.primary), + ), + ), + ), + const SizedBox(width: 8), + Text(_operadorNombre, style: appLabel(size: 13, color: AppColors.onSurface)), + ]), + const SizedBox(width: 16), + IconButton( + icon: const Icon(Icons.logout, color: AppColors.outline, size: 20), + tooltip: 'Cerrar sesión', + onPressed: _cerrarSesion, + ), + ]), + ); + + // ── Sidebar ───────────────────────────────────────────────────────────────── + 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), + ), + ), + ]), + ); + + Widget _navTile(int i) { + final item = _navItems[i]; + final activo = _indice == i; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Material( + color: Colors.transparent, + borderRadius: BorderRadius.circular(10), + child: InkWell( + borderRadius: BorderRadius.circular(10), + onTap: () => setState(() => _indice = i), + child: AnimatedContainer( + duration: const Duration(milliseconds: 160), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 11), + decoration: BoxDecoration( + 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, + 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); +} diff --git a/lib/theme.dart b/lib/theme.dart new file mode 100644 index 0000000..376e17a --- /dev/null +++ b/lib/theme.dart @@ -0,0 +1,55 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; + +class AppColors { + static const surfaceLowest = Color(0xFF0A0E14); + static const surfaceLow = Color(0xFF181C22); + static const surface = Color(0xFF1C2026); + static const surfaceHigh = Color(0xFF262A31); + static const surfaceHighest = Color(0xFF31353C); + static const primary = Color(0xFFB0C6FF); + static const primaryContainer = Color(0xFF002359); + static const error = Color(0xFFFFB4AB); + static const onError = Color(0xFF690005); + static const tertiary = Color(0xFFFFB3B3); + static const tertiaryContainer = Color(0xFF54000E); + static const secondary = Color(0xFFB4CAD6); + static const secondaryContainer = Color(0xFF374C56); + static const onSecondaryContainer = Color(0xFFA6BCC7); + static const onSurface = Color(0xFFDFE2EB); + static const onSurfaceVariant = Color(0xFFC4C6CF); + static const outline = Color(0xFF8E9199); + static const outlineVariant = Color(0xFF44474E); + + // Colores semánticos para estados de alarma / cliente + static const alarmaActiva = Color(0xFFFFB4AB); // error — rojo + static const alarmaEscalada = Color(0xFFFFB3B3); // tertiary — coral + static const alarmaSilenciada = Color(0xFFB4CAD6); // secondary — gris azul + static const clienteOk = Color(0xFF4CAF50); // verde + static const clienteAlerta = Color(0xFFFFB300); // ámbar + static const clienteCritico = Color(0xFFFFB4AB); // rojo +} + +TextStyle appHeadline({ + double size = 14, + FontWeight weight = FontWeight.bold, + Color color = AppColors.onSurface, + double spacing = 0, +}) => + GoogleFonts.manrope( + fontSize: size, + fontWeight: weight, + color: color, + letterSpacing: spacing); + +TextStyle appLabel({ + double size = 12, + FontWeight weight = FontWeight.normal, + Color color = AppColors.onSurfaceVariant, + double spacing = 0, +}) => + GoogleFonts.inter( + fontSize: size, + fontWeight: weight, + color: color, + letterSpacing: spacing); diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..cc1e245 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,91 @@ +name: central_monitoreo +description: Centro de Monitoreo General — plataforma de operadores de seguridad electrónica. + +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +version: 1.0.0+1 + +environment: + sdk: ">=2.17.0-69.2.beta <3.0.0" + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + cupertino_icons: ^1.0.2 + google_fonts: ^3.0.1 + sqflite: ^2.0.0 + sqflite_common_ffi: ^2.0.0 + path: ^1.8.1 + crypto: ^3.0.2 + shared_preferences: ^2.0.0 + http: ^0.13.4 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^1.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + assets: + - lib/recursos/logo_app.png + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware. + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages