feat: Agente Ventas SIGMAC — app de rutas y pedidos de campo
App Flutter 2.11 para vendedores de ruta de Telcotronics. Incluye ruta del día con mapa custom, catálogo, pedidos CRUD, firma digital, scanner QR/barcode, selector de clientes escalable, notificaciones in-app y soporte multiplataforma (Android + Linux desktop). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,311 @@
|
||||
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';
|
||||
|
||||
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;
|
||||
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;
|
||||
|
||||
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();
|
||||
|
||||
// Seed si es la primera vez
|
||||
final seeded = await _db.isSeeded();
|
||||
if (!seeded) await DbSeeder(_db).seed();
|
||||
|
||||
final row = await _db.loginUsuario(email.trim(), password);
|
||||
if (row == null) {
|
||||
_loginError = 'Correo o contraseña incorrectos';
|
||||
_loading = false;
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
|
||||
_vendedor = Vendedor.fromMap(row);
|
||||
await _loadAllData();
|
||||
|
||||
_loading = false;
|
||||
_isLoggedIn = true;
|
||||
notifyListeners();
|
||||
return true;
|
||||
}
|
||||
|
||||
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() {
|
||||
_isLoggedIn = false;
|
||||
_vendedor = null;
|
||||
_ruta = null;
|
||||
_pedidos = [];
|
||||
_productos = [];
|
||||
_clientes = [];
|
||||
_clientesMap = {};
|
||||
_productosMap = {};
|
||||
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')}';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user