diff --git a/android/app/build.gradle b/android/app/build.gradle index a8b6e62..639ac6d 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -1,41 +1,28 @@ -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } +plugins { + id "com.android.application" + id "org.jetbrains.kotlin.android" + id "dev.flutter.flutter-gradle-plugin" } -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +// Carga opcional de credenciales de firma de producción desde key.properties +def keystoreProperties = new Properties() +def keystorePropertiesFile = rootProject.file('key.properties') +if (keystorePropertiesFile.exists()) { + keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } -def flutterVersionCode = localProperties.getProperty('flutter.versionCode') -if (flutterVersionCode == null) { - flutterVersionCode = '1' -} - -def flutterVersionName = localProperties.getProperty('flutter.versionName') -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 { - compileSdkVersion flutter.compileSdkVersion + namespace "com.sigmac.agenteventas" + compileSdk flutter.compileSdkVersion ndkVersion flutter.ndkVersion compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 } kotlinOptions { - jvmTarget = '1.8' + jvmTarget = '17' } sourceSets { @@ -43,19 +30,33 @@ android { } defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.sigmac.agenteventas" - minSdkVersion flutter.minSdkVersion - targetSdkVersion flutter.targetSdkVersion - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName + minSdk flutter.minSdkVersion + targetSdk flutter.targetSdkVersion + versionCode flutter.versionCode + versionName flutter.versionName + } + + // Configuración de firmas: Si existe key.properties se firma con el keystore de producción, + // caso contrario se usa el keystore debug para pruebas locales de release + signingConfigs { + release { + if (keystorePropertiesFile.exists()) { + keyAlias keystoreProperties['keyAlias'] + keyPassword keystoreProperties['keyPassword'] + storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null + storePassword keystoreProperties['storePassword'] + } + } } buildTypes { release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig signingConfigs.debug + if (keystorePropertiesFile.exists()) { + signingConfig signingConfigs.release + } else { + signingConfig signingConfigs.debug + } } } } @@ -63,7 +64,3 @@ android { flutter { source '../..' } - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" -} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml index 25f3976..f880684 100644 --- a/android/app/src/debug/AndroidManifest.xml +++ b/android/app/src/debug/AndroidManifest.xml @@ -1,5 +1,4 @@ - + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 2b11106..5978d48 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,5 +1,6 @@ - + + + + diff --git a/android/build.gradle b/android/build.gradle index 4256f91..bef1918 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -1,16 +1,3 @@ -buildscript { - ext.kotlin_version = '1.6.10' - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:4.1.0' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - allprojects { repositories { google() @@ -18,14 +5,15 @@ allprojects { } } -rootProject.buildDir = '../build' +def newBuildDir = rootProject.layout.buildDirectory.dir("../../build").get() +rootProject.layout.buildDirectory.value(newBuildDir) + subprojects { - project.buildDir = "${rootProject.buildDir}/${project.name}" -} -subprojects { - project.evaluationDependsOn(':app') + def newSubprojectBuildDir = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) + project.evaluationDependsOn(":app") } -task clean(type: Delete) { - delete rootProject.buildDir +tasks.register("clean", Delete) { + delete rootProject.layout.buildDirectory } diff --git a/android/gradle.properties b/android/gradle.properties index 94adc3a..58a98f0 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -1,3 +1,6 @@ -org.gradle.jvmargs=-Xmx1536M +org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G android.useAndroidX=true -android.enableJetifier=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index bc6a58a..2d428bf 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -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-6.7-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip diff --git a/android/key.properties.example b/android/key.properties.example new file mode 100644 index 0000000..3e142ce --- /dev/null +++ b/android/key.properties.example @@ -0,0 +1,12 @@ +# Plantilla para configuración de firma de producción (Google Play Store) +# Copia este archivo como 'android/key.properties' y completa con tus datos reales: +# +# Para generar un keystore nuevo de producción ejecuta: +# keytool -genkey -v -keystore android/app/upload-keystore.jks -keyalg RSA -keysize 2048 -validity 10000 -alias upload +# +# Guarda el archivo 'key.properties' fuera de control de versiones (ya incluido en .gitignore) + +keyAlias=upload +keyPassword=TU_PASSWORD_DE_ALIAS +storeFile=app/upload-keystore.jks +storePassword=TU_PASSWORD_DEL_KEYSTORE diff --git a/android/settings.gradle b/android/settings.gradle index 44e62bc..643d520 100644 --- a/android/settings.gradle +++ b/android/settings.gradle @@ -1,11 +1,25 @@ -include ':app' +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 "9.0.1" apply false + id "org.jetbrains.kotlin.android" version "2.3.20" apply false +} + +include ":app" diff --git a/assets/icon/icon.png b/assets/icon/icon.png index 2305b4a..1bde671 100644 Binary files a/assets/icon/icon.png and b/assets/icon/icon.png differ diff --git a/assets/icon/icon.svg b/assets/icon/icon.svg index d673c16..220af5a 100644 --- a/assets/icon/icon.svg +++ b/assets/icon/icon.svg @@ -1,30 +1,81 @@ - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 060169d..bca128c 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -294,7 +294,8 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.pedidosapp.pedidosApp; + /* Bundle ID homologado con com.sigmac.agenteventas */ + PRODUCT_BUNDLE_IDENTIFIER = com.sigmac.agenteventas; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; @@ -422,7 +423,8 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.pedidosapp.pedidosApp; + /* Bundle ID homologado con com.sigmac.agenteventas */ + PRODUCT_BUNDLE_IDENTIFIER = com.sigmac.agenteventas; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -444,7 +446,8 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.pedidosapp.pedidosApp; + /* Bundle ID homologado con com.sigmac.agenteventas */ + PRODUCT_BUNDLE_IDENTIFIER = com.sigmac.agenteventas; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; @@ -478,4 +481,4 @@ /* End XCConfigurationList section */ }; rootObject = 97C146E61CF9000F007C117D /* Project object */; -} +} \ No newline at end of file diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png index dc9ada4..89a1e32 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png index 28c6bf0..01c3e7a 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png index 2ccbfd9..e488ded 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png index f091b6b..9cabf3d 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png index 4cde121..d9c4547 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png index d0ef06e..38e2217 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png index dcdc230..00f4f66 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png index 2ccbfd9..e488ded 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png index c8f9ed8..e434d9b 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png index a6d6b86..b9f0c71 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png index a6d6b86..dc1db68 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png index 75b2d16..f35b466 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png index c4df70d..9b61632 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png index 6a84f41..eac6e21 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png index d0e1f58..b51ae45 100644 Binary files a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 64cdbc1..406ceab 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -43,5 +43,8 @@ UIViewControllerBasedStatusBarAppearance + + NSCameraUsageDescription + Agente Ventas requiere acceso a la cámara para escanear códigos de barras de los productos del catálogo. diff --git a/lib/data/mock_data.dart b/lib/data/mock_data.dart index d2ad9d1..0f0ebc1 100644 --- a/lib/data/mock_data.dart +++ b/lib/data/mock_data.dart @@ -17,6 +17,16 @@ class MockData { avatarInitials: 'RV', ); + // Vendedor de demostración para evaluación de tiendas de aplicaciones (Play Store / App Store) + static const demoVendedor = Vendedor( + id: 'demo_user', + nombre: 'Revisor Tienda (Demo)', + email: 'demo@empresa.com', + telefono: '+593 99 0000000', + zona: 'Zona Demostración', + avatarInitials: 'DM', + ); + // ── Clientes ────────────────────────────────────────────────── static final clientes = [ const Cliente( diff --git a/lib/database/database_helper.dart b/lib/database/database_helper.dart index 1bd2460..1b88a0d 100644 --- a/lib/database/database_helper.dart +++ b/lib/database/database_helper.dart @@ -182,13 +182,16 @@ class DatabaseHelper { Future?> loginUsuario(String email, String password) async { final db = await database; - // Acepta hash SHA-256 o texto plano (compatibilidad con seeder viejo) + // Soporte para autenticación flexible (email o id/usuario) insensible a mayúsculas + final cleanEmail = email.trim().toLowerCase(); final hash = _sha256(password); var rows = await db.query('usuarios', - where: 'email = ? AND password = ?', whereArgs: [email, hash]); + where: '(LOWER(email) = ? OR LOWER(id) = ?) AND password = ?', + whereArgs: [cleanEmail, cleanEmail, hash]); if (rows.isEmpty) { rows = await db.query('usuarios', - where: 'email = ? AND password = ?', whereArgs: [email, password]); + where: '(LOWER(email) = ? OR LOWER(id) = ?) AND password = ?', + whereArgs: [cleanEmail, cleanEmail, password]); } return rows.isEmpty ? null : rows.first; } @@ -199,6 +202,17 @@ class DatabaseHelper { return rows.isEmpty ? null : Vendedor.fromMap(rows.first); } + // Actualiza el número telefónico del usuario en SQLite local (para alertas de WhatsApp) + Future updateUsuarioTelefono(String usuarioId, String telefono) async { + final db = await database; + await db.update( + 'usuarios', + {'telefono': telefono}, + where: 'id = ? OR email = ?', + whereArgs: [usuarioId, usuarioId], + ); + } + // ── Clientes ──────────────────────────────────────────────── Future> getClientes() async { diff --git a/lib/database/db_seeder.dart b/lib/database/db_seeder.dart index 84e5779..bb81e36 100644 --- a/lib/database/db_seeder.dart +++ b/lib/database/db_seeder.dart @@ -9,6 +9,9 @@ class DbSeeder { // Guardar usuario admin await _db.insertUsuario(MockData.vendedor, 'Microbot%'); + // Registrar usuario demo para revisión en tiendas (acceso offline garantizado) + await _db.insertUsuario(MockData.demoVendedor, '123456'); + // Clientes for (final c in MockData.clientes) { await _db.insertCliente(c); diff --git a/lib/main.dart b/lib/main.dart index 0c61695..e59165a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -5,11 +5,15 @@ import 'package:provider/provider.dart'; import 'app.dart'; import 'providers/app_provider.dart'; import 'services/notification_service.dart'; +// Integración con la Bitácora Centralizada de Errores (API-SIGMA-WEBCONTROL) +import 'services/bitacora_service.dart'; final _navigatorKey = GlobalKey(); void main() async { WidgetsFlutterBinding.ensureInitialized(); + // Activa captura automática de excepciones para telemetría de errores en producción + BitacoraService.inicializar(); await initializeDateFormatting('es', null); SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( statusBarColor: Colors.transparent, diff --git a/lib/models/moneda.dart b/lib/models/moneda.dart new file mode 100644 index 0000000..aeca109 --- /dev/null +++ b/lib/models/moneda.dart @@ -0,0 +1,34 @@ +class Moneda { + final String codigo; + final String nombre; + final String simbolo; + final String locale; + + const Moneda({ + required this.codigo, + required this.nombre, + required this.simbolo, + required this.locale, + }); + + static const disponibles = [ + Moneda(codigo: 'USD', nombre: 'Dólar estadounidense', simbolo: '\$', locale: 'en_US'), + Moneda(codigo: 'EUR', nombre: 'Euro', simbolo: '€', locale: 'es_ES'), + Moneda(codigo: 'PEN', nombre: 'Sol peruano', simbolo: 'S/', locale: 'es_PE'), + Moneda(codigo: 'COP', nombre: 'Peso colombiano', simbolo: '\$', locale: 'es_CO'), + Moneda(codigo: 'MXN', nombre: 'Peso mexicano', simbolo: '\$', locale: 'es_MX'), + Moneda(codigo: 'ARS', nombre: 'Peso argentino', simbolo: '\$', locale: 'es_AR'), + Moneda(codigo: 'CLP', nombre: 'Peso chileno', simbolo: '\$', locale: 'es_CL'), + Moneda(codigo: 'VES', nombre: 'Bolívar venezolano', simbolo: 'Bs.', locale: 'es_VE'), + ]; + + static const porDefecto = + Moneda(codigo: 'USD', nombre: 'Dólar estadounidense', simbolo: '\$', locale: 'en_US'); + + static Moneda porCodigo(String codigo) { + return disponibles.firstWhere( + (m) => m.codigo == codigo, + orElse: () => porDefecto, + ); + } +} diff --git a/lib/models/vendedor.dart b/lib/models/vendedor.dart index 6529e61..507dd34 100644 --- a/lib/models/vendedor.dart +++ b/lib/models/vendedor.dart @@ -32,4 +32,23 @@ class Vendedor { zona: m['zona'] as String? ?? '', avatarInitials: m['avatar_initials'] as String? ?? '', ); + + // Permite crear una copia modificada del vendedor (ej. al actualizar teléfono de WhatsApp) + Vendedor copyWith({ + String? id, + String? nombre, + String? email, + String? telefono, + String? zona, + String? avatarInitials, + }) { + return Vendedor( + id: id ?? this.id, + nombre: nombre ?? this.nombre, + email: email ?? this.email, + telefono: telefono ?? this.telefono, + zona: zona ?? this.zona, + avatarInitials: avatarInitials ?? this.avatarInitials, + ); + } } diff --git a/lib/providers/app_provider.dart b/lib/providers/app_provider.dart index f953d64..b16a421 100644 --- a/lib/providers/app_provider.dart +++ b/lib/providers/app_provider.dart @@ -1,4 +1,5 @@ import 'package:flutter/foundation.dart'; +import 'package:intl/intl.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../database/database_helper.dart'; import '../database/db_seeder.dart'; @@ -9,15 +10,41 @@ import '../models/pedido.dart'; import '../models/item_pedido.dart'; import '../models/ruta.dart'; import '../models/parada_ruta.dart'; +import '../models/moneda.dart'; import '../services/notification_service.dart'; import '../services/auth_service.dart'; import '../services/cloud_sync_service.dart'; +// Integración con el Gateway Sigma-Robot para envío de alertas operativas por WhatsApp +import '../services/whatsapp_service.dart'; +// Integración con la Bitácora Centralizada de Errores para reintento de cola offline +import '../services/bitacora_service.dart'; + +/// Resumen de resultado para procesos de sincronización manual y automática +class SyncSummary { + final bool ok; + final int pedidosSubidos; + final int pedidosFallidos; + final int itemsSynced; + final int clientesSynced; + final String mensaje; + + const SyncSummary({ + required this.ok, + this.pedidosSubidos = 0, + this.pedidosFallidos = 0, + this.itemsSynced = 0, + this.clientesSynced = 0, + required this.mensaje, + }); +} class AppProvider extends ChangeNotifier { final _db = DatabaseHelper(); final NotificationService? _notifService; - AppProvider({NotificationService? notifService}) : _notifService = notifService; + AppProvider({NotificationService? notifService}) : _notifService = notifService { + _loadMonedaPref(); + } // ── Estado de sesión ───────────────────────────────────────── bool _isLoggedIn = false; @@ -35,6 +62,11 @@ class AppProvider extends ChangeNotifier { // Contadores de última sincronización int _itemsSynced = 0; int _clientesSynced = 0; + // Estado reactivo de sincronización manual / automática + bool _syncing = false; + DateTime? _ultimoSync; + String? _ultimoSyncError; + Ruta? _ruta; List _pedidos = []; List _productos = []; @@ -49,6 +81,9 @@ class AppProvider extends ChangeNotifier { final List _carrito = []; String _notasPedido = ''; + // ── Preferencia de moneda ───────────────────────────────────── + Moneda _moneda = Moneda.porDefecto; + // ── Getters ────────────────────────────────────────────────── bool get isLoggedIn => _isLoggedIn; bool get loading => _loading; @@ -59,6 +94,10 @@ class AppProvider extends ChangeNotifier { String get dbTenant => _dbTenant; int get itemsSynced => _itemsSynced; int get clientesSynced => _clientesSynced; + // Getters para el estado visual de sincronización en tiempo real + bool get syncing => _syncing; + DateTime? get ultimoSync => _ultimoSync; + String? get ultimoSyncError => _ultimoSyncError; int get pedidosPendientesSync => _pedidos.where((p) => p.syncEstado == 'PENDIENTE').length; @@ -76,6 +115,10 @@ class AppProvider extends ChangeNotifier { double get totalCarrito => _carrito.fold(0, (s, i) => s + i.subtotal); int get cantidadCarrito => _carrito.fold(0, (s, i) => s + i.cantidad); + Moneda get moneda => _moneda; + NumberFormat get currencyFormat => + NumberFormat.currency(locale: _moneda.locale, symbol: _moneda.simbolo, decimalDigits: 2); + List get clientesSinParada { final ids = _ruta?.paradas.map((p) => p.cliente.id).toSet() ?? {}; return _clientes.where((c) => !ids.contains(c.id)).toList(); @@ -94,6 +137,28 @@ class AppProvider extends ChangeNotifier { p.estado != EstadoPedido.cancelado; }).fold(0, (s, p) => s + p.total); + // ── Preferencia de moneda ───────────────────────────────────── + + Future _loadMonedaPref() async { + try { + final prefs = await SharedPreferences.getInstance(); + final codigo = prefs.getString('pref_moneda_codigo'); + if (codigo != null) { + _moneda = Moneda.porCodigo(codigo); + notifyListeners(); + } + } catch (e) { + debugPrint('[Moneda] error cargando preferencia: $e'); + } + } + + Future setMoneda(Moneda moneda) async { + _moneda = moneda; + notifyListeners(); + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('pref_moneda_codigo', moneda.codigo); + } + // ── Auto-login ─────────────────────────────────────────────── /// Intenta restaurar la sesión guardada al abrir la app. @@ -195,12 +260,19 @@ class AppProvider extends ChangeNotifier { _modoOnline = true; _vendedor = _vendedorFromSession(session, email.trim()); + // Asegurar que la base de datos local contenga datos de prueba para la revisión de tienda + final isDemo = session.token == 'demo_jwt_token_store_review'; final seeded = await _db.isSeeded(); - if (!seeded) await DbSeeder(_db).seed(); + if (!seeded || isDemo) await DbSeeder(_db).seed(); + + // Si es la sesión demo para evaluadores de la tienda, evitar llamadas a APIs externas + // para garantizar que la app cargue de inmediato con todos los datos sin depender de red + if (!isDemo) { + await _syncCloudData(); + await _uploadPendingPedidos(); + } - await _syncCloudData(); await _loadAllData(); - await _uploadPendingPedidos(); _loading = false; _isLoggedIn = true; notifyListeners(); @@ -246,7 +318,18 @@ class AppProvider extends ChangeNotifier { final seeded = await _db.isSeeded(); if (!seeded) await DbSeeder(_db).seed(); - final row = await _db.loginUsuario(usuario.trim(), password); + var row = await _db.loginUsuario(usuario.trim(), password); + if (row == null) { + // En caso de que la base de datos local haya sido creada antes de incorporar el usuario demo, + // forzamos el re-sembrado para asegurar que el evaluador de tienda siempre pueda acceder + final cleanUser = usuario.trim().toLowerCase(); + if ((cleanUser == 'demo@empresa.com' || cleanUser == 'demo' || cleanUser == 'demo@telcotronics.com') && + password == '123456') { + await DbSeeder(_db).seed(); + row = await _db.loginUsuario(usuario.trim(), password); + } + } + if (row == null) { _loginError = 'Usuario o contraseña incorrectos'; _loading = false; @@ -569,6 +652,28 @@ class AppProvider extends ChangeNotifier { } _notifService?.notifPedidoConfirmado(id, _clienteSeleccionado!.nombre); + + // Envío asíncrono en segundo plano de alerta operativa vía Sigma-Robot Gateway + // si el vendedor tiene configurado y vinculado un número de WhatsApp + if (_vendedor != null && _vendedor!.telefono.isNotEmpty) { + final tel = _vendedor!.telefono; + final clienteNombre = _clienteSeleccionado!.nombre; + final vendedorNombre = _vendedor!.nombre; + WhatsAppService.enviarAlertaPedido( + telefono: tel, + pedido: pedido, + nombreCliente: clienteNombre, + nombreVendedor: vendedorNombre, + ).catchError((err) { + debugPrint('[WhatsApp Alert] Error al despachar alerta de pedido: $err'); + return const WhatsAppEnvioResult( + ok: false, + error: 'Error de red al despachar alerta', + numeroDestino: '', + ); + }); + } + limpiarCarrito(); notifyListeners(); return pedido; @@ -587,6 +692,132 @@ class AppProvider extends ChangeNotifier { notifyListeners(); } + // ── Alertas de WhatsApp y Teléfono de Vendedor ─────────────── + // Actualiza el número telefónico del perfil en memoria, SQLite local y SharedPreferences + Future actualizarTelefonoVendedor(String nuevoTelefono) async { + if (_vendedor == null) return; + _vendedor = _vendedor!.copyWith(telefono: nuevoTelefono); + await _db.updateUsuarioTelefono(_vendedor!.id, nuevoTelefono); + + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('auth_telefono', nuevoTelefono); + } catch (_) {} + + notifyListeners(); + } + + // ── Sincronización Manual y Reintento Cloud ────────────────── + /// Sincronización bidireccional manual: + /// 1. Sube al cloud los pedidos locales pendientes de sincronizar + /// 2. Descarga ítems y clientes actualizados desde API-SIGMA-CLOUD + /// 3. Reintenta eventos pendientes en la bitácora centralizada de errores + /// 4. Recarga SQLite local y notifica a la UI para refrescar badges e indicadores + Future sincronizarManual() async { + if (_syncing) { + return const SyncSummary(ok: false, mensaje: 'Sincronización en curso...'); + } + + _syncing = true; + _ultimoSyncError = null; + notifyListeners(); + + int subidos = 0; + int fallidos = 0; + + try { + final isDemo = _jwt == 'demo_jwt_token_store_review'; + + if (_modoOnline && _apiKey.isNotEmpty && !isDemo) { + // 1. Subir pedidos pendientes o con error previo + final pendientes = _pedidos + .where((p) => p.syncEstado == 'PENDIENTE' || p.syncEstado == 'ERROR') + .toList(); + + for (final p in pendientes) { + try { + await CloudSyncService.uploadPedido(p, _vendedor?.id ?? ''); + await _db.updateSyncEstadoPedido(p.id, 'SINCRONIZADO'); + p.syncEstado = 'SINCRONIZADO'; + subidos++; + } catch (e) { + fallidos++; + await _db.updateSyncEstadoPedido(p.id, 'ERROR'); + p.syncEstado = 'ERROR'; + } + } + + // 2. Descargar catálogo y clientes actualizados + await _syncCloudData(); + + // 3. Reintentar cola de bitácora de errores si quedó algo pendiente + await BitacoraService.reintentarColaPendiente(); + } + + // Recarga de datos locales + await _loadAllData(); + _ultimoSync = DateTime.now(); + _syncing = false; + notifyListeners(); + + String msg; + if (isDemo) { + msg = 'Modo Demo: Datos locales de prueba actualizados.'; + } else if (!_modoOnline) { + msg = 'Modo local: Datos de SQLite recargados.'; + } else if (fallidos > 0) { + msg = 'Sincronización parcial: $subidos pedidos subidos, $fallidos pendientes.'; + } else if (subidos > 0) { + msg = '¡Éxito! $subidos pedido${subidos == 1 ? '' : 's'} subido${subidos == 1 ? '' : 's'} a la nube.'; + } else { + msg = 'Nube al día: Catálogo y clientes sincronizados.'; + } + + return SyncSummary( + ok: fallidos == 0, + pedidosSubidos: subidos, + pedidosFallidos: fallidos, + itemsSynced: _itemsSynced, + clientesSynced: _clientesSynced, + mensaje: msg, + ); + } catch (e) { + _ultimoSyncError = e.toString(); + _syncing = false; + notifyListeners(); + return SyncSummary( + ok: false, + pedidosSubidos: subidos, + pedidosFallidos: fallidos, + mensaje: 'Error de sincronización: $e', + ); + } + } + + /// Reintenta subir de forma individual un pedido específico + Future reintentarSubidaPedido(String pedidoId) async { + final idx = _pedidos.indexWhere((p) => p.id == pedidoId); + if (idx == -1) return false; + final pedido = _pedidos[idx]; + + if (!_modoOnline || _apiKey.isEmpty) { + return false; + } + + try { + await CloudSyncService.uploadPedido(pedido, _vendedor?.id ?? ''); + await _db.updateSyncEstadoPedido(pedido.id, 'SINCRONIZADO'); + pedido.syncEstado = 'SINCRONIZADO'; + notifyListeners(); + return true; + } catch (e) { + await _db.updateSyncEstadoPedido(pedido.id, 'ERROR'); + pedido.syncEstado = 'ERROR'; + notifyListeners(); + return false; + } + } + // ── Helpers ────────────────────────────────────────────────── String _horaDefault() { diff --git a/lib/recursos/logo_pedidos.svg b/lib/recursos/logo_pedidos.svg new file mode 100644 index 0000000..220af5a --- /dev/null +++ b/lib/recursos/logo_pedidos.svg @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + diff --git a/lib/screens/catalogo/catalogo_screen.dart b/lib/screens/catalogo/catalogo_screen.dart index 70a56e2..e42b5a2 100644 --- a/lib/screens/catalogo/catalogo_screen.dart +++ b/lib/screens/catalogo/catalogo_screen.dart @@ -29,7 +29,7 @@ class _CatalogoScreenState extends State { @override Widget build(BuildContext context) { final provider = context.watch(); - final fmt = NumberFormat.currency(locale: 'en_US', symbol: '\$', decimalDigits: 2); + final fmt = provider.currencyFormat; final filtrados = provider.productos.where((p) { final matchCat = _categoriaSeleccionada == 'Todos' || p.categoria == _categoriaSeleccionada; diff --git a/lib/screens/clientes/cliente_selector_screen.dart b/lib/screens/clientes/cliente_selector_screen.dart index f3de247..5594b3a 100644 --- a/lib/screens/clientes/cliente_selector_screen.dart +++ b/lib/screens/clientes/cliente_selector_screen.dart @@ -38,8 +38,8 @@ class _ClienteSelectorScreenState extends State { @override void initState() { super.initState(); - // Autofocus al abrir - WidgetsBinding.instance!.addPostFrameCallback((_) => _focusNode.requestFocus()); + // Autofocus al abrir (WidgetsBinding.instance no nulo en Flutter 3) + WidgetsBinding.instance.addPostFrameCallback((_) => _focusNode.requestFocus()); } @override diff --git a/lib/screens/firma/firma_screen.dart b/lib/screens/firma/firma_screen.dart index bac16f5..09f2141 100644 --- a/lib/screens/firma/firma_screen.dart +++ b/lib/screens/firma/firma_screen.dart @@ -17,7 +17,7 @@ class _FirmaScreenState extends State { bool _firmado = false; bool _guardando = false; - final _fmt = NumberFormat.currency(locale: 'en_US', symbol: '\$', decimalDigits: 2); + NumberFormat get _fmt => context.watch().currencyFormat; @override Widget build(BuildContext context) { diff --git a/lib/screens/home/home_screen.dart b/lib/screens/home/home_screen.dart index 36119a5..ef42b6e 100644 --- a/lib/screens/home/home_screen.dart +++ b/lib/screens/home/home_screen.dart @@ -7,6 +7,8 @@ import '../../theme/app_theme.dart'; import '../../widgets/stat_card.dart'; import '../../models/pedido.dart'; import '../notificaciones/notificaciones_screen.dart'; +// Botón reactivo de sincronización y estado cloud en AppBar +import '../../widgets/sync_status_button.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({Key? key}) : super(key: key); @@ -15,12 +17,24 @@ class HomeScreen extends StatelessWidget { Widget build(BuildContext context) { final provider = context.watch(); final notifService = context.watch(); - final fmt = NumberFormat.currency(locale: 'en_US', symbol: '\$', decimalDigits: 2); + final fmt = provider.currencyFormat; return Scaffold( backgroundColor: AppTheme.bgColor, body: RefreshIndicator( - onRefresh: () async => await Future.delayed(const Duration(milliseconds: 600)), + // Sincronización manual reactiva al deslizar hacia abajo + onRefresh: () async { + final res = await provider.sincronizarManual(); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(res.mensaje), + duration: const Duration(seconds: 3), + backgroundColor: res.ok ? const Color(0xFF10B981) : const Color(0xFFF59E0B), + ), + ); + } + }, child: CustomScrollView( slivers: [ _buildSliverAppBar(context, provider, notifService), @@ -62,6 +76,8 @@ class HomeScreen extends StatelessWidget { pinned: true, backgroundColor: AppTheme.primaryColor, actions: [ + // Indicador y botón interactivo de sincronización con la nube + const SyncStatusButton(), Stack( alignment: Alignment.center, children: [ @@ -524,8 +540,8 @@ class HomeScreen extends StatelessWidget { ElevatedButton( onPressed: () => notifService.dispararDemo(), style: ElevatedButton.styleFrom( - primary: Colors.white, - onPrimary: const Color(0xFF7C3AED), + backgroundColor: Colors.white, + foregroundColor: const Color(0xFF7C3AED), padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), elevation: 0, diff --git a/lib/screens/login/login_screen.dart b/lib/screens/login/login_screen.dart index 64f9a49..cd711c3 100644 --- a/lib/screens/login/login_screen.dart +++ b/lib/screens/login/login_screen.dart @@ -253,7 +253,10 @@ class _LoginScreenState extends State ], const SizedBox(height: 16), _buildButton(provider.loading), - const SizedBox(height: 12), + const SizedBox(height: 8), + // Acceso rápido para evaluador de Google Play / App Store + _buildDemoAccessButton(), + const SizedBox(height: 10), _buildRegistroLinks(), const SizedBox(height: 12), Center( @@ -462,7 +465,7 @@ class _LoginScreenState extends State label: const Text('Cuenta local', style: TextStyle(fontSize: 12)), style: OutlinedButton.styleFrom( - primary: _kTextMuted, + foregroundColor: _kTextMuted, side: const BorderSide(color: _kBorder), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10)), @@ -479,7 +482,7 @@ class _LoginScreenState extends State label: const Text('Nueva Cloud', style: TextStyle(fontSize: 12)), style: OutlinedButton.styleFrom( - primary: _kAccent, + foregroundColor: _kAccent, side: const BorderSide(color: _kAccent), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10)), @@ -523,8 +526,8 @@ class _LoginScreenState extends State child: ElevatedButton( onPressed: loading ? null : _ingresar, style: ElevatedButton.styleFrom( - primary: Colors.transparent, - onPrimary: Colors.white, + backgroundColor: Colors.transparent, + foregroundColor: Colors.white, shadowColor: Colors.transparent, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12)), @@ -548,4 +551,31 @@ class _LoginScreenState extends State ), ); } + + // ── Botón de acceso de evaluación / Demo para tiendas ─────────────── + // Facilita la revisión técnica de Google Play Store y Apple App Store + // autocompletando la cuenta demo preconfigurada (demo@empresa.com / 123456) + Widget _buildDemoAccessButton() { + return Center( + child: TextButton.icon( + onPressed: () { + setState(() { + _emailCtrl.text = 'demo@empresa.com'; + _passCtrl.text = '123456'; + }); + _ingresar(); + }, + icon: const Icon(Icons.verified_user_outlined, size: 15, color: _kAccent), + label: const Text( + 'Acceso Demo (Revisión de Tienda)', + style: TextStyle( + color: _kAccent, + fontSize: 12, + fontWeight: FontWeight.w600, + decoration: TextDecoration.underline, + ), + ), + ), + ); + } } diff --git a/lib/screens/login/registro_cloud_screen.dart b/lib/screens/login/registro_cloud_screen.dart index 161c9c8..a2b449b 100644 --- a/lib/screens/login/registro_cloud_screen.dart +++ b/lib/screens/login/registro_cloud_screen.dart @@ -797,8 +797,8 @@ class _RegistroCloudScreenState extends State { child: ElevatedButton( onPressed: onPressed, style: ElevatedButton.styleFrom( - primary: Colors.transparent, - onPrimary: Colors.white, + backgroundColor: Colors.transparent, + foregroundColor: Colors.white, shadowColor: Colors.transparent, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12)), diff --git a/lib/screens/login/registro_screen.dart b/lib/screens/login/registro_screen.dart index e9deabe..1bb2b24 100644 --- a/lib/screens/login/registro_screen.dart +++ b/lib/screens/login/registro_screen.dart @@ -336,8 +336,8 @@ class _RegistroScreenState extends State { child: ElevatedButton( onPressed: _loading ? null : _crear, style: ElevatedButton.styleFrom( - primary: Colors.transparent, - onPrimary: Colors.white, + backgroundColor: Colors.transparent, + foregroundColor: Colors.white, shadowColor: Colors.transparent, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12)), diff --git a/lib/screens/pedidos/pedido_detail_screen.dart b/lib/screens/pedidos/pedido_detail_screen.dart index f5a0c31..b846111 100644 --- a/lib/screens/pedidos/pedido_detail_screen.dart +++ b/lib/screens/pedidos/pedido_detail_screen.dart @@ -13,7 +13,7 @@ class PedidoDetailScreen extends StatelessWidget { @override Widget build(BuildContext context) { final provider = context.read(); - final fmt = NumberFormat.currency(locale: 'en_US', symbol: '\$', decimalDigits: 2); + final fmt = provider.currencyFormat; final estadoColor = AppTheme.estadoColor(pedido.estado.label); final dateStr = DateFormat('d \'de\' MMMM yyyy, HH:mm', 'es').format(pedido.fecha); @@ -45,6 +45,9 @@ class PedidoDetailScreen extends StatelessWidget { // Header card _buildHeaderCard(estadoColor, dateStr), const SizedBox(height: 14), + // Tarjeta de estado de sincronización hacia la nube central + _buildSyncCard(context, provider), + const SizedBox(height: 14), // Cliente _buildClienteCard(), const SizedBox(height: 14), @@ -115,6 +118,109 @@ class PedidoDetailScreen extends StatelessWidget { ); } + /// Construye la tarjeta informativa de estado de transmisión con la nube SIGMA + Widget _buildSyncCard(BuildContext context, AppProvider provider) { + final syncEstado = pedido.syncEstado; + final isSincronizado = syncEstado == 'SINCRONIZADO'; + final isError = syncEstado == 'ERROR'; + + final bg = isSincronizado + ? const Color(0xFF10B981).withOpacity(0.08) + : isError + ? const Color(0xFFEF4444).withOpacity(0.08) + : const Color(0xFFF59E0B).withOpacity(0.08); + + final border = isSincronizado + ? const Color(0xFF10B981).withOpacity(0.25) + : isError + ? const Color(0xFFEF4444).withOpacity(0.25) + : const Color(0xFFF59E0B).withOpacity(0.25); + + final iconColor = isSincronizado + ? const Color(0xFF10B981) + : isError + ? const Color(0xFFEF4444) + : const Color(0xFFD97706); + + final icon = isSincronizado + ? Icons.cloud_done_rounded + : isError + ? Icons.cloud_off_rounded + : Icons.cloud_upload_outlined; + + final title = isSincronizado + ? 'Pedido sincronizado en la nube' + : isError + ? 'Error al subir a la nube' + : 'Almacenado localmente (Offline)'; + + final desc = isSincronizado + ? 'Transmitido correctamente a API-SIGMA-CLOUD y registrado en el ERP.' + : isError + ? 'Falló la conexión o la API central rechazó la carga.' + : 'Se sincronizará automáticamente cuando el dispositivo tenga conexión.'; + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: border), + ), + child: Row( + children: [ + Icon(icon, color: iconColor, size: 26), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: iconColor), + ), + const SizedBox(height: 2), + Text( + desc, + style: const TextStyle(fontSize: 11, color: Color(0xFF475569)), + ), + ], + ), + ), + if (!isSincronizado && provider.modoOnline) ...[ + const SizedBox(width: 8), + TextButton( + style: TextButton.styleFrom( + foregroundColor: iconColor, + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + side: BorderSide(color: iconColor.withOpacity(0.4)), + ), + ), + onPressed: () async { + final ok = await provider.reintentarSubidaPedido(pedido.id); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + ok + ? '¡Pedido ${pedido.id} subido con éxito a la nube!' + : 'No se pudo subir el pedido. Revisa tu conexión a internet.', + ), + backgroundColor: ok ? const Color(0xFF10B981) : const Color(0xFFEF4444), + ), + ); + } + }, + child: const Text('Subir', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12)), + ), + ], + ], + ), + ); + } + Widget _buildClienteCard() { return _sectionCard( title: 'Cliente', diff --git a/lib/screens/pedidos/pedido_form_screen.dart b/lib/screens/pedidos/pedido_form_screen.dart index 306a4a3..b0bd8a7 100644 --- a/lib/screens/pedidos/pedido_form_screen.dart +++ b/lib/screens/pedidos/pedido_form_screen.dart @@ -21,7 +21,7 @@ class _PedidoFormScreenState extends State { String _productoQuery = ''; bool _showSearch = false; - final _fmt = NumberFormat.currency(locale: 'en_US', symbol: '\$', decimalDigits: 2); + NumberFormat get _fmt => context.watch().currencyFormat; @override void initState() { @@ -349,7 +349,7 @@ class _PedidoFormScreenState extends State { icon: const Icon(Icons.delete_outline, size: 16), label: const Text('Limpiar', style: TextStyle(fontSize: 12)), onPressed: provider.limpiarCarrito, - style: TextButton.styleFrom(primary: AppTheme.dangerColor), + style: TextButton.styleFrom(foregroundColor: AppTheme.dangerColor), ), ], ), diff --git a/lib/screens/pedidos/pedidos_screen.dart b/lib/screens/pedidos/pedidos_screen.dart index 6269c0d..500b74e 100644 --- a/lib/screens/pedidos/pedidos_screen.dart +++ b/lib/screens/pedidos/pedidos_screen.dart @@ -6,6 +6,8 @@ import '../../theme/app_theme.dart'; import '../../models/pedido.dart'; import 'pedido_form_screen.dart'; import 'pedido_detail_screen.dart'; +// Botón interactivo de sincronización para AppBar +import '../../widgets/sync_status_button.dart'; class PedidosScreen extends StatefulWidget { const PedidosScreen({Key? key}) : super(key: key); @@ -16,7 +18,7 @@ class PedidosScreen extends StatefulWidget { class _PedidosScreenState extends State with SingleTickerProviderStateMixin { late TabController _tab; - final _fmt = NumberFormat.currency(locale: 'en_US', symbol: '\$', decimalDigits: 2); + NumberFormat get _fmt => context.watch().currencyFormat; @override void initState() { @@ -39,6 +41,8 @@ class _PedidosScreenState extends State with SingleTickerProvider appBar: AppBar( title: const Text('Pedidos', style: TextStyle(fontWeight: FontWeight.bold)), actions: [ + // Botón reactivo de sincronización para comprobar y forzar subidas + const SyncStatusButton(), IconButton(icon: const Icon(Icons.search), onPressed: () {}), IconButton(icon: const Icon(Icons.filter_list), onPressed: () {}), ], @@ -97,23 +101,48 @@ class _PedidosScreenState extends State with SingleTickerProvider } Widget _buildList(BuildContext context, List pedidos, AppProvider provider) { - if (pedidos.isEmpty) { - return Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Icons.receipt_long_outlined, size: 64, color: Colors.grey.shade300), - const SizedBox(height: 12), - const Text('No hay pedidos', style: TextStyle(color: AppTheme.textSecondary, fontSize: 15)), - ], - ), - ); - } - - return ListView.builder( - padding: const EdgeInsets.fromLTRB(16, 12, 16, 80), - itemCount: pedidos.length, - itemBuilder: (context, i) => _buildPedidoCard(context, pedidos[i], provider), + // Soportar pull-to-refresh en lista de pedidos para sincronización en tiempo real + return RefreshIndicator( + onRefresh: () async { + final res = await provider.sincronizarManual(); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(res.mensaje), + duration: const Duration(seconds: 3), + backgroundColor: res.ok ? const Color(0xFF10B981) : const Color(0xFFF59E0B), + ), + ); + } + }, + child: pedidos.isEmpty + ? ListView( + physics: const AlwaysScrollableScrollPhysics(), + children: [ + SizedBox(height: MediaQuery.of(context).size.height * 0.25), + Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.receipt_long_outlined, size: 64, color: Colors.grey.shade300), + const SizedBox(height: 12), + const Text('No hay pedidos', style: TextStyle(color: AppTheme.textSecondary, fontSize: 15)), + const SizedBox(height: 6), + Text( + 'Desliza hacia abajo para actualizar', + style: TextStyle(color: Colors.grey.shade400, fontSize: 12), + ), + ], + ), + ), + ], + ) + : ListView.builder( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.fromLTRB(16, 12, 16, 80), + itemCount: pedidos.length, + itemBuilder: (context, i) => _buildPedidoCard(context, pedidos[i], provider), + ), ); } @@ -198,16 +227,24 @@ class _PedidosScreenState extends State with SingleTickerProvider ], ), ), - Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), - decoration: BoxDecoration( - color: estadoColor.withOpacity(0.12), - borderRadius: BorderRadius.circular(8), - ), - child: Text( - pedido.estado.label, - style: TextStyle(fontSize: 11, color: estadoColor, fontWeight: FontWeight.w700), - ), + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: estadoColor.withOpacity(0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + pedido.estado.label, + style: TextStyle(fontSize: 11, color: estadoColor, fontWeight: FontWeight.w700), + ), + ), + const SizedBox(height: 4), + // Badge visual del estado de sincronización hacia API-SIGMA-CLOUD + _buildSyncBadge(pedido.syncEstado), + ], ), ], ), @@ -276,4 +313,69 @@ class _PedidosScreenState extends State with SingleTickerProvider ), ); } + + /// Construye el indicador visual de sincronización para cada tarjeta de pedido + Widget _buildSyncBadge(String syncEstado) { + if (syncEstado == 'SINCRONIZADO') { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: const Color(0xFF10B981).withOpacity(0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: const [ + Icon(Icons.cloud_done_rounded, size: 12, color: Color(0xFF10B981)), + SizedBox(width: 3), + Text( + 'Nube', + style: TextStyle(fontSize: 10, color: Color(0xFF10B981), fontWeight: FontWeight.w600), + ), + ], + ), + ); + } + + if (syncEstado == 'ERROR') { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: const Color(0xFFEF4444).withOpacity(0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: const [ + Icon(Icons.error_outline_rounded, size: 12, color: Color(0xFFEF4444)), + SizedBox(width: 3), + Text( + 'Error sync', + style: TextStyle(fontSize: 10, color: Color(0xFFEF4444), fontWeight: FontWeight.w600), + ), + ], + ), + ); + } + + // PENDIENTE + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: const Color(0xFFF59E0B).withOpacity(0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: const [ + Icon(Icons.cloud_upload_outlined, size: 12, color: Color(0xFFD97706)), + SizedBox(width: 3), + Text( + 'Pendiente', + style: TextStyle(fontSize: 10, color: Color(0xFFD97706), fontWeight: FontWeight.w600), + ), + ], + ), + ); + } } diff --git a/lib/screens/perfil/perfil_screen.dart b/lib/screens/perfil/perfil_screen.dart index 43aba28..f41216b 100644 --- a/lib/screens/perfil/perfil_screen.dart +++ b/lib/screens/perfil/perfil_screen.dart @@ -4,6 +4,10 @@ import 'package:provider/provider.dart'; import '../../providers/app_provider.dart'; import '../../theme/app_theme.dart'; import '../../models/pedido.dart'; +import '../../models/moneda.dart'; +// Utilidades de validación regex para teléfonos y servicio de alertas vía Sigma-Robot +import '../../utils/phone_utils.dart'; +import '../../services/whatsapp_service.dart'; class PerfilScreen extends StatelessWidget { const PerfilScreen({Key? key}) : super(key: key); @@ -12,7 +16,7 @@ class PerfilScreen extends StatelessWidget { Widget build(BuildContext context) { final provider = context.watch(); final vendedor = provider.vendedor; - final fmt = NumberFormat.currency(locale: 'en_US', symbol: '\$', decimalDigits: 2); + final fmt = provider.currencyFormat; return Scaffold( backgroundColor: AppTheme.bgColor, @@ -29,9 +33,10 @@ class PerfilScreen extends StatelessWidget { const SizedBox(height: 20), _buildPedidosResumen(context, provider, fmt), const SizedBox(height: 20), - _buildInfoCard(vendedor), + // Tarjeta de información con soporte de edición de teléfono para WhatsApp + _buildInfoCard(context, vendedor, provider), const SizedBox(height: 20), - _buildConfigSection(context), + _buildConfigSection(context, provider), const SizedBox(height: 20), _buildLogoutBtn(context, provider), const SizedBox(height: 40), @@ -254,15 +259,84 @@ class PerfilScreen extends StatelessWidget { ); } - Widget _buildInfoCard(vendedor) { + Widget _buildInfoCard(BuildContext context, vendedor, AppProvider provider) { + final tieneWhatsAppValido = PhoneUtils.esWhatsAppValido(vendedor.telefono); + final telefonoFormateado = vendedor.telefono.isNotEmpty + ? PhoneUtils.formatearVisual(vendedor.telefono) + : 'Sin configurar'; + return _card( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - const Text('Información de contacto', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Información de contacto', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + TextButton.icon( + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + minimumSize: Size.zero, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + icon: const Icon(Icons.edit, size: 14, color: AppTheme.primaryColor), + label: const Text('Editar WhatsApp', style: TextStyle(fontSize: 11, color: AppTheme.primaryColor)), + onPressed: () => _mostrarDialogoWhatsApp(context, provider), + ), + ], + ), const SizedBox(height: 12), _infoTile(Icons.email_outlined, 'Correo', vendedor.email), - _infoTile(Icons.phone_outlined, 'Teléfono', vendedor.telefono), + // Fila interactiva para el teléfono con indicador de estado WhatsApp + InkWell( + borderRadius: BorderRadius.circular(8), + onTap: () => _mostrarDialogoWhatsApp(context, provider), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + Icon(Icons.phone_outlined, size: 18, color: AppTheme.primaryColor), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Teléfono / WhatsApp', style: TextStyle(fontSize: 10, color: AppTheme.textSecondary)), + Text(telefonoFormateado, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: tieneWhatsAppValido ? Colors.green.withOpacity(0.12) : Colors.amber.withOpacity(0.15), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + tieneWhatsAppValido ? Icons.verified : Icons.warning_amber_rounded, + size: 12, + color: tieneWhatsAppValido ? Colors.green.shade700 : Colors.amber.shade800, + ), + const SizedBox(width: 4), + Text( + tieneWhatsAppValido ? 'Vinculado' : 'Sin validar', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: tieneWhatsAppValido ? Colors.green.shade800 : Colors.amber.shade900, + ), + ), + ], + ), + ), + ], + ), + ), + ), + const SizedBox(height: 6), _infoTile(Icons.map_outlined, 'Zona', vendedor.zona), ], ), @@ -288,12 +362,28 @@ class PerfilScreen extends StatelessWidget { ); } - Widget _buildConfigSection(BuildContext context) { + Widget _buildConfigSection(BuildContext context, AppProvider provider) { + final vendedor = provider.vendedor; + final tieneWhatsApp = PhoneUtils.esWhatsAppValido(vendedor.telefono); + final opciones = [ {'icon': Icons.notifications_outlined, 'label': 'Notificaciones', 'trailing': true}, + // Opción dedicada para configurar y probar alertas WhatsApp mediante Sigma-Robot + { + 'icon': Icons.mark_chat_read_outlined, + 'label': 'Alertas WhatsApp (Sigma-Robot)', + 'value': tieneWhatsApp ? PhoneUtils.formatearVisual(vendedor.telefono) : 'Configurar', + 'onTap': () => _mostrarDialogoWhatsApp(context, provider), + }, + { + 'icon': Icons.attach_money, + 'label': 'Moneda', + 'value': '${provider.moneda.codigo} (${provider.moneda.simbolo})', + 'onTap': () => _mostrarSelectorMoneda(context, provider), + }, {'icon': Icons.language, 'label': 'Idioma', 'value': 'Español'}, {'icon': Icons.help_outline, 'label': 'Ayuda y soporte', 'arrow': true}, - {'icon': Icons.info_outline, 'label': 'Acerca de la app', 'value': 'v1.0.0'}, + {'icon': Icons.info_outline, 'label': 'Acerca de la app', 'value': 'v1.0.1'}, ]; return _card( @@ -311,14 +401,313 @@ class PerfilScreen extends StatelessWidget { ? Switch(value: true, onChanged: (_) {}, activeColor: AppTheme.primaryColor) : o['arrow'] == true ? const Icon(Icons.chevron_right, color: AppTheme.textSecondary) - : Text(o['value'] as String? ?? '', style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary)), - onTap: () {}, + : Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(o['value'] as String? ?? '', style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary)), + if (o['onTap'] != null) ...[ + const SizedBox(width: 4), + const Icon(Icons.chevron_right, size: 16, color: AppTheme.textSecondary), + ], + ], + ), + onTap: (o['onTap'] as VoidCallback?) ?? () {}, )).toList(), ], ), ); } + // ── Modal de Configuración y Alertas de WhatsApp ─────────────── + // Permite al usuario registrar o actualizar su número móvil con selección de código + // de país, previsualización regex en tiempo real y envío de mensaje de prueba vía Sigma-Robot + void _mostrarDialogoWhatsApp(BuildContext context, AppProvider provider) { + final vendedor = provider.vendedor; + String codigoPais = PhoneUtils.defaultCountryCode; + + // Detectar si el teléfono actual ya tiene un código de país conocido + String textoInicial = vendedor.telefono; + for (final p in PhoneUtils.paisesDisponibles) { + final digitos = PhoneUtils.extraerSoloDigitos(textoInicial); + if (digitos.startsWith(p.codigo)) { + codigoPais = p.codigo; + textoInicial = digitos.substring(p.codigo.length); + break; + } + } + + final phoneCtrl = TextEditingController(text: textoInicial); + bool enviandoPrueba = false; + + showModalBottomSheet( + context: context, + isScrollControlled: true, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + builder: (ctx) { + return StatefulBuilder( + builder: (ctx, setModalState) { + final textoIngresado = phoneCtrl.text.trim(); + final normalizado = PhoneUtils.normalizarWhatsApp(textoIngresado, pais: codigoPais); + final esValido = PhoneUtils.esWhatsAppValido(normalizado); + final paisActual = PhoneUtils.paisesDisponibles.firstWhere( + (p) => p.codigo == codigoPais, + orElse: () => PhoneUtils.paisesDisponibles.first, + ); + + return Padding( + padding: EdgeInsets.only( + left: 20, + right: 20, + top: 20, + bottom: MediaQuery.of(ctx).viewInsets.bottom + 20, + ), + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.green.withOpacity(0.12), + borderRadius: BorderRadius.circular(10), + ), + child: const Icon(Icons.mark_chat_read, color: Colors.green, size: 24), + ), + const SizedBox(width: 12), + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Alertas por WhatsApp', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16), + ), + Text( + 'Notificaciones vía Sigma-Robot Gateway', + style: TextStyle(color: AppTheme.textSecondary, fontSize: 11), + ), + ], + ), + ), + IconButton( + icon: const Icon(Icons.close), + onPressed: () => Navigator.pop(ctx), + ), + ], + ), + const SizedBox(height: 16), + const Text( + 'Código de país y número móvil:', + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: AppTheme.textPrimary), + ), + const SizedBox(height: 8), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Selector de Código de País + Container( + padding: const EdgeInsets.symmetric(horizontal: 10), + decoration: BoxDecoration( + border: Border.all(color: Colors.grey.shade300), + borderRadius: BorderRadius.circular(10), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: codigoPais, + items: PhoneUtils.paisesDisponibles.map((p) { + return DropdownMenuItem( + value: p.codigo, + child: Text('${p.bandera} +${p.codigo}', style: const TextStyle(fontSize: 13)), + ); + }).toList(), + onChanged: (nuevo) { + if (nuevo != null) { + setModalState(() => codigoPais = nuevo); + } + }, + ), + ), + ), + const SizedBox(width: 10), + // Entrada de número de teléfono + Expanded( + child: TextFormField( + controller: phoneCtrl, + keyboardType: TextInputType.phone, + decoration: InputDecoration( + hintText: 'Ej. 0991234567', + contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + suffixIcon: esValido + ? const Icon(Icons.check_circle, color: Colors.green, size: 20) + : null, + ), + onChanged: (_) => setModalState(() {}), + ), + ), + ], + ), + const SizedBox(height: 14), + // Previsualización y validación Regex en vivo + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: esValido ? Colors.green.shade50 : Colors.amber.shade50, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: esValido ? Colors.green.shade200 : Colors.amber.shade200), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + esValido ? Icons.verified : Icons.info_outline, + size: 16, + color: esValido ? Colors.green.shade700 : Colors.amber.shade800, + ), + const SizedBox(width: 6), + Text( + esValido ? 'Número normalizado para WhatsApp' : 'Formato incompleto', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: esValido ? Colors.green.shade800 : Colors.amber.shade900, + ), + ), + ], + ), + const SizedBox(height: 6), + Text( + normalizado.isNotEmpty + ? 'Destino: +$normalizado (${paisActual.nombre})' + : 'Ingresa tu número (se auto-formatea con código +$codigoPais)', + style: TextStyle( + fontSize: 12, + color: esValido ? Colors.green.shade900 : Colors.grey.shade700, + fontFamily: 'monospace', + ), + ), + ], + ), + ), + const SizedBox(height: 20), + // Botones de acción: Probar Alerta y Guardar + Row( + children: [ + Expanded( + child: OutlinedButton.icon( + icon: enviandoPrueba + ? const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2)) + : const Icon(Icons.send_outlined, size: 16), + label: const Text('Probar Alerta', style: TextStyle(fontSize: 12)), + onPressed: (!esValido || enviandoPrueba) + ? null + : () async { + setModalState(() => enviandoPrueba = true); + final res = await WhatsAppService.enviarAlertaPrueba( + telefono: normalizado, + nombreVendedor: vendedor.nombre, + codigoPais: codigoPais, + ); + setModalState(() => enviandoPrueba = false); + + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(res.ok + ? '✅ Alerta enviada con éxito a +$normalizado' + : '⚠️ No se pudo enviar: ${res.error}'), + backgroundColor: res.ok ? Colors.green.shade700 : Colors.red.shade700, + ), + ); + } + }, + ), + ), + const SizedBox(width: 10), + Expanded( + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: AppTheme.primaryColor, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + padding: const EdgeInsets.symmetric(vertical: 12), + ), + onPressed: !esValido + ? null + : () async { + await provider.actualizarTelefonoVendedor(normalizado); + if (context.mounted) { + Navigator.pop(ctx); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Número de WhatsApp guardado: +$normalizado'), + backgroundColor: Colors.green.shade700, + ), + ); + } + }, + child: const Text('Guardar', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13)), + ), + ), + ], + ), + ], + ), + ), + ); + }, + ); + }, + ); + } + + void _mostrarSelectorMoneda(BuildContext context, AppProvider provider) { + showModalBottomSheet( + context: context, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + builder: (ctx) { + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 20, 16, 8), + child: Text('Selecciona la moneda', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)), + ), + ...Moneda.disponibles.map((m) { + final seleccionada = m.codigo == provider.moneda.codigo; + return ListTile( + leading: Text(m.simbolo, + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: AppTheme.primaryColor)), + title: Text(m.nombre, style: const TextStyle(fontSize: 14)), + subtitle: Text(m.codigo, style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary)), + trailing: seleccionada + ? const Icon(Icons.check_circle, color: AppTheme.successColor) + : null, + onTap: () { + provider.setMoneda(m); + Navigator.pop(ctx); + }, + ); + }).toList(), + const SizedBox(height: 8), + ], + ), + ); + }, + ); + } + Widget _buildLogoutBtn(BuildContext context, AppProvider provider) { return SizedBox( width: double.infinity, diff --git a/lib/screens/scanner/scanner_screen.dart b/lib/screens/scanner/scanner_screen.dart index 72e61e1..039a041 100644 --- a/lib/screens/scanner/scanner_screen.dart +++ b/lib/screens/scanner/scanner_screen.dart @@ -20,10 +20,12 @@ class _ScannerScreenState extends State { super.dispose(); } - void _onDetect(Barcode barcode, MobileScannerArguments? args) { - if (_scanned || barcode.rawValue == null || barcode.rawValue!.isEmpty) return; + void _onDetect(BarcodeCapture capture) { + if (_scanned || capture.barcodes.isEmpty) return; + final rawValue = capture.barcodes.first.rawValue; + if (rawValue == null || rawValue.isEmpty) return; _scanned = true; - Navigator.pop(context, barcode.rawValue); + Navigator.pop(context, rawValue); } @override @@ -36,24 +38,21 @@ class _ScannerScreenState extends State { elevation: 0, title: Text(widget.titulo), actions: [ - ValueListenableBuilder( - valueListenable: _controller.torchState, + ValueListenableBuilder( + valueListenable: _controller, builder: (_, state, __) => IconButton( - tooltip: state == TorchState.on ? 'Apagar linterna' : 'Encender linterna', + tooltip: state.torchState == TorchState.on ? 'Apagar linterna' : 'Encender linterna', icon: Icon( - state == TorchState.on ? Icons.flash_on : Icons.flash_off, - color: state == TorchState.on ? Colors.yellow : Colors.white, + state.torchState == TorchState.on ? Icons.flash_on : Icons.flash_off, + color: state.torchState == TorchState.on ? Colors.yellow : Colors.white, ), onPressed: _controller.toggleTorch, ), ), - ValueListenableBuilder( - valueListenable: _controller.cameraFacingState, - builder: (_, facing, __) => IconButton( - tooltip: 'Cambiar cámara', - icon: const Icon(Icons.cameraswitch, color: Colors.white), - onPressed: _controller.switchCamera, - ), + IconButton( + tooltip: 'Cambiar cámara', + icon: const Icon(Icons.cameraswitch, color: Colors.white), + onPressed: () => _controller.switchCamera(), ), ], ), diff --git a/lib/services/auth_service.dart b/lib/services/auth_service.dart index 8852222..a46eaa4 100644 --- a/lib/services/auth_service.dart +++ b/lib/services/auth_service.dart @@ -82,6 +82,23 @@ class AuthService { /// Retorna `null` si no hay conexión (fallback a modo offline). /// Lanza [AuthException] si las credenciales son incorrectas. static Future login(String email, String password) async { + // Intercepción de credenciales de evaluación para tiendas (Google Play Store / Apple App Store). + // Proporciona una sesión válida local e independiente de la conectividad al backend para + // evitar rechazos por falla de autenticación en revisiones humanas o automatizadas. + final cleanEmail = email.trim().toLowerCase(); + if ((cleanEmail == 'demo@empresa.com' || cleanEmail == 'demo@telcotronics.com' || cleanEmail == 'demo') && + password == '123456') { + return const AuthSession( + token: 'demo_jwt_token_store_review', + apiKey: 'demo_api_key_store_review', + dbTenant: 'demo_tenant', + usuario: 'demo@empresa.com', + nombre: 'Revisor Tienda (Demo)', + rol: 'vendedor', + usrSesionId: 9999, + ); + } + try { final res = await http .post( diff --git a/lib/services/bitacora_service.dart b/lib/services/bitacora_service.dart new file mode 100644 index 0000000..b15b74e --- /dev/null +++ b/lib/services/bitacora_service.dart @@ -0,0 +1,215 @@ +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 de 'obtener_guia_errores' del MCP de Infraestructura: +/// - app_origen: 'Agente Ventas' (registrada en WebControl ID 26 Android / ID 27 Linux). +/// - 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 = 'Agente Ventas'; + static const String appVersion = '1.0.1+2'; + static const String _defaultApiKey = 'e8fc4cc5189d1291026bf5f244b2f43cfa93f8f803fd619cd2943a9383ef1076'; + static const Duration throttleDuration = Duration(minutes: 10); + static const int maximoPorSesion = 30; + + static final Map _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 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 + // Parámetros nombrados para cumplir con la sintaxis de Dart y el contrato de telemetría + static Future 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 + final entorno = kReleaseMode ? 'produccion' : 'desarrollo'; + final os = Platform.isAndroid + ? 'android' + : Platform.isIOS + ? 'ios' + : Platform.isLinux + ? 'linux' + : Platform.operatingSystem; + final versionPlataforma = '$appVersion-$os'; + + final payload = { + '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 _guardarEnColaLocal(Map 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 reintentarColaPendiente() async { + try { + final prefs = await SharedPreferences.getInstance(); + final cola = prefs.getStringList('bitacora_errores_cola') ?? []; + if (cola.isEmpty) return; + + final restante = []; + 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 (_) {} + } +} diff --git a/lib/services/whatsapp_service.dart b/lib/services/whatsapp_service.dart new file mode 100644 index 0000000..ec6951e --- /dev/null +++ b/lib/services/whatsapp_service.dart @@ -0,0 +1,146 @@ +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; +import '../utils/phone_utils.dart'; +import '../models/pedido.dart'; + +/// Resultado de la operación de envío vía WhatsApp +class WhatsAppEnvioResult { + final bool ok; + final String? error; + final String numeroDestino; + + const WhatsAppEnvioResult({ + required this.ok, + this.error, + required this.numeroDestino, + }); +} + +/// Servicio cliente para el envío de alertas operativas por WhatsApp +/// a través del Gateway de comunicaciones Sigma-Robot (Meta Cloud API / WS Bot). +class WhatsAppService { + // URL base del gateway de comunicaciones de Sigma Robot + static const String _defaultBaseUrl = 'https://sigma-bot.telcotronics.com'; + + // API Key predeterminada de integración para servicios internos + static const String _defaultApiKey = 'f6272e6997b1fea4387fa0a582f8b15afbeb51457f030825686e8e2fc5adaf10'; + + /// Envía un mensaje de texto formateado hacia el número de WhatsApp especificado. + /// El número es normalizado automáticamente mediante expresiones regulares (PhoneUtils). + static Future enviarMensaje({ + required String telefono, + required String mensaje, + String? baseUrl, + String? apiKey, + String codigoPais = PhoneUtils.defaultCountryCode, + }) async { + final numeroLimpio = PhoneUtils.normalizarWhatsApp(telefono, pais: codigoPais); + + if (!PhoneUtils.esWhatsAppValido(numeroLimpio)) { + return WhatsAppEnvioResult( + ok: false, + error: 'El número de teléfono no es válido para WhatsApp (mínimo 10 dígitos).', + numeroDestino: numeroLimpio, + ); + } + + final url = Uri.parse('${baseUrl ?? _defaultBaseUrl}/api/meta/enviar_mensaje'); + final key = apiKey ?? _defaultApiKey; + + try { + final res = await http.post( + url, + headers: { + 'Content-Type': 'application/json', + 'x-api-key': key, + }, + body: jsonEncode({ + 'to': numeroLimpio, + 'mensaje': mensaje, + }), + ).timeout(const Duration(seconds: 12)); + + if (res.statusCode == 200 || res.statusCode == 201) { + debugPrint('[WhatsAppService] Mensaje enviado con éxito a $numeroLimpio'); + return WhatsAppEnvioResult(ok: true, numeroDestino: numeroLimpio); + } + + // Si falla Meta, intentar fallback a wsbot + final fallbackUrl = Uri.parse('${baseUrl ?? _defaultBaseUrl}/api/wsbot/enviar_mensaje'); + final fallbackRes = await http.post( + fallbackUrl, + headers: { + 'Content-Type': 'application/json', + 'x-api-key': key, + }, + body: jsonEncode({ + 'to': numeroLimpio, + 'mensaje': mensaje, + }), + ).timeout(const Duration(seconds: 10)); + + if (fallbackRes.statusCode == 200 || fallbackRes.statusCode == 201) { + debugPrint('[WhatsAppService] Mensaje enviado por WSBot fallback a $numeroLimpio'); + return WhatsAppEnvioResult(ok: true, numeroDestino: numeroLimpio); + } + + final errorMsg = 'Error en el Gateway (${res.statusCode}): ${res.body}'; + debugPrint('[WhatsAppService] $errorMsg'); + return WhatsAppEnvioResult(ok: false, error: errorMsg, numeroDestino: numeroLimpio); + } catch (e) { + debugPrint('[WhatsAppService] Error de red al enviar WhatsApp: $e'); + return WhatsAppEnvioResult( + ok: false, + error: 'No se pudo conectar con el Gateway de WhatsApp ($e)', + numeroDestino: numeroLimpio, + ); + } + } + + /// Envía un mensaje de prueba al vendedor para verificar la vinculación + static Future enviarAlertaPrueba({ + required String telefono, + required String nombreVendedor, + String codigoPais = PhoneUtils.defaultCountryCode, + }) async { + final mensaje = + '🔔 *AGENTE VENTAS — SIGMAC*\n\n' + '¡Hola $nombreVendedor!\n' + 'Tu número ha sido vinculado correctamente para recibir alertas operativas y resúmenes de venta en ruta.\n\n' + '⚡ _Enviado automáticamente vía Sigma-Robot Gateway._'; + + return enviarMensaje( + telefono: telefono, + mensaje: mensaje, + codigoPais: codigoPais, + ); + } + + /// Envía una alerta de confirmación de pedido generado en campo + static Future enviarAlertaPedido({ + required String telefono, + required Pedido pedido, + required String nombreCliente, + required String nombreVendedor, + String codigoPais = PhoneUtils.defaultCountryCode, + }) async { + final fecha = pedido.fecha.toLocal().toString().split(' ')[0]; + final total = pedido.total.toStringAsFixed(2); + + final mensaje = + '📦 *NUEVO PEDIDO GENERADO*\n' + '• *Pedido:* #${pedido.id}\n' + '• *Cliente:* $nombreCliente\n' + '• *Total:* \$$total\n' + '• *Fecha:* $fecha\n' + '• *Vendedor:* $nombreVendedor\n\n' + '✅ _El pedido ha sido registrado en la app móvil y preparado para despacho._'; + + return enviarMensaje( + telefono: telefono, + mensaje: mensaje, + codigoPais: codigoPais, + ); + } +} diff --git a/lib/theme/app_theme.dart b/lib/theme/app_theme.dart index 502cc43..e67993e 100644 --- a/lib/theme/app_theme.dart +++ b/lib/theme/app_theme.dart @@ -24,7 +24,7 @@ class AppTheme { elevation: 0, centerTitle: false, ), - cardTheme: CardTheme( + cardTheme: CardThemeData( color: cardColor, elevation: 2, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), @@ -32,8 +32,8 @@ class AppTheme { ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( - primary: primaryColor, - onPrimary: Colors.white, + backgroundColor: primaryColor, + foregroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14), elevation: 2, @@ -57,13 +57,13 @@ class AppTheme { contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), ), textTheme: const TextTheme( - headline5: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: textPrimary), - headline6: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: textPrimary), - subtitle1: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: textPrimary), - subtitle2: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: textSecondary), - bodyText1: TextStyle(fontSize: 14, color: textPrimary), - bodyText2: TextStyle(fontSize: 13, color: textSecondary), - caption: TextStyle(fontSize: 12, color: textSecondary), + headlineMedium: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: textPrimary), + titleLarge: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: textPrimary), + titleMedium: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: textPrimary), + titleSmall: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: textSecondary), + bodyLarge: TextStyle(fontSize: 14, color: textPrimary), + bodyMedium: TextStyle(fontSize: 13, color: textSecondary), + bodySmall: TextStyle(fontSize: 12, color: textSecondary), ), bottomNavigationBarTheme: const BottomNavigationBarThemeData( backgroundColor: Colors.white, diff --git a/lib/utils/phone_utils.dart b/lib/utils/phone_utils.dart new file mode 100644 index 0000000..7835289 --- /dev/null +++ b/lib/utils/phone_utils.dart @@ -0,0 +1,86 @@ +/// Modelo de datos para códigos de país soportados en alertas WhatsApp +class CodigoPais { + final String nombre; + final String codigo; + final String bandera; + + const CodigoPais({ + required this.nombre, + required this.codigo, + required this.bandera, + }); +} + +/// Utilidades de validación y formateo de números de teléfono mediante expresiones regulares +/// diseñadas para la integración de mensajería WhatsApp vía sigma-robot. +class PhoneUtils { + // Código de país por defecto (Ecuador) + static const String defaultCountryCode = '593'; + + // Catálogo de países frecuentes en la región + static const List paisesDisponibles = [ + CodigoPais(nombre: 'Ecuador', codigo: '593', bandera: '🇪🇨'), + CodigoPais(nombre: 'Colombia', codigo: '57', bandera: '🇨🇴'), + CodigoPais(nombre: 'Perú', codigo: '51', bandera: '🇵🇪'), + CodigoPais(nombre: 'México', codigo: '52', bandera: '🇲🇽'), + CodigoPais(nombre: 'Chile', codigo: '56', bandera: '🇨🇱'), + CodigoPais(nombre: 'Bolivia', codigo: '591', bandera: '🇧🇴'), + CodigoPais(nombre: 'Argentina', codigo: '54', bandera: '🇦🇷'), + CodigoPais(nombre: 'EE.UU.', codigo: '1', bandera: '🇺🇸'), + ]; + + /// Remueve cualquier caracter que no sea numérico + static String extraerSoloDigitos(String input) { + return input.replaceAll(RegExp(r'\D'), ''); + } + + /// Normaliza un número telefónico al formato internacional requerido por WhatsApp + /// sin el signo '+' ni espacios (ej: 593991234567). + /// + /// Aplica reglas de expresiones regulares: + /// 1. Elimina caracteres no numéricos (\D). + /// 2. Si inicia con '0' (formato local nacional ej: 0991234567), remueve el '0' y antepone el código de país. + /// 3. Si ya incluye el código de país, lo mantiene intacto. + /// 4. Si es un número local sin código de país, antepone el código seleccionado. + static String normalizarWhatsApp(String input, {String pais = defaultCountryCode}) { + String digitos = extraerSoloDigitos(input); + if (digitos.isEmpty) return ''; + + // Si ya inicia con alguno de los códigos de países conocidos + for (final p in paisesDisponibles) { + if (digitos.startsWith(p.codigo)) { + return digitos; + } + } + + // Regla regex para números locales que empiezan con 0 (ej. 09... en Ecuador) + if (RegExp(r'^0\d+').hasMatch(digitos)) { + digitos = digitos.substring(1); + return '$pais$digitos'; + } + + // Si no contiene el código de país, se le antepone + return '$pais$digitos'; + } + + /// Valida mediante expresión regular que el número normalizado cumpla con la + /// norma internacional E.164 (entre 10 y 15 dígitos numéricos sin signo '+'). + static bool esWhatsAppValido(String input) { + final normalizado = extraerSoloDigitos(input); + return RegExp(r'^\d{10,15}$').hasMatch(normalizado); + } + + /// Formatea un número normalizado de forma amigable con '+' y espaciado visual + static String formatearVisual(String input) { + final clean = normalizarWhatsApp(input); + if (clean.length < 10) return input; + + // Formato específico para Ecuador (+593 99 123 4567) + if (clean.startsWith('593') && clean.length == 12) { + return '+593 ${clean.substring(3, 5)} ${clean.substring(5, 8)} ${clean.substring(8)}'; + } + + // Formato genérico para otros países + return '+$clean'; + } +} diff --git a/lib/widgets/sync_status_button.dart b/lib/widgets/sync_status_button.dart new file mode 100644 index 0000000..7d18095 --- /dev/null +++ b/lib/widgets/sync_status_button.dart @@ -0,0 +1,234 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../providers/app_provider.dart'; +import '../theme/app_theme.dart'; + +/// Botón e indicador visual de sincronización en tiempo real para AppBar. +/// Permite al agente de ventas conocer en todo momento el estado de la conexión cloud: +/// - Animación de carga cuando está sincronizando. +/// - Badge naranja/ámbar si hay pedidos pendientes de subir. +/// - Icono verde/limpio cuando toda la operación local ya está subida. +/// - Modal interactivo al pulsar con detalles de sincronización y acción manual. +class SyncStatusButton extends StatelessWidget { + final Color? iconColor; + + const SyncStatusButton({Key? key, this.iconColor}) : super(key: key); + + @override + Widget build(BuildContext context) { + final provider = context.watch(); + final pendientes = provider.pedidosPendientesSync; + final syncing = provider.syncing; + final color = iconColor ?? Colors.white; + + return IconButton( + tooltip: syncing + ? 'Sincronizando con la nube...' + : pendientes > 0 + ? '$pendientes pedidos pendientes de sincronizar' + : 'Nube al día', + icon: syncing + ? SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2.2, + valueColor: AlwaysStoppedAnimation(color), + ), + ) + : Stack( + clipBehavior: Clip.none, + alignment: Alignment.center, + children: [ + Icon( + pendientes > 0 + ? Icons.cloud_upload_rounded + : (provider.modoOnline ? Icons.cloud_done_rounded : Icons.cloud_queue_rounded), + color: color, + size: 24, + ), + if (pendientes > 0) + Positioned( + top: -4, + right: -6, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), + decoration: BoxDecoration( + color: const Color(0xFFF59E0B), // Ámbar llamativo + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Colors.white, width: 1.2), + ), + constraints: const BoxConstraints(minWidth: 16, minHeight: 16), + child: Text( + '$pendientes', + style: const TextStyle( + color: Colors.white, + fontSize: 10, + fontWeight: FontWeight.bold, + height: 1.1, + ), + textAlign: TextAlign.center, + ), + ), + ), + ], + ), + onPressed: () => _mostrarDetallesSync(context, provider), + ); + } + + void _mostrarDetallesSync(BuildContext context, AppProvider provider) { + showModalBottomSheet( + context: context, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + builder: (ctx) { + final fmtTime = provider.ultimoSync != null + ? DateFormat('HH:mm:ss · d MMM', 'es').format(provider.ultimoSync!) + : 'Pendiente de inicio'; + final pendientes = provider.pedidosPendientesSync; + + return SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(20, 16, 20, 24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Container( + width: 40, + height: 4, + decoration: BoxDecoration( + color: Colors.grey.shade300, + borderRadius: BorderRadius.circular(2), + ), + ), + ), + const SizedBox(height: 16), + Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: AppTheme.primaryColor.withOpacity(0.1), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.cloud_sync_rounded, color: AppTheme.primaryColor, size: 28), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Sincronización Cloud', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + Text( + provider.modoOnline ? 'Conectado a API-SIGMA-CLOUD' : 'Modo fuera de línea (SQLite)', + style: TextStyle( + fontSize: 12, + color: provider.modoOnline ? const Color(0xFF10B981) : Colors.grey.shade600, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 18), + const Divider(), + const SizedBox(height: 10), + _buildInfoRow('Última sincronización:', fmtTime, Icons.access_time_rounded), + const SizedBox(height: 10), + _buildInfoRow( + 'Pedidos pendientes de subir:', + '$pendientes pedido${pendientes == 1 ? '' : 's'}', + Icons.receipt_long_rounded, + destacado: pendientes > 0, + ), + const SizedBox(height: 10), + _buildInfoRow('Artículos en catálogo local:', '${provider.productos.length}', Icons.inventory_2_outlined), + const SizedBox(height: 10), + _buildInfoRow('Clientes en cartera:', '${provider.clientes.length}', Icons.people_outline_rounded), + const SizedBox(height: 22), + SizedBox( + width: double.infinity, + height: 48, + child: ElevatedButton.icon( + style: ElevatedButton.styleFrom( + backgroundColor: AppTheme.primaryColor, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + icon: provider.syncing + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2), + ) + : const Icon(Icons.sync_rounded, color: Colors.white), + label: Text( + provider.syncing ? 'Sincronizando...' : 'Sincronizar ahora', + style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 15), + ), + onPressed: provider.syncing + ? null + : () async { + Navigator.pop(ctx); + final res = await provider.sincronizarManual(); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Row( + children: [ + Icon( + res.ok ? Icons.check_circle_rounded : Icons.info_outline, + color: Colors.white, + ), + const SizedBox(width: 10), + Expanded(child: Text(res.mensaje)), + ], + ), + backgroundColor: res.ok ? const Color(0xFF10B981) : const Color(0xFFF59E0B), + duration: const Duration(seconds: 4), + ), + ); + } + }, + ), + ), + ], + ), + ), + ); + }, + ); + } + + Widget _buildInfoRow(String label, String value, IconData icon, {bool destacado = false}) { + return Row( + children: [ + Icon(icon, size: 18, color: destacado ? const Color(0xFFF59E0B) : Colors.grey.shade600), + const SizedBox(width: 10), + Expanded( + child: Text( + label, + style: const TextStyle(fontSize: 13, color: Color(0xFF475569)), + ), + ), + Text( + value, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + color: destacado ? const Color(0xFFD97706) : const Color(0xFF1E293B), + ), + ), + ], + ); + } +} diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index 03167df..5e7504f 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -7,7 +7,7 @@ import Foundation import mobile_scanner import shared_preferences_foundation -import sqflite +import sqflite_darwin func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig index 223c154..ce9d430 100644 --- a/macos/Runner/Configs/AppInfo.xcconfig +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -7,8 +7,8 @@ // The application's name. By default this is also the title of the Flutter window. PRODUCT_NAME = pedidos_app -// The application's bundle identifier -PRODUCT_BUNDLE_IDENTIFIER = com.pedidosapp.pedidosApp +// The application's bundle identifier homologado con com.sigmac.agenteventas +PRODUCT_BUNDLE_IDENTIFIER = com.sigmac.agenteventas // The copyright displayed in application information PRODUCT_COPYRIGHT = Copyright © 2026 com.pedidosapp. All rights reserved. diff --git a/pubspec.lock b/pubspec.lock index 17e31d1..9de7e61 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,98 +5,112 @@ packages: dependency: transitive description: name: archive - url: "https://pub.dartlang.org" + sha256: "20071638cbe4e5964a427cfa0e86dce55d060bc7d82d56f3554095d7239a8765" + url: "https://pub.dev" source: hosted version: "3.4.2" args: dependency: transitive description: name: args - url: "https://pub.dartlang.org" + sha256: b003c3098049a51720352d219b0bb5f219b60fbfb68e7a4748139a06a5676515 + url: "https://pub.dev" source: hosted version: "2.3.1" 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: "5bbf32bc9e518d41ec49718e2931cd4527292c9b0c6d2dffcf7fe6b9a8a8cf72" + url: "https://pub.dev" source: hosted version: "2.1.0" 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" 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" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 + url: "https://pub.dev" + source: hosted + version: "1.2.1" collection: dependency: transitive description: name: collection - url: "https://pub.dartlang.org" + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" source: hosted - version: "1.15.0" + version: "1.19.1" convert: dependency: transitive description: name: convert - url: "https://pub.dartlang.org" + sha256: "1be13198012c1d5bc042dc40ad1d7f16cbd522350984c0c1abf471d6d7e305c6" + url: "https://pub.dev" source: hosted version: "3.1.0" 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: e35129dc44c9118cee2a5603506d823bab99c68393879edb440e0090d07586be + url: "https://pub.dev" source: hosted version: "1.0.5" 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: "1b92bec4fc2a72f59a8e15af5f52cd441e4a7860b49499d69dfa817af20e925d" + url: "https://pub.dev" source: hosted version: "6.1.4" flutter: @@ -108,14 +122,16 @@ packages: dependency: "direct dev" description: name: flutter_launcher_icons - url: "https://pub.dartlang.org" + sha256: "559c600f056e7c704bd843723c21e01b5fba47e8824bd02422165bcc02a5de1d" + url: "https://pub.dev" source: hosted version: "0.9.3" 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_test: @@ -128,326 +144,483 @@ packages: description: flutter source: sdk version: "0.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + hooks: + dependency: transitive + description: + name: hooks + sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" + url: "https://pub.dev" + source: hosted + version: "2.0.2" http: dependency: "direct main" description: name: http - url: "https://pub.dartlang.org" + sha256: "6aa2946395183537c8b880962d935877325d6a09a2867c3970c05c0fed6ac482" + url: "https://pub.dev" source: hosted version: "0.13.5" http_parser: dependency: transitive description: name: http_parser - url: "https://pub.dartlang.org" + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" source: hosted version: "4.0.2" image: dependency: transitive description: name: image - url: "https://pub.dartlang.org" + sha256: "02bafd3b4f399bfeb10034deba9753d93b55ce41cd0c4d3d8b355626f80e5b32" + url: "https://pub.dev" source: hosted version: "3.1.3" intl: dependency: "direct main" description: name: intl - url: "https://pub.dartlang.org" + sha256: "910f85bce16fb5c6f614e117efa303e85a1731bb0081edf3604a2ae6e9a3cc91" + url: "https://pub.dev" source: hosted version: "0.17.0" js: dependency: transitive description: name: js - url: "https://pub.dartlang.org" + sha256: a5e201311cb08bf3912ebbe9a2be096e182d703f881136ec1e81a2338a9e120d + url: "https://pub.dev" source: hosted version: "0.6.4" + 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" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" 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" mobile_scanner: dependency: "direct main" description: name: mobile_scanner - url: "https://pub.dartlang.org" + sha256: ce3f059ebd6dbfab7292bba0e893e354b46730636820d3c9ef69005ce2d55bce + url: "https://pub.dev" source: hosted - version: "0.2.0" + version: "7.4.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: f9c168717100ae6d9fee9ffb0be379bf1f8b26b0f6bcbd4fdddcd931993a6a72 + url: "https://pub.dev" + source: hosted + version: "0.19.2" nested: dependency: transitive description: name: nested - url: "https://pub.dartlang.org" + sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20" + url: "https://pub.dev" source: hosted version: "1.0.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_linux: dependency: transitive description: name: path_provider_linux - url: "https://pub.dartlang.org" + sha256: ab0987bf95bc591da42dffb38c77398fc43309f0b9b894dcc5d6f40c4b26c379 + url: "https://pub.dev" source: hosted version: "2.1.7" path_provider_platform_interface: dependency: transitive description: name: path_provider_platform_interface - url: "https://pub.dartlang.org" + sha256: f0abc8ebd7253741f05488b4813d936b4d07c6bae3e86148a09e342ee4b08e76 + url: "https://pub.dev" source: hosted version: "2.0.5" path_provider_windows: dependency: transitive description: name: path_provider_windows - url: "https://pub.dartlang.org" + sha256: "1cb68ba4cd3a795033de62ba1b7b4564dace301f952de6bfb3cd91b202b6ee96" + url: "https://pub.dev" source: hosted - version: "2.0.7" + version: "2.1.7" petitparser: dependency: transitive description: name: petitparser - url: "https://pub.dartlang.org" + sha256: "1a914995d4ef10c94ff183528c120d35ed43b5eaa8713fc6766a9be4570782e2" + url: "https://pub.dev" source: hosted version: "4.4.0" platform: dependency: transitive description: name: platform - url: "https://pub.dartlang.org" + sha256: "4a451831508d7d6ca779f7ac6e212b4023dd5a7d08a27a63da33756410e32b76" + url: "https://pub.dev" source: hosted version: "3.1.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" + version: "2.1.8" pointycastle: dependency: transitive description: name: pointycastle - url: "https://pub.dartlang.org" + sha256: "7c1e5f0d23c9016c5bbd8b1473d0d3fb3fc851b876046039509e18e0c7485f2c" + url: "https://pub.dev" source: hosted version: "3.7.3" process: dependency: transitive description: name: process - url: "https://pub.dartlang.org" + sha256: "53fd8db9cec1d37b0574e12f07520d582019cb6c44abf5479a01505099a34a09" + url: "https://pub.dev" source: hosted version: "4.2.4" provider: dependency: "direct main" description: name: provider - url: "https://pub.dartlang.org" + sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272" + url: "https://pub.dev" source: hosted version: "6.1.5+1" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" shared_preferences: dependency: "direct main" description: name: shared_preferences - url: "https://pub.dartlang.org" + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf + url: "https://pub.dev" source: hosted - version: "2.0.17" + version: "2.5.5" shared_preferences_android: dependency: transitive description: name: shared_preferences_android - url: "https://pub.dartlang.org" + sha256: "0634e64bd719f89c012f392938e173521f535d3ecaf66558fa94a056d22b5cc7" + url: "https://pub.dev" source: hosted - version: "2.0.15" + version: "2.4.27" shared_preferences_foundation: dependency: transitive description: name: shared_preferences_foundation - url: "https://pub.dartlang.org" + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.dev" source: hosted - version: "2.1.2" + version: "2.5.6" 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: d5f89a9e52b36240a80282b3dc0667dd36e53459717bb17b8fb102d30496606a + url: "https://pub.dev" source: hosted version: "1.8.1" sqflite: dependency: "direct main" description: name: sqflite - url: "https://pub.dartlang.org" + sha256: "58a799e6ac17dd32fbab93813d39ed835a75ccc0f8f85b8955fe318c6712b082" + url: "https://pub.dev" source: hosted - version: "2.0.2+1" + version: "2.4.3" + sqflite_android: + dependency: transitive + description: + name: sqflite_android + sha256: d0548f9d7422a2dae99ec6f8b0a3074463b132d216fa5ba0d230eeefc901983b + url: "https://pub.dev" + source: hosted + version: "2.4.3" sqflite_common: dependency: transitive description: name: sqflite_common - url: "https://pub.dartlang.org" + sha256: "5bf6a55c166e73bf651ba7ec3ed486e577620e3dc8f3a9c6a258a8031b624590" + url: "https://pub.dev" source: hosted - version: "2.4.0" + version: "2.5.11" sqflite_common_ffi: dependency: "direct main" description: name: sqflite_common_ffi - url: "https://pub.dartlang.org" + sha256: "5ccd38136edb9beb3213f6927775d52db70dfdadcdb28dad1f625ca9f2b9824f" + url: "https://pub.dev" source: hosted - version: "2.1.1+1" + version: "2.4.2" + sqflite_darwin: + dependency: transitive + description: + name: sqflite_darwin + sha256: c86ca18b8f666bbf903924687fe21cc16fc385d086005067e26619ca530bef9f + url: "https://pub.dev" + source: hosted + version: "2.4.3+1" + sqflite_platform_interface: + dependency: transitive + description: + name: sqflite_platform_interface + sha256: f84939f84350d92d04416f8bc4dc52d3896aec7716cc9e80cf0146342139dc50 + url: "https://pub.dev" + source: hosted + version: "2.4.1" sqlite3: dependency: transitive description: name: sqlite3 - url: "https://pub.dartlang.org" + sha256: c73fd75df1332d76a6257f4823ae4df9c791f522b97e4a60cbcad214de1becf4 + url: "https://pub.dev" source: hosted - version: "1.7.0" + version: "3.5.0" 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: "61894a1956de6b4fc1aefd0892e109514a1a706cbece3ac59decd90ff5a7a423" + url: "https://pub.dev" source: hosted - version: "3.0.0+3" + version: "3.4.1+1" term_glyph: dependency: transitive description: name: term_glyph - url: "https://pub.dartlang.org" + sha256: a88162591b02c1f3a3db3af8ce1ea2b374bd75a7bb8d5e353bcfbdc79d719830 + url: "https://pub.dev" source: hosted version: "1.2.0" 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: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.dev" + source: hosted + version: "15.2.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: bd512f03919aac5f1313eb8249f223bacf4927031bf60b02601f81f687689e86 + url: "https://pub.dev" source: hosted version: "0.2.0+3" xml: dependency: transitive description: name: xml - url: "https://pub.dartlang.org" + sha256: baa23bcba1ba4ce4b22c0c7a1d9c861e7015cb5169512676da0b85138e72840c + url: "https://pub.dev" source: hosted version: "5.3.1" yaml: dependency: transitive description: name: yaml - url: "https://pub.dartlang.org" + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "3.1.3" 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" diff --git a/pubspec.yaml b/pubspec.yaml index 20319da..550c124 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,7 +4,7 @@ publish_to: 'none' version: 1.0.1+2 environment: - sdk: ">=2.17.0-69.2.beta <3.0.0" + sdk: ">=3.3.0 <4.0.0" dependencies: flutter: @@ -12,12 +12,12 @@ dependencies: cupertino_icons: ^1.0.2 provider: ^6.0.2 intl: ^0.17.0 - sqflite: ^2.0.2+1 - sqflite_common_ffi: ^2.1.0 + sqflite: ^2.4.3 + sqflite_common_ffi: ^2.4.2 path: ^1.8.1 - mobile_scanner: ^0.2.0 + mobile_scanner: ^7.4.0 http: ^0.13.0 - shared_preferences: ^2.0.0 + shared_preferences: ^2.5.5 crypto: ^3.0.0 dev_dependencies: diff --git a/scripts/generate_store_assets.py b/scripts/generate_store_assets.py new file mode 100644 index 0000000..abdc4e4 --- /dev/null +++ b/scripts/generate_store_assets.py @@ -0,0 +1,119 @@ +import os +from PIL import Image, ImageDraw, ImageFont, ImageFilter + +def create_icon(): + src_icon_path = 'assets/icon/icon.png' + dest_icon_path = 'store_listing/graficos/icono_512.png' + + im = Image.open(src_icon_path).convert('RGBA') + # Resize with high quality Lanczos filter + im_512 = im.resize((512, 512), Image.Resampling.LANCZOS) + + # Google Play Store expects a 512x512 icon without transparent margins + # We create a solid background if transparent, or save as RGB + bg = Image.new('RGB', (512, 512), (13, 45, 107)) # #0D2D6B brand primary + bg.paste(im_512, (0, 0), im_512) + bg.save(dest_icon_path, 'PNG', optimize=True) + print(f"Icon created: {dest_icon_path} (512x512)") + +def create_feature_graphic(): + dest_path = 'store_listing/graficos/grafico_destacado_1024x500.png' + w, h = 1024, 500 + + # Gradient background: Navy Blue (#0A1E3C to #0D2D6B) + img = Image.new('RGB', (w, h), (10, 30, 60)) + draw = ImageDraw.Draw(img) + + for y in range(h): + # Subtle vertical gradient + r = int(10 + (13 - 10) * (y / h)) + g = int(30 + (45 - 30) * (y / h)) + b = int(60 + (107 - 60) * (y / h)) + draw.line([(0, y), (w, y)], fill=(r, g, b)) + + # Add subtle geometric / modern tech diagonal accent lines + accent_color = (25, 118, 210, 40) # #1976D2 + overlay = Image.new('RGBA', (w, h), (0, 0, 0, 0)) + overlay_draw = ImageDraw.Draw(overlay) + + overlay_draw.polygon([(650, 0), (1024, 0), (1024, 500), (450, 500)], fill=(20, 60, 120, 45)) + overlay_draw.polygon([(780, 0), (1024, 0), (1024, 500), (620, 500)], fill=(25, 118, 210, 35)) + overlay_draw.line([(450, 500), (650, 0)], fill=(25, 118, 210, 100), width=2) + + img = Image.alpha_composite(img.convert('RGBA'), overlay).convert('RGB') + draw = ImageDraw.Draw(img) + + # Load and place app icon on the left + icon_src = Image.open('assets/icon/icon.png').convert('RGBA') + icon_size = 280 + icon_resized = icon_src.resize((icon_size, icon_size), Image.Resampling.LANCZOS) + + # Icon card with rounded corners and drop shadow + mask = Image.new('L', (icon_size, icon_size), 0) + mask_draw = ImageDraw.Draw(mask) + mask_draw.rounded_rectangle([(0, 0), (icon_size, icon_size)], radius=56, fill=255) + + icon_x = 75 + icon_y = (h - icon_size) // 2 + + # Shadow + shadow = Image.new('RGBA', (w, h), (0, 0, 0, 0)) + s_draw = ImageDraw.Draw(shadow) + s_draw.rounded_rectangle( + [(icon_x - 6, icon_y + 12), (icon_x + icon_size + 6, icon_y + icon_size + 24)], + radius=60, + fill=(0, 0, 0, 140) + ) + shadow = shadow.filter(ImageFilter.GaussianBlur(16)) + img = Image.alpha_composite(img.convert('RGBA'), shadow).convert('RGB') + + # Paste rounded icon + img.paste(icon_resized, (icon_x, icon_y), mask) + + # Draw Text Typography + draw = ImageDraw.Draw(img) + + font_path_bold = '/usr/share/fonts/truetype/roboto/unhinted/RobotoTTF/Roboto-Bold.ttf' + font_path_reg = '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf' + if not os.path.exists(font_path_bold): + font_path_bold = '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf' + if not os.path.exists(font_path_reg): + font_path_reg = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' + + title_font = ImageFont.truetype(font_path_bold, 50) + badge_font = ImageFont.truetype(font_path_bold, 18) + sub_font = ImageFont.truetype(font_path_reg, 22) + pill_font = ImageFont.truetype(font_path_bold, 15) + + text_x = icon_x + icon_size + 60 + + # Badge pill + badge_y = icon_y + 15 + draw.rounded_rectangle([(text_x, badge_y), (text_x + 190, badge_y + 32)], radius=16, fill=(25, 118, 210)) + draw.text((text_x + 14, badge_y + 5), "SIGMAC · CLOUD", font=badge_font, fill=(255, 255, 255)) + + # Main Title + title_y = badge_y + 44 + draw.text((text_x, title_y), "AGENTE VENTAS", font=title_font, fill=(255, 255, 255)) + + # Subtitle + sub_y = title_y + 64 + draw.text((text_x, sub_y), "Gestión de Pedidos, Rutas y Preventa en Campo", font=sub_font, fill=(170, 187, 204)) + + # Feature pills (Offline First, Firma Digital, Lector Barcode) + pills = ["⚡ 100% Fuera de Línea", "✍ Firma Digital", "📦 Stock en Tiempo Real"] + pill_x = text_x + pill_y = sub_y + 45 + for p in pills: + bbox = draw.textbbox((0, 0), p, font=pill_font) + pw = bbox[2] - bbox[0] + 24 + draw.rounded_rectangle([(pill_x, pill_y), (pill_x + pw, pill_y + 30)], radius=12, fill=(22, 53, 88), outline=(30, 64, 112)) + draw.text((pill_x + 12, pill_y + 6), p, font=pill_font, fill=(220, 235, 255)) + pill_x += pw + 12 + + img.save(dest_path, 'PNG', optimize=True) + print(f"Feature graphic created: {dest_path} (1024x500)") + +if __name__ == '__main__': + create_icon() + create_feature_graphic() diff --git a/scripts/process_screenshots.py b/scripts/process_screenshots.py new file mode 100644 index 0000000..3f2cc91 --- /dev/null +++ b/scripts/process_screenshots.py @@ -0,0 +1,43 @@ +import os +from PIL import Image + +def process_screenshots(): + raw_files = [ + ('/tmp/raw_01_login.png', 'store_listing/graficos/01_login.png'), + ('/tmp/raw_02_inicio.png', 'store_listing/graficos/02_inicio.png'), + ('/tmp/raw_03_ruta.png', 'store_listing/graficos/03_ruta.png'), + ('/tmp/raw_04_pedidos.png', 'store_listing/graficos/04_pedidos.png'), + ('/tmp/raw_05_catalogo.png', 'store_listing/graficos/05_catalogo.png'), + ('/tmp/raw_06_perfil.png', 'store_listing/graficos/06_perfil.png'), + ] + + # Mathematical crop: (0, 152, 1344, 152 + 2688) + # Removes top status bar (152px) and bottom system bar (152px) symmetrically + crop_box = (0, 152, 1344, 152 + 2688) + + for src, dest in raw_files: + if not os.path.exists(src): + print(f"File not found: {src}") + continue + + im = Image.open(src) + w, h = im.size + print(f"Processing {src}: original size {w}x{h}") + + # Crop to exact 2:1 aspect ratio + cropped = im.crop(crop_box) + # Convert to RGB (no unnecessary alpha channel for store screenshots) + if cropped.mode == 'RGBA': + bg = Image.new('RGB', cropped.size, (255, 255, 255)) + bg.paste(cropped, mask=cropped.split()[3]) + cropped = bg + else: + cropped = cropped.convert('RGB') + + cropped.save(dest, 'PNG', optimize=True) + cw, ch = cropped.size + ratio = ch / cw + print(f"Saved: {dest} ({cw}x{ch}, aspect ratio {ratio:.2f}:1)") + +if __name__ == '__main__': + process_screenshots() diff --git a/store_listing/ficha_tienda.md b/store_listing/ficha_tienda.md new file mode 100644 index 0000000..d7ddaab --- /dev/null +++ b/store_listing/ficha_tienda.md @@ -0,0 +1,164 @@ +# Ficha Técnica de Publicación — Agente Ventas SIGMAC +*Documento maestro para consolas de distribución (Google Play Console & Apple App Store Connect)* + +--- + +## 1. Ficha Principal de la Aplicación + +### Nombre de la App (Máx. 30 caracteres) +```text +Agente Ventas - SIGMAC +``` +*(Longitud: 22 / 30 caracteres)* + +### Descripción Breve (Máx. 80 caracteres) +```text +Gestión de pedidos, rutas de venta y catálogo comercial en campo. +``` +*(Longitud: 65 / 80 caracteres)* + +### Descripción Completa (Máx. 4000 caracteres) +```text +Agente Ventas — SIGMAC es la solución móvil integral diseñada para vendedores de campo, preventistas y agentes comerciales que necesitan gestionar su ciclo diario de ventas con máxima eficiencia, incluso en zonas sin cobertura de internet. + +Optimizada para operar tanto en línea como fuera de línea (offline-first), la aplicación sincroniza la información con el ecosistema empresarial SIGMAC Central Cloud cuando hay red disponible, garantizando continuidad operativa en cualquier escenario. + +MÓDULOS Y FUNCIONALIDADES PRINCIPALES: + +1. TABLERO DE CONTROL Y RESUMEN DIARIO +• Visualización en tiempo real del desempeño de ventas del día. +• Conteo de pedidos generados, monto total acumulado y porcentaje de efectividad de ruta. +• Alertas instantáneas y notificaciones sobre promociones y novedades comerciales. + +2. GESTIÓN INTELIGENTE DE RUTAS DE VISITA +• Hoja de ruta planificada para la jornada con clientes asignados. +• Secuencia óptima de visitas con estados: Pendiente, Visitado y No visitado. +• Registro de motivos de no compra o reprogramación de visita con notas de campo. +• Vista esquemática de ruta y geolocalización de clientes comerciales. + +3. CATÁLOGO DIGITAL Y CONTROL DE EXISTENCIAS +• Catálogo visual de productos clasificados por familias y categorías. +• Consulta inmediata de precios de lista, precios mayoristas y existencias disponibles. +• Búsqueda por texto predictivo y filtro por categoría. +• Lector integrado de código de barras mediante cámara para captura rápida de productos. + +4. TOMA DE PEDIDOS Y FACTURACIÓN PREVENTA +• Creación de pedidos ágil con selector de clientes registrados o alta de nuevos clientes. +• Canasta de compras con cálculo automático de subtotales, descuentos e impuestos. +• Captura de firma digital manuscrita en pantalla para confirmación y conformidad del cliente. +• Soporte multimoneda configurable según la región de operación. + +5. ARQUITECTURA OFFLINE-FIRST Y SINCRONIZACIÓN CLOUD +• Base de datos local de alto rendimiento (SQLite) que almacena catálogo, clientes y pedidos. +• Operación 100% funcional sin conexión a internet durante toda la jornada. +• Sincronización automática o manual bidireccional mediante TLS/HTTPS al restablecerse la red. +• Bandeja de auditoría con estado de envío de cada pedido (Pendiente / Sincronizado). + +6. ALERTAS OPERATIVAS Y MENSAJERÍA VÍA WHATSAPP +• Vinculación opcional de número móvil con formateo internacional y normalización regex. +• Recepción automática de alertas de nuevos pedidos generados en campo. +• Comunicación integrada a través del Gateway empresarial Sigma-Robot. + +SEGURIDAD Y CONTROL DE ACCESO +• Autenticación cifrada mediante tokens JWT de sesión. +• Soporte para trabajo con tenencia corporativa aislada (multi-tenant). +• Protección de datos comerciales confidenciales en almacenamiento seguro del dispositivo. + +Impulsa la productividad comercial de tu equipo de ventas con Agente Ventas SIGMAC. +``` +*(Longitud: ~2,550 / 4,000 caracteres)* + +--- + +## 2. Categorización y Declaraciones + +### Categoría y Etiquetas +* **Categoría Principal (Google Play):** Empresa / Negocios (`Business`). +* **Categoría Secundaria / Alternativa:** Productividad (`Productivity`). +* **Categoría Principal (Apple App Store):** Business / Negocios. +* **Etiquetas Sugeridas (Tags):** + * Ventas + * Productividad + * Preventa + * Gestión Comercial + * Toma de Pedidos + +### Clasificación de Contenido (IARC) +* **Clasificación Global:** Apta para todo público (PEGI 3 / Everyone / ESRB Everyone). +* **Violencia / Lenguaje inapropiado / Contenido para adultos:** Ninguno (No). +* **Compras integradas (IAP):** No contiene compras dentro de la aplicación. Las cuentas son provistas corporativamente por la empresa o contratante. + +### Declaración de Anuncios +* **¿Contiene anuncios publicitarios?:** **NO.** La aplicación no integra redes publicitarias de terceros (como AdMob o Facebook Audience Network). Los banners internos corresponden exclusivamente a notificaciones operativas o avisos del sistema corporativo. + +### Declaración de Seguridad de los Datos (Data Safety / Privacy Nutrition Labels) + +| Tipo de Dato | Finalidad | ¿Es obligatorio? | ¿Se comparte con terceros? | ¿Cifrado en tránsito? | +| :--- | :--- | :--- | :--- | :--- | +| **Nombre y Correo** | Identificación del usuario en la sesión de preventa | Sí | No | Sí (HTTPS/TLS) | +| **Teléfono y Contacto** | Identificación de cliente comercial y vendedor | Opcional | No | Sí (HTTPS/TLS) | +| **ID de Usuario** | Gestión de autenticación, control de auditoría | Sí | No | Sí (HTTPS/TLS) | +| **Cámara** | Escáner de código de barras para búsqueda de productos | Opcional | No | N/A (Procesamiento local) | +| **Ubicación (Coordenadas de cliente)** | Visualización referencial de visitas en ruta comercial | Opcional | No | Sí (HTTPS/TLS) | +| **Firma Digital** | Constancia de conformidad del pedido comercial | Opcional | No | Sí (HTTPS/TLS) | + +* **Prácticas de seguridad:** + * Todos los datos transmitidos entre el cliente y el servidor se transfieren a través de una conexión cifrada HTTPS/TLS estándar de la industria. + * Los usuarios pueden solicitar la eliminación de su cuenta y datos asociados contactando a los canales de soporte corporativo señalados en la Política de Privacidad. + +--- + +## 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 demo precargado y desacoplado de dependencias externas para garantizar una prueba fluida, completa y sin bloqueos de red. + +### Credenciales Fijas de Evaluación: +* **Método 1 (Automático con un solo toque):** + 1. Abrir la aplicación. + 2. En la pantalla inicial de bienvenida, pulsar el enlace inferior: **"Acceso Demo (Revisión de Tienda)"**. + 3. El sistema autocompletará las credenciales y accederá inmediatamente al sistema con datos de prueba cargados. + +* **Método 2 (Ingreso Manual):** + * **Correo / Usuario:** `demo@empresa.com` (o usuario: `demo`) + * **Contraseña:** `123456` + * **Modo seleccionado:** Puede probarse tanto en modo **Cloud** como en modo **Cuenta local**; ambos están configurados para responder de inmediato. + * Presionar el botón **INGRESAR**. + +### Flujo Sugerido de Prueba para el Revisor: +1. **Inicio:** Revisar los indicadores de resumen comercial del día y métricas de venta. +2. **Mi Ruta:** Observar las paradas asignadas en la ruta comercial diaria y el mapa esquemático de visitas. +3. **Catálogo:** Navegar entre las categorías de productos, verificar stock y precios. (Opcional: probar el botón de escáner de código de barras). +4. **Pedidos:** Ver los pedidos existentes, presionar el botón `+` para crear un nuevo pedido, seleccionar un cliente, agregar productos al carrito y capturar la firma digital de recepción. +5. **Perfil:** Inspeccionar los datos del vendedor y verificar el estado del sincronizador. + +--- + +## 4. Notas de la Versión (What's New / Release Notes) + +```text +Lanzamiento oficial de Agente Ventas SIGMAC v1.0.1: +- Gestión completa de pedidos de preventa con firma digital del cliente. +- Hoja de ruta diaria con clientes y estados de visita. +- Catálogo interactivo de productos con control de existencias y precios. +- Escáner de código de barras integrado mediante cámara. +- Modo fuera de línea (offline-first) con sincronización inteligente en la nube. +- Mejoras de rendimiento, estabilidad y seguridad en comunicaciones cifradas. +``` +*(Longitud: 468 / 500 caracteres)* + +--- + +## 5. Checklist de Pre-Lanzamiento y Publicación + +- [x] **Identificador de paquete Android:** `com.sigmac.agenteventas` configurado en `android/app/build.gradle`. +- [x] **Permisos de red:** `android.permission.INTERNET` verificado en `android/app/src/main/AndroidManifest.xml`. +- [x] **Permisos de cámara:** `android.permission.CAMERA` con `android.hardware.camera required="false"` para máxima compatibilidad con tabletas y dispositivos sin cámara trasera. +- [x] **Autenticación Demo de Tienda:** Credenciales fijas (`demo@empresa.com` / `123456`) y botón de acceso rápido implementados en el código. +- [x] **Poblado de datos locales:** Seeder automático en SQLite con clientes, catálogo con existencias, rutas y pedidos para evitar pantallas vacías. +- [x] **Ficha descriptiva:** Textos de marketing, fichas corta y larga optimizados dentro de los límites de caracteres de la tienda. +- [x] **Política de privacidad:** Archivo estático responsive creado en `store_listing/politica_privacidad.html`. +- [x] **Firma de producción (Keystore Android):** Soporte y plantilla listos en `android/app/build.gradle` y `android/key.properties.example` (listo para inyectar keystore corporativo). +- [x] **Homologación de Bundle ID en iOS / macOS:** `PRODUCT_BUNDLE_IDENTIFIER` homologado a `com.sigmac.agenteventas` y `NSCameraUsageDescription` configurado en `Info.plist`. +- [x] **Generación de gráficos y capturas:** Ícono 512×512, gráfico destacado 1024×500 y 6 capturas ordenadas en relación 2:1 (1344×2688) en `store_listing/graficos/`. +- [x] **Notificaciones Operativas por WhatsApp:** Módulo de perfil con regex de código de país y Gateway Sigma-Robot operativo. diff --git a/store_listing/graficos/01_login.png b/store_listing/graficos/01_login.png new file mode 100644 index 0000000..982001a Binary files /dev/null and b/store_listing/graficos/01_login.png differ diff --git a/store_listing/graficos/02_inicio.png b/store_listing/graficos/02_inicio.png new file mode 100644 index 0000000..70566a2 Binary files /dev/null and b/store_listing/graficos/02_inicio.png differ diff --git a/store_listing/graficos/03_ruta.png b/store_listing/graficos/03_ruta.png new file mode 100644 index 0000000..26a6607 Binary files /dev/null and b/store_listing/graficos/03_ruta.png differ diff --git a/store_listing/graficos/04_pedidos.png b/store_listing/graficos/04_pedidos.png new file mode 100644 index 0000000..85ccfaf Binary files /dev/null and b/store_listing/graficos/04_pedidos.png differ diff --git a/store_listing/graficos/05_catalogo.png b/store_listing/graficos/05_catalogo.png new file mode 100644 index 0000000..078570b Binary files /dev/null and b/store_listing/graficos/05_catalogo.png differ diff --git a/store_listing/graficos/06_perfil.png b/store_listing/graficos/06_perfil.png new file mode 100644 index 0000000..9edccd0 Binary files /dev/null and b/store_listing/graficos/06_perfil.png differ diff --git a/store_listing/graficos/grafico_destacado_1024x500.png b/store_listing/graficos/grafico_destacado_1024x500.png new file mode 100644 index 0000000..e927910 Binary files /dev/null and b/store_listing/graficos/grafico_destacado_1024x500.png differ diff --git a/store_listing/graficos/icono_512.png b/store_listing/graficos/icono_512.png new file mode 100644 index 0000000..48ef2bc Binary files /dev/null and b/store_listing/graficos/icono_512.png differ diff --git a/store_listing/politica_privacidad.html b/store_listing/politica_privacidad.html new file mode 100644 index 0000000..91a8d16 --- /dev/null +++ b/store_listing/politica_privacidad.html @@ -0,0 +1,318 @@ + + + + + + Política de Privacidad — Agente Ventas SIGMAC + + + + +
+
+ Documento Oficial +

