Files

835 lines
28 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.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 '../models/moneda.dart';
import '../services/notification_service.dart';
import '../services/auth_service.dart';
import '../services/cloud_sync_service.dart';
// Integración con el Gateway Sigma-Robot para envío de alertas operativas por WhatsApp
import '../services/whatsapp_service.dart';
// Integración con la Bitácora Centralizada de Errores para reintento de cola offline
import '../services/bitacora_service.dart';
/// Resumen de resultado para procesos de sincronización manual y automática
class SyncSummary {
final bool ok;
final int pedidosSubidos;
final int pedidosFallidos;
final int itemsSynced;
final int clientesSynced;
final String mensaje;
const SyncSummary({
required this.ok,
this.pedidosSubidos = 0,
this.pedidosFallidos = 0,
this.itemsSynced = 0,
this.clientesSynced = 0,
required this.mensaje,
});
}
class AppProvider extends ChangeNotifier {
final _db = DatabaseHelper();
final NotificationService? _notifService;
AppProvider({NotificationService? notifService}) : _notifService = notifService {
_loadMonedaPref();
}
// ── Estado de sesión ─────────────────────────────────────────
bool _isLoggedIn = false;
bool _loading = false;
bool _autoLoginAttempted = false;
String? _loginError;
Vendedor? _vendedor;
// Tokens de sesión cloud (vacíos en modo offline)
String _jwt = '';
String _apiKey = '';
String _dbTenant = '';
bool _modoOnline = false;
// Contadores de última sincronización
int _itemsSynced = 0;
int _clientesSynced = 0;
// Estado reactivo de sincronización manual / automática
bool _syncing = false;
DateTime? _ultimoSync;
String? _ultimoSyncError;
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 = '';
// ── Preferencia de moneda ─────────────────────────────────────
Moneda _moneda = Moneda.porDefecto;
// ── 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;
int get itemsSynced => _itemsSynced;
int get clientesSynced => _clientesSynced;
// Getters para el estado visual de sincronización en tiempo real
bool get syncing => _syncing;
DateTime? get ultimoSync => _ultimoSync;
String? get ultimoSyncError => _ultimoSyncError;
int get pedidosPendientesSync =>
_pedidos.where((p) => p.syncEstado == 'PENDIENTE').length;
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);
Moneda get moneda => _moneda;
NumberFormat get currencyFormat =>
NumberFormat.currency(locale: _moneda.locale, symbol: _moneda.simbolo, decimalDigits: 2);
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);
// ── Preferencia de moneda ─────────────────────────────────────
Future<void> _loadMonedaPref() async {
try {
final prefs = await SharedPreferences.getInstance();
final codigo = prefs.getString('pref_moneda_codigo');
if (codigo != null) {
_moneda = Moneda.porCodigo(codigo);
notifyListeners();
}
} catch (e) {
debugPrint('[Moneda] error cargando preferencia: $e');
}
}
Future<void> setMoneda(Moneda moneda) async {
_moneda = moneda;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setString('pref_moneda_codigo', moneda.codigo);
}
// ── 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<void> 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<bool> login(String email, String password,
{bool rememberMe = true}) async {
_loginError = null;
_loading = true;
notifyListeners();
try {
final session = await AuthService.login(email.trim(), password);
if (session != null) {
await AuthService.saveSession(session, email.trim(),
rememberMe: rememberMe);
_apiKey = session.apiKey;
_dbTenant = session.dbTenant;
_jwt = session.token;
_modoOnline = true;
_vendedor = _vendedorFromSession(session, email.trim());
// Asegurar que la base de datos local contenga datos de prueba para la revisión de tienda
final isDemo = session.token == 'demo_jwt_token_store_review';
final seeded = await _db.isSeeded();
if (!seeded || isDemo) await DbSeeder(_db).seed();
// Si es la sesión demo para evaluadores de la tienda, evitar llamadas a APIs externas
// para garantizar que la app cargue de inmediato con todos los datos sin depender de red
if (!isDemo) {
await _syncCloudData();
await _uploadPendingPedidos();
}
await _loadAllData();
_loading = false;
_isLoggedIn = true;
notifyListeners();
return true;
}
// Fallback offline — sin red o timeout
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;
}
}
/// Login exclusivamente local — sin intentar cloud.
/// Usado cuando el toggle está en "Cuenta local".
Future<bool> 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();
var row = await _db.loginUsuario(usuario.trim(), password);
if (row == null) {
// En caso de que la base de datos local haya sido creada antes de incorporar el usuario demo,
// forzamos el re-sembrado para asegurar que el evaluador de tienda siempre pueda acceder
final cleanUser = usuario.trim().toLowerCase();
if ((cleanUser == 'demo@empresa.com' || cleanUser == 'demo' || cleanUser == 'demo@telcotronics.com') &&
password == '123456') {
await DbSeeder(_db).seed();
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<void> _syncCloudData() async {
_itemsSynced = 0;
_clientesSynced = 0;
try {
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(),
precio: productoExistente?.precio ?? 0.0,
precioMayorista: productoExistente?.precioMayorista ?? 0.0,
emoji: productoExistente?.emoji ?? '📦',
);
await _db.insertProducto(p);
}
_itemsSynced = items.length;
debugPrint('[Sync] items: ${items.length}');
} catch (e) {
debugPrint('[Sync] items error: $e');
}
try {
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);
}
_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<void> _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;
return Vendedor(
id: session.usrSesionId?.toString() ?? session.usuario,
nombre: nombre,
email: email,
telefono: '',
zona: '',
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<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);
// 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);
// Envío asíncrono en segundo plano de alerta operativa vía Sigma-Robot Gateway
// si el vendedor tiene configurado y vinculado un número de WhatsApp
if (_vendedor != null && _vendedor!.telefono.isNotEmpty) {
final tel = _vendedor!.telefono;
final clienteNombre = _clienteSeleccionado!.nombre;
final vendedorNombre = _vendedor!.nombre;
WhatsAppService.enviarAlertaPedido(
telefono: tel,
pedido: pedido,
nombreCliente: clienteNombre,
nombreVendedor: vendedorNombre,
).catchError((err) {
debugPrint('[WhatsApp Alert] Error al despachar alerta de pedido: $err');
return const WhatsAppEnvioResult(
ok: false,
error: 'Error de red al despachar alerta',
numeroDestino: '',
);
});
}
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();
}
// ── Alertas de WhatsApp y Teléfono de Vendedor ───────────────
// Actualiza el número telefónico del perfil en memoria, SQLite local y SharedPreferences
Future<void> actualizarTelefonoVendedor(String nuevoTelefono) async {
if (_vendedor == null) return;
_vendedor = _vendedor!.copyWith(telefono: nuevoTelefono);
await _db.updateUsuarioTelefono(_vendedor!.id, nuevoTelefono);
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('auth_telefono', nuevoTelefono);
} catch (_) {}
notifyListeners();
}
// ── Sincronización Manual y Reintento Cloud ──────────────────
/// Sincronización bidireccional manual:
/// 1. Sube al cloud los pedidos locales pendientes de sincronizar
/// 2. Descarga ítems y clientes actualizados desde API-SIGMA-CLOUD
/// 3. Reintenta eventos pendientes en la bitácora centralizada de errores
/// 4. Recarga SQLite local y notifica a la UI para refrescar badges e indicadores
Future<SyncSummary> sincronizarManual() async {
if (_syncing) {
return const SyncSummary(ok: false, mensaje: 'Sincronización en curso...');
}
_syncing = true;
_ultimoSyncError = null;
notifyListeners();
int subidos = 0;
int fallidos = 0;
try {
final isDemo = _jwt == 'demo_jwt_token_store_review';
if (_modoOnline && _apiKey.isNotEmpty && !isDemo) {
// 1. Subir pedidos pendientes o con error previo
final pendientes = _pedidos
.where((p) => p.syncEstado == 'PENDIENTE' || p.syncEstado == 'ERROR')
.toList();
for (final p in pendientes) {
try {
await CloudSyncService.uploadPedido(p, _vendedor?.id ?? '');
await _db.updateSyncEstadoPedido(p.id, 'SINCRONIZADO');
p.syncEstado = 'SINCRONIZADO';
subidos++;
} catch (e) {
fallidos++;
await _db.updateSyncEstadoPedido(p.id, 'ERROR');
p.syncEstado = 'ERROR';
}
}
// 2. Descargar catálogo y clientes actualizados
await _syncCloudData();
// 3. Reintentar cola de bitácora de errores si quedó algo pendiente
await BitacoraService.reintentarColaPendiente();
}
// Recarga de datos locales
await _loadAllData();
_ultimoSync = DateTime.now();
_syncing = false;
notifyListeners();
String msg;
if (isDemo) {
msg = 'Modo Demo: Datos locales de prueba actualizados.';
} else if (!_modoOnline) {
msg = 'Modo local: Datos de SQLite recargados.';
} else if (fallidos > 0) {
msg = 'Sincronización parcial: $subidos pedidos subidos, $fallidos pendientes.';
} else if (subidos > 0) {
msg = '¡Éxito! $subidos pedido${subidos == 1 ? '' : 's'} subido${subidos == 1 ? '' : 's'} a la nube.';
} else {
msg = 'Nube al día: Catálogo y clientes sincronizados.';
}
return SyncSummary(
ok: fallidos == 0,
pedidosSubidos: subidos,
pedidosFallidos: fallidos,
itemsSynced: _itemsSynced,
clientesSynced: _clientesSynced,
mensaje: msg,
);
} catch (e) {
_ultimoSyncError = e.toString();
_syncing = false;
notifyListeners();
return SyncSummary(
ok: false,
pedidosSubidos: subidos,
pedidosFallidos: fallidos,
mensaje: 'Error de sincronización: $e',
);
}
}
/// Reintenta subir de forma individual un pedido específico
Future<bool> reintentarSubidaPedido(String pedidoId) async {
final idx = _pedidos.indexWhere((p) => p.id == pedidoId);
if (idx == -1) return false;
final pedido = _pedidos[idx];
if (!_modoOnline || _apiKey.isEmpty) {
return false;
}
try {
await CloudSyncService.uploadPedido(pedido, _vendedor?.id ?? '');
await _db.updateSyncEstadoPedido(pedido.id, 'SINCRONIZADO');
pedido.syncEstado = 'SINCRONIZADO';
notifyListeners();
return true;
} catch (e) {
await _db.updateSyncEstadoPedido(pedido.id, 'ERROR');
pedido.syncEstado = 'ERROR';
notifyListeners();
return false;
}
}
// ── 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')}';
}
}