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>
173 lines
6.2 KiB
Dart
173 lines
6.2 KiB
Dart
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}');
|
|
}
|
|
}
|
|
}
|