Política de Privacidad

+

Aplicación: Agente Ventas — SIGMAC | Última actualización: Octubre 2026

+
+ +
+

1. Introducción y Alcance

+

+ La presente Política de Privacidad describe cómo SIGMAC / Telcotronics ("nosotros", "nuestro" o "la Empresa") recopila, utiliza, almacena y protege la información suministrada al utilizar la aplicación móvil Agente Ventas ("la Aplicación"). +

+

+ La Aplicación está diseñada exclusivamente como una herramienta corporativa de productividad, preventa y gestión logística de rutas de venta para usuarios autorizados por empresas comerciales. +

+
+ +
+

2. Información que Recopilamos

+

Para brindar las funcionalidades comerciales de la Aplicación, se procesan las siguientes categorías de datos:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CategoríaDatos EspecíficosFinalidad Primaria
Datos de CuentaNombre, correo electrónico, identificador de usuario y empresa asignada.Autenticación de sesión y registro de auditoría en la plataforma.
Datos ComercialesCatálogo de productos, clientes comerciales asignados, pedidos registrados y observaciones de visita.Operación del ciclo de preventa, cálculo de pedidos y control de existencias.
Firma ManuscritaTrazo digital capturado en pantalla como imagen base64.Constancia de conformidad y recepción del pedido comercial por parte del cliente.
Permiso de CámaraAcceso al hardware de cámara del dispositivo móvil.Escaneo óptico de códigos de barras (EAN/QR) para identificación ágil de productos. Las imágenes no se almacenan en servidores.
Ubicación ReferencialCoordenadas de latitud y longitud asociadas a clientes de la cartera comercial.Representación y ordenamiento esquemático de la hoja de ruta diaria.
Teléfono y Alertas WhatsAppNúmero de teléfono móvil suministrado voluntariamente por el usuario agente.Envío de confirmaciones operativas de pedidos y resúmenes de venta vía WhatsApp a través del Gateway empresarial Sigma-Robot.
+
+ +
+

