feat: integración real API-SIGMA-WEBCONTROL — login cloud con fallback offline
Flujo: POST /api/auth/empresas → POST /api/auth/login → JWT + apiKey + db_tenant. Si la API no responde, cae silenciosamente a credenciales locales SQLite. AuthException (credenciales incorrectas) se muestra al usuario sin fallback. Perfil muestra badge "SIGMAC Cloud" / "Modo offline" según el modo de sesión. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
212d0bc8f2
commit
40c6f71caa
@@ -9,6 +9,7 @@ import '../models/item_pedido.dart';
|
|||||||
import '../models/ruta.dart';
|
import '../models/ruta.dart';
|
||||||
import '../models/parada_ruta.dart';
|
import '../models/parada_ruta.dart';
|
||||||
import '../services/notification_service.dart';
|
import '../services/notification_service.dart';
|
||||||
|
import '../services/auth_service.dart';
|
||||||
|
|
||||||
class AppProvider extends ChangeNotifier {
|
class AppProvider extends ChangeNotifier {
|
||||||
final _db = DatabaseHelper();
|
final _db = DatabaseHelper();
|
||||||
@@ -21,6 +22,12 @@ class AppProvider extends ChangeNotifier {
|
|||||||
bool _loading = false;
|
bool _loading = false;
|
||||||
String? _loginError;
|
String? _loginError;
|
||||||
Vendedor? _vendedor;
|
Vendedor? _vendedor;
|
||||||
|
|
||||||
|
// Tokens de sesión cloud (vacíos en modo offline)
|
||||||
|
String _jwt = '';
|
||||||
|
String _apiKey = '';
|
||||||
|
String _dbTenant = '';
|
||||||
|
bool _modoOnline = false;
|
||||||
Ruta? _ruta;
|
Ruta? _ruta;
|
||||||
List<Pedido> _pedidos = [];
|
List<Pedido> _pedidos = [];
|
||||||
List<Producto> _productos = [];
|
List<Producto> _productos = [];
|
||||||
@@ -39,6 +46,10 @@ class AppProvider extends ChangeNotifier {
|
|||||||
bool get isLoggedIn => _isLoggedIn;
|
bool get isLoggedIn => _isLoggedIn;
|
||||||
bool get loading => _loading;
|
bool get loading => _loading;
|
||||||
String? get loginError => _loginError;
|
String? get loginError => _loginError;
|
||||||
|
bool get modoOnline => _modoOnline;
|
||||||
|
String get jwt => _jwt;
|
||||||
|
String get apiKey => _apiKey;
|
||||||
|
String get dbTenant => _dbTenant;
|
||||||
|
|
||||||
Vendedor get vendedor => _vendedor!;
|
Vendedor get vendedor => _vendedor!;
|
||||||
Ruta get ruta => _ruta!;
|
Ruta get ruta => _ruta!;
|
||||||
@@ -78,25 +89,89 @@ class AppProvider extends ChangeNotifier {
|
|||||||
_loading = true;
|
_loading = true;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
// Seed si es la primera vez
|
try {
|
||||||
|
// 1. Intentar autenticación real contra API-SIGMA-WEBCONTROL
|
||||||
|
final empresas = await AuthService.getEmpresas(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tomar la primera empresa (en Telcotronics siempre hay una sola)
|
||||||
|
final dba = empresas.first.dba;
|
||||||
|
final result = await AuthService.login(email.trim(), password, dba);
|
||||||
|
|
||||||
|
if (result != null) {
|
||||||
|
// Auth cloud exitosa
|
||||||
|
_jwt = result.jwt;
|
||||||
|
_apiKey = result.apiKey;
|
||||||
|
_dbTenant = result.dbTenant;
|
||||||
|
_modoOnline = true;
|
||||||
|
|
||||||
|
_vendedor = _vendedorFromApiData(result.usuarioData, email);
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Fallback offline — credenciales locales en SQLite
|
||||||
final seeded = await _db.isSeeded();
|
final seeded = await _db.isSeeded();
|
||||||
if (!seeded) await DbSeeder(_db).seed();
|
if (!seeded) await DbSeeder(_db).seed();
|
||||||
|
|
||||||
final row = await _db.loginUsuario(email.trim(), password);
|
final row = await _db.loginUsuario(email.trim(), password);
|
||||||
if (row == null) {
|
if (row == null) {
|
||||||
_loginError = 'Correo o contraseña incorrectos';
|
_loginError = empresas == null
|
||||||
|
? 'Sin conexión al servidor — credenciales locales incorrectas'
|
||||||
|
: 'Correo o contraseña incorrectos';
|
||||||
_loading = false;
|
_loading = false;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
_vendedor = Vendedor.fromMap(row);
|
_vendedor = Vendedor.fromMap(row);
|
||||||
|
_modoOnline = false;
|
||||||
await _loadAllData();
|
await _loadAllData();
|
||||||
|
|
||||||
_loading = false;
|
_loading = false;
|
||||||
_isLoggedIn = true;
|
_isLoggedIn = true;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
return true;
|
return true;
|
||||||
|
} on AuthException catch (e) {
|
||||||
|
_loginError = e.message;
|
||||||
|
_loading = false;
|
||||||
|
notifyListeners();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Vendedor _vendedorFromApiData(Map<String, dynamic> data, String email) {
|
||||||
|
final nombre = (data['nombre'] ?? data['name'] ?? data['usrSesion_nombre'] ??
|
||||||
|
data['usuario'] ?? email.split('@').first)
|
||||||
|
.toString();
|
||||||
|
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(),
|
||||||
|
avatarInitials: initials,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _loadAllData() async {
|
Future<void> _loadAllData() async {
|
||||||
@@ -136,6 +211,10 @@ class AppProvider extends ChangeNotifier {
|
|||||||
_clientes = [];
|
_clientes = [];
|
||||||
_clientesMap = {};
|
_clientesMap = {};
|
||||||
_productosMap = {};
|
_productosMap = {};
|
||||||
|
_jwt = '';
|
||||||
|
_apiKey = '';
|
||||||
|
_dbTenant = '';
|
||||||
|
_modoOnline = false;
|
||||||
limpiarCarrito();
|
limpiarCarrito();
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -89,6 +89,36 @@ class PerfilScreen extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: provider.modoOnline
|
||||||
|
? Colors.green.withOpacity(0.3)
|
||||||
|
: Colors.orange.withOpacity(0.3),
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
border: Border.all(
|
||||||
|
color: provider.modoOnline
|
||||||
|
? Colors.greenAccent.withOpacity(0.6)
|
||||||
|
: Colors.orangeAccent.withOpacity(0.6),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
provider.modoOnline ? Icons.cloud_done_outlined : Icons.cloud_off_outlined,
|
||||||
|
color: Colors.white,
|
||||||
|
size: 13,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Text(
|
||||||
|
provider.modoOnline ? 'SIGMAC Cloud' : 'Modo offline',
|
||||||
|
style: const TextStyle(color: Colors.white, fontSize: 11, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
const _kWebcontrolUrl = 'http://192.168.10.145:3002';
|
||||||
|
const _kTimeout = Duration(seconds: 10);
|
||||||
|
|
||||||
|
// ── Modelos ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class Empresa {
|
||||||
|
final String dba;
|
||||||
|
final String nombre;
|
||||||
|
const Empresa({required this.dba, required this.nombre});
|
||||||
|
|
||||||
|
factory Empresa.fromMap(Map<String, dynamic> m) => Empresa(
|
||||||
|
dba: (m['dba'] ?? m['db'] ?? '').toString(),
|
||||||
|
nombre: (m['nombre'] ?? m['name'] ?? m['empresa'] ?? m['dba'] ?? '')
|
||||||
|
.toString(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class AuthResult {
|
||||||
|
final String jwt;
|
||||||
|
final String apiKey;
|
||||||
|
final String dbTenant;
|
||||||
|
final Map<String, dynamic> usuarioData;
|
||||||
|
|
||||||
|
const AuthResult({
|
||||||
|
required this.jwt,
|
||||||
|
required this.apiKey,
|
||||||
|
required this.dbTenant,
|
||||||
|
required this.usuarioData,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
class AuthException implements Exception {
|
||||||
|
final String message;
|
||||||
|
const AuthException(this.message);
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Servicio ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class AuthService {
|
||||||
|
/// Paso 1 — obtiene la lista de empresas del email.
|
||||||
|
/// Retorna `null` si no hay conexión (fallback a modo offline).
|
||||||
|
/// Lanza [AuthException] si las credenciales son incorrectas.
|
||||||
|
static Future<List<Empresa>?> getEmpresas(
|
||||||
|
String email, String password) async {
|
||||||
|
try {
|
||||||
|
final res = await http
|
||||||
|
.post(
|
||||||
|
Uri.parse('$_kWebcontrolUrl/api/auth/empresas'),
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: jsonEncode({'email': email, 'password': password}),
|
||||||
|
)
|
||||||
|
.timeout(_kTimeout);
|
||||||
|
|
||||||
|
final body = _decodeBody(res.body);
|
||||||
|
|
||||||
|
if (res.statusCode == 401 || res.statusCode == 403) {
|
||||||
|
throw AuthException(
|
||||||
|
body['message'] as String? ?? 'Credenciales incorrectas');
|
||||||
|
}
|
||||||
|
if (res.statusCode != 200) {
|
||||||
|
throw AuthException(body['message'] as String? ??
|
||||||
|
'Error del servidor (${res.statusCode})');
|
||||||
|
}
|
||||||
|
|
||||||
|
final lista = body['empresas'] as List<dynamic>? ?? [];
|
||||||
|
return lista
|
||||||
|
.map((e) => Empresa.fromMap(e as Map<String, dynamic>))
|
||||||
|
.toList();
|
||||||
|
} on AuthException {
|
||||||
|
rethrow;
|
||||||
|
} on SocketException {
|
||||||
|
return null;
|
||||||
|
} on TimeoutException {
|
||||||
|
return null;
|
||||||
|
} on HttpException {
|
||||||
|
return null;
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paso 2 — obtiene JWT + apiKey + db_tenant.
|
||||||
|
/// Retorna `null` si no hay conexión.
|
||||||
|
/// Lanza [AuthException] si las credenciales son incorrectas.
|
||||||
|
static Future<AuthResult?> login(
|
||||||
|
String email, String password, String dba) async {
|
||||||
|
try {
|
||||||
|
final res = await http
|
||||||
|
.post(
|
||||||
|
Uri.parse('$_kWebcontrolUrl/api/auth/login'),
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: jsonEncode({'email': email, 'password': password, 'dba': dba}),
|
||||||
|
)
|
||||||
|
.timeout(_kTimeout);
|
||||||
|
|
||||||
|
final body = _decodeBody(res.body);
|
||||||
|
|
||||||
|
if (res.statusCode == 401 || res.statusCode == 403) {
|
||||||
|
throw AuthException(
|
||||||
|
body['message'] as String? ?? 'Credenciales incorrectas');
|
||||||
|
}
|
||||||
|
if (res.statusCode != 200) {
|
||||||
|
throw AuthException(body['message'] as String? ??
|
||||||
|
'Error del servidor (${res.statusCode})');
|
||||||
|
}
|
||||||
|
|
||||||
|
return AuthResult(
|
||||||
|
jwt: (body['token'] ?? body['jwt'] ?? '').toString(),
|
||||||
|
apiKey: (body['apiKey'] ?? body['api_key'] ?? '').toString(),
|
||||||
|
dbTenant: (body['db_tenant'] ?? body['dbTenant'] ?? dba).toString(),
|
||||||
|
usuarioData: (body['usuario'] as Map<String, dynamic>?) ??
|
||||||
|
(body['user'] as Map<String, dynamic>?) ??
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
} on AuthException {
|
||||||
|
rethrow;
|
||||||
|
} on SocketException {
|
||||||
|
return null;
|
||||||
|
} on TimeoutException {
|
||||||
|
return null;
|
||||||
|
} on HttpException {
|
||||||
|
return null;
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Map<String, dynamic> _decodeBody(String raw) {
|
||||||
|
try {
|
||||||
|
return jsonDecode(raw) as Map<String, dynamic>;
|
||||||
|
} catch (_) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -116,6 +116,20 @@ packages:
|
|||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
|
http:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: http
|
||||||
|
url: "https://pub.dartlang.org"
|
||||||
|
source: hosted
|
||||||
|
version: "0.13.5"
|
||||||
|
http_parser:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: http_parser
|
||||||
|
url: "https://pub.dartlang.org"
|
||||||
|
source: hosted
|
||||||
|
version: "4.0.2"
|
||||||
image:
|
image:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ dependencies:
|
|||||||
sqflite_common_ffi: ^2.1.0
|
sqflite_common_ffi: ^2.1.0
|
||||||
path: ^1.8.1
|
path: ^1.8.1
|
||||||
mobile_scanner: ^0.2.0
|
mobile_scanner: ^0.2.0
|
||||||
|
http: ^0.13.0
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
Reference in New Issue
Block a user