123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341 |
- 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';
- class RepoService<T> {
- static int dbVersion = 19;
- static String dbName = 'joshipos026.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(),
- 'Pedido': Pedido(productos: []),
- 'PedidoProducto': PedidoProducto(),
- 'Gasto': Gasto(),
- 'Deposito': Deposito(),
- 'CorteCaja': CorteCaja(),
- };
- 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.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)
- )
- ''');
- if (modelo.runtimeType.toString() == 'Pedido') {
- await db.execute(
- 'ALTER TABLE Pedido ADD COLUMN descuento INTEGER DEFAULT 0');
- }
- await db.execute('''
- CREATE TABLE 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});
- });
- 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)
- )
- ''');
- await db.execute('''
- CREATE TABLE Variable (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- nombre TEXT,
- clave TEXT,
- descripcion TEXT,
- activo BOOLEAN,
- idLocal INTEGER,
- eliminado TEXT
- )
- ''');
- 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;
- ''');
- 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': 'Sucursal',
- 'clave': 'PRUEBA',
- 'descripcion': 'Sucursal Prueba',
- 'activo': 1,
- 'idLocal': -1,
- });
- }
- 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");
- await db.insert('CategoriaProducto', {
- 'nombre': 'BASE PRODUCTO',
- 'descripcion': 'Base del producto',
- 'esToping': 1,
- 'maximo': 1,
- });
- await db.insert('CategoriaProducto', {
- 'nombre': 'SALSAS PRODUCTO',
- 'descripcion': 'Elige tus salsas (Máx. 2)',
- 'esToping': 1,
- 'maximo': 2,
- });
- await db.insert('CategoriaProducto', {
- 'nombre': 'ADEREZO PRODUCTO',
- 'descripcion': 'Elige tu aderezo (Máx. 2)',
- 'esToping': 1,
- 'maximo': 2,
- });
- await db.insert('CategoriaProducto', {
- 'nombre': 'TOPPING PRODUCTO',
- 'descripcion': 'Elige tus toppings (Máx. 2)',
- 'esToping': 1,
- 'maximo': 2,
- });
- await db.insert('Producto', {
- 'nombre': 'Papa Gajo',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'Papa Regilla',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'Papa Curly',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'Papa Smile',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'Papa Francesa',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'BBQ',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'HOTBBQ',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'BUFFALO',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'TERIYAKI',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'PARMESAN GARLIC',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'QUESO AMARILLO',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'RANCH',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'CHIPOTLE',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'ADEREZO JALAPEÑO',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'KETCHUP',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'JALAPEÑO',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'QUESO BLANCO',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'TAKIS',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'RUFFLES',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'QUESO PARMESANO',
- 'precio': 0,
- });
- await db.insert('Producto', {
- 'nombre': 'ELOTE',
- 'precio': 0,
- });
- 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;
- }
- oldVersion++;
- }
- }
- Future<int> guardar(T model) async {
- try {
- //print("Guardando modelo en la base de datos: ${model.runtimeType}");
- // Convertir el modelo a JSON para la base de datos
- String modelo = json.encode(model, toEncodable: toEncodable);
- //print("Modelo convertido a JSON: $modelo");
- Map<String, dynamic> modelMap = json.decode(modelo);
- var dbClient = await db;
- String nombreTabla = model.runtimeType.toString();
- // Verificar si el modelo es de tipo Permiso (con id de tipo String)
- if (model is Permiso) {
- String? id = modelMap['id'];
- if (id == null || id.isEmpty) {
- throw Exception('El ID del permiso no puede ser nulo o vacío');
- }
- List<Map> existing = 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 con ID: $id");
- await dbClient!.insert(nombreTabla, modelMap);
- }
- return 1;
- } else {
- int? id = modelMap['id'];
- if (id == null || id == 0) {
- modelMap.remove('id');
- }
- 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 y modificado: ${modelMap['modificado']}");
- 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!;
- }
- } catch (e) {
- print('Error al guardar en dynamic: $e');
- return 0;
- }
- }
- 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({String orderBy = 'id DESC'}) async {
- var db = await this.db;
- String tableName = T.toString();
- var result = await db!
- .query(tableName, where: 'eliminado IS NULL', 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;
- 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();
- }
- Future<List<Deposito>> obtenerDepositosPorIdCorteCaja(int idCorteCaja) async {
- var dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'Deposito',
- where: 'idCorteCaja = ?',
- whereArgs: [idCorteCaja],
- );
- return maps.map((map) => Deposito.fromJson(map)).toList();
- }
- Future<List<Gasto>> obtenerGastosPorIdCorteCaja(int idCorteCaja) async {
- var dbClient = await db;
- List<Map<String, dynamic>> maps = await dbClient!.query(
- 'Gasto',
- where: 'idCorteCaja = ?',
- 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<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));
- return response.isOk && response.resultados != null
- ? response.resultados!.map((json) => Producto.fromApi(json)).toList()
- : [];
- }
- 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()
- : [];
- }
- }
|