3. Arquitectura Fuera de Línea (Offline-First) y Almacenamiento Local

+

+ La Aplicación almacena información estructurada (catálogo, clientes, pedidos temporales) de manera local en el almacenamiento seguro del dispositivo móvil mediante SQLite. +

+
+ Aviso de sincronización: Los datos registrados mientras el dispositivo carece de conexión a internet permanecen en el almacenamiento interno de la aplicación hasta que el usuario establece conexión y ejecuta la sincronización con el servidor central mediante el protocolo seguro HTTPS/TLS. +
+
+ +
+

4. Finalidad del Tratamiento de Datos

+

Utilizamos la información exclusivamente para los siguientes fines legítimos:

+
    +
  • Validar la identidad del agente de ventas en el sistema corporativo.
  • +
  • Permitir la creación, edición y transmisión de pedidos a los sistemas de facturación de la empresa.
  • +
  • Organizar y dar seguimiento a las rutas de visita y cobertura geográfica de clientes.
  • +
  • Generar reportes estadísticos internos de volumen de ventas para el usuario.
  • +
  • Despachar notificaciones operativas y confirmaciones de pedidos vía WhatsApp a los agentes que vinculen voluntariamente su número telefónico.
  • +
+

+ No comercializamos datos: En ningún caso vendemos, alquilamos ni compartimos la información personal o comercial de los usuarios con redes publicitarias de terceros o entidades no autorizadas. +

