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
+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() {