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>
This commit is contained in:
Pablinux
2026-06-17 09:26:59 -05:00
co-authored by Claude Sonnet 4.6
parent abe310699d
commit eb081f3ea4
6 changed files with 324 additions and 35 deletions
+199 -27
View File
@@ -1,4 +1,5 @@
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';
@@ -21,6 +22,7 @@ class AppProvider extends ChangeNotifier {
// ── Estado de sesión ─────────────────────────────────────────
bool _isLoggedIn = false;
bool _loading = false;
bool _autoLoginAttempted = false;
String? _loginError;
Vendedor? _vendedor;
@@ -29,6 +31,10 @@ class AppProvider extends ChangeNotifier {
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 = [];
@@ -44,13 +50,18 @@ class AppProvider extends ChangeNotifier {
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;
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!;
@@ -83,44 +94,120 @@ class AppProvider extends ChangeNotifier {
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) async {
Future<bool> login(String email, String password,
{bool rememberMe = true}) async {
_loginError = null;
_loading = true;
notifyListeners();
try {
// 1. Autenticación real: POST https://api.siax-system.net/api/auth/login
// Body: {email, paswd} — campo es "paswd" (igual que sigmac_app)
final session = await AuthService.login(email.trim(), password);
if (session != null) {
// Auth cloud exitosa — guardar tokens en SharedPreferences
await AuthService.saveSession(session, email.trim());
await AuthService.saveSession(session, email.trim(),
rememberMe: rememberMe);
_apiKey = session.apiKey;
_dbTenant = session.dbTenant;
_jwt = session.token;
_modoOnline = true;
// Construir Vendedor desde los datos de sesión
_vendedor = _vendedorFromSession(session, email.trim());
// Seed demo si la BD está vacía (primer uso)
final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed();
// Sincronizar catálogo y clientes desde API-SIGMA-CLOUD
await _syncCloudData();
await _loadAllData();
await _uploadPendingPedidos();
_loading = false;
_isLoggedIn = true;
notifyListeners();
return true;
}
// 2. Fallback offline — API no respondió (timeout / sin red)
// Fallback offline — sin red o timeout
final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed();
@@ -147,12 +234,59 @@ class AppProvider extends ChangeNotifier {
}
}
/// 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 {
// Sync catálogo
final items = await CloudSyncService.downloadItems();
for (final item in items) {
final productoExistente = await _db.getProductoBySku(item.codigo);
@@ -164,20 +298,19 @@ class AppProvider extends ChangeNotifier {
categoria: item.grupo,
unidad: item.unidad,
stock: item.stock.toInt(),
// Preservar precio local si el producto ya existe; 0.0 si es nuevo
precio: productoExistente?.precio ?? 0.0,
precioMayorista: productoExistente?.precioMayorista ?? 0.0,
emoji: productoExistente?.emoji ?? '📦',
);
await _db.insertProducto(p); // ConflictAlgorithm.replace
await _db.insertProducto(p);
}
_itemsSynced = items.length;
debugPrint('[Sync] items: ${items.length}');
} catch (e) {
debugPrint('[Sync] items error: $e');
}
try {
// Sync clientes
final clientes = await CloudSyncService.downloadClientes();
for (final c in clientes) {
final cliente = Cliente(
@@ -191,29 +324,56 @@ class AppProvider extends ChangeNotifier {
lng: 0.0,
categoria: 'Cliente',
);
await _db.insertCliente(cliente); // ConflictAlgorithm.replace
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;
final initials = nombre.trim().isNotEmpty
? nombre.trim().split(' ').take(2).map((w) => w[0].toUpperCase()).join()
: email[0].toUpperCase();
return Vendedor(
id: session.usrSesionId?.toString() ?? session.usuario,
nombre: nombre,
email: email,
telefono: '',
zona: '',
avatarInitials: initials,
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();
@@ -396,6 +556,18 @@ class AppProvider extends ChangeNotifier {
);
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();