1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708 |
- import 'dart:convert';
- import 'package:intl/intl.dart';
- import 'package:path/path.dart';
- import 'package:path_provider/path_provider.dart';
- import 'package:sqflite/sqflite.dart';
- import '../data/api_response.dart';
- import '../models/models.dart';
- import 'services.dart';
- import '../views/producto/producto_imagen.dart';
- class RepoService<T> {
- static int dbVersion = 26;
- static String dbName = 'posTurquessa.db';
- static const String id = Basico.identificadorWeb;
- static const String idLocal = Basico.identificadorLocal;
- static Database? _db;
- final Map<String, dynamic> contexto = {
- 'Categoria': CategoriaProducto(),
- 'Producto': Producto(),
- 'ProductoTopping': ProductoTopping(),
- 'Pedido': Pedido(productos: []),
- 'PedidoProducto': PedidoProducto(),
- 'PedidoProductoTopping': PedidoProductoTopping(),
- 'Sucursal': Sucursal(),
- 'Usuario': Usuario(),
- 'UsuarioPermiso': UsuarioPermiso(),
- 'Variable': Variable(),
- 'Descuento': Descuento(),
- 'Mesa': Mesa(),
- 'Propinas': Propinas(),
- };
- Future<Database?> get db async {
- if (_db != null) return _db;
- _db = await databaseInit();
- return _db;
- }
- Future<Database> databaseInit() async {
- String dir = (await getApplicationDocumentsDirectory()).path;
- String path = join(dir, dbName);
- return await openDatabase(
- path,
- version: dbVersion,
- onCreate: _onCreate,
- onUpgrade: _onUpgrade,
- );
- }
- _onCreate(Database db, int version) async {
- contexto.forEach((String nombre, dynamic modelo) async {
- Map<String, dynamic> model = json.decode(json.encode(modelo.toJson()));
- String sql =
- "CREATE TABLE ${modelo.runtimeType.toString()} (id INTEGER PRIMARY KEY AUTOINCREMENT";
- model.forEach((String key, dynamic value) {
- if (key != "id") {
- String tipo = value.runtimeType.toString();
- String sqlType = "";
- if (equals(tipo, 'int')) {
- sqlType = "INTEGER";
- } else if (equals(tipo, 'double')) {
- sqlType = "REAL";
- } else if (equals(tipo, 'bool')) {
- sqlType = "BOOLEAN";
- } else {
- sqlType = "TEXT";
- }
- sql += ", $key $sqlType";
- }
- });
- sql += ")";
- await db.execute(sql);
- });
- await db.insert('Variable', {
- 'nombre': 'Imprimir Ticket Cocina',
- 'clave': 'ticket_cocina',
- 'descripcion':
- 'Variable para imprimir ticket de cocina automaticamente al momento de generar un pedido',
- 'activo': 1,
- 'idLocal': -1,
- });
- await db.insert('Variable', {
- 'nombre': 'Imprimir Ticket Venta',
- 'clave': 'ticket_venta',
- 'descripcion':
- 'Variable para imprimir ticket de venta automaticamente al momento de generar un pedido',
- 'activo': 1,
- 'idLocal': -1,
- });
- await db.insert('Variable', {
- 'nombre': 'Mesas',
- 'clave': 'MESAS',
- 'descripcion': 'Uso de mesas en el punto de venta',
- 'activo': 1,
- 'idLocal': -1,
- });
- await db.insert('Descuento', {'porcentaje': 0});
- await db.insert('Descuento', {'porcentaje': 5});
- await db.insert('Descuento', {'porcentaje': 10});
- await db.insert('Descuento', {'porcentaje': 15});
- await db.insert('Descuento', {'porcentaje': 20});
- await db.insert('Descuento', {'porcentaje': 25});
- await db.insert('Descuento', {'porcentaje': 30});
- await db.execute('''
- CREATE TABLE Permiso (
- id TEXT PRIMARY KEY,
- idModulo TEXT,
- nombre TEXT,
- descripcion TEXT,
- eliminado TEXT,
- creado TEXT,
- modificado TEXT
- )
- ''');
- await db.execute('''
- CREATE TABLE CorteCaja (
- id TEXT PRIMARY KEY,
- fechaApertura TEXT,
- fechaCorte TEXT,
- idUsuario INTEGER,
- idSucursal INTEGER,
- fondo REAL,
- fondoDiaSig REAL,
- ventaPuntos REAL,
- ventaEfe REAL,
- ventaTrans REAL,
- ventaTarj REAL,
- gasto REAL,
- retiro REAL,
- deposito REAL,
- corteFinal REAL,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT,
- idWeb TEXT,
- sincronizado TEXT
- )
- ''');
- await db.execute('''
- CREATE TABLE Deposito (
- id TEXT PRIMARY KEY,
- idCorteCaja TEXT,
- idSucursal INTEGER,
- idUsuario INTEGER,
- fechaDeposito TEXT,
- monto REAL,
- persona TEXT,
- descripcion TEXT,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT,
- idWeb TEXT
- )
- ''');
- await db.execute('''
- CREATE TABLE Retiro (
- id TEXT PRIMARY KEY,
- idCorteCaja TEXT,
- idSucursal INTEGER,
- idUsuario INTEGER,
- fechaRetiro TEXT,
- monto REAL,
- persona TEXT,
- descripcion TEXT,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT,
- sincronizado TEXT,
- idWeb TEXT
- )
- ''');
- await db.execute('''
- CREATE TABLE Gasto (
- id TEXT PRIMARY KEY,
- idCorteCaja TEXT,
- idSucursal INTEGER,
- idUsuario INTEGER,
- fechaGasto TEXT,
- monto REAL,
- persona TEXT,
- descripcion TEXT,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT,
- idWeb TEXT,
- sincronizado TEXT
- )
- ''');
- }
- void _onUpgrade(Database db, int oldVersion, int newVersion) async {
- while (oldVersion < newVersion) {
- switch (oldVersion) {
- case 1:
- await db.execute(
- "ALTER TABLE CategoriaProducto ADD COLUMN esToping INTEGER DEFAULT 0");
- await db.execute(
- "ALTER TABLE CategoriaProducto ADD COLUMN descripcion TEXT DEFAULT ''");
- await db.execute(
- "ALTER TABLE CategoriaProducto ADD COLUMN maximo INTEGER");
- break;
- case 2:
- await db.execute('''
- CREATE TABLE ProductoTopping (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- idProducto INTEGER,
- idTopping INTEGER,
- FOREIGN KEY (idProducto) REFERENCES Producto(id),
- FOREIGN KEY (idTopping) REFERENCES Producto(id)
- )
- ''');
- break;
- case 3:
- await db.execute('''
- CREATE TABLE PedidoProductoTopping (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- idPedidoProducto INTEGER,
- idTopping INTEGER,
- FOREIGN KEY (idPedidoProducto) REFERENCES PedidoProducto(id),
- FOREIGN KEY (idTopping) REFERENCES Producto(id)
- )
- ''');
- break;
- case 4:
- await db.execute('''
- ALTER TABLE Pedido ADD COLUMN descuento INTEGER DEFAULT 0
- ''');
- break;
- case 5:
- await db.execute('''
- CREATE TABLE IF NOT EXISTS Descuento (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- porcentaje INTEGER
- )
- ''');
- await db.insert('Descuento', {'porcentaje': 0});
- await db.insert('Descuento', {'porcentaje': 5});
- await db.insert('Descuento', {'porcentaje': 10});
- await db.insert('Descuento', {'porcentaje': 15});
- await db.insert('Descuento', {'porcentaje': 20});
- await db.insert('Descuento', {'porcentaje': 25});
- await db.insert('Descuento', {'porcentaje': 30});
- break;
- case 6:
- await db.execute('''
- ALTER TABLE Pedido ADD COLUMN tipoPago TEXT DEFAULT '';
- ''');
- await db.execute('''
- ALTER TABLE Pedido ADD COLUMN cantEfectivo REAL DEFAULT 0;
- ''');
- await db.execute('''
- ALTER TABLE Pedido ADD COLUMN cantTarjeta REAL DEFAULT 0;
- ''');
- await db.execute('''
- ALTER TABLE Pedido ADD COLUMN cantTransferencia REAL DEFAULT 0;
- ''');
- break;
- case 7:
- await db.execute('''
- CREATE TABLE Variable (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- nombre TEXT,
- clave TEXT,
- descripcion TEXT,
- activo BOOLEAN,
- idLocal INTEGER,
- eliminado TEXT
- )
- ''');
- break;
- // case 8:
- // await db.execute('''
- // ALTER TABLE Producto ADD COLUMN toping INTEGER DEFAULT 0;
- // ''');
- // break;
- case 9:
- await db.execute('''
- ALTER TABLE Pedido ADD COLUMN idWeb INTEGER;
- ''');
- await db.execute('''
- ALTER TABLE Pedido ADD COLUMN sincronizado TEXT;
- ''');
- await db.execute('''
- ALTER TABLE PedidoProducto ADD COLUMN idWeb INTEGER;
- ''');
- await db.execute('''
- ALTER TABLE PedidoProducto ADD COLUMN sincronizado TEXT;
- ''');
- break;
- case 10:
- await db.execute('''
- update Pedido set sincronizado = null, peticion = strftime('%Y-%m-%dT%H:%M:%S',
- datetime(substr(peticion, 7, 4) || '-' ||
- substr(peticion, 4, 2) || '-' ||
- substr(peticion, 1, 2) || ' ' ||
- substr(peticion, 12, 8) || ' -07:00', 'localtime', '+07:00'))
- WHERE strftime('%Y-%m-%dT%H:%M:%S',
- datetime(substr(peticion, 7, 4) || '-' ||
- substr(peticion, 4, 2) || '-' ||
- substr(peticion, 1, 2) || ' ' ||
- substr(peticion, 12, 8) || ' -07:00', 'localtime', '+07:00')) is not null
- ''');
- break;
- case 11:
- await db.execute('DROP TABLE IF EXISTS Producto');
- //Se tiene que crear nuevamente para que precio sea Double
- await db.execute('''
- CREATE TABLE Producto (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- idCategoria INTEGER,
- idLocal INTEGER,
- nombre TEXT,
- descripcion TEXT,
- imagen TEXT,
- venta INTEGER,
- existencia INTEGER,
- precio REAL,
- verMenu INTEGER,
- codigo TEXT,
- descuento TEXT,
- toping INTEGER,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT
- )
- ''');
- await db.execute('DELETE FROM CategoriaProducto');
- await db.execute('''
- ALTER TABLE CategoriaProducto ADD COLUMN creado TEXT;
- ''');
- await db.execute('''
- ALTER TABLE CategoriaProducto ADD COLUMN modificado TEXT;
- ''');
- break;
- case 12:
- await db.execute('''
- ALTER TABLE Producto ADD COLUMN activo INTEGER;
- ''');
- break;
- case 13:
- await db.execute('''
- ALTER TABLE Producto ADD COLUMN activo INTEGER;
- ''');
- break;
- case 14:
- await db.execute('''
- ALTER TABLE ProductoTopping ADD COLUMN idCategoria INTEGER;
- ''');
- await db.execute('''
- ALTER TABLE ProductoTopping ADD COLUMN creado text;
- ''');
- await db.execute('''
- ALTER TABLE ProductoTopping ADD COLUMN modificado text;
- ''');
- await db.execute('''
- ALTER TABLE ProductoTopping ADD COLUMN eliminado text;
- ''');
- break;
- case 15:
- await db.execute('''
- CREATE TABLE Sucursal (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- nombre TEXT,
- descripcion TEXT,
- direccion TEXT,
- ciudad TEXT,
- activo INTEGER,
- clave TEXT,
- eliminado TEXT,
- creado TEXT,
- modificado TEXT,
- idLocal INTEGER,
- seleccionado INTEGER
- )
- ''');
- break;
- case 16:
- await db.execute('''
- CREATE TABLE Usuario (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- nombre TEXT,
- apellidos TEXT,
- correo TEXT,
- celular TEXT,
- celularPersonal TEXT,
- rol INTEGER,
- genero BOOLEAN,
- estatus INTEGER,
- imagen TEXT,
- rfc TEXT,
- razonSocial TEXT,
- calle TEXT,
- numeroExterior TEXT,
- colonia TEXT,
- codigoPostal TEXT,
- idCiudad INTEGER,
- idEstado INTEGER,
- idSucursal INTEGER,
- turno TEXT,
- eliminado TEXT,
- creado TEXT,
- modificado TEXT,
- idLocal INTEGER
- )
- ''');
- await db.execute('''
- CREATE TABLE Permiso (
- id TEXT PRIMARY KEY,
- idModulo TEXT,
- nombre TEXT,
- descripcion TEXT,
- eliminado TEXT,
- creado TEXT,
- modificado TEXT
- )
- ''');
- await db.execute('''
- CREATE TABLE UsuarioPermiso (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- idUsuario INTEGER,
- idPermiso TEXT,
- asignado TEXT,
- modificado TEXT,
- eliminado TEXT,
- idLocal INTEGER
- )
- ''');
- await db.execute('''
- ALTER TABLE ProductoTopping ADD COLUMN idLocal INTEGER;
- ''');
- await db.execute('''
- ALTER TABLE PedidoProductoTopping ADD COLUMN idLocal INTEGER;
- ''');
- await db.execute('''
- ALTER TABLE PedidoProductoTopping ADD COLUMN idCategoria INTEGER;
- ''');
- break;
- case 17:
- await db.execute('''
- ALTER TABLE CategoriaProducto ADD COLUMN minimo INTEGER;
- ''');
- break;
- case 18:
- await db.execute('''
- ALTER TABLE Usuario ADD COLUMN clave TEXT;
- ''');
- break;
- case 19:
- await db.execute('DROP TABLE CorteCaja');
- await db.execute('DROP TABLE Deposito');
- await db.execute('DROP TABLE Gasto');
- await db.execute('''
- CREATE TABLE CorteCaja (
- id TEXT PRIMARY KEY,
- fechaApertura TEXT,
- fechaCorte TEXT,
- idUsuario INTEGER,
- idSucursal INTEGER,
- fondo REAL,
- fondoDiaSig REAL,
- ventaPuntos REAL,
- ventaEfe REAL,
- ventaTrans REAL,
- ventaTarj REAL,
- gasto REAL,
- retiro REAL,
- corteFinal REAL,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT
- )
- ''');
- await db.execute('''
- CREATE TABLE Deposito (
- id TEXT PRIMARY KEY,
- idCorteCaja TEXT,
- idSucursal INTEGER,
- idUsuario INTEGER,
- fechaDeposito TEXT,
- monto REAL,
- persona TEXT,
- descripcion TEXT,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT
- )
- ''');
- await db.execute('''
- CREATE TABLE Retiro (
- id TEXT PRIMARY KEY,
- idCorteCaja TEXT,
- idSucursal INTEGER,
- idUsuario INTEGER,
- fechaRetiro TEXT,
- monto REAL,
- persona TEXT,
- descripcion TEXT,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT
- )
- ''');
- await db.execute('''
- CREATE TABLE Gasto (
- id TEXT PRIMARY KEY,
- idCorteCaja TEXT,
- idSucursal INTEGER,
- idUsuario INTEGER,
- fechaGasto TEXT,
- monto REAL,
- persona TEXT,
- descripcion TEXT,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT
- )
- ''');
- await db.execute('''
- update Pedido set sincronizado = null where estatus = 'CANCELADO'
- ''');
- await db.insert('Variable', {
- 'nombre': 'Imprimir ticket PC/Tablet',
- 'clave': 'ticket_pc',
- 'descripcion':
- 'Al estar activo imprime ticket para pc, el estar desactivado imprime ticket para tablet',
- 'activo': 1,
- 'idLocal': -1,
- });
- break;
- case 20:
- await db.execute('''
- ALTER TABLE CorteCaja ADD COLUMN deposito REAL;
- ''');
- await db.execute('''
- ALTER TABLE CorteCaja ADD COLUMN idWeb TEXT;
- ''');
- await db.execute('''
- ALTER TABLE CorteCaja ADD COLUMN sincronizado TEXT;
- ''');
- await db.execute('''
- ALTER TABLE Gasto ADD COLUMN idWeb TEXT;
- ''');
- await db.execute('''
- ALTER TABLE Gasto ADD COLUMN sincronizado TEXT;
- ''');
- await db.execute('''
- ALTER TABLE Retiro ADD COLUMN idWeb TEXT;
- ''');
- await db.execute('''
- ALTER TABLE Retiro ADD COLUMN sincronizado TEXT;
- ''');
- await db.execute('''
- ALTER TABLE Deposito ADD COLUMN idWeb TEXT;
- ''');
- await db.execute('''
- ALTER TABLE Deposito ADD COLUMN sincronizado TEXT;
- ''');
- break;
- case 21:
- await db.execute('''
- CREATE TABLE Mesa (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- idLocal INTEGER,
- idSucursal INTEGER,
- nombre TEXT,
- clave TEXT,
- posicion TEXT,
- activa BOOLEAN,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT
- )
- ''');
- break;
- case 22:
- await db.execute('''
- ALTER TABLE Usuario ADD COLUMN token TEXT;
- ''');
- await db.insert('Variable', {
- 'nombre': 'Mesas',
- 'clave': 'MESAS',
- 'descripcion': 'Uso de mesas en el punto de venta',
- 'activo': 1,
- 'idLocal': -1,
- });
- break;
- case 23:
- await db.execute('''
- ALTER TABLE Pedido ADD COLUMN uuid TEXT;
- ''');
- break;
- case 24:
- await db.execute('''
- CREATE TABLE Propinas (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- idLocal INTEGER,
- idPedido INTEGER,
- cantidad REAL,
- comentario TEXT,
- sincronizado TEXT,
- idWeb INTEGER,
- creado TEXT,
- modificado TEXT,
- eliminado TEXT
- )
- ''');
- break;
- case 25:
- await db.execute('''
- ALTER TABLE Pedido ADD COLUMN idCorteCaja TEXT;
- ''');
- await db.execute('''
- ALTER TABLE Producto ADD COLUMN idWeb INTEGER;
- ''');
- await db.execute('''
- ALTER TABLE Producto ADD COLUMN sincronizado TEXT;
- ''');
- await db.execute('''
- ALTER TABLE CategoriaProducto ADD COLUMN idWeb INTEGER;
- ''');
- await db.execute('''
- ALTER TABLE CategoriaProducto ADD COLUMN sincronizado TEXT;
- ''');
- break;
- }
- oldVersion++;
- }
- }
- Future<int> guardar(T model) async {
- try {
- // Convert the model to JSON for the database
- String modelo = json.encode(model, toEncodable: toEncodable);
- Map<String, dynamic> modelMap = json.decode(modelo);
- var dbClient = await db;
- String nombreTabla = model.runtimeType.toString();
- // Check if the model has a String ID or an int ID
- dynamic id = modelMap['id'];
- bool isStringId = id is String;
- bool isIntId = id is int;
- // If id is of type String (e.g., Permiso)
- if (isStringId) {
- if (id == null || (id as String).isEmpty) {
- throw Exception('El ID del modelo no puede ser nulo o vacío');
- }
- // Check for existing record with the String ID
- List<Map> existing = await dbClient!.query(
- nombreTabla,
- where: 'id = ?',
- whereArgs: [id],
- );
- if (existing.isNotEmpty) {
- await dbClient.update(
- nombreTabla,
- modelMap,
- where: 'id = ?',
- whereArgs: [id],
- );
- } else {
- print(
- "Insertando nuevo registro en la tabla $nombreTabla con ID: $id");
- await dbClient.insert(nombreTabla, modelMap);
- }
- return 1;
- } else if (isIntId) {
- // If id is of type int (e.g., other models)
- if (id == null || id == 0) {
- modelMap
- .remove('id'); // Remove id if it's null or 0 for auto-increment
- }
- List<Map> existing = (id != null && id > 0)
- ? await dbClient!
- .query(nombreTabla, where: 'id = ?', whereArgs: [id])
- : [];
- if (existing.isNotEmpty) {
- print("Actualizando registro existente con ID: $id");
- await dbClient!.update(
- nombreTabla,
- modelMap,
- where: 'id = ?',
- whereArgs: [id],
- );
- } else {
- print("Insertando nuevo registro en la tabla $nombreTabla");
- id = await dbClient!.insert(nombreTabla, modelMap);
- }
- return id as int;
- } else {
- throw Exception('Tipo de ID no soportado');
- }
- } catch (e) {
- print('Error al guardar en dynamic: $e');
- return 0;
- }
- }
- Future<int> guardarPedidoProducto(PedidoProducto pedidoProducto) async {
- try {
- var dbClient = await db;
- // Busca registros existentes
- List<Map<String, dynamic>> existingRecords = await dbClient!.query(
- 'PedidoProducto',
- where: 'idPedido = ? AND idProducto = ?',
- whereArgs: [pedidoProducto.idPedido, pedidoProducto.idProducto],
- );
- if (existingRecords.isNotEmpty) {
- // Obtiene el ID existente
- int existingId = existingRecords.first['id'] as int;
- // Clona el mapa JSON y elimina el campo 'id' para la actualización
- Map<String, dynamic> dataToUpdate = Map.from(pedidoProducto.toJson());
- dataToUpdate.remove('id');
- // Actualiza el registro
- await dbClient.update(
- 'PedidoProducto',
- dataToUpdate,
- where: 'id = ?',
- whereArgs: [existingId],
- );
- print(
- "Registro actualizado para idPedido: ${pedidoProducto.idPedido}, idProducto: ${pedidoProducto.idProducto}");
- return existingId;
- } else {
- // Inserta un nuevo registro eliminando el campo 'id' antes de insertar
- Map<String, dynamic> dataToInsert = Map.from(pedidoProducto.toJson());
- dataToInsert.remove('id');
- int id = await dbClient.insert('PedidoProducto', dataToInsert);
- print(
- "Registro insertado para idPedido: ${pedidoProducto.idPedido}, idProducto: ${pedidoProducto.idProducto}");
- return id;
- }
- } catch (e) {
- print('Error al guardar PedidoProducto: $e');
- return 0;
- }
- }
- Future<PedidoProducto?> obtenerPorIdPedidoYProducto({
- required int idPedido,
- required int idProducto,
- }) async {
- Database? dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'PedidoProducto',
- where: 'idPedido = ? AND idProducto = ?',
- whereArgs: [idPedido, idProducto],
- );
- if (maps.isNotEmpty) {
- return PedidoProducto.fromJson(Map<String, dynamic>.from(maps.first));
- }
- return null; // Retorna null si no se encuentra ningún registro
- }
- void asignarFechasLocalmente(Basico model) {
- DateTime ahora = DateTime.now();
- if (model.creado == null) {
- model.creado = ahora.toUtc();
- }
- model.modificado = ahora.toUtc();
- }
- Future<void> _guardarToppings(
- Database db, int idProducto, List<Producto>? topings) async {
- await db.delete('ProductoTopping',
- where: 'idProducto = ?', whereArgs: [idProducto]);
- if (topings != null) {
- for (var topping in topings) {
- await db.insert('ProductoTopping', {
- 'idProducto': idProducto,
- 'idTopping': topping.id,
- });
- }
- }
- }
- Future<int> guardarLocal(T model) async {
- var dbClient = await db;
- String nombreTabla = model.runtimeType.toString();
- String modelo = json.encode(model, toEncodable: toEncodable);
- Map<String, dynamic> modelMap = json.decode(modelo);
- if (nombreTabla == "PedidoProductoTopping") {
- modelMap.remove('idLocal');
- modelMap.remove('eliminado');
- }
- if (modelMap['id'] == null || modelMap['id'] == 0) {
- modelMap.remove('id');
- }
- int resultado;
- int? identificadorLocal = modelMap[Basico.identificadorLocal];
- if (identificadorLocal != null && identificadorLocal > 0) {
- resultado = await dbClient!.update(
- nombreTabla,
- modelMap,
- where: "$idLocal = ?",
- whereArgs: [identificadorLocal],
- );
- } else {
- resultado = await dbClient!.insert(nombreTabla, modelMap);
- var rawQuery =
- await dbClient.rawQuery("SELECT last_insert_rowid() as id");
- if (rawQuery.isNotEmpty) {
- resultado = int.parse(rawQuery.first["id"].toString());
- modelMap[Basico.identificadorLocal] = resultado;
- }
- }
- if (model is Pedido) {
- model.id = resultado;
- }
- if (model is Producto) {
- await _guardarToppings(dbClient!, model.id!, model.topings);
- }
- return resultado;
- }
- dynamic toEncodable(dynamic item) {
- return item.toJson();
- }
- Future<List<T>> obtenerTodos<T>({
- String where = 'eliminado IS NULL',
- List<dynamic>? whereArgs,
- String orderBy = 'id DESC',
- }) async {
- var db = await this.db;
- String tableName = T.toString();
- var result = await db!.query(
- tableName,
- where: where,
- whereArgs: whereArgs,
- orderBy: orderBy,
- );
- return result.map((map) => fromMap<T>(map)).toList();
- }
- T fromMap<T>(Map<String, dynamic> map) {
- switch (T) {
- case Pedido:
- return Pedido.fromJson(map) as T;
- case Producto:
- return Producto.fromJson(map) as T;
- case Usuario:
- return Usuario.fromJson(map) as T;
- case CorteCaja:
- return CorteCaja.fromJson(map) as T;
- case Propinas:
- return Propinas.fromJson(map) as T;
- default:
- throw Exception('Tipo no soportado');
- }
- }
- Future<Pedido?> obtenerPorId(int id) async {
- Database? dbClient = await db;
- List<Map> maps =
- await dbClient!.query('Pedido', where: 'id = ?', whereArgs: [id]);
- if (maps.isNotEmpty) {
- return Pedido.fromJson(Map<String, dynamic>.from(maps.first));
- }
- return null;
- }
- Future<List<PedidoProducto>> obtenerPorIdPedido(int idPedido) async {
- Database? dbClient = await db;
- List<Map> maps = await dbClient!
- .query('PedidoProducto', where: 'idPedido = ?', whereArgs: [idPedido]);
- return maps
- .map((map) => PedidoProducto.fromJson(Map<String, dynamic>.from(map)))
- .toList();
- }
- //CORTE CAJA
- Future<List<Pedido>> obtenerPedidosPorCorteCaja(String idCorteCaja) async {
- var dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'Pedido',
- where: 'idCorteCaja = ? AND eliminado IS NULL AND estatus != ?',
- whereArgs: [idCorteCaja, 'CANCELADO'],
- );
- return maps.map((map) => Pedido.fromJson(map)).toList();
- }
- Future<List<Deposito>> obtenerDepositosPorIdCorteCaja(
- String idCorteCaja) async {
- var dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'Deposito',
- where: 'idCorteCaja = ? AND eliminado IS NULL',
- whereArgs: [idCorteCaja],
- );
- return maps.map((map) => Deposito.fromJson(map)).toList();
- }
- Future<List<Retiro>> obtenerRetirosPorIdCorteCaja(String idCorteCaja) async {
- var dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'Retiro',
- where: 'idCorteCaja = ? AND eliminado IS NULL',
- whereArgs: [idCorteCaja],
- );
- return maps.map((map) => Retiro.fromJson(map)).toList();
- }
- Future<List<Gasto>> obtenerGastosPorIdCorteCaja(String idCorteCaja) async {
- var dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'Gasto',
- where: 'idCorteCaja = ? AND eliminado IS NULL',
- whereArgs: [idCorteCaja],
- );
- return maps.map((map) => Gasto.fromJson(map)).toList();
- }
- Future<int> contarPedidos() async {
- Database? dbClient = await db;
- var result = await dbClient!.rawQuery('SELECT COUNT(*) FROM Pedido');
- return Sqflite.firstIntValue(result) ?? 0;
- }
- Future<double?> obtenerFondoDiaSigDelUltimoCorte() async {
- var dbClient = await db;
- List<Map<String, dynamic>> result = await dbClient!.query(
- 'CorteCaja',
- orderBy: 'fechaApertura DESC',
- limit: 1,
- );
- if (result.isNotEmpty) {
- return result.first['fondoDiaSig'] as double?;
- }
- return null;
- }
- Future<List<Pedido>> obtenerPedidosPaginados(int limit, int offset) async {
- Database? dbClient = await db;
- List<Map<String, dynamic>> result = await dbClient!
- .query('Pedido', limit: limit, offset: offset, orderBy: 'id DESC');
- return result.map((map) => Pedido.fromJson(map)).toList();
- }
- Future<Producto?> obtenerProductoPorId(int idProducto) async {
- Database? dbClient = await db;
- List<Map> maps = await dbClient!
- .query('Producto', where: 'id = ?', whereArgs: [idProducto]);
- if (maps.isNotEmpty) {
- return Producto.fromJson(Map<String, dynamic>.from(maps.first));
- }
- return null;
- }
- Future<List<int>> obtenerToppingsPorProducto(int idProducto) async {
- var dbClient = await db;
- var result = await dbClient!.query(
- 'ProductoTopping',
- where: 'idProducto = ?',
- whereArgs: [idProducto],
- );
- return result.map((map) => map['idTopping'] as int).toList();
- }
- Future<List<PedidoProductoTopping>> obtenerToppingsPorPedidoProducto(
- int idPedidoProducto) async {
- var dbClient = await db;
- List<Map> maps = await dbClient!.query('PedidoProductoTopping',
- where: 'idPedidoProducto = ?', whereArgs: [idPedidoProducto]);
- if (maps.isNotEmpty) {
- return maps
- .map((map) =>
- PedidoProductoTopping.fromJson(Map<String, dynamic>.from(map)))
- .toList();
- }
- return [];
- }
- Future<int> obtenerProximoFolio() async {
- var dbClient = await db;
- var result = await dbClient!.rawQuery(
- 'SELECT MAX(CAST(folio AS INTEGER)) as last_folio FROM Pedido');
- if (result.isNotEmpty && result.first["last_folio"] != null) {
- return int.tryParse(result.first["last_folio"].toString())! + 1;
- }
- return 1;
- }
- Future<List<T>> buscarPorFolio(String folio) async {
- var dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'Pedido',
- where: 'folio LIKE ?',
- whereArgs: ['%$folio%'],
- );
- return maps.map((map) => fromMap<T>(map)).toList();
- }
- Future<List<Pedido>> buscarPorFecha(
- DateTime startDate, DateTime endDate) async {
- var dbClient = await db;
- String startDateString = startDate.toIso8601String();
- String endDateString = endDate.toIso8601String();
- print(
- 'Ejecutando consulta: SELECT * FROM Pedido WHERE peticion BETWEEN $startDateString AND $endDateString');
- List<Map<String, dynamic>> maps = await dbClient!.rawQuery('''
- SELECT * FROM Pedido
- WHERE peticion BETWEEN ? AND ?
- ''', [startDateString, endDateString]);
- print('Resultado de la consulta: ${maps.length} pedidos encontrados.');
- return maps.map((map) => Pedido.fromJson(map)).toList();
- }
- Future<List<CorteCaja>> buscarPorFechaCorte(
- DateTime startDate, DateTime endDate) async {
- var dbClient = await db;
- String startDateString = DateFormat('dd-MM-yyyy').format(startDate);
- String endDateString = DateFormat('dd-MM-yyyy 23:59:59').format(endDate);
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'CorteCaja',
- where: 'fecha BETWEEN ? AND ?',
- whereArgs: [startDateString, endDateString],
- );
- return maps.map((map) => CorteCaja.fromJson(map)).toList();
- }
- Future<void> eliminar<T>(int id) async {
- var dbClient = await db;
- String tableName = T.toString();
- await dbClient!.delete(tableName, where: 'id = ?', whereArgs: [id]);
- }
- Future<List<Descuento>> obtenerTodosDescuentos() async {
- var dbClient = await db;
- var result = await dbClient!.query('Descuento', orderBy: 'porcentaje ASC');
- return result.map((map) => Descuento.fromJson(map)).toList();
- }
- Future<int> guardarDescuento(Descuento descuento) async {
- var dbClient = await db;
- if (descuento.id != null && descuento.id! > 0) {
- return await dbClient!.update(
- 'Descuento',
- descuento.toJson(),
- where: 'id = ?',
- whereArgs: [descuento.id],
- );
- } else {
- return await dbClient!.insert('Descuento', descuento.toJson());
- }
- }
- Future<int> eliminarDescuento(int id) async {
- var dbClient = await db;
- return await dbClient!
- .delete('Descuento', where: 'id = ?', whereArgs: [id]);
- }
- Future<Variable?> obtenerPorNombre(String nombre) async {
- var dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'Variable',
- where: 'nombre = ?',
- whereArgs: [nombre],
- );
- if (maps.isNotEmpty) {
- return Variable.fromJson(Map<String, dynamic>.from(maps.first));
- }
- return null;
- }
- Future<List<Pedido>> obtenerPedidosOrdenadosPorFecha() async {
- var dbClient = await db;
- String orderBy =
- "datetime(substr(peticion, 7, 4) || '-' || substr(peticion, 4, 2) || '-' || substr(peticion, 1, 2) || ' ' || substr(peticion, 12)) ASC";
- List<Map<String, dynamic>> result = await dbClient!.query(
- 'Pedido',
- where: 'sincronizado IS NULL',
- orderBy: orderBy,
- );
- return result.map((map) => Pedido.fromJson(map)).toList();
- }
- Future<void> sincronizarCategorias(List<CategoriaProducto> categoriasApi,
- {bool forzar = false}) async {
- var db = await RepoService().db;
- var categoriasLocalesQuery = await db!.query('CategoriaProducto');
- List<CategoriaProducto> categoriasLocales = categoriasLocalesQuery
- .map((e) => CategoriaProducto.fromJson(e))
- .toList();
- for (var categoriaApi in categoriasApi) {
- var categoriaLocal = categoriasLocales.firstWhere(
- (categoria) => categoria.id == categoriaApi.id,
- orElse: () => CategoriaProducto(),
- );
- if (forzar ||
- categoriaLocal.id != 0 &&
- categoriaApi.modificado != null &&
- (categoriaLocal.modificado == null ||
- categoriaApi.modificado!
- .isAfter(categoriaLocal.modificado!))) {
- await RepoService().guardar(categoriaApi);
- } else if (categoriaLocal.id == 0) {
- await RepoService().guardar(categoriaApi);
- }
- }
- }
- Future<void> sincronizarProductos(List<Producto> productosApi,
- {bool forzar = false}) async {
- var db = await RepoService().db;
- // // Print del JSON recibido
- // print(
- // "Productos API recibidos: ${productosApi.map((e) => e.toJson()).toList()}");
- var productosLocalesQuery = await db!.query('Producto');
- List<Producto> productosLocales =
- productosLocalesQuery.map((e) => Producto.fromJson(e)).toList();
- for (var productoApi in productosApi) {
- // Validar que el ID del producto no sea nulo
- if (productoApi.id == null) {
- print("Producto con ID nulo, se omite: ${productoApi.nombre}");
- continue; // Ignorar productos sin ID
- }
- // Buscar el producto localmente
- var productoLocal = productosLocales.firstWhere(
- (producto) => producto.id == productoApi.id,
- orElse: () =>
- Producto(), // Si no existe el producto, devolver uno nuevo con id 0
- );
- if (productoLocal.id == 0) {
- print("Insertando nuevo producto: ${productoApi.nombre}");
- await RepoService().guardar(productoApi);
- } else if (forzar ||
- productoApi.modificado != null &&
- (productoLocal.modificado == null ||
- productoApi.modificado!.isAfter(productoLocal.modificado!))) {
- print("Actualizando producto: ${productoApi.nombre}");
- await RepoService().guardar(productoApi);
- } else {
- // Producto sin cambios
- // print(
- // "Producto sin cambios o datos insuficientes: ${productoApi.nombre}");
- }
- }
- }
- Future<void> sincronizarProductoTopping(
- List<ProductoTopping> toppingsApi) async {
- var db = await RepoService().db;
- await db!.delete('ProductoTopping');
- for (var toppingApi in toppingsApi) {
- await RepoService().guardar(toppingApi);
- }
- print("Todos los registros de ProductoTopping han sido sincronizados.");
- }
- Future<void> sincronizarSucursales(List<Sucursal> sucursalesApi,
- {bool forzar = false}) async {
- var db = await RepoService().db;
- int? idSucursalSeleccionada = await obtenerIdSucursalSeleccionada();
- var sucursalesLocalesQuery = await db!.query('Sucursal');
- List<Sucursal> sucursalesLocales =
- sucursalesLocalesQuery.map((e) => Sucursal.fromJson(e)).toList();
- for (var sucursalApi in sucursalesApi) {
- var sucursalLocal = sucursalesLocales.firstWhere(
- (sucursal) => sucursal.id == sucursalApi.id,
- orElse: () => Sucursal(),
- );
- sucursalApi.seleccionado =
- (sucursalApi.id == idSucursalSeleccionada) ? 1 : 0;
- if (forzar ||
- sucursalLocal.id != 0 &&
- sucursalApi.modificado != null &&
- (sucursalLocal.modificado == null ||
- sucursalApi.modificado!.isAfter(sucursalLocal.modificado!))) {
- await RepoService().guardar(sucursalApi);
- } else if (sucursalLocal.id == 0) {
- await RepoService().guardar(sucursalApi);
- }
- }
- }
- Future<void> sincronizarPermisos(List<Permiso> permisosApi,
- {bool forzar = false}) async {
- var db = await RepoService().db;
- var permisosLocalesQuery = await db!.query('Permiso');
- List<Permiso> permisosLocales =
- permisosLocalesQuery.map((e) => Permiso.fromJson(e)).toList();
- for (var permisoApi in permisosApi) {
- var permisoLocal = permisosLocales.firstWhere(
- (permiso) => permiso.id == permisoApi.id,
- orElse: () => Permiso(),
- );
- if (forzar ||
- permisoLocal.id != null &&
- permisoApi.modificado != null &&
- (permisoLocal.modificado == null ||
- permisoApi.modificado!.isAfter(permisoLocal.modificado!))) {
- print('Actualizando permiso con ID: ${permisoApi.id}');
- await RepoService().guardar(permisoApi);
- } else if (permisoLocal.id == null) {
- print('Insertando nuevo permiso con ID: ${permisoApi.id}');
- await RepoService().guardar(permisoApi);
- } else {
- //print('Permiso sin cambios: ${permisoApi.id}');
- }
- }
- }
- Future<void> sincronizarUsuarios(List<Usuario> usuariosApi,
- {bool forzar = false}) async {
- var db = await RepoService().db;
- var usuariosLocalesQuery = await db!.query('Usuario');
- List<Usuario> usuariosLocales =
- usuariosLocalesQuery.map((e) => Usuario.fromJson(e)).toList();
- for (var usuarioApi in usuariosApi) {
- var usuarioLocal = usuariosLocales.firstWhere(
- (usuario) => usuario.id == usuarioApi.id,
- orElse: () => Usuario(),
- );
- // Comprobar si realmente se necesita actualizar el usuario basado en la fecha de modificado
- if (forzar ||
- usuarioLocal.id != 0 &&
- usuarioApi.modificado != null &&
- (usuarioLocal.modificado == null ||
- usuarioApi.modificado!.isAfter(usuarioLocal.modificado!))) {
- print('Actualizando usuario con ID: ${usuarioApi.id}');
- await RepoService().guardar(usuarioApi);
- // Comparar permisos antes de actualizarlos
- await _actualizarPermisosUsuario(
- db, usuarioApi.id!, usuarioApi.permisos!);
- } else if (usuarioLocal.id == 0) {
- print('Insertando nuevo usuario con ID: ${usuarioApi.id}');
- await RepoService().guardar(usuarioApi);
- // Insertar los permisos correspondientes
- await _guardarPermisosUsuario(db, usuarioApi.id!, usuarioApi.permisos!);
- } else {
- //print('Usuario sin cambios: ${usuarioApi.id}');
- }
- }
- }
- Future<void> _actualizarPermisosUsuario(
- Database db, int idUsuario, List<String> permisosApi) async {
- // Obtener los permisos actuales del usuario
- var permisosLocalesQuery = await db.query(
- 'UsuarioPermiso',
- where: 'idUsuario = ?',
- whereArgs: [idUsuario],
- );
- List<String> permisosLocales = permisosLocalesQuery
- .map((permiso) => permiso['idPermiso'] as String)
- .toList();
- // Comparar los permisos del API con los locales
- bool sonIguales = _listasIguales(permisosLocales, permisosApi);
- if (!sonIguales) {
- // Si los permisos no son iguales, actualizarlos
- print('Actualizando permisos del usuario con ID: $idUsuario');
- await _guardarPermisosUsuario(db, idUsuario, permisosApi);
- } else {
- print('Permisos del usuario con ID: $idUsuario no han cambiado.');
- }
- }
- Future<void> _guardarPermisosUsuario(
- Database db, int idUsuario, List<String> permisos) async {
- // Eliminar los permisos actuales solo si hay cambios
- await db.delete('UsuarioPermiso',
- where: 'idUsuario = ?', whereArgs: [idUsuario]);
- // Insertar los nuevos permisos
- for (var idPermiso in permisos) {
- await db.insert('UsuarioPermiso', {
- 'idUsuario': idUsuario,
- 'idPermiso': idPermiso,
- });
- }
- }
- bool _listasIguales(List<String> lista1, List<String> lista2) {
- if (lista1.length != lista2.length) return false;
- lista1.sort();
- lista2.sort();
- for (int i = 0; i < lista1.length; i++) {
- if (lista1[i] != lista2[i]) return false;
- }
- return true;
- }
- Future<String?> obtenerClaveSucursalSeleccionada() async {
- var db = await this.db;
- List<Map<String, dynamic>> queryResult = await db!.query(
- 'Sucursal',
- where: 'seleccionado = ? AND eliminado IS NULL',
- whereArgs: [1],
- limit: 1,
- );
- if (queryResult.isNotEmpty) {
- Sucursal sucursalSeleccionada = Sucursal.fromJson(queryResult.first);
- return sucursalSeleccionada.clave;
- }
- return null;
- }
- Future<int?> obtenerIdSucursalSeleccionada() async {
- var db = await this.db;
- List<Map<String, dynamic>> queryResult = await db!.query(
- 'Sucursal',
- where: 'seleccionado = ? AND eliminado IS NULL',
- whereArgs: [1],
- limit: 1,
- );
- if (queryResult.isNotEmpty) {
- return Sucursal.fromJson(queryResult.first).id;
- }
- return null;
- }
- Future<void> forzarSincronizacion() async {
- String? claveSucursal = await obtenerClaveSucursalSeleccionada();
- try {
- // Sincronizar categorías
- await sincronizarCategorias(
- await fetchCategoriasApi(claveSucursal: claveSucursal),
- forzar: true);
- // Sincronizar productos
- await sincronizarProductos(
- await fetchProductosApi(claveSucursal: claveSucursal),
- forzar: true);
- // Sincronizar toppings de producto
- await sincronizarProductoTopping(
- await fetchProductoToppingApi(claveSucursal: claveSucursal));
- // Sincronizar sucursales
- await sincronizarSucursales(await fetchSucursalesApi(), forzar: true);
- // Sincronizar permisos
- await sincronizarPermisos(await fetchPermisosApi(), forzar: true);
- // Sincronizar usuarios
- await sincronizarUsuarios(await fetchUsuariosApi(), forzar: true);
- print('Sincronización forzosa completada.');
- } catch (e) {
- print('Error en la sincronización forzosa: $e');
- }
- }
- Future<List<CategoriaProducto>> fetchCategoriasApi(
- {String? claveSucursal}) async {
- Map<String, String> parametros = {
- "claveSucursal": claveSucursal!,
- "limite": "-1"
- };
- final response = ApiResponse(
- await BaseService().get('/pos/categoria', queryParameters: parametros));
- return response.isOk && response.resultados != null
- ? response.resultados!
- .map((json) => CategoriaProducto.fromApi(json))
- .toList()
- : [];
- }
- Future<List<Producto>> fetchProductosApi({String? claveSucursal}) async {
- Map<String, String> parametros = {
- "limite": "-1",
- "claveSucursal": claveSucursal!,
- "expand": "media"
- };
- final response = ApiResponse(
- await BaseService().get('/pos/producto', queryParameters: parametros));
- if (response.isOk && response.resultados != null) {
- List<Producto> productosApi =
- response.resultados!.map((json) => Producto.fromApi(json)).toList();
- // Descargar y almacenar cada imagen de producto
- for (var productoApi in productosApi) {
- if (productoApi.media != null && productoApi.media!.isNotEmpty) {
- for (var media in productoApi.media!) {
- // Descargar y guardar la imagen localmente
- String? localImagePath = await downloadAndStoreImage(
- media.ruta!, productoApi.id!, media.nombre!);
- if (localImagePath != null) {
- productoApi.imagen = localImagePath;
- }
- }
- }
- }
- return productosApi;
- }
- return [];
- }
- Future<List<ProductoTopping>> fetchProductoToppingApi(
- {String? claveSucursal}) async {
- Map<String, String> parametros = {
- "limite": "-1",
- "claveSucursal": claveSucursal!,
- };
- final response = ApiResponse(await BaseService()
- .get('/pos/producto-topping', queryParameters: parametros));
- return response.isOk && response.resultados != null
- ? response.resultados!
- .map((json) => ProductoTopping.fromApi(json))
- .toList()
- : [];
- }
- Future<List<Sucursal>> fetchSucursalesApi() async {
- Map<String, String> parametros = {
- "limite": "-1",
- };
- final response = ApiResponse(
- await BaseService().get('/pos/sucursal', queryParameters: parametros));
- return response.isOk && response.resultados != null
- ? response.resultados!.map((json) => Sucursal.fromApi(json)).toList()
- : [];
- }
- Future<List<Permiso>> fetchPermisosApi() async {
- Map<String, String> parametros = {
- "limite": "-1",
- };
- final response = ApiResponse(
- await BaseService().get('/pos/permiso', queryParameters: parametros));
- return response.isOk && response.resultados != null
- ? response.resultados!.map((json) => Permiso.fromJson(json)).toList()
- : [];
- }
- Future<List<Usuario>> fetchUsuariosApi() async {
- Map<String, String> parametros = {
- "limite": "-1",
- "expand": "permisos",
- };
- final response = ApiResponse(
- await BaseService().get('/pos/usuario', queryParameters: parametros));
- return response.isOk && response.resultados != null
- ? response.resultados!.map((json) => Usuario.fromApi(json)).toList()
- : [];
- }
- Future<void> sincronizarMesas(List<Mesa> mesasApi,
- {bool forzar = false}) async {
- var db = await RepoService().db;
- // Obtener mesas locales
- var mesasLocalesQuery = await db!.query('Mesa');
- List<Mesa> mesasLocales =
- mesasLocalesQuery.map((e) => Mesa.fromJson(e)).toList();
- for (var mesaApi in mesasApi) {
- // Buscar la mesa localmente
- var mesaLocal = mesasLocales.firstWhere(
- (mesa) => mesa.id == mesaApi.id,
- orElse: () => Mesa(),
- );
- // Validar si es una nueva mesa o si necesita ser actualizada
- if (mesaLocal.id == 0) {
- print("Insertando nueva mesa: ${mesaApi.nombre}");
- await RepoService().guardar(mesaApi);
- } else if (forzar ||
- mesaApi.modificado != null &&
- (mesaLocal.modificado == null ||
- mesaApi.modificado!.isAfter(mesaLocal.modificado!))) {
- print("Actualizando mesa: ${mesaApi.nombre}");
- await RepoService().guardar(mesaApi);
- }
- }
- }
- Future<List<Producto>>
- obtenerProductosNoSincronizadosOrdenadosPorFecha() async {
- var dbClient = await db;
- List<Map<String, dynamic>> result = await dbClient!.query(
- 'Producto',
- where: 'sincronizado IS NULL AND eliminado IS NULL',
- orderBy: 'creado ASC',
- );
- return result.map((map) => Producto.fromJson(map)).toList();
- }
- Future<List<CategoriaProducto>>
- obtenerCategoriasNoSincronizadasOrdenadasPorFecha() async {
- var dbClient = await db;
- // Similar a productos, ordenando por 'modificado'
- List<Map<String, dynamic>> result = await dbClient!.query(
- 'CategoriaProducto',
- where: 'sincronizado IS NULL AND eliminado IS NULL',
- orderBy: 'creado ASC',
- );
- return result.map((map) => CategoriaProducto.fromJson(map)).toList();
- }
- Future<void> actualizarProductoSincronizado(
- int idProducto, int idWeb, String sincronizado) async {
- var dbClient = await db;
- await dbClient!.update(
- 'Producto',
- {
- 'idWeb': idWeb,
- 'sincronizado': sincronizado,
- },
- where: 'id = ?',
- whereArgs: [idProducto],
- );
- }
- Future<void> actualizarCategoriaSincronizada(
- int idCategoria, int idWeb, String sincronizado) async {
- var dbClient = await db;
- await dbClient!.update(
- 'CategoriaProducto',
- {
- 'idWeb': idWeb,
- 'sincronizado': sincronizado,
- },
- where: 'id = ?',
- whereArgs: [idCategoria],
- );
- }
- Future<List<Pedido>> obtenerPedidosConPropinasPorCorte(
- String idCorteCaja) async {
- Database? dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.rawQuery('''
- SELECT *
- FROM Pedido
- WHERE idCorteCaja = ?
- AND estatus = 'TERMINADO'
- AND eliminado IS NULL
- AND id IN (
- SELECT idPedido
- FROM Propinas
- WHERE eliminado IS NULL
- )
- ORDER BY id DESC
- ''', [idCorteCaja]);
- List<Pedido> pedidos = [];
- for (var map in maps) {
- Pedido pedido = Pedido.fromJson(map);
- List<Propinas> propinas = await obtenerPropinasPorPedido(pedido.id!);
- pedido.propinas = propinas;
- pedidos.add(pedido);
- }
- return pedidos;
- }
- Future<List<Propinas>> obtenerPropinasPorPedido(int idPedido) async {
- Database? dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'Propinas',
- where: 'idPedido = ? AND eliminado IS NULL',
- whereArgs: [idPedido],
- );
- return maps.map((map) => Propinas.fromJson(map)).toList();
- }
- }
|