From eb081f3ea40c0d95f1060ac39f2c99fab9be9891 Mon Sep 17 00:00:00 2001 From: Pablinux Date: Wed, 17 Jun 2026 09:26:59 -0500 Subject: [PATCH] =?UTF-8?q?feat:=20integraci=C3=B3n=20cloud=20real=20?= =?UTF-8?q?=E2=80=94=20JWT=20auto-login,=20upload=20pedidos=20y=20sync?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- lib/database/database_helper.dart | 66 +++++++- lib/main.dart | 9 +- lib/models/item_pedido.dart | 9 ++ lib/models/pedido.dart | 21 +++ lib/providers/app_provider.dart | 226 +++++++++++++++++++++++---- lib/services/cloud_sync_service.dart | 28 ++++ 6 files changed, 324 insertions(+), 35 deletions(-) diff --git a/lib/database/database_helper.dart b/lib/database/database_helper.dart index 33f6284..1bd2460 100644 --- a/lib/database/database_helper.dart +++ b/lib/database/database_helper.dart @@ -1,4 +1,6 @@ +import 'dart:convert'; import 'dart:io' show Platform; +import 'package:crypto/crypto.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; @@ -30,12 +32,24 @@ class DatabaseHelper { final path = join(dbPath, 'telcotronics.db'); return databaseFactoryFfi.openDatabase( path, - options: OpenDatabaseOptions(version: 1, onCreate: _createTables), + options: OpenDatabaseOptions( + version: 2, + onCreate: _createTables, + onUpgrade: _onUpgrade, + ), ); } final dbPath = await getDatabasesPath(); final path = join(dbPath, 'telcotronics.db'); - return openDatabase(path, version: 1, onCreate: _createTables); + return openDatabase(path, version: 2, + onCreate: _createTables, onUpgrade: _onUpgrade); + } + + Future _onUpgrade(Database db, int oldVersion, int newVersion) async { + if (oldVersion < 2) { + await db.execute( + "ALTER TABLE pedidos ADD COLUMN sync_estado TEXT NOT NULL DEFAULT 'PENDIENTE'"); + } } Future _createTables(Database db, int version) async { @@ -112,6 +126,7 @@ class DatabaseHelper { fecha TEXT NOT NULL, notas TEXT, firma_base64 TEXT, + sync_estado TEXT NOT NULL DEFAULT 'PENDIENTE', FOREIGN KEY (cliente_id) REFERENCES clientes(id) ) '''); @@ -131,16 +146,50 @@ class DatabaseHelper { // ── Usuarios ──────────────────────────────────────────────── + static String _sha256(String input) => + sha256.convert(utf8.encode(input)).toString(); + Future insertUsuario(Vendedor v, String password) async { final db = await database; - await db.insert('usuarios', {...v.toMap(), 'password': password}, + await db.insert('usuarios', {...v.toMap(), 'password': _sha256(password)}, conflictAlgorithm: ConflictAlgorithm.ignore); } + /// Registra un usuario nuevo. Retorna false si el email ya existe. + Future registerUsuario({ + required String nombre, + required String email, + required String telefono, + required String empresa, + required String ruc, + required String password, + }) async { + final db = await database; + final exists = await db.query('usuarios', + where: 'email = ?', whereArgs: [email.toLowerCase()]); + if (exists.isNotEmpty) return false; + final id = 'local_${DateTime.now().millisecondsSinceEpoch}'; + await db.insert('usuarios', { + 'id': id, + 'nombre': nombre, + 'email': email.toLowerCase(), + 'telefono': telefono, + 'zona': empresa, + 'password': _sha256(password), + }); + return true; + } + Future?> loginUsuario(String email, String password) async { final db = await database; - final rows = await db.query('usuarios', - where: 'email = ? AND password = ?', whereArgs: [email, password]); + // Acepta hash SHA-256 o texto plano (compatibilidad con seeder viejo) + final hash = _sha256(password); + var rows = await db.query('usuarios', + where: 'email = ? AND password = ?', whereArgs: [email, hash]); + if (rows.isEmpty) { + rows = await db.query('usuarios', + where: 'email = ? AND password = ?', whereArgs: [email, password]); + } return rows.isEmpty ? null : rows.first; } @@ -320,6 +369,7 @@ class DatabaseHelper { fecha: DateTime.parse(row['fecha'] as String), notas: row['notas'] as String? ?? '', firmaBase64: row['firma_base64'] as String?, + syncEstado: row['sync_estado'] as String? ?? 'PENDIENTE', items: items, )); } @@ -342,6 +392,12 @@ class DatabaseHelper { where: 'id = ?', whereArgs: [pedidoId]); } + Future updateSyncEstadoPedido(String pedidoId, String syncEstado) async { + final db = await database; + await db.update('pedidos', {'sync_estado': syncEstado}, + where: 'id = ?', whereArgs: [pedidoId]); + } + Future updateFirmaPedido(String pedidoId, String firma) async { final db = await database; await db.update('pedidos', {'firma_base64': firma, 'estado': 'confirmado'}, diff --git a/lib/main.dart b/lib/main.dart index 34afb3d..0c61695 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -17,13 +17,16 @@ void main() async { )); final notifService = NotificationService(navigatorKey: _navigatorKey); + final appProvider = AppProvider(notifService: notifService); + + // Fire-and-forget: restaura sesión guardada si existe JWT válido. + // AppProvider._loading se activa internamente, la UI muestra _LoadingScreen. + appProvider.tryAutoLogin(); runApp( MultiProvider( providers: [ - ChangeNotifierProvider( - create: (_) => AppProvider(notifService: notifService), - ), + ChangeNotifierProvider.value(value: appProvider), ChangeNotifierProvider.value(value: notifService), ], child: PedidosApp(navigatorKey: _navigatorKey), diff --git a/lib/models/item_pedido.dart b/lib/models/item_pedido.dart index d32be2a..31f7196 100644 --- a/lib/models/item_pedido.dart +++ b/lib/models/item_pedido.dart @@ -22,4 +22,13 @@ class ItemPedido { 'cantidad': cantidad, 'precio_unitario': precioUnitario, }; + + /// Payload de un ítem para POST /api/documentos/pedidos — campo names del gateway. + Map toCloudDetalle() => { + 'PedUsoPrdctDet_codigoProducto': producto.sku, + 'PedUsoPrdct_cant': cantidad.toDouble(), + 'PedUsoPrdct_costo': precioUnitario, + 'PedUsoPrdct_desct': 0.0, + 'PedUsoPrdct_iva': 0.0, + }; } diff --git a/lib/models/pedido.dart b/lib/models/pedido.dart index c203800..428f13d 100644 --- a/lib/models/pedido.dart +++ b/lib/models/pedido.dart @@ -31,6 +31,7 @@ class Pedido { final DateTime fecha; String notas; String? firmaBase64; + String syncEstado; // 'PENDIENTE' | 'SINCRONIZADO' | 'ERROR' Pedido({ required this.id, @@ -40,6 +41,7 @@ class Pedido { required this.fecha, this.notas = '', this.firmaBase64, + this.syncEstado = 'PENDIENTE', }); double get subtotal => items.fold(0, (s, i) => s + i.subtotal); @@ -53,5 +55,24 @@ class Pedido { 'fecha': fecha.toIso8601String(), 'notas': notas, 'firma_base64': firmaBase64, + 'sync_estado': syncEstado, }; + + /// Payload para POST /api/documentos/pedidos — campo names del gateway SIGMA. + /// El número es el sufijo numérico del id local (TTC-0001 → 1). + Map toCloudEncabezado(String usuario) { + final num = int.tryParse(id.replaceAll(RegExp(r'[^0-9]'), '')) ?? 0; + return { + 'PedUsoPrdct_Num': num, + 'PedUsoPrdct_idClient': cliente.nit.isNotEmpty ? cliente.nit : cliente.id, + 'PedUsoPrdct_reg': fecha.toIso8601String(), + 'PedUsoPrdct_estado': 'PENDIENTE', + 'PedUsoPrdct_plataforma': 'AGENTE_VENTAS', + 'PedUsoPrdct_usuario': usuario, + 'PedUsoPrdct_valor': total, + 'PedUsoPrdct_iva': 0.0, + 'PedUsoPrdct_origen': 'app', + 'PedUsoPrdct_OBSERVACION': notas, + }; + } } diff --git a/lib/providers/app_provider.dart b/lib/providers/app_provider.dart index 7039b25..f953d64 100644 --- a/lib/providers/app_provider.dart +++ b/lib/providers/app_provider.dart @@ -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 _pedidos = []; List _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 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 login(String email, String password) async { + Future 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 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 _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 _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 _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(); diff --git a/lib/services/cloud_sync_service.dart b/lib/services/cloud_sync_service.dart index 1b84263..39abeba 100644 --- a/lib/services/cloud_sync_service.dart +++ b/lib/services/cloud_sync_service.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; +import '../models/pedido.dart'; // URL idéntica a sigmac_app/gateway_cloud_api.dart const _kBase = 'https://api-gateway-cloud.telcotronics.net'; @@ -159,6 +160,33 @@ class CloudSyncService { .toList(); } + // ── Upload Pedidos ───────────────────────────────────────────────────────── + + /// Sube un pedido al cloud. + /// Endpoint: POST /api/documentos/pedidos?db={db} + /// Body: { encabezado: {...}, detalles: [...] } + static Future uploadPedido(Pedido pedido, String usuario) async { + final db = await _requireDb(); + final headers = await _headers(); + headers['Content-Type'] = 'application/json'; + + final uri = Uri.parse('$_kBase/api/documentos/pedidos') + .replace(queryParameters: {'db': db}); + + final res = await http + .post( + uri, + headers: headers, + body: jsonEncode({ + 'encabezado': pedido.toCloudEncabezado(usuario), + 'detalles': pedido.items.map((i) => i.toCloudDetalle()).toList(), + }), + ) + .timeout(const Duration(seconds: 20)); + + _checkStatus(res); + } + // ── Helper ───────────────────────────────────────────────────────────────── static void _checkStatus(http.Response res) {