feat: suite de tiendas, sync reactivo, bitácora de errores y alertas whatsapp

This commit is contained in:
Pablinux
2026-11-22 17:41:18 -05:00
parent cc4ab12d1d
commit 6a5ebb907d
76 changed files with 2975 additions and 312 deletions
+10
View File
@@ -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(
+17 -3
View File
@@ -182,13 +182,16 @@ class DatabaseHelper {
Future<Map<String, dynamic>?> 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<void> 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<List<Cliente>> getClientes() async {
+3
View File
@@ -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);
+4
View File
@@ -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<NavigatorState>();
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,
+34
View File
@@ -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>[
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,
);
}
}
+19
View File
@@ -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,
);
}
}
+236 -5
View File
@@ -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<Pedido> _pedidos = [];
List<Producto> _productos = [];
@@ -49,6 +81,9 @@ class AppProvider extends ChangeNotifier {
final List<ItemPedido> _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<Cliente> 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<void> _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<void> 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<void> 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<SyncSummary> 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<bool> 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() {
+81
View File
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="48"
height="48"
viewBox="0 0 48 48"
version="1.1"
id="svg1"
inkscape:version="1.4.3 (1:1.4.3+202512261035+0d15f75042)"
sodipodi:docname="logo_pedidos.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview1"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:document-units="px"
inkscape:zoom="5.347495"
inkscape:cx="46.376855"
inkscape:cy="46.283353"
inkscape:window-width="1920"
inkscape:window-height="1011"
inkscape:window-x="0"
inkscape:window-y="32"
inkscape:window-maximized="1"
inkscape:current-layer="layer1" />
<defs
id="defs1" />
<g
inkscape:label="Capa 1"
inkscape:groupmode="layer"
id="layer1">
<circle
style="fill:#00ffff;stroke-width:0.273123"
id="path103-46-4-7-6"
cx="23.945089"
cy="23.897419"
r="23.037413"
inkscape:export-filename="ICONOS_MARCAS64/PEDIDOS64.png"
inkscape:export-xdpi="18.062223"
inkscape:export-ydpi="18.062223" />
<circle
style="fill:#000000;stroke-width:0.257519"
id="path103-4-9-9-6-3"
cx="24.356398"
cy="23.003456"
r="21.720993" />
<path
style="fill:#ffffff;stroke-width:0.724619"
d="m 14.653544,41.66314 c -0.03604,-0.04766 -0.156948,-0.08664 -0.268639,-0.08664 -0.243663,0 -0.899041,-0.294647 -1.43084,-0.643317 -0.426078,-0.279325 -1.217815,-1.178128 -1.217815,-1.382474 0,-0.07118 -0.04765,-0.15367 -0.106129,-0.183097 -0.136051,-0.06867 -0.147586,-32.55007 -0.01176,-32.766575 0.05203,-0.08271 0.207107,-0.342878 0.344773,-0.57812 0.460322,-0.786637 1.454447,-1.4255063 2.750795,-1.7677848 0.274602,-0.072575 2.94263,-0.099979 9.699085,-0.099979 9.165235,0 9.636499,0.012391 10.262121,0.2705021 0.101319,0.041825 0.256476,0.076018 0.344767,0.076018 0.08831,0 0.160575,0.039061 0.160575,0.08663 0,0.047714 0.06855,0.086627 0.152198,0.086627 0.28606,0 1.317456,0.9448867 1.64716,1.5089807 l 0.322304,0.551455 v 16.209795 16.209786 l -0.313814,0.565148 c -0.464092,0.835772 -1.868415,1.856514 -2.554216,1.856514 -0.10768,0 -0.225374,0.03885 -0.261415,0.08662 -0.04288,0.05674 -3.411368,0.08663 -9.75968,0.08663 -6.348297,0 -9.716721,-0.02985 -9.759658,-0.08663 z m 10.972231,-0.970079 c 0.617738,-0.269247 1.174305,-0.733696 1.174305,-0.979936 0,-0.0709 0.04765,-0.128943 0.106126,-0.128943 0.06394,0 0.106129,-0.360939 0.106129,-0.909558 0,-0.548603 -0.04211,-0.909543 -0.106129,-0.909543 -0.05833,0 -0.106126,-0.06356 -0.106126,-0.141337 0,-0.250191 -0.90409,-0.897962 -1.502616,-1.07661 -0.60303,-0.179979 -1.413319,-0.22335 -1.520745,-0.08141 -0.03612,0.04771 -0.161589,0.08662 -0.278891,0.08662 -0.322009,0 -1.10212,0.475405 -1.382355,0.842412 -0.293223,0.383982 -0.50962,0.920826 -0.511872,1.269817 -0.0023,0.611264 0.519703,1.47144 1.110497,1.824195 0.551103,0.329035 0.754582,0.377849 1.609512,0.386255 0.701357,0.0066 0.947908,-0.02749 1.302165,-0.18197 z m 9.846969,-17.644746 c 0.01992,-9.236185 -0.0054,-12.625859 -0.09264,-12.71203 -0.09909,-0.09754 -1.956351,-0.117511 -10.918237,-0.117511 -5.939365,0 -10.874334,0.0237 -10.96663,0.05269 -0.15196,0.04766 -0.167814,1.244983 -0.167814,12.675932 0,6.942816 0.03204,12.649486 0.07116,12.681457 0.03912,0.032 5.015823,0.04828 11.059192,0.03609 l 10.987972,-0.02201 z M 21.156436,7.862611 c 0.175506,-0.143315 0.160029,-0.661304 -0.02421,-0.811769 -0.342112,-0.279367 -1.015374,-0.03594 -1.015374,0.367265 0,0.33573 0.228002,0.548454 0.587759,0.548454 0.178512,0 0.381829,-0.04674 0.451854,-0.103996 z m 5.7285,0 C 27.060457,7.719296 27.044971,7.201307 26.860726,7.050842 26.738569,6.951052 26.25659,6.927074 24.375474,6.927074 h -2.333715 l -0.219857,0.228247 c -0.264664,0.274753 -0.268653,0.32345 -0.04857,0.597734 l 0.171325,0.213506 h 2.406501 c 1.730293,0 2.442285,-0.02923 2.533804,-0.103996 z"
id="path1479-5-9" />
<path
style="fill:#ffffff;stroke-width:0.699719"
d="m 30.519032,20.825415 c -1.151718,-1.14882 -1.758382,-1.884353 -2.201681,-2.669407 -0.30412,-0.538533 -0.359036,-0.722474 -0.351167,-1.176229 0.02083,-1.197121 0.901393,-2.320349 2.152928,-2.745983 0.717289,-0.24393 1.844661,-0.268012 2.508232,-0.05356 1.391561,0.449706 2.38435,1.740374 2.26967,2.950678 -0.08343,0.880413 -1.113071,2.346023 -2.677028,3.810353 l -0.817467,0.765394 z m 2.181125,-1.962726 c 1.277918,-0.691497 1.525794,-2.331274 0.493067,-3.261924 -1.143733,-1.030745 -3.046077,-0.821816 -3.884538,0.426612 -0.235225,0.35024 -0.27826,0.509613 -0.275785,1.021202 0.0023,0.72294 0.23876,1.182936 0.825458,1.614032 0.533021,0.391662 0.94197,0.50709 1.706533,0.481702 0.528455,-0.01766 0.747727,-0.07189 1.135265,-0.281624 z"
id="path1481-5-9" />
<path
style="fill:#ffffff;stroke-width:0.699719"
d="M 30.802604,18.267786 C 29.882335,17.9171 29.641439,16.75989 30.358135,16.132627 c 0.92991,-0.813902 2.580182,-0.229504 2.580182,0.91371 0,0.957496 -1.130967,1.604331 -2.135713,1.221449 z"
id="path1483-3-9" />
<path
style="fill:#ffffff;stroke-width:0.388827"
d="m 22.121805,30.681752 c -0.229677,-0.0299 -0.681614,-0.13097 -0.848537,-0.189987 -0.165546,-0.05853 -0.784152,-0.367999 -0.823591,-0.412026 -0.01368,-0.01526 -0.103553,-0.09015 -0.199652,-0.166069 -0.255214,-0.201859 -0.461774,-0.41924 -0.598495,-0.629823 -0.06617,-0.102086 -0.135438,-0.197456 -0.153735,-0.212052 -0.05026,-0.04003 -0.303428,-0.586455 -0.3559,-0.768133 -0.120928,-0.418626 -0.289465,-1.167772 -0.289465,-1.286604 0,-0.07299 -0.0242,-0.231019 -0.05395,-0.351014 -0.100202,-0.405668 -0.13735,-0.588119 -0.195763,-0.960306 -0.03204,-0.204086 -0.07623,-0.442636 -0.09816,-0.530091 -0.02205,-0.08736 -0.06432,-0.290226 -0.09393,-0.450587 -0.02967,-0.160335 -0.08998,-0.482383 -0.134001,-0.715613 -0.04395,-0.233252 -0.122065,-0.662618 -0.1734,-0.954164 -0.05141,-0.291546 -0.11867,-0.649363 -0.149601,-0.795129 -0.03097,-0.145775 -0.076,-0.396243 -0.100217,-0.556589 -0.06409,-0.426002 -0.187141,-0.995114 -0.277124,-1.282728 -0.165216,-0.52833 -0.551809,-0.767868 -1.348366,-0.835588 -0.413681,-0.03512 -0.547083,-0.0677 -0.679631,-0.166171 -0.343674,-0.255065 -0.489379,-0.537775 -0.489379,-0.949546 0,-0.197502 0.03535,-0.307985 0.162228,-0.50668 0.288112,-0.451277 0.634368,-0.557843 1.45314,-0.447217 0.634169,0.08566 1.190466,0.30332 1.670515,0.65354 0.775362,0.565707 1.141391,1.340025 1.432699,3.030792 0.04019,0.233226 0.0959,0.531417 0.123649,0.662613 0.02782,0.1312 0.07132,0.369714 0.09668,0.530086 0.02536,0.16035 0.07008,0.410828 0.09955,0.556599 0.02944,0.145775 0.08683,0.455874 0.127729,0.689131 0.04088,0.23321 0.108795,0.591032 0.150915,0.795128 0.04211,0.204086 0.09717,0.490339 0.122289,0.63612 0.02521,0.145755 0.06686,0.372366 0.09275,0.503577 0.151569,0.768774 0.219425,1.118441 0.267348,1.378216 0.161712,0.876323 0.38315,1.242029 0.903321,1.491831 l 0.260248,0.124945 h 2.793813 2.79383 l 0.340624,-0.530086 c 0.187348,-0.291556 0.396267,-0.63743 0.464294,-0.768635 0.06801,-0.131196 0.171017,-0.322023 0.228923,-0.424078 0.227947,-0.401686 0.435478,-0.8194 1.027018,-2.067347 0.412429,-0.870072 0.671393,-1.354523 0.784622,-1.467806 0.598847,-0.599044 1.62458,-0.111578 1.62458,0.77202 0,0.237418 -0.05518,0.39459 -0.398919,1.135038 -0.482154,1.038787 -1.053352,2.198977 -1.252158,2.5433 -0.08019,0.138925 -0.145843,0.264684 -0.145843,0.279433 0,0.0688 -0.886185,1.498225 -1.118536,1.80428 -0.228433,0.300905 -0.60396,0.64043 -0.844018,0.763117 -0.13659,0.0698 -0.570593,0.08206 -3.103728,0.08735 -1.619718,0.0031 -3.012326,-0.0026 -3.094684,-0.01305 z"
id="path1499-8-4" />
<path
style="fill:#ffffff;stroke-width:0.388827"
d="m 21.447661,34.803223 c -0.415543,-0.144082 -0.801437,-0.507786 -1.000328,-0.94284 -0.172817,-0.377957 -0.171941,-1.101081 7.72e-4,-1.47551 0.156886,-0.338205 0.456256,-0.655983 0.774225,-0.821853 0.352018,-0.183649 1.035108,-0.189234 1.387965,-0.01198 0.5386,0.27153 0.928259,0.872059 0.972709,1.499132 0.04211,0.592384 -0.376512,1.348369 -0.911345,1.646269 -0.219665,0.122359 -0.986611,0.188804 -1.225033,0.106197 z"
id="path1501-6-9" />
<path
style="fill:#ffffff;stroke-width:0.388827"
d="m 27.337511,34.803223 c -0.372854,-0.129276 -0.79761,-0.50667 -0.944214,-0.838926 -0.03596,-0.08147 -0.08613,-0.191251 -0.111614,-0.243864 -0.02544,-0.05263 -0.05933,-0.244836 -0.07523,-0.427159 -0.09569,-1.089399 0.716512,-1.960694 1.746592,-1.873444 0.457119,0.0387 0.796597,0.212042 1.086929,0.554997 0.585693,0.691809 0.567265,1.715555 -0.04273,2.36668 -0.359166,0.383481 -0.55566,0.472185 -1.085405,0.489985 -0.247076,0.008 -0.505533,-0.0031 -0.574334,-0.02831 z"
id="path1503-0-8" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 8.9 KiB

+1 -1
View File
@@ -29,7 +29,7 @@ class _CatalogoScreenState extends State<CatalogoScreen> {
@override
Widget build(BuildContext context) {
final provider = context.watch<AppProvider>();
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;
@@ -38,8 +38,8 @@ class _ClienteSelectorScreenState extends State<ClienteSelectorScreen> {
@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
+1 -1
View File
@@ -17,7 +17,7 @@ class _FirmaScreenState extends State<FirmaScreen> {
bool _firmado = false;
bool _guardando = false;
final _fmt = NumberFormat.currency(locale: 'en_US', symbol: '\$', decimalDigits: 2);
NumberFormat get _fmt => context.watch<AppProvider>().currencyFormat;
@override
Widget build(BuildContext context) {
+20 -4
View File
@@ -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<AppProvider>();
final notifService = context.watch<NotificationService>();
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,
+35 -5
View File
@@ -253,7 +253,10 @@ class _LoginScreenState extends State<LoginScreen>
],
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<LoginScreen>
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<LoginScreen>
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<LoginScreen>
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<LoginScreen>
),
);
}
// ── 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,
),
),
),
);
}
}
+2 -2
View File
@@ -797,8 +797,8 @@ class _RegistroCloudScreenState extends State<RegistroCloudScreen> {
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)),
+2 -2
View File
@@ -336,8 +336,8 @@ class _RegistroScreenState extends State<RegistroScreen> {
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)),
+107 -1
View File
@@ -13,7 +13,7 @@ class PedidoDetailScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final provider = context.read<AppProvider>();
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',
+2 -2
View File
@@ -21,7 +21,7 @@ class _PedidoFormScreenState extends State<PedidoFormScreen> {
String _productoQuery = '';
bool _showSearch = false;
final _fmt = NumberFormat.currency(locale: 'en_US', symbol: '\$', decimalDigits: 2);
NumberFormat get _fmt => context.watch<AppProvider>().currencyFormat;
@override
void initState() {
@@ -349,7 +349,7 @@ class _PedidoFormScreenState extends State<PedidoFormScreen> {
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),
),
],
),
+130 -28
View File
@@ -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<PedidosScreen> with SingleTickerProviderStateMixin {
late TabController _tab;
final _fmt = NumberFormat.currency(locale: 'en_US', symbol: '\$', decimalDigits: 2);
NumberFormat get _fmt => context.watch<AppProvider>().currencyFormat;
@override
void initState() {
@@ -39,6 +41,8 @@ class _PedidosScreenState extends State<PedidosScreen> 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<PedidosScreen> with SingleTickerProvider
}
Widget _buildList(BuildContext context, List<Pedido> 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<PedidosScreen> 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<PedidosScreen> 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),
),
],
),
);
}
}
+399 -10
View File
@@ -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<AppProvider>();
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<String>(
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,
+14 -15
View File
@@ -20,10 +20,12 @@ class _ScannerScreenState extends State<ScannerScreen> {
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<ScannerScreen> {
elevation: 0,
title: Text(widget.titulo),
actions: [
ValueListenableBuilder<TorchState>(
valueListenable: _controller.torchState,
ValueListenableBuilder<MobileScannerState>(
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<CameraFacing>(
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(),
),
],
),
+17
View File
@@ -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<AuthSession?> 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(
+215
View File
@@ -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<String, DateTime> _ultimoEnvio = {};
static int _conteoEnviosSesion = 0;
static String? _usuarioActual;
static String? _cuentaActual;
static bool _inicializado = false;
/// Inicializa los hooks globales para capturar excepciones no controladas de la app
static void inicializar({String? apiKey}) {
if (_inicializado) return;
_inicializado = true;
// Captura errores del framework Flutter (render, widgets, layouts)
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
reportarError(
details.exception,
stack: details.stack,
clase: 'FlutterError',
metodo: details.library ?? 'framework',
categoria: 'desconocido',
nivel: 'error',
);
};
// Captura errores asíncronos y de la plataforma raíz
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
reportarError(
error,
stack: stack,
clase: 'PlatformDispatcher',
metodo: 'root',
categoria: 'desconocido',
nivel: 'error',
);
return true; // Evita crash abrupto
};
// Procesar posibles reportes pendientes en cola de sesiones anteriores
unawaited(reintentarColaPendiente());
}
/// Vincula la sesión del 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<void> reportarError(
Object error, {
StackTrace? stack,
String? clase,
String? metodo,
String nivel = 'error',
String categoria = 'desconocido',
String? codigo,
}) async {
final mensaje = error.toString();
final firma = '$clase|$metodo|$mensaje';
final ahora = DateTime.now();
// 1. Throttle / Dedup: evitar inundar la API con el mismo fallo en bucle
final ultimo = _ultimoEnvio[firma];
if (ultimo != null && ahora.difference(ultimo) < throttleDuration) {
return;
}
if (_conteoEnviosSesion >= maximoPorSesion) {
return;
}
_ultimoEnvio[firma] = ahora;
_conteoEnviosSesion++;
// 2. Determinar entorno y versión con etiqueta de sistema operativo
final entorno = kReleaseMode ? 'produccion' : 'desarrollo';
final os = Platform.isAndroid
? 'android'
: Platform.isIOS
? 'ios'
: Platform.isLinux
? 'linux'
: Platform.operatingSystem;
final versionPlataforma = '$appVersion-$os';
final payload = <String, dynamic>{
'app_origen': appOrigen,
'mensaje': mensaje.length > 500 ? mensaje.substring(0, 500) : mensaje,
'entorno': entorno,
'version': versionPlataforma,
'nivel': nivel,
'categoria': categoria,
'fecha_evento': ahora.toUtc().toIso8601String(),
};
if (_usuarioActual != null && _usuarioActual!.isNotEmpty) {
payload['usuario'] = _usuarioActual;
}
if (_cuentaActual != null && _cuentaActual!.isNotEmpty) {
payload['cuenta'] = _cuentaActual;
}
if (clase != null && clase.isNotEmpty) {
payload['clase'] = clase;
}
if (metodo != null && metodo.isNotEmpty) {
payload['metodo'] = metodo;
}
if (codigo != null && codigo.isNotEmpty) {
payload['codigo'] = codigo;
}
if (stack != null) {
final stackStr = stack.toString();
payload['detalle'] = stackStr.length > 4000 ? stackStr.substring(0, 4000) : stackStr;
}
// 3. Envío HTTP inmediato con timeout seguro
try {
final res = await http
.post(
Uri.parse(endpoint),
headers: {
'Content-Type': 'application/json',
'x-api-key': _defaultApiKey,
},
body: jsonEncode(payload),
)
.timeout(const Duration(seconds: 8));
if (res.statusCode == 201 || res.statusCode == 200) {
debugPrint('[BitacoraService] Error reportado a WebControl (HTTP ${res.statusCode})');
return;
} else {
debugPrint('[BitacoraService] Falla al reportar (${res.statusCode}): ${res.body}');
await _guardarEnColaLocal(payload);
}
} catch (e) {
debugPrint('[BitacoraService] Sin conexión, guardando en cola offline: $e');
await _guardarEnColaLocal(payload);
}
}
/// Guarda el reporte en almacenamiento persistente si no hay red disponible
static Future<void> _guardarEnColaLocal(Map<String, dynamic> payload) async {
try {
final prefs = await SharedPreferences.getInstance();
final cola = prefs.getStringList('bitacora_errores_cola') ?? [];
if (cola.length < 50) {
cola.add(jsonEncode(payload));
await prefs.setStringList('bitacora_errores_cola', cola);
}
} catch (_) {}
}
/// Reintenta enviar los reportes almacenados durante periodos sin conexión
static Future<void> reintentarColaPendiente() async {
try {
final prefs = await SharedPreferences.getInstance();
final cola = prefs.getStringList('bitacora_errores_cola') ?? [];
if (cola.isEmpty) return;
final restante = <String>[];
for (final raw in cola) {
try {
final res = await http
.post(
Uri.parse(endpoint),
headers: {
'Content-Type': 'application/json',
'x-api-key': _defaultApiKey,
},
body: raw,
)
.timeout(const Duration(seconds: 6));
if (res.statusCode != 200 && res.statusCode != 201) {
restante.add(raw);
}
} catch (_) {
restante.add(raw);
break; // Si falla la red, suspender hasta el próximo ciclo
}
}
await prefs.setStringList('bitacora_errores_cola', restante);
} catch (_) {}
}
}
+146
View File
@@ -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<WhatsAppEnvioResult> 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<WhatsAppEnvioResult> 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<WhatsAppEnvioResult> 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,
);
}
}
+10 -10
View File
@@ -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,
+86
View File
@@ -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<CodigoPais> 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';
}
}
+234
View File
@@ -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<AppProvider>();
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>(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),
),
),
],
);
}
}