repo_service.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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 = 4;
  9. static String dbName = 'joshipos026.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. _onCreate(Database db, int version) async {
  38. contexto.forEach((String nombre, dynamic modelo) async {
  39. Map<String, dynamic> model = json.decode(json.encode(modelo.toJson()));
  40. String sql =
  41. "CREATE TABLE ${modelo.runtimeType.toString()} (id INTEGER PRIMARY KEY AUTOINCREMENT";
  42. model.forEach((String key, dynamic value) {
  43. if (key != "id") {
  44. String tipo = value.runtimeType.toString();
  45. String sqlType = "";
  46. if (equals(tipo, 'int')) {
  47. sqlType = "INTEGER";
  48. } else if (equals(tipo, 'double')) {
  49. sqlType = "REAL";
  50. } else if (equals(tipo, 'bool')) {
  51. sqlType = "BOOLEAN";
  52. } else {
  53. sqlType = "TEXT";
  54. }
  55. sql += ", $key $sqlType";
  56. }
  57. });
  58. sql += ")";
  59. await db.execute(sql);
  60. await db.execute('''
  61. CREATE TABLE PedidoProductoTopping (
  62. id INTEGER PRIMARY KEY AUTOINCREMENT,
  63. idPedidoProducto INTEGER,
  64. idTopping INTEGER,
  65. FOREIGN KEY (idPedidoProducto) REFERENCES PedidoProducto(id),
  66. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  67. )
  68. ''');
  69. });
  70. await db.execute('''
  71. CREATE TABLE ProductoTopping (
  72. id INTEGER PRIMARY KEY AUTOINCREMENT,
  73. idProducto INTEGER,
  74. idTopping INTEGER,
  75. FOREIGN KEY (idProducto) REFERENCES Producto(id),
  76. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  77. )
  78. ''');
  79. }
  80. void _onUpgrade(Database db, int oldVersion, int newVersion) async {
  81. while (oldVersion < newVersion) {
  82. switch (oldVersion) {
  83. case 1:
  84. await db.execute(
  85. "ALTER TABLE CategoriaProducto ADD COLUMN esToping INTEGER DEFAULT 0");
  86. await db.execute(
  87. "ALTER TABLE CategoriaProducto ADD COLUMN descripcion TEXT DEFAULT ''");
  88. await db.execute(
  89. "ALTER TABLE CategoriaProducto ADD COLUMN maximo INTEGER");
  90. await db.insert('CategoriaProducto', {
  91. 'nombre': 'BASE PRODUCTO',
  92. 'descripcion': 'Base del producto',
  93. 'esToping': 1,
  94. 'maximo': 1,
  95. });
  96. await db.insert('CategoriaProducto', {
  97. 'nombre': 'SALSAS PRODUCTO',
  98. 'descripcion': 'Elige tus salsas (Máx. 2)',
  99. 'esToping': 1,
  100. 'maximo': 2,
  101. });
  102. await db.insert('CategoriaProducto', {
  103. 'nombre': 'ADEREZO PRODUCTO',
  104. 'descripcion': 'Elige tu aderezo (Máx. 2)',
  105. 'esToping': 1,
  106. 'maximo': 2,
  107. });
  108. await db.insert('CategoriaProducto', {
  109. 'nombre': 'TOPPING PRODUCTO',
  110. 'descripcion': 'Elige tus toppings (Máx. 2)',
  111. 'esToping': 1,
  112. 'maximo': 2,
  113. });
  114. await db.insert('Producto', {
  115. 'nombre': 'Papa Gajo',
  116. 'precio': 0,
  117. });
  118. await db.insert('Producto', {
  119. 'nombre': 'Papa Regilla',
  120. 'precio': 0,
  121. });
  122. await db.insert('Producto', {
  123. 'nombre': 'Papa Curly',
  124. 'precio': 0,
  125. });
  126. await db.insert('Producto', {
  127. 'nombre': 'Papa Smile',
  128. 'precio': 0,
  129. });
  130. await db.insert('Producto', {
  131. 'nombre': 'Papa Francesa',
  132. 'precio': 0,
  133. });
  134. await db.insert('Producto', {
  135. 'nombre': 'BBQ',
  136. 'precio': 0,
  137. });
  138. await db.insert('Producto', {
  139. 'nombre': 'HOTBBQ',
  140. 'precio': 0,
  141. });
  142. await db.insert('Producto', {
  143. 'nombre': 'BUFFALO',
  144. 'precio': 0,
  145. });
  146. await db.insert('Producto', {
  147. 'nombre': 'TERIYAKI',
  148. 'precio': 0,
  149. });
  150. await db.insert('Producto', {
  151. 'nombre': 'PARMESAN GARLIC',
  152. 'precio': 0,
  153. });
  154. await db.insert('Producto', {
  155. 'nombre': 'QUESO AMARILLO',
  156. 'precio': 0,
  157. });
  158. await db.insert('Producto', {
  159. 'nombre': 'RANCH',
  160. 'precio': 0,
  161. });
  162. await db.insert('Producto', {
  163. 'nombre': 'CHIPOTLE',
  164. 'precio': 0,
  165. });
  166. await db.insert('Producto', {
  167. 'nombre': 'ADEREZO JALAPEÑO',
  168. 'precio': 0,
  169. });
  170. await db.insert('Producto', {
  171. 'nombre': 'KETCHUP',
  172. 'precio': 0,
  173. });
  174. await db.insert('Producto', {
  175. 'nombre': 'JALAPEÑO',
  176. 'precio': 0,
  177. });
  178. await db.insert('Producto', {
  179. 'nombre': 'QUESO BLANCO',
  180. 'precio': 0,
  181. });
  182. await db.insert('Producto', {
  183. 'nombre': 'TAKIS',
  184. 'precio': 0,
  185. });
  186. await db.insert('Producto', {
  187. 'nombre': 'RUFFLES',
  188. 'precio': 0,
  189. });
  190. await db.insert('Producto', {
  191. 'nombre': 'QUESO PARMESANO',
  192. 'precio': 0,
  193. });
  194. await db.insert('Producto', {
  195. 'nombre': 'ELOTE',
  196. 'precio': 0,
  197. });
  198. break;
  199. case 2:
  200. await db.execute('''
  201. CREATE TABLE ProductoTopping (
  202. id INTEGER PRIMARY KEY AUTOINCREMENT,
  203. idProducto INTEGER,
  204. idTopping INTEGER,
  205. FOREIGN KEY (idProducto) REFERENCES Producto(id),
  206. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  207. )
  208. ''');
  209. break;
  210. case 3:
  211. await db.execute('''
  212. CREATE TABLE PedidoProductoTopping (
  213. id INTEGER PRIMARY KEY AUTOINCREMENT,
  214. idPedidoProducto INTEGER,
  215. idTopping INTEGER,
  216. FOREIGN KEY (idPedidoProducto) REFERENCES PedidoProducto(id),
  217. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  218. )
  219. ''');
  220. break;
  221. }
  222. oldVersion++;
  223. }
  224. }
  225. Future<int> guardar(T model) async {
  226. try {
  227. var dbClient = await db;
  228. String nombreTabla = model.runtimeType.toString();
  229. String modelo = json.encode(model, toEncodable: toEncodable);
  230. Map<String, dynamic> modelMap = json.decode(modelo);
  231. int id = 0;
  232. if (modelMap['id'] != null && modelMap['id'] != 0) {
  233. await dbClient!.update(
  234. nombreTabla,
  235. modelMap,
  236. where: 'id = ?',
  237. whereArgs: [modelMap['id']],
  238. );
  239. id = modelMap['id'];
  240. } else {
  241. modelMap.remove('id');
  242. id = await dbClient!.insert(nombreTabla, modelMap);
  243. }
  244. if (model is Producto) {
  245. await _guardarToppings(dbClient, id, model.topings);
  246. }
  247. return id;
  248. } catch (e) {
  249. print('Error al guardar en $T: $e');
  250. return 0;
  251. }
  252. }
  253. Future<void> _guardarToppings(
  254. Database db, int idProducto, List<Producto>? topings) async {
  255. await db.delete('ProductoTopping',
  256. where: 'idProducto = ?', whereArgs: [idProducto]);
  257. if (topings != null) {
  258. for (var topping in topings) {
  259. await db.insert('ProductoTopping', {
  260. 'idProducto': idProducto,
  261. 'idTopping': topping.id,
  262. });
  263. }
  264. }
  265. }
  266. Future<int> guardarLocal(T model) async {
  267. var dbClient = await db;
  268. String nombreTabla = model.runtimeType.toString();
  269. String modelo = json.encode(model, toEncodable: toEncodable);
  270. Map<String, dynamic> modelMap = json.decode(modelo);
  271. if (nombreTabla == "PedidoProductoTopping") {
  272. modelMap.remove('idLocal');
  273. modelMap.remove('eliminado');
  274. }
  275. if (modelMap['id'] == null || modelMap['id'] == 0) {
  276. modelMap.remove('id');
  277. }
  278. int resultado;
  279. int? identificadorLocal = modelMap[Basico.identificadorLocal];
  280. if (identificadorLocal != null && identificadorLocal > 0) {
  281. resultado = await dbClient!.update(
  282. nombreTabla,
  283. modelMap,
  284. where: "$idLocal = ?",
  285. whereArgs: [identificadorLocal],
  286. );
  287. } else {
  288. resultado = await dbClient!.insert(nombreTabla, modelMap);
  289. var rawQuery =
  290. await dbClient.rawQuery("SELECT last_insert_rowid() as id");
  291. if (rawQuery.isNotEmpty) {
  292. resultado = int.parse(rawQuery.first["id"].toString());
  293. modelMap[Basico.identificadorLocal] = resultado;
  294. }
  295. }
  296. if (model is Pedido) {
  297. model.id = resultado;
  298. }
  299. if (model is Producto) {
  300. await _guardarToppings(dbClient!, model.id!, model.topings);
  301. }
  302. return resultado;
  303. }
  304. dynamic toEncodable(dynamic item) {
  305. if (item is Pedido) {
  306. return item.toJson();
  307. } else if (item is PedidoProducto) {
  308. return item.toJson();
  309. } else if (item is PedidoProductoTopping) {
  310. return item.toJson();
  311. } else if (item is Producto) {
  312. return item.toJson();
  313. } else if (item is CategoriaProducto) {
  314. return item.toJson();
  315. }
  316. throw UnsupportedError(
  317. 'Type not supported for serialization: ${item.runtimeType}');
  318. }
  319. Future<List<T>> obtenerTodos({String orderBy = 'id DESC'}) async {
  320. var db = await this.db;
  321. String tableName = T.toString();
  322. var result = await db!.query(tableName, orderBy: orderBy);
  323. return result.map((map) => fromMap<T>(map)).toList();
  324. }
  325. T fromMap<T>(Map<String, dynamic> map) {
  326. switch (T) {
  327. case Pedido:
  328. return Pedido.fromJson(map) as T;
  329. case Producto:
  330. return Producto.fromJson(map) as T;
  331. default:
  332. throw Exception('Tipo no soportado');
  333. }
  334. }
  335. Future<Pedido?> obtenerPorId(int id) async {
  336. Database? dbClient = await db;
  337. List<Map> maps =
  338. await dbClient!.query('Pedido', where: 'id = ?', whereArgs: [id]);
  339. if (maps.isNotEmpty) {
  340. return Pedido.fromJson(Map<String, dynamic>.from(maps.first));
  341. }
  342. return null;
  343. }
  344. Future<List<PedidoProducto>> obtenerPorIdPedido(int idPedido) async {
  345. Database? dbClient = await db;
  346. List<Map> maps = await dbClient!
  347. .query('PedidoProducto', where: 'idPedido = ?', whereArgs: [idPedido]);
  348. return maps
  349. .map((map) => PedidoProducto.fromJson(Map<String, dynamic>.from(map)))
  350. .toList();
  351. }
  352. Future<int> contarPedidos() async {
  353. Database? dbClient = await db;
  354. var result = await dbClient!.rawQuery('SELECT COUNT(*) FROM Pedido');
  355. return Sqflite.firstIntValue(result) ?? 0;
  356. }
  357. Future<List<Pedido>> obtenerPedidosPaginados(int limit, int offset) async {
  358. Database? dbClient = await db;
  359. List<Map<String, dynamic>> result = await dbClient!
  360. .query('Pedido', limit: limit, offset: offset, orderBy: 'id DESC');
  361. return result.map((map) => Pedido.fromJson(map)).toList();
  362. }
  363. Future<Producto?> obtenerProductoPorId(int idProducto) async {
  364. Database? dbClient = await db;
  365. List<Map> maps = await dbClient!
  366. .query('Producto', where: 'id = ?', whereArgs: [idProducto]);
  367. if (maps.isNotEmpty) {
  368. return Producto.fromJson(Map<String, dynamic>.from(maps.first));
  369. }
  370. return null;
  371. }
  372. Future<List<int>> obtenerToppingsPorProducto(int idProducto) async {
  373. var dbClient = await db;
  374. var result = await dbClient!.query(
  375. 'ProductoTopping',
  376. where: 'idProducto = ?',
  377. whereArgs: [idProducto],
  378. );
  379. return result.map((map) => map['idTopping'] as int).toList();
  380. }
  381. Future<List<PedidoProductoTopping>> obtenerToppingsPorPedidoProducto(
  382. int idPedidoProducto) async {
  383. var dbClient = await db;
  384. List<Map> maps = await dbClient!.query('PedidoProductoTopping',
  385. where: 'idPedidoProducto = ?', whereArgs: [idPedidoProducto]);
  386. if (maps.isNotEmpty) {
  387. return maps
  388. .map((map) =>
  389. PedidoProductoTopping.fromJson(Map<String, dynamic>.from(map)))
  390. .toList();
  391. }
  392. return [];
  393. }
  394. Future<int> obtenerProximoFolio() async {
  395. var dbClient = await db;
  396. var result = await dbClient!.rawQuery(
  397. 'SELECT MAX(CAST(folio AS INTEGER)) as last_folio FROM Pedido');
  398. if (result.isNotEmpty && result.first["last_folio"] != null) {
  399. return int.tryParse(result.first["last_folio"].toString())! + 1;
  400. }
  401. return 1;
  402. }
  403. Future<List<T>> buscarPorFolio(String folio) async {
  404. var dbClient = await db;
  405. List<Map<String, dynamic>> maps = await dbClient!.query(
  406. 'Pedido',
  407. where: 'folio LIKE ?',
  408. whereArgs: ['%$folio%'],
  409. );
  410. return maps.map((map) => fromMap<T>(map)).toList();
  411. }
  412. Future<List<Pedido>> buscarPorFecha(
  413. DateTime startDate, DateTime endDate) async {
  414. var dbClient = await db;
  415. String startDateString = DateFormat('dd-MM-yyyy').format(startDate);
  416. String endDateString = DateFormat('dd-MM-yyyy 23:59:59').format(endDate);
  417. List<Map<String, dynamic>> maps = await dbClient!.query(
  418. 'Pedido',
  419. where: 'peticion BETWEEN ? AND ?',
  420. whereArgs: [startDateString, endDateString],
  421. );
  422. return maps.map((map) => Pedido.fromJson(map)).toList();
  423. }
  424. Future<List<CorteCaja>> buscarPorFechaCorte(
  425. DateTime startDate, DateTime endDate) async {
  426. var dbClient = await db;
  427. String startDateString = DateFormat('dd-MM-yyyy').format(startDate);
  428. String endDateString = DateFormat('dd-MM-yyyy 23:59:59').format(endDate);
  429. List<Map<String, dynamic>> maps = await dbClient!.query(
  430. 'CorteCaja',
  431. where: 'fecha BETWEEN ? AND ?',
  432. whereArgs: [startDateString, endDateString],
  433. );
  434. return maps.map((map) => CorteCaja.fromJson(map)).toList();
  435. }
  436. Future<void> eliminar<T>(int id) async {
  437. var dbClient = await db;
  438. String tableName = T.toString();
  439. await dbClient!.delete(tableName, where: 'id = ?', whereArgs: [id]);
  440. }
  441. }