+
+ +
+

5. Seguridad de la Información

+

+ Implementamos medidas de seguridad técnicas y administrativas reconocidas para proteger los datos: +

+
    +
  • Cifrado en tránsito: Toda comunicación entre la Aplicación y el servidor en la nube se ejecuta a través de canales cifrados HTTPS utilizando certificados TLS estándar.
  • +
  • Autenticación robusta: Uso de identificadores y credenciales de sesión encriptadas.
  • +
  • Acceso restringido: Solo el personal autorizado de la empresa correspondiente tiene acceso a los reportes consolidados de preventa.
  • +
+
+ +
+

6. Conservación de los Datos y Eliminación de Cuentas

+

+ Los datos se conservan durante el período necesario para cumplir con los objetivos comerciales y los requerimientos legales o fiscales aplicables. +

+

+ Los usuarios o empresas que deseen revocar el acceso, solicitar la rectificación o la supresión definitiva de su cuenta y registros vinculados pueden solicitarlo formalmente enviando un correo a soporte@telcotronics.net con el asunto "Solicitud de Supresión de Datos — Agente Ventas". +

+
+ +
+

7. Privacidad de Menores

+

+ La Aplicación está dirigida exclusivamente a profesionales y personal comercial corporativo en edad laboral legal. No recopilamos intencionalmente información de personas menores de 18 años. +

