436 lines
15 KiB
Dart
436 lines
15 KiB
Dart
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';
|
|
|
|
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: 2,
|
|
onCreate: _createTables,
|
|
onUpgrade: _onUpgrade,
|
|
),
|
|
);
|
|
}
|
|
final dbPath = await getDatabasesPath();
|
|
final path = join(dbPath, 'telcotronics.db');
|
|
return openDatabase(path, version: 2,
|
|
onCreate: _createTables, onUpgrade: _onUpgrade);
|
|
}
|
|
|
|
Future<void> _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<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,
|
|
sync_estado TEXT NOT NULL DEFAULT 'PENDIENTE',
|
|
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 ────────────────────────────────────────────────
|
|
|
|
static String _sha256(String input) =>
|
|
sha256.convert(utf8.encode(input)).toString();
|
|
|
|
Future<void> insertUsuario(Vendedor v, String password) async {
|
|
final db = await database;
|
|
await db.insert('usuarios', {...v.toMap(), 'password': _sha256(password)},
|
|
conflictAlgorithm: ConflictAlgorithm.ignore);
|
|
}
|
|
|
|
/// Registra un usuario nuevo. Retorna false si el email ya existe.
|
|
Future<bool> 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<Map<String, dynamic>?> loginUsuario(String email, String password) async {
|
|
final db = await database;
|
|
// Soporte para autenticación flexible (email o id/usuario) insensible a mayúsculas
|
|
final cleanEmail = email.trim().toLowerCase();
|
|
final hash = _sha256(password);
|
|
var rows = await db.query('usuarios',
|
|
where: '(LOWER(email) = ? OR LOWER(id) = ?) AND password = ?',
|
|
whereArgs: [cleanEmail, cleanEmail, hash]);
|
|
if (rows.isEmpty) {
|
|
rows = await db.query('usuarios',
|
|
where: '(LOWER(email) = ? OR LOWER(id) = ?) AND password = ?',
|
|
whereArgs: [cleanEmail, cleanEmail, 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);
|
|
}
|
|
|
|
// Actualiza el número telefónico del usuario en SQLite local (para alertas de WhatsApp)
|
|
Future<void> updateUsuarioTelefono(String usuarioId, String telefono) async {
|
|
final db = await database;
|
|
await db.update(
|
|
'usuarios',
|
|
{'telefono': telefono},
|
|
where: 'id = ? OR email = ?',
|
|
whereArgs: [usuarioId, usuarioId],
|
|
);
|
|
}
|
|
|
|
// ── 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<Producto?> getProductoBySku(String sku) async {
|
|
final db = await database;
|
|
final rows = await db.query('productos', where: 'sku = ?', whereArgs: [sku], limit: 1);
|
|
return rows.isEmpty ? null : Producto.fromMap(rows.first);
|
|
}
|
|
|
|
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?,
|
|
syncEstado: row['sync_estado'] as String? ?? 'PENDIENTE',
|
|
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> updateSyncEstadoPedido(String pedidoId, String syncEstado) async {
|
|
final db = await database;
|
|
await db.update('pedidos', {'sync_estado': syncEstado},
|
|
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();
|
|
}
|