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,359 @@
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:path/path.dart';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.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';
|
||||
|
||||
class DatabaseHelper {
|
||||
static final DatabaseHelper _instance = DatabaseHelper._();
|
||||
factory DatabaseHelper() => _instance;
|
||||
DatabaseHelper._();
|
||||
|
||||
static Database? _db;
|
||||
|
||||
Future<Database> get database async {
|
||||
_db ??= await _initDB();
|
||||
return _db!;
|
||||
}
|
||||
|
||||
Future<Database> _initDB() async {
|
||||
if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) {
|
||||
sqfliteFfiInit();
|
||||
final dbPath = await databaseFactoryFfi.getDatabasesPath();
|
||||
final path = join(dbPath, 'telcotronics.db');
|
||||
return databaseFactoryFfi.openDatabase(
|
||||
path,
|
||||
options: OpenDatabaseOptions(version: 1, onCreate: _createTables),
|
||||
);
|
||||
}
|
||||
final dbPath = await getDatabasesPath();
|
||||
final path = join(dbPath, 'telcotronics.db');
|
||||
return openDatabase(path, version: 1, onCreate: _createTables);
|
||||
}
|
||||
|
||||
Future<void> _createTables(Database db, int version) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE usuarios (
|
||||
id TEXT PRIMARY KEY,
|
||||
nombre TEXT NOT NULL,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
password TEXT NOT NULL,
|
||||
telefono TEXT,
|
||||
zona TEXT,
|
||||
avatar_initials TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE clientes (
|
||||
id TEXT PRIMARY KEY,
|
||||
nombre TEXT NOT NULL,
|
||||
razon_social TEXT,
|
||||
direccion TEXT,
|
||||
telefono TEXT,
|
||||
nit TEXT,
|
||||
lat REAL DEFAULT 0,
|
||||
lng REAL DEFAULT 0,
|
||||
categoria TEXT DEFAULT 'Minorista'
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE productos (
|
||||
id TEXT PRIMARY KEY,
|
||||
sku TEXT UNIQUE NOT NULL,
|
||||
nombre TEXT NOT NULL,
|
||||
descripcion TEXT,
|
||||
categoria TEXT,
|
||||
precio REAL NOT NULL,
|
||||
precio_mayorista REAL NOT NULL,
|
||||
unidad TEXT DEFAULT 'unidad',
|
||||
stock INTEGER DEFAULT 0,
|
||||
emoji TEXT DEFAULT '📦'
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE rutas (
|
||||
id TEXT PRIMARY KEY,
|
||||
nombre TEXT NOT NULL,
|
||||
zona TEXT,
|
||||
fecha TEXT NOT NULL
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE paradas_ruta (
|
||||
id TEXT PRIMARY KEY,
|
||||
ruta_id TEXT NOT NULL,
|
||||
cliente_id TEXT NOT NULL,
|
||||
orden INTEGER NOT NULL,
|
||||
estado TEXT NOT NULL DEFAULT 'pendiente',
|
||||
hora_estimada TEXT,
|
||||
hora_visita TEXT,
|
||||
notas_visita TEXT,
|
||||
FOREIGN KEY (ruta_id) REFERENCES rutas(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (cliente_id) REFERENCES clientes(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE pedidos (
|
||||
id TEXT PRIMARY KEY,
|
||||
cliente_id TEXT NOT NULL,
|
||||
estado TEXT NOT NULL DEFAULT 'pendiente',
|
||||
fecha TEXT NOT NULL,
|
||||
notas TEXT,
|
||||
firma_base64 TEXT,
|
||||
FOREIGN KEY (cliente_id) REFERENCES clientes(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE items_pedido (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pedido_id TEXT NOT NULL,
|
||||
producto_id TEXT NOT NULL,
|
||||
cantidad INTEGER NOT NULL,
|
||||
precio_unitario REAL NOT NULL,
|
||||
FOREIGN KEY (pedido_id) REFERENCES pedidos(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (producto_id) REFERENCES productos(id)
|
||||
)
|
||||
''');
|
||||
}
|
||||
|
||||
// ── Usuarios ────────────────────────────────────────────────
|
||||
|
||||
Future<void> insertUsuario(Vendedor v, String password) async {
|
||||
final db = await database;
|
||||
await db.insert('usuarios', {...v.toMap(), 'password': password},
|
||||
conflictAlgorithm: ConflictAlgorithm.ignore);
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>?> loginUsuario(String email, String password) async {
|
||||
final db = await database;
|
||||
final rows = await db.query('usuarios',
|
||||
where: 'email = ? AND password = ?', whereArgs: [email, password]);
|
||||
return rows.isEmpty ? null : rows.first;
|
||||
}
|
||||
|
||||
Future<Vendedor?> getVendedor(String id) async {
|
||||
final db = await database;
|
||||
final rows = await db.query('usuarios', where: 'id = ?', whereArgs: [id]);
|
||||
return rows.isEmpty ? null : Vendedor.fromMap(rows.first);
|
||||
}
|
||||
|
||||
// ── Clientes ────────────────────────────────────────────────
|
||||
|
||||
Future<List<Cliente>> getClientes() async {
|
||||
final db = await database;
|
||||
final rows = await db.query('clientes', orderBy: 'nombre ASC');
|
||||
return rows.map(Cliente.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<void> insertCliente(Cliente c) async {
|
||||
final db = await database;
|
||||
await db.insert('clientes', c.toMap(),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
|
||||
Future<void> updateCliente(Cliente c) async {
|
||||
final db = await database;
|
||||
await db.update('clientes', c.toMap(), where: 'id = ?', whereArgs: [c.id]);
|
||||
}
|
||||
|
||||
Future<void> deleteCliente(String id) async {
|
||||
final db = await database;
|
||||
await db.delete('clientes', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
// ── Productos ────────────────────────────────────────────────
|
||||
|
||||
Future<List<Producto>> getProductos() async {
|
||||
final db = await database;
|
||||
final rows = await db.query('productos', orderBy: 'categoria ASC, nombre ASC');
|
||||
return rows.map(Producto.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<void> insertProducto(Producto p) async {
|
||||
final db = await database;
|
||||
await db.insert('productos', p.toMap(),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
|
||||
Future<void> updateProducto(Producto p) async {
|
||||
final db = await database;
|
||||
await db.update('productos', p.toMap(), where: 'id = ?', whereArgs: [p.id]);
|
||||
}
|
||||
|
||||
Future<void> updateStock(String productoId, int nuevoStock) async {
|
||||
final db = await database;
|
||||
await db.update('productos', {'stock': nuevoStock},
|
||||
where: 'id = ?', whereArgs: [productoId]);
|
||||
}
|
||||
|
||||
// ── Rutas ────────────────────────────────────────────────────
|
||||
|
||||
Future<String?> getRutaIdHoy() async {
|
||||
final db = await database;
|
||||
final hoy = DateTime.now().toIso8601String().substring(0, 10);
|
||||
final rows = await db.query('rutas',
|
||||
where: "fecha LIKE ?", whereArgs: ['$hoy%']);
|
||||
return rows.isEmpty ? null : rows.first['id'] as String;
|
||||
}
|
||||
|
||||
Future<Ruta?> getRutaConParadas(
|
||||
String rutaId, Map<String, Cliente> clientesMap) async {
|
||||
final db = await database;
|
||||
final rutaRows = await db.query('rutas', where: 'id = ?', whereArgs: [rutaId]);
|
||||
if (rutaRows.isEmpty) return null;
|
||||
final r = rutaRows.first;
|
||||
|
||||
final paradaRows = await db.query('paradas_ruta',
|
||||
where: 'ruta_id = ?', whereArgs: [rutaId], orderBy: 'orden ASC');
|
||||
|
||||
final paradas = paradaRows.map((row) {
|
||||
final cliente = clientesMap[row['cliente_id'] as String];
|
||||
if (cliente == null) return null;
|
||||
return ParadaRuta(
|
||||
id: row['id'] as String,
|
||||
cliente: cliente,
|
||||
orden: row['orden'] as int,
|
||||
estado: EstadoParadaExt.fromString(row['estado'] as String),
|
||||
horaEstimada: row['hora_estimada'] as String? ?? '',
|
||||
horaVisita: row['hora_visita'] as String?,
|
||||
notasVisita: row['notas_visita'] as String?,
|
||||
);
|
||||
}).whereType<ParadaRuta>().toList();
|
||||
|
||||
return Ruta(
|
||||
id: r['id'] as String,
|
||||
nombre: r['nombre'] as String,
|
||||
zona: r['zona'] as String? ?? '',
|
||||
paradas: paradas,
|
||||
fecha: DateTime.parse(r['fecha'] as String),
|
||||
);
|
||||
}
|
||||
|
||||
Future<String> insertRuta(Ruta ruta) async {
|
||||
final db = await database;
|
||||
await db.insert('rutas', ruta.toMap(),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
return ruta.id;
|
||||
}
|
||||
|
||||
Future<void> insertParada(ParadaRuta parada, String rutaId) async {
|
||||
final db = await database;
|
||||
await db.insert('paradas_ruta', parada.toMap(rutaId),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
|
||||
Future<void> updateParadaEstado(
|
||||
String paradaId, String estado, String? horaVisita) async {
|
||||
final db = await database;
|
||||
await db.update(
|
||||
'paradas_ruta',
|
||||
{'estado': estado, 'hora_visita': horaVisita},
|
||||
where: 'id = ?',
|
||||
whereArgs: [paradaId],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> deleteParada(String paradaId) async {
|
||||
final db = await database;
|
||||
await db.delete('paradas_ruta', where: 'id = ?', whereArgs: [paradaId]);
|
||||
}
|
||||
|
||||
Future<void> reordenarParadas(List<ParadaRuta> paradas, String rutaId) async {
|
||||
final db = await database;
|
||||
final batch = db.batch();
|
||||
for (int i = 0; i < paradas.length; i++) {
|
||||
batch.update('paradas_ruta', {'orden': i + 1},
|
||||
where: 'id = ?', whereArgs: [paradas[i].id]);
|
||||
}
|
||||
await batch.commit(noResult: true);
|
||||
}
|
||||
|
||||
// ── Pedidos ─────────────────────────────────────────────────
|
||||
|
||||
Future<List<Pedido>> getPedidos(
|
||||
Map<String, Cliente> clientesMap, Map<String, Producto> productosMap) async {
|
||||
final db = await database;
|
||||
final pedidoRows = await db.query('pedidos', orderBy: 'fecha DESC');
|
||||
|
||||
final pedidos = <Pedido>[];
|
||||
for (final row in pedidoRows) {
|
||||
final cliente = clientesMap[row['cliente_id'] as String];
|
||||
if (cliente == null) continue;
|
||||
|
||||
final itemRows = await db.query('items_pedido',
|
||||
where: 'pedido_id = ?', whereArgs: [row['id']]);
|
||||
|
||||
final items = itemRows.map((ir) {
|
||||
final producto = productosMap[ir['producto_id'] as String];
|
||||
if (producto == null) return null;
|
||||
return ItemPedido(
|
||||
dbId: ir['id'] as int?,
|
||||
producto: producto,
|
||||
cantidad: ir['cantidad'] as int,
|
||||
precioUnitario: (ir['precio_unitario'] as num).toDouble(),
|
||||
);
|
||||
}).whereType<ItemPedido>().toList();
|
||||
|
||||
pedidos.add(Pedido(
|
||||
id: row['id'] as String,
|
||||
cliente: cliente,
|
||||
estado: EstadoPedidoExt.fromString(row['estado'] as String),
|
||||
fecha: DateTime.parse(row['fecha'] as String),
|
||||
notas: row['notas'] as String? ?? '',
|
||||
firmaBase64: row['firma_base64'] as String?,
|
||||
items: items,
|
||||
));
|
||||
}
|
||||
return pedidos;
|
||||
}
|
||||
|
||||
Future<void> insertPedido(Pedido pedido) async {
|
||||
final db = await database;
|
||||
await db.insert('pedidos', pedido.toMap(),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
for (final item in pedido.items) {
|
||||
await db.insert('items_pedido', item.toMap(pedido.id),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateEstadoPedido(String pedidoId, String estado) async {
|
||||
final db = await database;
|
||||
await db.update('pedidos', {'estado': estado},
|
||||
where: 'id = ?', whereArgs: [pedidoId]);
|
||||
}
|
||||
|
||||
Future<void> updateFirmaPedido(String pedidoId, String firma) async {
|
||||
final db = await database;
|
||||
await db.update('pedidos', {'firma_base64': firma, 'estado': 'confirmado'},
|
||||
where: 'id = ?', whereArgs: [pedidoId]);
|
||||
}
|
||||
|
||||
Future<void> deletePedido(String pedidoId) async {
|
||||
final db = await database;
|
||||
await db.delete('pedidos', where: 'id = ?', whereArgs: [pedidoId]);
|
||||
}
|
||||
|
||||
// ── Utilidades ───────────────────────────────────────────────
|
||||
|
||||
Future<bool> isSeeded() async {
|
||||
final db = await database;
|
||||
final rows = await db.query('productos', limit: 1);
|
||||
return rows.isNotEmpty;
|
||||
}
|
||||
|
||||
Future<void> close() async => (await database).close();
|
||||
}
|
||||
Reference in New Issue
Block a user