fix: auth e integración cloud correcta desde código real de sigmac_app
auth_service.dart: - URL corregida: https://api.siax-system.net (no la IP interna) - Campo contraseña corregido: paswd (no password) - Eliminado paso empresas innecesario — login directo igual que sigmac_app - Sesión guardada en SharedPreferences con mismas claves que sigmac_app - AuthSession.fromMap idéntico al de CentralCloudApi.AuthSession cloud_sync_service.dart (nuevo): - Base URL: https://api-gateway-cloud.telcotronics.net - Solo x-api-key en headers (NO Bearer JWT) — igual que GatewayCloudApi - Items: GET /api/items/sync con paginación por offset - Clientes: GET /api/clientes/verClientesJsonApp - Campos reales: codigo_prdcto, detalle_prdcto, client_rucCed, etc. app_provider.dart: - login() llama AuthService.login() con la firma correcta - Después de auth exitosa sincroniza items y clientes del cloud - Preserva precios locales en upsert de productos (API no devuelve precios) - Fallback offline mantiene credenciales SQLite locales - logout() borra SharedPreferences Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
40c6f71caa
commit
0c09e10e4d
@@ -10,6 +10,7 @@ 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();
|
||||
@@ -90,53 +91,42 @@ class AppProvider extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
// 1. Intentar autenticación real contra API-SIGMA-WEBCONTROL
|
||||
final empresas = await AuthService.getEmpresas(email.trim(), password);
|
||||
// 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 (empresas != null) {
|
||||
// API alcanzable
|
||||
if (empresas.isEmpty) {
|
||||
_loginError = 'No se encontraron empresas asociadas a este usuario';
|
||||
_loading = false;
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
if (session != null) {
|
||||
// Auth cloud exitosa — guardar tokens en SharedPreferences
|
||||
await AuthService.saveSession(session, email.trim());
|
||||
_apiKey = session.apiKey;
|
||||
_dbTenant = session.dbTenant;
|
||||
_jwt = session.token;
|
||||
_modoOnline = true;
|
||||
|
||||
// Tomar la primera empresa (en Telcotronics siempre hay una sola)
|
||||
final dba = empresas.first.dba;
|
||||
final result = await AuthService.login(email.trim(), password, dba);
|
||||
// Construir Vendedor desde los datos de sesión
|
||||
_vendedor = _vendedorFromSession(session, email.trim());
|
||||
|
||||
if (result != null) {
|
||||
// Auth cloud exitosa
|
||||
_jwt = result.jwt;
|
||||
_apiKey = result.apiKey;
|
||||
_dbTenant = result.dbTenant;
|
||||
_modoOnline = true;
|
||||
// Seed demo si la BD está vacía (primer uso)
|
||||
final seeded = await _db.isSeeded();
|
||||
if (!seeded) await DbSeeder(_db).seed();
|
||||
|
||||
_vendedor = _vendedorFromApiData(result.usuarioData, email);
|
||||
// Sincronizar catálogo y clientes desde API-SIGMA-CLOUD
|
||||
await _syncCloudData();
|
||||
|
||||
final seeded = await _db.isSeeded();
|
||||
if (!seeded) await DbSeeder(_db).seed();
|
||||
|
||||
await _loadAllData();
|
||||
_loading = false;
|
||||
_isLoggedIn = true;
|
||||
notifyListeners();
|
||||
return true;
|
||||
}
|
||||
// result == null → timeout al hacer login tras obtener empresas (raro)
|
||||
// caer al fallback local
|
||||
await _loadAllData();
|
||||
_loading = false;
|
||||
_isLoggedIn = true;
|
||||
notifyListeners();
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. Fallback offline — credenciales locales en SQLite
|
||||
// 2. Fallback offline — API no respondió (timeout / sin red)
|
||||
final seeded = await _db.isSeeded();
|
||||
if (!seeded) await DbSeeder(_db).seed();
|
||||
|
||||
final row = await _db.loginUsuario(email.trim(), password);
|
||||
if (row == null) {
|
||||
_loginError = empresas == null
|
||||
? 'Sin conexión al servidor — credenciales locales incorrectas'
|
||||
: 'Correo o contraseña incorrectos';
|
||||
_loginError = 'Sin conexión. Verifica tu internet o las credenciales locales.';
|
||||
_loading = false;
|
||||
notifyListeners();
|
||||
return false;
|
||||
@@ -157,19 +147,69 @@ class AppProvider extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Vendedor _vendedorFromApiData(Map<String, dynamic> data, String email) {
|
||||
final nombre = (data['nombre'] ?? data['name'] ?? data['usrSesion_nombre'] ??
|
||||
data['usuario'] ?? email.split('@').first)
|
||||
.toString();
|
||||
/// 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 {
|
||||
try {
|
||||
// Sync catálogo
|
||||
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(),
|
||||
// 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
|
||||
}
|
||||
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(
|
||||
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); // ConflictAlgorithm.replace
|
||||
}
|
||||
debugPrint('[Sync] clientes: ${clientes.length}');
|
||||
} catch (e) {
|
||||
debugPrint('[Sync] clientes 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: (data['id'] ?? data['usrSesion_id'] ?? email).toString(),
|
||||
nombre: nombre,
|
||||
email: email,
|
||||
telefono: (data['telefono'] ?? data['usrSesion_telefono'] ?? '').toString(),
|
||||
zona: (data['zona'] ?? '').toString(),
|
||||
id: session.usrSesionId?.toString() ?? session.usuario,
|
||||
nombre: nombre,
|
||||
email: email,
|
||||
telefono: '',
|
||||
zona: '',
|
||||
avatarInitials: initials,
|
||||
);
|
||||
}
|
||||
@@ -203,6 +243,7 @@ class AppProvider extends ChangeNotifier {
|
||||
);
|
||||
|
||||
void logout() {
|
||||
AuthService.clearSession(); // fire-and-forget — borrar SharedPrefs
|
||||
_isLoggedIn = false;
|
||||
_vendedor = null;
|
||||
_ruta = null;
|
||||
|
||||
Reference in New Issue
Block a user