repo_service.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. import 'dart:convert';
  2. import 'package:intl/intl.dart';
  3. import 'package:path/path.dart';
  4. import 'package:path_provider/path_provider.dart';
  5. import 'package:sqflite/sqflite.dart';
  6. import '../models/models.dart';
  7. class RepoService<T> {
  8. static int dbVersion = 9;
  9. static String dbName = 'conalepPos7.db';
  10. static const String id = Basico.identificadorWeb;
  11. static const String idLocal = Basico.identificadorLocal;
  12. static Database? _db;
  13. final Map<String, dynamic> contexto = {
  14. 'Categoria': CategoriaProducto(),
  15. 'Producto': Producto(),
  16. 'Pedido': Pedido(productos: []),
  17. 'PedidoProducto': PedidoProducto(),
  18. 'Gasto': Gasto(),
  19. 'Deposito': Deposito(),
  20. 'CorteCaja': CorteCaja(),
  21. };
  22. Future<Database?> get db async {
  23. if (_db != null) return _db;
  24. _db = await databaseInit();
  25. return _db;
  26. }
  27. Future<Database> databaseInit() async {
  28. String dir = (await getApplicationDocumentsDirectory()).path;
  29. String path = join(dir, dbName);
  30. return await openDatabase(
  31. path,
  32. version: dbVersion,
  33. onCreate: _onCreate,
  34. onUpgrade: _onUpgrade,
  35. );
  36. }
  37. /// Crea la base de datos
  38. _onCreate(Database db, int version) async {
  39. contexto.forEach((String nombre, dynamic modelo) async {
  40. Map<String, dynamic> model = json.decode(json.encode(modelo.toJson()));
  41. String sql =
  42. "CREATE TABLE ${modelo.runtimeType.toString()} (id INTEGER PRIMARY KEY AUTOINCREMENT";
  43. model.forEach((String key, dynamic value) {
  44. if (key != "id") {
  45. String tipo = value.runtimeType.toString();
  46. String sqlType = "";
  47. if (equals(tipo, 'int')) {
  48. sqlType = "INTEGER";
  49. } else if (equals(tipo, 'double')) {
  50. sqlType = "REAL";
  51. } else if (equals(tipo, 'bool')) {
  52. sqlType = "BOOLEAN";
  53. } else {
  54. sqlType = "TEXT";
  55. }
  56. sql += ", $key $sqlType";
  57. }
  58. });
  59. sql += ")";
  60. await db.execute(sql);
  61. await db.execute('''
  62. CREATE TABLE PedidoProductoTopping (
  63. id INTEGER PRIMARY KEY AUTOINCREMENT,
  64. idPedidoProducto INTEGER,
  65. idTopping INTEGER,
  66. FOREIGN KEY (idPedidoProducto) REFERENCES PedidoProducto(id),
  67. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  68. )
  69. ''');
  70. if (modelo.runtimeType.toString() == 'Pedido') {
  71. await db.execute(
  72. 'ALTER TABLE Pedido ADD COLUMN descuento INTEGER DEFAULT 0');
  73. }
  74. await db.execute('''
  75. CREATE TABLE Descuento (
  76. id INTEGER PRIMARY KEY AUTOINCREMENT,
  77. porcentaje INTEGER
  78. )
  79. ''');
  80. await db.insert('Descuento', {'porcentaje': 0});
  81. await db.insert('Descuento', {'porcentaje': 5});
  82. await db.insert('Descuento', {'porcentaje': 10});
  83. await db.insert('Descuento', {'porcentaje': 15});
  84. await db.insert('Descuento', {'porcentaje': 20});
  85. await db.insert('Descuento', {'porcentaje': 25});
  86. await db.insert('Descuento', {'porcentaje': 30});
  87. });
  88. await db.execute('''
  89. CREATE TABLE ProductoTopping (
  90. id INTEGER PRIMARY KEY AUTOINCREMENT,
  91. idProducto INTEGER,
  92. idTopping INTEGER,
  93. FOREIGN KEY (idProducto) REFERENCES Producto(id),
  94. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  95. )
  96. ''');
  97. await db.execute('''
  98. CREATE TABLE Variable (
  99. id INTEGER PRIMARY KEY AUTOINCREMENT,
  100. nombre TEXT,
  101. clave TEXT,
  102. descripcion TEXT,
  103. activo BOOLEAN,
  104. idLocal INTEGER,
  105. eliminado TEXT
  106. )
  107. ''');
  108. }
  109. /// Actualiza la version de la base de datos
  110. void _onUpgrade(Database db, int oldVersion, int newVersion) async {
  111. while (oldVersion < newVersion) {
  112. switch (oldVersion) {
  113. case 1:
  114. await db.execute(
  115. "ALTER TABLE CategoriaProducto ADD COLUMN esToping INTEGER DEFAULT 0");
  116. await db.execute(
  117. "ALTER TABLE CategoriaProducto ADD COLUMN descripcion TEXT DEFAULT ''");
  118. await db.execute(
  119. "ALTER TABLE CategoriaProducto ADD COLUMN maximo INTEGER");
  120. break;
  121. case 2:
  122. await db.execute('''
  123. CREATE TABLE ProductoTopping (
  124. id INTEGER PRIMARY KEY AUTOINCREMENT,
  125. idProducto INTEGER,
  126. idTopping INTEGER,
  127. FOREIGN KEY (idProducto) REFERENCES Producto(id),
  128. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  129. )
  130. ''');
  131. break;
  132. case 3:
  133. await db.execute('''
  134. CREATE TABLE PedidoProductoTopping (
  135. id INTEGER PRIMARY KEY AUTOINCREMENT,
  136. idPedidoProducto INTEGER,
  137. idTopping INTEGER,
  138. FOREIGN KEY (idPedidoProducto) REFERENCES PedidoProducto(id),
  139. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  140. )
  141. ''');
  142. break;
  143. case 4:
  144. await db.execute('''
  145. ALTER TABLE Pedido ADD COLUMN descuento INTEGER DEFAULT 0
  146. ''');
  147. break;
  148. case 5:
  149. await db.execute('''
  150. CREATE TABLE IF NOT EXISTS Descuento (
  151. id INTEGER PRIMARY KEY AUTOINCREMENT,
  152. porcentaje INTEGER
  153. )
  154. ''');
  155. await db.insert('Descuento', {'porcentaje': 0});
  156. await db.insert('Descuento', {'porcentaje': 5});
  157. await db.insert('Descuento', {'porcentaje': 10});
  158. await db.insert('Descuento', {'porcentaje': 15});
  159. await db.insert('Descuento', {'porcentaje': 20});
  160. await db.insert('Descuento', {'porcentaje': 25});
  161. await db.insert('Descuento', {'porcentaje': 30});
  162. break;
  163. case 6:
  164. await db.execute('''
  165. ALTER TABLE Pedido ADD COLUMN tipoPago TEXT DEFAULT '';
  166. ''');
  167. await db.execute('''
  168. ALTER TABLE Pedido ADD COLUMN cantEfectivo REAL DEFAULT 0;
  169. ''');
  170. await db.execute('''
  171. ALTER TABLE Pedido ADD COLUMN cantTarjeta REAL DEFAULT 0;
  172. ''');
  173. await db.execute('''
  174. ALTER TABLE Pedido ADD COLUMN cantTransferencia REAL DEFAULT 0;
  175. ''');
  176. break;
  177. case 7:
  178. await db.execute('''
  179. CREATE TABLE Variable (
  180. id INTEGER PRIMARY KEY AUTOINCREMENT,
  181. nombre TEXT,
  182. clave TEXT,
  183. descripcion TEXT,
  184. activo BOOLEAN,
  185. idLocal INTEGER,
  186. eliminado TEXT
  187. )
  188. ''');
  189. break;
  190. case 8:
  191. await db.execute('''
  192. ALTER TABLE Producto ADD COLUMN toping INTEGER DEFAULT 0;
  193. ''');
  194. break;
  195. }
  196. oldVersion++;
  197. }
  198. }
  199. Future<int> guardar(T model) async {
  200. try {
  201. var dbClient = await db;
  202. String nombreTabla = model.runtimeType.toString();
  203. String modelo = json.encode(model, toEncodable: toEncodable);
  204. Map<String, dynamic> modelMap = json.decode(modelo);
  205. int id = 0;
  206. if (modelMap['id'] != null && modelMap['id'] != 0) {
  207. await dbClient!.update(
  208. nombreTabla,
  209. modelMap,
  210. where: 'id = ?',
  211. whereArgs: [modelMap['id']],
  212. );
  213. id = modelMap['id'];
  214. } else {
  215. modelMap.remove('id');
  216. id = await dbClient!.insert(nombreTabla, modelMap);
  217. }
  218. if (model is Producto) {
  219. await _guardarToppings(dbClient, id, model.topings);
  220. }
  221. return id;
  222. } catch (e) {
  223. print('Error al guardar en $T: $e');
  224. return 0;
  225. }
  226. }
  227. Future<void> _guardarToppings(
  228. Database db, int idProducto, List<Producto>? topings) async {
  229. await db.delete('ProductoTopping',
  230. where: 'idProducto = ?', whereArgs: [idProducto]);
  231. if (topings != null) {
  232. for (var topping in topings) {
  233. await db.insert('ProductoTopping', {
  234. 'idProducto': idProducto,
  235. 'idTopping': topping.id,
  236. });
  237. }
  238. }
  239. }
  240. Future<int> guardarLocal(T model) async {
  241. var dbClient = await db;
  242. String nombreTabla = model.runtimeType.toString();
  243. String modelo = json.encode(model, toEncodable: toEncodable);
  244. Map<String, dynamic> modelMap = json.decode(modelo);
  245. if (nombreTabla == "PedidoProductoTopping") {
  246. modelMap.remove('idLocal');
  247. modelMap.remove('eliminado');
  248. }
  249. if (modelMap['id'] == null || modelMap['id'] == 0) {
  250. modelMap.remove('id');
  251. }
  252. int resultado;
  253. int? identificadorLocal = modelMap[Basico.identificadorLocal];
  254. if (identificadorLocal != null && identificadorLocal > 0) {
  255. resultado = await dbClient!.update(
  256. nombreTabla,
  257. modelMap,
  258. where: "$idLocal = ?",
  259. whereArgs: [identificadorLocal],
  260. );
  261. } else {
  262. resultado = await dbClient!.insert(nombreTabla, modelMap);
  263. var rawQuery =
  264. await dbClient.rawQuery("SELECT last_insert_rowid() as id");
  265. if (rawQuery.isNotEmpty) {
  266. resultado = int.parse(rawQuery.first["id"].toString());
  267. modelMap[Basico.identificadorLocal] = resultado;
  268. }
  269. }
  270. if (model is Pedido) {
  271. model.id = resultado;
  272. }
  273. if (model is Producto) {
  274. await _guardarToppings(dbClient!, model.id!, model.topings);
  275. }
  276. return resultado;
  277. }
  278. dynamic toEncodable(dynamic item) {
  279. if (item is Pedido) {
  280. return item.toJson();
  281. } else if (item is PedidoProducto) {
  282. return item.toJson();
  283. } else if (item is PedidoProductoTopping) {
  284. return item.toJson();
  285. } else if (item is Producto) {
  286. return item.toJson();
  287. } else if (item is CategoriaProducto) {
  288. return item.toJson();
  289. } else if (item is Variable) {
  290. return item.toJson();
  291. }
  292. throw UnsupportedError(
  293. 'Type not supported for serialization: ${item.runtimeType}');
  294. }
  295. Future<List<T>> obtenerTodos({String orderBy = 'id DESC'}) async {
  296. var db = await this.db;
  297. String tableName = T.toString();
  298. var result = await db!.query(tableName, orderBy: orderBy);
  299. return result.map((map) => fromMap<T>(map)).toList();
  300. }
  301. T fromMap<T>(Map<String, dynamic> map) {
  302. switch (T) {
  303. case Pedido:
  304. return Pedido.fromJson(map) as T;
  305. case Producto:
  306. return Producto.fromJson(map) as T;
  307. default:
  308. throw Exception('Tipo no soportado');
  309. }
  310. }
  311. Future<Pedido?> obtenerPorId(int id) async {
  312. Database? dbClient = await db;
  313. List<Map> maps =
  314. await dbClient!.query('Pedido', where: 'id = ?', whereArgs: [id]);
  315. if (maps.isNotEmpty) {
  316. return Pedido.fromJson(Map<String, dynamic>.from(maps.first));
  317. }
  318. return null;
  319. }
  320. Future<List<PedidoProducto>> obtenerPorIdPedido(int idPedido) async {
  321. Database? dbClient = await db;
  322. List<Map> maps = await dbClient!
  323. .query('PedidoProducto', where: 'idPedido = ?', whereArgs: [idPedido]);
  324. return maps
  325. .map((map) => PedidoProducto.fromJson(Map<String, dynamic>.from(map)))
  326. .toList();
  327. }
  328. Future<int> contarPedidos() async {
  329. Database? dbClient = await db;
  330. var result = await dbClient!.rawQuery('SELECT COUNT(*) FROM Pedido');
  331. return Sqflite.firstIntValue(result) ?? 0;
  332. }
  333. Future<List<Pedido>> obtenerPedidosPaginados(int limit, int offset) async {
  334. Database? dbClient = await db;
  335. List<Map<String, dynamic>> result = await dbClient!.query('Pedido',
  336. limit: limit,
  337. offset: offset,
  338. orderBy: 'id DESC',
  339. where: 'idMesa = null');
  340. return result.map((map) => Pedido.fromJson(map)).toList();
  341. }
  342. Future<List<Pedido>> obtenerMesaPedidosPaginados(
  343. int limit, int offset) async {
  344. Database? dbClient = await db;
  345. List<Map<String, dynamic>> result = await dbClient!.query('Pedido',
  346. limit: limit,
  347. offset: offset,
  348. orderBy: 'id DESC',
  349. where: 'idMesa != null');
  350. return result.map((map) => Pedido.fromJson(map)).toList();
  351. }
  352. Future<Producto?> obtenerProductoPorId(int idProducto) async {
  353. Database? dbClient = await db;
  354. List<Map> maps = await dbClient!
  355. .query('Producto', where: 'id = ?', whereArgs: [idProducto]);
  356. if (maps.isNotEmpty) {
  357. return Producto.fromJson(Map<String, dynamic>.from(maps.first));
  358. }
  359. return null;
  360. }
  361. Future<List<int>> obtenerToppingsPorProducto(int idProducto) async {
  362. var dbClient = await db;
  363. var result = await dbClient!.query(
  364. 'ProductoTopping',
  365. where: 'idProducto = ?',
  366. whereArgs: [idProducto],
  367. );
  368. return result.map((map) => map['idTopping'] as int).toList();
  369. }
  370. Future<List<PedidoProductoTopping>> obtenerToppingsPorPedidoProducto(
  371. int idPedidoProducto) async {
  372. var dbClient = await db;
  373. List<Map> maps = await dbClient!.query('PedidoProductoTopping',
  374. where: 'idPedidoProducto = ?', whereArgs: [idPedidoProducto]);
  375. if (maps.isNotEmpty) {
  376. return maps
  377. .map((map) =>
  378. PedidoProductoTopping.fromJson(Map<String, dynamic>.from(map)))
  379. .toList();
  380. }
  381. return [];
  382. }
  383. Future<int> obtenerProximoFolio() async {
  384. var dbClient = await db;
  385. var result = await dbClient!.rawQuery(
  386. 'SELECT MAX(CAST(folio AS INTEGER)) as last_folio FROM Pedido');
  387. if (result.isNotEmpty && result.first["last_folio"] != null) {
  388. return int.tryParse(result.first["last_folio"].toString())! + 1;
  389. }
  390. return 1;
  391. }
  392. Future<List<T>> buscarPorFolio(String folio) async {
  393. var dbClient = await db;
  394. List<Map<String, dynamic>> maps = await dbClient!.query(
  395. 'Pedido',
  396. where: 'folio LIKE ?',
  397. whereArgs: ['%$folio%'],
  398. );
  399. return maps.map((map) => fromMap<T>(map)).toList();
  400. }
  401. Future<List<Pedido>> buscarPorFecha(
  402. DateTime startDate, DateTime endDate) async {
  403. var dbClient = await db;
  404. String startDateString =
  405. DateFormat('yyyy-MM-dd 00:00:00').format(startDate);
  406. String endDateString = DateFormat('yyyy-MM-dd 23:59:59').format(endDate);
  407. List<Map<String, dynamic>> maps = await dbClient!.rawQuery('''
  408. SELECT * FROM Pedido
  409. WHERE
  410. (datetime(substr(peticion, 7, 4) || '-' || substr(peticion, 4, 2) || '-' || substr(peticion, 1, 2) || ' ' || substr(peticion, 12)) BETWEEN ? AND ?)
  411. OR
  412. (datetime(substr(peticion, 7, 4) || '-' || substr(peticion, 1, 2) || '-' || substr(peticion, 4, 2) || ' ' || substr(peticion, 12)) BETWEEN ? AND ?)
  413. ''', [startDateString, endDateString, startDateString, endDateString]);
  414. return maps.map((map) => Pedido.fromJson(map)).toList();
  415. }
  416. Future<List<CorteCaja>> buscarPorFechaCorte(
  417. DateTime startDate, DateTime endDate) async {
  418. var dbClient = await db;
  419. String startDateString = DateFormat('dd-MM-yyyy').format(startDate);
  420. String endDateString = DateFormat('dd-MM-yyyy 23:59:59').format(endDate);
  421. List<Map<String, dynamic>> maps = await dbClient!.query(
  422. 'CorteCaja',
  423. where: 'fecha BETWEEN ? AND ?',
  424. whereArgs: [startDateString, endDateString],
  425. );
  426. return maps.map((map) => CorteCaja.fromJson(map)).toList();
  427. }
  428. Future<void> eliminar<T>(int id) async {
  429. var dbClient = await db;
  430. String tableName = T.toString();
  431. await dbClient!.delete(tableName, where: 'id = ?', whereArgs: [id]);
  432. }
  433. Future<List<Descuento>> obtenerTodosDescuentos() async {
  434. var dbClient = await db;
  435. var result = await dbClient!.query('Descuento', orderBy: 'porcentaje ASC');
  436. return result.map((map) => Descuento.fromJson(map)).toList();
  437. }
  438. Future<int> guardarDescuento(Descuento descuento) async {
  439. var dbClient = await db;
  440. if (descuento.id != null && descuento.id! > 0) {
  441. return await dbClient!.update(
  442. 'Descuento',
  443. descuento.toJson(),
  444. where: 'id = ?',
  445. whereArgs: [descuento.id],
  446. );
  447. } else {
  448. return await dbClient!.insert('Descuento', descuento.toJson());
  449. }
  450. }
  451. Future<int> eliminarDescuento(int id) async {
  452. var dbClient = await db;
  453. return await dbClient!
  454. .delete('Descuento', where: 'id = ?', whereArgs: [id]);
  455. }
  456. }