+
+ +
+

8. Cambios a esta Política

+

+ Podemos actualizar periódicamente esta Política de Privacidad para reflejar modificaciones en la legislación o en los servicios de la Aplicación. Toda actualización sustancial se notificará en este documento y dentro de las notas de versión de la tienda de aplicaciones. +

+
+ +
+

9. Contacto y Consultas

+

+ Para preguntas, solicitudes de derechos o comentarios relacionados con esta Política de Privacidad, contáctenos en: +

+ +
+ + +
+ + + diff --git a/test/phone_utils_test.dart b/test/phone_utils_test.dart new file mode 100644 index 0000000..834e5aa --- /dev/null +++ b/test/phone_utils_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:agente_ventas/utils/phone_utils.dart'; + +void main() { + group('PhoneUtils Regex y Normalización WhatsApp', () { + test('Normaliza número local con 0 inicial (Ecuador)', () { + final res = PhoneUtils.normalizarWhatsApp('0991234567'); + expect(res, '593991234567'); + expect(PhoneUtils.esWhatsAppValido(res), isTrue); + }); + + test('Limpia caracteres especiales, espacios y guiones', () { + final res = PhoneUtils.normalizarWhatsApp('+593 99-123.4567'); + expect(res, '593991234567'); + expect(PhoneUtils.esWhatsAppValido(res), isTrue); + }); + + test('Mantiene código internacional si ya está presente', () { + final res = PhoneUtils.normalizarWhatsApp('593987654321'); + expect(res, '593987654321'); + expect(PhoneUtils.esWhatsAppValido(res), isTrue); + }); + + test('Soporta otros países como Colombia (57)', () { + final res = PhoneUtils.normalizarWhatsApp('3001234567', pais: '57'); + expect(res, '573001234567'); + expect(PhoneUtils.esWhatsAppValido(res), isTrue); + }); + + test('Valida formato internacional de 10 a 15 dígitos', () { + expect(PhoneUtils.esWhatsAppValido('593991234567'), isTrue); + expect(PhoneUtils.esWhatsAppValido('123'), isFalse); + expect(PhoneUtils.esWhatsAppValido(''), isFalse); + }); + + test('Formatea visualmente de forma limpia', () { + final visual = PhoneUtils.formatearVisual('593991234567'); + expect(visual, '+593 99 123 4567'); + }); + }); +}