docs: nuevas páginas, plan y documentación sesión 10
- alarmas_page.dart, registrar_usuario_page.dart: páginas nuevas - plan_proyecto.md: actualizado a sesión 10 - solicituda_backend.md, agents.md: documentación de endpoints y agentes Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
efa4a792f4
commit
d150d7dc9f
@@ -0,0 +1,523 @@
|
|||||||
|
# SENTINEL ONE — Plan del Proyecto
|
||||||
|
**App:** Sistema de Seguridad Electrónica
|
||||||
|
**Stack:** Flutter · Google Fonts (Manrope + Inter) · Material 3 · Dark Theme
|
||||||
|
**Última revisión:** 2026-04-16 (sesión 7)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Estado actual de módulos
|
||||||
|
|
||||||
|
| Módulo | Archivo | Estado |
|
||||||
|
|--------|---------|--------|
|
||||||
|
| Login (PIN local + SharedPreferences) | `main.dart` → `LoginPage` | ✅ Completo |
|
||||||
|
| Layout principal (nav + header) | `main_page.dart` | ✅ Completo |
|
||||||
|
| Inicio (usuario, empresa, banner, log) | `pages/inicio_page.dart` | ✅ Completo |
|
||||||
|
| Monitoreo y Alarmas | `pages/monitoreo_alarma_page.dart` | ✅ BD conectada |
|
||||||
|
| Control de Acceso | `pages/control_acceso_page.dart` | ✅ BD conectada |
|
||||||
|
| Mensajería (chat WhatsApp) | `pages/mensageria_page.dart` | ✅ BD conectada |
|
||||||
|
| Perfil de Usuario | `pages/perfil_usuario_page.dart` | ✅ BD + foto perfil |
|
||||||
|
| Llamada simulada | `pages/llamada_page.dart` | ✅ Completo |
|
||||||
|
| Conectar Proveedor | `pages/conectar_proveedor_page.dart` | ✅ Completo |
|
||||||
|
| Cambio de PIN | `pages/seguridad_page.dart` | ✅ Completo |
|
||||||
|
| Historial de sesiones | `pages/historial_sesiones_page.dart` | ✅ Completo |
|
||||||
|
| Registro de usuario | `pages/register_page.dart` | 🔴 Sin estilo del sistema |
|
||||||
|
| Configuración | `pages/settings_page.dart` | 🟡 Parcial |
|
||||||
|
| Alarmas (página propia) | `pages/alarmas_page.dart` | ✅ Completo |
|
||||||
|
| Clientes | `pages/clientes_page.dart` | 🔴 Pendiente |
|
||||||
|
| Suscripciones | `pages/suscripciones_page.dart` | 🔴 Pendiente |
|
||||||
|
| Tema / Colores | `theme.dart` | ✅ Completo |
|
||||||
|
| Menú global | `widgets/app_menu_button.dart` | ✅ Completo |
|
||||||
|
| Base de datos SQLite | `db/database_helper.dart` | ✅ v3 — 14 tablas + foto_path |
|
||||||
|
| Modelos de datos | `models/*.dart` (12 modelos) | ✅ Completo |
|
||||||
|
| DAOs | `db/dao/*.dart` (14 DAOs) | ✅ Completo |
|
||||||
|
| ApiAuthService | `services/api_auth_service.dart` | ✅ Estructura lista |
|
||||||
|
| Sincronizador | `services/sincronizador.dart` | ✅ Estructura lista |
|
||||||
|
| DemoDataService | `services/demo_data_service.dart` | ✅ Completo |
|
||||||
|
| Clientes (modelo + DAO) | `models/cliente.dart` · `db/dao/clientes_dao.dart` | ✅ Completo |
|
||||||
|
| Suscripciones (modelo + DAO) | `models/suscripcion.dart` · `db/dao/suscripciones_dao.dart` | ✅ Completo |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Lo que está hecho
|
||||||
|
|
||||||
|
### Login (`main.dart` → `LoginPage`)
|
||||||
|
- PIN de 4–6 dígitos, cajas individuales animadas
|
||||||
|
- Auto-avance al siguiente campo, retroceso con backspace
|
||||||
|
- Enlace a RegisterPage
|
||||||
|
- Al ingresar navega a `MainPage(initialIndex: 0)` — abre en tab INICIO
|
||||||
|
- **Autenticación local vía `SharedPreferences`** — el PIN se guarda como hash SHA-256 bajo la clave `local_pin_hash`
|
||||||
|
- PIN inicial por defecto: `123456` — si no hay hash guardado, se compara contra ese valor
|
||||||
|
- El login NO depende de SQLite — funciona en todas las plataformas sin plugins nativos
|
||||||
|
- Spinner de carga mientras valida, mensaje de error visible en snackbar
|
||||||
|
- **Foco automático** al primer campo al abrir la página (`initState` + `addPostFrameCallback`)
|
||||||
|
- **Click en el card** mueve el foco al primer input (`GestureDetector` → `requestFocus`)
|
||||||
|
- **Tecla Enter** dispara login si hay 4+ dígitos (manejo en `_onKeyEvent` — Enter y NumpadEnter)
|
||||||
|
|
||||||
|
### Cambio de PIN (`pages/seguridad_page.dart`)
|
||||||
|
- Accesible desde Perfil → Seguridad
|
||||||
|
- 3 secciones de cajas PIN: PIN actual · Nuevo PIN · Confirmar nuevo PIN
|
||||||
|
- Valida que el PIN actual sea correcto antes de permitir el cambio
|
||||||
|
- Verifica que nuevo PIN ≠ PIN actual, y que nuevo PIN = confirmación
|
||||||
|
- Guarda el nuevo hash SHA-256 en `SharedPreferences` (`local_pin_hash`)
|
||||||
|
- Botón deshabilitado hasta que los 3 campos tengan mínimo 4 dígitos
|
||||||
|
- Snackbar de éxito (azul) o error (rojo) según resultado
|
||||||
|
|
||||||
|
### MainPage (`main_page.dart`)
|
||||||
|
- Header: logo SENTINEL ONE (izq) + título de sección activa + AppMenuButton (der)
|
||||||
|
- Bottom nav: INICIO · ACCESO · ALARMAS · PERFIL
|
||||||
|
- `IndexedStack` mantiene estado de cada pestaña
|
||||||
|
- Routing: INICIO→InicioPage, ACCESO→ControlAccesoPage, ALARMAS→MonitoreoAlarmaPage, PERFIL→PerfilUsuarioPage
|
||||||
|
|
||||||
|
### InicioPage (`pages/inicio_page.dart`)
|
||||||
|
- **Sección usuario:** "Bienvenido / Juan Díaz" a la izquierda + avatar con ícono de persona y punto online a la derecha — sin fondo de tarjeta
|
||||||
|
- **Línea separadora** entre usuario y empresa
|
||||||
|
- **Tarjeta empresa:** logo ALARM WORK (CustomPainter centrado) + badge verificado + "Partner de Seguridad"
|
||||||
|
- **Banner slider:** PageView con 3 slides, auto-avance cada 4 s, dots tappables, flechas ‹ › sobre el banner, swipe manual
|
||||||
|
- **Métricas rápidas:** 2 tarjetas (Estado Sistema PROTEGIDO / 12 Nodos Activos ONLINE)
|
||||||
|
- **Log de eventos:** timeline con 4 tipos (Alerta Crítica, Noticia, Notificación, Evento General) con líneas verticales conectoras
|
||||||
|
- **FAB de pánico:** botón rojo circular con animación ping pulsante + texto "PÁNICO" → navega a MensajeriaPage
|
||||||
|
|
||||||
|
### MonitoreoAlarmaPage (`pages/monitoreo_alarma_page.dart`) — tab ALARMAS
|
||||||
|
> Renombrado desde `dashboard_page.dart` / `DashboardPage`
|
||||||
|
- Tarjeta "MONITOREO ACTIVO" con animación de pulso
|
||||||
|
- Mini-stats: Alarmas activas / Resueltas 24h
|
||||||
|
- Gráfico de frecuencia semanal (barras custom)
|
||||||
|
- Sección eventos críticos + botón RESPONDER
|
||||||
|
- Registro de eventos con timeline
|
||||||
|
- Vista táctica con grid y ping animado
|
||||||
|
|
||||||
|
### ControlAccesoPage (`pages/control_acceso_page.dart`)
|
||||||
|
- Control de 3 puertas: Lobby Principal, Muelle de Carga, Centro de Datos
|
||||||
|
- Toggle bloqueo/desbloqueo por puerta
|
||||||
|
- Registro de acceso con avatar + estado OK/denegado
|
||||||
|
- Snapshot de cámara simulado (grid verde + overlay REC)
|
||||||
|
|
||||||
|
### MensajeriaPage (`pages/mensageria_page.dart`)
|
||||||
|
- **Tarjetas de acción fijas:** Botón de Pánico (rojo) → envía mensaje de alerta; Soporte/Asistencia (azul) → envía mensaje de soporte
|
||||||
|
- **Chat estilo WhatsApp:** burbujas izq (recibidos) / der (enviados), timestamps, ícono doble check
|
||||||
|
- **Input bar:** campo multi-línea + ícono adjunto + botón enviar circular
|
||||||
|
- **Botón llamar** en header → diálogo de confirmación → Snackbar "Conectando con Central..."
|
||||||
|
- 5 mensajes iniciales de demostración pre-cargados
|
||||||
|
|
||||||
|
### PerfilUsuarioPage (`pages/perfil_usuario_page.dart`)
|
||||||
|
- Avatar con iniciales + badge nivel de acceso
|
||||||
|
- Estadísticas del turno (alarmas gestionadas, accesos autorizados, alertas activas)
|
||||||
|
- Menú: Configuración, Seguridad, Historial de sesiones, Ayuda y soporte
|
||||||
|
- Botón Cerrar Sesión → LoginPage
|
||||||
|
|
||||||
|
### Capa de datos SQLite (`lib/db/` · `lib/models/` · `lib/services/`)
|
||||||
|
- **`database_helper.dart`** — Singleton, 14 `CREATE TABLE` (v2), seed mínimo al primer arranque:
|
||||||
|
- 1 usuario admin (Juan Díaz, nivel 3, PIN 123456)
|
||||||
|
- 6 zonas (Z-01 a Z-06), 3 puertas, 3 banners, configuración base
|
||||||
|
- 3 clientes, 5 suscripciones con estados variados
|
||||||
|
- **Sin datos operacionales** — eventos, alarmas, mensajes, accesos y sesiones arrancan vacíos
|
||||||
|
- **12 modelos** con `fromMap()` / `toMap()` — `Usuario`, `Zona`, `Nodo`, `Puerta`, `Alarma`, `Acceso`, `Evento`, `Mensaje`, `BannerItem`, `Sesion`, `Cliente`, `Suscripcion`
|
||||||
|
- **14 DAOs** — CRUD + `getPendientes()` + métodos específicos (`resolver`, `silenciar`, `setBloqueada`, `contarActivas`, `marcarLeido`, `getProximasAVencer`, `cambiarEstado`, `contarActivos`, etc.)
|
||||||
|
- **`DemoDataService`** — singleton que borra e inserta datos de prueba en tablas operacionales (eventos, alarmas, mensajes, accesos, sesiones); invocable desde `SettingsPage`
|
||||||
|
- **`ApiAuthService`** — estructura lista: `login()`, `logout()`, `isAuthenticated()`, `getToken()` — token JWT en SharedPreferences
|
||||||
|
- **`Sincronizador`** — estructura lista: `sincronizar()`, métodos por tabla, `pushPendientes()` — pendiente de URL de API real
|
||||||
|
- Compatible con Linux/Windows desktop vía `sqflite_common_ffi` (detección automática de plataforma en `database_helper.dart`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Lo que falta hacer
|
||||||
|
|
||||||
|
### 🔴 ALTA PRIORIDAD
|
||||||
|
|
||||||
|
#### 1. Botones Pánico y Soporte — convertir a eventos directos (`pages/mensageria_page.dart`)
|
||||||
|
Actualmente insertan un mensaje de chat en la tabla `mensajes`. El comportamiento correcto es:
|
||||||
|
- **PÁNICO:** insertar un evento de tipo `alerta` en la tabla `eventos` con severidad máxima + mostrar snackbar/diálogo de confirmación (no un mensaje de chat)
|
||||||
|
- **SOPORTE:** abrir la llamada simulada (`LlamadaPage`) o enviar un evento de tipo `notificacion` a la central — no un mensaje de chat
|
||||||
|
- El chat debe quedar exclusivamente para comunicación de texto libre con la central
|
||||||
|
|
||||||
|
#### 2. Página de Alarmas real (`pages/alarmas_page.dart`) ✅ IMPLEMENTADO
|
||||||
|
- Tab ACTIVAS: chips de filtro por tipo + cards con severidad, zona, timestamp
|
||||||
|
- Acciones: Responder (diálogo + notas), Silenciar, Escalar (incrementa severidad)
|
||||||
|
- Tab HISTORIAL: lista compacta de resueltas y silenciadas
|
||||||
|
- Pull to refresh · empty states · navegación desde botón RESPONDER de MonitoreoAlarmaPage
|
||||||
|
- Endpoints backend pendientes documentados en `solicituda_backend.md`
|
||||||
|
|
||||||
|
#### 2. Control de Acceso — Registrar usuarios (`pages/control_acceso_page.dart`)
|
||||||
|
Comentario pendiente en el código: *"agregar un botón para registrar usuarios y darle acceso por tiempo y áreas"*
|
||||||
|
- FAB o botón en header para abrir formulario
|
||||||
|
- Formulario: nombre, nivel de acceso, áreas permitidas, fecha inicio/fin
|
||||||
|
- Lista de usuarios con acceso activo/expirado
|
||||||
|
|
||||||
|
### 🟡 MEDIA PRIORIDAD
|
||||||
|
|
||||||
|
#### 3. Rediseño de RegisterPage (`pages/register_page.dart`)
|
||||||
|
- Aplicar `AppColors`, `appHeadline`, `appLabel`
|
||||||
|
- Consistencia visual con el sistema (actualmente usa Material por defecto)
|
||||||
|
- Definir si usa PIN de 6 dígitos o email + contraseña
|
||||||
|
|
||||||
|
#### 4. Rediseño de SettingsPage (`pages/settings_page.dart`)
|
||||||
|
- Aplicar `AppColors`, `appHeadline`, `appLabel`
|
||||||
|
- Consistencia visual con el sistema
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Arquitectura de datos — Offline First + Sincronización
|
||||||
|
|
||||||
|
### Principio fundamental
|
||||||
|
La app funciona **completamente de forma independiente**. SQLite es la única fuente de verdad para la UI. El servidor es una fuente externa que alimenta la BD local, nunca se consulta directamente desde las páginas.
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────┐
|
||||||
|
│ APP │
|
||||||
|
│ │
|
||||||
|
│ Páginas ──────► DAOs ──────► SQLite (local) │
|
||||||
|
│ ▲ │
|
||||||
|
│ │ │
|
||||||
|
│ Sincronizador │
|
||||||
|
│ ▲ │
|
||||||
|
│ │ │
|
||||||
|
│ ApiAuthService │
|
||||||
|
│ (token JWT) │
|
||||||
|
└─────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
API / Servidor
|
||||||
|
```
|
||||||
|
|
||||||
|
### Clases de servicio
|
||||||
|
|
||||||
|
#### `ApiAuthService` (`lib/services/api_auth_service.dart`)
|
||||||
|
Responsabilidad: autenticación contra el servidor y gestión del token.
|
||||||
|
- `login(usuario, password)` → solicita token al servidor y lo almacena en `configuracion` (clave: `api_token`, `api_token_expiry`)
|
||||||
|
- `logout()` → elimina el token local
|
||||||
|
- `isAuthenticated()` → verifica si hay token válido no expirado
|
||||||
|
- `getToken()` → devuelve el token activo para usarlo en peticiones
|
||||||
|
- El token **nunca se expone a las páginas** — solo lo usa `Sincronizador`
|
||||||
|
|
||||||
|
#### `Sincronizador` (`lib/services/sincronizador.dart`)
|
||||||
|
Responsabilidad: mantener SQLite actualizado con los datos del servidor.
|
||||||
|
- `sincronizar()` → punto de entrada principal, llama a los métodos específicos
|
||||||
|
- `sincronizarAlarmas()` → descarga alarmas nuevas del servidor → inserta/actualiza en SQLite
|
||||||
|
- `sincronizarAccesos()` → descarga registros de acceso → SQLite
|
||||||
|
- `sincronizarUsuarios()` → descarga usuarios autorizados → SQLite
|
||||||
|
- `sincronizarZonas()` → descarga zonas y nodos → SQLite
|
||||||
|
- `sincronizarMensajes()` → descarga mensajes nuevos de la central → SQLite
|
||||||
|
- `sincronizarBanners()` → descarga contenido del slider → SQLite
|
||||||
|
- `pushPendientes()` → envía al servidor los registros locales marcados como `sincronizado = 0`
|
||||||
|
- Registra cada sincronización en la tabla `sync_log`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Plan de integración SQLite
|
||||||
|
|
||||||
|
### Dependencias a agregar en `pubspec.yaml`
|
||||||
|
```yaml
|
||||||
|
dependencies:
|
||||||
|
sqflite: ^2.3.0
|
||||||
|
path: ^1.9.0
|
||||||
|
crypto: ^3.0.3 # hash del PIN
|
||||||
|
shared_preferences: ^2.2.2 # almacenamiento del token (más seguro que SQLite para auth)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Tablas completas
|
||||||
|
|
||||||
|
#### `usuarios`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | ID del servidor |
|
||||||
|
| nombre | TEXT | Nombre completo |
|
||||||
|
| iniciales | TEXT | Para el avatar (ej. "JD") |
|
||||||
|
| nivel_acceso | INTEGER | 1–5 |
|
||||||
|
| pin_hash | TEXT | SHA-256 del PIN |
|
||||||
|
| areas | TEXT | JSON con lista de IDs de zonas permitidas |
|
||||||
|
| fecha_inicio | TEXT | ISO 8601 |
|
||||||
|
| fecha_fin | TEXT | ISO 8601, null = sin expiración |
|
||||||
|
| activo | INTEGER | 0/1 |
|
||||||
|
| sincronizado | INTEGER | 0=pendiente, 1=sincronizado |
|
||||||
|
|
||||||
|
#### `zonas`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | ID del servidor |
|
||||||
|
| codigo | TEXT | Ej. "Z-03" |
|
||||||
|
| nombre | TEXT | Ej. "Almacén G-4" |
|
||||||
|
| descripcion | TEXT | Ej. "Bodega · 2 cámaras · 4 sensores" |
|
||||||
|
| estado | TEXT | segura / alerta / inactiva |
|
||||||
|
| sincronizado | INTEGER | 0/1 |
|
||||||
|
|
||||||
|
#### `nodos`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | ID del servidor |
|
||||||
|
| zona_id | INTEGER | FK zonas.id |
|
||||||
|
| tipo | TEXT | camara / sensor_movimiento / sensor_humo / control_acceso |
|
||||||
|
| nombre | TEXT | Ej. "CAM_01_LOBBY" |
|
||||||
|
| activo | INTEGER | 0/1 |
|
||||||
|
| ultima_senal | TEXT | ISO 8601 |
|
||||||
|
| sincronizado | INTEGER | 0/1 |
|
||||||
|
|
||||||
|
#### `puertas`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | ID del servidor |
|
||||||
|
| zona_id | INTEGER | FK zonas.id |
|
||||||
|
| nombre | TEXT | Ej. "Lobby Principal" |
|
||||||
|
| codigo | TEXT | Ej. "Entrada 01" |
|
||||||
|
| bloqueada | INTEGER | 0/1 — persiste entre sesiones |
|
||||||
|
| sincronizado | INTEGER | 0/1 |
|
||||||
|
|
||||||
|
#### `alarmas`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | ID del servidor |
|
||||||
|
| zona_id | INTEGER | FK zonas.id |
|
||||||
|
| tipo | TEXT | intrusion / humo / movimiento / acceso |
|
||||||
|
| severidad | INTEGER | 1–5 |
|
||||||
|
| timestamp | TEXT | ISO 8601 |
|
||||||
|
| estado | TEXT | activa / silenciada / resuelta |
|
||||||
|
| resuelto_por | INTEGER | FK usuarios.id, nullable |
|
||||||
|
| notas | TEXT | nullable |
|
||||||
|
| sincronizado | INTEGER | 0/1 |
|
||||||
|
|
||||||
|
#### `accesos`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | ID del servidor |
|
||||||
|
| usuario_id | INTEGER | FK usuarios.id |
|
||||||
|
| puerta_id | INTEGER | FK puertas.id |
|
||||||
|
| timestamp | TEXT | ISO 8601 |
|
||||||
|
| autorizado | INTEGER | 0/1 |
|
||||||
|
| metodo | TEXT | pin / remoto / biometrico |
|
||||||
|
| sincronizado | INTEGER | 0/1 |
|
||||||
|
|
||||||
|
#### `eventos`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | ID del servidor |
|
||||||
|
| tipo | TEXT | alerta / noticia / notificacion / general |
|
||||||
|
| titulo | TEXT | Título del evento |
|
||||||
|
| descripcion | TEXT | Detalle |
|
||||||
|
| hora | TEXT | HH:MM AM/PM para mostrar |
|
||||||
|
| timestamp | TEXT | ISO 8601 para ordenar |
|
||||||
|
| leido | INTEGER | 0/1 |
|
||||||
|
| sincronizado | INTEGER | 0/1 |
|
||||||
|
|
||||||
|
#### `mensajes`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | ID del servidor |
|
||||||
|
| texto | TEXT | Contenido |
|
||||||
|
| es_mio | INTEGER | 0/1 |
|
||||||
|
| hora | TEXT | HH:MM para mostrar |
|
||||||
|
| timestamp | TEXT | ISO 8601 para ordenar |
|
||||||
|
| sincronizado | INTEGER | 0/1 |
|
||||||
|
|
||||||
|
#### `banners`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | ID del servidor |
|
||||||
|
| badge | TEXT | Ej. "Premium Access" |
|
||||||
|
| titulo | TEXT | Título del banner |
|
||||||
|
| subtitulo | TEXT | Descripción |
|
||||||
|
| orden | INTEGER | Posición en el slider |
|
||||||
|
| activo | INTEGER | 0/1 |
|
||||||
|
| sincronizado | INTEGER | 0/1 |
|
||||||
|
|
||||||
|
#### `sesiones`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | Auto-incremental local |
|
||||||
|
| usuario_id | INTEGER | FK usuarios.id |
|
||||||
|
| timestamp_inicio | TEXT | ISO 8601 |
|
||||||
|
| timestamp_fin | TEXT | ISO 8601, null = sesión activa |
|
||||||
|
| dispositivo | TEXT | Identificador del dispositivo |
|
||||||
|
|
||||||
|
#### `sync_log`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| id | INTEGER PK | Auto-incremental |
|
||||||
|
| timestamp | TEXT | ISO 8601 |
|
||||||
|
| tipo | TEXT | full / parcial / push |
|
||||||
|
| estado | TEXT | ok / error |
|
||||||
|
| detalle | TEXT | Mensaje de resultado o error |
|
||||||
|
|
||||||
|
#### `configuracion`
|
||||||
|
| Campo | Tipo | Descripción |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| clave | TEXT PK | Ej. "notificaciones_activas" |
|
||||||
|
| valor | TEXT | Valor serializado |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Estructura de archivos
|
||||||
|
|
||||||
|
```
|
||||||
|
lib/
|
||||||
|
db/
|
||||||
|
database_helper.dart ← Singleton, CREATE TABLE, migraciones, seed
|
||||||
|
dao/
|
||||||
|
usuarios_dao.dart
|
||||||
|
zonas_dao.dart
|
||||||
|
nodos_dao.dart
|
||||||
|
puertas_dao.dart
|
||||||
|
alarmas_dao.dart
|
||||||
|
accesos_dao.dart
|
||||||
|
eventos_dao.dart
|
||||||
|
mensajes_dao.dart
|
||||||
|
banners_dao.dart
|
||||||
|
sesiones_dao.dart
|
||||||
|
sync_log_dao.dart
|
||||||
|
configuracion_dao.dart
|
||||||
|
models/
|
||||||
|
usuario.dart
|
||||||
|
zona.dart
|
||||||
|
nodo.dart
|
||||||
|
puerta.dart
|
||||||
|
alarma.dart
|
||||||
|
acceso.dart
|
||||||
|
evento.dart
|
||||||
|
mensaje.dart
|
||||||
|
banner.dart
|
||||||
|
sesion.dart
|
||||||
|
services/
|
||||||
|
api_auth_service.dart ← Login API, gestión de token JWT
|
||||||
|
sincronizador.dart ← Orquesta la sincronización API → SQLite
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pasos de implementación (en orden)
|
||||||
|
|
||||||
|
1. ✅ **`database_helper.dart`** — Singleton, `onCreate` con todos los `CREATE TABLE`, datos de seed
|
||||||
|
2. ✅ **Modelos** — clases Dart con `fromMap()` / `toMap()` por cada tabla
|
||||||
|
3. ✅ **DAOs** — `insert`, `getAll`, `getById`, `update`, `delete`, `getPendientes()` por tabla
|
||||||
|
4. ✅ **`ApiAuthService`** — estructura lista, pendiente URL de API real
|
||||||
|
5. ✅ **`Sincronizador`** — estructura lista, pendiente URL de API real
|
||||||
|
6. **Conectar páginas** en orden (pendiente):
|
||||||
|
- `InicioPage` → `EventosDao`, `BannersDao`, `ZonasDao`
|
||||||
|
- `MensajeriaPage` → `MensajesDao`
|
||||||
|
- `ControlAccesoPage` → `PuertasDao`, `AccesosDao`
|
||||||
|
- `MonitoreoAlarmaPage` → `AlarmasDao`, `EventosDao`
|
||||||
|
- `PerfilUsuarioPage` → `UsuariosDao`, `SesionesDao`
|
||||||
|
|
||||||
|
### Datos de seed (primer arranque, antes de primera sincronización)
|
||||||
|
- 1 usuario admin: Juan Díaz, nivel 3, PIN 123456
|
||||||
|
- 6 zonas (Z-01 a Z-06) con sus estados
|
||||||
|
- 3 puertas (Lobby, Muelle, Centro de Datos)
|
||||||
|
- 3 banners del slider
|
||||||
|
- 3 clientes y 5 suscripciones con estados variados
|
||||||
|
- Configuración base (notificaciones, api_base_url, etc.)
|
||||||
|
- **Sin datos operacionales** — alarmas, accesos, eventos, mensajes y sesiones arrancan vacíos
|
||||||
|
|
||||||
|
> Los datos de prueba se cargan desde **`DemoDataService`** vía Configuración → "Datos de demostración"
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Plataformas objetivo
|
||||||
|
|
||||||
|
| Plataforma | Notas |
|
||||||
|
|------------|-------|
|
||||||
|
| Android | Target principal — `sqflite` nativo, `getDatabasesPath()` |
|
||||||
|
| iOS | Target principal — `sqflite` nativo, `getDatabasesPath()` |
|
||||||
|
| Linux (Ubuntu Touch) | Mobile Linux — `sqflite_common_ffi`, BD en `~/.local/share/sentinel_one/` |
|
||||||
|
|
||||||
|
> macOS y Windows **no son targets** de este proyecto.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Requisitos del sistema — Linux / Ubuntu Touch
|
||||||
|
|
||||||
|
| Paquete | Comando de instalación | Por qué |
|
||||||
|
|---------|----------------------|---------|
|
||||||
|
| `libsqlite3-dev` | `sudo apt install libsqlite3-dev` | `sqflite_common_ffi` busca `libsqlite3.so` (symlink que solo incluye el paquete `-dev`) |
|
||||||
|
|
||||||
|
- Aplica a desarrollo en Ubuntu desktop y posiblemente Ubuntu Touch según la imagen del dispositivo
|
||||||
|
- Sin este paquete la app compila pero crashea al inicializar la BD
|
||||||
|
- El `CMakeLists.txt` lo verifica en tiempo de compilación (`pkg_check_modules(SQLITE3 REQUIRED sqlite3)`)
|
||||||
|
- Si el usuario final no lo tiene, la app muestra un diálogo con la instrucción exacta (`settings_page.dart` → `_mostrarErrorSqlite()`)
|
||||||
|
- La BD se guarda en `~/.local/share/sentinel_one/sentinel_one.db` (estándar XDG)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Notas de arquitectura
|
||||||
|
|
||||||
|
- **Tema:** Todo en `theme.dart` — siempre `AppColors`, `appHeadline()`, `appLabel()`
|
||||||
|
- **Navegación:** `IndexedStack` en MainPage — las páginas mantienen estado al cambiar tab
|
||||||
|
- **Datos:** Offline-first — las páginas solo leen SQLite, nunca la API directamente
|
||||||
|
- **Sincronización:** `Sincronizador` orquesta la bajada de datos; `ApiAuthService` provee el token
|
||||||
|
- **Token:** Se guarda en `shared_preferences`, no en SQLite (más seguro para datos de auth)
|
||||||
|
- **Campo `sincronizado`:** Todas las tablas operacionales lo tienen — permite saber qué enviar al servidor en el próximo `pushPendientes()`
|
||||||
|
- **SDK:** `sdk: ">=2.17.0-69.2.beta <3.0.0"` — actualizar a Dart 3.x antes de implementar SQLite
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Decisiones tomadas
|
||||||
|
|
||||||
|
- ✅ Login abre en tab INICIO (índice 0), no en ACCESO
|
||||||
|
- ✅ INICIO → InicioPage (usuario + empresa + banner + log de eventos)
|
||||||
|
- ✅ ALARMAS → MonitoreoAlarmaPage (renombrado desde DashboardPage)
|
||||||
|
- ✅ Mensajería accesible desde FAB de pánico (no en el nav principal)
|
||||||
|
- ✅ Tarjetas Pánico/Soporte viven dentro de MensajeriaPage
|
||||||
|
- ✅ Sección usuario en InicioPage: texto izquierda, avatar derecha, sin tarjeta de fondo
|
||||||
|
- ✅ Login no usa SQLite — usa SharedPreferences para no depender de plugins nativos
|
||||||
|
- ✅ Cambio de PIN en página dedicada (`seguridad_page.dart`) accesible desde Perfil
|
||||||
|
- ✅ Cerrar sesión con diálogo de confirmación — limpia autologin y regresa a LoginPage
|
||||||
|
- ✅ Fix Linux desktop: `primary: false` en todos los `SingleChildScrollView` del IndexedStack
|
||||||
|
- ✅ Fix Linux SQLite: detección de plataforma en `database_helper.dart` con `sqflite_common_ffi`
|
||||||
|
- ✅ Fix BD Linux: ruta corregida a `~/.local/share/sentinel_one/` (antes usaba `Directory.current` impredecible)
|
||||||
|
- ✅ Fix BD Linux settings: misma corrección de ruta en `settings_page.dart` → `_confirmarInicializarBd()`
|
||||||
|
- ✅ Error SQLite amigable: si falta `libsqlite3.so` muestra diálogo con instrucción `sudo apt install libsqlite3-dev`
|
||||||
|
- ✅ ApplicationId: `com.example.seguridad_electronica` → `net.siaxsystem.sentinelone`
|
||||||
|
- ✅ Login UX: foco automático al primer campo al abrir, click en card → foco, Enter → login
|
||||||
|
- ✅ Perfil conectado a BD: carga nombre real, edición con recálculo de iniciales, `sincronizado=false` al guardar
|
||||||
|
- ✅ Historial de sesiones: página nueva con tarjetas, badge "ACTIVA", duración calculada, pull to refresh
|
||||||
|
- ✅ Ayuda y soporte → navega a MensajeriaPage
|
||||||
|
- ✅ InicioPage: nombre real desde BD (fallback "Usuario"), click en avatar → tab PERFIL
|
||||||
|
- ✅ BD v2: tablas `clientes` y `suscripciones` con migración `onUpgrade`
|
||||||
|
- ✅ Modelos: `cliente.dart`, `suscripcion.dart` (con props calculadas `vencida` y `activa`)
|
||||||
|
- ✅ DAOs: `ClientesDao`, `SuscripcionesDao` (con `getProximasAVencer()`, `cambiarEstado()`)
|
||||||
|
- ✅ Seed v2: 3 clientes, 5 suscripciones con estados variados
|
||||||
|
- ✅ `DemoDataService`: singleton que carga datos de prueba en tablas operacionales desde `SettingsPage`
|
||||||
|
- ✅ InicioPage arranca vacía — eventos/logs solo aparecen tras cargar demo o sincronizar
|
||||||
|
- ✅ SettingsPage: botón "Datos de demostración" con diálogo de confirmación
|
||||||
|
- ✅ Seed limpiado — datos operacionales (alarmas, accesos, eventos, mensajes, sesiones) eliminados del seed
|
||||||
|
- ✅ Usuario seed renombrado a "Usuario Sistema" (iniciales US) — el usuario lo cambia desde Perfil
|
||||||
|
- ✅ MonitoreoAlarmaPage conectada a AlarmasDao — alarma más crítica, log real, contadores, pull-to-refresh
|
||||||
|
- ✅ MensajeriaPage conectada a MensajesDao — mensajes desde BD, envío persiste, botones pánico/soporte también
|
||||||
|
- ✅ ControlAccesoPage conectada a AccesosDao — registro real con JOIN a usuarios y puertas, pull-to-refresh
|
||||||
|
- ✅ AlarmasDao: contarResueltasUltimas24h, getActivasConZona, getAllConZona
|
||||||
|
- ✅ AccesosDao: getRecientesConDetalle (JOIN usuarios + puertas)
|
||||||
|
- ✅ LlamadaPage: pantalla fullscreen de llamada simulada, pulso animado, auto-conexión 5s, cronómetro, colgar
|
||||||
|
- ✅ ConectarProveedorPage: onboarding para URL/usuario/contraseña del proveedor, accesible desde Configuración
|
||||||
|
- ✅ Settings: botón "Cambiar proveedor de servicios" navega a ConectarProveedorPage
|
||||||
|
- ✅ DemoDataService: datos completos con todos los tipos — alarmas(10), accesos(8), mensajes(11), eventos(9)
|
||||||
|
- ✅ Foto de perfil: file_picker, columna foto_path BD v3, muestra imagen o iniciales como fallback
|
||||||
|
- ✅ ConectarProveedorPage: botón X (Icons.close) en AppBar para volver a Configuración sin perderse
|
||||||
|
- ✅ MensajeriaPage: botones Pánico y Soporte rediseñados como chips compactos horizontales (icono + label + mini-botón)
|
||||||
|
|
||||||
|
## Roadmap de autenticación (Login)
|
||||||
|
|
||||||
|
### Estado actual
|
||||||
|
- PIN local validado contra hash SHA-256 en `SharedPreferences`
|
||||||
|
- PIN inicial: `123456` (el usuario debe cambiarlo)
|
||||||
|
- No depende de SQLite ni plugins nativos — funciona en todas las plataformas
|
||||||
|
|
||||||
|
### Próximas mejoras (en orden sugerido)
|
||||||
|
|
||||||
|
#### 1. Cambio de PIN (`pages/seguridad_page.dart`) ✅ IMPLEMENTADO
|
||||||
|
- Formulario: PIN actual → nuevo PIN → confirmar
|
||||||
|
- Guarda el nuevo hash en `SharedPreferences` bajo `local_pin_hash`
|
||||||
|
|
||||||
|
#### 2. Auto-login (checkbox en pantalla de login)
|
||||||
|
- Checkbox "Recordar acceso en este dispositivo"
|
||||||
|
- Si está marcado: guarda flag `autologin = true` en SharedPreferences
|
||||||
|
- Al abrir la app: si `autologin = true` → salta directo a `MainPage`
|
||||||
|
|
||||||
|
#### 3. Biometría (futuro — Android/iOS)
|
||||||
|
- Paquete: `local_auth` (Flutter oficial)
|
||||||
|
- Flujo: pantalla de login muestra ícono de huella/Face ID además del PIN
|
||||||
|
- Solo disponible en móvil — en desktop mantiene solo PIN
|
||||||
|
- Al autenticarse con biometría: mismo flujo que PIN correcto (sin tocar SharedPreferences)
|
||||||
|
- Activar/desactivar desde `settings_page.dart`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Decisiones pendientes
|
||||||
|
|
||||||
|
- [ ] ¿RegisterPage usa PIN o email+contraseña? (afecta diseño y tabla `usuarios`)
|
||||||
|
- [ ] ¿El registro de usuarios en ControlAcceso es solo para nivel 3+?
|
||||||
|
- [ ] ¿Backend propio o SQLite local permanente?
|
||||||
|
- [ ] ¿Cuándo activar el checkbox de auto-login? (¿después del primer login exitoso o siempre visible?)
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# ideas.md — Ideas y posibilidades
|
||||||
|
|
||||||
|
> Especulativo — "podría ser interesante si...". Sin compromiso.
|
||||||
|
> Cuando una idea se aprueba y se decide que debe hacerse, moverla a `objetivos.md`.
|
||||||
|
> Cuando una idea pasa directamente a ejecución, moverla a `proyecto_memoria.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ideas pendientes
|
||||||
|
|
||||||
|
### Notificaciones push de alarma vía sigma-robot (WhatsApp)
|
||||||
|
Cuando una alarma activa supere severidad 4, enviar mensaje WhatsApp al supervisor vía
|
||||||
|
`sigma-robot` (`POST https://sigma-bot.telcotronics.com/api/meta/enviar_mensaje`).
|
||||||
|
Requiere que el `Sincronizador` esté activo y que la app tenga conectividad.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Biometría en LoginPage (Android/iOS)
|
||||||
|
Agregar huella/Face ID como alternativa al PIN usando el paquete `local_auth`.
|
||||||
|
- Solo disponible en móvil — desktop mantiene solo PIN
|
||||||
|
- Activar/desactivar desde SettingsPage
|
||||||
|
- Al autenticarse: mismo flujo que PIN correcto
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Dashboard táctico en tiempo real
|
||||||
|
Conectar la vista táctica de MonitoreoAlarmaPage a un WebSocket del backend del proveedor
|
||||||
|
para recibir eventos de alarma en tiempo real sin polling.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Modo multicámara
|
||||||
|
Mostrar feeds de cámaras Hikvision en ControlAccesoPage via `API_CENTINEL_SECURITY` (cuando
|
||||||
|
el hardware esté disponible). Reemplaza la cámara simulada actual.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Reportes de turno en PDF
|
||||||
|
Al cerrar sesión, generar un PDF con el resumen del turno: alarmas gestionadas, accesos
|
||||||
|
autorizados, mensajes enviados, duración. Exportar o enviar por email vía SMTP del ecosistema.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ideas en borrador
|
||||||
|
|
||||||
|
- Modo oscuro/claro configurable (actualmente solo dark theme)
|
||||||
|
- Widget Android de alarmas activas (sin abrir la app)
|
||||||
|
- Escáner QR para registrar usuarios de acceso en ControlAccesoPage
|
||||||
|
- Notificación de alarma con sonido diferente según tipo (ya hay archivos de audio en `recursos/`)
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,56 @@
|
|||||||
|
# objetivos.md — Objetivos del proyecto
|
||||||
|
|
||||||
|
> Cosas que deben implementarse o cumplirse, sin importar cuándo.
|
||||||
|
> Describen QUÉ — no cómo. El cómo va en proyecto_memoria.md cuando se ejecuta.
|
||||||
|
>
|
||||||
|
> Flujo: ideas.md → objetivos.md → (en ejecución) → proyecto_memoria.md
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pendientes
|
||||||
|
|
||||||
|
| # | Objetivo | Origen | Prioridad |
|
||||||
|
|---|----------|--------|-----------|
|
||||||
|
| 1 | Probar y activar flujo de login real: WebControl → `apiKey + db_tenant` → Centinel headers | pablinux | **Alta** |
|
||||||
|
| 2 | `Sincronizador` — activar pull de alarmas, zonas y puertas desde `api.telcotronics.com` hacia SQLite | pablinux | **Alta** |
|
||||||
|
| 3 | `RegisterPage` → aplicar AppColors, appHeadline, appLabel | pablinux | Media |
|
||||||
|
| 4 | `SettingsPage` → completar opciones y aplicar estilos del sistema | pablinux | Media |
|
||||||
|
| 5 | `desplegar.sh` → compilar APK + tar.gz Linux + subir a WebControlSigma CLI Sync | pablinux | Media |
|
||||||
|
| 6 | Registrar `centinel_device_id` en `configuracion` al vincular dispositivo Hikvision | pablinux | Media |
|
||||||
|
| 7 | `ControlAccesoPage` → apertura remota de puertas vía Centinel (requiere hardware) | pablinux | Baja |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## En curso
|
||||||
|
|
||||||
|
| # | Objetivo | Iniciado |
|
||||||
|
|---|----------|----------|
|
||||||
|
| — | — | — |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Completados
|
||||||
|
|
||||||
|
| Fecha | Objetivo | Notas |
|
||||||
|
|---|---|---|
|
||||||
|
| Sesión 1 | Login PIN local con SHA-256 | Auto-avance, Enter, foco automático |
|
||||||
|
| Sesión 1 | MainPage con nav de 4 tabs | IndexedStack |
|
||||||
|
| Sesión 2 | InicioPage con banner slider, métricas y log de eventos | |
|
||||||
|
| Sesión 2 | MonitoreoAlarmaPage con animaciones | |
|
||||||
|
| Sesión 2 | ControlAccesoPage con toggle puertas | |
|
||||||
|
| Sesión 3 | BD SQLite offline-first (14 tablas, 14 DAOs, 12 modelos) | Versión final v3 |
|
||||||
|
| Sesión 3 | Fix Linux: scroll + SQLite + ruta BD | |
|
||||||
|
| Sesión 4 | Cambio de PIN (SeguridadPage) | |
|
||||||
|
| Sesión 4 | HistorialSesionesPage | |
|
||||||
|
| Sesión 4 | LoginPage UX: foco automático, Enter, click en card | |
|
||||||
|
| Sesión 5 | MensajeríaPage conectada a BD | |
|
||||||
|
| Sesión 5 | LlamadaPage fullscreen | |
|
||||||
|
| Sesión 5 | DemoDataService | |
|
||||||
|
| Sesión 5 | ConectarProveedorPage | |
|
||||||
|
| Sesión 6 | Foto de perfil + BD v3 | |
|
||||||
|
| Sesión 7 | Chips compactos Pánico/Soporte en MensajeríaPage | |
|
||||||
|
| Sesión 8 | AlarmasPage — tabs ACTIVAS/HISTORIAL, filtros, acciones | |
|
||||||
|
| Sesión 8 | Migración plan_proyecto.md → esquema de agentes | |
|
||||||
|
| Sesión 9 | Botones Pánico/Soporte → insertan evento en tabla `eventos` (no mensaje de chat) | PÁNICO: diálogo de confirmación + evento tipo alerta. SOPORTE: evento tipo notificacion + abre LlamadaPage |
|
||||||
|
| Sesión 9 | ControlAccesoPage → FAB + RegistrarUsuarioPage + sección Usuarios con Acceso | Formulario con nombre, PIN, nivel (N1-N5), áreas (chips de zonas), fechas inicio/fin |
|
||||||
|
| Sesión 9 | Backend `API_CENTINEL_SECURITY` disponible en `https://api.telcotronics.com` | API Key dev: `dev-api-key-123456`. Endpoints: dispositivos, acceso, empleados, biometría, alarmas, sync-queue |
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# proyecto_errores.md — Registro de errores
|
||||||
|
|
||||||
|
> Cada error relevante durante desarrollo o producción.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Plantilla
|
||||||
|
|
||||||
|
### [FECHA] — [Título corto]
|
||||||
|
- **Síntoma:** [qué fallaba]
|
||||||
|
- **Causa raíz:** [por qué ocurrió]
|
||||||
|
- **Solución:** [qué se cambió]
|
||||||
|
- **Estado:** ✅ Resuelto | 🔧 En curso | ⏳ Pendiente
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Errores registrados
|
||||||
|
|
||||||
|
### Sesión 3 — Scroll conflictuaba en Linux desktop
|
||||||
|
- **Síntoma:** Al usar la app en Linux desktop, el scroll interno de las páginas no funcionaba o saltaba.
|
||||||
|
- **Causa raíz:** `SingleChildScrollView` sin `primary: false` dentro de un `IndexedStack` — Flutter interpreta que el scroll primario es el de la página contenedora.
|
||||||
|
- **Solución:** Agregar `primary: false` a todos los `SingleChildScrollView` que viven dentro del `IndexedStack` de `MainPage`.
|
||||||
|
- **Estado:** ✅ Resuelto
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Sesión 3 — Crash al inicializar BD en Linux
|
||||||
|
- **Síntoma:** La app compilaba pero crasheaba al intentar abrir la BD SQLite en Linux desktop.
|
||||||
|
- **Causa raíz:** `sqflite` requiere `libsqlite3.so` — el symlink solo lo provee el paquete `libsqlite3-dev`, no `libsqlite3-0`.
|
||||||
|
- **Solución:**
|
||||||
|
1. `sudo apt install libsqlite3-dev` en la máquina de desarrollo.
|
||||||
|
2. Usar `sqflite_common_ffi` con detección automática de plataforma en `database_helper.dart`.
|
||||||
|
3. Mostrar diálogo amigable si falta la librería (`settings_page.dart` → `_mostrarErrorSqlite()`).
|
||||||
|
- **Estado:** ✅ Resuelto
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Sesión 3 — Ruta de BD impredecible en Linux
|
||||||
|
- **Síntoma:** La BD se creaba en rutas distintas según desde dónde se lanzaba la app (`Directory.current` varía).
|
||||||
|
- **Causa raíz:** Uso de `Directory.current` como base para la ruta de la BD.
|
||||||
|
- **Solución:** Fijar ruta a `~/.local/share/sentinel_one/sentinel_one.db` (estándar XDG). Corrección aplicada en `database_helper.dart` y en `settings_page.dart → _confirmarInicializarBd()`.
|
||||||
|
- **Estado:** ✅ Resuelto
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### General — APIs de Flutter 3.x no disponibles
|
||||||
|
- **Síntoma:** Errores de compilación al usar APIs modernas de Flutter (p.ej. `MaterialState`, `ColorScheme.fromSeed`, etc.).
|
||||||
|
- **Causa raíz:** El proyecto usa Flutter 2.11.0 / Dart 2.17-beta. Las APIs de Flutter 3.x no existen.
|
||||||
|
- **Solución:** Consultar siempre este archivo y la documentación de Flutter 2.11 antes de usar cualquier API. Usar equivalentes de Flutter 2.x.
|
||||||
|
- **Estado:** ✅ Documentado — verificar antes de usar APIs nuevas
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# proyecto_estructura.md — Estructura del proyecto
|
||||||
|
|
||||||
|
> Árbol de archivos, rutas y dependencias entre módulos.
|
||||||
|
> Actualizar al agregar o mover archivos ("actualizar proyecto").
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Árbol de archivos
|
||||||
|
|
||||||
|
```
|
||||||
|
lib/
|
||||||
|
├── main.dart ← LoginPage (PIN SHA-256 + SharedPreferences)
|
||||||
|
├── main_page.dart ← Shell con header + bottom nav (IndexedStack)
|
||||||
|
├── theme.dart ← AppColors, appHeadline(), appLabel()
|
||||||
|
│
|
||||||
|
├── db/
|
||||||
|
│ ├── database_helper.dart ← Singleton SQLite v3, CREATE TABLE, seed, migrations
|
||||||
|
│ └── dao/
|
||||||
|
│ ├── alarmas_dao.dart
|
||||||
|
│ ├── accesos_dao.dart
|
||||||
|
│ ├── banners_dao.dart
|
||||||
|
│ ├── clientes_dao.dart
|
||||||
|
│ ├── configuracion_dao.dart
|
||||||
|
│ ├── eventos_dao.dart
|
||||||
|
│ ├── mensajes_dao.dart
|
||||||
|
│ ├── nodos_dao.dart
|
||||||
|
│ ├── puertas_dao.dart
|
||||||
|
│ ├── sesiones_dao.dart
|
||||||
|
│ ├── suscripciones_dao.dart
|
||||||
|
│ ├── sync_log_dao.dart
|
||||||
|
│ ├── usuarios_dao.dart
|
||||||
|
│ └── zonas_dao.dart
|
||||||
|
│
|
||||||
|
├── models/
|
||||||
|
│ ├── alarma.dart
|
||||||
|
│ ├── acceso.dart
|
||||||
|
│ ├── banner.dart (BannerItem)
|
||||||
|
│ ├── cliente.dart
|
||||||
|
│ ├── evento.dart
|
||||||
|
│ ├── mensaje.dart
|
||||||
|
│ ├── nodo.dart
|
||||||
|
│ ├── puerta.dart
|
||||||
|
│ ├── sesion.dart
|
||||||
|
│ ├── suscripcion.dart
|
||||||
|
│ ├── usuario.dart
|
||||||
|
│ └── zona.dart
|
||||||
|
│
|
||||||
|
├── pages/
|
||||||
|
│ ├── alarmas_page.dart ← AlarmasPage (tabs ACTIVAS/HISTORIAL + acciones)
|
||||||
|
│ ├── conectar_proveedor_page.dart ← OnBoarding URL/usuario/contraseña proveedor
|
||||||
|
│ ├── control_acceso_page.dart ← Toggle puertas + registro accesos
|
||||||
|
│ ├── historial_sesiones_page.dart ← Lista sesiones con badge ACTIVA
|
||||||
|
│ ├── inicio_page.dart ← Banner slider + métricas + log eventos
|
||||||
|
│ ├── llamada_page.dart ← Llamada simulada fullscreen
|
||||||
|
│ ├── mensageria_page.dart ← Chat + chips pánico/soporte
|
||||||
|
│ ├── monitoreo_alarma_page.dart ← Dashboard alarmas + botón RESPONDER→AlarmasPage
|
||||||
|
│ ├── perfil_usuario_page.dart ← Foto perfil + menú opciones
|
||||||
|
│ ├── register_page.dart ← 🔴 Sin AppColors/appHeadline/appLabel — pendiente
|
||||||
|
│ ├── registrar_usuario_page.dart ← Formulario nuevo usuario: nombre, PIN, nivel, áreas, fechas
|
||||||
|
│ ├── seguridad_page.dart ← Cambio de PIN con validación
|
||||||
|
│ └── settings_page.dart ← 🟡 Opciones básicas + demo + reset BD; sin estilos completos
|
||||||
|
│
|
||||||
|
├── services/
|
||||||
|
│ ├── api_auth_service.dart ← WebControl login → guarda apiKey+tenant; getCentinelHeaders() → x-api-key+x-database
|
||||||
|
│ ├── demo_data_service.dart ← Inserta datos de prueba en tablas operacionales
|
||||||
|
│ └── sincronizador.dart ← _centinelBase hardcodeado; pull/push pendientes de activar
|
||||||
|
│
|
||||||
|
├── widgets/
|
||||||
|
│ └── app_menu_button.dart ← Menú hamburguesa global
|
||||||
|
│
|
||||||
|
└── recursos/
|
||||||
|
├── alerta_fuego.mp3 ← Sonidos de alerta (sin trackear en git aún)
|
||||||
|
├── alerta_intrucion.mp3
|
||||||
|
├── alerta_intrucion2.mp3
|
||||||
|
├── tono_alarma_fuerte.wav
|
||||||
|
├── tono_alerta_suave.wav
|
||||||
|
├── tono_espera_llamada.wav
|
||||||
|
├── tono_llamda_espera.mp3
|
||||||
|
└── tono_notificacion.mp3
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Flujo de navegación
|
||||||
|
|
||||||
|
```
|
||||||
|
LoginPage
|
||||||
|
│
|
||||||
|
└── MainPage (IndexedStack)
|
||||||
|
├── [0] InicioPage
|
||||||
|
│ └── FAB pánico → MensajeríaPage
|
||||||
|
├── [1] ControlAccesoPage
|
||||||
|
├── [2] MonitoreoAlarmaPage
|
||||||
|
│ └── Botón RESPONDER → AlarmasPage
|
||||||
|
└── [3] PerfilUsuarioPage
|
||||||
|
├── Configuración → SettingsPage
|
||||||
|
│ └── "Cambiar proveedor" → ConectarProveedorPage
|
||||||
|
├── Seguridad → SeguridadPage
|
||||||
|
├── Historial → HistorialSesionesPage
|
||||||
|
└── Ayuda y soporte → MensajeríaPage
|
||||||
|
|
||||||
|
MensajeríaPage
|
||||||
|
└── Botón llamar → LlamadaPage
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tablas SQLite (v3)
|
||||||
|
|
||||||
|
| Tabla | DAO | Modelo | Notas |
|
||||||
|
|-------|-----|--------|-------|
|
||||||
|
| `usuarios` | UsuariosDao | Usuario | foto_path añadido en v3 |
|
||||||
|
| `zonas` | ZonasDao | Zona | |
|
||||||
|
| `nodos` | NodosDao | Nodo | |
|
||||||
|
| `puertas` | PuertasDao | Puerta | |
|
||||||
|
| `alarmas` | AlarmasDao | Alarma | getActivasConZona, getHistorialConZona, escalar |
|
||||||
|
| `accesos` | AccesosDao | Acceso | getRecientesConDetalle (JOIN) |
|
||||||
|
| `eventos` | EventosDao | Evento | |
|
||||||
|
| `mensajes` | MensajesDao | Mensaje | |
|
||||||
|
| `banners` | BannersDao | BannerItem | |
|
||||||
|
| `sesiones` | SesionesDao | Sesion | |
|
||||||
|
| `clientes` | ClientesDao | Cliente | getProximasAVencer |
|
||||||
|
| `suscripciones` | SuscripcionesDao | Suscripcion | cambiarEstado |
|
||||||
|
| `sync_log` | SyncLogDao | — | |
|
||||||
|
| `configuracion` | ConfiguracionDao | — | api_base_url, api_token |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencias entre módulos
|
||||||
|
|
||||||
|
```
|
||||||
|
LoginPage
|
||||||
|
└── SharedPreferences (local_pin_hash)
|
||||||
|
|
||||||
|
MainPage
|
||||||
|
└── IndexedStack → páginas no se destruyen al cambiar tab
|
||||||
|
|
||||||
|
InicioPage → EventosDao, BannersDao, ZonasDao
|
||||||
|
MonitoreoAlarmaPage → AlarmasDao (getActivasConZona, getAllConZona, contadores)
|
||||||
|
AlarmasPage → AlarmasDao (getActivasConZona, getHistorialConZona, resolver, silenciar, escalar)
|
||||||
|
ControlAccesoPage → PuertasDao, AccesosDao
|
||||||
|
MensajeríaPage → MensajesDao
|
||||||
|
PerfilUsuarioPage → UsuariosDao, SesionesDao, file_picker
|
||||||
|
HistorialSesionesPage → SesionesDao
|
||||||
|
SettingsPage → DemoDataService, ConfiguracionDao
|
||||||
|
|
||||||
|
DemoDataService → AlarmasDao, AccesosDao, MensajesDao, EventosDao, SesionesDao
|
||||||
|
ApiAuthService → ConfiguracionDao (api_token, api_base_url)
|
||||||
|
Sincronizador → ApiAuthService + todos los DAOs
|
||||||
|
```
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
# proyecto_memoria.md — Memoria técnica del proyecto
|
||||||
|
|
||||||
|
> Decisiones tomadas, razonamiento detrás de cada elección y estado actual.
|
||||||
|
> Actualizar con cada decisión técnica relevante.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Decisiones técnicas
|
||||||
|
|
||||||
|
| Fecha | Decisión | Razonamiento |
|
||||||
|
|---|---|---|
|
||||||
|
| Sesión 1 | Login abre en tab INICIO (índice 0), no en ACCESO | Flujo más natural para el operador al llegar al turno |
|
||||||
|
| Sesión 1 | Auth local con SHA-256 + SharedPreferences, sin SQLite | El login no depende de plugins nativos — funciona en todas las plataformas desde el día 1 |
|
||||||
|
| Sesión 1 | PIN inicial `123456` hardcoded como fallback | Permite primera ejecución sin configuración previa |
|
||||||
|
| Sesión 2 | ALARMAS tab → MonitoreoAlarmaPage (renombrado desde DashboardPage) | Nombre más preciso del rol de la pantalla |
|
||||||
|
| Sesión 2 | Mensajería accesible desde FAB de pánico (no en nav) | El chat con la central no es una función de navegación frecuente |
|
||||||
|
| Sesión 3 | Arquitectura offline-first: páginas solo leen SQLite, nunca API directa | Funciona sin conectividad; sincronización delegada a Sincronizador |
|
||||||
|
| Sesión 3 | `primary: false` en todos los `SingleChildScrollView` del `IndexedStack` | Fix Linux desktop: sin esto el scroll interno conflictuaba con el scroll del shell |
|
||||||
|
| Sesión 3 | `sqflite_common_ffi` con detección automática de plataforma | Mismo código corre en Android y Linux desktop |
|
||||||
|
| Sesión 3 | BD en `~/.local/share/sentinel_one/` en Linux | Estándar XDG; `Directory.current` era impredecible en distintos entornos |
|
||||||
|
| Sesión 4 | ApplicationId `net.siaxsystem.sentinelone` (antes `com.example`) | Identidad real del producto en los stores |
|
||||||
|
| Sesión 4 | Cambio de PIN en página dedicada (SeguridadPage) | Evita contaminar PerfilUsuarioPage con lógica de seguridad |
|
||||||
|
| Sesión 5 | Cerrar sesión con diálogo de confirmación | Evita cierres accidentales de turno |
|
||||||
|
| Sesión 5 | InicioPage arranca vacía — eventos solo aparecen tras cargar demo o sincronizar | Honestidad: no mostrar datos falsos mezclados con seed |
|
||||||
|
| Sesión 5 | Seed limpiado de datos operacionales (alarmas, accesos, eventos, mensajes, sesiones) | Solo `DemoDataService` los carga; el seed solo pone datos de configuración |
|
||||||
|
| Sesión 6 | Foto de perfil con `file_picker` + columna `foto_path` en BD v3 | Permite personalización real sin depender de cámara |
|
||||||
|
| Sesión 6 | ConectarProveedorPage con botón X (Icons.close) en AppBar | El usuario no debe perderse navegando hacia atrás sin querer |
|
||||||
|
| Sesión 7 | Botones Pánico/Soporte como chips compactos horizontales | Más espacio para el chat; los botones de acción deben ser claros pero no dominantes |
|
||||||
|
| Sesión 8 | AlarmasPage separada de MonitoreoAlarmaPage | MonitoreoAlarmaPage = dashboard/overview; AlarmasPage = gestión detallada con filtros y acciones |
|
||||||
|
| Sesión 8 | Escalar solo incrementa severidad local + marca sincronizado=0 | Sin URL de API real, la notificación a la central es responsabilidad del Sincronizador futuro |
|
||||||
|
| Sesión 9 | PÁNICO → evento tipo `alerta` en tabla `eventos` con diálogo de confirmación | El mensaje de chat era incorrecto — el registro debe quedar en la tabla de eventos para auditoria y sincronización |
|
||||||
|
| Sesión 9 | SOPORTE → evento tipo `notificacion` + abre LlamadaPage inmediatamente | El evento queda registrado antes de abrir la pantalla de llamada |
|
||||||
|
| Sesión 9 | `EventosDao.registrar()` inserta sin id — deja que SQLite asigne rowid | El modelo `Evento` requiere id obligatorio; para inserciones nuevas se usa el método registrar() con mapa directo |
|
||||||
|
| Sesión 9 | RegistrarUsuarioPage — Dart 2.17: records `(id:, label:)` no existen | Usar listas paralelas de constantes en vez de records (Dart 3+) |
|
||||||
|
| Sesión 9 | Backend disponible: `https://api.telcotronics.com` · API Key: `dev-api-key-123456` · BD: `security_db` | Bloqueado estaba pendiente de URL; ahora puede conectarse ApiAuthService |
|
||||||
|
| Sesión 9 | Auth via WebControl (`api.siax-system.net/api/auth/login`) → recibe `{ jwt, apiKey, db_tenant }` | Mismo patrón que sistema-gimnasio. WebControl es dueño de las keys; Centinel solo las valida |
|
||||||
|
| Sesión 9 | Todas las llamadas a Centinel usan `x-api-key + x-database` (no Bearer JWT) | JWT es de WebControl; Centinel usa API key en header — `getCentinelHeaders()` encapsula esto |
|
||||||
|
| Sesión 9 | `ConectarProveedorPage` sin campo URL — WebControl URL hardcodeada en `ApiAuthService` | El operador solo ingresa usuario + contraseña; la app autentica y guarda apiKey + tenant automáticamente |
|
||||||
|
| Sesión 9 | `Sincronizador._centinelBase` hardcodeado a `https://api.telcotronics.com` | Centinel URL es infraestructura fija del ecosistema, no configurable por cliente |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Arquitectura de datos
|
||||||
|
|
||||||
|
```
|
||||||
|
Páginas ──────► DAOs ──────► SQLite (local)
|
||||||
|
▲
|
||||||
|
Sincronizador (pendiente)
|
||||||
|
▲
|
||||||
|
ApiAuthService (JWT)
|
||||||
|
│
|
||||||
|
API del proveedor
|
||||||
|
```
|
||||||
|
|
||||||
|
**Principio:** SQLite es la única fuente de verdad para la UI. El servidor nunca se consulta directamente desde las páginas.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Estado actual (sesión 9 — pausado)
|
||||||
|
|
||||||
|
### UI: 15/15 módulos completos y funcionales
|
||||||
|
- `InicioPage` — banner slider, métricas (zonas/nodos/accesos/usuarios), log de eventos
|
||||||
|
- `MonitoreoAlarmaPage` — dashboard alarmas con animaciones, botón RESPONDER → AlarmasPage
|
||||||
|
- `AlarmasPage` — tabs ACTIVAS/HISTORIAL, filtros, acciones (resolver/silenciar/escalar)
|
||||||
|
- `ControlAccesoPage` — toggle puertas + sección usuarios con acceso + FAB → RegistrarUsuarioPage
|
||||||
|
- `RegistrarUsuarioPage` — nombre, PIN SHA-256, nivel N1-N5 (chips), áreas (zonas), fechas vigencia
|
||||||
|
- `MensajeríaPage` — chat + chips compactos PÁNICO/SOPORTE, ambos insertan en tabla `eventos`
|
||||||
|
- `LlamadaPage` — fullscreen llamada simulada
|
||||||
|
- `PerfilUsuarioPage` — foto de perfil (file_picker), nombre editable, menú de opciones
|
||||||
|
- `SeguridadPage` — cambio de PIN con validación
|
||||||
|
- `HistorialSesionesPage` — lista sesiones con badge ACTIVA
|
||||||
|
- `SettingsPage` — opciones básicas + DemoData + reset BD (🟡 sin estilo completo del sistema)
|
||||||
|
- `ConectarProveedorPage` — login usuario/contraseña WebControl (sin campo URL — hardcodeado)
|
||||||
|
- `LoginPage` — PIN SHA-256, auto-avance, Enter, foco automático
|
||||||
|
- `RegisterPage` — registro inicial (🔴 sin estilos AppColors/appHeadline/appLabel)
|
||||||
|
|
||||||
|
### Backend
|
||||||
|
- `API_CENTINEL_SECURITY` disponible en `https://api.telcotronics.com`
|
||||||
|
- API Key dev: `dev-api-key-123456` · BD autorizada: `security_db`
|
||||||
|
- `ApiAuthService` reescrito: WebControl login → guarda `jwt + apiKey + db_tenant` → `getCentinelHeaders()` devuelve `x-api-key + x-database`
|
||||||
|
- `Sincronizador` estructura lista con `_centinelBase` hardcodeado — pull/push pendientes de activar
|
||||||
|
- `ConectarProveedorPage` simplificada: solo usuario + contraseña, URL hardcodeada en `ApiAuthService`
|
||||||
|
|
||||||
|
### BD
|
||||||
|
- SQLite v3 · 14 tablas · 14 DAOs · 12 modelos · ruta `~/.local/share/sentinel_one/`
|
||||||
|
- Seed limpio: solo configuración y datos de referencia (zonas, puertas, clientes, suscripciones)
|
||||||
|
- `DemoDataService`: carga datos operacionales (alarmas, accesos, mensajes, eventos, sesiones)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pendientes (por prioridad)
|
||||||
|
|
||||||
|
| Prioridad | Tarea |
|
||||||
|
|-----------|-------|
|
||||||
|
| **Alta** | Probar flujo de login real: `api.siax-system.net/api/auth/login` → `apiKey + db_tenant` → Centinel |
|
||||||
|
| **Alta** | Activar `Sincronizador`: pull de alarmas/zonas/puertas desde Centinel → cache SQLite |
|
||||||
|
| **Media** | Registrar `centinel_device_id` en `configuracion` al vincular dispositivo Hikvision |
|
||||||
|
| **Media** | `_pushUsuariosPendientes()` en Sincronizador: requiere `centinel_device_id` configurado |
|
||||||
|
| **Media** | `RegisterPage` → aplicar AppColors, appHeadline, appLabel |
|
||||||
|
| **Media** | `SettingsPage` → completar opciones y aplicar estilos del sistema |
|
||||||
|
| **Media** | `desplegar.sh` → compilar APK + tar.gz Linux + subir a WebControlSigma CLI Sync |
|
||||||
|
| **Baja** | `ControlAccesoPage` → apertura remota real vía Centinel (requiere hardware Hikvision) |
|
||||||
@@ -57,7 +57,19 @@ lib/
|
|||||||
│ ├── perfil_usuario_page.dart # Perfil del operador
|
│ ├── perfil_usuario_page.dart # Perfil del operador
|
||||||
│ ├── register_page.dart # Registro de nuevo usuario
|
│ ├── register_page.dart # Registro de nuevo usuario
|
||||||
│ ├── settings_page.dart # Configuración del sistema
|
│ ├── settings_page.dart # Configuración del sistema
|
||||||
│ └── alarmas_page.dart # (Pendiente) Página de alarmas dedicada
|
│ ├── alarmas_page.dart # Alarmas con tabs ACTIVAS/HISTORIAL + acciones
|
||||||
|
│ ├── llamada_page.dart # Llamada simulada fullscreen
|
||||||
|
│ ├── conectar_proveedor_page.dart # Onboarding proveedor
|
||||||
|
│ ├── seguridad_page.dart # Cambio de PIN
|
||||||
|
│ └── historial_sesiones_page.dart # Historial de sesiones
|
||||||
|
├── db/
|
||||||
|
│ ├── database_helper.dart # SQLite v3 — 14 tablas
|
||||||
|
│ └── dao/ # 14 DAOs (CRUD + métodos específicos)
|
||||||
|
├── models/ # 12 modelos con fromMap/toMap
|
||||||
|
└── services/
|
||||||
|
├── api_auth_service.dart # Auth con backend proveedor (estructura lista)
|
||||||
|
├── sincronizador.dart # Sync API→SQLite (estructura lista)
|
||||||
|
└── demo_data_service.dart # Datos de prueba
|
||||||
└── widgets/
|
└── widgets/
|
||||||
└── app_menu_button.dart # Menú contextual global (⋮)
|
└── app_menu_button.dart # Menú contextual global (⋮)
|
||||||
```
|
```
|
||||||
@@ -154,25 +166,26 @@ flutter build linux --release
|
|||||||
|
|
||||||
### Credenciales de prueba
|
### Credenciales de prueba
|
||||||
|
|
||||||
> La autenticación es visual por ahora (cualquier PIN de 4+ dígitos da acceso).
|
**PIN inicial:** `123456`
|
||||||
> Próximamente validación real contra base de datos SQLite.
|
|
||||||
|
El PIN se valida contra un hash SHA-256 en SharedPreferences. Cambiable desde Perfil → Seguridad.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
|
|
||||||
### En progreso
|
### Completado
|
||||||
- [ ] Página de alarmas dedicada (`alarmas_page.dart`)
|
- [x] BD SQLite offline-first (14 tablas, 14 DAOs, 12 modelos)
|
||||||
- [ ] Registro de usuarios con acceso por tiempo y áreas en Control de Acceso
|
- [x] Auth real con PIN SHA-256 + SharedPreferences
|
||||||
- [ ] Rediseño de RegisterPage y SettingsPage con tema oscuro
|
- [x] Página de alarmas dedicada con tabs, filtros y acciones
|
||||||
|
- [x] Todas las páginas conectadas a BD
|
||||||
|
|
||||||
### Próximas versiones
|
### Pendiente
|
||||||
- [ ] Integración SQLite con `sqflite` para persistencia local
|
- [ ] Botones Pánico/Soporte → insertar en tabla `eventos`
|
||||||
- Tablas: `usuarios`, `alarmas`, `accesos`, `mensajes`, `configuracion`
|
- [ ] Registro de usuarios en Control de Acceso (áreas + fechas)
|
||||||
- Autenticación real con PIN hasheado
|
- [ ] Rediseño de RegisterPage y SettingsPage
|
||||||
- [ ] Notificaciones push para alarmas críticas
|
- [ ] Integración con backend del proveedor de seguridad
|
||||||
- [ ] Actualización a Dart 3.x / Flutter 3.x
|
- [ ] `desplegar.sh` → publicar APK + Linux en WebControlSigma
|
||||||
- [ ] Conexión a backend / API REST
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,256 @@
|
|||||||
|
# agents.md — Punto de entrada del proyecto
|
||||||
|
|
||||||
|
> **Reglas:**
|
||||||
|
> - Este archivo es el eslabón más importante. Leerlo siempre antes de cualquier tarea.
|
||||||
|
> - Cada cambio significativo debe reflejarse en este archivo y en los demás archivos del índice.
|
||||||
|
> - Debe ser técnico, claro y detallado para que cualquier humano, agente o IA lo entienda sin explicaciones previas.
|
||||||
|
> - **Cuando se diga "actualizar proyecto":** hacer commit de los cambios pendientes, actualizar `agents.md` y `.agente/proyecto_estructura.md` con el árbol de archivos actual.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Antecedentes
|
||||||
|
|
||||||
|
App de seguridad electrónica para operadores y guardias que gestionan sistemas de alarma, acceso físico y comunicación con la central de monitoreo. Nace como producto independiente del ecosistema SIGMA/Telcotronics — no comparte BD ni APIs con el ERP, aunque podrá consumir `API_CENTINEL_SECURITY` cuando se integre el hardware Hikvision real.
|
||||||
|
|
||||||
|
El nombre comercial del producto es **SENTINEL ONE**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Objetivo general
|
||||||
|
|
||||||
|
Proveer a operadores de seguridad una app móvil/desktop offline-first para gestionar en tiempo real: alarmas por zona, acceso a puertas físicas, mensajería con la central y sesiones de turno.
|
||||||
|
|
||||||
|
1. Monitorear alarmas activas por zona y sensor con niveles de severidad 1–5.
|
||||||
|
2. Controlar puertas (lock/unlock) y registrar accesos.
|
||||||
|
3. Comunicarse con la central vía chat + botones de pánico/soporte.
|
||||||
|
4. Sincronizar con el backend del proveedor cuando esté disponible (offline-first).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stack técnico
|
||||||
|
|
||||||
|
| Componente | Tecnología |
|
||||||
|
|---|---|
|
||||||
|
| Lenguaje | Dart 2.17.0-beta |
|
||||||
|
| Framework | Flutter 2.11.0 |
|
||||||
|
| UI | Material 3 · Dark Theme · Google Fonts (Manrope + Inter) |
|
||||||
|
| BD local | SQLite v3 — sqflite + sqflite_common_ffi (Linux/Desktop) |
|
||||||
|
| Auth local | SHA-256 PIN + SharedPreferences |
|
||||||
|
| Plataformas | Android · iOS · Linux desktop (Ubuntu Touch) |
|
||||||
|
| App ID | `net.siaxsystem.sentinelone` |
|
||||||
|
|
||||||
|
> ⚠️ Flutter 2.11 / Dart 2.17-beta: APIs de Flutter 3.x no existen.
|
||||||
|
> Antes de usar cualquier API nueva consultar `.agente/proyecto_errores.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Módulos del sistema
|
||||||
|
|
||||||
|
### Login
|
||||||
|
**Estado: ✅ Completo**
|
||||||
|
PIN 4–6 dígitos, cajas animadas, auto-avance, Enter dispara login, foco automático.
|
||||||
|
Auth local via SHA-256 → SharedPreferences (`local_pin_hash`). PIN por defecto: `123456`.
|
||||||
|
|
||||||
|
### MainPage + navegación
|
||||||
|
**Estado: ✅ Completo**
|
||||||
|
Header SENTINEL ONE + bottom nav (INICIO · ACCESO · ALARMAS · PERFIL). `IndexedStack`.
|
||||||
|
|
||||||
|
### InicioPage
|
||||||
|
**Estado: ✅ BD conectada**
|
||||||
|
Bienvenida con nombre real de BD, banner slider (PageView + auto-avance), métricas rápidas,
|
||||||
|
log de eventos desde `EventosDao`, FAB de pánico → MensajeríaPage.
|
||||||
|
|
||||||
|
### MonitoreoAlarmaPage (tab ALARMAS)
|
||||||
|
**Estado: ✅ BD conectada**
|
||||||
|
Alarma más crítica, contadores, registro de eventos, vista táctica animada.
|
||||||
|
Botón RESPONDER navega a AlarmasPage.
|
||||||
|
|
||||||
|
### AlarmasPage
|
||||||
|
**Estado: ✅ Completo** *(sesión 8)*
|
||||||
|
Tab ACTIVAS: chips filtro por tipo, cards con borde de color por severidad, acciones Responder/Silenciar/Escalar.
|
||||||
|
Tab HISTORIAL: lista compacta de resueltas/silenciadas. Pull to refresh.
|
||||||
|
|
||||||
|
### ControlAccesoPage (tab ACCESO)
|
||||||
|
**Estado: ✅ BD conectada**
|
||||||
|
Toggle lock/unlock por puerta (3 puertas), registro de accesos con JOIN usuarios+puertas.
|
||||||
|
**Pendiente:** FAB para registrar nuevos usuarios con áreas y fechas.
|
||||||
|
|
||||||
|
### MensajeríaPage
|
||||||
|
**Estado: ✅ BD conectada**
|
||||||
|
Chat WhatsApp-style desde BD, botones Pánico/Soporte como chips compactos.
|
||||||
|
**Pendiente:** Pánico debe insertar en tabla `eventos` (no mensaje de chat).
|
||||||
|
|
||||||
|
### PerfilUsuarioPage (tab PERFIL)
|
||||||
|
**Estado: ✅ BD + foto perfil**
|
||||||
|
Foto seleccionable desde archivo, edición de nombre, badge nivel, menú de opciones.
|
||||||
|
|
||||||
|
### LlamadaPage
|
||||||
|
**Estado: ✅ Completo**
|
||||||
|
Pantalla fullscreen de llamada simulada, pulso animado, auto-conexión 5s, cronómetro, colgar.
|
||||||
|
|
||||||
|
### ConectarProveedorPage
|
||||||
|
**Estado: ✅ Completo**
|
||||||
|
Onboarding para URL/usuario/contraseña del proveedor. Accesible desde Configuración.
|
||||||
|
|
||||||
|
### SeguridadPage
|
||||||
|
**Estado: ✅ Completo**
|
||||||
|
Cambio de PIN con validación del actual, confirmación de nuevo PIN, SHA-256.
|
||||||
|
|
||||||
|
### HistorialSesionesPage
|
||||||
|
**Estado: ✅ Completo**
|
||||||
|
Tarjetas de sesiones, badge "ACTIVA", duración calculada, pull to refresh.
|
||||||
|
|
||||||
|
### RegisterPage
|
||||||
|
**Estado: 🔴 Sin estilo del sistema**
|
||||||
|
Funcional pero usa Material por defecto. Pendiente aplicar AppColors + appHeadline/appLabel.
|
||||||
|
|
||||||
|
### SettingsPage
|
||||||
|
**Estado: 🟡 Parcial**
|
||||||
|
Botón "Datos de demostración" operativo. Pendiente aplicar estilos y completar opciones.
|
||||||
|
|
||||||
|
### AlarmasPage (antiguo vacío)
|
||||||
|
**Estado: ✅ Completo** *(sesión 8)*
|
||||||
|
|
||||||
|
### BD SQLite v3
|
||||||
|
**Estado: ✅ Completo**
|
||||||
|
14 tablas, 14 DAOs, 12 modelos. Seed inicial (1 usuario, 6 zonas, 3 puertas, 3 banners).
|
||||||
|
DemoDataService carga datos de prueba (10 alarmas, 8 accesos, 11 mensajes, 9 eventos).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Infraestructura (referencia rápida)
|
||||||
|
|
||||||
|
> ⚠️ La infraestructura del ecosistema Telcotronics vive en **`mcp.telcotronics.net`** — 🔧 **en mantenimiento**.
|
||||||
|
> Fuente alternativa: `/home/pablinux/Projects/infraestructura.md`.
|
||||||
|
> No editar `.agente/infraestructura.md` directamente — ver protocolo de sincronización.
|
||||||
|
|
||||||
|
| Parámetro | Valor |
|
||||||
|
|---|---|
|
||||||
|
| Repositorio Git | `https://git.telcotronics.net/pablinux/seguridad_electronica.git` |
|
||||||
|
| Código local | `siax-amd (192.168.10.100)` — `/home/pablinux/Projects/flutter/seguridad_electronica` |
|
||||||
|
| Plataformas | Android · iOS · Linux desktop |
|
||||||
|
| App ID | `net.siaxsystem.sentinelone` |
|
||||||
|
| Servidor de producción | Sin servidor — APK/binario distribuido vía WebControlSigma |
|
||||||
|
| Dominio público | — |
|
||||||
|
| Puerto | — |
|
||||||
|
| BD local | SQLite v3 — `sentinel_one.db` (dispositivo) / `~/.local/share/sentinel_one/` (Linux) |
|
||||||
|
| API backend proveedor | Pendiente URL — `ApiAuthService` + `Sincronizador` estructurados |
|
||||||
|
| MCP ecosistema | `mcp.telcotronics.net` 🔧 en mantenimiento |
|
||||||
|
|
||||||
|
> Para el detalle completo del ecosistema ver `.agente/infraestructura.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Documentos del ecosistema (referencia)
|
||||||
|
|
||||||
|
| Documento | Descripción |
|
||||||
|
|---|---|
|
||||||
|
| `~/Projects/design-system.md` | Sistema de diseño unificado — colores, tipografía, componentes |
|
||||||
|
| `~/Projects/roadmap.md` | Hoja de ruta estratégica del ecosistema |
|
||||||
|
| `~/Projects/infraestructura.md` | Arquitectura de servidores, red y servicios |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Variables de entorno
|
||||||
|
|
||||||
|
No aplica — app móvil/desktop sin servidor propio. Configuración en BD local tabla `configuracion`:
|
||||||
|
|
||||||
|
| Clave | Descripción |
|
||||||
|
|---|---|
|
||||||
|
| `api_base_url` | URL del backend del proveedor (se configura en ConectarProveedorPage) |
|
||||||
|
| `api_token` | JWT del proveedor (gestionado por ApiAuthService) |
|
||||||
|
| `api_token_expiry` | Expiración del token |
|
||||||
|
| `notificaciones_activas` | `1` / `0` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Para arrancar en local
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Requisito Linux: libsqlite3
|
||||||
|
sudo apt install libsqlite3-dev
|
||||||
|
|
||||||
|
# Clonar y correr
|
||||||
|
git clone https://git.telcotronics.net/pablinux/seguridad_electronica.git
|
||||||
|
cd seguridad_electronica
|
||||||
|
flutter pub get
|
||||||
|
flutter run -d linux # desktop
|
||||||
|
flutter run -d <device_id> # Android
|
||||||
|
|
||||||
|
# PIN inicial: 123456
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Migraciones
|
||||||
|
|
||||||
|
No aplica (BD local SQLite). Las versiones del schema se gestionan en `DatabaseHelper.onUpgrade`:
|
||||||
|
|
||||||
|
| Versión | Cambio |
|
||||||
|
|---|---|
|
||||||
|
| v1 | Schema inicial — 12 tablas |
|
||||||
|
| v2 | + tablas `clientes` y `suscripciones` |
|
||||||
|
| v3 | + columna `foto_path` en `usuarios` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Índice de archivos del proyecto
|
||||||
|
|
||||||
|
```
|
||||||
|
seguridad_electronica/
|
||||||
|
├── README.md
|
||||||
|
├── agents.md ← LEER PRIMERO
|
||||||
|
├── solicituda_backend.md ← Endpoints pendientes al backend
|
||||||
|
├── plan_proyecto.md ← ARCHIVADO en .agente/archivo/
|
||||||
|
├── pubspec.yaml
|
||||||
|
├── lib/
|
||||||
|
│ ├── main.dart ← LoginPage
|
||||||
|
│ ├── main_page.dart ← Shell + nav
|
||||||
|
│ ├── theme.dart ← AppColors, appHeadline(), appLabel()
|
||||||
|
│ ├── db/
|
||||||
|
│ │ ├── database_helper.dart
|
||||||
|
│ │ └── dao/ (14 DAOs)
|
||||||
|
│ ├── models/ (12 modelos)
|
||||||
|
│ ├── pages/ (ver proyecto_estructura.md)
|
||||||
|
│ ├── services/
|
||||||
|
│ │ ├── api_auth_service.dart
|
||||||
|
│ │ ├── sincronizador.dart
|
||||||
|
│ │ └── demo_data_service.dart
|
||||||
|
│ ├── widgets/
|
||||||
|
│ │ └── app_menu_button.dart
|
||||||
|
│ └── recursos/ (audio)
|
||||||
|
└── .agente/
|
||||||
|
├── infraestructura.md ← Espejo del global
|
||||||
|
├── proyecto_estructura.md
|
||||||
|
├── proyecto_memoria.md
|
||||||
|
├── proyecto_errores.md
|
||||||
|
├── objetivos.md
|
||||||
|
├── ideas.md
|
||||||
|
└── archivo/
|
||||||
|
└── plan_proyecto_legacy.md
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Estado global del proyecto
|
||||||
|
|
||||||
|
| Módulo | Estado |
|
||||||
|
|---|---|
|
||||||
|
| Login PIN | ✅ Completo |
|
||||||
|
| MainPage + navegación | ✅ Completo |
|
||||||
|
| InicioPage | ✅ BD conectada |
|
||||||
|
| MonitoreoAlarmaPage | ✅ BD conectada |
|
||||||
|
| AlarmasPage | ✅ Completo |
|
||||||
|
| ControlAccesoPage | ✅ BD conectada |
|
||||||
|
| MensajeríaPage | ✅ BD conectada |
|
||||||
|
| PerfilUsuarioPage | ✅ BD + foto |
|
||||||
|
| LlamadaPage | ✅ Completo |
|
||||||
|
| ConectarProveedorPage | ✅ Completo |
|
||||||
|
| SeguridadPage | ✅ Completo |
|
||||||
|
| HistorialSesionesPage | ✅ Completo |
|
||||||
|
| BD SQLite v3 | ✅ Completo |
|
||||||
|
| RegisterPage | 🔴 Sin estilo |
|
||||||
|
| SettingsPage | 🟡 Parcial |
|
||||||
|
| Botones Pánico/Soporte → eventos | 🔴 Pendiente |
|
||||||
|
| ControlAcceso → registrar usuarios | 🔴 Pendiente |
|
||||||
|
| Integración API backend proveedor | 🔴 Pendiente |
|
||||||
@@ -0,0 +1,649 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import '../theme.dart';
|
||||||
|
import '../db/dao/alarmas_dao.dart';
|
||||||
|
|
||||||
|
class AlarmasPage extends StatefulWidget {
|
||||||
|
const AlarmasPage({Key? key}) : super(key: key);
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<AlarmasPage> createState() => _AlarmasPageState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _AlarmasPageState extends State<AlarmasPage>
|
||||||
|
with SingleTickerProviderStateMixin {
|
||||||
|
final _dao = AlarmasDao();
|
||||||
|
late final TabController _tab;
|
||||||
|
|
||||||
|
List<Map<String, dynamic>> _activas = [];
|
||||||
|
List<Map<String, dynamic>> _historial = [];
|
||||||
|
bool _cargando = true;
|
||||||
|
String? _filtroTipo; // null = todos
|
||||||
|
|
||||||
|
static const _tipos = ['intrusion', 'humo', 'movimiento', 'acceso'];
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_tab = TabController(length: 2, vsync: this);
|
||||||
|
_cargar();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_tab.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _cargar() async {
|
||||||
|
setState(() => _cargando = true);
|
||||||
|
try {
|
||||||
|
final activas = await _dao.getActivasConZona();
|
||||||
|
final historial = await _dao.getHistorialConZona();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_activas = activas;
|
||||||
|
_historial = historial;
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
if (mounted) setState(() => _cargando = false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
List<Map<String, dynamic>> get _activasFiltradas {
|
||||||
|
if (_filtroTipo == null) return _activas;
|
||||||
|
return _activas.where((a) => a['tipo'] == _filtroTipo).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
Color _sevColor(int sev) {
|
||||||
|
if (sev >= 5) return AppColors.error;
|
||||||
|
if (sev >= 4) return AppColors.tertiary;
|
||||||
|
if (sev >= 3) return AppColors.secondary;
|
||||||
|
if (sev >= 2) return AppColors.onSecondaryContainer;
|
||||||
|
return AppColors.outline;
|
||||||
|
}
|
||||||
|
|
||||||
|
IconData _tipoIcon(String tipo) {
|
||||||
|
switch (tipo) {
|
||||||
|
case 'intrusion': return Icons.warning_amber_rounded;
|
||||||
|
case 'humo': return Icons.local_fire_department;
|
||||||
|
case 'movimiento': return Icons.directions_run;
|
||||||
|
case 'acceso': return Icons.lock_open;
|
||||||
|
default: return Icons.notifications;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _tipoLabel(String tipo) {
|
||||||
|
switch (tipo) {
|
||||||
|
case 'intrusion': return 'INTRUSIÓN';
|
||||||
|
case 'humo': return 'HUMO';
|
||||||
|
case 'movimiento': return 'MOVIMIENTO';
|
||||||
|
case 'acceso': return 'ACCESO';
|
||||||
|
default: return tipo.toUpperCase();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _formatTs(String iso) {
|
||||||
|
try {
|
||||||
|
final dt = DateTime.parse(iso).toLocal();
|
||||||
|
final d = dt.day.toString().padLeft(2, '0');
|
||||||
|
final mo = dt.month.toString().padLeft(2, '0');
|
||||||
|
final h = dt.hour.toString().padLeft(2, '0');
|
||||||
|
final m = dt.minute.toString().padLeft(2, '0');
|
||||||
|
return '$d/$mo $h:$m';
|
||||||
|
} catch (_) {
|
||||||
|
return iso;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Color _estadoColor(String estado) {
|
||||||
|
switch (estado) {
|
||||||
|
case 'resuelta': return AppColors.primary;
|
||||||
|
case 'silenciada': return AppColors.outline;
|
||||||
|
default: return AppColors.error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _estadoLabel(String estado) {
|
||||||
|
switch (estado) {
|
||||||
|
case 'resuelta': return 'RESUELTA';
|
||||||
|
case 'silenciada': return 'SILENCIADA';
|
||||||
|
default: return estado.toUpperCase();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Acciones ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
Future<void> _responder(Map<String, dynamic> a) async {
|
||||||
|
final notasCtrl = TextEditingController();
|
||||||
|
final ok = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (_) => AlertDialog(
|
||||||
|
backgroundColor: AppColors.surfaceHigh,
|
||||||
|
title: Text('Responder alarma',
|
||||||
|
style: appHeadline(size: 16)),
|
||||||
|
content: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'${_tipoLabel(a['tipo'] as String)} · ${a['zona_nombre'] ?? 'Sin zona'}',
|
||||||
|
style: appLabel(size: 12),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
TextField(
|
||||||
|
controller: notasCtrl,
|
||||||
|
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||||
|
maxLines: 3,
|
||||||
|
decoration: InputDecoration(
|
||||||
|
hintText: 'Notas de resolución (opcional)',
|
||||||
|
hintStyle: appLabel(size: 12),
|
||||||
|
filled: true,
|
||||||
|
fillColor: AppColors.surfaceLowest,
|
||||||
|
border: OutlineInputBorder(
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
borderSide: BorderSide.none,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context, false),
|
||||||
|
child: Text('Cancelar', style: appLabel(size: 13, color: AppColors.outline)),
|
||||||
|
),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () => Navigator.pop(context, true),
|
||||||
|
style: ElevatedButton.styleFrom(
|
||||||
|
primary: AppColors.primary,
|
||||||
|
onPrimary: AppColors.surfaceLowest,
|
||||||
|
elevation: 0,
|
||||||
|
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||||
|
),
|
||||||
|
child: Text('Confirmar', style: appLabel(size: 13, weight: FontWeight.bold,
|
||||||
|
color: AppColors.surfaceLowest)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (ok == true && mounted) {
|
||||||
|
await _dao.resolver(a['id'] as int, 1, notas: notasCtrl.text.trim().isEmpty
|
||||||
|
? null : notasCtrl.text.trim());
|
||||||
|
_cargar();
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||||
|
content: Text('Alarma resuelta', style: appLabel(size: 13, color: AppColors.surfaceLowest)),
|
||||||
|
backgroundColor: AppColors.primary,
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _silenciar(Map<String, dynamic> a) async {
|
||||||
|
final ok = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (_) => AlertDialog(
|
||||||
|
backgroundColor: AppColors.surfaceHigh,
|
||||||
|
title: Text('Silenciar alarma', style: appHeadline(size: 16)),
|
||||||
|
content: Text(
|
||||||
|
'La alarma se marcará como silenciada.\n${_tipoLabel(a['tipo'] as String)} · ${a['zona_nombre'] ?? ''}',
|
||||||
|
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context, false),
|
||||||
|
child: Text('Cancelar', style: appLabel(size: 13, color: AppColors.outline)),
|
||||||
|
),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () => Navigator.pop(context, true),
|
||||||
|
style: ElevatedButton.styleFrom(
|
||||||
|
primary: AppColors.onSurfaceVariant,
|
||||||
|
onPrimary: AppColors.surfaceLowest,
|
||||||
|
elevation: 0,
|
||||||
|
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||||
|
),
|
||||||
|
child: Text('Silenciar', style: appLabel(size: 13, weight: FontWeight.bold,
|
||||||
|
color: AppColors.surfaceLowest)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (ok == true && mounted) {
|
||||||
|
await _dao.silenciar(a['id'] as int);
|
||||||
|
_cargar();
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||||
|
content: Text('Alarma silenciada', style: appLabel(size: 13, color: AppColors.onSurface)),
|
||||||
|
backgroundColor: AppColors.surfaceHighest,
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _escalar(Map<String, dynamic> a) async {
|
||||||
|
final sevActual = a['severidad'] as int;
|
||||||
|
if (sevActual >= 5) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||||
|
content: Text('Ya está en nivel máximo (5)',
|
||||||
|
style: appLabel(size: 13, color: AppColors.onSurface)),
|
||||||
|
backgroundColor: AppColors.surfaceHighest,
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final ok = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (_) => AlertDialog(
|
||||||
|
backgroundColor: AppColors.surfaceHigh,
|
||||||
|
title: Text('Escalar alarma', style: appHeadline(size: 16)),
|
||||||
|
content: Text(
|
||||||
|
'La severidad subirá de NIVEL $sevActual → NIVEL ${sevActual + 1}.\n'
|
||||||
|
'Se notificará a la central cuando se sincronice.',
|
||||||
|
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context, false),
|
||||||
|
child: Text('Cancelar', style: appLabel(size: 13, color: AppColors.outline)),
|
||||||
|
),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () => Navigator.pop(context, true),
|
||||||
|
style: ElevatedButton.styleFrom(
|
||||||
|
primary: AppColors.tertiary,
|
||||||
|
onPrimary: AppColors.surfaceLowest,
|
||||||
|
elevation: 0,
|
||||||
|
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||||
|
),
|
||||||
|
child: Text('Escalar', style: appLabel(size: 13, weight: FontWeight.bold,
|
||||||
|
color: AppColors.surfaceLowest)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (ok == true && mounted) {
|
||||||
|
await _dao.escalar(a['id'] as int);
|
||||||
|
_cargar();
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||||
|
content: Text('Alarma escalada a nivel ${sevActual + 1}',
|
||||||
|
style: appLabel(size: 13, color: AppColors.surfaceLowest)),
|
||||||
|
backgroundColor: AppColors.tertiary,
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Build ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Scaffold(
|
||||||
|
backgroundColor: AppColors.surfaceLowest,
|
||||||
|
appBar: AppBar(
|
||||||
|
backgroundColor: AppColors.surfaceLow,
|
||||||
|
elevation: 0,
|
||||||
|
leading: IconButton(
|
||||||
|
icon: const Icon(Icons.arrow_back_ios_new, size: 18,
|
||||||
|
color: AppColors.onSurface),
|
||||||
|
onPressed: () => Navigator.pop(context),
|
||||||
|
),
|
||||||
|
title: Text('ALARMAS', style: appHeadline(size: 14, spacing: 2.0)),
|
||||||
|
bottom: TabBar(
|
||||||
|
controller: _tab,
|
||||||
|
labelStyle: appLabel(size: 12, weight: FontWeight.bold, spacing: 1.5),
|
||||||
|
unselectedLabelStyle: appLabel(size: 12, spacing: 1.5),
|
||||||
|
labelColor: AppColors.primary,
|
||||||
|
unselectedLabelColor: AppColors.outline,
|
||||||
|
indicatorColor: AppColors.primary,
|
||||||
|
indicatorWeight: 2,
|
||||||
|
tabs: const [
|
||||||
|
Tab(text: 'ACTIVAS'),
|
||||||
|
Tab(text: 'HISTORIAL'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
body: TabBarView(
|
||||||
|
controller: _tab,
|
||||||
|
children: [
|
||||||
|
_tabActivas(),
|
||||||
|
_tabHistorial(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Tab Activas ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
Widget _tabActivas() {
|
||||||
|
final lista = _activasFiltradas;
|
||||||
|
return RefreshIndicator(
|
||||||
|
onRefresh: _cargar,
|
||||||
|
color: AppColors.primary,
|
||||||
|
backgroundColor: AppColors.surfaceHigh,
|
||||||
|
child: CustomScrollView(
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
|
primary: false,
|
||||||
|
slivers: [
|
||||||
|
SliverToBoxAdapter(child: _filtroChips()),
|
||||||
|
if (_cargando)
|
||||||
|
const SliverFillRemaining(
|
||||||
|
child: Center(child: CircularProgressIndicator(
|
||||||
|
strokeWidth: 2, color: AppColors.primary)),
|
||||||
|
)
|
||||||
|
else if (lista.isEmpty)
|
||||||
|
SliverFillRemaining(child: _emptyState(
|
||||||
|
icon: Icons.shield_outlined,
|
||||||
|
titulo: 'Sin alarmas activas',
|
||||||
|
sub: 'Todos los sectores en estado normal',
|
||||||
|
color: AppColors.primary,
|
||||||
|
))
|
||||||
|
else ...[
|
||||||
|
SliverToBoxAdapter(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 4, 20, 12),
|
||||||
|
child: Text(
|
||||||
|
'${lista.length} alarma${lista.length == 1 ? '' : 's'} activa${lista.length == 1 ? '' : 's'}',
|
||||||
|
style: appLabel(size: 12, color: AppColors.outline),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SliverList(
|
||||||
|
delegate: SliverChildBuilderDelegate(
|
||||||
|
(_, i) => Padding(
|
||||||
|
padding: EdgeInsets.fromLTRB(16, 0, 16,
|
||||||
|
i == lista.length - 1 ? 24 : 12),
|
||||||
|
child: _alarmaCard(lista[i]),
|
||||||
|
),
|
||||||
|
childCount: lista.length,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _filtroChips() {
|
||||||
|
return SingleChildScrollView(
|
||||||
|
scrollDirection: Axis.horizontal,
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
_chip('Todos', null),
|
||||||
|
..._tipos.map((t) => _chip(_tipoLabel(t), t)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _chip(String label, String? tipo) {
|
||||||
|
final selected = _filtroTipo == tipo;
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(right: 8),
|
||||||
|
child: GestureDetector(
|
||||||
|
onTap: () => setState(() => _filtroTipo = tipo),
|
||||||
|
child: AnimatedContainer(
|
||||||
|
duration: const Duration(milliseconds: 200),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 7),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: selected ? AppColors.primaryContainer : AppColors.surfaceHigh,
|
||||||
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
border: Border.all(
|
||||||
|
color: selected ? AppColors.primary : AppColors.outlineVariant,
|
||||||
|
width: 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
label,
|
||||||
|
style: appLabel(
|
||||||
|
size: 11,
|
||||||
|
weight: selected ? FontWeight.bold : FontWeight.normal,
|
||||||
|
color: selected ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||||
|
spacing: 1.0,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _alarmaCard(Map<String, dynamic> a) {
|
||||||
|
final sev = a['severidad'] as int;
|
||||||
|
final tipo = a['tipo'] as String;
|
||||||
|
final zona = a['zona_nombre'] as String? ?? 'Zona desconocida';
|
||||||
|
final codigo = a['zona_codigo'] as String? ?? '';
|
||||||
|
final ts = _formatTs(a['timestamp'] as String);
|
||||||
|
final color = _sevColor(sev);
|
||||||
|
|
||||||
|
return ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
child: IntrinsicHeight(
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Container(width: 5, color: color),
|
||||||
|
Expanded(
|
||||||
|
child: Container(
|
||||||
|
color: AppColors.surfaceHigh,
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
// Cabecera
|
||||||
|
Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.all(8),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: color.withOpacity(0.12),
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
),
|
||||||
|
child: Icon(_tipoIcon(tipo), color: color, size: 18),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
_tipoLabel(tipo),
|
||||||
|
style: appLabel(size: 10, weight: FontWeight.bold,
|
||||||
|
color: color, spacing: 1.5),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(zona,
|
||||||
|
style: appHeadline(size: 15)),
|
||||||
|
if (codigo.isNotEmpty)
|
||||||
|
Text(codigo,
|
||||||
|
style: appLabel(size: 11)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// Badge severidad
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 10, vertical: 5),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: color.withOpacity(0.15),
|
||||||
|
borderRadius: BorderRadius.circular(6),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
'N$sev',
|
||||||
|
style: appLabel(size: 12, weight: FontWeight.bold,
|
||||||
|
color: color, spacing: 0.5),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
// Timestamp
|
||||||
|
Row(children: [
|
||||||
|
const Icon(Icons.schedule, size: 13,
|
||||||
|
color: AppColors.outline),
|
||||||
|
const SizedBox(width: 5),
|
||||||
|
Text(ts, style: appLabel(size: 11)),
|
||||||
|
]),
|
||||||
|
const SizedBox(height: 14),
|
||||||
|
// Botones de acción
|
||||||
|
Row(children: [
|
||||||
|
_accionBtn('RESPONDER', AppColors.primary,
|
||||||
|
() => _responder(a)),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
_accionBtn('SILENCIAR', AppColors.onSurfaceVariant,
|
||||||
|
() => _silenciar(a)),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
_accionBtn('ESCALAR', sev >= 5
|
||||||
|
? AppColors.outlineVariant : AppColors.tertiary,
|
||||||
|
sev >= 5 ? null : () => _escalar(a)),
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _accionBtn(String label, Color color, VoidCallback? onTap) =>
|
||||||
|
Expanded(
|
||||||
|
child: GestureDetector(
|
||||||
|
onTap: onTap,
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: onTap != null ? color.withOpacity(0.12) : AppColors.surfaceLowest,
|
||||||
|
borderRadius: BorderRadius.circular(7),
|
||||||
|
border: Border.all(
|
||||||
|
color: onTap != null ? color.withOpacity(0.3) : AppColors.outlineVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
label,
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: appLabel(size: 10, weight: FontWeight.bold,
|
||||||
|
color: onTap != null ? color : AppColors.outlineVariant,
|
||||||
|
spacing: 1.0),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Tab Historial ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
Widget _tabHistorial() {
|
||||||
|
return RefreshIndicator(
|
||||||
|
onRefresh: _cargar,
|
||||||
|
color: AppColors.primary,
|
||||||
|
backgroundColor: AppColors.surfaceHigh,
|
||||||
|
child: _cargando
|
||||||
|
? const Center(child: CircularProgressIndicator(
|
||||||
|
strokeWidth: 2, color: AppColors.primary))
|
||||||
|
: _historial.isEmpty
|
||||||
|
? _emptyState(
|
||||||
|
icon: Icons.history,
|
||||||
|
titulo: 'Sin historial',
|
||||||
|
sub: 'Las alarmas resueltas y silenciadas aparecerán aquí',
|
||||||
|
color: AppColors.outline,
|
||||||
|
)
|
||||||
|
: ListView.separated(
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
|
primary: false,
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
|
||||||
|
itemCount: _historial.length,
|
||||||
|
separatorBuilder: (_, __) => const SizedBox(height: 8),
|
||||||
|
itemBuilder: (_, i) => _historialItem(_historial[i]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _historialItem(Map<String, dynamic> a) {
|
||||||
|
final sev = a['severidad'] as int;
|
||||||
|
final tipo = a['tipo'] as String;
|
||||||
|
final zona = a['zona_nombre'] as String? ?? 'Zona desconocida';
|
||||||
|
final ts = _formatTs(a['timestamp'] as String);
|
||||||
|
final estado = a['estado'] as String;
|
||||||
|
final notas = a['notas'] as String?;
|
||||||
|
final sevColor = _sevColor(sev);
|
||||||
|
final estadoC = _estadoColor(estado);
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.all(14),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: AppColors.surfaceLow,
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(_tipoIcon(tipo), color: sevColor, size: 18),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(children: [
|
||||||
|
Text(_tipoLabel(tipo),
|
||||||
|
style: appLabel(size: 10, weight: FontWeight.bold,
|
||||||
|
color: sevColor, spacing: 1.0)),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
Text('·', style: appLabel(size: 10, color: AppColors.outlineVariant)),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
Text('N$sev', style: appLabel(size: 10, color: sevColor)),
|
||||||
|
]),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(zona, style: appHeadline(size: 13)),
|
||||||
|
if (notas != null && notas.isNotEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 2),
|
||||||
|
child: Text(notas,
|
||||||
|
style: appLabel(size: 11),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(ts, style: appLabel(size: 11, color: AppColors.outline)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: estadoC.withOpacity(0.12),
|
||||||
|
borderRadius: BorderRadius.circular(5),
|
||||||
|
),
|
||||||
|
child: Text(_estadoLabel(estado),
|
||||||
|
style: appLabel(size: 9, weight: FontWeight.bold,
|
||||||
|
color: estadoC, spacing: 0.8)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Empty state ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
Widget _emptyState({
|
||||||
|
required IconData icon,
|
||||||
|
required String titulo,
|
||||||
|
required String sub,
|
||||||
|
required Color color,
|
||||||
|
}) =>
|
||||||
|
Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(40),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(icon, color: color, size: 36),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Text(titulo, style: appHeadline(size: 15, color: color)),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
Text(sub,
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: appLabel(size: 12, color: AppColors.outline)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,462 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'package:crypto/crypto.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import '../theme.dart';
|
||||||
|
import '../db/dao/usuarios_dao.dart';
|
||||||
|
import '../db/dao/zonas_dao.dart';
|
||||||
|
import '../models/zona.dart';
|
||||||
|
|
||||||
|
class RegistrarUsuarioPage extends StatefulWidget {
|
||||||
|
const RegistrarUsuarioPage({Key? key}) : super(key: key);
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<RegistrarUsuarioPage> createState() => _RegistrarUsuarioPageState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
|
||||||
|
final _formKey = GlobalKey<FormState>();
|
||||||
|
final _nombreCtrl = TextEditingController();
|
||||||
|
final _pinCtrl = TextEditingController();
|
||||||
|
final _dao = UsuariosDao();
|
||||||
|
final _zonasDao = ZonasDao();
|
||||||
|
|
||||||
|
int _nivelAcceso = 1;
|
||||||
|
final Set<int> _zonasSeleccionadas = {};
|
||||||
|
List<Zona> _zonas = [];
|
||||||
|
DateTime _fechaInicio = DateTime.now();
|
||||||
|
DateTime? _fechaFin;
|
||||||
|
bool _guardando = false;
|
||||||
|
bool _pinVisible = false;
|
||||||
|
|
||||||
|
static const _nivelesId = [1, 2, 3, 4, 5];
|
||||||
|
static const _nivelesLabel = ['Visitante', 'Empleado', 'Supervisor', 'Admin', 'Super Admin'];
|
||||||
|
static const _nivelesColor = [
|
||||||
|
AppColors.outline,
|
||||||
|
AppColors.secondary,
|
||||||
|
AppColors.primary,
|
||||||
|
AppColors.tertiary,
|
||||||
|
AppColors.error,
|
||||||
|
];
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_cargarZonas();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _cargarZonas() async {
|
||||||
|
final z = await _zonasDao.getAll();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _zonas = z);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_nombreCtrl.dispose();
|
||||||
|
_pinCtrl.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
String _calcularIniciales(String nombre) {
|
||||||
|
final partes = nombre.trim().split(RegExp(r'\s+'));
|
||||||
|
if (partes.length >= 2) {
|
||||||
|
return '${partes.first[0]}${partes.last[0]}'.toUpperCase();
|
||||||
|
}
|
||||||
|
return nombre.isNotEmpty ? nombre[0].toUpperCase() : '?';
|
||||||
|
}
|
||||||
|
|
||||||
|
String _hashPin(String pin) =>
|
||||||
|
sha256.convert(utf8.encode(pin)).toString();
|
||||||
|
|
||||||
|
String _formatFecha(DateTime dt) =>
|
||||||
|
'${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}';
|
||||||
|
|
||||||
|
Future<void> _seleccionarFecha({required bool esFin}) async {
|
||||||
|
final inicial = esFin ? (_fechaFin ?? _fechaInicio) : _fechaInicio;
|
||||||
|
final picked = await showDatePicker(
|
||||||
|
context: context,
|
||||||
|
initialDate: inicial,
|
||||||
|
firstDate: esFin ? _fechaInicio : DateTime(2020),
|
||||||
|
lastDate: DateTime(2035),
|
||||||
|
builder: (ctx, child) => Theme(
|
||||||
|
data: Theme.of(ctx).copyWith(
|
||||||
|
colorScheme: const ColorScheme.dark(
|
||||||
|
primary: AppColors.primary,
|
||||||
|
onPrimary: AppColors.primaryContainer,
|
||||||
|
surface: AppColors.surfaceHigh,
|
||||||
|
onSurface: AppColors.onSurface,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: child!,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (picked == null) return;
|
||||||
|
setState(() {
|
||||||
|
if (esFin) {
|
||||||
|
_fechaFin = picked;
|
||||||
|
} else {
|
||||||
|
_fechaInicio = picked;
|
||||||
|
if (_fechaFin != null && _fechaFin!.isBefore(_fechaInicio)) {
|
||||||
|
_fechaFin = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _guardar() async {
|
||||||
|
if (!_formKey.currentState!.validate()) return;
|
||||||
|
setState(() => _guardando = true);
|
||||||
|
try {
|
||||||
|
final areas = _zonasSeleccionadas.isEmpty
|
||||||
|
? null
|
||||||
|
: _zonas
|
||||||
|
.where((z) => _zonasSeleccionadas.contains(z.id))
|
||||||
|
.map((z) => z.codigo)
|
||||||
|
.join(',');
|
||||||
|
await _dao.registrar(
|
||||||
|
nombre: _nombreCtrl.text.trim(),
|
||||||
|
iniciales: _calcularIniciales(_nombreCtrl.text),
|
||||||
|
nivelAcceso: _nivelAcceso,
|
||||||
|
pinHash: _hashPin(_pinCtrl.text.trim()),
|
||||||
|
areas: areas,
|
||||||
|
fechaInicio: _fechaInicio.toIso8601String(),
|
||||||
|
fechaFin: _fechaFin?.toIso8601String(),
|
||||||
|
);
|
||||||
|
if (!mounted) return;
|
||||||
|
Navigator.pop(context, true);
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
backgroundColor: AppColors.error,
|
||||||
|
content: Text('Error al guardar: $e',
|
||||||
|
style: appLabel(color: Colors.white)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _guardando = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Scaffold(
|
||||||
|
backgroundColor: AppColors.surfaceLowest,
|
||||||
|
appBar: AppBar(
|
||||||
|
backgroundColor: AppColors.surfaceLow,
|
||||||
|
elevation: 0,
|
||||||
|
leading: IconButton(
|
||||||
|
icon: const Icon(Icons.close,
|
||||||
|
color: AppColors.onSurface, size: 22),
|
||||||
|
onPressed: () => Navigator.pop(context),
|
||||||
|
),
|
||||||
|
title: Text('Registrar Usuario',
|
||||||
|
style: appHeadline(size: 17, weight: FontWeight.w700)),
|
||||||
|
actions: [
|
||||||
|
if (_guardando)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.all(16),
|
||||||
|
child: SizedBox(
|
||||||
|
width: 20,
|
||||||
|
height: 20,
|
||||||
|
child: CircularProgressIndicator(
|
||||||
|
strokeWidth: 2, color: AppColors.primary)),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
TextButton(
|
||||||
|
onPressed: _guardar,
|
||||||
|
child: Text('GUARDAR',
|
||||||
|
style: appLabel(
|
||||||
|
weight: FontWeight.bold, color: AppColors.primary)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
body: Form(
|
||||||
|
key: _formKey,
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
primary: false,
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 24, 20, 40),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_seccion('Datos personales'),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
_campoNombre(),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
_campoPin(),
|
||||||
|
const SizedBox(height: 28),
|
||||||
|
_seccion('Nivel de acceso'),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
_selectorNivel(),
|
||||||
|
const SizedBox(height: 28),
|
||||||
|
_seccion('Áreas permitidas'),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
_zonas.isEmpty
|
||||||
|
? 'Sin zonas en el sistema — carga datos de demo primero'
|
||||||
|
: 'Sin selección = acceso a todas las áreas',
|
||||||
|
style: appLabel(
|
||||||
|
size: 11, color: AppColors.onSurfaceVariant),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
if (_zonas.isNotEmpty) _selectorAreas(),
|
||||||
|
const SizedBox(height: 28),
|
||||||
|
_seccion('Vigencia'),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
_selectorFechas(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _seccion(String titulo) => Text(titulo,
|
||||||
|
style: appHeadline(
|
||||||
|
size: 13,
|
||||||
|
weight: FontWeight.w700,
|
||||||
|
color: AppColors.onSurfaceVariant,
|
||||||
|
spacing: 1.0));
|
||||||
|
|
||||||
|
// ── Campo nombre ──────────────────────────────────────────────────────────
|
||||||
|
Widget _campoNombre() => TextFormField(
|
||||||
|
controller: _nombreCtrl,
|
||||||
|
style: appLabel(size: 15, color: AppColors.onSurface),
|
||||||
|
textCapitalization: TextCapitalization.words,
|
||||||
|
decoration: _inputDeco(
|
||||||
|
label: 'Nombre completo',
|
||||||
|
icon: Icons.person_outline,
|
||||||
|
),
|
||||||
|
validator: (v) {
|
||||||
|
if (v == null || v.trim().isEmpty) return 'Campo requerido';
|
||||||
|
if (v.trim().length < 3) return 'Mínimo 3 caracteres';
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Campo PIN ─────────────────────────────────────────────────────────────
|
||||||
|
Widget _campoPin() => TextFormField(
|
||||||
|
controller: _pinCtrl,
|
||||||
|
style: appLabel(size: 15, color: AppColors.onSurface),
|
||||||
|
obscureText: !_pinVisible,
|
||||||
|
keyboardType: TextInputType.number,
|
||||||
|
inputFormatters: [
|
||||||
|
FilteringTextInputFormatter.digitsOnly,
|
||||||
|
LengthLimitingTextInputFormatter(6),
|
||||||
|
],
|
||||||
|
decoration: _inputDeco(
|
||||||
|
label: 'PIN de acceso (4–6 dígitos)',
|
||||||
|
icon: Icons.lock_outline,
|
||||||
|
suffix: IconButton(
|
||||||
|
icon: Icon(
|
||||||
|
_pinVisible ? Icons.visibility_off : Icons.visibility,
|
||||||
|
color: AppColors.outline,
|
||||||
|
size: 20,
|
||||||
|
),
|
||||||
|
onPressed: () => setState(() => _pinVisible = !_pinVisible),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
validator: (v) {
|
||||||
|
if (v == null || v.isEmpty) return 'Campo requerido';
|
||||||
|
if (v.length < 4) return 'Mínimo 4 dígitos';
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
InputDecoration _inputDeco({
|
||||||
|
required String label,
|
||||||
|
required IconData icon,
|
||||||
|
Widget? suffix,
|
||||||
|
}) =>
|
||||||
|
InputDecoration(
|
||||||
|
labelText: label,
|
||||||
|
labelStyle: appLabel(color: AppColors.outline),
|
||||||
|
prefixIcon: Icon(icon, color: AppColors.outline, size: 20),
|
||||||
|
suffixIcon: suffix,
|
||||||
|
filled: true,
|
||||||
|
fillColor: AppColors.surfaceHigh,
|
||||||
|
border: OutlineInputBorder(
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
borderSide: BorderSide.none,
|
||||||
|
),
|
||||||
|
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, width: 1.5),
|
||||||
|
),
|
||||||
|
focusedErrorBorder: OutlineInputBorder(
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
borderSide: const BorderSide(color: AppColors.error, width: 1.5),
|
||||||
|
),
|
||||||
|
errorStyle: appLabel(size: 11, color: AppColors.error),
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Selector de nivel ─────────────────────────────────────────────────────
|
||||||
|
Widget _selectorNivel() {
|
||||||
|
final chips = <Widget>[];
|
||||||
|
for (var i = 0; i < _nivelesId.length; i++) {
|
||||||
|
final nId = _nivelesId[i];
|
||||||
|
final nLabel = _nivelesLabel[i];
|
||||||
|
final nColor = _nivelesColor[i];
|
||||||
|
final sel = _nivelAcceso == nId;
|
||||||
|
chips.add(
|
||||||
|
GestureDetector(
|
||||||
|
onTap: () => setState(() => _nivelAcceso = nId),
|
||||||
|
child: AnimatedContainer(
|
||||||
|
duration: const Duration(milliseconds: 180),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 9),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: sel ? nColor.withOpacity(0.15) : AppColors.surfaceHigh,
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
border: Border.all(
|
||||||
|
color: sel ? nColor : AppColors.surfaceHighest,
|
||||||
|
width: sel ? 1.5 : 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||||
|
if (sel) ...[
|
||||||
|
Icon(Icons.check_circle, size: 14, color: nColor),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
],
|
||||||
|
Text(
|
||||||
|
'N$nId · $nLabel',
|
||||||
|
style: appLabel(
|
||||||
|
size: 12,
|
||||||
|
weight: sel ? FontWeight.bold : FontWeight.normal,
|
||||||
|
color: sel ? nColor : AppColors.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Wrap(spacing: 8, runSpacing: 8, children: chips);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Selector de áreas ─────────────────────────────────────────────────────
|
||||||
|
Widget _selectorAreas() => Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: _zonas.map((z) {
|
||||||
|
final sel = _zonasSeleccionadas.contains(z.id);
|
||||||
|
return GestureDetector(
|
||||||
|
onTap: () => setState(() {
|
||||||
|
if (sel) {
|
||||||
|
_zonasSeleccionadas.remove(z.id);
|
||||||
|
} else {
|
||||||
|
_zonasSeleccionadas.add(z.id);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
child: AnimatedContainer(
|
||||||
|
duration: const Duration(milliseconds: 160),
|
||||||
|
padding:
|
||||||
|
const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: sel
|
||||||
|
? AppColors.primaryContainer
|
||||||
|
: AppColors.surfaceHigh,
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
border: Border.all(
|
||||||
|
color: sel
|
||||||
|
? AppColors.primary.withOpacity(0.5)
|
||||||
|
: AppColors.surfaceHighest,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||||
|
if (sel) ...[
|
||||||
|
const Icon(Icons.check, size: 13, color: AppColors.primary),
|
||||||
|
const SizedBox(width: 5),
|
||||||
|
],
|
||||||
|
Text(
|
||||||
|
'${z.codigo} · ${z.nombre}',
|
||||||
|
style: appLabel(
|
||||||
|
size: 12,
|
||||||
|
weight: sel ? FontWeight.w600 : FontWeight.normal,
|
||||||
|
color: sel
|
||||||
|
? AppColors.primary
|
||||||
|
: AppColors.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}).toList(),
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Selector de fechas ────────────────────────────────────────────────────
|
||||||
|
Widget _selectorFechas() => Column(
|
||||||
|
children: [
|
||||||
|
_fechaRow(
|
||||||
|
label: 'Inicio de vigencia',
|
||||||
|
valor: _formatFecha(_fechaInicio),
|
||||||
|
onTap: () => _seleccionarFecha(esFin: false),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
_fechaRow(
|
||||||
|
label: 'Fin de vigencia',
|
||||||
|
valor: _fechaFin != null
|
||||||
|
? _formatFecha(_fechaFin!)
|
||||||
|
: 'Sin vencimiento',
|
||||||
|
valorColor: _fechaFin != null
|
||||||
|
? AppColors.onSurface
|
||||||
|
: AppColors.onSurfaceVariant,
|
||||||
|
onTap: () => _seleccionarFecha(esFin: true),
|
||||||
|
trailing: _fechaFin != null
|
||||||
|
? IconButton(
|
||||||
|
icon: const Icon(Icons.close,
|
||||||
|
color: AppColors.outline, size: 18),
|
||||||
|
onPressed: () => setState(() => _fechaFin = null),
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
constraints: const BoxConstraints(),
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
Widget _fechaRow({
|
||||||
|
required String label,
|
||||||
|
required String valor,
|
||||||
|
Color? valorColor,
|
||||||
|
required VoidCallback onTap,
|
||||||
|
Widget? trailing,
|
||||||
|
}) =>
|
||||||
|
GestureDetector(
|
||||||
|
onTap: onTap,
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: AppColors.surfaceHigh,
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
),
|
||||||
|
child: Row(children: [
|
||||||
|
const Icon(Icons.calendar_today,
|
||||||
|
color: AppColors.outline, size: 18),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(label,
|
||||||
|
style: appLabel(
|
||||||
|
size: 11, color: AppColors.onSurfaceVariant)),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(valor,
|
||||||
|
style: appLabel(
|
||||||
|
size: 14,
|
||||||
|
weight: FontWeight.w600,
|
||||||
|
color: valorColor ?? AppColors.onSurface)),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
trailing ??
|
||||||
|
const Icon(Icons.chevron_right,
|
||||||
|
color: AppColors.outline, size: 20),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
+7
-8
@@ -22,7 +22,7 @@
|
|||||||
| Historial de sesiones | `pages/historial_sesiones_page.dart` | ✅ Completo |
|
| Historial de sesiones | `pages/historial_sesiones_page.dart` | ✅ Completo |
|
||||||
| Registro de usuario | `pages/register_page.dart` | 🔴 Sin estilo del sistema |
|
| Registro de usuario | `pages/register_page.dart` | 🔴 Sin estilo del sistema |
|
||||||
| Configuración | `pages/settings_page.dart` | 🟡 Parcial |
|
| Configuración | `pages/settings_page.dart` | 🟡 Parcial |
|
||||||
| Alarmas (página propia) | `pages/alarmas_page.dart` | 🔴 Vacío |
|
| Alarmas (página propia) | `pages/alarmas_page.dart` | ✅ Completo |
|
||||||
| Clientes | `pages/clientes_page.dart` | 🔴 Pendiente |
|
| Clientes | `pages/clientes_page.dart` | 🔴 Pendiente |
|
||||||
| Suscripciones | `pages/suscripciones_page.dart` | 🔴 Pendiente |
|
| Suscripciones | `pages/suscripciones_page.dart` | 🔴 Pendiente |
|
||||||
| Tema / Colores | `theme.dart` | ✅ Completo |
|
| Tema / Colores | `theme.dart` | ✅ Completo |
|
||||||
@@ -130,13 +130,12 @@ Actualmente insertan un mensaje de chat en la tabla `mensajes`. El comportamient
|
|||||||
- **SOPORTE:** abrir la llamada simulada (`LlamadaPage`) o enviar un evento de tipo `notificacion` a la central — no un mensaje de chat
|
- **SOPORTE:** abrir la llamada simulada (`LlamadaPage`) o enviar un evento de tipo `notificacion` a la central — no un mensaje de chat
|
||||||
- El chat debe quedar exclusivamente para comunicación de texto libre con la central
|
- El chat debe quedar exclusivamente para comunicación de texto libre con la central
|
||||||
|
|
||||||
#### 2. Página de Alarmas real (`pages/alarmas_page.dart`)
|
#### 2. Página de Alarmas real (`pages/alarmas_page.dart`) ✅ IMPLEMENTADO
|
||||||
Actualmente el archivo está vacío. Construir página dedicada de alarmas.
|
- Tab ACTIVAS: chips de filtro por tipo + cards con severidad, zona, timestamp
|
||||||
- Lista de alarmas activas con nivel de severidad (1–5)
|
- Acciones: Responder (diálogo + notas), Silenciar, Escalar (incrementa severidad)
|
||||||
- Detalle por alarma: zona, sensor, timestamp, estado
|
- Tab HISTORIAL: lista compacta de resueltas y silenciadas
|
||||||
- Acciones: Responder / Silenciar / Escalar
|
- Pull to refresh · empty states · navegación desde botón RESPONDER de MonitoreoAlarmaPage
|
||||||
- Filtros por zona, tipo, estado
|
- Endpoints backend pendientes documentados en `solicituda_backend.md`
|
||||||
- Historial de alarmas resueltas
|
|
||||||
|
|
||||||
#### 2. Control de Acceso — Registrar usuarios (`pages/control_acceso_page.dart`)
|
#### 2. Control de Acceso — Registrar usuarios (`pages/control_acceso_page.dart`)
|
||||||
Comentario pendiente en el código: *"agregar un botón para registrar usuarios y darle acceso por tiempo y áreas"*
|
Comentario pendiente en el código: *"agregar un botón para registrar usuarios y darle acceso por tiempo y áreas"*
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
# Integración con API_CENTINEL_SECURITY
|
||||||
|
|
||||||
|
Backend implementado en `https://api.telcotronics.com`.
|
||||||
|
|
||||||
|
**API Key de desarrollo:** `dev-api-key-123456`
|
||||||
|
**BD autorizada:** `security_db`
|
||||||
|
|
||||||
|
Documentación interactiva: Swagger UI → clic en **Authorize** e introducir la API Key.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Endpoints disponibles
|
||||||
|
|
||||||
|
### Dispositivos
|
||||||
|
|
||||||
|
| Método | Ruta | Descripción |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| GET | `/api/devices` | Listar dispositivos del tenant |
|
||||||
|
| GET | `/api/devices/{id}` | Detalle de un dispositivo |
|
||||||
|
| POST | `/api/devices` | Registrar dispositivo |
|
||||||
|
| DELETE | `/api/devices/{id}` | Eliminar dispositivo |
|
||||||
|
| GET | `/api/devices/test/{id}` | Test de conexión física contra el hardware |
|
||||||
|
|
||||||
|
### Control de Acceso
|
||||||
|
|
||||||
|
| Método | Ruta | Descripción |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| POST | `/api/access/open-door/{deviceId}/{door}` | Abrir puerta remotamente |
|
||||||
|
| POST | `/api/devices/{id}/alarm-host` | Configurar recepción de eventos del dispositivo |
|
||||||
|
|
||||||
|
### Empleados y Credenciales
|
||||||
|
|
||||||
|
| Método | Ruta | Descripción |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| GET | `/api/devices/{deviceId}/employees` | Listar empleados registrados en el dispositivo (desde BD) |
|
||||||
|
| POST | `/api/devices/{deviceId}/employees` | Sincronizar empleado al dispositivo (encola si está offline) |
|
||||||
|
| POST | `/api/devices/{deviceId}/employees/bulk` | Sincronización masiva de empleados |
|
||||||
|
| DELETE | `/api/devices/{deviceId}/employees/{employeeNo}` | Dar de baja empleado en dispositivo |
|
||||||
|
| DELETE | `/api/employees/{employeeNo}` | Baja en cascada en todos los terminales del tenant |
|
||||||
|
| GET | `/api/devices/{deviceId}/users` | Listar usuarios directamente desde el hardware |
|
||||||
|
| POST | `/api/devices/{deviceId}/users` | Registrar usuario directo en hardware |
|
||||||
|
| DELETE | `/api/devices/{deviceId}/users/{employeeNo}` | Eliminar usuario del hardware |
|
||||||
|
|
||||||
|
### Biometría
|
||||||
|
|
||||||
|
| Método | Ruta | Descripción |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| POST | `/api/biometria/{employeeNo}` | Subir foto / rostro / huella (`multipart/form-data`) |
|
||||||
|
| GET | `/api/biometria/{employeeNo}` | Listar biometrías del empleado |
|
||||||
|
| GET | `/api/biometria/{employeeNo}/{tipo}` | Descargar binario (JPEG o template de huella) |
|
||||||
|
| DELETE | `/api/biometria/{employeeNo}` | Eliminar toda la biometría del empleado |
|
||||||
|
|
||||||
|
Tipos válidos para `{tipo}`: `FOTO`, `ROSTRO`, `HUELLA`.
|
||||||
|
|
||||||
|
### Alarmas
|
||||||
|
|
||||||
|
| Método | Ruta | Descripción |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| POST | `/api/alarmas/{id}/escalar` | Escalar alarma (aumenta severidad, estado → ESCALADA) |
|
||||||
|
| PUT | `/api/alarmas/{id}/resolver` | Resolver alarma con notas del operador (estado → RESUELTA) |
|
||||||
|
| PUT | `/api/alarmas/{id}/silenciar` | Silenciar alarma (estado → SILENCIADA) |
|
||||||
|
|
||||||
|
Usado por SENTINEL ONE para sincronizar el estado local (registros con `sincronizado=0`) al servidor vía `Sincronizador.pushPendientes()`.
|
||||||
|
|
||||||
|
### Cola de sincronización
|
||||||
|
|
||||||
|
| Método | Ruta | Descripción |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| GET | `/api/sync-queue` | Ver operaciones pendientes o fallidas del tenant |
|
||||||
|
| POST | `/api/sync-queue/retry` | Reintentar manualmente las operaciones fallidas |
|
||||||
|
|
||||||
|
Cuando un dispositivo está offline, las operaciones se encolan con estado `PENDING` y se reintentan automáticamente.
|
||||||
|
|
||||||
|
### Administración *(requiere ADMIN_API_KEY)*
|
||||||
|
|
||||||
|
| Método | Ruta | Descripción |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| GET | `/api/admin/clients` | Listar clientes de API |
|
||||||
|
| GET | `/api/admin/clients/{id}` | Detalle de cliente |
|
||||||
|
| POST | `/api/admin/clients` | Crear cliente y generar API Key |
|
||||||
|
| DELETE | `/api/admin/clients/{id}` | Eliminar cliente |
|
||||||
|
| POST | `/api/admin/clients/{id}/databases` | Asociar BD (tenant) a cliente |
|
||||||
|
| DELETE | `/api/admin/clients/{id}/databases/{db}` | Desasociar BD de cliente |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Mapeo a SENTINEL ONE
|
||||||
|
|
||||||
|
| Funcionalidad app | Endpoint API |
|
||||||
|
|---|---|
|
||||||
|
| Abrir puerta (ControlAccesoPage) | `POST /api/access/open-door/{deviceId}/{door}` |
|
||||||
|
| Registrar usuario (RegistrarUsuarioPage) | `POST /api/devices/{deviceId}/employees` |
|
||||||
|
| Baja de usuario | `DELETE /api/employees/{employeeNo}` |
|
||||||
|
| Sync masiva tras DemoDataService | `POST /api/devices/{deviceId}/employees/bulk` |
|
||||||
|
| Escalar alarma (AlarmasPage) | `POST /api/alarmas/{id}/escalar` |
|
||||||
|
| Resolver alarma | `PUT /api/alarmas/{id}/resolver` |
|
||||||
|
| Silenciar alarma | `PUT /api/alarmas/{id}/silenciar` |
|
||||||
|
| Foto de perfil / biometría | `POST /api/biometria/{employeeNo}` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Notas de integración
|
||||||
|
|
||||||
|
- Autenticación: API Key en header `X-API-Key: dev-api-key-123456` (desarrollo). Producción usará la key asignada en ConectarProveedorPage.
|
||||||
|
- Los registros locales con `sincronizado = 0` se empujan cuando `Sincronizador.pushPendientes()` esté activo.
|
||||||
|
- La URL base (`https://api.telcotronics.com`) se configura en `ConectarProveedorPage` → tabla `configuracion` clave `api_base_url`.
|
||||||
|
- El campo `employeeNo` corresponde al `id` del usuario en la tabla `usuarios` de SQLite local.
|
||||||
Reference in New Issue
Block a user