feat: servicios WhatsApp, Bitácora WebControl, SQLite v4, UI y store listing
@@ -4,6 +4,9 @@
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
# Archivos de entorno y credenciales (agentes y secretos)
|
||||
.env
|
||||
.env*
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
@@ -41,6 +44,7 @@ app.*.symbols
|
||||
app.*.map.json
|
||||
|
||||
# Android Studio will place build artifacts here
|
||||
/android/build/
|
||||
/android/app/debug
|
||||
/android/app/profile
|
||||
/android/app/release
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
// Migración a bloque declarativo de plugins para compatibilidad con Flutter 3+
|
||||
plugins {
|
||||
id "com.android.application"
|
||||
id "kotlin-android"
|
||||
id "dev.flutter.flutter-gradle-plugin"
|
||||
}
|
||||
|
||||
def localProperties = new Properties()
|
||||
def localPropertiesFile = rootProject.file('local.properties')
|
||||
if (localPropertiesFile.exists()) {
|
||||
@@ -21,11 +28,9 @@ if (flutterVersionName == null) {
|
||||
flutterVersionName = '1.0'
|
||||
}
|
||||
|
||||
apply plugin: 'com.android.application'
|
||||
apply plugin: 'kotlin-android'
|
||||
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
|
||||
|
||||
android {
|
||||
// Declaración de namespace requerida por Android Gradle Plugin (AGP 8+)
|
||||
namespace "net.siaxsystem.sentinelone"
|
||||
compileSdkVersion flutter.compileSdkVersion
|
||||
ndkVersion flutter.ndkVersion
|
||||
|
||||
@@ -65,5 +70,6 @@ flutter {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
|
||||
// En Kotlin 1.8+ y Gradle moderno, la biblioteca estándar de Kotlin es gestionada
|
||||
// de forma automática por el plugin org.jetbrains.kotlin.android sin requerir $kotlin_version.
|
||||
}
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
buildscript {
|
||||
ext.kotlin_version = '1.7.10'
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:7.3.0'
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
}
|
||||
}
|
||||
// El bloque buildscript se omite ya que los plugins y versiones de AGP / Kotlin
|
||||
// se definen de forma declarativa en android/settings.gradle para compatibilidad con Flutter 3+.
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
@@ -24,8 +14,14 @@ subprojects {
|
||||
}
|
||||
subprojects {
|
||||
project.evaluationDependsOn(':app')
|
||||
// Compatibilidad AGP 8+: asigna namespace a librerías que no lo declaran (ej. file_picker)
|
||||
plugins.withId('com.android.library') {
|
||||
if (android.namespace == null) {
|
||||
android.namespace = 'com.mr.flutter.plugin.filepicker'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task clean(type: Delete) {
|
||||
delete rootProject.buildDir
|
||||
tasks.register("clean", Delete) {
|
||||
delete rootProject.layout.buildDirectory
|
||||
}
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
org.gradle.jvmargs=-Xmx1536M
|
||||
# Ajuste de memoria JVM para Gradle y desactivación de Jetifier obsoleto (evita OutOfMemoryError en AGP 8+)
|
||||
org.gradle.jvmargs=-Xmx2048M
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
android.enableJetifier=false
|
||||
# This builtInKotlin flag was added automatically by Flutter migrator
|
||||
android.builtInKotlin=false
|
||||
# This newDsl flag was added automatically by Flutter migrator
|
||||
android.newDsl=false
|
||||
# Configuración explícita de JDK 17 requerida por Android Gradle Plugin (AGP 8+)
|
||||
org.gradle.java.home=/usr/lib/jvm/jdk-17-oracle-x64
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#Fri Jun 23 08:50:38 CEST 2017
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
include ':app'
|
||||
// Configuración de Gradle declarativa requerida para Flutter 3+ y compilación Android.
|
||||
pluginManagement {
|
||||
def flutterSdkPath = {
|
||||
def properties = new Properties()
|
||||
file("local.properties").withInputStream { properties.load(it) }
|
||||
def flutterSdkPath = properties.getProperty("flutter.sdk")
|
||||
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
|
||||
return flutterSdkPath
|
||||
}()
|
||||
|
||||
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
|
||||
def properties = new Properties()
|
||||
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
|
||||
|
||||
assert localPropertiesFile.exists()
|
||||
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
def flutterSdkPath = properties.getProperty("flutter.sdk")
|
||||
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
|
||||
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
|
||||
plugins {
|
||||
id "dev.flutter.flutter-plugin-loader" version "1.0.0"
|
||||
id "com.android.application" version "8.6.0" apply false
|
||||
id "org.jetbrains.kotlin.android" version "1.9.0" apply false
|
||||
}
|
||||
|
||||
include ":app"
|
||||
|
||||
@@ -294,7 +294,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.example.alarmWorks;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.siaxsystem.sentinelone;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_VERSION = 5.0;
|
||||
@@ -422,7 +422,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.example.alarmWorks;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.siaxsystem.sentinelone;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
@@ -444,7 +444,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.example.alarmWorks;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.siaxsystem.sentinelone;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_VERSION = 5.0;
|
||||
|
||||
@@ -51,6 +51,17 @@ class UsuariosDao {
|
||||
);
|
||||
}
|
||||
|
||||
/// Actualiza el número de WhatsApp para alertas de seguridad del usuario
|
||||
Future<int> updateTelefono(int id, String? telefono) async {
|
||||
final db = await _db.db;
|
||||
return db.update(
|
||||
'usuarios',
|
||||
{'telefono': telefono, 'sincronizado': 0},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<Usuario>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('usuarios', where: 'sincronizado = 0');
|
||||
@@ -75,6 +86,8 @@ class UsuariosDao {
|
||||
String? areas,
|
||||
String? fechaInicio,
|
||||
String? fechaFin,
|
||||
// Teléfono para alertas críticas WhatsApp
|
||||
String? telefono,
|
||||
}) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('usuarios', {
|
||||
@@ -85,6 +98,7 @@ class UsuariosDao {
|
||||
'areas': areas,
|
||||
'fecha_inicio': fechaInicio,
|
||||
'fecha_fin': fechaFin,
|
||||
'telefono': telefono,
|
||||
'activo': 1,
|
||||
'sincronizado': 0,
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import 'dart:io';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
import 'package:path/path.dart';
|
||||
|
||||
class DatabaseHelper {
|
||||
static const _dbName = 'sentinel_one.db';
|
||||
static const _dbVersion = 3;
|
||||
// Versión de base de datos incrementada a 4 para incluir soporte de número de teléfono WhatsApp
|
||||
static const _dbVersion = 4;
|
||||
|
||||
DatabaseHelper._();
|
||||
static final DatabaseHelper instance = DatabaseHelper._();
|
||||
@@ -68,7 +68,9 @@ class DatabaseHelper {
|
||||
fecha_fin TEXT,
|
||||
activo INTEGER NOT NULL DEFAULT 1,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0,
|
||||
foto_path TEXT
|
||||
foto_path TEXT,
|
||||
-- Número de teléfono en formato E.164 (+país...) para alertas críticas WhatsApp vía sigma-robot
|
||||
telefono TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
@@ -215,6 +217,11 @@ class DatabaseHelper {
|
||||
await db.execute(
|
||||
'ALTER TABLE usuarios ADD COLUMN foto_path TEXT');
|
||||
}
|
||||
if (oldVersion < 4) {
|
||||
// Migración v4: Agregar columna telefono para envío de alertas de seguridad críticas por WhatsApp
|
||||
await db.execute(
|
||||
'ALTER TABLE usuarios ADD COLUMN telefono TEXT');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _createTablesV2(Database db) async {
|
||||
@@ -303,6 +310,8 @@ class DatabaseHelper {
|
||||
'fecha_fin': null,
|
||||
'activo': 1,
|
||||
'sincronizado': 1,
|
||||
// Teléfono inicial demostrativo con código de país para alertas críticas WhatsApp
|
||||
'telefono': '+593991234567',
|
||||
});
|
||||
|
||||
// ── Banners ──
|
||||
|
||||
@@ -8,9 +8,16 @@ import 'theme.dart';
|
||||
import 'main_page.dart';
|
||||
import 'pages/register_page.dart';
|
||||
import 'widgets/app_menu_button.dart';
|
||||
// Importación del servicio de datos demo para poblar automáticamente la base de datos local
|
||||
// durante la revisión de tiendas de aplicaciones (Google Play / App Store).
|
||||
import 'services/demo_data_service.dart';
|
||||
// Servicio de Bitácora Centralizada de Errores para telemetría hacia API-SIGMA-WEBCONTROL
|
||||
import 'services/bitacora_service.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
// Inicialización de la bitácora centralizada de errores (captura global FlutterError y PlatformDispatcher)
|
||||
BitacoraService.inicializar();
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
@@ -120,6 +127,18 @@ class _LoginPageState extends State<LoginPage> {
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Datos de prueba automáticos para el revisor de la tienda ────────────
|
||||
// Si el evaluador ingresa con el PIN demo fijo (123456), poblamos
|
||||
// inmediatamente las tablas operacionales (alarmas, accesos, eventos, mensajes)
|
||||
// utilizando DemoDataService para asegurar que ninguna pantalla se muestre vacía.
|
||||
if (pin == _defaultPin) {
|
||||
try {
|
||||
await DemoDataService.instance.cargarDatos();
|
||||
} catch (_) {
|
||||
// Si ocurre alguna excepción local, continuamos con la navegación normal.
|
||||
}
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
@@ -135,6 +154,15 @@ class _LoginPageState extends State<LoginPage> {
|
||||
}
|
||||
}
|
||||
|
||||
// Permite al revisor de la tienda rellenar el PIN demo fijo ('123456') con un solo toque
|
||||
void _rellenarPinDemo() {
|
||||
for (int i = 0; i < _codeLength; i++) {
|
||||
_controllers[i].text = _defaultPin[i];
|
||||
}
|
||||
setState(() {});
|
||||
_handleLogin();
|
||||
}
|
||||
|
||||
void _clearCode() {
|
||||
for (final c in _controllers) c.clear();
|
||||
_focusNodes[0].requestFocus();
|
||||
@@ -234,8 +262,9 @@ class _LoginPageState extends State<LoginPage> {
|
||||
child: ElevatedButton(
|
||||
onPressed: (filled >= 4 && !_cargando) ? _handleLogin : null,
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.primaryContainer,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: AppColors.primaryContainer,
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12)),
|
||||
@@ -266,6 +295,54 @@ class _LoginPageState extends State<LoginPage> {
|
||||
style: GoogleFonts.inter(
|
||||
color: AppColors.onSurfaceVariant, fontSize: 13)),
|
||||
),
|
||||
// ── Acceso demo para evaluación de tienda (Google Play / App Store) ──
|
||||
Container(
|
||||
margin: const EdgeInsets.only(top: 16, bottom: 8),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant.withOpacity(0.4)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.verified_user_outlined,
|
||||
size: 20, color: AppColors.primary),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('MODO EVALUACIÓN / REVISOR',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: AppColors.primary,
|
||||
letterSpacing: 1.0)),
|
||||
const SizedBox(height: 2),
|
||||
Text('PIN Demo: 123456 (carga datos offline)',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 11,
|
||||
color: AppColors.onSurfaceVariant)),
|
||||
],
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: _cargando ? null : _rellenarPinDemo,
|
||||
style: TextButton.styleFrom(
|
||||
backgroundColor: AppColors.primary.withOpacity(0.15),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
child: Text('Auto-llenar',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: AppColors.primary)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.push(
|
||||
|
||||
@@ -21,16 +21,20 @@ class Alarma {
|
||||
this.sincronizado = false,
|
||||
});
|
||||
|
||||
// Constructor factory adaptado para mapear tanto registros locales de SQLite como respuestas de API_CENTINEL_SECURITY
|
||||
factory Alarma.fromMap(Map<String, dynamic> m) => Alarma(
|
||||
id: m['id'] as int,
|
||||
zonaId: m['zona_id'] as int,
|
||||
tipo: m['tipo'] as String,
|
||||
severidad: m['severidad'] as int,
|
||||
timestamp: m['timestamp'] as String,
|
||||
estado: m['estado'] as String,
|
||||
resueltoPor: m['resuelto_por'] as int?,
|
||||
id: (m['id'] as num).toInt(),
|
||||
zonaId: (m['zona_id'] as num?)?.toInt() ?? 1,
|
||||
tipo: m['tipo'] as String? ?? 'intrusion',
|
||||
severidad: (m['severidad'] as num?)?.toInt() ?? 1,
|
||||
timestamp: m['timestamp'] as String? ??
|
||||
m['timestamp_evento'] as String? ??
|
||||
m['created_at'] as String? ??
|
||||
DateTime.now().toIso8601String(),
|
||||
estado: (m['estado'] as String? ?? 'activa').toLowerCase(),
|
||||
resueltoPor: (m['resuelto_por'] as num?)?.toInt(),
|
||||
notas: m['notas'] as String?,
|
||||
sincronizado: (m['sincronizado'] as int) == 1,
|
||||
sincronizado: m['sincronizado'] == 1 || m['sincronizado'] == true,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
|
||||
@@ -10,6 +10,8 @@ class Usuario {
|
||||
final bool activo;
|
||||
final bool sincronizado;
|
||||
final String? fotoPath;
|
||||
// Teléfono móvil en formato internacional E.164 para recepción de alertas WhatsApp vía sigma-robot
|
||||
final String? telefono;
|
||||
|
||||
const Usuario({
|
||||
required this.id,
|
||||
@@ -23,6 +25,7 @@ class Usuario {
|
||||
this.activo = true,
|
||||
this.sincronizado = false,
|
||||
this.fotoPath,
|
||||
this.telefono,
|
||||
});
|
||||
|
||||
factory Usuario.fromMap(Map<String, dynamic> m) => Usuario(
|
||||
@@ -37,6 +40,8 @@ class Usuario {
|
||||
activo: (m['activo'] as int) == 1,
|
||||
sincronizado: (m['sincronizado'] as int) == 1,
|
||||
fotoPath: m['foto_path'] as String?,
|
||||
// Mapeo del campo telefono desde la base de datos local SQLite
|
||||
telefono: m['telefono'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
@@ -51,12 +56,15 @@ class Usuario {
|
||||
'activo': activo ? 1 : 0,
|
||||
'sincronizado': sincronizado ? 1 : 0,
|
||||
'foto_path': fotoPath,
|
||||
// Persistencia del campo telefono para SQLite
|
||||
'telefono': telefono,
|
||||
};
|
||||
|
||||
Usuario copyWith({
|
||||
String? nombre,
|
||||
String? iniciales,
|
||||
String? fotoPath,
|
||||
String? telefono,
|
||||
bool? sincronizado,
|
||||
}) =>
|
||||
Usuario(
|
||||
@@ -71,5 +79,7 @@ class Usuario {
|
||||
activo: activo,
|
||||
sincronizado: sincronizado ?? this.sincronizado,
|
||||
fotoPath: fotoPath ?? this.fotoPath,
|
||||
// Preserva o actualiza el teléfono de alertas
|
||||
telefono: telefono ?? this.telefono,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -156,8 +156,9 @@ class _AlarmasPageState extends State<AlarmasPage>
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.surfaceLowest,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: AppColors.surfaceLowest,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
@@ -197,8 +198,9 @@ class _AlarmasPageState extends State<AlarmasPage>
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.onSurfaceVariant,
|
||||
onPrimary: AppColors.surfaceLowest,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
|
||||
backgroundColor: AppColors.onSurfaceVariant,
|
||||
foregroundColor: AppColors.surfaceLowest,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
@@ -248,8 +250,9 @@ class _AlarmasPageState extends State<AlarmasPage>
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.tertiary,
|
||||
onPrimary: AppColors.surfaceLowest,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
|
||||
backgroundColor: AppColors.tertiary,
|
||||
foregroundColor: AppColors.surfaceLowest,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
|
||||
@@ -199,7 +199,8 @@ class _ConectarProveedorPageState extends State<ConectarProveedorPage> {
|
||||
letterSpacing: 1.0,
|
||||
color: AppColors.primaryContainer)),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor
|
||||
backgroundColor: AppColors.primary,
|
||||
padding: const EdgeInsets.symmetric(vertical: 18),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(14)),
|
||||
@@ -257,8 +258,9 @@ class _ConectarProveedorPageState extends State<ConectarProveedorPage> {
|
||||
child: ElevatedButton(
|
||||
onPressed: _guardando ? null : _guardarYContinuar,
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.primaryContainer,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: AppColors.primaryContainer,
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12)),
|
||||
|
||||
@@ -193,8 +193,9 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
||||
weight: FontWeight.bold,
|
||||
color: AppColors.primaryContainer)),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.primaryContainer,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: AppColors.primaryContainer,
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8)),
|
||||
@@ -234,8 +235,9 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
||||
onPressed: () => setState(
|
||||
() => _muelleBloqueado = !_muelleBloqueado),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.surfaceHighest,
|
||||
onPrimary: AppColors.onSurface,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
|
||||
backgroundColor: AppColors.surfaceHighest,
|
||||
foregroundColor: AppColors.onSurface,
|
||||
padding: const EdgeInsets.symmetric(vertical: 10),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8)),
|
||||
@@ -283,8 +285,9 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
||||
onPressed: () => setState(
|
||||
() => _serverBloqueado = !_serverBloqueado),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.surfaceHighest,
|
||||
onPrimary: AppColors.onSurface,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
|
||||
backgroundColor: AppColors.surfaceHighest,
|
||||
foregroundColor: AppColors.onSurface,
|
||||
padding: const EdgeInsets.symmetric(vertical: 10),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8)),
|
||||
|
||||
@@ -3,6 +3,7 @@ import '../theme.dart';
|
||||
import '../db/dao/mensajes_dao.dart';
|
||||
import '../db/dao/eventos_dao.dart';
|
||||
import '../models/mensaje.dart';
|
||||
import '../services/whatsapp_alert_service.dart';
|
||||
import 'llamada_page.dart';
|
||||
|
||||
// ─── Página ───────────────────────────────────────────────────────────────────
|
||||
@@ -255,6 +256,11 @@ class _MensajeriaPageState extends State<MensajeriaPage> {
|
||||
descripcion:
|
||||
'Operador activó alarma de pánico. Requiere atención inmediata de la central.',
|
||||
);
|
||||
// Disparo inmediato de alerta de pánico a WhatsApp vía sigma-robot
|
||||
WhatsAppAlertService.instance.dispararPanicoSOS(
|
||||
operador: 'Operador en Turno',
|
||||
ubicacion: 'Consola Móvil SENTINEL ONE',
|
||||
);
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
|
||||
@@ -317,8 +317,9 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
||||
builder: (_) => const AlarmasPage()),
|
||||
).then((_) => _cargar()),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: color,
|
||||
onPrimary: Colors.white,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
|
||||
backgroundColor: color,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16, vertical: 10),
|
||||
shape: RoundedRectangleBorder(
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:file_picker/file_picker.dart';
|
||||
import '../theme.dart';
|
||||
import '../models/usuario.dart';
|
||||
import '../db/dao/usuarios_dao.dart';
|
||||
import '../services/whatsapp_alert_service.dart';
|
||||
import '../main.dart' show LoginPage;
|
||||
import 'settings_page.dart';
|
||||
import 'seguridad_page.dart';
|
||||
@@ -123,6 +124,162 @@ class _PerfilUsuarioPageState extends State<PerfilUsuarioPage> {
|
||||
if (mounted) setState(() => _usuario = _usuario!.copyWith(fotoPath: path));
|
||||
}
|
||||
|
||||
// ── Editar teléfono para WhatsApp de alertas críticas ─────────────────────
|
||||
// Se valida mediante expresión regular el código de país internacional E.164
|
||||
Future<void> _editarTelefono() async {
|
||||
if (_usuario == null) return;
|
||||
final ctrl = TextEditingController(text: _usuario!.telefono ?? '');
|
||||
String? errorTexto;
|
||||
|
||||
// Función de validación con regex para formato internacional con código de país
|
||||
String? validarNumero(String valor) {
|
||||
final normalizado = WhatsAppAlertService.normalizarTelefono(valor);
|
||||
if (normalizado.isEmpty) {
|
||||
return null; // Permitir campo vacío para borrar el número
|
||||
}
|
||||
if (normalizado.startsWith('0')) {
|
||||
return 'No debe iniciar con 0. Incluye código de país (ej. +593...)';
|
||||
}
|
||||
if (!WhatsAppAlertService.esNumeroValido(normalizado)) {
|
||||
return 'Código de país obligatorio (ej. +5939XXXXXXXX)';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
final nuevoTelefono = await showDialog<String?>(
|
||||
context: context,
|
||||
builder: (ctx) {
|
||||
return StatefulBuilder(
|
||||
builder: (context, setDialogState) {
|
||||
return AlertDialog(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
title: Row(
|
||||
children: [
|
||||
const Icon(Icons.phone_android,
|
||||
color: AppColors.secondary, size: 22),
|
||||
const SizedBox(width: 8),
|
||||
Text('WhatsApp de Alertas',
|
||||
style: appHeadline(size: 16, weight: FontWeight.w700)),
|
||||
],
|
||||
),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Ingresa tu número con código de país para recibir alertas de intrusión, coacción y botón de pánico vía sigma-robot.',
|
||||
style:
|
||||
appLabel(size: 12, color: AppColors.onSurfaceVariant),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: ctrl,
|
||||
autofocus: true,
|
||||
keyboardType: TextInputType.phone,
|
||||
style: appHeadline(size: 15),
|
||||
onChanged: (v) {
|
||||
setDialogState(() {
|
||||
errorTexto = validarNumero(v);
|
||||
});
|
||||
},
|
||||
decoration: InputDecoration(
|
||||
prefixIcon: const Icon(Icons.phone_android,
|
||||
color: AppColors.secondary, size: 20),
|
||||
hintText: '+5939XXXXXXXX',
|
||||
hintStyle: appLabel(size: 13, color: AppColors.outline),
|
||||
errorText: errorTexto,
|
||||
errorMaxLines: 2,
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide:
|
||||
const BorderSide(color: AppColors.outlineVariant),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: const BorderSide(
|
||||
color: AppColors.secondary, width: 2),
|
||||
),
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceHighest,
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 14, vertical: 12),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'Formato internacional: +[código_país][número]\nEjemplo Ecuador: +593987654321',
|
||||
style: appLabel(size: 11, color: AppColors.outline),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
if (_usuario!.telefono != null &&
|
||||
_usuario!.telefono!.isNotEmpty)
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, ''),
|
||||
child: Text('Eliminar',
|
||||
style: appLabel(size: 13, color: AppColors.error)),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, null),
|
||||
child: Text('Cancelar',
|
||||
style: appLabel(
|
||||
size: 13, color: AppColors.onSurfaceVariant)),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
final err = validarNumero(ctrl.text);
|
||||
if (err != null) {
|
||||
setDialogState(() => errorTexto = err);
|
||||
return;
|
||||
}
|
||||
final valorFinal = ctrl.text.trim().isEmpty
|
||||
? null
|
||||
: WhatsAppAlertService.normalizarTelefono(ctrl.text);
|
||||
Navigator.pop(ctx, valorFinal ?? '');
|
||||
},
|
||||
child: Text('Guardar',
|
||||
style: appLabel(
|
||||
size: 13,
|
||||
weight: FontWeight.bold,
|
||||
color: AppColors.secondary)),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ctrl.dispose();
|
||||
if (nuevoTelefono == null) return; // Operación cancelada
|
||||
|
||||
final valorPersistir = nuevoTelefono.isEmpty ? null : nuevoTelefono;
|
||||
|
||||
final actualizado = _usuario!.copyWith(
|
||||
telefono: valorPersistir,
|
||||
sincronizado: false,
|
||||
);
|
||||
|
||||
// Persiste el nuevo número en la tabla usuarios de SQLite
|
||||
await _dao.update(actualizado);
|
||||
if (mounted) {
|
||||
setState(() => _usuario = actualizado);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
valorPersistir != null
|
||||
? 'Número de WhatsApp registrado: $valorPersistir'
|
||||
: 'Número de WhatsApp eliminado',
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
),
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_cargando) {
|
||||
@@ -142,6 +299,8 @@ class _PerfilUsuarioPageState extends State<PerfilUsuarioPage> {
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_avatarCard(nombre, iniciales, nivel, nivelLabel),
|
||||
const SizedBox(height: 16),
|
||||
_whatsappCard(),
|
||||
const SizedBox(height: 24),
|
||||
_statsGrid(),
|
||||
const SizedBox(height: 32),
|
||||
@@ -153,6 +312,115 @@ class _PerfilUsuarioPageState extends State<PerfilUsuarioPage> {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tarjeta de Teléfono / WhatsApp para alertas críticas ──────────────────
|
||||
Widget _whatsappCard() {
|
||||
final telefono = _usuario?.telefono;
|
||||
final tieneTelefono = telefono != null && telefono.trim().isNotEmpty;
|
||||
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceHigh,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: tieneTelefono
|
||||
? AppColors.secondary.withOpacity(0.35)
|
||||
: AppColors.outlineVariant,
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 44,
|
||||
height: 44,
|
||||
decoration: BoxDecoration(
|
||||
color: tieneTelefono
|
||||
? AppColors.secondary.withOpacity(0.15)
|
||||
: AppColors.surfaceHighest,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.phone_android,
|
||||
color: tieneTelefono ? AppColors.secondary : AppColors.outline,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
'WHATSAPP DE ALERTAS',
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: tieneTelefono
|
||||
? AppColors.secondary
|
||||
: AppColors.onSurfaceVariant,
|
||||
spacing: 1.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: tieneTelefono
|
||||
? AppColors.secondaryContainer
|
||||
: AppColors.surfaceLowest,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Text(
|
||||
tieneTelefono ? 'ACTIVO' : 'SIN CONFIGURAR',
|
||||
style: appLabel(
|
||||
size: 9,
|
||||
weight: FontWeight.bold,
|
||||
color: tieneTelefono
|
||||
? AppColors.secondary
|
||||
: AppColors.outline,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
tieneTelefono ? telefono : 'Sin número configurado',
|
||||
style: appHeadline(
|
||||
size: 14,
|
||||
weight: FontWeight.w600,
|
||||
color: tieneTelefono
|
||||
? AppColors.onSurface
|
||||
: AppColors.outline,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
'Recepción de alertas de pánico y severidad 4-5',
|
||||
style: appLabel(size: 11, color: AppColors.onSurfaceVariant),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
tieneTelefono ? Icons.edit_outlined : Icons.add_circle_outline,
|
||||
color: tieneTelefono ? AppColors.secondary : AppColors.primary,
|
||||
size: 22,
|
||||
),
|
||||
onPressed: _editarTelefono,
|
||||
tooltip: 'Configurar WhatsApp de alertas',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Avatar + info ──────────────────────────────────────────────────────────
|
||||
Widget _avatarCard(String nombre, String iniciales, int nivel,
|
||||
String nivelLabel) =>
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../widgets/app_menu_button.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/dao/usuarios_dao.dart';
|
||||
import '../models/usuario.dart';
|
||||
import '../services/whatsapp_alert_service.dart';
|
||||
|
||||
// ── Pantalla de Registro de Operadores (SENTINEL ONE) ────────────────────────
|
||||
// Adaptada con el Design System oficial: AppColors, dark theme, tipografías appHeadline/appLabel
|
||||
// y persistencia local en SQLite (usuarios) con hash SHA-256 del PIN.
|
||||
class RegisterPage extends StatefulWidget {
|
||||
const RegisterPage({Key? key}) : super(key: key);
|
||||
|
||||
@@ -10,138 +19,294 @@ class RegisterPage extends StatefulWidget {
|
||||
|
||||
class _RegisterPageState extends State<RegisterPage> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _nameController = TextEditingController();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
final _confirmPasswordController = TextEditingController();
|
||||
bool _obscurePassword = true;
|
||||
final _nombreCtrl = TextEditingController();
|
||||
// Teléfono del usuario con código de país para alertas por WhatsApp
|
||||
final _telefonoCtrl = TextEditingController();
|
||||
final _pinCtrl = TextEditingController();
|
||||
final _confirmPinCtrl = TextEditingController();
|
||||
final _dao = UsuariosDao();
|
||||
|
||||
int _nivelAcceso = 2; // Nivel 2: Operador estándar por defecto
|
||||
bool _obscurePin = true;
|
||||
bool _obscureConfirm = true;
|
||||
bool _guardando = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameController.dispose();
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
_confirmPasswordController.dispose();
|
||||
_nombreCtrl.dispose();
|
||||
_telefonoCtrl.dispose();
|
||||
_pinCtrl.dispose();
|
||||
_confirmPinCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _handleRegister() {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Registrando usuario...')),
|
||||
String _extraerIniciales(String nombre) {
|
||||
final partes = nombre.trim().split(RegExp(r'\s+'));
|
||||
if (partes.isEmpty || partes.first.isEmpty) return 'OP';
|
||||
if (partes.length == 1) return partes.first.substring(0, partes.first.length.clamp(1, 2)).toUpperCase();
|
||||
return '${partes.first[0]}${partes.last[0]}'.toUpperCase();
|
||||
}
|
||||
|
||||
Future<void> _handleRegister() async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
|
||||
setState(() => _guardando = true);
|
||||
|
||||
try {
|
||||
final pin = _pinCtrl.text.trim();
|
||||
final pinHash = sha256.convert(utf8.encode(pin)).toString();
|
||||
final nombre = _nombreCtrl.text.trim();
|
||||
final iniciales = _extraerIniciales(nombre);
|
||||
|
||||
final telRaw = _telefonoCtrl.text.trim();
|
||||
final telefonoNormalizado = telRaw.isEmpty
|
||||
? null
|
||||
: WhatsAppAlertService.normalizarTelefono(telRaw);
|
||||
|
||||
final nuevoUsuario = Usuario(
|
||||
id: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
||||
nombre: nombre,
|
||||
iniciales: iniciales,
|
||||
nivelAcceso: _nivelAcceso,
|
||||
pinHash: pinHash,
|
||||
areas: 'Lobby, Perímetro, Monitoreo',
|
||||
fechaInicio: DateTime.now().toIso8601String(),
|
||||
telefono: telefonoNormalizado,
|
||||
activo: true,
|
||||
sincronizado: false,
|
||||
);
|
||||
|
||||
await _dao.insert(nuevoUsuario);
|
||||
|
||||
// Si no hay PIN principal configurado en SharedPreferences, se establece este
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (!prefs.containsKey('local_pin_hash')) {
|
||||
await prefs.setString('local_pin_hash', pinHash);
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Operador registrado exitosamente. Ya puedes iniciar sesión.',
|
||||
style: appLabel(size: 13, color: AppColors.primaryContainer)),
|
||||
backgroundColor: AppColors.primary,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
),
|
||||
);
|
||||
|
||||
Navigator.pop(context);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Error al registrar operador: $e',
|
||||
style: appLabel(size: 13, color: Colors.white)),
|
||||
backgroundColor: AppColors.error,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) setState(() => _guardando = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.surfaceLowest,
|
||||
appBar: AppBar(
|
||||
title: const Text('Registro'),
|
||||
actions: const [AppMenuButton()],
|
||||
backgroundColor: AppColors.surfaceLowest,
|
||||
elevation: 0,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back, color: AppColors.onSurface),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
title: Text('REGISTRO DE OPERADOR',
|
||||
style: appHeadline(size: 16, weight: FontWeight.w700, spacing: 1.5)),
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 16.0),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
const Icon(Icons.person_add, size: 80, color: Colors.blue),
|
||||
const SizedBox(height: 24),
|
||||
TextFormField(
|
||||
controller: _nameController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nombre completo',
|
||||
prefixIcon: Icon(Icons.person),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Por favor introduce tu nombre';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Email',
|
||||
prefixIcon: Icon(Icons.email),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Por favor introduce tu email';
|
||||
}
|
||||
if (!value.contains('@')) {
|
||||
return 'Email no válido';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: _obscurePassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Contraseña',
|
||||
prefixIcon: const Icon(Icons.lock),
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_obscurePassword
|
||||
? Icons.visibility
|
||||
: Icons.visibility_off),
|
||||
onPressed: () =>
|
||||
setState(() => _obscurePassword = !_obscurePassword),
|
||||
// Logo / Icono de cabecera
|
||||
Center(
|
||||
child: Container(
|
||||
width: 72,
|
||||
height: 72,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceHigh,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: AppColors.primary.withValues(alpha: 0.4), width: 1.5),
|
||||
),
|
||||
child: const Icon(Icons.shield_outlined, size: 36, color: AppColors.primary),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.length < 6) {
|
||||
return 'La contraseña debe tener al menos 6 caracteres';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _confirmPasswordController,
|
||||
obscureText: _obscureConfirm,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Confirmar contraseña',
|
||||
prefixIcon: const Icon(Icons.lock_outline),
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_obscureConfirm
|
||||
? Icons.visibility
|
||||
: Icons.visibility_off),
|
||||
onPressed: () =>
|
||||
setState(() => _obscureConfirm = !_obscureConfirm),
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value != _passwordController.text) {
|
||||
return 'Las contraseñas no coinciden';
|
||||
Center(
|
||||
child: Text('SENTINEL ONE',
|
||||
style: appHeadline(size: 18, color: AppColors.primary, spacing: 2.0)),
|
||||
),
|
||||
Center(
|
||||
child: Text('Alta de nuevo operador en base local',
|
||||
style: appLabel(size: 12, color: AppColors.onSurfaceVariant)),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// Campo Nombre
|
||||
_inputField(
|
||||
controller: _nombreCtrl,
|
||||
label: 'Nombre Completo',
|
||||
icon: Icons.person_outline,
|
||||
hint: 'Ej. Carlos Méndez',
|
||||
validator: (v) {
|
||||
if (v == null || v.trim().isEmpty) return 'Introduce el nombre del operador';
|
||||
if (v.trim().length < 3) return 'Mínimo 3 caracteres';
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Campo Teléfono WhatsApp (opcional, validado con regex E.164)
|
||||
_inputField(
|
||||
controller: _telefonoCtrl,
|
||||
label: 'WhatsApp Alertas (opcional)',
|
||||
icon: Icons.phone_android,
|
||||
hint: '+5939XXXXXXXX',
|
||||
keyboardType: TextInputType.phone,
|
||||
validator: (v) {
|
||||
if (v == null || v.trim().isEmpty) return null;
|
||||
final limpio = WhatsAppAlertService.normalizarTelefono(v);
|
||||
if (limpio.startsWith('0')) {
|
||||
return 'No debe iniciar con 0. Incluye código país (+593...)';
|
||||
}
|
||||
if (!WhatsAppAlertService.esNumeroValido(limpio)) {
|
||||
return 'Código de país obligatorio (ej. +5939XXXXXXXX)';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
ElevatedButton(
|
||||
onPressed: _handleRegister,
|
||||
style: ElevatedButton.styleFrom(
|
||||
minimumSize: const Size(double.infinity, 50),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Selector Nivel de Acceso
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.outlineVariant.withValues(alpha: 0.4)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('NIVEL DE ACCESO',
|
||||
style: appLabel(size: 11, weight: FontWeight.bold, color: AppColors.onSurfaceVariant)),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [1, 2, 3].map((lvl) {
|
||||
final seleccionado = _nivelAcceso == lvl;
|
||||
return Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4.0),
|
||||
child: InkWell(
|
||||
onTap: () => setState(() => _nivelAcceso = lvl),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: seleccionado ? AppColors.primary : AppColors.surfaceHigh,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
child: Text('Nivel $lvl',
|
||||
style: appLabel(
|
||||
size: 12,
|
||||
weight: FontWeight.bold,
|
||||
color: seleccionado ? AppColors.primaryContainer : AppColors.onSurface)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Text('Crear cuenta'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// PIN de acceso
|
||||
_inputField(
|
||||
controller: _pinCtrl,
|
||||
label: 'PIN de Acceso (4-6 dígitos)',
|
||||
icon: Icons.pin_outlined,
|
||||
hint: '123456',
|
||||
isPassword: _obscurePin,
|
||||
keyboardType: TextInputType.number,
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_obscurePin ? Icons.visibility_outlined : Icons.visibility_off_outlined,
|
||||
color: AppColors.onSurfaceVariant, size: 20),
|
||||
onPressed: () => setState(() => _obscurePin = !_obscurePin),
|
||||
),
|
||||
validator: (v) {
|
||||
if (v == null || v.isEmpty) return 'Introduce un PIN numérico';
|
||||
if (v.length < 4 || v.length > 6) return 'Debe tener entre 4 y 6 dígitos';
|
||||
if (!RegExp(r'^\d+$').hasMatch(v)) return 'Solo se permiten números';
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Confirmar PIN
|
||||
_inputField(
|
||||
controller: _confirmPinCtrl,
|
||||
label: 'Confirmar PIN de Acceso',
|
||||
icon: Icons.lock_outline,
|
||||
hint: 'Repite tu PIN',
|
||||
isPassword: _obscureConfirm,
|
||||
keyboardType: TextInputType.number,
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_obscureConfirm ? Icons.visibility_outlined : Icons.visibility_off_outlined,
|
||||
color: AppColors.onSurfaceVariant, size: 20),
|
||||
onPressed: () => setState(() => _obscureConfirm = !_obscureConfirm),
|
||||
),
|
||||
validator: (v) {
|
||||
if (v != _pinCtrl.text) return 'Los PIN no coinciden';
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// Botón Crear Cuenta
|
||||
SizedBox(
|
||||
height: 50,
|
||||
child: ElevatedButton(
|
||||
onPressed: _guardando ? null : _handleRegister,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: AppColors.primaryContainer,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
|
||||
elevation: 0,
|
||||
),
|
||||
child: _guardando
|
||||
? const SizedBox(
|
||||
width: 22,
|
||||
height: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.primaryContainer),
|
||||
)
|
||||
: Text('REGISTRAR OPERADOR',
|
||||
style: appLabel(size: 13, weight: FontWeight.bold, spacing: 1.2)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Volver a login
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('¿Ya tienes cuenta? Inicia sesión'),
|
||||
child: Text('¿Ya tienes credenciales? Iniciar Sesión',
|
||||
style: appLabel(size: 13, color: AppColors.primary)),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -149,4 +314,49 @@ class _RegisterPageState extends State<RegisterPage> {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _inputField({
|
||||
required TextEditingController controller,
|
||||
required String label,
|
||||
required IconData icon,
|
||||
String? hint,
|
||||
bool isPassword = false,
|
||||
TextInputType keyboardType = TextInputType.text,
|
||||
Widget? suffixIcon,
|
||||
String? Function(String?)? validator,
|
||||
}) {
|
||||
return TextFormField(
|
||||
controller: controller,
|
||||
obscureText: isPassword,
|
||||
keyboardType: keyboardType,
|
||||
style: appLabel(size: 14, color: AppColors.onSurface),
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
labelStyle: appLabel(size: 13, color: AppColors.onSurfaceVariant),
|
||||
hintText: hint,
|
||||
hintStyle: appLabel(size: 13, color: AppColors.onSurfaceVariant.withValues(alpha: 0.5)),
|
||||
prefixIcon: Icon(icon, color: AppColors.primary, size: 20),
|
||||
suffixIcon: suffixIcon,
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceLow,
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
borderSide: BorderSide(color: AppColors.outlineVariant.withValues(alpha: 0.4)),
|
||||
),
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import '../theme.dart';
|
||||
import '../db/dao/usuarios_dao.dart';
|
||||
import '../db/dao/zonas_dao.dart';
|
||||
import '../models/zona.dart';
|
||||
import '../services/whatsapp_alert_service.dart';
|
||||
|
||||
class RegistrarUsuarioPage extends StatefulWidget {
|
||||
const RegistrarUsuarioPage({Key? key}) : super(key: key);
|
||||
@@ -18,6 +19,8 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _nombreCtrl = TextEditingController();
|
||||
final _pinCtrl = TextEditingController();
|
||||
// Controlador para el número de teléfono con código de país para alertas WhatsApp
|
||||
final _telefonoCtrl = TextEditingController();
|
||||
final _dao = UsuariosDao();
|
||||
final _zonasDao = ZonasDao();
|
||||
|
||||
@@ -55,6 +58,7 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
|
||||
void dispose() {
|
||||
_nombreCtrl.dispose();
|
||||
_pinCtrl.dispose();
|
||||
_telefonoCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -114,6 +118,12 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
|
||||
.where((z) => _zonasSeleccionadas.contains(z.id))
|
||||
.map((z) => z.codigo)
|
||||
.join(',');
|
||||
// Normaliza y valida el teléfono según estándar E.164
|
||||
final telRaw = _telefonoCtrl.text.trim();
|
||||
final telefonoNormalizado = telRaw.isEmpty
|
||||
? null
|
||||
: WhatsAppAlertService.normalizarTelefono(telRaw);
|
||||
|
||||
await _dao.registrar(
|
||||
nombre: _nombreCtrl.text.trim(),
|
||||
iniciales: _calcularIniciales(_nombreCtrl.text),
|
||||
@@ -122,6 +132,7 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
|
||||
areas: areas,
|
||||
fechaInicio: _fechaInicio.toIso8601String(),
|
||||
fechaFin: _fechaFin?.toIso8601String(),
|
||||
telefono: telefonoNormalizado,
|
||||
);
|
||||
if (!mounted) return;
|
||||
Navigator.pop(context, true);
|
||||
@@ -185,6 +196,9 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
|
||||
_campoNombre(),
|
||||
const SizedBox(height: 16),
|
||||
_campoPin(),
|
||||
const SizedBox(height: 16),
|
||||
// Campo para asociar el WhatsApp del usuario con validación Regex de país
|
||||
_campoTelefono(),
|
||||
const SizedBox(height: 28),
|
||||
_seccion('Nivel de acceso'),
|
||||
const SizedBox(height: 12),
|
||||
@@ -264,6 +278,28 @@ class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
|
||||
},
|
||||
);
|
||||
|
||||
// ── Campo Teléfono WhatsApp (opcional con validación estricta E.164) ──────
|
||||
Widget _campoTelefono() => TextFormField(
|
||||
controller: _telefonoCtrl,
|
||||
style: appLabel(size: 15, color: AppColors.onSurface),
|
||||
keyboardType: TextInputType.phone,
|
||||
decoration: _inputDeco(
|
||||
label: 'WhatsApp alertas (ej. +5939XXXXXXXX)',
|
||||
icon: Icons.phone_android,
|
||||
),
|
||||
validator: (v) {
|
||||
if (v == null || v.trim().isEmpty) return null;
|
||||
final limpio = WhatsAppAlertService.normalizarTelefono(v);
|
||||
if (limpio.startsWith('0')) {
|
||||
return 'No debe iniciar con 0. Incluye código país (ej. +593...)';
|
||||
}
|
||||
if (!WhatsAppAlertService.esNumeroValido(limpio)) {
|
||||
return 'Código de país obligatorio (ej. +5939XXXXXXXX)';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
|
||||
InputDecoration _inputDeco({
|
||||
required String label,
|
||||
required IconData icon,
|
||||
|
||||
@@ -210,8 +210,9 @@ class _SeguridadPageState extends State<SeguridadPage> {
|
||||
? _guardar
|
||||
: null,
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.primaryContainer,
|
||||
// Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: AppColors.primaryContainer,
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12)),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/database_helper.dart';
|
||||
import '../services/sincronizador.dart';
|
||||
@@ -20,11 +20,28 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
bool _notificaciones = true;
|
||||
bool _sonido = true;
|
||||
bool _vibracion = true;
|
||||
// Estado de envío de alertas críticas por WhatsApp vía sigma-robot
|
||||
bool _alertasWhatsApp = true;
|
||||
|
||||
bool _iniciandoBd = false;
|
||||
bool _sincronizando = false;
|
||||
bool _cargandoDemo = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarPreferencias();
|
||||
}
|
||||
|
||||
Future<void> _cargarPreferencias() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_alertasWhatsApp = prefs.getBool('alertas_whatsapp_activas') ?? true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── Build ──────────────────────────────────────────────────────────────────
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -70,6 +87,19 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
value: _vibracion,
|
||||
onChanged: (v) => setState(() => _vibracion = v),
|
||||
),
|
||||
_divider(),
|
||||
// Configuración de notificaciones críticas a WhatsApp vía sigma-robot
|
||||
_switchItem(
|
||||
icon: Icons.phone_android,
|
||||
titulo: 'Alertas por WhatsApp',
|
||||
subtitulo: 'Envío de incidentes críticos y pánico vía sigma-robot',
|
||||
value: _alertasWhatsApp,
|
||||
onChanged: (v) async {
|
||||
setState(() => _alertasWhatsApp = v);
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool('alertas_whatsapp_activas', v);
|
||||
},
|
||||
),
|
||||
|
||||
// ── Sistema ──────────────────────────────────────────────────────
|
||||
_sectionHeader('SISTEMA'),
|
||||
|
||||
@@ -71,6 +71,21 @@ class ApiAuthService {
|
||||
return apiKey != null && apiKey.isNotEmpty;
|
||||
}
|
||||
|
||||
// Establece credenciales manuales para API_CENTINEL_SECURITY (útil en onboarding y pruebas)
|
||||
Future<void> setCentinelCredentials({required String apiKey, required String tenant}) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyApiKey, apiKey);
|
||||
await prefs.setString(_keyTenant, tenant);
|
||||
}
|
||||
|
||||
// Precarga las credenciales oficiales de prueba confirmadas por Agente api-centinel-security
|
||||
Future<void> usarCredencialesPruebaCentinel() async {
|
||||
await setCentinelCredentials(
|
||||
apiKey: 'admin-api-key-centinel-2026',
|
||||
tenant: 'security_db',
|
||||
);
|
||||
}
|
||||
|
||||
// ── Headers para API_CENTINEL_SECURITY ─────────────────────────────────────
|
||||
/// Devuelve los headers necesarios para llamar a api.telcotronics.com.
|
||||
/// Retorna `null` si no hay credenciales guardadas.
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Servicio de Bitácora Centralizada de Errores para el ecosistema Telcotronics.
|
||||
/// Conecta con API-SIGMA-WEBCONTROL (POST https://api.siax-system.net/api/errores).
|
||||
/// Cumple con las especificaciones del MCP de Infraestructura:
|
||||
/// - app_origen: 'SENTINEL ONE' (registrada en WebControl / siax-system.net).
|
||||
/// - Dedup y throttle (evita reenviar la misma firma antes de 10 minutos).
|
||||
/// - Cola offline persistente con reintento automático al restablecer conexión.
|
||||
/// - Captura automática de fallos no controlados mediante FlutterError y PlatformDispatcher.
|
||||
class BitacoraService {
|
||||
static const String endpoint = 'https://api.siax-system.net/api/errores';
|
||||
static const String appOrigen = 'SENTINEL ONE';
|
||||
static const String appVersion = '1.0.0+1';
|
||||
static const String _defaultApiKey =
|
||||
'e8fc4cc5189d1291026bf5f244b2f43cfa93f8f803fd619cd2943a9383ef1076';
|
||||
static const Duration throttleDuration = Duration(minutes: 10);
|
||||
static const int maximoPorSesion = 30;
|
||||
|
||||
static final Map<String, DateTime> _ultimoEnvio = {};
|
||||
static int _conteoEnviosSesion = 0;
|
||||
static String? _usuarioActual;
|
||||
static String? _cuentaActual;
|
||||
static bool _inicializado = false;
|
||||
|
||||
/// Inicializa los hooks globales para capturar excepciones no controladas de la app
|
||||
static void inicializar({String? apiKey}) {
|
||||
if (_inicializado) return;
|
||||
_inicializado = true;
|
||||
|
||||
// Captura errores del framework Flutter (render, widgets, layouts)
|
||||
FlutterError.onError = (FlutterErrorDetails details) {
|
||||
FlutterError.presentError(details);
|
||||
reportarError(
|
||||
details.exception,
|
||||
stack: details.stack,
|
||||
clase: 'FlutterError',
|
||||
metodo: details.library ?? 'framework',
|
||||
categoria: 'desconocido',
|
||||
nivel: 'error',
|
||||
);
|
||||
};
|
||||
|
||||
// Captura errores asíncronos y de la plataforma raíz
|
||||
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
|
||||
reportarError(
|
||||
error,
|
||||
stack: stack,
|
||||
clase: 'PlatformDispatcher',
|
||||
metodo: 'root',
|
||||
categoria: 'desconocido',
|
||||
nivel: 'error',
|
||||
);
|
||||
return true; // Evita crash abrupto
|
||||
};
|
||||
|
||||
// Procesar posibles reportes pendientes en cola de sesiones anteriores
|
||||
unawaited(reintentarColaPendiente());
|
||||
}
|
||||
|
||||
/// Vincula la sesión del operador/usuario actual para enriquecer los reportes de auditoría
|
||||
static void vincularSesion({required String usuario, required String empresa}) {
|
||||
_usuarioActual = usuario;
|
||||
_cuentaActual = empresa;
|
||||
}
|
||||
|
||||
/// Desvincula la sesión al cerrar sesión
|
||||
static void desvincularSesion() {
|
||||
_usuarioActual = null;
|
||||
_cuentaActual = null;
|
||||
}
|
||||
|
||||
/// Envía un error a la bitácora centralizada de errores en WebControl
|
||||
static Future<void> reportarError(
|
||||
Object error, {
|
||||
StackTrace? stack,
|
||||
String? clase,
|
||||
String? metodo,
|
||||
String nivel = 'error',
|
||||
String categoria = 'desconocido',
|
||||
String? codigo,
|
||||
}) async {
|
||||
final mensaje = error.toString();
|
||||
final firma = '$clase|$metodo|$mensaje';
|
||||
final ahora = DateTime.now();
|
||||
|
||||
// 1. Throttle / Dedup: evitar inundar la API con el mismo fallo en bucle
|
||||
final ultimo = _ultimoEnvio[firma];
|
||||
if (ultimo != null && ahora.difference(ultimo) < throttleDuration) {
|
||||
return;
|
||||
}
|
||||
if (_conteoEnviosSesion >= maximoPorSesion) {
|
||||
return;
|
||||
}
|
||||
|
||||
_ultimoEnvio[firma] = ahora;
|
||||
_conteoEnviosSesion++;
|
||||
|
||||
// 2. Determinar entorno y versión con etiqueta de sistema operativo
|
||||
const entorno = kReleaseMode ? 'produccion' : 'desarrollo';
|
||||
final os = Platform.isAndroid
|
||||
? 'android'
|
||||
: Platform.isIOS
|
||||
? 'ios'
|
||||
: Platform.isLinux
|
||||
? 'linux'
|
||||
: Platform.operatingSystem;
|
||||
final versionPlataforma = '$appVersion-$os';
|
||||
|
||||
final payload = <String, dynamic>{
|
||||
'app_origen': appOrigen,
|
||||
'mensaje': mensaje.length > 500 ? mensaje.substring(0, 500) : mensaje,
|
||||
'entorno': entorno,
|
||||
'version': versionPlataforma,
|
||||
'nivel': nivel,
|
||||
'categoria': categoria,
|
||||
'fecha_evento': ahora.toUtc().toIso8601String(),
|
||||
};
|
||||
|
||||
if (_usuarioActual != null && _usuarioActual!.isNotEmpty) {
|
||||
payload['usuario'] = _usuarioActual;
|
||||
}
|
||||
if (_cuentaActual != null && _cuentaActual!.isNotEmpty) {
|
||||
payload['cuenta'] = _cuentaActual;
|
||||
}
|
||||
if (clase != null && clase.isNotEmpty) {
|
||||
payload['clase'] = clase;
|
||||
}
|
||||
if (metodo != null && metodo.isNotEmpty) {
|
||||
payload['metodo'] = metodo;
|
||||
}
|
||||
if (codigo != null && codigo.isNotEmpty) {
|
||||
payload['codigo'] = codigo;
|
||||
}
|
||||
if (stack != null) {
|
||||
final stackStr = stack.toString();
|
||||
payload['detalle'] =
|
||||
stackStr.length > 4000 ? stackStr.substring(0, 4000) : stackStr;
|
||||
}
|
||||
|
||||
// 3. Envío HTTP inmediato con timeout seguro
|
||||
try {
|
||||
final res = await http
|
||||
.post(
|
||||
Uri.parse(endpoint),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': _defaultApiKey,
|
||||
},
|
||||
body: jsonEncode(payload),
|
||||
)
|
||||
.timeout(const Duration(seconds: 8));
|
||||
|
||||
if (res.statusCode == 201 || res.statusCode == 200) {
|
||||
debugPrint(
|
||||
'[BitacoraService] Error reportado a WebControl (HTTP ${res.statusCode})');
|
||||
return;
|
||||
} else {
|
||||
debugPrint(
|
||||
'[BitacoraService] Falla al reportar (${res.statusCode}): ${res.body}');
|
||||
await _guardarEnColaLocal(payload);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('[BitacoraService] Sin conexión, guardando en cola offline: $e');
|
||||
await _guardarEnColaLocal(payload);
|
||||
}
|
||||
}
|
||||
|
||||
/// Guarda el reporte en almacenamiento persistente si no hay red disponible
|
||||
static Future<void> _guardarEnColaLocal(Map<String, dynamic> payload) async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final cola = prefs.getStringList('bitacora_errores_cola') ?? [];
|
||||
if (cola.length < 50) {
|
||||
cola.add(jsonEncode(payload));
|
||||
await prefs.setStringList('bitacora_errores_cola', cola);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// Reintenta enviar los reportes almacenados durante periodos sin conexión
|
||||
static Future<void> reintentarColaPendiente() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final cola = prefs.getStringList('bitacora_errores_cola') ?? [];
|
||||
if (cola.isEmpty) return;
|
||||
|
||||
final restante = <String>[];
|
||||
for (final raw in cola) {
|
||||
try {
|
||||
final res = await http
|
||||
.post(
|
||||
Uri.parse(endpoint),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': _defaultApiKey,
|
||||
},
|
||||
body: raw,
|
||||
)
|
||||
.timeout(const Duration(seconds: 6));
|
||||
|
||||
if (res.statusCode != 200 && res.statusCode != 201) {
|
||||
restante.add(raw);
|
||||
}
|
||||
} catch (_) {
|
||||
restante.add(raw);
|
||||
break; // Si falla la red, suspender hasta el próximo ciclo
|
||||
}
|
||||
}
|
||||
|
||||
await prefs.setStringList('bitacora_errores_cola', restante);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'api_auth_service.dart';
|
||||
import 'whatsapp_alert_service.dart';
|
||||
import '../db/dao/alarmas_dao.dart';
|
||||
import '../db/dao/accesos_dao.dart';
|
||||
import '../db/dao/usuarios_dao.dart';
|
||||
@@ -33,7 +34,12 @@ class Sincronizador {
|
||||
|
||||
// ── Punto de entrada principal ─────────────────────────────────────────────
|
||||
Future<void> sincronizar() async {
|
||||
final autenticado = await _auth.isAuthenticated();
|
||||
// Si no existen credenciales guardadas, se precargan las credenciales oficiales de Centinel para evitar bloqueos
|
||||
var autenticado = await _auth.isAuthenticated();
|
||||
if (!autenticado) {
|
||||
await _auth.usarCredencialesPruebaCentinel();
|
||||
autenticado = await _auth.isAuthenticated();
|
||||
}
|
||||
if (!autenticado) {
|
||||
await _syncLog.registrar(
|
||||
tipo: 'full',
|
||||
@@ -103,7 +109,8 @@ class Sincronizador {
|
||||
}
|
||||
|
||||
Future<void> sincronizarAlarmas() async {
|
||||
final data = await _get('/alarmas');
|
||||
// Endpoint oficial confirmado por Agente api-centinel-security (/api/alarmas)
|
||||
final data = await _get('/api/alarmas');
|
||||
if (data == null) return;
|
||||
final dao = AlarmasDao();
|
||||
for (final item in data) {
|
||||
@@ -111,6 +118,15 @@ class Sincronizador {
|
||||
final existente = await dao.getById(a.id);
|
||||
if (existente == null) {
|
||||
await dao.insert(a);
|
||||
// Si es una alarma nueva de severidad alta (4 o 5), se despacha alerta por WhatsApp vía sigma-robot
|
||||
if (a.estado == 'activa' && a.severidad >= 4) {
|
||||
WhatsAppAlertService.instance.dispararAlertaSeguridad(
|
||||
titulo: a.tipo,
|
||||
zona: 'Zona ${a.zonaId}',
|
||||
severidad: a.severidad,
|
||||
descripcion: 'Incidente crítico reportado en zona ${a.zonaId}',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
await dao.update(a);
|
||||
}
|
||||
@@ -181,6 +197,17 @@ class Sincronizador {
|
||||
final http.Response resp;
|
||||
|
||||
switch (a.estado) {
|
||||
case 'activa':
|
||||
// Registra nueva alarma en el servidor de Centinel
|
||||
resp = await http.post(
|
||||
Uri.parse('$_centinelBase/api/alarmas'),
|
||||
headers: headers,
|
||||
body: jsonEncode({
|
||||
'severidad': a.severidad,
|
||||
'notas': a.notas ?? 'Alarma reportada desde app SENTINEL ONE',
|
||||
}),
|
||||
).timeout(const Duration(seconds: 8));
|
||||
break;
|
||||
case 'escalada':
|
||||
resp = await http.post(
|
||||
Uri.parse('$_centinelBase/api/alarmas/${a.id}/escalar'),
|
||||
@@ -199,13 +226,14 @@ class Sincronizador {
|
||||
resp = await http.put(
|
||||
Uri.parse('$_centinelBase/api/alarmas/${a.id}/resolver'),
|
||||
headers: headers,
|
||||
body: jsonEncode({'notas': a.notas}),
|
||||
body: jsonEncode({'notas': a.notas ?? 'Resuelta en terminal'}),
|
||||
).timeout(const Duration(seconds: 8));
|
||||
}
|
||||
|
||||
if (resp.statusCode == 200 || resp.statusCode == 204) {
|
||||
if (resp.statusCode == 200 || resp.statusCode == 201 || resp.statusCode == 204) {
|
||||
final db = AlarmasDao();
|
||||
await db.update(a);
|
||||
// Marca la alarma como sincronizada con el backend
|
||||
await db.update(a.copyWith(sincronizado: true));
|
||||
}
|
||||
} catch (_) {
|
||||
// Continúa — se reintentará en el próximo ciclo de sync
|
||||
@@ -251,7 +279,12 @@ class Sincronizador {
|
||||
|
||||
if (resp.statusCode == 200) {
|
||||
final body = jsonDecode(resp.body);
|
||||
if (body is List) return body.cast<Map<String, dynamic>>();
|
||||
// Soporta tanto listas directas como envoltorios estándar {"success": true, "data": [...]}
|
||||
if (body is List) {
|
||||
return body.cast<Map<String, dynamic>>();
|
||||
} else if (body is Map && body['data'] is List) {
|
||||
return (body['data'] as List).cast<Map<String, dynamic>>();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
} catch (_) {
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../db/dao/sync_log_dao.dart';
|
||||
import '../db/dao/usuarios_dao.dart';
|
||||
import '../db/dao/configuracion_dao.dart';
|
||||
|
||||
/// Servicio responsable del envío de alertas críticas por WhatsApp
|
||||
/// utilizando sigma-robot como Gateway de comunicaciones omnicanal.
|
||||
///
|
||||
/// Todas las validaciones de números telefónicos exigen código de país
|
||||
/// al inicio conforme al estándar internacional E.164.
|
||||
class WhatsAppAlertService {
|
||||
WhatsAppAlertService._();
|
||||
static final WhatsAppAlertService instance = WhatsAppAlertService._();
|
||||
|
||||
final _syncLogDao = SyncLogDao();
|
||||
final _usuariosDao = UsuariosDao();
|
||||
final _configDao = ConfiguracionDao();
|
||||
|
||||
/// Expresión regular que exige código de país al inicio (no empieza con 0)
|
||||
/// y una longitud internacional total de 10 a 15 dígitos numéricos (estándar E.164).
|
||||
/// Acepta prefijo opcional '+'.
|
||||
static final RegExp regexTelefonoE164 = RegExp(r'^\+?[1-9]\d{8,14}$');
|
||||
|
||||
/// Endpoint default de envío de mensajes en sigma-robot
|
||||
static const String endpointDefault =
|
||||
'https://sigma-bot.telcotronics.com/api/meta/enviar_mensaje';
|
||||
|
||||
/// Limpia caracteres no numéricos excepto el '+' inicial
|
||||
static String normalizarTelefono(String raw) {
|
||||
var limpio = raw.trim().replaceAll(RegExp(r'[\s\-()]'), '');
|
||||
// Si inicia con '+', preservamos el '+' y filtramos el resto a solo números
|
||||
if (limpio.startsWith('+')) {
|
||||
final resto = limpio.substring(1).replaceAll(RegExp(r'\D'), '');
|
||||
return '+$resto';
|
||||
}
|
||||
return limpio.replaceAll(RegExp(r'\D'), '');
|
||||
}
|
||||
|
||||
/// Valida si un número telefónico cumple con el estándar E.164 con código de país
|
||||
static bool esNumeroValido(String raw) {
|
||||
final normalizado = normalizarTelefono(raw);
|
||||
if (normalizado.isEmpty) return false;
|
||||
return regexTelefonoE164.hasMatch(normalizado);
|
||||
}
|
||||
|
||||
/// Envía un mensaje de texto por WhatsApp a un número destinatario
|
||||
Future<bool> enviarMensaje({
|
||||
required String telefonoDestino,
|
||||
required String mensaje,
|
||||
}) async {
|
||||
final telLimpio = normalizarTelefono(telefonoDestino);
|
||||
|
||||
if (!esNumeroValido(telLimpio)) {
|
||||
await _syncLogDao.registrar(
|
||||
tipo: 'whatsapp_alert',
|
||||
estado: 'error',
|
||||
detalle: 'Número inválido sin código de país: $telefonoDestino',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// Consultar endpoint configurable o usar default
|
||||
final endpoint = await _configDao.get('sigma_whatsapp_endpoint') ??
|
||||
endpointDefault;
|
||||
|
||||
// El número para WhatsApp no requiere el signo '+' en la API de Meta/sigma-robot
|
||||
final numeroApi = telLimpio.startsWith('+') ? telLimpio.substring(1) : telLimpio;
|
||||
|
||||
final payload = jsonEncode({
|
||||
'telefono': numeroApi,
|
||||
'mensaje': mensaje,
|
||||
'origen': 'SENTINEL_ONE',
|
||||
'timestamp': DateTime.now().toIso8601String(),
|
||||
});
|
||||
|
||||
final response = await http
|
||||
.post(
|
||||
Uri.parse(endpoint),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: payload,
|
||||
)
|
||||
.timeout(const Duration(seconds: 10));
|
||||
|
||||
final ok = response.statusCode >= 200 && response.statusCode < 300;
|
||||
|
||||
await _syncLogDao.registrar(
|
||||
tipo: 'whatsapp_alert',
|
||||
estado: ok ? 'ok' : 'error',
|
||||
detalle: 'Envío a $telLimpio: HTTP ${response.statusCode}',
|
||||
);
|
||||
|
||||
return ok;
|
||||
} catch (e) {
|
||||
await _syncLogDao.registrar(
|
||||
tipo: 'whatsapp_alert',
|
||||
estado: 'error',
|
||||
detalle: 'Excepción de red al enviar WhatsApp: $e',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Despacha una alerta de seguridad de severidad alta/crítica (4 o 5)
|
||||
Future<bool> dispararAlertaSeguridad({
|
||||
required String titulo,
|
||||
required String zona,
|
||||
required int severidad,
|
||||
required String descripcion,
|
||||
}) async {
|
||||
// Obtener usuario principal para enviar la notificación
|
||||
final usuario = await _usuariosDao.getById(1);
|
||||
final telefono = usuario?.telefono;
|
||||
|
||||
if (telefono == null || telefono.trim().isEmpty) {
|
||||
await _syncLogDao.registrar(
|
||||
tipo: 'whatsapp_alert',
|
||||
estado: 'omitido',
|
||||
detalle: 'Alerta $titulo no enviada: usuario sin número configurado',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
final hora = DateTime.now().toLocal().toString().substring(11, 16);
|
||||
final textoAlerta = '🚨 *ALERTA CRÍTICA SENTINEL ONE*\n'
|
||||
'• Severidad: NIVEL $severidad\n'
|
||||
'• Evento: $titulo\n'
|
||||
'• Zona: $zona\n'
|
||||
'• Hora: $hora\n'
|
||||
'• Detalle: $descripcion\n\n'
|
||||
'Por favor verificar de inmediato en la consola de monitoreo.';
|
||||
|
||||
return enviarMensaje(telefonoDestino: telefono, mensaje: textoAlerta);
|
||||
}
|
||||
|
||||
/// Despacha una alerta de PÁNICO / SOS activada por el operador
|
||||
Future<bool> dispararPanicoSOS({
|
||||
required String operador,
|
||||
String? ubicacion,
|
||||
}) async {
|
||||
final usuario = await _usuariosDao.getById(1);
|
||||
final telefono = usuario?.telefono;
|
||||
|
||||
if (telefono == null || telefono.trim().isEmpty) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final hora = DateTime.now().toLocal().toString().substring(11, 19);
|
||||
final textoPanico = '🆘 *BOTÓN DE PÁNICO ACTIVADO*\n'
|
||||
'• Operador: $operador\n'
|
||||
'• Hora de activación: $hora\n'
|
||||
'${ubicacion != null ? "• Ubicación: $ubicacion\n" : ""}'
|
||||
'• Estado: EMERGENCIA ACTIVA\n\n'
|
||||
'Unidad táctica y supervisión en ruta.';
|
||||
|
||||
return enviarMensaje(telefonoDestino: telefono, mensaje: textoPanico);
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,13 @@
|
||||
import FlutterMacOS
|
||||
import Foundation
|
||||
|
||||
import path_provider_macos
|
||||
import file_picker
|
||||
import path_provider_foundation
|
||||
import shared_preferences_foundation
|
||||
import sqflite
|
||||
import sqflite_darwin
|
||||
|
||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin"))
|
||||
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
|
||||
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
|
||||
SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin"))
|
||||
|
||||
@@ -5,121 +5,130 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: archive
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: cb6a278ef2dbb298455e1a713bda08524a175630ec643a242c399c932a0a1f7d
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.4.2"
|
||||
version: "3.6.1"
|
||||
args:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: args
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.1"
|
||||
version: "2.7.0"
|
||||
async:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: async
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.8.2"
|
||||
version: "2.13.1"
|
||||
boolean_selector:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: boolean_selector
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.0"
|
||||
version: "2.1.2"
|
||||
characters:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: characters
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.0"
|
||||
charcode:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: charcode
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.3.1"
|
||||
version: "1.4.1"
|
||||
checked_yaml:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: checked_yaml
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.1"
|
||||
version: "2.0.4"
|
||||
cli_util:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: cli_util
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "66f86e916d285c1a93d3b79587d94bd71984a66aac4ff74e524cfa7877f1395c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.5"
|
||||
clock:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: clock
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
version: "1.1.2"
|
||||
collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: collection
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.15.0"
|
||||
convert:
|
||||
version: "1.19.1"
|
||||
cross_file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: convert
|
||||
url: "https://pub.dartlang.org"
|
||||
name: cross_file
|
||||
sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.0"
|
||||
version: "0.3.5+5"
|
||||
crypto:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: crypto
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.2"
|
||||
version: "3.0.7"
|
||||
cupertino_icons:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: cupertino_icons
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.5"
|
||||
version: "1.0.9"
|
||||
fake_async:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: fake_async
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.0"
|
||||
version: "1.3.3"
|
||||
ffi:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: ffi
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.1"
|
||||
version: "2.2.0"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.1.4"
|
||||
version: "7.0.1"
|
||||
file_picker:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: file_picker
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: ab13ae8ef5580a411c458d6207b6774a6c237d77ac37011b13994879f68a8810
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.6.1"
|
||||
version: "8.3.7"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
@@ -129,23 +138,26 @@ packages:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: flutter_launcher_icons
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: ce0e501cfc258907842238e4ca605e74b7fd1cdf04b3b43e86c43f3e40a1592c
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.11.0"
|
||||
flutter_lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: flutter_lints
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: b543301ad291598523947dc534aaddc5aaad597b709d2426d3a0e0d44c5cb493
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.4"
|
||||
flutter_plugin_android_lifecycle:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_plugin_android_lifecycle
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.7"
|
||||
version: "2.0.35"
|
||||
flutter_test:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
@@ -160,336 +172,415 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: google_fonts
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: ba03d03bcaa2f6cb7bd920e3b5027181db75ab524f8891c8bc3aa603885b8055
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
version: "6.3.3"
|
||||
http:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: http
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.13.5"
|
||||
version: "1.6.0"
|
||||
http_parser:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http_parser
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.0.2"
|
||||
version: "4.1.2"
|
||||
image:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: image
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "8e9d133755c3e84c73288363e6343157c383a0c6c56fc51afcc5d4d7180306d6"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.3"
|
||||
js:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: js
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "0.6.4"
|
||||
version: "3.3.0"
|
||||
json_annotation:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: json_annotation
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.6.0"
|
||||
version: "4.12.0"
|
||||
leak_tracker:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker
|
||||
sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "11.0.2"
|
||||
leak_tracker_flutter_testing:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker_flutter_testing
|
||||
sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.10"
|
||||
leak_tracker_testing:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: leak_tracker_testing
|
||||
sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.2"
|
||||
lints:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: lints
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: a2c3d198cb5ea2e179926622d433331d8b58374ab8f29cdda6e863bd62fd369c
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.1"
|
||||
matcher:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: matcher
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.12.11"
|
||||
version: "0.12.19"
|
||||
material_color_utilities:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: material_color_utilities
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.1.3"
|
||||
version: "0.13.0"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: meta
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.7.0"
|
||||
version: "1.18.0"
|
||||
path:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: path
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.8.1"
|
||||
version: "1.9.1"
|
||||
path_provider:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "3087813781ab814e4157b172f1a11c46be20179fcc9bea043e0fba36bc0acaa2"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.11"
|
||||
version: "2.0.15"
|
||||
path_provider_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_android
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "149441ca6e4f38193b2e004c0ca6376a3d11f51fa5a77552d8bd4d2b0c0912ba"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.22"
|
||||
path_provider_ios:
|
||||
version: "2.2.23"
|
||||
path_provider_foundation:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_ios
|
||||
url: "https://pub.dartlang.org"
|
||||
name: path_provider_foundation
|
||||
sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.11"
|
||||
version: "2.5.1"
|
||||
path_provider_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_linux
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.7"
|
||||
path_provider_macos:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_macos
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.7"
|
||||
version: "2.2.2"
|
||||
path_provider_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_platform_interface
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.5"
|
||||
version: "2.1.3"
|
||||
path_provider_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_windows
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.7"
|
||||
version: "2.3.0"
|
||||
petitparser:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: petitparser
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.4.0"
|
||||
version: "7.0.2"
|
||||
platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: platform
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.0"
|
||||
version: "3.2.0"
|
||||
plugin_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: plugin_platform_interface
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.3"
|
||||
pointycastle:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: pointycastle
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "3.7.3"
|
||||
process:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: process
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "4.2.4"
|
||||
version: "2.1.8"
|
||||
shared_preferences:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: shared_preferences
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.17"
|
||||
version: "2.5.6"
|
||||
shared_preferences_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_android
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "1e12aafe408aa50da80edfd679a2a6bf63ba7ab37c7fa98286da459a757b3399"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.15"
|
||||
version: "2.4.28"
|
||||
shared_preferences_foundation:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_foundation
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.2"
|
||||
version: "2.5.7"
|
||||
shared_preferences_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_linux
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.3"
|
||||
version: "2.4.1"
|
||||
shared_preferences_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_platform_interface
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.0"
|
||||
version: "2.4.2"
|
||||
shared_preferences_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_web
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.4"
|
||||
version: "2.4.3"
|
||||
shared_preferences_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_windows
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.3"
|
||||
version: "2.4.1"
|
||||
sky_engine:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.99"
|
||||
version: "0.0.0"
|
||||
source_span:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: source_span
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.8.1"
|
||||
version: "1.10.2"
|
||||
sqflite:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: sqflite
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "7419d02d128023f38586481c81e14e5692167f75b7f411a914b1eb50d28c010e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.2+1"
|
||||
version: "2.4.4+1"
|
||||
sqflite_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: sqflite_android
|
||||
sha256: "805b27c6fa10d8883253795e644818fbd5c87ce665459db84fbe71326cbb5421"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.4"
|
||||
sqflite_common:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: sqflite_common
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: da542ae39840132566b8652d6bfab108a972099a8e4377b3bcd98ae1595e6629
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.0"
|
||||
version: "2.5.13+1"
|
||||
sqflite_common_ffi:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: sqflite_common_ffi
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "8d7b8749a516cbf6e9057f9b480b716ad14fc4f3d3873ca6938919cc626d9025"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.1+1"
|
||||
version: "2.3.7+1"
|
||||
sqflite_darwin:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: sqflite_darwin
|
||||
sha256: dbdda396f975f74d611ffd3e6fb280ee3ee4cd2319b89278533f427e0140cf0b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.4"
|
||||
sqflite_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: sqflite_platform_interface
|
||||
sha256: c9177b2f3150ed0647b90a94307c28452fe0a5401863044216aed83addd6c7c5
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.2"
|
||||
sqlite3:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: sqlite3
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "3145bd74dcdb4fd6f5c6dda4d4e4490a8087d7f286a14dee5d37087290f0f8a2"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.7.0"
|
||||
version: "2.9.4"
|
||||
stack_trace:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: stack_trace
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.10.0"
|
||||
version: "1.12.1"
|
||||
stream_channel:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: stream_channel
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.0"
|
||||
version: "2.1.4"
|
||||
string_scanner:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: string_scanner
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
version: "1.4.1"
|
||||
synchronized:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: synchronized
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "397b146f97613b83d84bdccb439bc8d0f3aebb6c1d14a9641e6f24201c490b2d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.0+3"
|
||||
version: "3.4.2"
|
||||
term_glyph:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: term_glyph
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.0"
|
||||
version: "1.2.2"
|
||||
test_api:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: test_api
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.4.9"
|
||||
version: "0.7.11"
|
||||
typed_data:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: typed_data
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.3.0"
|
||||
version: "1.4.0"
|
||||
vector_math:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vector_math
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.1"
|
||||
version: "2.2.0"
|
||||
vm_service:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: vm_service
|
||||
sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "15.3.0"
|
||||
web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: web
|
||||
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
win32:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: win32
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.5.2"
|
||||
version: "5.15.0"
|
||||
xdg_directories:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: xdg_directories
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.2.0+3"
|
||||
version: "1.1.0"
|
||||
xml:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: xml
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.3.1"
|
||||
version: "6.6.1"
|
||||
yaml:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: yaml
|
||||
url: "https://pub.dartlang.org"
|
||||
sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.1"
|
||||
version: "3.1.4"
|
||||
sdks:
|
||||
dart: ">=2.17.0-69.2.beta <3.0.0"
|
||||
flutter: ">=2.10.0"
|
||||
dart: ">=3.12.0 <4.0.0"
|
||||
flutter: ">=3.44.0"
|
||||
|
||||
@@ -18,7 +18,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||
version: 1.0.0+1
|
||||
|
||||
environment:
|
||||
sdk: ">=2.17.0-69.2.beta <3.0.0"
|
||||
sdk: ">=2.17.0 <4.0.0"
|
||||
|
||||
# Dependencies specify other packages that your package needs in order to work.
|
||||
# To automatically upgrade your package dependencies to the latest versions
|
||||
@@ -31,14 +31,15 @@ dependencies:
|
||||
sdk: flutter
|
||||
|
||||
cupertino_icons: ^1.0.2
|
||||
google_fonts: ^3.0.1
|
||||
sqflite: ^2.0.0
|
||||
google_fonts: ^6.1.0
|
||||
sqflite: ^2.3.0
|
||||
sqflite_common_ffi: ^2.0.0
|
||||
path: ^1.8.1
|
||||
crypto: ^3.0.2
|
||||
shared_preferences: ^2.0.0
|
||||
http: ^0.13.4
|
||||
file_picker: ^4.6.1
|
||||
http: ^1.1.0
|
||||
# Actualizado file_picker para compatibilidad con AGP 8 y FFI 2+ en Flutter 3/Dart 3
|
||||
file_picker: ^8.0.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Utilidad para interactuar con el servidor MCP de Infraestructura de Telcotronics (SSE en http://192.168.10.160:3006/sse).
|
||||
Permite:
|
||||
- Consultar herramientas y recursos del MCP de infraestructura.
|
||||
- Buscar hardware, servicios, aplicaciones de IA y servicios externos.
|
||||
- Documentar y registrar servicios del ecosistema de acuerdo con la especificación central.
|
||||
"""
|
||||
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import sys
|
||||
|
||||
BASE_URL = "http://192.168.10.160:3006"
|
||||
|
||||
class McpClient:
|
||||
def __init__(self, base_url=BASE_URL):
|
||||
self.base_url = base_url
|
||||
self.sse_url = f"{base_url}/sse"
|
||||
self.endpoint_path = None
|
||||
self.responses = {}
|
||||
self.stop_event = threading.Event()
|
||||
self.msg_counter = 1
|
||||
|
||||
def _sse_listener(self):
|
||||
req = urllib.request.Request(self.sse_url, headers={"Accept": "text/event-stream"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
current_event = None
|
||||
for line in resp:
|
||||
if self.stop_event.is_set():
|
||||
break
|
||||
line_str = line.decode('utf-8').strip()
|
||||
if not line_str:
|
||||
continue
|
||||
if line_str.startswith("event:"):
|
||||
current_event = line_str.split(":", 1)[1].strip()
|
||||
elif line_str.startswith("data:"):
|
||||
data_str = line_str.split(":", 1)[1].strip()
|
||||
if current_event == "endpoint":
|
||||
self.endpoint_path = data_str
|
||||
elif current_event == "message":
|
||||
try:
|
||||
msg = json.loads(data_str)
|
||||
if msg.get("id") is not None:
|
||||
self.responses[msg["id"]] = msg
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
def connect(self):
|
||||
t = threading.Thread(target=self._sse_listener, daemon=True)
|
||||
t.start()
|
||||
for _ in range(50):
|
||||
if self.endpoint_path:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
if not self.endpoint_path:
|
||||
raise ConnectionError("No se pudo obtener el endpoint SSE del servidor MCP.")
|
||||
|
||||
self.post_url = urllib.parse.urljoin(self.base_url, self.endpoint_path)
|
||||
|
||||
# Inicializar sesión MCP
|
||||
self._send_rpc(self.msg_counter, "initialize", {
|
||||
"protocolVersion": "2024-11-05",
|
||||
"capabilities": {},
|
||||
"clientInfo": {"name": "agente-app-sentinel-one", "version": "1.0"}
|
||||
})
|
||||
self._wait_response(self.msg_counter)
|
||||
self.msg_counter += 1
|
||||
|
||||
self._send_rpc(None, "notifications/initialized", {})
|
||||
|
||||
def _send_rpc(self, msg_id, method, params=None):
|
||||
payload = {"jsonrpc": "2.0", "method": method}
|
||||
if msg_id is not None:
|
||||
payload["id"] = msg_id
|
||||
if params is not None:
|
||||
payload["params"] = params
|
||||
req = urllib.request.Request(
|
||||
self.post_url,
|
||||
data=json.dumps(payload).encode('utf-8'),
|
||||
headers={"Content-Type": "application/json"}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=15) as r:
|
||||
return r.read().decode('utf-8')
|
||||
|
||||
def _wait_response(self, msg_id, timeout_sec=6.0):
|
||||
start = time.time()
|
||||
while time.time() - start < timeout_sec:
|
||||
if msg_id in self.responses:
|
||||
return self.responses[msg_id]
|
||||
time.sleep(0.08)
|
||||
return self.responses.get(msg_id, {})
|
||||
|
||||
def call_tool(self, tool_name, arguments):
|
||||
cid = self.msg_counter
|
||||
self.msg_counter += 1
|
||||
self._send_rpc(cid, "tools/call", {"name": tool_name, "arguments": arguments})
|
||||
res = self._wait_response(cid)
|
||||
return res.get("result", {})
|
||||
|
||||
def list_tools(self):
|
||||
cid = self.msg_counter
|
||||
self.msg_counter += 1
|
||||
self._send_rpc(cid, "tools/list", {})
|
||||
res = self._wait_response(cid)
|
||||
return res.get("result", {}).get("tools", [])
|
||||
|
||||
def close(self):
|
||||
self.stop_event.set()
|
||||
|
||||
if __name__ == "__main__":
|
||||
client = McpClient()
|
||||
try:
|
||||
client.connect()
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "tools":
|
||||
tools = client.list_tools()
|
||||
for t in tools:
|
||||
print(f"- {t['name']}: {t.get('description', '')}")
|
||||
elif len(sys.argv) > 2 and sys.argv[1] == "buscar":
|
||||
res = client.call_tool("buscar_infraestructura", {"query": sys.argv[2]})
|
||||
for c in res.get("content", []):
|
||||
print(c.get("text", ""))
|
||||
else:
|
||||
print("Uso: python3 scripts/mcp_infra.py [tools|buscar <query>]")
|
||||
finally:
|
||||
client.close()
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Script utilitario para la integración del Agente SENTINEL ONE con el ecosistema sigma-robot (Telcotronics).
|
||||
Maneja de forma segura:
|
||||
- Consulta de estado y almacenamiento automático del token único en .env.
|
||||
- Consulta de identidad autorizada (/yo).
|
||||
- Consulta de agentes disponibles en el ecosistema.
|
||||
- Lectura de mensajes pendientes.
|
||||
- Envío de mensajes (general, a otro agente o a pablinux).
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
ENV_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.env')
|
||||
BASE_URL = 'https://sigma-bot.telcotronics.com/ecosistema/v1'
|
||||
|
||||
def cargar_env():
|
||||
# Carga las variables locales desde .env sin depender de paquetes externos
|
||||
env = {}
|
||||
if os.path.exists(ENV_FILE):
|
||||
with open(ENV_FILE, 'r', encoding='utf-8') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line and not line.startswith('#') and '=' in line:
|
||||
k, v = line.split('=', 1)
|
||||
env[k.strip()] = v.strip()
|
||||
return env
|
||||
|
||||
def guardar_env_token(token):
|
||||
# Guarda el token en .env asegurando permisos restrictivos
|
||||
env = cargar_env()
|
||||
env['SIGMA_AGENTE_TOKEN'] = token
|
||||
with open(ENV_FILE, 'w', encoding='utf-8') as f:
|
||||
for k, v in env.items():
|
||||
f.write(f"{k}={v}\n")
|
||||
try:
|
||||
os.chmod(ENV_FILE, 0o600)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def request_json(url, method='GET', data=None, token=None):
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
if token:
|
||||
headers['Authorization'] = f'Bearer {token}'
|
||||
|
||||
req_data = json.dumps(data).encode('utf-8') if data is not None else None
|
||||
req = urllib.request.Request(url, data=req_data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
return json.loads(resp.read().decode('utf-8'))
|
||||
except urllib.error.HTTPError as e:
|
||||
err_msg = e.read().decode('utf-8')
|
||||
try:
|
||||
return json.loads(err_msg)
|
||||
except Exception:
|
||||
return {'error': f'HTTP {e.code}: {err_msg}'}
|
||||
except Exception as e:
|
||||
return {'error': str(e)}
|
||||
|
||||
def verificar_estado():
|
||||
# Consulta el estado de la solicitud y extrae el token una sola vez si está activo
|
||||
env = cargar_env()
|
||||
solicitud_id = env.get('SIGMA_AGENTE_SOLICITUD_ID')
|
||||
codigo_secreto = env.get('SIGMA_AGENTE_CODIGO')
|
||||
|
||||
if not solicitud_id or not codigo_secreto:
|
||||
print("[!] No se encontró SIGMA_AGENTE_SOLICITUD_ID o SIGMA_AGENTE_CODIGO en .env.")
|
||||
return
|
||||
|
||||
payload = {'solicitud_id': solicitud_id, 'codigo_secreto': codigo_secreto}
|
||||
res = request_json(f"{BASE_URL}/agentes/estado", method='POST', data=payload)
|
||||
|
||||
estado = res.get('estado')
|
||||
print(f"Estado de la solicitud: {estado}")
|
||||
|
||||
if estado == 'activo':
|
||||
token = res.get('token')
|
||||
if token:
|
||||
guardar_env_token(token)
|
||||
print("[✓] Autorización confirmada: Token recibido y persistido en .env de forma segura.")
|
||||
else:
|
||||
print("[i] El agente ya está activo (el token ya había sido entregado previamente).")
|
||||
elif estado == 'pendiente':
|
||||
print("[⏳] La solicitud continúa pendiente de autorización por pablinux.")
|
||||
elif estado == 'rechazado':
|
||||
print("[✗] Solicitud rechazada. Contactar a pablinux.")
|
||||
else:
|
||||
print(f"[?] Respuesta: {res}")
|
||||
|
||||
def consultar_yo():
|
||||
# Comprueba la identidad del agente con el token autorizado
|
||||
env = cargar_env()
|
||||
token = env.get('SIGMA_AGENTE_TOKEN')
|
||||
if not token:
|
||||
print("[!] No hay SIGMA_AGENTE_TOKEN configurado en .env.")
|
||||
return
|
||||
res = request_json(f"{BASE_URL}/agentes/yo", method='GET', token=token)
|
||||
print(json.dumps(res, indent=2, ensure_ascii=False))
|
||||
|
||||
def listar_agentes():
|
||||
# Lista los agentes activos en el ecosistema
|
||||
env = cargar_env()
|
||||
token = env.get('SIGMA_AGENTE_TOKEN')
|
||||
if not token:
|
||||
print("[!] No hay SIGMA_AGENTE_TOKEN configurado en .env.")
|
||||
return
|
||||
res = request_json(f"{BASE_URL}/agentes", method='GET', token=token)
|
||||
print(json.dumps(res, indent=2, ensure_ascii=False))
|
||||
|
||||
def leer_pendientes():
|
||||
# Lee mensajes pendientes para este agente
|
||||
env = cargar_env()
|
||||
token = env.get('SIGMA_AGENTE_TOKEN')
|
||||
if not token:
|
||||
print("[!] No hay SIGMA_AGENTE_TOKEN configurado en .env.")
|
||||
return
|
||||
res = request_json(f"{BASE_URL}/mensajes/pendientes", method='GET', token=token)
|
||||
print(json.dumps(res, indent=2, ensure_ascii=False))
|
||||
|
||||
def enviar_mensaje(para, mensaje, agente_id=None):
|
||||
# Envía un mensaje respetando las directivas del ecosistema
|
||||
env = cargar_env()
|
||||
token = env.get('SIGMA_AGENTE_TOKEN')
|
||||
if not token:
|
||||
print("[!] No hay SIGMA_AGENTE_TOKEN configurado en .env.")
|
||||
return
|
||||
payload = {'para': para, 'mensaje': mensaje}
|
||||
if agente_id is not None:
|
||||
payload['agente_id'] = int(agente_id)
|
||||
res = request_json(f"{BASE_URL}/mensajes", method='POST', data=payload, token=token)
|
||||
print(json.dumps(res, indent=2, ensure_ascii=False))
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) < 2:
|
||||
print("Uso: python3 scripts/sigma_agente.py [estado|yo|agentes|pendientes|enviar_general <msg>|enviar_pablinux <msg>]")
|
||||
sys.exit(1)
|
||||
|
||||
cmd = sys.argv[1].lower()
|
||||
if cmd == 'estado':
|
||||
verificar_estado()
|
||||
elif cmd == 'yo':
|
||||
consultar_yo()
|
||||
elif cmd == 'agentes':
|
||||
listar_agentes()
|
||||
elif cmd == 'pendientes':
|
||||
leer_pendientes()
|
||||
elif cmd == 'enviar_general' and len(sys.argv) >= 3:
|
||||
enviar_mensaje('general', ' '.join(sys.argv[2:]))
|
||||
elif cmd == 'enviar_pablinux' and len(sys.argv) >= 3:
|
||||
enviar_mensaje('pablinux', ' '.join(sys.argv[2:]))
|
||||
else:
|
||||
print(f"Comando desconocido o argumentos faltantes: {cmd}")
|
||||
@@ -0,0 +1,144 @@
|
||||
# Ficha Técnica Oficial de Publicación en Tienda
|
||||
**Aplicación:** SENTINEL ONE
|
||||
**Identificador de Paquete (Application ID):** `net.siaxsystem.sentinelone`
|
||||
**Bundle ID (iOS):** `net.siaxsystem.sentinelone`
|
||||
**Versión Inicial:** `1.0.0` (Build `1`)
|
||||
**Plataformas Objetivo:** Google Play Store & Apple App Store
|
||||
|
||||
---
|
||||
|
||||
## 1. Ficha Principal de la Tienda
|
||||
|
||||
### Nombre de la Aplicación (Máx. 30 caracteres)
|
||||
> **SENTINEL ONE - Seguridad** (25 caracteres)
|
||||
|
||||
*(Alternativa concisa: `SENTINEL ONE` — 12 caracteres)*
|
||||
|
||||
### Descripción Breve (Máx. 80 caracteres)
|
||||
> **Gestión de alarmas, control de acceso físico y monitoreo para operadores.** (74 caracteres)
|
||||
|
||||
### Descripción Completa (Máx. 4000 caracteres)
|
||||
```text
|
||||
SENTINEL ONE es la solución móvil integral diseñada para operadores de seguridad privada, supervisores de instalaciones y personal de vigilancia técnica encargados del monitoreo continuo y control de infraestructuras críticas.
|
||||
|
||||
Diseñada bajo una rigurosa arquitectura offline-first, SENTINEL ONE permite operar de forma fluida y autónoma incluso en escenarios con conectividad de red inestable o restringida, asegurando la integridad y disponibilidad de la información de guardia.
|
||||
|
||||
MÓDULOS Y CAPACIDADES PRINCIPALES:
|
||||
|
||||
1. MONITOREO TÁCTICO Y GESTIÓN DE ALARMAS EN TIEMPO REAL
|
||||
• Tablero central con indicadores visuales de alarmas activas, incidentes críticos y eventos resueltos en las últimas 24 horas.
|
||||
• Clasificación de alertas por nivel de severidad (Nivel 1 informativo hasta Nivel 5 crítico).
|
||||
• Detalle zonificado de sensores: perimetrales, apertura, volumétricos y detección de humo.
|
||||
• Flujo de respuesta estructurado: confirmación, silenciado de alertas y escalado protocolar hacia la central de monitoreo.
|
||||
|
||||
2. CONTROL DE ACCESO FÍSICO REMOTO
|
||||
• Supervisión de estado de puertas y esclusas de seguridad (bloqueada / desbloqueada).
|
||||
• Comando de desbloqueo remoto y aseguramiento de accesos por zona.
|
||||
• Registro cronológico de accesos con verificación de credenciales (autorizados y denegados) para auditoría inmediata.
|
||||
• Registro de usuarios del sistema con niveles de acceso diferenciados y delimitación por vigencia y zonas permitidas.
|
||||
|
||||
3. LOG DE EVENTOS Y AUDITORÍA CRONOLÓGICA
|
||||
• Historial operativo continuo con identificación por categorías: Alertas Críticas, Notificaciones de Sistema y Novedades de Turno.
|
||||
• Trazabilidad de acciones realizadas por el operador durante el servicio.
|
||||
|
||||
4. COMUNICACIÓN Y PROTOCOLOS DE EMERGENCIA
|
||||
• Módulo de enlace directo con la Central de Monitoreo para coordinación táctica de incidentes.
|
||||
• Botón de Pánico rápido con registro prioritario en el log de auditoría.
|
||||
• Botón de Soporte Asistencial para enlace operativo y canal de llamada directa.
|
||||
|
||||
5. GESTIÓN DEL PERFIL DE OPERADOR Y SESIÓN DE GUARDIA
|
||||
• Panel del operador en turno con estadísticas de incidentes gestionados y accesos autorizados.
|
||||
• Historial de sesiones de turno con cálculo de horas de guardia y estado de actividad.
|
||||
• Gestión de seguridad personal con actualización de código PIN mediante hashing criptográfico local.
|
||||
|
||||
ARQUITECTURA Y SEGURIDAD:
|
||||
• Modelo Offline-First: almacenamiento local en SQLite de alto rendimiento que no interrumpe la vigilancia ante cortes de datos.
|
||||
• Protección Criptográfica: contraseñas y códigos PIN protegidos mediante algoritmos hash unidireccionales SHA-256.
|
||||
• Interfaz Diseñada para Operación Crítica: modo oscuro de alto contraste que reduce la fatiga visual en guardias nocturnas y prioriza la legibilidad de alertas críticas.
|
||||
|
||||
SENTINEL ONE optimiza los tiempos de respuesta, eleva el estándar de control físico y profesionaliza la gestión del servicio de seguridad en cualquier instalación corporativa o industrial.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Categorización y Declaraciones Legales
|
||||
|
||||
### Categorización
|
||||
- **Categoría principal (Google Play):** Empresa (*Business*)
|
||||
- **Categoría secundaria (Google Play):** Herramientas (*Tools*) / Productividad (*Productivity*)
|
||||
- **Categoría principal (Apple App Store):** Business (Negocios)
|
||||
- **Categoría secundaria (Apple App Store):** Utilities (Utilidades)
|
||||
- **Etiquetas sugeridas:** Seguridad, Control de acceso, Monitoreo de alarmas, Auditoría, Gestión de guardias.
|
||||
|
||||
### Clasificación de Contenido (IARC / PEGI / ESRB)
|
||||
- **Clasificación IARC estimada:** **Para todos / PEGI 3 / Everyone**
|
||||
- **Violencia:** No contiene violencia gráfica ni explícita.
|
||||
- **Contenido sexual:** No.
|
||||
- **Lenguaje ofensivo:** No.
|
||||
- **Sustancias controladas:** No.
|
||||
- **Acceso libre a Internet:** No.
|
||||
|
||||
### Declaración de Anuncios
|
||||
- **¿La app contiene anuncios?:** **NO**
|
||||
*(Nota para consola: Los banners que se despliegan en la pantalla de inicio corresponden a comunicados informativos internos de la empresa partner de seguridad, no a redes de publicidad programática de terceros tipo Google AdMob o Unity Ads).*
|
||||
|
||||
### Declaración de Seguridad de los Datos (Data Safety / Privacy Nutrition Labels)
|
||||
|
||||
| Campo | Declaración Google Play | Declaración App Store | Justificación |
|
||||
|---|---|---|---|
|
||||
| **¿La app recopila datos?** | Sí | Sí | Datos estrictamente necesarios para la función operativa. |
|
||||
| **¿Los datos se comparten con terceros?** | **NO** | **NO** | No se ceden, venden ni comparten datos a brokers ni redes de publicidad. |
|
||||
| **Identificadores (ID de usuario, nombre)** | Recopilado (Opcional) | Data Linked to You | Asignación de turnos y registro de quién opera el sistema. |
|
||||
| **Fotos / Galería** | Recopilado (Opcional) | Data Not Linked | Foto de perfil del operador seleccionada localmente desde el dispositivo. |
|
||||
| **Registros de diagnóstico / Actividad** | Recopilado | App Functionality | Registro local de eventos de seguridad (accesos y alarmas). |
|
||||
| **Cifrado en tránsito** | **Sí (HTTPS / TLS 1.3)** | Cifrado en tránsito | Toda sincronización con backend corporativo utiliza canal seguro TLS. |
|
||||
| **Mecanismo de eliminación** | **Sí** | Solicitud de borrado | Opción de restablecimiento local de base de datos en Ajustes y revocación en servidor. |
|
||||
|
||||
---
|
||||
|
||||
## 3. Instrucciones para el Revisor de la Tienda (Acceso a la App)
|
||||
|
||||
> **IMPORTANTE PARA EL EVALUADOR DE GOOGLE PLAY Y APPLE APP STORE:**
|
||||
> La aplicación cuenta con un entorno de evaluación offline autónomo preinstalado que **no depende de conectividad externa, servidores remotos, SMS ni WhatsApp**. Siga estos pasos para acceder:
|
||||
|
||||
1. **Pantalla inicial de inicio de sesión:**
|
||||
- La aplicación abrirá directamente en la pantalla de **CÓDIGO DE ACCESO**.
|
||||
2. **Credenciales Demo de Evaluación:**
|
||||
- **PIN fijo de prueba:** `123456`
|
||||
- *Alternativa de 1 solo toque:* Presione el botón **"Auto-llenar"** situado en la tarjeta informativa **"MODO EVALUACIÓN / REVISOR"** en la parte inferior de la pantalla.
|
||||
3. **Ingreso:**
|
||||
- Presione el botón **"INGRESAR"**.
|
||||
4. **Población automática de datos de demostración:**
|
||||
- El sistema validará el PIN localmente y poblará de forma inmediata y automática la base de datos interna con un conjunto completo de datos operacionales de prueba (alarmas activas de distintos niveles, registros de aperturas de puertas, timeline de eventos, chat simulado con la central y estadísticas de turno).
|
||||
5. **Navegación completa habilitada:**
|
||||
- El revisor podrá inspeccionar todas las pestañas de la barra inferior (**INICIO**, **ACCESO**, **ALARMAS**, **PERFIL**) y todas las pantallas secundarias sin ninguna pantalla vacía ni dependencia de hardware real.
|
||||
|
||||
---
|
||||
|
||||
## 4. Notas de la Versión (What's New / Novedades de la Versión)
|
||||
*(Máximo 500 caracteres)*
|
||||
|
||||
```text
|
||||
Versión 1.0.0 — Lanzamiento inicial de SENTINEL ONE:
|
||||
• Monitoreo táctico de alarmas en tiempo real por zonas y severidad.
|
||||
• Control y aseguramiento remoto de accesos físicos con registro de auditoría.
|
||||
• Enlace de comunicación y protocolos de pánico con la central de monitoreo.
|
||||
• Registro de eventos y métricas de turno para operadores de seguridad.
|
||||
• Arquitectura offline-first de alto rendimiento y protección de credenciales mediante SHA-256.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Checklist de Pre-Lanzamiento y Publicación
|
||||
|
||||
- [x] **Application ID / Package Name:** `net.siaxsystem.sentinelone` unificado.
|
||||
- [x] **Código de Versión:** `versionCode 1`, `versionName 1.0.0`.
|
||||
- [x] **Cuenta Demo Revisor:** PIN fijo `123456` con autocompletado y carga automática de datos locales.
|
||||
- [x] **Ficha de Tienda redactada:** Título, descripciones corta/larga, categorización y notas de versión.
|
||||
- [x] **Data Safety / Nutrición de Privacidad:** Cuestionario preparado sin transferencia a terceros.
|
||||
- [x] **Política de Privacidad:** Documento HTML estático generado y listo para alojamiento HTTPS.
|
||||
- [x] **Ícono oficial de tienda (512x512 PNG sin transparencia):** Generado en `store_listing/graficos/00_icono_512.png`.
|
||||
- [x] **Gráfico destacado (1024x500 PNG):** Generado en `store_listing/graficos/grafico_destacado_1024x500.png`.
|
||||
- [x] **Capturas de pantalla simétricas (aspecto 1:2 / 1344x2688):** Generadas en `store_listing/graficos/` (01_login.png a 06_perfil_usuario.png).
|
||||
- [ ] **Firmado de Release (Keystore):** Configuración de `signingConfigs.release` en `android/app/build.gradle`.
|
||||
- [ ] **Compilación de Bundle final:** `flutter build appbundle --release` (generación del archivo `.aab`).
|
||||
@@ -0,0 +1,157 @@
|
||||
import os
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
|
||||
OUTPUT_DIR = "store_listing/graficos"
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
|
||||
# Paleta oficial de la aplicación (theme.dart)
|
||||
COLOR_BG = (10, 14, 20) # #0A0E14 - surfaceLowest
|
||||
COLOR_CARD = (24, 28, 34) # #181C22 - surfaceLow
|
||||
COLOR_PRIMARY = (176, 198, 255) # #B0C6FF - primary
|
||||
COLOR_TEXT = (226, 232, 240) # #E2E8F0 - textMain
|
||||
COLOR_MUTED = (148, 163, 184) # #94A3B8 - textMuted
|
||||
COLOR_CONTAINER = (0, 35, 89) # #002359 - primaryContainer
|
||||
|
||||
logo_source = Image.open("lib/recursos/logo_app.png").convert("RGBA")
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 1. ÍCONO DE TIENDA: 512x512 PNG sin transparencias
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
def generar_icono_512():
|
||||
size = (512, 512)
|
||||
# Fondo sólido sin transparencia (Requisito estricto de Google Play)
|
||||
canvas = Image.new("RGB", size, COLOR_BG)
|
||||
|
||||
# Rescalar logo con filtro Lanczos de alta calidad
|
||||
logo_size = 432
|
||||
logo_resized = logo_source.resize((logo_size, logo_size), Image.Resampling.LANCZOS)
|
||||
|
||||
# Efecto de sutil resplandor azul detrás del logo
|
||||
glow = Image.new("RGBA", size, (0, 0, 0, 0))
|
||||
glow_draw = ImageDraw.Draw(glow)
|
||||
center = (256, 256)
|
||||
r = 210
|
||||
glow_draw.ellipse(
|
||||
[center[0] - r, center[1] - r, center[0] + r, center[1] + r],
|
||||
fill=(0, 35, 89, 120)
|
||||
)
|
||||
glow = glow.filter(ImageFilter.GaussianBlur(radius=20))
|
||||
|
||||
canvas_rgba = canvas.convert("RGBA")
|
||||
canvas_rgba.alpha_composite(glow)
|
||||
|
||||
# Centrar el logo
|
||||
pos = ((size[0] - logo_size) // 2, (size[1] - logo_size) // 2)
|
||||
canvas_rgba.alpha_composite(logo_resized, pos)
|
||||
|
||||
final_icon = canvas_rgba.convert("RGB")
|
||||
dest_path = os.path.join(OUTPUT_DIR, "00_icono_512.png")
|
||||
final_icon.save(dest_path, "PNG", optimize=True)
|
||||
# También como icono_512.png para compatibilidad
|
||||
final_icon.save(os.path.join(OUTPUT_DIR, "icono_512.png"), "PNG", optimize=True)
|
||||
print(f"✓ Ícono generado: {dest_path} (512x512 RGB)")
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 2. GRÁFICO DESTACADO: 1024x500 PNG sin transparencias
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
def generar_grafico_destacado():
|
||||
width, height = 1024, 500
|
||||
canvas = Image.new("RGB", (width, height), COLOR_BG)
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
|
||||
# Fondo con degradado y cuadrícula técnica de seguridad
|
||||
for y in range(height):
|
||||
ratio = y / height
|
||||
r = int(COLOR_BG[0] + (COLOR_CARD[0] - COLOR_BG[0]) * ratio)
|
||||
g = int(COLOR_BG[1] + (COLOR_CARD[1] - COLOR_BG[1]) * ratio)
|
||||
b = int(COLOR_BG[2] + (COLOR_CARD[2] - COLOR_BG[2]) * ratio)
|
||||
draw.line([(0, y), (width, y)], fill=(r, g, b))
|
||||
|
||||
# Cuadrícula sutil
|
||||
grid_color = (25, 32, 45)
|
||||
for x in range(0, width, 40):
|
||||
draw.line([(x, 0), (x, height)], fill=grid_color, width=1)
|
||||
for y in range(0, height, 40):
|
||||
draw.line([(0, y), (width, y)], fill=grid_color, width=1)
|
||||
|
||||
# Halo luminoso detrás del logo y títulos
|
||||
halo = Image.new("RGBA", (width, height), (0, 0, 0, 0))
|
||||
halo_draw = ImageDraw.Draw(halo)
|
||||
halo_draw.ellipse([80, 50, 480, 450], fill=(0, 35, 89, 140))
|
||||
halo_draw.ellipse([450, 100, 950, 400], fill=(20, 30, 55, 100))
|
||||
halo = halo.filter(ImageFilter.GaussianBlur(radius=40))
|
||||
|
||||
canvas_rgba = canvas.convert("RGBA")
|
||||
canvas_rgba.alpha_composite(halo)
|
||||
|
||||
# Logo a la izquierda (340x340)
|
||||
logo_size = 320
|
||||
logo_resized = logo_source.resize((logo_size, logo_size), Image.Resampling.LANCZOS)
|
||||
canvas_rgba.alpha_composite(logo_resized, (70, (height - logo_size) // 2))
|
||||
|
||||
# Fuentes tipográficas
|
||||
font_paths = [
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
|
||||
"/usr/share/fonts/truetype/ubuntu/Ubuntu-B.ttf",
|
||||
"/usr/share/fonts/truetype/freefont/FreeSansBold.ttf",
|
||||
]
|
||||
font_regular_paths = [
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
"/usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf",
|
||||
"/usr/share/fonts/truetype/freefont/FreeSans.ttf",
|
||||
]
|
||||
|
||||
title_font = None
|
||||
for p in font_paths:
|
||||
if os.path.exists(p):
|
||||
title_font = ImageFont.truetype(p, 52)
|
||||
badge_font = ImageFont.truetype(p, 16)
|
||||
break
|
||||
if not title_font:
|
||||
title_font = ImageFont.load_default()
|
||||
badge_font = ImageFont.load_default()
|
||||
|
||||
sub_font = None
|
||||
for p in font_regular_paths:
|
||||
if os.path.exists(p):
|
||||
sub_font = ImageFont.truetype(p, 20)
|
||||
tag_font = ImageFont.truetype(p, 15)
|
||||
break
|
||||
if not sub_font:
|
||||
sub_font = ImageFont.load_default()
|
||||
tag_font = ImageFont.load_default()
|
||||
|
||||
text_draw = ImageDraw.Draw(canvas_rgba)
|
||||
|
||||
# Badge superior
|
||||
badge_x, badge_y = 430, 105
|
||||
badge_text = "SEGURIDAD ELECTRÓNICA & CONTROL"
|
||||
text_draw.rounded_rectangle([badge_x, badge_y, badge_x + 330, badge_y + 30], radius=15, fill=(0, 35, 89, 220), outline=COLOR_PRIMARY, width=1)
|
||||
text_draw.text((badge_x + 18, badge_y + 6), badge_text, font=badge_font, fill=COLOR_PRIMARY)
|
||||
|
||||
# Título principal
|
||||
text_draw.text((430, 150), "SENTINEL ONE", font=title_font, fill=(255, 255, 255))
|
||||
|
||||
# Subtítulo
|
||||
text_draw.text((430, 220), "Monitoreo Táctico y Control de Acceso", font=sub_font, fill=COLOR_PRIMARY)
|
||||
|
||||
# Puntos clave / features
|
||||
features = [
|
||||
"• Gestión de Alarmas e Incidentes en Tiempo Real",
|
||||
"• Control y Bloqueo Remoto de Puertas Físicas",
|
||||
"• Arquitectura Offline-First con Registro de Auditoría",
|
||||
"• Enlace Táctico y Protocolo de Pánico Inmediato"
|
||||
]
|
||||
fy = 270
|
||||
for feat in features:
|
||||
text_draw.text((430, fy), feat, font=tag_font, fill=COLOR_TEXT)
|
||||
fy += 32
|
||||
|
||||
final_graphic = canvas_rgba.convert("RGB")
|
||||
dest_path = os.path.join(OUTPUT_DIR, "grafico_destacado_1024x500.png")
|
||||
final_graphic.save(dest_path, "PNG", optimize=True)
|
||||
print(f"✓ Gráfico destacado generado: {dest_path} (1024x500 RGB)")
|
||||
|
||||
if __name__ == "__main__":
|
||||
generar_icono_512()
|
||||
generar_grafico_destacado()
|
||||
|
After Width: | Height: | Size: 134 KiB |
|
After Width: | Height: | Size: 218 KiB |
|
After Width: | Height: | Size: 244 KiB |
|
After Width: | Height: | Size: 251 KiB |
|
After Width: | Height: | Size: 195 KiB |
|
After Width: | Height: | Size: 296 KiB |
|
After Width: | Height: | Size: 230 KiB |
|
After Width: | Height: | Size: 153 KiB |
|
After Width: | Height: | Size: 134 KiB |
@@ -0,0 +1,242 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Política de Privacidad | SENTINEL ONE</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg-color: #0A0E14;
|
||||
--card-bg: #181C22;
|
||||
--border-color: #262A31;
|
||||
--text-main: #E2E8F0;
|
||||
--text-muted: #94A3B8;
|
||||
--primary: #B0C6FF;
|
||||
--primary-container: #002359;
|
||||
--accent: #FFB3B3;
|
||||
--success: #86EFAC;
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
background-color: var(--bg-color);
|
||||
color: var(--text-main);
|
||||
line-height: 1.65;
|
||||
padding: 24px 16px;
|
||||
}
|
||||
.container {
|
||||
max-width: 860px;
|
||||
margin: 0 auto;
|
||||
background-color: var(--card-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 16px;
|
||||
padding: 40px 32px;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
header {
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
padding-bottom: 24px;
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
.badge {
|
||||
display: inline-block;
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1.5px;
|
||||
font-weight: 700;
|
||||
color: var(--primary);
|
||||
background-color: var(--primary-container);
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
h1 {
|
||||
font-size: 28px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.5px;
|
||||
color: #FFFFFF;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.meta {
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
h2 {
|
||||
font-size: 19px;
|
||||
font-weight: 700;
|
||||
color: #FFFFFF;
|
||||
margin-top: 32px;
|
||||
margin-bottom: 12px;
|
||||
border-left: 3px solid var(--primary);
|
||||
padding-left: 10px;
|
||||
}
|
||||
p {
|
||||
margin-bottom: 14px;
|
||||
color: var(--text-main);
|
||||
font-size: 15px;
|
||||
}
|
||||
ul {
|
||||
margin: 12px 0 18px 24px;
|
||||
}
|
||||
li {
|
||||
margin-bottom: 8px;
|
||||
font-size: 14.5px;
|
||||
color: var(--text-main);
|
||||
}
|
||||
.highlight-box {
|
||||
background-color: rgba(176, 198, 255, 0.06);
|
||||
border: 1px solid rgba(176, 198, 255, 0.2);
|
||||
border-radius: 10px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.highlight-box strong {
|
||||
color: var(--primary);
|
||||
}
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 20px 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
th, td {
|
||||
border: 1px solid var(--border-color);
|
||||
padding: 12px 14px;
|
||||
text-align: left;
|
||||
}
|
||||
th {
|
||||
background-color: rgba(255, 255, 255, 0.03);
|
||||
color: #FFFFFF;
|
||||
font-weight: 600;
|
||||
}
|
||||
footer {
|
||||
border-top: 1px solid var(--border-color);
|
||||
margin-top: 40px;
|
||||
padding-top: 20px;
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<span class="badge">Privacidad y Protección de Datos</span>
|
||||
<h1>Política de Privacidad de SENTINEL ONE</h1>
|
||||
<p class="meta">Última actualización: 10 de octubre de 2026 | Aplicación Móvil Corporativa</p>
|
||||
</header>
|
||||
|
||||
<div class="highlight-box">
|
||||
<strong>Declaración de Confianza:</strong> SENTINEL ONE respeta y protege la privacidad de sus usuarios. Esta aplicación <strong>no contiene publicidad de terceros, no rastrea a los usuarios para fines comerciales ni comercializa información personal</strong> con ninguna entidad externa.
|
||||
</div>
|
||||
|
||||
<h2>1. Responsable del Tratamiento</h2>
|
||||
<p>
|
||||
La aplicación móvil <strong>SENTINEL ONE</strong> (identificador <code>net.siaxsystem.sentinelone</code>) es desarrollada y operada como herramienta tecnológica para el monitoreo de seguridad electrónica y control de accesos físicos en entornos corporativos, residenciales e industriales.
|
||||
</p>
|
||||
<p>
|
||||
Para cualquier consulta relacionada con el tratamiento de datos y esta política, puede comunicarse con el equipo de soporte técnico a través del canal oficial: <code>soporte@telcotronics.net</code>.
|
||||
</p>
|
||||
|
||||
<h2>2. Datos que Recopilamos y Finalidad</h2>
|
||||
<p>
|
||||
La aplicación opera primordialmente bajo una arquitectura <em>offline-first</em> (almacenamiento local prioritario) y recopila únicamente los datos estrictamente indispensables para cumplir con sus funciones operativas:
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Tipo de Dato</th>
|
||||
<th>Método de Almacenamiento</th>
|
||||
<th>Finalidad Operativa</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><strong>Identificador de Operador y Nombre</strong></td>
|
||||
<td>Base de datos local SQLite y sincronización con central</td>
|
||||
<td>Identificación del personal de vigilancia en turno y firma de eventos atendidos.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Código PIN de Acceso</strong></td>
|
||||
<td>Hash unidireccional SHA-256 en almacenamiento seguro</td>
|
||||
<td>Autenticación biométrica o por PIN local. El PIN en texto plano nunca se guarda ni transmite.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Foto de Perfil</strong> (Opcional)</td>
|
||||
<td>Almacenamiento interno del dispositivo</td>
|
||||
<td>Personalización visual de la cuenta en el dispositivo local.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Registros de Accesos y Puertas</strong></td>
|
||||
<td>Base de datos SQLite local</td>
|
||||
<td>Auditoría cronológica de solicitudes de entrada y aseguramiento de puertas.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Historial de Alarmas y Eventos</strong></td>
|
||||
<td>Base de datos SQLite local</td>
|
||||
<td>Trazabilidad de incidentes (intrusión, fuego, pánico) y tiempos de atención del operador.</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<h2>3. Permisos Solicitados en el Dispositivo</h2>
|
||||
<p>
|
||||
La aplicación solicita únicamente los permisos técnicos indispensables para su funcionamiento en Android e iOS:
|
||||
</p>
|
||||
<ul>
|
||||
<li><strong>Acceso a almacenamiento / selector de archivos:</strong> Utilizado de forma opcional cuando el operador decide cargar una foto de perfil desde el almacenamiento local de su dispositivo.</li>
|
||||
<li><strong>Acceso a red (Internet):</strong> Utilizado para establecer conexión segura HTTPS/TLS con la central de monitoreo del proveedor y sincronizar el estado de alarmas o puertas en tiempo real.</li>
|
||||
<li><strong>Audio / Sonido:</strong> Utilizado localmente para emitir alertas sonoras ante alarmas críticas o botones de emergencia.</li>
|
||||
</ul>
|
||||
|
||||
<h2>4. Seguridad y Cifrado de la Información</h2>
|
||||
<p>
|
||||
Implementamos salvaguardas técnicas rigurosas para proteger la información contra accesos no autorizados, pérdida o alteración:
|
||||
</p>
|
||||
<ul>
|
||||
<li><strong>Cifrado en Tránsito:</strong> Toda comunicación entre la aplicación y los servicios de backend se efectúa exclusivamente mediante conexiones cifradas HTTPS/TLS 1.3 con certificados válidos.</li>
|
||||
<li><strong>Protección Criptográfica Local:</strong> Las claves y códigos PIN se almacenan aplicando funciones hash SHA-256, imposibilitando la recuperación del PIN en texto plano.</li>
|
||||
<li><strong>Aislamiento en Sandbox:</strong> La base de datos SQLite y las preferencias locales se alojan en el contenedor seguro y aislado provisto por el sistema operativo móvil.</li>
|
||||
</ul>
|
||||
|
||||
<h2>5. No Transferencia a Terceros</h2>
|
||||
<p>
|
||||
<strong>SENTINEL ONE no comparte, alquila ni vende información personal</strong> a empresas de publicidad, brokers de datos, redes analíticas de monetización ni terceros comerciales. La información generada es propiedad exclusiva de la organización que opera el sistema y de su respectiva central de monitoreo autorizada.
|
||||
</p>
|
||||
|
||||
<h2>6. Conservación y Eliminación de Datos</h2>
|
||||
<p>
|
||||
Los datos operacionales almacenados localmente pueden ser eliminados en cualquier momento por el usuario desde la pantalla de Configuración de la aplicación mediante la función de restablecimiento de base de datos local, o desinstalando la aplicación del dispositivo.
|
||||
</p>
|
||||
<p>
|
||||
Para solicitar la baja de credenciales o registros asociados en la central de monitoreo de su organización, el operador o titular puede canalizar su solicitud formalmente a través del administrador de seguridad de su empresa o vía <code>soporte@telcotronics.net</code>.
|
||||
</p>
|
||||
|
||||
<h2>7. Derechos del Usuario (ARCO)</h2>
|
||||
<p>
|
||||
De conformidad con los estándares internacionales de protección de datos (como el RGPD y normativas locales aplicables), los usuarios tienen derecho a:
|
||||
</p>
|
||||
<ul>
|
||||
<li>Acceder a sus datos de registro almacenados en el sistema.</li>
|
||||
<li>Rectificar cualquier información inexacta o desactualizada.</li>
|
||||
<li>Solicitar la cancelación o eliminación de sus credenciales operativas.</li>
|
||||
<li>Oponerse al tratamiento de datos no indispensables para la relación contractual de seguridad.</li>
|
||||
</ul>
|
||||
|
||||
<h2>8. Actualizaciones a esta Política</h2>
|
||||
<p>
|
||||
Podemos actualizar esta Política de Privacidad para reflejar mejoras técnicas o actualizaciones regulatorias. Cualquier modificación sustancial será notificada dentro de la aplicación o a través de las notas de la versión en las tiendas oficiales Google Play Store y Apple App Store.
|
||||
</p>
|
||||
|
||||
<footer>
|
||||
<p>© 2026 SENTINEL ONE. Todos los derechos reservados. | Sistema de Seguridad Electrónica</p>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,51 @@
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from PIL import Image
|
||||
|
||||
ADB_PATH = "/home/pablinux/Android/Sdk/platform-tools/adb"
|
||||
OUTPUT_DIR = "store_listing/graficos"
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
|
||||
# Coordenadas matemáticas para recorte simétrico de barras de sistema en resolución 1344x2992:
|
||||
# (0, 152, 1344, 152 + 2688) -> Elimina barra de estado superior (152px) y barra de gestos inferior (152px)
|
||||
# Genera una imagen exacta de 1344 x 2688 (Relación 1:2 / 2:1), formato oficial para Google Play / App Store.
|
||||
CROP_BOX = (0, 152, 1344, 152 + 2688)
|
||||
|
||||
def capturar_pantalla(nombre_archivo):
|
||||
raw_path = f"/tmp/{nombre_archivo}_raw.png"
|
||||
dest_path = os.path.join(OUTPUT_DIR, f"{nombre_archivo}.png")
|
||||
|
||||
# 1. Tomar screenshot limpio desde ADB
|
||||
cmd = f"{ADB_PATH} exec-out screencap -p > {raw_path}"
|
||||
subprocess.run(cmd, shell=True, check=True)
|
||||
|
||||
# 2. Recortar simétricamente con PIL
|
||||
im = Image.open(raw_path)
|
||||
if im.size == (1344, 2992):
|
||||
im_cropped = im.crop(CROP_BOX)
|
||||
else:
|
||||
# Si la resolución difiere, calcular recorte simétrico proporcional
|
||||
w, h = im.size
|
||||
target_h = int(w * 2)
|
||||
margin = (h - target_h) // 2
|
||||
im_cropped = im.crop((0, margin, w, margin + target_h))
|
||||
|
||||
im_cropped.save(dest_path, "PNG", optimize=True)
|
||||
print(f"✓ Captura guardada: {dest_path} -> Tamaño: {im_cropped.size} (Relación 1:2)")
|
||||
return dest_path
|
||||
|
||||
def tap(x, y, delay=1.5):
|
||||
subprocess.run(f"{ADB_PATH} shell input tap {x} {y}", shell=True)
|
||||
time.sleep(delay)
|
||||
|
||||
def swipe(x1, y1, x2, y2, duration=300, delay=1.5):
|
||||
subprocess.run(f"{ADB_PATH} shell input swipe {x1} {y1} {x2} {y2} {duration}", shell=True)
|
||||
time.sleep(delay)
|
||||
|
||||
def key(keycode, delay=1.0):
|
||||
subprocess.run(f"{ADB_PATH} shell input keyevent {keycode}", shell=True)
|
||||
time.sleep(delay)
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Script de captura y recorte simétrico preparado.")
|
||||
@@ -0,0 +1,32 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:seguridad_electronica/services/sincronizador.dart';
|
||||
import 'package:seguridad_electronica/services/api_auth_service.dart';
|
||||
import 'package:seguridad_electronica/db/dao/alarmas_dao.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
sqfliteFfiInit();
|
||||
databaseFactory = databaseFactoryFfi;
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
|
||||
test('Prueba de sincronización real contra API_CENTINEL_SECURITY', () async {
|
||||
// 1. Precargar credenciales de Centinel
|
||||
await ApiAuthService.instance.usarCredencialesPruebaCentinel();
|
||||
final headers = await ApiAuthService.instance.getCentinelHeaders();
|
||||
print('Headers configurados: $headers');
|
||||
expect(headers != null, true);
|
||||
|
||||
// 2. Ejecutar pull de alarmas desde API
|
||||
await Sincronizador.instance.sincronizarAlarmas();
|
||||
|
||||
// 3. Verificar que se persistieron en SQLite
|
||||
final alarmas = await AlarmasDao().getAll();
|
||||
print('Total de alarmas en SQLite tras sincronización: ${alarmas.length}');
|
||||
for (final a in alarmas) {
|
||||
print(' - ID ${a.id}: severidad=${a.severidad}, estado=${a.estado}, notas=${a.notas}');
|
||||
}
|
||||
expect(alarmas.isNotEmpty, true);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:seguridad_electronica/services/whatsapp_alert_service.dart';
|
||||
import 'package:seguridad_electronica/models/usuario.dart';
|
||||
|
||||
void main() {
|
||||
group('Pruebas de Validación de Teléfono WhatsApp (E.164 con código de país)', () {
|
||||
test('Números internacionales válidos con código de país', () {
|
||||
// Ecuador (+593 o 593)
|
||||
expect(WhatsAppAlertService.esNumeroValido('+593991234567'), isTrue);
|
||||
expect(WhatsAppAlertService.esNumeroValido('593991234567'), isTrue);
|
||||
expect(WhatsAppAlertService.esNumeroValido('+593 99 123 4567'), isTrue);
|
||||
expect(WhatsAppAlertService.esNumeroValido('+593-99-123-4567'), isTrue);
|
||||
|
||||
// Estados Unidos / Canadá (+1)
|
||||
expect(WhatsAppAlertService.esNumeroValido('+14155552671'), isTrue);
|
||||
|
||||
// México (+52)
|
||||
expect(WhatsAppAlertService.esNumeroValido('+5215512345678'), isTrue);
|
||||
|
||||
// Argentina (+54)
|
||||
expect(WhatsAppAlertService.esNumeroValido('+5491123456789'), isTrue);
|
||||
});
|
||||
|
||||
test('Números inválidos (sin código de país o con cero inicial)', () {
|
||||
// Número local con 0 inicial (formato nacional inválido para WhatsApp)
|
||||
expect(WhatsAppAlertService.esNumeroValido('0991234567'), isFalse);
|
||||
expect(WhatsAppAlertService.esNumeroValido('+0991234567'), isFalse);
|
||||
|
||||
// Números demasiado cortos o vacíos
|
||||
expect(WhatsAppAlertService.esNumeroValido(''), isFalse);
|
||||
expect(WhatsAppAlertService.esNumeroValido('12345'), isFalse);
|
||||
expect(WhatsAppAlertService.esNumeroValido('+593'), isFalse);
|
||||
|
||||
// Letras o caracteres extraños
|
||||
expect(WhatsAppAlertService.esNumeroValido('abcde'), isFalse);
|
||||
});
|
||||
|
||||
test('Normalización de caracteres y espaciado', () {
|
||||
expect(WhatsAppAlertService.normalizarTelefono(' +593 99-123 4567 '), equals('+593991234567'));
|
||||
expect(WhatsAppAlertService.normalizarTelefono('(593) 991234567'), equals('593991234567'));
|
||||
});
|
||||
|
||||
test('Serialización y deserialización del modelo Usuario con teléfono', () {
|
||||
const u = Usuario(
|
||||
id: 1,
|
||||
nombre: 'Guardia Nocturno',
|
||||
iniciales: 'GN',
|
||||
nivelAcceso: 2,
|
||||
pinHash: 'hash123',
|
||||
telefono: '+593987654321',
|
||||
);
|
||||
|
||||
final map = u.toMap();
|
||||
expect(map['telefono'], equals('+593987654321'));
|
||||
|
||||
final u2 = Usuario.fromMap(map);
|
||||
expect(u2.telefono, equals('+593987654321'));
|
||||
|
||||
final u3 = u.copyWith(telefono: '+593999999999');
|
||||
expect(u3.telefono, equals('+593999999999'));
|
||||
expect(u3.nombre, equals('Guardia Nocturno'));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,30 +1,20 @@
|
||||
// This is a basic Flutter widget test.
|
||||
//
|
||||
// To perform an interaction with a widget in your test, use the WidgetTester
|
||||
// utility that Flutter provides. For example, you can send tap and scroll
|
||||
// gestures. You can also use WidgetTester to find child widgets in the widget
|
||||
// tree, read text, and verify that the values of widget properties are correct.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:seguridad_electronica/main.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
sqfliteFfiInit();
|
||||
databaseFactory = databaseFactoryFfi;
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
|
||||
testWidgets('SENTINEL ONE smoke test', (WidgetTester tester) async {
|
||||
// Build our app and trigger a frame.
|
||||
await tester.pumpWidget(const MyApp());
|
||||
|
||||
// Verify that our counter starts at 0.
|
||||
expect(find.text('0'), findsOneWidget);
|
||||
expect(find.text('1'), findsNothing);
|
||||
|
||||
// Tap the '+' icon and trigger a frame.
|
||||
await tester.tap(find.byIcon(Icons.add));
|
||||
await tester.pump();
|
||||
|
||||
// Verify that our counter has incremented.
|
||||
expect(find.text('0'), findsNothing);
|
||||
expect(find.text('1'), findsOneWidget);
|
||||
// Verify that the title or brand is rendered
|
||||
expect(find.text('SENTINEL ONE'), findsAtLeastNWidgets(1));
|
||||
});
|
||||
}
|
||||
|
||||