12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667 |
- 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],
- );
- }
- }
|