Files
APP_PEDIDOS_SIGMA/lib/providers/app_provider.dart
T
PablinuxandClaude Sonnet 4.6 eb081f3ea4 feat: integración cloud real — JWT auto-login, upload pedidos y sync
- tryAutoLogin: restaura sesión cloud y local desde SharedPreferences
- uploadPedido: sube pedidos al gateway con toCloudEncabezado/Detalle
- _uploadPendingPedidos: sube PENDIENTE en silencio al iniciar sesión
- _syncCloudData: actualiza contadores itemsSynced/clientesSynced
- loginLocal(): auth explícita sin cloud para el toggle "Cuenta local"
- DB v2: migración onUpgrade agrega columna sync_estado, SHA-256 en passwords
- Pedido.syncEstado: campo mutable PENDIENTE|SINCRONIZADO|ERROR
- ItemPedido.toCloudDetalle() + Pedido.toCloudEncabezado(usuario)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 09:26:59 -05:00

604 lines
20 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../database/database_helper.dart';
import '../database/db_seeder.dart';
import '../models/vendedor.dart';
import '../models/cliente.dart';
import '../models/producto.dart';
import '../models/pedido.dart';
import '../models/item_pedido.dart';
import '../models/ruta.dart';
import '../models/parada_ruta.dart';
import '../services/notification_service.dart';
import '../services/auth_service.dart';
import '../services/cloud_sync_service.dart';
class AppProvider extends ChangeNotifier {
final _db = DatabaseHelper();
final NotificationService? _notifService;
AppProvider({NotificationService? notifService}) : _notifService = notifService;
// ── Estado de sesión ─────────────────────────────────────────
bool _isLoggedIn = false;
bool _loading = false;
bool _autoLoginAttempted = false;
String? _loginError;
Vendedor? _vendedor;
// Tokens de sesión cloud (vacíos en modo offline)
String _jwt = '';
String _apiKey = '';
String _dbTenant = '';
bool _modoOnline = false;
// Contadores de última sincronización
int _itemsSynced = 0;
int _clientesSynced = 0;
Ruta? _ruta;
List<Pedido> _pedidos = [];
List<Producto> _productos = [];
List<Cliente> _clientes = [];
// índices en memoria para joins rápidos
Map<String, Cliente> _clientesMap = {};
Map<String, Producto> _productosMap = {};
// ── Carrito activo ───────────────────────────────────────────
Cliente? _clienteSeleccionado;
final List<ItemPedido> _carrito = [];
String _notasPedido = '';
// ── Getters ──────────────────────────────────────────────────
bool get isLoggedIn => _isLoggedIn;
bool get loading => _loading;
String? get loginError => _loginError;
bool get modoOnline => _modoOnline;
String get jwt => _jwt;
String get apiKey => _apiKey;
String get dbTenant => _dbTenant;
int get itemsSynced => _itemsSynced;
int get clientesSynced => _clientesSynced;
int get pedidosPendientesSync =>
_pedidos.where((p) => p.syncEstado == 'PENDIENTE').length;
Vendedor get vendedor => _vendedor!;
Ruta get ruta => _ruta!;
List<Pedido> get pedidos => _pedidos;
List<Producto> get productos => _productos;
List<Cliente> get clientes => _clientes;
Cliente? get clienteSeleccionado => _clienteSeleccionado;
List<ItemPedido> get carrito => _carrito;
String get notasPedido => _notasPedido;
double get totalCarrito => _carrito.fold(0, (s, i) => s + i.subtotal);
int get cantidadCarrito => _carrito.fold(0, (s, i) => s + i.cantidad);
List<Cliente> get clientesSinParada {
final ids = _ruta?.paradas.map((p) => p.cliente.id).toSet() ?? {};
return _clientes.where((c) => !ids.contains(c.id)).toList();
}
// ── Stats del día ────────────────────────────────────────────
int get pedidosHoy => _pedidos.where((p) {
final now = DateTime.now();
return p.fecha.day == now.day && p.fecha.month == now.month &&
p.estado != EstadoPedido.cancelado;
}).length;
double get ventasTotalesHoy => _pedidos.where((p) {
final now = DateTime.now();
return p.fecha.day == now.day && p.fecha.month == now.month &&
p.estado != EstadoPedido.cancelado;
}).fold(0, (s, p) => s + p.total);
// ── Auto-login ───────────────────────────────────────────────
/// Intenta restaurar la sesión guardada al abrir la app.
/// Mismo patrón que sigmac_app/login_screen.dart → _checkAutoLogin().
/// Se llama una sola vez desde main() antes de runApp().
Future<void> tryAutoLogin() async {
if (_autoLoginAttempted || _isLoggedIn) return;
_autoLoginAttempted = true;
_loading = true;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
final remember = prefs.getBool('pref_remember_me') ?? false;
final usuario = prefs.getString('auth_usuario') ?? '';
if (!remember || usuario.isEmpty) { _loading = false; notifyListeners(); return; }
final esCloud = prefs.getBool('auth_es_cloud') ?? false;
final nombre = prefs.getString('auth_nombre') ?? '';
final email = prefs.getString('auth_email') ?? '';
final empresa = prefs.getString('auth_empresa') ?? '';
if (!esCloud) {
// Sesión local guardada — restaurar sin validar JWT
if (empresa.isEmpty) { _loading = false; notifyListeners(); return; }
_modoOnline = false;
final displayName = nombre.isNotEmpty ? nombre : usuario;
final initials = _buildInitials(displayName, email);
_vendedor = Vendedor(
id: usuario, nombre: displayName, email: email,
telefono: '', zona: '',
avatarInitials: initials,
);
final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed();
await _loadAllData();
_isLoggedIn = true;
_loading = false;
notifyListeners();
return;
}
final token = prefs.getString('auth_token') ?? '';
final apiKey = prefs.getString('auth_api_key') ?? '';
if (!AuthService.isJwtVigente(token)) {
await AuthService.clearSession();
_loading = false;
notifyListeners();
return;
}
if (empresa.isEmpty) { _loading = false; notifyListeners(); return; }
_jwt = token;
_apiKey = apiKey;
_dbTenant = empresa;
_modoOnline = true;
final displayName = nombre.isNotEmpty ? nombre : usuario;
_vendedor = Vendedor(
id: usuario, nombre: displayName, email: email,
telefono: '', zona: '',
avatarInitials: _buildInitials(displayName, email),
);
final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed();
await _syncCloudData();
await _loadAllData();
await _uploadPendingPedidos();
_isLoggedIn = true;
} catch (e) {
debugPrint('[AutoLogin] error: $e');
}
_loading = false;
notifyListeners();
}
// ── Login / Logout ───────────────────────────────────────────
Future<bool> login(String email, String password,
{bool rememberMe = true}) async {
_loginError = null;
_loading = true;
notifyListeners();
try {
final session = await AuthService.login(email.trim(), password);
if (session != null) {
await AuthService.saveSession(session, email.trim(),
rememberMe: rememberMe);
_apiKey = session.apiKey;
_dbTenant = session.dbTenant;
_jwt = session.token;
_modoOnline = true;
_vendedor = _vendedorFromSession(session, email.trim());
final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed();
await _syncCloudData();
await _loadAllData();
await _uploadPendingPedidos();
_loading = false;
_isLoggedIn = true;
notifyListeners();
return true;
}
// Fallback offline — sin red o timeout
final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed();
final row = await _db.loginUsuario(email.trim(), password);
if (row == null) {
_loginError = 'Sin conexión. Verifica tu internet o las credenciales locales.';
_loading = false;
notifyListeners();
return false;
}
_vendedor = Vendedor.fromMap(row);
_modoOnline = false;
await _loadAllData();
_loading = false;
_isLoggedIn = true;
notifyListeners();
return true;
} on AuthException catch (e) {
_loginError = e.message;
_loading = false;
notifyListeners();
return false;
}
}
/// Login exclusivamente local — sin intentar cloud.
/// Usado cuando el toggle está en "Cuenta local".
Future<bool> loginLocal(String usuario, String password,
{bool rememberMe = true}) async {
_loginError = null;
_loading = true;
notifyListeners();
try {
final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed();
final row = await _db.loginUsuario(usuario.trim(), password);
if (row == null) {
_loginError = 'Usuario o contraseña incorrectos';
_loading = false;
notifyListeners();
return false;
}
_vendedor = Vendedor.fromMap(row);
_modoOnline = false;
await AuthService.saveLocalSession(
usuario: _vendedor!.id,
nombre: _vendedor!.nombre,
email: _vendedor!.email,
empresa: 'local',
rol: 'vendedor',
rememberMe: rememberMe,
);
await _loadAllData();
_loading = false;
_isLoggedIn = true;
notifyListeners();
return true;
} catch (e) {
_loginError = 'Error inesperado: $e';
_loading = false;
notifyListeners();
return false;
}
}
/// Sincroniza items y clientes desde API-SIGMA-CLOUD hacia SQLite local.
/// Si falla el sync (sin red, error API) no interrumpe el login — la app
/// continúa con los datos locales que ya tenga en SQLite.
Future<void> _syncCloudData() async {
_itemsSynced = 0;
_clientesSynced = 0;
try {
final items = await CloudSyncService.downloadItems();
for (final item in items) {
final productoExistente = await _db.getProductoBySku(item.codigo);
final p = Producto(
id: item.codigo,
sku: item.codigo,
nombre: item.detalle,
descripcion: item.descripcion,
categoria: item.grupo,
unidad: item.unidad,
stock: item.stock.toInt(),
precio: productoExistente?.precio ?? 0.0,
precioMayorista: productoExistente?.precioMayorista ?? 0.0,
emoji: productoExistente?.emoji ?? '📦',
);
await _db.insertProducto(p);
}
_itemsSynced = items.length;
debugPrint('[Sync] items: ${items.length}');
} catch (e) {
debugPrint('[Sync] items error: $e');
}
try {
final clientes = await CloudSyncService.downloadClientes();
for (final c in clientes) {
final cliente = Cliente(
id: c.rucCed,
nombre: c.nombre,
razonSocial: c.nombre,
direccion: c.direccion,
telefono: c.telefono,
nit: c.rucCed,
lat: 0.0,
lng: 0.0,
categoria: 'Cliente',
);
await _db.insertCliente(cliente);
}
_clientesSynced = clientes.length;
debugPrint('[Sync] clientes: ${clientes.length}');
} catch (e) {
debugPrint('[Sync] clientes error: $e');
}
}
/// Sube al cloud todos los pedidos con sync_estado=PENDIENTE.
/// Silencioso — los errores no interrumpen el flujo.
Future<void> _uploadPendingPedidos() async {
if (!_modoOnline || _apiKey.isEmpty) return;
final pendientes = _pedidos.where((p) => p.syncEstado == 'PENDIENTE').toList();
for (final pedido in pendientes) {
try {
await CloudSyncService.uploadPedido(pedido, _vendedor?.id ?? '');
await _db.updateSyncEstadoPedido(pedido.id, 'SINCRONIZADO');
pedido.syncEstado = 'SINCRONIZADO';
debugPrint('[Sync] pedido ${pedido.id} subido');
} catch (e) {
await _db.updateSyncEstadoPedido(pedido.id, 'ERROR');
pedido.syncEstado = 'ERROR';
debugPrint('[Sync] pedido ${pedido.id} error: $e');
}
}
}
Vendedor _vendedorFromSession(AuthSession session, String email) {
final nombre = session.nombre.isNotEmpty ? session.nombre : session.usuario;
return Vendedor(
id: session.usrSesionId?.toString() ?? session.usuario,
nombre: nombre,
email: email,
telefono: '',
zona: '',
avatarInitials: _buildInitials(nombre, email),
);
}
String _buildInitials(String nombre, String email) {
final trimmed = nombre.trim();
if (trimmed.isNotEmpty) {
return trimmed.split(' ').take(2)
.map((w) => w.isNotEmpty ? w[0].toUpperCase() : '')
.join();
}
return email.isNotEmpty ? email[0].toUpperCase() : 'U';
}
Future<void> _loadAllData() async {
// 1. catálogo y clientes (base para joins)
_productos = await _db.getProductos();
_clientes = await _db.getClientes();
_productosMap = {for (final p in _productos) p.id: p};
_clientesMap = {for (final c in _clientes) c.id: c};
// 2. Ruta de hoy (o crear una vacía)
final rutaId = await _db.getRutaIdHoy();
if (rutaId != null) {
_ruta = await _db.getRutaConParadas(rutaId, _clientesMap) ?? _emptyRuta();
} else {
_ruta = _emptyRuta();
await _db.insertRuta(_ruta!);
}
// 3. Pedidos
_pedidos = await _db.getPedidos(_clientesMap, _productosMap);
}
Ruta _emptyRuta() => Ruta(
id: 'ruta_${DateTime.now().toIso8601String().substring(0, 10)}',
nombre: 'Ruta del día',
zona: _vendedor?.zona ?? '',
paradas: [],
fecha: DateTime.now(),
);
void logout() {
AuthService.clearSession(); // fire-and-forget — borrar SharedPrefs
_isLoggedIn = false;
_vendedor = null;
_ruta = null;
_pedidos = [];
_productos = [];
_clientes = [];
_clientesMap = {};
_productosMap = {};
_jwt = '';
_apiKey = '';
_dbTenant = '';
_modoOnline = false;
limpiarCarrito();
notifyListeners();
}
// ── Clientes ─────────────────────────────────────────────────
Future<void> agregarCliente(Cliente cliente, {bool agregarARuta = false}) async {
await _db.insertCliente(cliente);
_clientes.add(cliente);
_clientesMap[cliente.id] = cliente;
if (agregarARuta) {
await agregarParadaARuta(cliente, _horaDefault());
} else {
notifyListeners();
}
}
Future<void> actualizarCliente(Cliente cliente) async {
await _db.updateCliente(cliente);
final idx = _clientes.indexWhere((c) => c.id == cliente.id);
if (idx >= 0) _clientes[idx] = cliente;
_clientesMap[cliente.id] = cliente;
notifyListeners();
}
// ── Productos ────────────────────────────────────────────────
Future<void> actualizarStock(String productoId, int nuevoStock) async {
await _db.updateStock(productoId, nuevoStock);
final idx = _productos.indexWhere((p) => p.id == productoId);
if (idx >= 0) {
_productos[idx] = _productos[idx].copyWith(stock: nuevoStock);
_productosMap[productoId] = _productos[idx];
if (nuevoStock <= 5) {
_notifService?.notifStockBajo(_productos[idx].nombre, nuevoStock);
}
}
notifyListeners();
}
// ── Ruta / Paradas ───────────────────────────────────────────
Future<void> agregarParadaARuta(Cliente cliente, String horaEstimada) async {
final nuevaOrden = (_ruta?.paradas.length ?? 0) + 1;
final parada = ParadaRuta(
id: 'pr_${DateTime.now().millisecondsSinceEpoch}',
cliente: cliente,
orden: nuevaOrden,
estado: EstadoParada.pendiente,
horaEstimada: horaEstimada,
);
await _db.insertParada(parada, _ruta!.id);
_ruta!.paradas.add(parada);
notifyListeners();
}
Future<void> eliminarParada(String paradaId) async {
await _db.deleteParada(paradaId);
_ruta!.paradas.removeWhere((p) => p.id == paradaId);
// reordenar
for (int i = 0; i < _ruta!.paradas.length; i++) {
_ruta!.paradas[i] = ParadaRuta(
id: _ruta!.paradas[i].id,
cliente: _ruta!.paradas[i].cliente,
orden: i + 1,
estado: _ruta!.paradas[i].estado,
horaEstimada: _ruta!.paradas[i].horaEstimada,
horaVisita: _ruta!.paradas[i].horaVisita,
);
}
await _db.reordenarParadas(_ruta!.paradas, _ruta!.id);
notifyListeners();
}
Future<void> marcarParadaVisitada(String paradaId) async {
final hora = _horaActual();
await _db.updateParadaEstado(paradaId, 'visitado', hora);
final parada = _ruta!.paradas.firstWhere((p) => p.id == paradaId);
parada.estado = EstadoParada.visitado;
parada.horaVisita = hora;
_notifService?.notifParadaVisitada(parada.cliente.nombre);
notifyListeners();
}
// ── Carrito ──────────────────────────────────────────────────
void seleccionarCliente(Cliente cliente) {
_clienteSeleccionado = cliente;
notifyListeners();
}
void agregarAlCarrito(Producto producto, {bool esMayorista = false}) {
final precio = esMayorista ? producto.precioMayorista : producto.precio;
final existente = _carrito.where((i) => i.producto.id == producto.id);
if (existente.isNotEmpty) {
existente.first.cantidad++;
} else {
_carrito.add(ItemPedido(producto: producto, cantidad: 1, precioUnitario: precio));
}
notifyListeners();
}
void quitarDelCarrito(String productoId) {
_carrito.removeWhere((i) => i.producto.id == productoId);
notifyListeners();
}
void actualizarCantidad(String productoId, int cantidad) {
if (cantidad <= 0) { quitarDelCarrito(productoId); return; }
_carrito.firstWhere((i) => i.producto.id == productoId).cantidad = cantidad;
notifyListeners();
}
void setNotasPedido(String notas) {
_notasPedido = notas;
notifyListeners();
}
void limpiarCarrito() {
_carrito.clear();
_clienteSeleccionado = null;
_notasPedido = '';
notifyListeners();
}
// ── Pedidos ──────────────────────────────────────────────────
Future<Pedido> confirmarPedido({String? firmaBase64}) async {
final id = 'TTC-${(_pedidos.length + 1).toString().padLeft(4, '0')}';
final pedido = Pedido(
id: id,
cliente: _clienteSeleccionado!,
items: List.from(_carrito),
estado: EstadoPedido.confirmado,
fecha: DateTime.now(),
notas: _notasPedido,
firmaBase64: firmaBase64,
);
await _db.insertPedido(pedido);
_pedidos.insert(0, pedido);
// Intento de upload inmediato; si falla queda PENDIENTE y se sube en el próximo login
if (_modoOnline && _apiKey.isNotEmpty) {
try {
await CloudSyncService.uploadPedido(pedido, _vendedor?.id ?? '');
await _db.updateSyncEstadoPedido(pedido.id, 'SINCRONIZADO');
pedido.syncEstado = 'SINCRONIZADO';
} catch (_) {
// sin conexión o error de API — permanece PENDIENTE
}
}
_notifService?.notifPedidoConfirmado(id, _clienteSeleccionado!.nombre);
limpiarCarrito();
notifyListeners();
return pedido;
}
Future<void> cambiarEstadoPedido(String pedidoId, EstadoPedido nuevoEstado) async {
await _db.updateEstadoPedido(pedidoId, nuevoEstado.label.toLowerCase());
final pedido = _pedidos.firstWhere((p) => p.id == pedidoId);
pedido.estado = nuevoEstado;
notifyListeners();
}
Future<void> eliminarPedido(String pedidoId) async {
await _db.deletePedido(pedidoId);
_pedidos.removeWhere((p) => p.id == pedidoId);
notifyListeners();
}
// ── Helpers ──────────────────────────────────────────────────
String _horaDefault() {
final now = DateTime.now();
final h = now.hour.toString().padLeft(2, '0');
final m = ((now.minute ~/ 15 + 1) * 15 % 60).toString().padLeft(2, '0');
return '$h:$m';
}
String _horaActual() {
final now = DateTime.now();
return '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
}
}