Files
APP_PEDIDOS_SIGMA/lib/providers/app_provider.dart
T
PablinuxandClaude Sonnet 4.6 0c09e10e4d 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>
2026-06-14 09:37:50 -05:00

432 lines
15 KiB
Dart

import 'package:flutter/foundation.dart';
import '../database/database_helper.dart';
import '../database/db_seeder.dart';
import '../models/vendedor.dart';
import '../models/cliente.dart';
import '../models/producto.dart';
import '../models/pedido.dart';
import '../models/item_pedido.dart';
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();
final NotificationService? _notifService;
AppProvider({NotificationService? notifService}) : _notifService = notifService;
// ── Estado de sesión ─────────────────────────────────────────
bool _isLoggedIn = false;
bool _loading = false;
String? _loginError;
Vendedor? _vendedor;
// Tokens de sesión cloud (vacíos en modo offline)
String _jwt = '';
String _apiKey = '';
String _dbTenant = '';
bool _modoOnline = false;
Ruta? _ruta;
List<Pedido> _pedidos = [];
List<Producto> _productos = [];
List<Cliente> _clientes = [];
// índices en memoria para joins rápidos
Map<String, Cliente> _clientesMap = {};
Map<String, Producto> _productosMap = {};
// ── Carrito activo ───────────────────────────────────────────
Cliente? _clienteSeleccionado;
final List<ItemPedido> _carrito = [];
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;
Vendedor get vendedor => _vendedor!;
Ruta get ruta => _ruta!;
List<Pedido> get pedidos => _pedidos;
List<Producto> get productos => _productos;
List<Cliente> get clientes => _clientes;
Cliente? get clienteSeleccionado => _clienteSeleccionado;
List<ItemPedido> get carrito => _carrito;
String get notasPedido => _notasPedido;
double get totalCarrito => _carrito.fold(0, (s, i) => s + i.subtotal);
int get cantidadCarrito => _carrito.fold(0, (s, i) => s + i.cantidad);
List<Cliente> get clientesSinParada {
final ids = _ruta?.paradas.map((p) => p.cliente.id).toSet() ?? {};
return _clientes.where((c) => !ids.contains(c.id)).toList();
}
// ── Stats del día ────────────────────────────────────────────
int get pedidosHoy => _pedidos.where((p) {
final now = DateTime.now();
return p.fecha.day == now.day && p.fecha.month == now.month &&
p.estado != EstadoPedido.cancelado;
}).length;
double get ventasTotalesHoy => _pedidos.where((p) {
final now = DateTime.now();
return p.fecha.day == now.day && p.fecha.month == now.month &&
p.estado != EstadoPedido.cancelado;
}).fold(0, (s, p) => s + p.total);
// ── Login / Logout ───────────────────────────────────────────
Future<bool> login(String email, String password) 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());
_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();
_loading = false;
_isLoggedIn = true;
notifyListeners();
return true;
}
// 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 = 'Sin conexión. Verifica tu internet o las credenciales locales.';
_loading = false;
notifyListeners();
return false;
}
_vendedor = Vendedor.fromMap(row);
_modoOnline = false;
await _loadAllData();
_loading = false;
_isLoggedIn = true;
notifyListeners();
return true;
} on AuthException catch (e) {
_loginError = e.message;
_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<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: session.usrSesionId?.toString() ?? session.usuario,
nombre: nombre,
email: email,
telefono: '',
zona: '',
avatarInitials: initials,
);
}
Future<void> _loadAllData() async {
// 1. catálogo y clientes (base para joins)
_productos = await _db.getProductos();
_clientes = await _db.getClientes();
_productosMap = {for (final p in _productos) p.id: p};
_clientesMap = {for (final c in _clientes) c.id: c};
// 2. Ruta de hoy (o crear una vacía)
final rutaId = await _db.getRutaIdHoy();
if (rutaId != null) {
_ruta = await _db.getRutaConParadas(rutaId, _clientesMap) ?? _emptyRuta();
} else {
_ruta = _emptyRuta();
await _db.insertRuta(_ruta!);
}
// 3. Pedidos
_pedidos = await _db.getPedidos(_clientesMap, _productosMap);
}
Ruta _emptyRuta() => Ruta(
id: 'ruta_${DateTime.now().toIso8601String().substring(0, 10)}',
nombre: 'Ruta del día',
zona: _vendedor?.zona ?? '',
paradas: [],
fecha: DateTime.now(),
);
void logout() {
AuthService.clearSession(); // fire-and-forget — borrar SharedPrefs
_isLoggedIn = false;
_vendedor = null;
_ruta = null;
_pedidos = [];
_productos = [];
_clientes = [];
_clientesMap = {};
_productosMap = {};
_jwt = '';
_apiKey = '';
_dbTenant = '';
_modoOnline = false;
limpiarCarrito();
notifyListeners();
}
// ── Clientes ─────────────────────────────────────────────────
Future<void> agregarCliente(Cliente cliente, {bool agregarARuta = false}) async {
await _db.insertCliente(cliente);
_clientes.add(cliente);
_clientesMap[cliente.id] = cliente;
if (agregarARuta) {
await agregarParadaARuta(cliente, _horaDefault());
} else {
notifyListeners();
}
}
Future<void> actualizarCliente(Cliente cliente) async {
await _db.updateCliente(cliente);
final idx = _clientes.indexWhere((c) => c.id == cliente.id);
if (idx >= 0) _clientes[idx] = cliente;
_clientesMap[cliente.id] = cliente;
notifyListeners();
}
// ── Productos ────────────────────────────────────────────────
Future<void> actualizarStock(String productoId, int nuevoStock) async {
await _db.updateStock(productoId, nuevoStock);
final idx = _productos.indexWhere((p) => p.id == productoId);
if (idx >= 0) {
_productos[idx] = _productos[idx].copyWith(stock: nuevoStock);
_productosMap[productoId] = _productos[idx];
if (nuevoStock <= 5) {
_notifService?.notifStockBajo(_productos[idx].nombre, nuevoStock);
}
}
notifyListeners();
}
// ── Ruta / Paradas ───────────────────────────────────────────
Future<void> agregarParadaARuta(Cliente cliente, String horaEstimada) async {
final nuevaOrden = (_ruta?.paradas.length ?? 0) + 1;
final parada = ParadaRuta(
id: 'pr_${DateTime.now().millisecondsSinceEpoch}',
cliente: cliente,
orden: nuevaOrden,
estado: EstadoParada.pendiente,
horaEstimada: horaEstimada,
);
await _db.insertParada(parada, _ruta!.id);
_ruta!.paradas.add(parada);
notifyListeners();
}
Future<void> eliminarParada(String paradaId) async {
await _db.deleteParada(paradaId);
_ruta!.paradas.removeWhere((p) => p.id == paradaId);
// reordenar
for (int i = 0; i < _ruta!.paradas.length; i++) {
_ruta!.paradas[i] = ParadaRuta(
id: _ruta!.paradas[i].id,
cliente: _ruta!.paradas[i].cliente,
orden: i + 1,
estado: _ruta!.paradas[i].estado,
horaEstimada: _ruta!.paradas[i].horaEstimada,
horaVisita: _ruta!.paradas[i].horaVisita,
);
}
await _db.reordenarParadas(_ruta!.paradas, _ruta!.id);
notifyListeners();
}
Future<void> marcarParadaVisitada(String paradaId) async {
final hora = _horaActual();
await _db.updateParadaEstado(paradaId, 'visitado', hora);
final parada = _ruta!.paradas.firstWhere((p) => p.id == paradaId);
parada.estado = EstadoParada.visitado;
parada.horaVisita = hora;
_notifService?.notifParadaVisitada(parada.cliente.nombre);
notifyListeners();
}
// ── Carrito ──────────────────────────────────────────────────
void seleccionarCliente(Cliente cliente) {
_clienteSeleccionado = cliente;
notifyListeners();
}
void agregarAlCarrito(Producto producto, {bool esMayorista = false}) {
final precio = esMayorista ? producto.precioMayorista : producto.precio;
final existente = _carrito.where((i) => i.producto.id == producto.id);
if (existente.isNotEmpty) {
existente.first.cantidad++;
} else {
_carrito.add(ItemPedido(producto: producto, cantidad: 1, precioUnitario: precio));
}
notifyListeners();
}
void quitarDelCarrito(String productoId) {
_carrito.removeWhere((i) => i.producto.id == productoId);
notifyListeners();
}
void actualizarCantidad(String productoId, int cantidad) {
if (cantidad <= 0) { quitarDelCarrito(productoId); return; }
_carrito.firstWhere((i) => i.producto.id == productoId).cantidad = cantidad;
notifyListeners();
}
void setNotasPedido(String notas) {
_notasPedido = notas;
notifyListeners();
}
void limpiarCarrito() {
_carrito.clear();
_clienteSeleccionado = null;
_notasPedido = '';
notifyListeners();
}
// ── Pedidos ──────────────────────────────────────────────────
Future<Pedido> confirmarPedido({String? firmaBase64}) async {
final id = 'TTC-${(_pedidos.length + 1).toString().padLeft(4, '0')}';
final pedido = Pedido(
id: id,
cliente: _clienteSeleccionado!,
items: List.from(_carrito),
estado: EstadoPedido.confirmado,
fecha: DateTime.now(),
notas: _notasPedido,
firmaBase64: firmaBase64,
);
await _db.insertPedido(pedido);
_pedidos.insert(0, pedido);
_notifService?.notifPedidoConfirmado(id, _clienteSeleccionado!.nombre);
limpiarCarrito();
notifyListeners();
return pedido;
}
Future<void> cambiarEstadoPedido(String pedidoId, EstadoPedido nuevoEstado) async {
await _db.updateEstadoPedido(pedidoId, nuevoEstado.label.toLowerCase());
final pedido = _pedidos.firstWhere((p) => p.id == pedidoId);
pedido.estado = nuevoEstado;
notifyListeners();
}
Future<void> eliminarPedido(String pedidoId) async {
await _db.deletePedido(pedidoId);
_pedidos.removeWhere((p) => p.id == pedidoId);
notifyListeners();
}
// ── Helpers ──────────────────────────────────────────────────
String _horaDefault() {
final now = DateTime.now();
final h = now.hour.toString().padLeft(2, '0');
final m = ((now.minute ~/ 15 + 1) * 15 % 60).toString().padLeft(2, '0');
return '$h:$m';
}
String _horaActual() {
final now = DateTime.now();
return '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
}
}