feat: commit inicial — Central Monitoreo v1.0.0
- OperadorLoginPage con auth WebControl 2 pasos (empresas → login) - ShellPage: sidebar 220px + IndexedStack + header con estado API - DashboardPage: stat cards, feed alarmas, clientes, incidentes (timer 30s) - ApiAuthService: flujo real con email + paswd + dba → token + apiKey - DB SQLite v1: 7 tablas + 7 DAOs completos - theme.dart: AppColors, appHeadline (Manrope), appLabel (Inter) - Logo app: escudo radar neón (SVG + PNG 512px) en lib/recursos/ - desplegar.sh: build release Linux + upload a siax-system.net - agents.md: estado completo + objetivos futuros documentados Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import '../database_helper.dart';
|
||||
|
||||
class CacheAlarmasDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Map<String, dynamic>>> getActivas({int? clienteId}) async {
|
||||
final db = await _db.db;
|
||||
if (clienteId != null) {
|
||||
return db.query(
|
||||
'cache_alarmas',
|
||||
where: "estado = 'activa' AND cliente_id = ?",
|
||||
whereArgs: [clienteId],
|
||||
orderBy: 'severidad DESC, timestamp DESC',
|
||||
);
|
||||
}
|
||||
return db.query(
|
||||
'cache_alarmas',
|
||||
where: "estado = 'activa'",
|
||||
orderBy: 'severidad DESC, timestamp DESC',
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> getTodas({int limit = 100}) async {
|
||||
final db = await _db.db;
|
||||
return db.query('cache_alarmas', orderBy: 'severidad DESC, timestamp DESC', limit: limit);
|
||||
}
|
||||
|
||||
Future<int> contarActivas() async {
|
||||
final db = await _db.db;
|
||||
final result = await db.rawQuery("SELECT COUNT(*) as c FROM cache_alarmas WHERE estado = 'activa'");
|
||||
return result.first['c'] as int;
|
||||
}
|
||||
|
||||
Future<int> contarCriticas() async {
|
||||
final db = await _db.db;
|
||||
final result = await db.rawQuery("SELECT COUNT(*) as c FROM cache_alarmas WHERE estado = 'activa' AND severidad >= 4");
|
||||
return result.first['c'] as int;
|
||||
}
|
||||
|
||||
Future<void> reemplazarTodas(List<Map<String, dynamic>> alarmas) async {
|
||||
final db = await _db.db;
|
||||
await db.delete('cache_alarmas');
|
||||
for (final a in alarmas) {
|
||||
await db.insert('cache_alarmas', a, conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
}
|
||||
|
||||
Future<int> actualizarEstado(int id, String nuevoEstado) async {
|
||||
final db = await _db.db;
|
||||
return db.update(
|
||||
'cache_alarmas',
|
||||
{'estado': nuevoEstado},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> limpiar() async {
|
||||
final db = await _db.db;
|
||||
await db.delete('cache_alarmas');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import '../database_helper.dart';
|
||||
|
||||
class CacheClientesDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Map<String, dynamic>>> getTodos() async {
|
||||
final db = await _db.db;
|
||||
return db.query('cache_clientes', orderBy: 'alarmas_criticas DESC, nombre ASC');
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>?> getById(int id) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('cache_clientes', where: 'id = ?', whereArgs: [id]);
|
||||
return rows.isEmpty ? null : rows.first;
|
||||
}
|
||||
|
||||
Future<int> contarActivos() async {
|
||||
final db = await _db.db;
|
||||
final result = await db.rawQuery('SELECT COUNT(*) as c FROM cache_clientes');
|
||||
return result.first['c'] as int;
|
||||
}
|
||||
|
||||
Future<void> reemplazarTodos(List<Map<String, dynamic>> clientes) async {
|
||||
final db = await _db.db;
|
||||
await db.delete('cache_clientes');
|
||||
for (final c in clientes) {
|
||||
await db.insert('cache_clientes', c, conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import '../database_helper.dart';
|
||||
|
||||
class ConfiguracionDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<String?> get(String clave) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('configuracion', where: 'clave = ?', whereArgs: [clave]);
|
||||
return rows.isEmpty ? null : rows.first['valor'] as String?;
|
||||
}
|
||||
|
||||
Future<void> set(String clave, String valor) async {
|
||||
final db = await _db.db;
|
||||
await db.insert(
|
||||
'configuracion',
|
||||
{'clave': clave, 'valor': valor},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import '../database_helper.dart';
|
||||
|
||||
class IncidentesDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<int> registrar({
|
||||
int? alarmaId,
|
||||
int? clienteId,
|
||||
String? clienteNombre,
|
||||
required String tipo,
|
||||
required String operador,
|
||||
String? notas,
|
||||
}) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('incidentes', {
|
||||
'alarma_id': alarmaId,
|
||||
'cliente_id': clienteId,
|
||||
'cliente_nombre': clienteNombre,
|
||||
'tipo': tipo,
|
||||
'operador': operador,
|
||||
'notas': notas,
|
||||
'timestamp': DateTime.now().toIso8601String(),
|
||||
'resuelto': 0,
|
||||
'sincronizado': 0,
|
||||
});
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> getRecientes({int limit = 50}) async {
|
||||
final db = await _db.db;
|
||||
return db.query('incidentes', orderBy: 'timestamp DESC', limit: limit);
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
return db.query('incidentes', where: 'sincronizado = 0');
|
||||
}
|
||||
|
||||
Future<int> marcarResuelto(int id, String notas) async {
|
||||
final db = await _db.db;
|
||||
return db.update(
|
||||
'incidentes',
|
||||
{'resuelto': 1, 'notas': notas, 'sincronizado': 0},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import '../database_helper.dart';
|
||||
|
||||
class OperadoresDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Map<String, dynamic>>> getTodos() async {
|
||||
final db = await _db.db;
|
||||
return db.query('operadores', where: 'activo = 1', orderBy: 'nombre ASC');
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> getEnTurno() async {
|
||||
final db = await _db.db;
|
||||
return db.query('operadores', where: 'activo = 1 AND en_turno = 1');
|
||||
}
|
||||
|
||||
Future<int> insertar(String nombre, int nivel) async {
|
||||
final db = await _db.db;
|
||||
final iniciales = _calcularIniciales(nombre);
|
||||
return db.insert('operadores', {
|
||||
'nombre': nombre,
|
||||
'iniciales': iniciales,
|
||||
'nivel': nivel,
|
||||
'activo': 1,
|
||||
'en_turno': 0,
|
||||
});
|
||||
}
|
||||
|
||||
Future<int> setEnTurno(int id, bool valor) async {
|
||||
final db = await _db.db;
|
||||
return db.update(
|
||||
'operadores',
|
||||
{'en_turno': valor ? 1 : 0},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> desactivar(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.update('operadores', {'activo': 0}, where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
String _calcularIniciales(String nombre) {
|
||||
final p = nombre.trim().split(RegExp(r'\s+'));
|
||||
if (p.length >= 2) return '${p.first[0]}${p.last[0]}'.toUpperCase();
|
||||
return nombre.isNotEmpty ? nombre[0].toUpperCase() : '?';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import '../database_helper.dart';
|
||||
|
||||
class SesionesDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<int> iniciarSesion(String nombre, String usuario) async {
|
||||
final db = await _db.db;
|
||||
await db.update('sesiones_operador', {'activa': 0});
|
||||
return db.insert('sesiones_operador', {
|
||||
'nombre': nombre,
|
||||
'usuario': usuario,
|
||||
'inicio': DateTime.now().toIso8601String(),
|
||||
'activa': 1,
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> cerrarSesion() async {
|
||||
final db = await _db.db;
|
||||
await db.update(
|
||||
'sesiones_operador',
|
||||
{'fin': DateTime.now().toIso8601String(), 'activa': 0},
|
||||
where: 'activa = 1',
|
||||
);
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>?> getSesionActiva() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('sesiones_operador', where: 'activa = 1', limit: 1);
|
||||
return rows.isEmpty ? null : rows.first;
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> getRecientes({int limit = 10}) async {
|
||||
final db = await _db.db;
|
||||
return db.query('sesiones_operador', orderBy: 'inicio DESC', limit: limit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import '../database_helper.dart';
|
||||
|
||||
class SyncLogDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<void> registrar({
|
||||
required String tipo,
|
||||
required String estado,
|
||||
String? detalle,
|
||||
}) async {
|
||||
final db = await _db.db;
|
||||
await db.insert('sync_log', {
|
||||
'tipo': tipo,
|
||||
'estado': estado,
|
||||
'detalle': detalle,
|
||||
'timestamp': DateTime.now().toIso8601String(),
|
||||
});
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> getRecientes({int limit = 20}) async {
|
||||
final db = await _db.db;
|
||||
return db.query('sync_log', orderBy: 'timestamp DESC', limit: limit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
|
||||
class DatabaseHelper {
|
||||
static const _dbName = 'central_monitoreo.db';
|
||||
static const _dbVersion = 1;
|
||||
|
||||
DatabaseHelper._();
|
||||
static final DatabaseHelper instance = DatabaseHelper._();
|
||||
|
||||
Database? _db;
|
||||
|
||||
Future<Database> get db async {
|
||||
_db ??= await _initDb();
|
||||
return _db!;
|
||||
}
|
||||
|
||||
Future<Database> _initDb() async {
|
||||
if (!kIsWeb && (Platform.isLinux || Platform.isWindows)) {
|
||||
sqfliteFfiInit();
|
||||
databaseFactory = databaseFactoryFfi;
|
||||
}
|
||||
|
||||
final path = await _dbPath();
|
||||
return openDatabase(path, version: _dbVersion, onCreate: _onCreate);
|
||||
}
|
||||
|
||||
Future<String> _dbPath() async {
|
||||
if (!kIsWeb && Platform.isLinux) {
|
||||
final home = Platform.environment['HOME'] ?? '';
|
||||
final dir = Directory('$home/.local/share/central_monitoreo');
|
||||
if (!dir.existsSync()) dir.createSync(recursive: true);
|
||||
return join(dir.path, _dbName);
|
||||
}
|
||||
final base = await getDatabasesPath();
|
||||
return join(base, _dbName);
|
||||
}
|
||||
|
||||
Future<void> _onCreate(Database db, int version) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE configuracion (
|
||||
clave TEXT PRIMARY KEY,
|
||||
valor TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE sesiones_operador (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
nombre TEXT NOT NULL,
|
||||
usuario TEXT NOT NULL,
|
||||
inicio TEXT NOT NULL,
|
||||
fin TEXT,
|
||||
activa INTEGER NOT NULL DEFAULT 1
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE cache_clientes (
|
||||
id INTEGER PRIMARY KEY,
|
||||
nombre TEXT NOT NULL,
|
||||
estado TEXT NOT NULL DEFAULT 'normal',
|
||||
alarmas_activas INTEGER NOT NULL DEFAULT 0,
|
||||
alarmas_criticas INTEGER NOT NULL DEFAULT 0,
|
||||
ultima_actualizacion TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE cache_alarmas (
|
||||
id INTEGER PRIMARY KEY,
|
||||
cliente_id INTEGER NOT NULL,
|
||||
cliente_nombre TEXT,
|
||||
tipo TEXT NOT NULL,
|
||||
severidad INTEGER NOT NULL DEFAULT 1,
|
||||
estado TEXT NOT NULL DEFAULT 'activa',
|
||||
zona_nombre TEXT,
|
||||
timestamp TEXT NOT NULL,
|
||||
notas TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE incidentes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
alarma_id INTEGER,
|
||||
cliente_id INTEGER,
|
||||
cliente_nombre TEXT,
|
||||
tipo TEXT NOT NULL,
|
||||
operador TEXT NOT NULL,
|
||||
notas TEXT,
|
||||
timestamp TEXT NOT NULL,
|
||||
resuelto INTEGER NOT NULL DEFAULT 0,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE operadores (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
nombre TEXT NOT NULL,
|
||||
iniciales TEXT NOT NULL,
|
||||
nivel INTEGER NOT NULL DEFAULT 1,
|
||||
activo INTEGER NOT NULL DEFAULT 1,
|
||||
en_turno INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE sync_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tipo TEXT NOT NULL,
|
||||
estado TEXT NOT NULL,
|
||||
detalle TEXT,
|
||||
timestamp TEXT NOT NULL
|
||||
)
|
||||
''');
|
||||
|
||||
// Configuración por defecto
|
||||
await db.insert('configuracion', {'clave': 'poll_interval_seg', 'valor': '30'});
|
||||
await db.insert('configuracion', {'clave': 'sonido_alerta', 'valor': '1'});
|
||||
}
|
||||
}
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
import 'theme.dart';
|
||||
import 'services/api_auth_service.dart';
|
||||
import 'shell_page.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
sqfliteFfiInit();
|
||||
databaseFactory = databaseFactoryFfi;
|
||||
|
||||
final autenticado = await ApiAuthService.instance.isAuthenticated();
|
||||
runApp(CentroMonitoreoApp(inicioAutenticado: autenticado));
|
||||
}
|
||||
|
||||
class CentroMonitoreoApp extends StatelessWidget {
|
||||
final bool inicioAutenticado;
|
||||
const CentroMonitoreoApp({Key? key, required this.inicioAutenticado})
|
||||
: super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: 'Centro de Monitoreo',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
brightness: Brightness.dark,
|
||||
scaffoldBackgroundColor: AppColors.surfaceLowest,
|
||||
canvasColor: AppColors.surfaceLow,
|
||||
cardColor: AppColors.surfaceHigh,
|
||||
dialogBackgroundColor: AppColors.surfaceHigh,
|
||||
dividerColor: AppColors.outlineVariant,
|
||||
colorScheme: const ColorScheme.dark(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.primaryContainer,
|
||||
secondary: AppColors.secondary,
|
||||
surface: AppColors.surface,
|
||||
onSurface: AppColors.onSurface,
|
||||
error: AppColors.error,
|
||||
onError: AppColors.onError,
|
||||
),
|
||||
),
|
||||
initialRoute: inicioAutenticado ? '/shell' : '/login',
|
||||
routes: {
|
||||
'/login': (_) => const OperadorLoginPage(),
|
||||
'/shell': (_) => const ShellPage(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Login Page ───────────────────────────────────────────────────────────────
|
||||
|
||||
class OperadorLoginPage extends StatefulWidget {
|
||||
const OperadorLoginPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<OperadorLoginPage> createState() => _OperadorLoginPageState();
|
||||
}
|
||||
|
||||
class _OperadorLoginPageState extends State<OperadorLoginPage> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _ctrlUser = TextEditingController();
|
||||
final _ctrlPass = TextEditingController();
|
||||
bool _cargando = false;
|
||||
bool _verPass = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ctrlUser.dispose();
|
||||
_ctrlPass.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _login() async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
setState(() { _cargando = true; _error = null; });
|
||||
|
||||
final ok = await ApiAuthService.instance.login(
|
||||
_ctrlUser.text.trim(),
|
||||
_ctrlPass.text,
|
||||
);
|
||||
|
||||
if (!mounted) return;
|
||||
if (ok) {
|
||||
Navigator.of(context).pushReplacementNamed('/shell');
|
||||
} else {
|
||||
setState(() {
|
||||
_cargando = false;
|
||||
_error = 'Credenciales incorrectas o sin conexión con WebControl.';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.surfaceLowest,
|
||||
body: Center(
|
||||
child: SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 400),
|
||||
child: Column(children: [
|
||||
// Logo
|
||||
Image.asset(
|
||||
'lib/recursos/logo_app.png',
|
||||
width: 96,
|
||||
height: 96,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text('CENTRO DE MONITOREO',
|
||||
style: appHeadline(
|
||||
size: 18,
|
||||
weight: FontWeight.w800,
|
||||
color: AppColors.primary,
|
||||
spacing: 2.0)),
|
||||
const SizedBox(height: 6),
|
||||
Text('Acceso para operadores autorizados',
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// Card de login
|
||||
Container(
|
||||
padding: const EdgeInsets.all(32),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: AppColors.outlineVariant, width: 1),
|
||||
),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||||
Text('Iniciar sesión',
|
||||
style: appHeadline(size: 16, weight: FontWeight.w700)),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Usuario
|
||||
_campo(
|
||||
controller: _ctrlUser,
|
||||
label: 'Usuario',
|
||||
icono: Icons.person_outline,
|
||||
validator: (v) =>
|
||||
(v == null || v.trim().isEmpty) ? 'Ingresa tu usuario' : null,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Contraseña
|
||||
_campo(
|
||||
controller: _ctrlPass,
|
||||
label: 'Contraseña',
|
||||
icono: Icons.lock_outline,
|
||||
obscure: !_verPass,
|
||||
sufijo: IconButton(
|
||||
icon: Icon(
|
||||
_verPass ? Icons.visibility_off : Icons.visibility,
|
||||
color: AppColors.outline,
|
||||
size: 18,
|
||||
),
|
||||
onPressed: () => setState(() => _verPass = !_verPass),
|
||||
),
|
||||
validator: (v) =>
|
||||
(v == null || v.isEmpty) ? 'Ingresa tu contraseña' : null,
|
||||
onSubmit: (_) => _login(),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Error
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Text(_error!,
|
||||
style: appLabel(size: 12, color: AppColors.error)),
|
||||
),
|
||||
|
||||
// Botón
|
||||
SizedBox(
|
||||
height: 48,
|
||||
child: ElevatedButton(
|
||||
onPressed: _cargando ? null : _login,
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.primaryContainer,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10)),
|
||||
),
|
||||
child: _cargando
|
||||
? const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: AppColors.primaryContainer),
|
||||
)
|
||||
: Text('INGRESAR',
|
||||
style: appHeadline(
|
||||
size: 13,
|
||||
weight: FontWeight.w800,
|
||||
color: AppColors.primaryContainer,
|
||||
spacing: 1.2)),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 32),
|
||||
Text('Telcotronics · WebControl',
|
||||
style: appLabel(size: 11, color: AppColors.outlineVariant)),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _campo({
|
||||
required TextEditingController controller,
|
||||
required String label,
|
||||
required IconData icono,
|
||||
bool obscure = false,
|
||||
Widget? sufijo,
|
||||
String? Function(String?)? validator,
|
||||
void Function(String)? onSubmit,
|
||||
}) =>
|
||||
TextFormField(
|
||||
controller: controller,
|
||||
obscureText: obscure,
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
onFieldSubmitted: onSubmit,
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
labelStyle: appLabel(size: 12, color: AppColors.outline),
|
||||
prefixIcon: Icon(icono, color: AppColors.outline, size: 18),
|
||||
suffixIcon: sufijo,
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceHigh,
|
||||
contentPadding:
|
||||
const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
borderSide: const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
borderSide: const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
borderSide: const BorderSide(color: AppColors.primary, width: 1.5),
|
||||
),
|
||||
errorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
borderSide: const BorderSide(color: AppColors.error),
|
||||
),
|
||||
focusedErrorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
borderSide: const BorderSide(color: AppColors.error, width: 1.5),
|
||||
),
|
||||
),
|
||||
validator: validator,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
class ClientesPage extends StatelessWidget {
|
||||
const ClientesPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Clientes', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Estado de todos los clientes', style: appLabel(size: 14)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
class ConfiguracionPage extends StatelessWidget {
|
||||
const ConfiguracionPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Configuración', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Parámetros del sistema', style: appLabel(size: 14)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/dao/cache_alarmas_dao.dart';
|
||||
import '../db/dao/cache_clientes_dao.dart';
|
||||
import '../db/dao/incidentes_dao.dart';
|
||||
|
||||
class DashboardPage extends StatefulWidget {
|
||||
const DashboardPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<DashboardPage> createState() => _DashboardPageState();
|
||||
}
|
||||
|
||||
class _DashboardPageState extends State<DashboardPage> {
|
||||
final _alarmasDao = CacheAlarmasDao();
|
||||
final _clientesDao = CacheClientesDao();
|
||||
final _incidentesDao = IncidentesDao();
|
||||
|
||||
List<Map<String, dynamic>> _alarmas = [];
|
||||
List<Map<String, dynamic>> _clientes = [];
|
||||
List<Map<String, dynamic>> _incidentes = [];
|
||||
|
||||
int _totalClientes = 0;
|
||||
int _totalActivas = 0;
|
||||
int _totalCriticas = 0;
|
||||
int _totalPendientes = 0;
|
||||
|
||||
bool _cargando = true;
|
||||
DateTime? _ultimaActualizacion;
|
||||
Timer? _timer;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargar();
|
||||
_timer = Timer.periodic(const Duration(seconds: 30), (_) => _cargar());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _cargar() async {
|
||||
if (!mounted) return;
|
||||
setState(() => _cargando = true);
|
||||
|
||||
final results = await Future.wait<dynamic>([
|
||||
_clientesDao.getTodos(),
|
||||
_alarmasDao.getActivas(),
|
||||
_incidentesDao.getRecientes(limit: 8),
|
||||
_incidentesDao.getPendientes(),
|
||||
_alarmasDao.contarActivas(),
|
||||
_alarmasDao.contarCriticas(),
|
||||
_clientesDao.contarActivos(),
|
||||
]);
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_clientes = List<Map<String, dynamic>>.from(results[0] as List);
|
||||
_alarmas = List<Map<String, dynamic>>.from(results[1] as List);
|
||||
_incidentes = List<Map<String, dynamic>>.from(results[2] as List);
|
||||
_totalPendientes = (results[3] as List).length;
|
||||
_totalActivas = results[4] as int;
|
||||
_totalCriticas = results[5] as int;
|
||||
_totalClientes = results[6] as int;
|
||||
_cargando = false;
|
||||
_ultimaActualizacion = DateTime.now();
|
||||
});
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
String _timeAgo(String? iso) {
|
||||
if (iso == null) return '';
|
||||
final dt = DateTime.tryParse(iso);
|
||||
if (dt == null) return '';
|
||||
final diff = DateTime.now().difference(dt);
|
||||
if (diff.inSeconds < 60) return 'ahora';
|
||||
if (diff.inMinutes < 60) return 'hace ${diff.inMinutes} min';
|
||||
if (diff.inHours < 24) return 'hace ${diff.inHours} h';
|
||||
return 'hace ${diff.inDays} d';
|
||||
}
|
||||
|
||||
String _horaCorta(DateTime dt) {
|
||||
final h = dt.hour.toString().padLeft(2, '0');
|
||||
final m = dt.minute.toString().padLeft(2, '0');
|
||||
final s = dt.second.toString().padLeft(2, '0');
|
||||
return '$h:$m:$s';
|
||||
}
|
||||
|
||||
Color _colorSeveridad(int sev) {
|
||||
if (sev >= 4) return AppColors.alarmaActiva;
|
||||
if (sev == 3) return AppColors.clienteAlerta;
|
||||
return AppColors.alarmaSilenciada;
|
||||
}
|
||||
|
||||
String _labelSeveridad(int sev) {
|
||||
if (sev >= 5) return 'MAX';
|
||||
if (sev == 4) return 'CRIT';
|
||||
if (sev == 3) return 'ALTA';
|
||||
if (sev == 2) return 'MED';
|
||||
return 'BAJA';
|
||||
}
|
||||
|
||||
Color _colorEstadoCliente(String? estado) {
|
||||
if (estado == 'critico') return AppColors.clienteCritico;
|
||||
if (estado == 'alerta') return AppColors.clienteAlerta;
|
||||
return AppColors.clienteOk;
|
||||
}
|
||||
|
||||
// ── Build ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.fromLTRB(28, 24, 28, 32),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
_headerRow(),
|
||||
const SizedBox(height: 24),
|
||||
_statCards(),
|
||||
const SizedBox(height: 24),
|
||||
IntrinsicHeight(
|
||||
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Expanded(flex: 3, child: _alarmasSection()),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(flex: 2, child: _clientesSection()),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_incidentesSection(),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Header ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Widget _headerRow() => Row(children: [
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Dashboard', style: appHeadline(size: 22, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
_ultimaActualizacion != null
|
||||
? 'Actualizado a las ${_horaCorta(_ultimaActualizacion!)}'
|
||||
: 'Cargando…',
|
||||
style: appLabel(size: 12, color: AppColors.outline),
|
||||
),
|
||||
]),
|
||||
const Spacer(),
|
||||
if (_cargando)
|
||||
const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.primary),
|
||||
)
|
||||
else
|
||||
IconButton(
|
||||
tooltip: 'Actualizar ahora',
|
||||
icon: const Icon(Icons.refresh, color: AppColors.outline, size: 20),
|
||||
onPressed: _cargar,
|
||||
),
|
||||
]);
|
||||
|
||||
// ── Stat cards ───────────────────────────────────────────────────────────────
|
||||
|
||||
Widget _statCards() => Row(children: [
|
||||
Expanded(child: _statCard(
|
||||
icono: Icons.business,
|
||||
color: AppColors.primary,
|
||||
valor: _totalClientes,
|
||||
label: 'Clientes activos',
|
||||
)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: _statCard(
|
||||
icono: Icons.notifications_active,
|
||||
color: AppColors.clienteAlerta,
|
||||
valor: _totalActivas,
|
||||
label: 'Alarmas activas',
|
||||
)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: _statCard(
|
||||
icono: Icons.warning_amber_rounded,
|
||||
color: AppColors.alarmaActiva,
|
||||
valor: _totalCriticas,
|
||||
label: 'Críticas (sev ≥4)',
|
||||
highlight: _totalCriticas > 0,
|
||||
)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: _statCard(
|
||||
icono: Icons.assignment_late_outlined,
|
||||
color: AppColors.secondary,
|
||||
valor: _totalPendientes,
|
||||
label: 'Incidentes pend.',
|
||||
)),
|
||||
]);
|
||||
|
||||
Widget _statCard({
|
||||
required IconData icono,
|
||||
required Color color,
|
||||
required int valor,
|
||||
required String label,
|
||||
bool highlight = false,
|
||||
}) =>
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18),
|
||||
decoration: BoxDecoration(
|
||||
color: highlight ? color.withOpacity(0.12) : AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: highlight ? color.withOpacity(0.4) : AppColors.outlineVariant,
|
||||
),
|
||||
),
|
||||
child: Row(children: [
|
||||
Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.15),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Icon(icono, color: color, size: 20),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(
|
||||
'$valor',
|
||||
style: appHeadline(
|
||||
size: 26, weight: FontWeight.w800, color: highlight ? color : AppColors.onSurface),
|
||||
),
|
||||
Text(label, style: appLabel(size: 11, color: AppColors.outline)),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
|
||||
// ── Alarmas activas ──────────────────────────────────────────────────────────
|
||||
|
||||
Widget _alarmasSection() => _card(
|
||||
title: 'Alarmas activas',
|
||||
icono: Icons.notifications_active_outlined,
|
||||
badge: _totalActivas > 0 ? '$_totalActivas' : null,
|
||||
badgeColor: _totalCriticas > 0 ? AppColors.alarmaActiva : AppColors.clienteAlerta,
|
||||
child: _alarmas.isEmpty
|
||||
? _emptyState('Sin alarmas activas', Icons.notifications_none)
|
||||
: Column(
|
||||
children: _alarmas.take(12).map(_alarmaRow).toList(),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _alarmaRow(Map<String, dynamic> a) {
|
||||
final sev = (a['severidad'] as int?) ?? 1;
|
||||
final color = _colorSeveridad(sev);
|
||||
final label = _labelSeveridad(sev);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 5),
|
||||
child: Row(children: [
|
||||
// Badge severidad
|
||||
Container(
|
||||
width: 42,
|
||||
padding: const EdgeInsets.symmetric(vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.15),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: color.withOpacity(0.3)),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(label, style: appLabel(size: 10, weight: FontWeight.bold, color: color)),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
// Contenido
|
||||
Expanded(
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(
|
||||
a['tipo'] as String? ?? '—',
|
||||
style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
Row(children: [
|
||||
if (a['cliente_nombre'] != null)
|
||||
Text(
|
||||
a['cliente_nombre'] as String,
|
||||
style: appLabel(size: 11, color: AppColors.primary),
|
||||
),
|
||||
if (a['zona_nombre'] != null) ...[
|
||||
Text(' · ', style: appLabel(size: 11, color: AppColors.outline)),
|
||||
Text(
|
||||
a['zona_nombre'] as String,
|
||||
style: appLabel(size: 11, color: AppColors.onSurfaceVariant),
|
||||
),
|
||||
],
|
||||
]),
|
||||
]),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
_timeAgo(a['timestamp'] as String?),
|
||||
style: appLabel(size: 11, color: AppColors.outline),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Clientes ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Widget _clientesSection() => _card(
|
||||
title: 'Estado de clientes',
|
||||
icono: Icons.business_outlined,
|
||||
badge: _totalClientes > 0 ? '$_totalClientes' : null,
|
||||
badgeColor: AppColors.primary,
|
||||
child: _clientes.isEmpty
|
||||
? _emptyState('Sin clientes en caché', Icons.business_outlined)
|
||||
: Column(
|
||||
children: _clientes.take(10).map(_clienteRow).toList(),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _clienteRow(Map<String, dynamic> c) {
|
||||
final estado = c['estado'] as String? ?? 'normal';
|
||||
final color = _colorEstadoCliente(estado);
|
||||
final criticas = (c['alarmas_criticas'] as int?) ?? 0;
|
||||
final activas = (c['alarmas_activas'] as int?) ?? 0;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 5),
|
||||
child: Row(children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(shape: BoxShape.circle, color: color),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
c['nombre'] as String? ?? '—',
|
||||
style: appLabel(
|
||||
size: 12,
|
||||
weight: FontWeight.w500,
|
||||
color: criticas > 0 ? AppColors.onSurface : AppColors.onSurfaceVariant,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
if (criticas > 0)
|
||||
_pillCount('$criticas', AppColors.alarmaActiva)
|
||||
else if (activas > 0)
|
||||
_pillCount('$activas', AppColors.clienteAlerta)
|
||||
else
|
||||
Text('OK', style: appLabel(size: 11, color: AppColors.clienteOk)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _pillCount(String text, Color color) => Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.15),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(text, style: appLabel(size: 11, weight: FontWeight.bold, color: color)),
|
||||
);
|
||||
|
||||
// ── Incidentes recientes ─────────────────────────────────────────────────────
|
||||
|
||||
Widget _incidentesSection() => _card(
|
||||
title: 'Últimos incidentes',
|
||||
icono: Icons.assignment_outlined,
|
||||
child: _incidentes.isEmpty
|
||||
? _emptyState('Sin incidentes registrados', Icons.assignment_outlined)
|
||||
: Column(children: [
|
||||
_incidenteHeader(),
|
||||
const Divider(color: AppColors.outlineVariant, height: 12),
|
||||
..._incidentes.map(_incidenteRow),
|
||||
]),
|
||||
);
|
||||
|
||||
Widget _incidenteHeader() => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Row(children: [
|
||||
Expanded(flex: 2, child: Text('Tipo', style: appLabel(size: 11, color: AppColors.outline))),
|
||||
Expanded(flex: 2, child: Text('Cliente', style: appLabel(size: 11, color: AppColors.outline))),
|
||||
Expanded(flex: 2, child: Text('Operador', style: appLabel(size: 11, color: AppColors.outline))),
|
||||
SizedBox(width: 80, child: Text('Cuándo', style: appLabel(size: 11, color: AppColors.outline))),
|
||||
SizedBox(width: 70, child: Text('Estado', style: appLabel(size: 11, color: AppColors.outline))),
|
||||
]),
|
||||
);
|
||||
|
||||
Widget _incidenteRow(Map<String, dynamic> inc) {
|
||||
final resuelto = (inc['resuelto'] as int?) == 1;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 5),
|
||||
child: Row(children: [
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Text(
|
||||
inc['tipo'] as String? ?? '—',
|
||||
style: appLabel(size: 12, weight: FontWeight.w500, color: AppColors.onSurface),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Text(
|
||||
inc['cliente_nombre'] as String? ?? '—',
|
||||
style: appLabel(size: 12, color: AppColors.primary),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Text(
|
||||
inc['operador'] as String? ?? '—',
|
||||
style: appLabel(size: 12, color: AppColors.onSurfaceVariant),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 80,
|
||||
child: Text(
|
||||
_timeAgo(inc['timestamp'] as String?),
|
||||
style: appLabel(size: 11, color: AppColors.outline),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 70,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: resuelto
|
||||
? AppColors.clienteOk.withOpacity(0.12)
|
||||
: AppColors.clienteAlerta.withOpacity(0.12),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(
|
||||
resuelto ? 'Resuelto' : 'Pendiente',
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.w600,
|
||||
color: resuelto ? AppColors.clienteOk : AppColors.clienteAlerta,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Shared widgets ───────────────────────────────────────────────────────────
|
||||
|
||||
Widget _card({
|
||||
required String title,
|
||||
required IconData icono,
|
||||
required Widget child,
|
||||
String? badge,
|
||||
Color badgeColor = AppColors.primary,
|
||||
}) =>
|
||||
Container(
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant),
|
||||
),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Row(children: [
|
||||
Icon(icono, size: 16, color: AppColors.outline),
|
||||
const SizedBox(width: 8),
|
||||
Text(title, style: appHeadline(size: 13, weight: FontWeight.w700)),
|
||||
if (badge != null) ...[
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: badgeColor.withOpacity(0.15),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(badge, style: appLabel(size: 11, weight: FontWeight.bold, color: badgeColor)),
|
||||
),
|
||||
],
|
||||
]),
|
||||
const SizedBox(height: 14),
|
||||
child,
|
||||
]),
|
||||
);
|
||||
|
||||
Widget _emptyState(String texto, IconData icono) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 24),
|
||||
child: Center(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Icon(icono, size: 32, color: AppColors.outlineVariant),
|
||||
const SizedBox(height: 10),
|
||||
Text(texto, style: appLabel(size: 12, color: AppColors.outline)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Esperando sincronización con Centinel',
|
||||
style: appLabel(size: 11, color: AppColors.outlineVariant)),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
class DispositivosPage extends StatelessWidget {
|
||||
const DispositivosPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Dispositivos', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Dispositivos Hikvision registrados en Centinel', style: appLabel(size: 14)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
class IncidentesPage extends StatelessWidget {
|
||||
const IncidentesPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Incidentes', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Registro de incidentes gestionados', style: appLabel(size: 14)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,746 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/dao/cache_alarmas_dao.dart';
|
||||
import '../db/dao/cache_clientes_dao.dart';
|
||||
import '../db/dao/incidentes_dao.dart';
|
||||
import '../services/api_auth_service.dart';
|
||||
|
||||
class MonitoreoPage extends StatefulWidget {
|
||||
const MonitoreoPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<MonitoreoPage> createState() => _MonitoreoPageState();
|
||||
}
|
||||
|
||||
class _MonitoreoPageState extends State<MonitoreoPage> {
|
||||
final _alarmasDao = CacheAlarmasDao();
|
||||
final _clientesDao = CacheClientesDao();
|
||||
final _incidentesDao = IncidentesDao();
|
||||
|
||||
List<Map<String, dynamic>> _todasAlarmas = [];
|
||||
List<Map<String, dynamic>> _alarmasFiltradas = [];
|
||||
List<Map<String, dynamic>> _clientes = [];
|
||||
|
||||
String _filtroEstado = 'activa'; // 'todas' | 'activa' | 'silenciada'
|
||||
int _filtroSeveridad = 0; // 0=todas, 3=alta, 4=critica
|
||||
int? _filtroClienteId; // null = todos
|
||||
|
||||
bool _cargando = true;
|
||||
String _operador = '';
|
||||
Timer? _timer;
|
||||
|
||||
static const _tiposIncidenteId = [
|
||||
'verificacion',
|
||||
'contacto_cliente',
|
||||
'despacho_patrulla',
|
||||
'llamada_policia',
|
||||
'falsa_alarma',
|
||||
'otro',
|
||||
];
|
||||
static const _tiposIncidenteLabel = [
|
||||
'Verificación',
|
||||
'Contacto con cliente',
|
||||
'Despacho de patrulla',
|
||||
'Llamada a policía',
|
||||
'Falsa alarma',
|
||||
'Otro',
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarOperador();
|
||||
_cargar();
|
||||
_timer = Timer.periodic(const Duration(seconds: 30), (_) => _cargar());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _cargarOperador() async {
|
||||
final u = await ApiAuthService.instance.getUsuario();
|
||||
if (mounted) setState(() => _operador = u ?? '');
|
||||
}
|
||||
|
||||
Future<void> _cargar() async {
|
||||
if (!mounted) return;
|
||||
setState(() => _cargando = true);
|
||||
|
||||
final results = await Future.wait([
|
||||
_alarmasDao.getTodas(limit: 200),
|
||||
_clientesDao.getTodos(),
|
||||
]);
|
||||
|
||||
if (!mounted) return;
|
||||
_todasAlarmas = (results[0] as List).cast<Map<String, dynamic>>();
|
||||
_clientes = (results[1] as List).cast<Map<String, dynamic>>();
|
||||
_aplicarFiltros();
|
||||
setState(() => _cargando = false);
|
||||
}
|
||||
|
||||
void _aplicarFiltros() {
|
||||
var lista = List<Map<String, dynamic>>.from(_todasAlarmas);
|
||||
|
||||
if (_filtroEstado != 'todas') {
|
||||
lista = lista.where((a) => a['estado'] == _filtroEstado).toList();
|
||||
}
|
||||
if (_filtroSeveridad > 0) {
|
||||
lista = lista.where((a) => ((a['severidad'] as int?) ?? 0) >= _filtroSeveridad).toList();
|
||||
}
|
||||
if (_filtroClienteId != null) {
|
||||
lista = lista.where((a) => a['cliente_id'] == _filtroClienteId).toList();
|
||||
}
|
||||
|
||||
lista.sort((a, b) {
|
||||
final sevCmp = ((b['severidad'] as int?) ?? 0)
|
||||
.compareTo((a['severidad'] as int?) ?? 0);
|
||||
if (sevCmp != 0) return sevCmp;
|
||||
return ((b['timestamp'] as String?) ?? '')
|
||||
.compareTo((a['timestamp'] as String?) ?? '');
|
||||
});
|
||||
|
||||
setState(() => _alarmasFiltradas = lista);
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
String _timeAgo(String? iso) {
|
||||
if (iso == null) return '';
|
||||
final dt = DateTime.tryParse(iso);
|
||||
if (dt == null) return '';
|
||||
final diff = DateTime.now().difference(dt);
|
||||
if (diff.inSeconds < 60) return 'ahora';
|
||||
if (diff.inMinutes < 60) return '${diff.inMinutes} min';
|
||||
if (diff.inHours < 24) return '${diff.inHours} h';
|
||||
return '${diff.inDays} d';
|
||||
}
|
||||
|
||||
Color _colorSev(int sev) {
|
||||
if (sev >= 4) return AppColors.alarmaActiva;
|
||||
if (sev == 3) return AppColors.clienteAlerta;
|
||||
return AppColors.alarmaSilenciada;
|
||||
}
|
||||
|
||||
String _labelSev(int sev) {
|
||||
if (sev >= 5) return 'MAX';
|
||||
if (sev == 4) return 'CRIT';
|
||||
if (sev == 3) return 'ALTA';
|
||||
if (sev == 2) return 'MED';
|
||||
return 'BAJA';
|
||||
}
|
||||
|
||||
int get _countActivas => _todasAlarmas.where((a) => a['estado'] == 'activa').length;
|
||||
int get _countCriticas => _todasAlarmas.where((a) => a['estado'] == 'activa' && ((a['severidad'] as int?) ?? 0) >= 4).length;
|
||||
int get _countSilenciadas => _todasAlarmas.where((a) => a['estado'] == 'silenciada').length;
|
||||
|
||||
// ── Acciones inline ───────────────────────────────────────────────────────────
|
||||
|
||||
Future<void> _escalar(Map<String, dynamic> alarma) async {
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => _dialogConfirmar(
|
||||
titulo: 'Escalar alarma',
|
||||
cuerpo: 'Se registrará la escalación de esta alarma.\n'
|
||||
'Un supervisor recibirá la notificación.',
|
||||
labelBoton: 'ESCALAR',
|
||||
colorBoton: AppColors.alarmaActiva,
|
||||
),
|
||||
);
|
||||
if (ok != true || !mounted) return;
|
||||
|
||||
await _incidentesDao.registrar(
|
||||
alarmaId: alarma['id'] as int?,
|
||||
clienteId: alarma['cliente_id'] as int?,
|
||||
clienteNombre: alarma['cliente_nombre'] as String?,
|
||||
tipo: 'escalacion',
|
||||
operador: _operador,
|
||||
notas: 'Alarma escalada desde Monitoreo. '
|
||||
'Severidad: ${_labelSev((alarma['severidad'] as int?) ?? 0)}',
|
||||
);
|
||||
|
||||
_mostrarSnack('Alarma escalada y registrada.', AppColors.alarmaActiva);
|
||||
}
|
||||
|
||||
Future<void> _silenciar(Map<String, dynamic> alarma) async {
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => _dialogConfirmar(
|
||||
titulo: 'Silenciar alarma',
|
||||
cuerpo: 'La alarma dejará de aparecer en alarmas activas.\n'
|
||||
'Queda registrada en el historial.',
|
||||
labelBoton: 'SILENCIAR',
|
||||
colorBoton: AppColors.clienteAlerta,
|
||||
),
|
||||
);
|
||||
if (ok != true || !mounted) return;
|
||||
|
||||
final id = alarma['id'] as int?;
|
||||
if (id != null) await _alarmasDao.actualizarEstado(id, 'silenciada');
|
||||
|
||||
await _incidentesDao.registrar(
|
||||
alarmaId: id,
|
||||
clienteId: alarma['cliente_id'] as int?,
|
||||
clienteNombre: alarma['cliente_nombre'] as String?,
|
||||
tipo: 'silenciado',
|
||||
operador: _operador,
|
||||
);
|
||||
|
||||
_mostrarSnack('Alarma silenciada.', AppColors.clienteAlerta);
|
||||
_cargar();
|
||||
}
|
||||
|
||||
Future<void> _registrarIncidente(Map<String, dynamic> alarma) async {
|
||||
String tipoSeleccionado = _tiposIncidenteId[0];
|
||||
final ctrlNotas = TextEditingController();
|
||||
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => StatefulBuilder(
|
||||
builder: (ctx, setDlg) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
title: Text('Registrar incidente',
|
||||
style: appHeadline(size: 16, weight: FontWeight.w700)),
|
||||
content: SizedBox(
|
||||
width: 420,
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
// Info de alarma
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceHighest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(children: [
|
||||
const Icon(Icons.notifications_active_outlined,
|
||||
size: 16, color: AppColors.outline),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(alarma['tipo'] as String? ?? '—',
|
||||
style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface)),
|
||||
if (alarma['cliente_nombre'] != null)
|
||||
Text(alarma['cliente_nombre'] as String,
|
||||
style: appLabel(size: 11, color: AppColors.primary)),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
// Tipo incidente
|
||||
DropdownButtonFormField<String>(
|
||||
value: tipoSeleccionado,
|
||||
dropdownColor: AppColors.surfaceHighest,
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
decoration: _inputDecoration('Tipo de incidente'),
|
||||
items: List.generate(
|
||||
_tiposIncidenteId.length,
|
||||
(i) => DropdownMenuItem(
|
||||
value: _tiposIncidenteId[i],
|
||||
child: Text(_tiposIncidenteLabel[i]),
|
||||
),
|
||||
),
|
||||
onChanged: (v) {
|
||||
if (v != null) setDlg(() => tipoSeleccionado = v);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
// Notas
|
||||
TextField(
|
||||
controller: ctrlNotas,
|
||||
maxLines: 3,
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
decoration: _inputDecoration('Notas (opcional)'),
|
||||
),
|
||||
]),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: Text('Cancelar', style: appLabel(color: AppColors.onSurfaceVariant)),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.primaryContainer,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: Text('REGISTRAR',
|
||||
style: appLabel(weight: FontWeight.bold, color: AppColors.primaryContainer)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
ctrlNotas.dispose();
|
||||
if (ok != true || !mounted) return;
|
||||
|
||||
await _incidentesDao.registrar(
|
||||
alarmaId: alarma['id'] as int?,
|
||||
clienteId: alarma['cliente_id'] as int?,
|
||||
clienteNombre: alarma['cliente_nombre'] as String?,
|
||||
tipo: tipoSeleccionado,
|
||||
operador: _operador,
|
||||
notas: ctrlNotas.text.trim().isEmpty ? null : ctrlNotas.text.trim(),
|
||||
);
|
||||
|
||||
_mostrarSnack('Incidente registrado.', AppColors.primary);
|
||||
}
|
||||
|
||||
Widget _dialogConfirmar({
|
||||
required String titulo,
|
||||
required String cuerpo,
|
||||
required String labelBoton,
|
||||
required Color colorBoton,
|
||||
}) =>
|
||||
AlertDialog(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
title: Text(titulo, style: appHeadline(size: 16, weight: FontWeight.w700)),
|
||||
content: Text(cuerpo, style: appLabel(size: 13, color: AppColors.onSurface)),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text('Cancelar', style: appLabel(color: AppColors.onSurfaceVariant)),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: Text(labelBoton,
|
||||
style: appLabel(weight: FontWeight.bold, color: colorBoton)),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
InputDecoration _inputDecoration(String label) => InputDecoration(
|
||||
labelText: label,
|
||||
labelStyle: appLabel(size: 12, color: AppColors.outline),
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceHighest,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: const BorderSide(color: AppColors.outlineVariant)),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: const BorderSide(color: AppColors.outlineVariant)),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: const BorderSide(color: AppColors.primary, width: 1.5)),
|
||||
);
|
||||
|
||||
void _mostrarSnack(String msg, Color color) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text(msg, style: appLabel(color: AppColors.surfaceLowest)),
|
||||
backgroundColor: color,
|
||||
duration: const Duration(seconds: 3),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
margin: const EdgeInsets.all(16),
|
||||
));
|
||||
}
|
||||
|
||||
// ── Build ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
// ── Sección fija: header + filtros + cabecera de tabla ──────────────────
|
||||
Container(
|
||||
color: AppColors.surfaceLowest,
|
||||
padding: const EdgeInsets.fromLTRB(28, 20, 28, 0),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
_headerRow(),
|
||||
const SizedBox(height: 14),
|
||||
_barraFiltros(),
|
||||
const SizedBox(height: 14),
|
||||
_tablaHeader(),
|
||||
const Divider(color: AppColors.outlineVariant, height: 1),
|
||||
]),
|
||||
),
|
||||
// ── Cuerpo scrollable de la tabla ───────────────────────────────────────
|
||||
Expanded(
|
||||
child: _cargando
|
||||
? const Center(
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.primary))
|
||||
: _alarmasFiltradas.isEmpty
|
||||
? _emptyState()
|
||||
: ListView.separated(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 4),
|
||||
itemCount: _alarmasFiltradas.length,
|
||||
separatorBuilder: (_, __) =>
|
||||
const Divider(color: AppColors.outlineVariant, height: 1),
|
||||
itemBuilder: (_, i) => _alarmaRow(_alarmasFiltradas[i]),
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
// ── Header ───────────────────────────────────────────────────────────────────
|
||||
|
||||
Widget _headerRow() => Row(children: [
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Monitoreo', style: appHeadline(size: 22, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 2),
|
||||
RichText(
|
||||
text: TextSpan(children: [
|
||||
TextSpan(
|
||||
text: '$_countActivas activas',
|
||||
style: appLabel(size: 12, color: AppColors.clienteAlerta),
|
||||
),
|
||||
if (_countCriticas > 0) ...[
|
||||
TextSpan(text: ' · ', style: appLabel(size: 12, color: AppColors.outline)),
|
||||
TextSpan(
|
||||
text: '$_countCriticas críticas',
|
||||
style: appLabel(size: 12, color: AppColors.alarmaActiva, weight: FontWeight.bold),
|
||||
),
|
||||
],
|
||||
if (_countSilenciadas > 0) ...[
|
||||
TextSpan(text: ' · ', style: appLabel(size: 12, color: AppColors.outline)),
|
||||
TextSpan(
|
||||
text: '$_countSilenciadas silenciadas',
|
||||
style: appLabel(size: 12, color: AppColors.outline),
|
||||
),
|
||||
],
|
||||
]),
|
||||
),
|
||||
]),
|
||||
const Spacer(),
|
||||
if (_cargando)
|
||||
const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.primary),
|
||||
)
|
||||
else
|
||||
IconButton(
|
||||
tooltip: 'Actualizar',
|
||||
icon: const Icon(Icons.refresh, color: AppColors.outline, size: 20),
|
||||
onPressed: _cargar,
|
||||
),
|
||||
]);
|
||||
|
||||
// ── Filtros ──────────────────────────────────────────────────────────────────
|
||||
|
||||
static const _estadoIds = ['todas', 'activa', 'silenciada'];
|
||||
static const _estadoLabels = ['Todas', 'Activas', 'Silenciadas'];
|
||||
static const _sevIds = [0, 4, 3, 1];
|
||||
static const _sevLabels = ['Todas', 'Críticas', 'Altas', 'Medias/Bajas'];
|
||||
|
||||
Widget _barraFiltros() {
|
||||
final chipEstado = <Widget>[];
|
||||
for (int i = 0; i < _estadoIds.length; i++) {
|
||||
final id = _estadoIds[i];
|
||||
final label = _estadoLabels[i];
|
||||
chipEstado.add(_chip(
|
||||
label: label,
|
||||
seleccionado: _filtroEstado == id,
|
||||
onTap: () {
|
||||
setState(() => _filtroEstado = id);
|
||||
_aplicarFiltros();
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
final chipSev = <Widget>[];
|
||||
for (int i = 0; i < _sevIds.length; i++) {
|
||||
final id = _sevIds[i];
|
||||
final label = _sevLabels[i];
|
||||
Color? color;
|
||||
if (id >= 4) { color = AppColors.alarmaActiva; }
|
||||
else if (id == 3) { color = AppColors.clienteAlerta; }
|
||||
chipSev.add(_chip(
|
||||
label: label,
|
||||
seleccionado: _filtroSeveridad == id,
|
||||
color: color,
|
||||
onTap: () {
|
||||
setState(() => _filtroSeveridad = id);
|
||||
_aplicarFiltros();
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Text('Estado:', style: appLabel(size: 11, color: AppColors.outline)),
|
||||
...chipEstado,
|
||||
const SizedBox(width: 12),
|
||||
Text('Severidad:', style: appLabel(size: 11, color: AppColors.outline)),
|
||||
...chipSev,
|
||||
const SizedBox(width: 12),
|
||||
if (_clientes.isNotEmpty) ...[
|
||||
Text('Cliente:', style: appLabel(size: 11, color: AppColors.outline)),
|
||||
_dropdownCliente(),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _chip({
|
||||
required String label,
|
||||
required bool seleccionado,
|
||||
required VoidCallback onTap,
|
||||
Color? color,
|
||||
}) {
|
||||
final efectivoColor = color ?? AppColors.primary;
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 120),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
|
||||
decoration: BoxDecoration(
|
||||
color: seleccionado ? efectivoColor.withOpacity(0.15) : AppColors.surfaceHighest,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: seleccionado ? efectivoColor.withOpacity(0.5) : AppColors.outlineVariant,
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: appLabel(
|
||||
size: 11,
|
||||
weight: seleccionado ? FontWeight.w600 : FontWeight.normal,
|
||||
color: seleccionado ? efectivoColor : AppColors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _dropdownCliente() => Container(
|
||||
height: 28,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: _filtroClienteId != null
|
||||
? AppColors.primaryContainer
|
||||
: AppColors.surfaceHighest,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: _filtroClienteId != null
|
||||
? AppColors.primary.withOpacity(0.5)
|
||||
: AppColors.outlineVariant,
|
||||
),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<int?>(
|
||||
value: _filtroClienteId,
|
||||
isDense: true,
|
||||
dropdownColor: AppColors.surfaceHigh,
|
||||
style: appLabel(size: 11, color: AppColors.onSurfaceVariant),
|
||||
icon: const Icon(Icons.keyboard_arrow_down, size: 14, color: AppColors.outline),
|
||||
items: [
|
||||
DropdownMenuItem<int?>(
|
||||
value: null,
|
||||
child: Text('Todos', style: appLabel(size: 11)),
|
||||
),
|
||||
..._clientes.map((c) => DropdownMenuItem<int?>(
|
||||
value: c['id'] as int?,
|
||||
child: Text(
|
||||
c['nombre'] as String? ?? '—',
|
||||
style: appLabel(size: 11),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
)),
|
||||
],
|
||||
onChanged: (v) {
|
||||
setState(() => _filtroClienteId = v);
|
||||
_aplicarFiltros();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// ── Tabla ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Widget _tablaHeader() => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Row(children: [
|
||||
const SizedBox(width: 62),
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: Text('Tipo / Descripción',
|
||||
style: appLabel(size: 11, color: AppColors.outline)),
|
||||
),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Text('Cliente', style: appLabel(size: 11, color: AppColors.outline)),
|
||||
),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Text('Zona', style: appLabel(size: 11, color: AppColors.outline)),
|
||||
),
|
||||
const SizedBox(
|
||||
width: 80,
|
||||
child: Text('', style: TextStyle()), // tiempo — no label para ahorrar espacio
|
||||
),
|
||||
const SizedBox(width: 110),
|
||||
]),
|
||||
);
|
||||
|
||||
Widget _alarmaRow(Map<String, dynamic> a) {
|
||||
final sev = (a['severidad'] as int?) ?? 1;
|
||||
final color = _colorSev(sev);
|
||||
final label = _labelSev(sev);
|
||||
final estado = a['estado'] as String? ?? 'activa';
|
||||
final esActiva = estado == 'activa';
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Row(children: [
|
||||
// Badge severidad
|
||||
Container(
|
||||
width: 52,
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(esActiva ? 0.15 : 0.06),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: color.withOpacity(esActiva ? 0.35 : 0.15)),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
label,
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: color.withOpacity(esActiva ? 1.0 : 0.5)),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
// Tipo
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(
|
||||
a['tipo'] as String? ?? '—',
|
||||
style: appLabel(
|
||||
size: 12,
|
||||
weight: FontWeight.w600,
|
||||
color: esActiva ? AppColors.onSurface : AppColors.outline,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (a['notas'] != null && (a['notas'] as String).isNotEmpty)
|
||||
Text(
|
||||
a['notas'] as String,
|
||||
style: appLabel(size: 11, color: AppColors.onSurfaceVariant),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
]),
|
||||
),
|
||||
// Cliente
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Text(
|
||||
a['cliente_nombre'] as String? ?? '—',
|
||||
style: appLabel(
|
||||
size: 12,
|
||||
color: esActiva ? AppColors.primary : AppColors.outline),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
// Zona
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: Text(
|
||||
a['zona_nombre'] as String? ?? '—',
|
||||
style: appLabel(size: 12, color: AppColors.onSurfaceVariant),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
// Tiempo
|
||||
SizedBox(
|
||||
width: 80,
|
||||
child: Text(
|
||||
_timeAgo(a['timestamp'] as String?),
|
||||
style: appLabel(size: 11, color: AppColors.outline),
|
||||
),
|
||||
),
|
||||
// Acciones
|
||||
SizedBox(
|
||||
width: 110,
|
||||
child: esActiva
|
||||
? Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
_accionBtn(
|
||||
icon: Icons.arrow_upward,
|
||||
tooltip: 'Escalar',
|
||||
color: AppColors.alarmaActiva,
|
||||
onTap: () => _escalar(a),
|
||||
),
|
||||
const SizedBox(width: 2),
|
||||
_accionBtn(
|
||||
icon: Icons.volume_off_outlined,
|
||||
tooltip: 'Silenciar',
|
||||
color: AppColors.clienteAlerta,
|
||||
onTap: () => _silenciar(a),
|
||||
),
|
||||
const SizedBox(width: 2),
|
||||
_accionBtn(
|
||||
icon: Icons.note_add_outlined,
|
||||
tooltip: 'Registrar incidente',
|
||||
color: AppColors.primary,
|
||||
onTap: () => _registrarIncidente(a),
|
||||
),
|
||||
])
|
||||
: Text('Silenciada',
|
||||
style: appLabel(size: 11, color: AppColors.outline)),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _accionBtn({
|
||||
required IconData icon,
|
||||
required String tooltip,
|
||||
required Color color,
|
||||
required VoidCallback onTap,
|
||||
}) =>
|
||||
Tooltip(
|
||||
message: tooltip,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: Container(
|
||||
width: 30,
|
||||
height: 30,
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Icon(icon, size: 15, color: color),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// ── Empty state ──────────────────────────────────────────────────────────────
|
||||
|
||||
Widget _emptyState() => Center(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
const Icon(Icons.notifications_none, size: 48, color: AppColors.outlineVariant),
|
||||
const SizedBox(height: 14),
|
||||
Text(
|
||||
_filtroEstado == 'activa'
|
||||
? 'Sin alarmas activas'
|
||||
: 'Sin resultados con los filtros actuales',
|
||||
style: appLabel(size: 14, color: AppColors.outline),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'El sistema sincroniza con Centinel cada 30 segundos',
|
||||
style: appLabel(size: 12, color: AppColors.outlineVariant),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
class OperadoresPage extends StatelessWidget {
|
||||
const OperadoresPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Operadores', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Gestión de operadores y turnos', style: appLabel(size: 14)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
class ReportesPage extends StatelessWidget {
|
||||
const ReportesPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text('Reportes', style: appHeadline(size: 28, weight: FontWeight.w800)),
|
||||
const SizedBox(height: 8),
|
||||
Text('Informes por cliente, operador y período', style: appLabel(size: 14)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 77 KiB |
@@ -0,0 +1,109 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stop-color="#131B2E"/>
|
||||
<stop offset="100%" stop-color="#0A0E14"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="shield_grad" x1="0.5" y1="0" x2="0.5" y2="1">
|
||||
<stop offset="0%" stop-color="#1A3A6E"/>
|
||||
<stop offset="100%" stop-color="#071228"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="shield_border" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stop-color="#4A80D0"/>
|
||||
<stop offset="100%" stop-color="#1A3A6E"/>
|
||||
</linearGradient>
|
||||
<filter id="glow_soft" x="-40%" y="-40%" width="180%" height="180%">
|
||||
<feGaussianBlur stdDeviation="5" result="blur"/>
|
||||
<feMerge>
|
||||
<feMergeNode in="blur"/>
|
||||
<feMergeNode in="blur"/>
|
||||
<feMergeNode in="SourceGraphic"/>
|
||||
</feMerge>
|
||||
</filter>
|
||||
<filter id="glow_strong" x="-80%" y="-80%" width="260%" height="260%">
|
||||
<feGaussianBlur stdDeviation="10" result="blur"/>
|
||||
<feMerge>
|
||||
<feMergeNode in="blur"/>
|
||||
<feMergeNode in="blur"/>
|
||||
<feMergeNode in="blur"/>
|
||||
<feMergeNode in="SourceGraphic"/>
|
||||
</feMerge>
|
||||
</filter>
|
||||
<pattern id="hex" x="0" y="0" width="32" height="28" patternUnits="userSpaceOnUse">
|
||||
<polygon points="16,1 31,8.5 31,19.5 16,27 1,19.5 1,8.5"
|
||||
fill="none" stroke="#1E3A6A" stroke-width="0.6" opacity="0.45"/>
|
||||
</pattern>
|
||||
<clipPath id="clip_bg">
|
||||
<rect x="0" y="0" width="512" height="512" rx="112" ry="112"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<!-- Background -->
|
||||
<rect x="0" y="0" width="512" height="512" rx="112" ry="112" fill="url(#bg)"/>
|
||||
<!-- Hex texture -->
|
||||
<rect x="0" y="0" width="512" height="512" fill="url(#hex)" clip-path="url(#clip_bg)"/>
|
||||
|
||||
<!-- Shield outer (border glow) -->
|
||||
<path d="M256 72 L408 128 L408 278 Q408 384 256 452 Q104 384 104 278 L104 128 Z"
|
||||
fill="url(#shield_grad)" stroke="url(#shield_border)" stroke-width="3.5"
|
||||
filter="url(#glow_soft)"/>
|
||||
|
||||
<!-- Shield inner highlight -->
|
||||
<path d="M256 90 L390 142 L390 276 Q390 372 256 434 Q122 372 122 276 L122 142 Z"
|
||||
fill="none" stroke="#3A6AB0" stroke-width="1.5" opacity="0.5"/>
|
||||
|
||||
<!-- ── RADAR symbol ── -->
|
||||
|
||||
<!-- Arc 3 — outer -->
|
||||
<path d="M174 284 A84 84 0 0 1 338 284"
|
||||
fill="none" stroke="#B0C6FF" stroke-width="2.5" stroke-linecap="round"
|
||||
opacity="0.35" filter="url(#glow_soft)"/>
|
||||
<path d="M192 210 A74 80 0 0 1 320 210"
|
||||
fill="none" stroke="#B0C6FF" stroke-width="2" stroke-linecap="round"
|
||||
opacity="0.3"/>
|
||||
|
||||
<!-- Arc 2 — medium -->
|
||||
<path d="M196 284 A60 60 0 0 1 316 284"
|
||||
fill="none" stroke="#B0C6FF" stroke-width="3" stroke-linecap="round"
|
||||
opacity="0.55" filter="url(#glow_soft)"/>
|
||||
<path d="M210 228 A52 60 0 0 1 302 228"
|
||||
fill="none" stroke="#B0C6FF" stroke-width="2.5" stroke-linecap="round"
|
||||
opacity="0.5"/>
|
||||
|
||||
<!-- Arc 1 — inner -->
|
||||
<path d="M216 284 A40 40 0 0 1 296 284"
|
||||
fill="none" stroke="#C8DAFF" stroke-width="3.5" stroke-linecap="round"
|
||||
opacity="0.75" filter="url(#glow_soft)"/>
|
||||
<path d="M228 249 A32 38 0 0 1 284 249"
|
||||
fill="none" stroke="#C8DAFF" stroke-width="3" stroke-linecap="round"
|
||||
opacity="0.7"/>
|
||||
|
||||
<!-- Vertical antenna line -->
|
||||
<line x1="256" y1="284" x2="256" y2="155"
|
||||
stroke="#B0C6FF" stroke-width="3" stroke-linecap="round"
|
||||
filter="url(#glow_soft)" opacity="0.85"/>
|
||||
|
||||
<!-- Sweep line (rotated 30° from vertical) -->
|
||||
<line x1="256" y1="284" x2="318" y2="172"
|
||||
stroke="#90BAFF" stroke-width="2" stroke-linecap="round"
|
||||
opacity="0.5" filter="url(#glow_soft)"/>
|
||||
|
||||
<!-- Center dot -->
|
||||
<circle cx="256" cy="284" r="7" fill="#B0C6FF" filter="url(#glow_strong)" opacity="1"/>
|
||||
<circle cx="256" cy="284" r="3.5" fill="#FFFFFF" opacity="0.9"/>
|
||||
|
||||
<!-- Signal dot top -->
|
||||
<circle cx="256" cy="153" r="5" fill="#B0C6FF" filter="url(#glow_soft)" opacity="0.9"/>
|
||||
|
||||
<!-- Blip dots on sweep -->
|
||||
<circle cx="287" cy="228" r="4" fill="#90BAFF" filter="url(#glow_soft)" opacity="0.7"/>
|
||||
<circle cx="318" cy="172" r="4" fill="#90BAFF" filter="url(#glow_soft)" opacity="0.5"/>
|
||||
|
||||
<!-- Base horizontal bar -->
|
||||
<line x1="206" y1="316" x2="306" y2="316"
|
||||
stroke="#B0C6FF" stroke-width="2.5" stroke-linecap="round"
|
||||
opacity="0.45"/>
|
||||
<line x1="230" y1="330" x2="282" y2="330"
|
||||
stroke="#B0C6FF" stroke-width="1.5" stroke-linecap="round"
|
||||
opacity="0.3"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.4 KiB |
@@ -0,0 +1,142 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Flujo de autenticación WebControl (2 pasos):
|
||||
///
|
||||
/// Paso 1 — POST /api/auth/empresas { email, paswd }
|
||||
/// → { success, usuario, empresas:[{dba,nombre,rol}], unica }
|
||||
///
|
||||
/// Paso 2 — POST /api/auth/login { email, paswd, dba }
|
||||
/// → { success, token, apiKey, db_tenant, usuario:{id,nombre,usuario,rol} }
|
||||
///
|
||||
/// Uso posterior (llamadas a api.telcotronics.com):
|
||||
/// final h = await ApiAuthService.instance.getCentinelHeaders();
|
||||
class ApiAuthService {
|
||||
static const _base = 'https://api.siax-system.net';
|
||||
|
||||
static const _keyToken = 'webcontrol_token';
|
||||
static const _keyApiKey = 'centinel_api_key';
|
||||
static const _keyTenant = 'centinel_tenant';
|
||||
static const _keyNombre = 'operador_nombre';
|
||||
static const _keyUsuario = 'operador_usuario';
|
||||
|
||||
ApiAuthService._();
|
||||
static final ApiAuthService instance = ApiAuthService._();
|
||||
|
||||
// ── Paso 1: obtener empresas del usuario ──────────────────────
|
||||
Future<List<Map<String, dynamic>>?> getEmpresas(
|
||||
String email, String paswd) async {
|
||||
try {
|
||||
final resp = await http.post(
|
||||
Uri.parse('$_base/api/auth/empresas'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'accept': 'application/json',
|
||||
},
|
||||
body: jsonEncode({'email': email, 'paswd': paswd}),
|
||||
).timeout(const Duration(seconds: 10));
|
||||
|
||||
if (resp.statusCode != 200) return null;
|
||||
final body = jsonDecode(resp.body) as Map<String, dynamic>;
|
||||
if (body['success'] != true) return null;
|
||||
|
||||
return List<Map<String, dynamic>>.from(
|
||||
body['empresas'] as List? ?? []);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Paso 2: login completo con dba ────────────────────────────
|
||||
Future<bool> login(String email, String paswd, {String? dba}) async {
|
||||
try {
|
||||
// Paso 1: obtener dba si no se pasó
|
||||
String? dbaTenant = dba;
|
||||
if (dbaTenant == null) {
|
||||
final empresas = await getEmpresas(email, paswd);
|
||||
if (empresas == null || empresas.isEmpty) return false;
|
||||
dbaTenant = empresas.first['dba'] as String?;
|
||||
if (dbaTenant == null) return false;
|
||||
}
|
||||
|
||||
// Paso 2: login real
|
||||
final resp = await http.post(
|
||||
Uri.parse('$_base/api/auth/login'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'accept': 'application/json',
|
||||
},
|
||||
body: jsonEncode({'email': email, 'paswd': paswd, 'dba': dbaTenant}),
|
||||
).timeout(const Duration(seconds: 10));
|
||||
|
||||
if (resp.statusCode != 200) return false;
|
||||
|
||||
final body = jsonDecode(resp.body) as Map<String, dynamic>;
|
||||
if (body['success'] != true) return false;
|
||||
|
||||
final token = body['token'] as String?;
|
||||
final apiKey = body['apiKey'] as String?;
|
||||
final tenant = body['db_tenant'] as String?;
|
||||
final usr = body['usuario'] as Map<String, dynamic>?;
|
||||
final nombre = usr?['nombre'] as String? ?? email;
|
||||
final usuario = usr?['usuario'] as String? ?? email;
|
||||
|
||||
if (apiKey == null || tenant == null) return false;
|
||||
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (token != null) await prefs.setString(_keyToken, token);
|
||||
await prefs.setString(_keyApiKey, apiKey);
|
||||
await prefs.setString(_keyTenant, tenant);
|
||||
await prefs.setString(_keyNombre, nombre);
|
||||
await prefs.setString(_keyUsuario, usuario);
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Logout ────────────────────────────────────────────────────
|
||||
Future<void> logout() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keyToken);
|
||||
await prefs.remove(_keyApiKey);
|
||||
await prefs.remove(_keyTenant);
|
||||
await prefs.remove(_keyNombre);
|
||||
await prefs.remove(_keyUsuario);
|
||||
}
|
||||
|
||||
// ── Estado ────────────────────────────────────────────────────
|
||||
Future<bool> isAuthenticated() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final apiKey = prefs.getString(_keyApiKey);
|
||||
return apiKey != null && apiKey.isNotEmpty;
|
||||
}
|
||||
|
||||
// ── Headers para api.telcotronics.com ─────────────────────────
|
||||
Future<Map<String, String>?> getCentinelHeaders() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final apiKey = prefs.getString(_keyApiKey);
|
||||
final tenant = prefs.getString(_keyTenant);
|
||||
if (apiKey == null || apiKey.isEmpty) return null;
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
'accept': 'application/json',
|
||||
'x-api-key': apiKey,
|
||||
'x-database': tenant ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
// ── Getters ───────────────────────────────────────────────────
|
||||
Future<String?> getNombre() async =>
|
||||
(await SharedPreferences.getInstance()).getString(_keyNombre);
|
||||
|
||||
Future<String?> getUsuario() async =>
|
||||
(await SharedPreferences.getInstance()).getString(_keyUsuario);
|
||||
|
||||
Future<String?> getApiKey() async =>
|
||||
(await SharedPreferences.getInstance()).getString(_keyApiKey);
|
||||
|
||||
Future<String?> getToken() async =>
|
||||
(await SharedPreferences.getInstance()).getString(_keyToken);
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'theme.dart';
|
||||
import 'services/api_auth_service.dart';
|
||||
import 'db/dao/sesiones_dao.dart';
|
||||
import 'pages/dashboard_page.dart';
|
||||
import 'pages/monitoreo_page.dart';
|
||||
import 'pages/clientes_page.dart';
|
||||
import 'pages/operadores_page.dart';
|
||||
import 'pages/incidentes_page.dart';
|
||||
import 'pages/dispositivos_page.dart';
|
||||
import 'pages/reportes_page.dart';
|
||||
import 'pages/configuracion_page.dart';
|
||||
|
||||
class ShellPage extends StatefulWidget {
|
||||
const ShellPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<ShellPage> createState() => _ShellPageState();
|
||||
}
|
||||
|
||||
class _ShellPageState extends State<ShellPage> {
|
||||
int _indice = 0;
|
||||
String _operadorNombre = 'Operador';
|
||||
bool _apiConectada = false;
|
||||
|
||||
final _sesionesDao = SesionesDao();
|
||||
|
||||
static const _paginas = [
|
||||
DashboardPage(),
|
||||
MonitoreoPage(),
|
||||
ClientesPage(),
|
||||
OperadoresPage(),
|
||||
IncidentesPage(),
|
||||
DispositivosPage(),
|
||||
ReportesPage(),
|
||||
ConfiguracionPage(),
|
||||
];
|
||||
|
||||
static const _navItems = [
|
||||
_NavItem(Icons.dashboard_outlined, Icons.dashboard, 'Dashboard'),
|
||||
_NavItem(Icons.track_changes_outlined, Icons.track_changes, 'Monitoreo'),
|
||||
_NavItem(Icons.business_outlined, Icons.business, 'Clientes'),
|
||||
_NavItem(Icons.group_outlined, Icons.group, 'Operadores'),
|
||||
_NavItem(Icons.assignment_outlined, Icons.assignment, 'Incidentes'),
|
||||
_NavItem(Icons.devices_outlined, Icons.devices, 'Dispositivos'),
|
||||
_NavItem(Icons.bar_chart_outlined, Icons.bar_chart, 'Reportes'),
|
||||
_NavItem(Icons.settings_outlined, Icons.settings, 'Configuración'),
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarOperador();
|
||||
}
|
||||
|
||||
Future<void> _cargarOperador() async {
|
||||
final nombre = await ApiAuthService.instance.getNombre();
|
||||
final usuario = await ApiAuthService.instance.getUsuario() ?? '';
|
||||
if (!mounted) return;
|
||||
setState(() => _operadorNombre = nombre ?? usuario);
|
||||
await _sesionesDao.iniciarSesion(_operadorNombre, usuario);
|
||||
_verificarApi();
|
||||
}
|
||||
|
||||
Future<void> _verificarApi() async {
|
||||
final ok = await ApiAuthService.instance.isAuthenticated();
|
||||
if (!mounted) return;
|
||||
setState(() => _apiConectada = ok);
|
||||
}
|
||||
|
||||
Future<void> _cerrarSesion() async {
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
title: Text('Cerrar sesión',
|
||||
style: appHeadline(size: 16, weight: FontWeight.w700)),
|
||||
content: Text('¿Finalizar el turno y cerrar sesión?',
|
||||
style: appLabel(size: 13, color: AppColors.onSurface)),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text('Cancelar', style: appLabel(color: AppColors.onSurfaceVariant)),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: Text('CERRAR', style: appLabel(weight: FontWeight.bold, color: AppColors.error)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ok != true) return;
|
||||
await _sesionesDao.cerrarSesion();
|
||||
await ApiAuthService.instance.logout();
|
||||
if (!mounted) return;
|
||||
Navigator.of(context).pushReplacementNamed('/login');
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.surfaceLowest,
|
||||
body: Column(children: [
|
||||
_header(),
|
||||
Expanded(
|
||||
child: Row(children: [
|
||||
_sidebar(),
|
||||
const VerticalDivider(width: 1, color: AppColors.outlineVariant),
|
||||
Expanded(
|
||||
child: IndexedStack(
|
||||
index: _indice,
|
||||
children: _paginas,
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Header ──────────────────────────────────────────────────────────────────
|
||||
Widget _header() => Container(
|
||||
height: 56,
|
||||
color: AppColors.surfaceLow,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
child: Row(children: [
|
||||
// Logo + nombre app
|
||||
Container(
|
||||
width: 32,
|
||||
height: 32,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: AppColors.primaryContainer,
|
||||
),
|
||||
child: const Icon(Icons.shield, color: AppColors.primary, size: 18),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text('CENTRO DE MONITOREO',
|
||||
style: appHeadline(
|
||||
size: 14,
|
||||
weight: FontWeight.w800,
|
||||
color: AppColors.primary,
|
||||
spacing: 1.5)),
|
||||
const Spacer(),
|
||||
// Estado API
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: (_apiConectada ? AppColors.primaryContainer : AppColors.surfaceHighest),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Container(
|
||||
width: 7,
|
||||
height: 7,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: _apiConectada
|
||||
? const Color(0xFF4CAF50)
|
||||
: AppColors.outline,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
_apiConectada ? 'API conectada' : 'Sin conexión',
|
||||
style: appLabel(
|
||||
size: 11,
|
||||
color: _apiConectada ? AppColors.primary : AppColors.outline),
|
||||
),
|
||||
]),
|
||||
),
|
||||
const SizedBox(width: 20),
|
||||
// Operador
|
||||
Row(children: [
|
||||
Container(
|
||||
width: 32,
|
||||
height: 32,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: AppColors.primaryContainer,
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
_operadorNombre.isNotEmpty ? _operadorNombre[0].toUpperCase() : 'O',
|
||||
style: appHeadline(size: 14, weight: FontWeight.bold, color: AppColors.primary),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(_operadorNombre, style: appLabel(size: 13, color: AppColors.onSurface)),
|
||||
]),
|
||||
const SizedBox(width: 16),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.logout, color: AppColors.outline, size: 20),
|
||||
tooltip: 'Cerrar sesión',
|
||||
onPressed: _cerrarSesion,
|
||||
),
|
||||
]),
|
||||
);
|
||||
|
||||
// ── Sidebar ─────────────────────────────────────────────────────────────────
|
||||
Widget _sidebar() => Container(
|
||||
width: 220,
|
||||
color: AppColors.surfaceLow,
|
||||
child: Column(children: [
|
||||
const SizedBox(height: 8),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
|
||||
itemCount: _navItems.length,
|
||||
itemBuilder: (_, i) => _navTile(i),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
|
||||
Widget _navTile(int i) {
|
||||
final item = _navItems[i];
|
||||
final activo = _indice == i;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
onTap: () => setState(() => _indice = i),
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 160),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 11),
|
||||
decoration: BoxDecoration(
|
||||
color: activo ? AppColors.primaryContainer : Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Row(children: [
|
||||
Icon(
|
||||
activo ? item.iconActivo : item.icon,
|
||||
size: 20,
|
||||
color: activo ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
item.label,
|
||||
style: appLabel(
|
||||
size: 13,
|
||||
weight: activo ? FontWeight.w600 : FontWeight.normal,
|
||||
color: activo ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _NavItem {
|
||||
final IconData icon;
|
||||
final IconData iconActivo;
|
||||
final String label;
|
||||
const _NavItem(this.icon, this.iconActivo, this.label);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
|
||||
class AppColors {
|
||||
static const surfaceLowest = Color(0xFF0A0E14);
|
||||
static const surfaceLow = Color(0xFF181C22);
|
||||
static const surface = Color(0xFF1C2026);
|
||||
static const surfaceHigh = Color(0xFF262A31);
|
||||
static const surfaceHighest = Color(0xFF31353C);
|
||||
static const primary = Color(0xFFB0C6FF);
|
||||
static const primaryContainer = Color(0xFF002359);
|
||||
static const error = Color(0xFFFFB4AB);
|
||||
static const onError = Color(0xFF690005);
|
||||
static const tertiary = Color(0xFFFFB3B3);
|
||||
static const tertiaryContainer = Color(0xFF54000E);
|
||||
static const secondary = Color(0xFFB4CAD6);
|
||||
static const secondaryContainer = Color(0xFF374C56);
|
||||
static const onSecondaryContainer = Color(0xFFA6BCC7);
|
||||
static const onSurface = Color(0xFFDFE2EB);
|
||||
static const onSurfaceVariant = Color(0xFFC4C6CF);
|
||||
static const outline = Color(0xFF8E9199);
|
||||
static const outlineVariant = Color(0xFF44474E);
|
||||
|
||||
// Colores semánticos para estados de alarma / cliente
|
||||
static const alarmaActiva = Color(0xFFFFB4AB); // error — rojo
|
||||
static const alarmaEscalada = Color(0xFFFFB3B3); // tertiary — coral
|
||||
static const alarmaSilenciada = Color(0xFFB4CAD6); // secondary — gris azul
|
||||
static const clienteOk = Color(0xFF4CAF50); // verde
|
||||
static const clienteAlerta = Color(0xFFFFB300); // ámbar
|
||||
static const clienteCritico = Color(0xFFFFB4AB); // rojo
|
||||
}
|
||||
|
||||
TextStyle appHeadline({
|
||||
double size = 14,
|
||||
FontWeight weight = FontWeight.bold,
|
||||
Color color = AppColors.onSurface,
|
||||
double spacing = 0,
|
||||
}) =>
|
||||
GoogleFonts.manrope(
|
||||
fontSize: size,
|
||||
fontWeight: weight,
|
||||
color: color,
|
||||
letterSpacing: spacing);
|
||||
|
||||
TextStyle appLabel({
|
||||
double size = 12,
|
||||
FontWeight weight = FontWeight.normal,
|
||||
Color color = AppColors.onSurfaceVariant,
|
||||
double spacing = 0,
|
||||
}) =>
|
||||
GoogleFonts.inter(
|
||||
fontSize: size,
|
||||
fontWeight: weight,
|
||||
color: color,
|
||||
letterSpacing: spacing);
|
||||
Reference in New Issue
Block a user