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
@@ -182,6 +182,12 @@ class DatabaseHelper {
|
||||
return rows.map(Producto.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<Producto?> getProductoBySku(String sku) async {
|
||||
final db = await database;
|
||||
final rows = await db.query('productos', where: 'sku = ?', whereArgs: [sku], limit: 1);
|
||||
return rows.isEmpty ? null : Producto.fromMap(rows.first);
|
||||
}
|
||||
|
||||
Future<void> insertProducto(Producto p) async {
|
||||
final db = await database;
|
||||
await db.insert('productos', p.toMap(),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
// 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;
|
||||
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;
|
||||
|
||||
_vendedor = _vendedorFromApiData(result.usuarioData, email);
|
||||
// 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();
|
||||
_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
|
||||
// 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(),
|
||||
id: session.usrSesionId?.toString() ?? session.usuario,
|
||||
nombre: nombre,
|
||||
email: email,
|
||||
telefono: (data['telefono'] ?? data['usrSesion_telefono'] ?? '').toString(),
|
||||
zona: (data['zona'] ?? '').toString(),
|
||||
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;
|
||||
|
||||
+109
-88
@@ -2,36 +2,60 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
const _kWebcontrolUrl = 'http://192.168.10.145:3002';
|
||||
const _kTimeout = Duration(seconds: 10);
|
||||
// URL pública de API-SIGMA-WEBCONTROL — igual que en sigmac_app/CentralCloudApi
|
||||
const _kBase = 'https://api.siax-system.net';
|
||||
|
||||
// ── 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;
|
||||
class AuthSession {
|
||||
final String token;
|
||||
final String apiKey;
|
||||
final String dbTenant;
|
||||
final Map<String, dynamic> usuarioData;
|
||||
final String usuario;
|
||||
final String nombre;
|
||||
final String rol;
|
||||
final int? usrSesionId;
|
||||
|
||||
const AuthResult({
|
||||
required this.jwt,
|
||||
const AuthSession({
|
||||
required this.token,
|
||||
required this.apiKey,
|
||||
required this.dbTenant,
|
||||
required this.usuarioData,
|
||||
required this.usuario,
|
||||
required this.nombre,
|
||||
required this.rol,
|
||||
this.usrSesionId,
|
||||
});
|
||||
|
||||
// Mismo parsing que sigmac_app/central_cloud_api.dart → AuthSession.fromMap()
|
||||
factory AuthSession.fromMap(Map<String, dynamic> m) {
|
||||
final d = m['data'] is Map<String, dynamic>
|
||||
? m['data'] as Map<String, dynamic>
|
||||
: m;
|
||||
|
||||
final rawUsuario = d['usuario'];
|
||||
final usuarioMap = rawUsuario is Map<String, dynamic> ? rawUsuario : null;
|
||||
|
||||
final usuarioStr = rawUsuario is String
|
||||
? rawUsuario
|
||||
: (usuarioMap?['usuario'] as String?) ?? '';
|
||||
|
||||
final nombre = d['nombre'] as String? ?? usuarioMap?['nombre'] as String? ?? '';
|
||||
final rol = d['rol'] as String? ?? usuarioMap?['rol'] as String? ?? '';
|
||||
final rawId = d['usrSesion_ID'] ?? d['id'] ?? d['userId']
|
||||
?? usuarioMap?['id'] ?? usuarioMap?['id_usr'];
|
||||
|
||||
return AuthSession(
|
||||
token: (d['token'] as String?) ?? (d['accessToken'] as String?) ?? '',
|
||||
apiKey: (d['apiKey'] as String?) ?? '',
|
||||
dbTenant: (d['db_tenant'] as String?) ?? (d['dba'] as String?) ?? '',
|
||||
usuario: usuarioStr,
|
||||
nombre: nombre,
|
||||
rol: rol,
|
||||
usrSesionId: rawId is int ? rawId : int.tryParse(rawId?.toString() ?? ''),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AuthException implements Exception {
|
||||
@@ -44,39 +68,46 @@ class AuthException implements Exception {
|
||||
// ── Servicio ───────────────────────────────────────────────────────────────
|
||||
|
||||
class AuthService {
|
||||
/// Paso 1 — obtiene la lista de empresas del email.
|
||||
static const _headersJson = {
|
||||
'accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
/// Login contra API-SIGMA-WEBCONTROL.
|
||||
/// Endpoint: POST https://api.siax-system.net/api/auth/login
|
||||
/// Body: {email, paswd} ← campo es `paswd`, NO `password`
|
||||
///
|
||||
/// Retorna [AuthSession] si el login fue exitoso.
|
||||
/// 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 {
|
||||
static Future<AuthSession?> login(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}),
|
||||
Uri.parse('$_kBase/api/auth/login'),
|
||||
headers: _headersJson,
|
||||
body: jsonEncode({'email': email, 'paswd': password}),
|
||||
)
|
||||
.timeout(_kTimeout);
|
||||
.timeout(const Duration(seconds: 15));
|
||||
|
||||
final body = _decodeBody(res.body);
|
||||
|
||||
if (res.statusCode == 401 || res.statusCode == 403) {
|
||||
throw AuthException(
|
||||
body['message'] as String? ?? 'Credenciales incorrectas');
|
||||
if (res.statusCode == 401 || res.statusCode == 400) {
|
||||
throw const AuthException('Usuario o contraseña incorrectos');
|
||||
}
|
||||
if (res.statusCode >= 500) {
|
||||
throw AuthException('Error del servidor (${res.statusCode})');
|
||||
}
|
||||
if (res.statusCode != 200) {
|
||||
throw AuthException(body['message'] as String? ??
|
||||
'Error del servidor (${res.statusCode})');
|
||||
final msg = _extractMsg(res.body);
|
||||
throw AuthException(msg.isNotEmpty ? msg : 'Respuesta inesperada (${res.statusCode})');
|
||||
}
|
||||
|
||||
final lista = body['empresas'] as List<dynamic>? ?? [];
|
||||
return lista
|
||||
.map((e) => Empresa.fromMap(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
final body = jsonDecode(res.body);
|
||||
final map = body is Map<String, dynamic> ? body : <String, dynamic>{};
|
||||
return AuthSession.fromMap(map);
|
||||
} on AuthException {
|
||||
rethrow;
|
||||
} on SocketException {
|
||||
return null;
|
||||
return null; // sin red → fallback offline
|
||||
} on TimeoutException {
|
||||
return null;
|
||||
} on HttpException {
|
||||
@@ -86,57 +117,47 @@ class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// Guarda la sesión en SharedPreferences.
|
||||
/// Mismas claves que usa sigmac_app para compatibilidad futura.
|
||||
static Future<void> saveSession(AuthSession s, String email) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString('auth_token', s.token);
|
||||
await prefs.setString('auth_usuario', s.usuario);
|
||||
await prefs.setString('auth_email', email.toLowerCase());
|
||||
await prefs.setString('auth_nombre', s.nombre);
|
||||
await prefs.setString('auth_rol', s.rol);
|
||||
await prefs.setString('auth_empresa', s.dbTenant);
|
||||
await prefs.setBool('auth_es_cloud', true);
|
||||
if (s.apiKey.isNotEmpty) {
|
||||
await prefs.setString('auth_api_key', s.apiKey);
|
||||
}
|
||||
if (s.usrSesionId != null) {
|
||||
await prefs.setInt('auth_cloud_id', s.usrSesionId!);
|
||||
}
|
||||
}
|
||||
|
||||
/// Borra la sesión de SharedPreferences al hacer logout.
|
||||
static Future<void> clearSession() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove('auth_token');
|
||||
await prefs.remove('auth_usuario');
|
||||
await prefs.remove('auth_email');
|
||||
await prefs.remove('auth_nombre');
|
||||
await prefs.remove('auth_rol');
|
||||
await prefs.remove('auth_api_key');
|
||||
await prefs.remove('auth_empresa');
|
||||
await prefs.setBool('auth_es_cloud', false);
|
||||
}
|
||||
|
||||
static String _extractMsg(String body) {
|
||||
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;
|
||||
final j = jsonDecode(body);
|
||||
if (j is Map) {
|
||||
for (final k in ['message', 'error', 'msg', 'detail']) {
|
||||
if (j[k] is String && (j[k] as String).isNotEmpty) return j[k] as String;
|
||||
}
|
||||
}
|
||||
|
||||
static Map<String, dynamic> _decodeBody(String raw) {
|
||||
try {
|
||||
return jsonDecode(raw) as Map<String, dynamic>;
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
} catch (_) {}
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
// URL idéntica a sigmac_app/gateway_cloud_api.dart
|
||||
const _kBase = 'https://api-gateway-cloud.telcotronics.net';
|
||||
|
||||
// ── Modelos de respuesta de la API ─────────────────────────────────────────
|
||||
// Campos reales del gateway, extraídos de sigmac_app/GatewayItemSync y GatewayClienteSync
|
||||
|
||||
class ApiItem {
|
||||
final String codigo; // codigo_prdcto → sku / id
|
||||
final String detalle; // detalle_prdcto → nombre
|
||||
final String descripcion; // describe_prdcto
|
||||
final String grupo; // grupo_prdcto → categoria
|
||||
final String unidad; // unidaMed_prdcto
|
||||
final double stock; // stock
|
||||
|
||||
const ApiItem({
|
||||
required this.codigo,
|
||||
required this.detalle,
|
||||
required this.descripcion,
|
||||
required this.grupo,
|
||||
required this.unidad,
|
||||
required this.stock,
|
||||
});
|
||||
|
||||
factory ApiItem.fromMap(Map<String, dynamic> m) => ApiItem(
|
||||
codigo: (m['codigo_prdcto'] as String?) ?? '',
|
||||
detalle: (m['detalle_prdcto'] as String?) ?? '',
|
||||
descripcion: (m['describe_prdcto'] as String?) ?? '',
|
||||
grupo: (m['grupo_prdcto'] as String?) ?? 'General',
|
||||
unidad: (m['unidaMed_prdcto'] as String?) ?? 'unidad',
|
||||
stock: _parseDouble(m['stock']),
|
||||
);
|
||||
|
||||
static double _parseDouble(dynamic v) {
|
||||
if (v == null) return 0;
|
||||
if (v is num) return v.toDouble();
|
||||
return double.tryParse(v.toString()) ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
class ApiCliente {
|
||||
final String rucCed; // client_rucCed → nit / id
|
||||
final String nombre; // client_nombre
|
||||
final String direccion; // client_direccion
|
||||
final String telefono; // client_celular
|
||||
|
||||
const ApiCliente({
|
||||
required this.rucCed,
|
||||
required this.nombre,
|
||||
required this.direccion,
|
||||
required this.telefono,
|
||||
});
|
||||
|
||||
factory ApiCliente.fromMap(Map<String, dynamic> m) => ApiCliente(
|
||||
rucCed: (m['client_rucCed'] as String?) ?? '',
|
||||
nombre: (m['client_nombre'] as String?) ?? '',
|
||||
direccion: (m['client_direccion'] as String?) ?? '',
|
||||
telefono: (m['client_celular'] as String?) ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
class CloudSyncException implements Exception {
|
||||
final String message;
|
||||
const CloudSyncException(this.message);
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
// ── Servicio ───────────────────────────────────────────────────────────────
|
||||
|
||||
class CloudSyncService {
|
||||
CloudSyncService._();
|
||||
|
||||
// Headers: solo x-api-key — igual que sigmac_app/GatewayCloudApi._headers()
|
||||
// El gateway NO usa Bearer JWT
|
||||
static Future<Map<String, String>> _headers() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final apiKey = prefs.getString('auth_api_key') ?? '';
|
||||
return {
|
||||
'accept': 'application/json',
|
||||
if (apiKey.isNotEmpty) 'x-api-key': apiKey,
|
||||
};
|
||||
}
|
||||
|
||||
/// db_tenant guardado por AuthService.saveSession() como 'auth_empresa'.
|
||||
static Future<String> _requireDb() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final db = prefs.getString('auth_empresa') ?? '';
|
||||
if (db.isEmpty) throw const CloudSyncException('Sin sesión cloud activa');
|
||||
return db;
|
||||
}
|
||||
|
||||
// ── Items ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Descarga catálogo completo.
|
||||
/// Endpoint: GET /api/items/sync?db={db}&limite=1000&offset={offset}
|
||||
/// Respuesta: { total, offset, items: [...] }
|
||||
static Future<List<ApiItem>> downloadItems() async {
|
||||
final db = await _requireDb();
|
||||
final headers = await _headers();
|
||||
final items = <ApiItem>[];
|
||||
int offset = 0;
|
||||
const limite = 1000;
|
||||
|
||||
while (true) {
|
||||
final uri = Uri.parse('$_kBase/api/items/sync').replace(
|
||||
queryParameters: {
|
||||
'db': db,
|
||||
'limite': '$limite',
|
||||
'offset': '$offset',
|
||||
},
|
||||
);
|
||||
final res = await http
|
||||
.get(uri, headers: headers)
|
||||
.timeout(const Duration(seconds: 30));
|
||||
|
||||
_checkStatus(res);
|
||||
final body = jsonDecode(res.body) as Map<String, dynamic>;
|
||||
final page = (body['items'] as List? ?? [])
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(ApiItem.fromMap)
|
||||
.where((i) => i.codigo.isNotEmpty)
|
||||
.toList();
|
||||
|
||||
items.addAll(page);
|
||||
offset += page.length;
|
||||
|
||||
if (page.length < limite) break; // última página
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
// ── Clientes ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// Descarga lista completa de clientes del tenant.
|
||||
/// Endpoint: GET /api/clientes/verClientesJsonApp?db={db}
|
||||
/// Respuesta: { "Clientes": [ { client_rucCed, client_nombre, ... } ] }
|
||||
static Future<List<ApiCliente>> downloadClientes() async {
|
||||
final db = await _requireDb();
|
||||
final headers = await _headers();
|
||||
|
||||
final uri = Uri.parse('$_kBase/api/clientes/verClientesJsonApp')
|
||||
.replace(queryParameters: {'db': db});
|
||||
final res = await http
|
||||
.get(uri, headers: headers)
|
||||
.timeout(const Duration(seconds: 30));
|
||||
|
||||
_checkStatus(res);
|
||||
final body = jsonDecode(res.body) as Map<String, dynamic>;
|
||||
|
||||
return (body['Clientes'] as List? ?? [])
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(ApiCliente.fromMap)
|
||||
.where((c) => c.rucCed.isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
|
||||
// ── Helper ─────────────────────────────────────────────────────────────────
|
||||
|
||||
static void _checkStatus(http.Response res) {
|
||||
if (res.statusCode == 401) {
|
||||
throw const CloudSyncException('API Key inválida — vuelve a iniciar sesión');
|
||||
}
|
||||
if (res.statusCode >= 400) {
|
||||
throw CloudSyncException('Error ${res.statusCode}');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,11 @@ import FlutterMacOS
|
||||
import Foundation
|
||||
|
||||
import mobile_scanner
|
||||
import shared_preferences_foundation
|
||||
import sqflite
|
||||
|
||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin"))
|
||||
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
|
||||
SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin"))
|
||||
}
|
||||
|
||||
+119
-2
@@ -92,6 +92,13 @@ packages:
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.2.1"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "6.1.4"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
@@ -116,6 +123,11 @@ packages:
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_web_plugins:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
http:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -150,7 +162,7 @@ packages:
|
||||
name: js
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "0.6.5"
|
||||
version: "0.6.4"
|
||||
lints:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -200,6 +212,27 @@ packages:
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.8.1"
|
||||
path_provider_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_linux
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.1.7"
|
||||
path_provider_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_platform_interface
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.5"
|
||||
path_provider_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_windows
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.7"
|
||||
petitparser:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -207,6 +240,20 @@ packages:
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "4.4.0"
|
||||
platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: platform
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "3.1.0"
|
||||
plugin_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: plugin_platform_interface
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.1.3"
|
||||
pointycastle:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -214,6 +261,13 @@ packages:
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "3.7.3"
|
||||
process:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: process
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "4.2.4"
|
||||
provider:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -221,6 +275,55 @@ packages:
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "6.1.5+1"
|
||||
shared_preferences:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: shared_preferences
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.17"
|
||||
shared_preferences_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_android
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.15"
|
||||
shared_preferences_foundation:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_foundation
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.1.2"
|
||||
shared_preferences_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_linux
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.1.3"
|
||||
shared_preferences_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_platform_interface
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.1.0"
|
||||
shared_preferences_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_web
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.4"
|
||||
shared_preferences_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_windows
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.1.3"
|
||||
sky_engine:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
@@ -317,6 +420,20 @@ packages:
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.1.1"
|
||||
win32:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: win32
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.5.2"
|
||||
xdg_directories:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: xdg_directories
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "0.2.0+3"
|
||||
xml:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -333,4 +450,4 @@ packages:
|
||||
version: "3.1.1"
|
||||
sdks:
|
||||
dart: ">=2.17.0-69.2.beta <3.0.0"
|
||||
flutter: ">=1.16.0"
|
||||
flutter: ">=2.10.0"
|
||||
|
||||
@@ -17,6 +17,7 @@ dependencies:
|
||||
path: ^1.8.1
|
||||
mobile_scanner: ^0.2.0
|
||||
http: ^0.13.0
|
||||
shared_preferences: ^2.0.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
Reference in New Issue
Block a user