repo_service.dart 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  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 '../data/api_response.dart';
  7. import '../models/models.dart';
  8. import '../views/producto/producto_imagen.dart';
  9. import 'base_service.dart';
  10. class RepoService<T> {
  11. static int dbVersion = 23;
  12. static String dbName = 'conalepPos7.db';
  13. static const String id = Basico.identificadorWeb;
  14. static const String idLocal = Basico.identificadorLocal;
  15. static Database? _db;
  16. final Map<String, dynamic> contexto = {
  17. 'Categoria': CategoriaProducto(),
  18. 'Producto': Producto(),
  19. 'Pedido': Pedido(productos: []),
  20. 'PedidoProducto': PedidoProducto(),
  21. 'Gasto': Gasto(),
  22. 'Deposito': Deposito(),
  23. 'CorteCaja': CorteCaja(),
  24. };
  25. Future<Database?> get db async {
  26. if (_db != null) return _db;
  27. _db = await databaseInit();
  28. return _db;
  29. }
  30. Future<Database> databaseInit() async {
  31. String dir = (await getApplicationDocumentsDirectory()).path;
  32. String path = join(dir, dbName);
  33. return await openDatabase(
  34. path,
  35. version: dbVersion,
  36. onCreate: _onCreate,
  37. onUpgrade: _onUpgrade,
  38. );
  39. }
  40. /// Crea la base de datos
  41. _onCreate(Database db, int version) async {
  42. contexto.forEach((String nombre, dynamic modelo) async {
  43. Map<String, dynamic> model = json.decode(json.encode(modelo.toJson()));
  44. String sql =
  45. "CREATE TABLE ${modelo.runtimeType.toString()} (id INTEGER PRIMARY KEY AUTOINCREMENT";
  46. model.forEach((String key, dynamic value) {
  47. if (key != "id") {
  48. String tipo = value.runtimeType.toString();
  49. String sqlType = "";
  50. if (equals(tipo, 'int')) {
  51. sqlType = "INTEGER";
  52. } else if (equals(tipo, 'double')) {
  53. sqlType = "REAL";
  54. } else if (equals(tipo, 'bool')) {
  55. sqlType = "BOOLEAN";
  56. } else {
  57. sqlType = "TEXT";
  58. }
  59. sql += ", $key $sqlType";
  60. }
  61. });
  62. sql += ")";
  63. await db.execute(sql);
  64. await db.execute('''
  65. CREATE TABLE PedidoProductoTopping (
  66. id INTEGER PRIMARY KEY AUTOINCREMENT,
  67. idPedidoProducto INTEGER,
  68. idTopping INTEGER,
  69. FOREIGN KEY (idPedidoProducto) REFERENCES PedidoProducto(id),
  70. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  71. )
  72. ''');
  73. if (modelo.runtimeType.toString() == 'Pedido') {
  74. await db.execute(
  75. 'ALTER TABLE Pedido ADD COLUMN IF NOT EXISTS descuento INTEGER DEFAULT 0');
  76. }
  77. await db.execute('''
  78. CREATE TABLE Descuento (
  79. id INTEGER PRIMARY KEY AUTOINCREMENT,
  80. porcentaje INTEGER
  81. )
  82. ''');
  83. await db.insert('Descuento', {'porcentaje': 0});
  84. await db.insert('Descuento', {'porcentaje': 5});
  85. await db.insert('Descuento', {'porcentaje': 10});
  86. await db.insert('Descuento', {'porcentaje': 15});
  87. await db.insert('Descuento', {'porcentaje': 20});
  88. await db.insert('Descuento', {'porcentaje': 25});
  89. await db.insert('Descuento', {'porcentaje': 30});
  90. });
  91. await db.execute('''
  92. CREATE TABLE ProductoTopping (
  93. id INTEGER PRIMARY KEY AUTOINCREMENT,
  94. idProducto INTEGER,
  95. idTopping INTEGER,
  96. FOREIGN KEY (idProducto) REFERENCES Producto(id),
  97. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  98. )
  99. ''');
  100. await db.execute('''
  101. CREATE TABLE Variable (
  102. id INTEGER PRIMARY KEY AUTOINCREMENT,
  103. nombre TEXT,
  104. clave TEXT,
  105. descripcion TEXT,
  106. activo BOOLEAN,
  107. idLocal INTEGER,
  108. eliminado TEXT
  109. )
  110. ''');
  111. await db.insert('Variable', {
  112. 'nombre': 'Imprimir Ticket Cocina',
  113. 'clave': 'ticket_cocina',
  114. 'descripcion':
  115. 'Variable para imprimir ticket de cocina automaticamente al momento de generar un pedido',
  116. 'activo': 1,
  117. 'idLocal': -1,
  118. });
  119. await db.insert('Variable', {
  120. 'nombre': 'Imprimir Ticket Venta',
  121. 'clave': 'ticket_venta',
  122. 'descripcion':
  123. 'Variable para imprimir ticket de venta automaticamente al momento de generar un pedido',
  124. 'activo': 0,
  125. 'idLocal': -1,
  126. });
  127. await db.insert('Variable', {
  128. 'nombre': 'Imprimir ticket PC/Tablet',
  129. 'clave': 'ticket_pc',
  130. 'descripcion':
  131. 'Al estar activo imprime ticket para pc, el estar desactivado imprime ticket para tablet',
  132. 'activo': 1,
  133. 'idLocal': -1,
  134. });
  135. }
  136. /// Actualiza la version de la base de datos
  137. void _onUpgrade(Database db, int oldVersion, int newVersion) async {
  138. while (oldVersion < newVersion) {
  139. switch (oldVersion) {
  140. case 1:
  141. await db.execute(
  142. "ALTER TABLE CategoriaProducto ADD COLUMN esToping INTEGER DEFAULT 0");
  143. await db.execute(
  144. "ALTER TABLE CategoriaProducto ADD COLUMN descripcion TEXT DEFAULT ''");
  145. await db.execute(
  146. "ALTER TABLE CategoriaProducto ADD COLUMN maximo INTEGER");
  147. break;
  148. case 2:
  149. await db.execute('''
  150. CREATE TABLE ProductoTopping (
  151. id INTEGER PRIMARY KEY AUTOINCREMENT,
  152. idProducto INTEGER,
  153. idTopping INTEGER,
  154. FOREIGN KEY (idProducto) REFERENCES Producto(id),
  155. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  156. )
  157. ''');
  158. break;
  159. case 3:
  160. await db.execute('''
  161. CREATE TABLE PedidoProductoTopping (
  162. id INTEGER PRIMARY KEY AUTOINCREMENT,
  163. idPedidoProducto INTEGER,
  164. idTopping INTEGER,
  165. FOREIGN KEY (idPedidoProducto) REFERENCES PedidoProducto(id),
  166. FOREIGN KEY (idTopping) REFERENCES Producto(id)
  167. )
  168. ''');
  169. break;
  170. case 4:
  171. await db.execute('''
  172. ALTER TABLE Pedido ADD COLUMN IF NOT EXISTS descuento INTEGER DEFAULT 0
  173. ''');
  174. break;
  175. case 5:
  176. await db.execute('''
  177. CREATE TABLE IF NOT EXISTS Descuento (
  178. id INTEGER PRIMARY KEY AUTOINCREMENT,
  179. porcentaje INTEGER
  180. )
  181. ''');
  182. await db.insert('Descuento', {'porcentaje': 0});
  183. await db.insert('Descuento', {'porcentaje': 5});
  184. await db.insert('Descuento', {'porcentaje': 10});
  185. await db.insert('Descuento', {'porcentaje': 15});
  186. await db.insert('Descuento', {'porcentaje': 20});
  187. await db.insert('Descuento', {'porcentaje': 25});
  188. await db.insert('Descuento', {'porcentaje': 30});
  189. break;
  190. case 6:
  191. await db.execute('''
  192. ALTER TABLE Pedido ADD COLUMN tipoPago TEXT DEFAULT '';
  193. ''');
  194. await db.execute('''
  195. ALTER TABLE Pedido ADD COLUMN cantEfectivo REAL DEFAULT 0;
  196. ''');
  197. await db.execute('''
  198. ALTER TABLE Pedido ADD COLUMN cantTarjeta REAL DEFAULT 0;
  199. ''');
  200. await db.execute('''
  201. ALTER TABLE Pedido ADD COLUMN cantTransferencia REAL DEFAULT 0;
  202. ''');
  203. break;
  204. case 7:
  205. await db.execute('''
  206. CREATE TABLE Variable (
  207. id INTEGER PRIMARY KEY AUTOINCREMENT,
  208. nombre TEXT,
  209. clave TEXT,
  210. descripcion TEXT,
  211. activo BOOLEAN,
  212. idLocal INTEGER,
  213. eliminado TEXT
  214. )
  215. ''');
  216. break;
  217. case 8:
  218. await db.execute('''
  219. ALTER TABLE Producto ADD COLUMN toping INTEGER DEFAULT 0;
  220. ''');
  221. break;
  222. case 9:
  223. await db.execute('''
  224. ALTER TABLE Pedido ADD COLUMN idWeb INTEGER;
  225. ''');
  226. await db.execute('''
  227. ALTER TABLE Pedido ADD COLUMN sincronizado TEXT;
  228. ''');
  229. await db.execute('''
  230. ALTER TABLE PedidoProducto ADD COLUMN idWeb INTEGER;
  231. ''');
  232. await db.execute('''
  233. ALTER TABLE PedidoProducto ADD COLUMN sincronizado TEXT;
  234. ''');
  235. break;
  236. // case 10:
  237. // await db.execute('''
  238. // ALTER TABLE Pedido ADD COLUMN idWeb INTEGER;
  239. // ''');
  240. // await db.execute('''
  241. // ALTER TABLE Pedido ADD COLUMN sincronizado TEXT;
  242. // ''');
  243. // await db.execute('''
  244. // ALTER TABLE PedidoProducto ADD COLUMN idWeb INTEGER;
  245. // ''');
  246. // await db.execute('''
  247. // ALTER TABLE PedidoProducto ADD COLUMN sincronizado TEXT;
  248. // ''');
  249. // break;
  250. // case 11:
  251. // await db.execute('''
  252. // ALTER TABLE Pedido ADD COLUMN idWeb INTEGER;
  253. // ''');
  254. // await db.execute('''
  255. // ALTER TABLE Pedido ADD COLUMN sincronizado TEXT;
  256. // ''');
  257. // await db.execute('''
  258. // ALTER TABLE PedidoProducto ADD COLUMN idWeb INTEGER;
  259. // ''');
  260. // await db.execute('''
  261. // ALTER TABLE PedidoProducto ADD COLUMN sincronizado TEXT;
  262. // ''');
  263. // break;
  264. case 12:
  265. await db.execute('''
  266. update Pedido set sincronizado = null, peticion = strftime('%Y-%m-%dT%H:%M:%S',
  267. datetime(substr(peticion, 7, 4) || '-' ||
  268. substr(peticion, 4, 2) || '-' ||
  269. substr(peticion, 1, 2) || ' ' ||
  270. substr(peticion, 12, 8) || ' -07:00', 'localtime', '+07:00'))
  271. WHERE strftime('%Y-%m-%dT%H:%M:%S',
  272. datetime(substr(peticion, 7, 4) || '-' ||
  273. substr(peticion, 4, 2) || '-' ||
  274. substr(peticion, 1, 2) || ' ' ||
  275. substr(peticion, 12, 8) || ' -07:00', 'localtime', '+07:00')) is not null
  276. ''');
  277. break;
  278. case 13:
  279. await db.execute('DROP TABLE IF EXISTS Producto');
  280. //Se tiene que crear nuevamente para que precio sea Double
  281. await db.execute('''
  282. CREATE TABLE Producto (
  283. id INTEGER PRIMARY KEY AUTOINCREMENT,
  284. idCategoria INTEGER,
  285. idLocal INTEGER,
  286. nombre TEXT,
  287. descripcion TEXT,
  288. imagen TEXT,
  289. venta INTEGER,
  290. existencia INTEGER,
  291. precio REAL,
  292. verMenu INTEGER,
  293. codigo TEXT,
  294. descuento TEXT,
  295. toping INTEGER,
  296. creado TEXT,
  297. modificado TEXT,
  298. eliminado TEXT
  299. )
  300. ''');
  301. await db.execute('DELETE FROM CategoriaProducto');
  302. await db.execute('''
  303. ALTER TABLE CategoriaProducto ADD COLUMN creado TEXT;
  304. ''');
  305. await db.execute('''
  306. ALTER TABLE CategoriaProducto ADD COLUMN modificado TEXT;
  307. ''');
  308. break;
  309. case 14:
  310. await db.execute('''
  311. ALTER TABLE Producto ADD COLUMN activo INTEGER;
  312. ''');
  313. break;
  314. case 16:
  315. await db.execute('''
  316. ALTER TABLE ProductoTopping ADD COLUMN idCategoria INTEGER;
  317. ''');
  318. await db.execute('''
  319. ALTER TABLE ProductoTopping ADD COLUMN creado text;
  320. ''');
  321. await db.execute('''
  322. ALTER TABLE ProductoTopping ADD COLUMN modificado text;
  323. ''');
  324. await db.execute('''
  325. ALTER TABLE ProductoTopping ADD COLUMN eliminado text;
  326. ''');
  327. break;
  328. case 17:
  329. await db.execute('''
  330. CREATE TABLE Sucursal (
  331. id INTEGER PRIMARY KEY AUTOINCREMENT,
  332. nombre TEXT,
  333. descripcion TEXT,
  334. direccion TEXT,
  335. ciudad TEXT,
  336. activo INTEGER,
  337. clave TEXT,
  338. eliminado TEXT,
  339. creado TEXT,
  340. modificado TEXT,
  341. idLocal INTEGER,
  342. seleccionado INTEGER
  343. )
  344. ''');
  345. break;
  346. case 18:
  347. await db.execute('''
  348. CREATE TABLE Usuario (
  349. id INTEGER PRIMARY KEY AUTOINCREMENT,
  350. nombre TEXT,
  351. apellidos TEXT,
  352. correo TEXT,
  353. celular TEXT,
  354. celularPersonal TEXT,
  355. rol INTEGER,
  356. genero BOOLEAN,
  357. estatus INTEGER,
  358. imagen TEXT,
  359. rfc TEXT,
  360. razonSocial TEXT,
  361. calle TEXT,
  362. numeroExterior TEXT,
  363. colonia TEXT,
  364. codigoPostal TEXT,
  365. idCiudad INTEGER,
  366. idEstado INTEGER,
  367. idSucursal INTEGER,
  368. turno TEXT,
  369. eliminado TEXT,
  370. creado TEXT,
  371. modificado TEXT,
  372. idLocal INTEGER
  373. )
  374. ''');
  375. await db.execute('''
  376. CREATE TABLE Permiso (
  377. id TEXT PRIMARY KEY,
  378. idModulo TEXT,
  379. nombre TEXT,
  380. descripcion TEXT,
  381. eliminado TEXT,
  382. creado TEXT,
  383. modificado TEXT
  384. )
  385. ''');
  386. await db.execute('''
  387. CREATE TABLE UsuarioPermiso (
  388. id INTEGER PRIMARY KEY AUTOINCREMENT,
  389. idUsuario INTEGER,
  390. idPermiso TEXT,
  391. asignado TEXT,
  392. modificado TEXT,
  393. eliminado TEXT,
  394. idLocal INTEGER
  395. )
  396. ''');
  397. await db.execute('''
  398. ALTER TABLE ProductoTopping ADD COLUMN idLocal INTEGER;
  399. ''');
  400. await db.execute('''
  401. ALTER TABLE PedidoProductoTopping ADD COLUMN idLocal INTEGER;
  402. ''');
  403. await db.execute('''
  404. ALTER TABLE PedidoProductoTopping ADD COLUMN idCategoria INTEGER;
  405. ''');
  406. break;
  407. case 19:
  408. await db.execute('''
  409. ALTER TABLE CategoriaProducto ADD COLUMN minimo INTEGER;
  410. ''');
  411. break;
  412. case 20:
  413. await db.execute('''
  414. ALTER TABLE Usuario ADD COLUMN clave TEXT;
  415. ''');
  416. await db.insert('Variable', {
  417. 'nombre': 'Imprimir ticket PC/Tablet',
  418. 'clave': 'ticket_pc',
  419. 'descripcion':
  420. 'Al estar activo imprime ticket para pc, el estar desactivado imprime ticket para tablet',
  421. 'activo': 1,
  422. 'idLocal': -1,
  423. });
  424. break;
  425. case 21:
  426. await db.execute('DROP TABLE CorteCaja');
  427. await db.execute('DROP TABLE Deposito');
  428. await db.execute('DROP TABLE Gasto');
  429. await db.execute('''
  430. CREATE TABLE CorteCaja (
  431. id TEXT PRIMARY KEY,
  432. fechaApertura TEXT,
  433. fechaCorte TEXT,
  434. idUsuario INTEGER,
  435. idSucursal INTEGER,
  436. fondo REAL,
  437. fondoDiaSig REAL,
  438. ventaPuntos REAL,
  439. ventaEfe REAL,
  440. ventaTrans REAL,
  441. ventaTarj REAL,
  442. gasto REAL,
  443. retiro REAL,
  444. corteFinal REAL,
  445. creado TEXT,
  446. modificado TEXT,
  447. eliminado TEXT
  448. )
  449. ''');
  450. await db.execute('''
  451. CREATE TABLE Deposito (
  452. id TEXT PRIMARY KEY,
  453. idCorteCaja TEXT,
  454. idSucursal INTEGER,
  455. idUsuario INTEGER,
  456. fechaDeposito TEXT,
  457. monto REAL,
  458. persona TEXT,
  459. descripcion TEXT,
  460. creado TEXT,
  461. modificado TEXT,
  462. eliminado TEXT
  463. )
  464. ''');
  465. await db.execute('''
  466. CREATE TABLE Retiro (
  467. id TEXT PRIMARY KEY,
  468. idCorteCaja TEXT,
  469. idSucursal INTEGER,
  470. idUsuario INTEGER,
  471. fechaRetiro TEXT,
  472. monto REAL,
  473. persona TEXT,
  474. descripcion TEXT,
  475. creado TEXT,
  476. modificado TEXT,
  477. eliminado TEXT
  478. )
  479. ''');
  480. await db.execute('''
  481. CREATE TABLE Gasto (
  482. id TEXT PRIMARY KEY,
  483. idCorteCaja TEXT,
  484. idSucursal INTEGER,
  485. idUsuario INTEGER,
  486. fechaGasto TEXT,
  487. monto REAL,
  488. persona TEXT,
  489. descripcion TEXT,
  490. creado TEXT,
  491. modificado TEXT,
  492. eliminado TEXT
  493. )
  494. ''');
  495. await db.execute('''
  496. update Pedido set sincronizado = null where estatus = 'CANCELADO'
  497. ''');
  498. break;
  499. case 22:
  500. await db.execute('''
  501. ALTER TABLE CorteCaja ADD COLUMN deposito REAL;
  502. ''');
  503. await db.execute('''
  504. ALTER TABLE CorteCaja ADD COLUMN idWeb TEXT;
  505. ''');
  506. await db.execute('''
  507. ALTER TABLE CorteCaja ADD COLUMN sincronizado TEXT;
  508. ''');
  509. await db.execute('''
  510. ALTER TABLE Gasto ADD COLUMN idWeb TEXT;
  511. ''');
  512. await db.execute('''
  513. ALTER TABLE Gasto ADD COLUMN sincronizado TEXT;
  514. ''');
  515. await db.execute('''
  516. ALTER TABLE Retiro ADD COLUMN idWeb TEXT;
  517. ''');
  518. await db.execute('''
  519. ALTER TABLE Retiro ADD COLUMN sincronizado TEXT;
  520. ''');
  521. await db.execute('''
  522. ALTER TABLE Deposito ADD COLUMN idWeb TEXT;
  523. ''');
  524. await db.execute('''
  525. ALTER TABLE Deposito ADD COLUMN sincronizado TEXT;
  526. ''');
  527. }
  528. oldVersion++;
  529. }
  530. }
  531. Future<int> guardar(T model) async {
  532. try {
  533. // Convert the model to JSON for the database
  534. String modelo = json.encode(model, toEncodable: toEncodable);
  535. Map<String, dynamic> modelMap = json.decode(modelo);
  536. var dbClient = await db;
  537. String nombreTabla = model.runtimeType.toString();
  538. // Check if the model has a String ID or an int ID
  539. dynamic id = modelMap['id'];
  540. bool isStringId = id is String;
  541. bool isIntId = id is int;
  542. // If id is of type String (e.g., Permiso)
  543. if (isStringId) {
  544. if (id == null || (id as String).isEmpty) {
  545. throw Exception('El ID del modelo no puede ser nulo o vacío');
  546. }
  547. // Check for existing record with the String ID
  548. List<Map> existing = await dbClient!.query(
  549. nombreTabla,
  550. where: 'id = ?',
  551. whereArgs: [id],
  552. );
  553. if (existing.isNotEmpty) {
  554. await dbClient.update(
  555. nombreTabla,
  556. modelMap,
  557. where: 'id = ?',
  558. whereArgs: [id],
  559. );
  560. } else {
  561. print(
  562. "Insertando nuevo registro en la tabla $nombreTabla con ID: $id");
  563. await dbClient.insert(nombreTabla, modelMap);
  564. }
  565. return 1;
  566. } else if (isIntId) {
  567. // If id is of type int (e.g., other models)
  568. if (id == null || id == 0) {
  569. modelMap
  570. .remove('id'); // Remove id if it's null or 0 for auto-increment
  571. }
  572. List<Map> existing = (id != null && id > 0)
  573. ? await dbClient!
  574. .query(nombreTabla, where: 'id = ?', whereArgs: [id])
  575. : [];
  576. if (existing.isNotEmpty) {
  577. print("Actualizando registro existente con ID: $id");
  578. await dbClient!.update(
  579. nombreTabla,
  580. modelMap,
  581. where: 'id = ?',
  582. whereArgs: [id],
  583. );
  584. } else {
  585. print("Insertando nuevo registro en la tabla $nombreTabla");
  586. id = await dbClient!.insert(nombreTabla, modelMap);
  587. }
  588. return id as int;
  589. } else {
  590. throw Exception('Tipo de ID no soportado');
  591. }
  592. } catch (e) {
  593. print('Error al guardar en dynamic: $e');
  594. return 0;
  595. }
  596. }
  597. void asignarFechasLocalmente(Basico model) {
  598. DateTime ahora = DateTime.now();
  599. if (model.creado == null) {
  600. model.creado = ahora.toUtc();
  601. }
  602. model.modificado = ahora.toUtc();
  603. }
  604. Future<void> _guardarToppings(
  605. Database db, int idProducto, List<Producto>? topings) async {
  606. await db.delete('ProductoTopping',
  607. where: 'idProducto = ?', whereArgs: [idProducto]);
  608. if (topings != null) {
  609. for (var topping in topings) {
  610. await db.insert('ProductoTopping', {
  611. 'idProducto': idProducto,
  612. 'idTopping': topping.id,
  613. });
  614. }
  615. }
  616. }
  617. Future<int> guardarLocal(T model) async {
  618. var dbClient = await db;
  619. String nombreTabla = model.runtimeType.toString();
  620. String modelo = json.encode(model, toEncodable: toEncodable);
  621. Map<String, dynamic> modelMap = json.decode(modelo);
  622. if (nombreTabla == "PedidoProductoTopping") {
  623. modelMap.remove('idLocal');
  624. modelMap.remove('eliminado');
  625. }
  626. if (modelMap['id'] == null || modelMap['id'] == 0) {
  627. modelMap.remove('id');
  628. }
  629. int resultado;
  630. int? identificadorLocal = modelMap[Basico.identificadorLocal];
  631. if (identificadorLocal != null && identificadorLocal > 0) {
  632. resultado = await dbClient!.update(
  633. nombreTabla,
  634. modelMap,
  635. where: "$idLocal = ?",
  636. whereArgs: [identificadorLocal],
  637. );
  638. } else {
  639. resultado = await dbClient!.insert(nombreTabla, modelMap);
  640. var rawQuery =
  641. await dbClient.rawQuery("SELECT last_insert_rowid() as id");
  642. if (rawQuery.isNotEmpty) {
  643. resultado = int.parse(rawQuery.first["id"].toString());
  644. modelMap[Basico.identificadorLocal] = resultado;
  645. }
  646. }
  647. if (model is Pedido) {
  648. model.id = resultado;
  649. }
  650. if (model is Producto) {
  651. await _guardarToppings(dbClient!, model.id!, model.topings);
  652. }
  653. return resultado;
  654. }
  655. dynamic toEncodable(dynamic item) {
  656. return item.toJson();
  657. }
  658. Future<List<T>> obtenerTodos({String orderBy = 'id DESC'}) async {
  659. var db = await this.db;
  660. String tableName = T.toString();
  661. var result = await db!
  662. .query(tableName, where: 'eliminado IS NULL', orderBy: orderBy);
  663. return result.map((map) => fromMap<T>(map)).toList();
  664. }
  665. T fromMap<T>(Map<String, dynamic> map) {
  666. switch (T) {
  667. case Pedido:
  668. return Pedido.fromJson(map) as T;
  669. case Producto:
  670. return Producto.fromJson(map) as T;
  671. case Usuario:
  672. return Usuario.fromJson(map) as T;
  673. case CorteCaja:
  674. return CorteCaja.fromJson(map) as T;
  675. default:
  676. throw Exception('Tipo no soportado');
  677. }
  678. }
  679. Future<Pedido?> obtenerPorId(int id) async {
  680. Database? dbClient = await db;
  681. List<Map> maps =
  682. await dbClient!.query('Pedido', where: 'id = ?', whereArgs: [id]);
  683. if (maps.isNotEmpty) {
  684. return Pedido.fromJson(Map<String, dynamic>.from(maps.first));
  685. }
  686. return null;
  687. }
  688. Future<List<PedidoProducto>> obtenerPorIdPedido(int idPedido) async {
  689. Database? dbClient = await db;
  690. List<Map> maps = await dbClient!
  691. .query('PedidoProducto', where: 'idPedido = ?', whereArgs: [idPedido]);
  692. return maps
  693. .map((map) => PedidoProducto.fromJson(Map<String, dynamic>.from(map)))
  694. .toList();
  695. }
  696. //CORTE CAJA
  697. Future<List<Deposito>> obtenerDepositosPorIdCorteCaja(
  698. String idCorteCaja) async {
  699. var dbClient = await db;
  700. List<Map<String, dynamic>> maps = await dbClient!.query(
  701. 'Deposito',
  702. where: 'idCorteCaja = ? AND eliminado IS NULL',
  703. whereArgs: [idCorteCaja],
  704. );
  705. return maps.map((map) => Deposito.fromJson(map)).toList();
  706. }
  707. Future<List<Retiro>> obtenerRetirosPorIdCorteCaja(String idCorteCaja) async {
  708. var dbClient = await db;
  709. List<Map<String, dynamic>> maps = await dbClient!.query(
  710. 'Retiro',
  711. where: 'idCorteCaja = ? AND eliminado IS NULL',
  712. whereArgs: [idCorteCaja],
  713. );
  714. return maps.map((map) => Retiro.fromJson(map)).toList();
  715. }
  716. Future<List<Gasto>> obtenerGastosPorIdCorteCaja(String idCorteCaja) async {
  717. var dbClient = await db;
  718. List<Map<String, dynamic>> maps = await dbClient!.query(
  719. 'Gasto',
  720. where: 'idCorteCaja = ? AND eliminado IS NULL',
  721. whereArgs: [idCorteCaja],
  722. );
  723. return maps.map((map) => Gasto.fromJson(map)).toList();
  724. }
  725. Future<int> contarPedidos() async {
  726. Database? dbClient = await db;
  727. var result = await dbClient!.rawQuery('SELECT COUNT(*) FROM Pedido');
  728. return Sqflite.firstIntValue(result) ?? 0;
  729. }
  730. Future<double?> obtenerFondoDiaSigDelUltimoCorte() async {
  731. var dbClient = await db;
  732. List<Map<String, dynamic>> result = await dbClient!.query(
  733. 'CorteCaja',
  734. orderBy: 'fechaApertura DESC',
  735. limit: 1,
  736. );
  737. if (result.isNotEmpty) {
  738. return result.first['fondoDiaSig'] as double?;
  739. }
  740. return null;
  741. }
  742. Future<List<Pedido>> obtenerPedidosPaginados(int limit, int offset) async {
  743. Database? dbClient = await db;
  744. List<Map<String, dynamic>> result = await dbClient!
  745. .query('Pedido', limit: limit, offset: offset, orderBy: 'id DESC');
  746. return result.map((map) => Pedido.fromJson(map)).toList();
  747. }
  748. Future<Producto?> obtenerProductoPorId(int idProducto) async {
  749. Database? dbClient = await db;
  750. List<Map> maps = await dbClient!
  751. .query('Producto', where: 'id = ?', whereArgs: [idProducto]);
  752. if (maps.isNotEmpty) {
  753. return Producto.fromJson(Map<String, dynamic>.from(maps.first));
  754. }
  755. return null;
  756. }
  757. Future<List<int>> obtenerToppingsPorProducto(int idProducto) async {
  758. var dbClient = await db;
  759. var result = await dbClient!.query(
  760. 'ProductoTopping',
  761. where: 'idProducto = ?',
  762. whereArgs: [idProducto],
  763. );
  764. return result.map((map) => map['idTopping'] as int).toList();
  765. }
  766. Future<List<PedidoProductoTopping>> obtenerToppingsPorPedidoProducto(
  767. int idPedidoProducto) async {
  768. var dbClient = await db;
  769. List<Map> maps = await dbClient!.query('PedidoProductoTopping',
  770. where: 'idPedidoProducto = ?', whereArgs: [idPedidoProducto]);
  771. if (maps.isNotEmpty) {
  772. return maps
  773. .map((map) =>
  774. PedidoProductoTopping.fromJson(Map<String, dynamic>.from(map)))
  775. .toList();
  776. }
  777. return [];
  778. }
  779. Future<int> obtenerProximoFolio() async {
  780. var dbClient = await db;
  781. var result = await dbClient!.rawQuery(
  782. 'SELECT MAX(CAST(folio AS INTEGER)) as last_folio FROM Pedido');
  783. if (result.isNotEmpty && result.first["last_folio"] != null) {
  784. return int.tryParse(result.first["last_folio"].toString())! + 1;
  785. }
  786. return 1;
  787. }
  788. Future<List<T>> buscarPorFolio(String folio) async {
  789. var dbClient = await db;
  790. List<Map<String, dynamic>> maps = await dbClient!.query(
  791. 'Pedido',
  792. where: 'folio LIKE ?',
  793. whereArgs: ['%$folio%'],
  794. );
  795. return maps.map((map) => fromMap<T>(map)).toList();
  796. }
  797. Future<List<Pedido>> buscarPorFecha(
  798. DateTime startDate, DateTime endDate) async {
  799. var dbClient = await db;
  800. String startDateString = startDate.toIso8601String();
  801. String endDateString = endDate.toIso8601String();
  802. print(
  803. 'Ejecutando consulta: SELECT * FROM Pedido WHERE peticion BETWEEN $startDateString AND $endDateString');
  804. List<Map<String, dynamic>> maps = await dbClient!.rawQuery('''
  805. SELECT * FROM Pedido
  806. WHERE peticion BETWEEN ? AND ?
  807. ''', [startDateString, endDateString]);
  808. print('Resultado de la consulta: ${maps.length} pedidos encontrados.');
  809. return maps.map((map) => Pedido.fromJson(map)).toList();
  810. }
  811. Future<List<CorteCaja>> buscarPorFechaCorte(
  812. DateTime startDate, DateTime endDate) async {
  813. var dbClient = await db;
  814. String startDateString = DateFormat('dd-MM-yyyy').format(startDate);
  815. String endDateString = DateFormat('dd-MM-yyyy 23:59:59').format(endDate);
  816. List<Map<String, dynamic>> maps = await dbClient!.query(
  817. 'CorteCaja',
  818. where: 'fecha BETWEEN ? AND ?',
  819. whereArgs: [startDateString, endDateString],
  820. );
  821. return maps.map((map) => CorteCaja.fromJson(map)).toList();
  822. }
  823. Future<void> eliminar<T>(int id) async {
  824. var dbClient = await db;
  825. String tableName = T.toString();
  826. await dbClient!.delete(tableName, where: 'id = ?', whereArgs: [id]);
  827. }
  828. Future<List<Descuento>> obtenerTodosDescuentos() async {
  829. var dbClient = await db;
  830. var result = await dbClient!.query('Descuento', orderBy: 'porcentaje ASC');
  831. return result.map((map) => Descuento.fromJson(map)).toList();
  832. }
  833. Future<int> guardarDescuento(Descuento descuento) async {
  834. var dbClient = await db;
  835. if (descuento.id != null && descuento.id! > 0) {
  836. return await dbClient!.update(
  837. 'Descuento',
  838. descuento.toJson(),
  839. where: 'id = ?',
  840. whereArgs: [descuento.id],
  841. );
  842. } else {
  843. return await dbClient!.insert('Descuento', descuento.toJson());
  844. }
  845. }
  846. Future<int> eliminarDescuento(int id) async {
  847. var dbClient = await db;
  848. return await dbClient!
  849. .delete('Descuento', where: 'id = ?', whereArgs: [id]);
  850. }
  851. Future<Variable?> obtenerPorNombre(String nombre) async {
  852. var dbClient = await db;
  853. List<Map<String, dynamic>> maps = await dbClient!.query(
  854. 'Variable',
  855. where: 'nombre = ?',
  856. whereArgs: [nombre],
  857. );
  858. if (maps.isNotEmpty) {
  859. return Variable.fromJson(Map<String, dynamic>.from(maps.first));
  860. }
  861. return null;
  862. }
  863. Future<List<Pedido>> obtenerPedidosOrdenadosPorFecha() async {
  864. var dbClient = await db;
  865. String orderBy =
  866. "datetime(substr(peticion, 7, 4) || '-' || substr(peticion, 4, 2) || '-' || substr(peticion, 1, 2) || ' ' || substr(peticion, 12)) ASC";
  867. List<Map<String, dynamic>> result = await dbClient!.query(
  868. 'Pedido',
  869. where: 'sincronizado IS NULL',
  870. orderBy: orderBy,
  871. );
  872. return result.map((map) => Pedido.fromJson(map)).toList();
  873. }
  874. Future<void> sincronizarCategorias(List<CategoriaProducto> categoriasApi,
  875. {bool forzar = false}) async {
  876. var db = await RepoService().db;
  877. var categoriasLocalesQuery = await db!.query('CategoriaProducto');
  878. List<CategoriaProducto> categoriasLocales = categoriasLocalesQuery
  879. .map((e) => CategoriaProducto.fromJson(e))
  880. .toList();
  881. for (var categoriaApi in categoriasApi) {
  882. var categoriaLocal = categoriasLocales.firstWhere(
  883. (categoria) => categoria.id == categoriaApi.id,
  884. orElse: () => CategoriaProducto(),
  885. );
  886. if (forzar ||
  887. categoriaLocal.id != 0 &&
  888. categoriaApi.modificado != null &&
  889. (categoriaLocal.modificado == null ||
  890. categoriaApi.modificado!
  891. .isAfter(categoriaLocal.modificado!))) {
  892. await RepoService().guardar(categoriaApi);
  893. } else if (categoriaLocal.id == 0) {
  894. await RepoService().guardar(categoriaApi);
  895. }
  896. }
  897. }
  898. Future<void> sincronizarProductos(List<Producto> productosApi,
  899. {bool forzar = false}) async {
  900. var db = await RepoService().db;
  901. // // Print del JSON recibido
  902. // print(
  903. // "Productos API recibidos: ${productosApi.map((e) => e.toJson()).toList()}");
  904. var productosLocalesQuery = await db!.query('Producto');
  905. List<Producto> productosLocales =
  906. productosLocalesQuery.map((e) => Producto.fromJson(e)).toList();
  907. for (var productoApi in productosApi) {
  908. // Validar que el ID del producto no sea nulo
  909. if (productoApi.id == null) {
  910. print("Producto con ID nulo, se omite: ${productoApi.nombre}");
  911. continue; // Ignorar productos sin ID
  912. }
  913. // Buscar el producto localmente
  914. var productoLocal = productosLocales.firstWhere(
  915. (producto) => producto.id == productoApi.id,
  916. orElse: () =>
  917. Producto(), // Si no existe el producto, devolver uno nuevo con id 0
  918. );
  919. if (productoLocal.id == 0) {
  920. print("Insertando nuevo producto: ${productoApi.nombre}");
  921. await RepoService().guardar(productoApi);
  922. } else if (forzar ||
  923. productoApi.modificado != null &&
  924. (productoLocal.modificado == null ||
  925. productoApi.modificado!.isAfter(productoLocal.modificado!))) {
  926. print("Actualizando producto: ${productoApi.nombre}");
  927. await RepoService().guardar(productoApi);
  928. } else {
  929. // Producto sin cambios
  930. // print(
  931. // "Producto sin cambios o datos insuficientes: ${productoApi.nombre}");
  932. }
  933. }
  934. }
  935. Future<void> sincronizarProductoTopping(
  936. List<ProductoTopping> toppingsApi) async {
  937. var db = await RepoService().db;
  938. await db!.delete('ProductoTopping');
  939. for (var toppingApi in toppingsApi) {
  940. await RepoService().guardar(toppingApi);
  941. }
  942. print("Todos los registros de ProductoTopping han sido sincronizados.");
  943. }
  944. Future<void> sincronizarSucursales(List<Sucursal> sucursalesApi,
  945. {bool forzar = false}) async {
  946. var db = await RepoService().db;
  947. int? idSucursalSeleccionada = await obtenerIdSucursalSeleccionada();
  948. var sucursalesLocalesQuery = await db!.query('Sucursal');
  949. List<Sucursal> sucursalesLocales =
  950. sucursalesLocalesQuery.map((e) => Sucursal.fromJson(e)).toList();
  951. for (var sucursalApi in sucursalesApi) {
  952. var sucursalLocal = sucursalesLocales.firstWhere(
  953. (sucursal) => sucursal.id == sucursalApi.id,
  954. orElse: () => Sucursal(),
  955. );
  956. sucursalApi.seleccionado =
  957. (sucursalApi.id == idSucursalSeleccionada) ? 1 : 0;
  958. if (forzar ||
  959. sucursalLocal.id != 0 &&
  960. sucursalApi.modificado != null &&
  961. (sucursalLocal.modificado == null ||
  962. sucursalApi.modificado!.isAfter(sucursalLocal.modificado!))) {
  963. await RepoService().guardar(sucursalApi);
  964. } else if (sucursalLocal.id == 0) {
  965. await RepoService().guardar(sucursalApi);
  966. }
  967. }
  968. }
  969. Future<void> sincronizarPermisos(List<Permiso> permisosApi,
  970. {bool forzar = false}) async {
  971. var db = await RepoService().db;
  972. var permisosLocalesQuery = await db!.query('Permiso');
  973. List<Permiso> permisosLocales =
  974. permisosLocalesQuery.map((e) => Permiso.fromJson(e)).toList();
  975. for (var permisoApi in permisosApi) {
  976. var permisoLocal = permisosLocales.firstWhere(
  977. (permiso) => permiso.id == permisoApi.id,
  978. orElse: () => Permiso(),
  979. );
  980. if (forzar ||
  981. permisoLocal.id != null &&
  982. permisoApi.modificado != null &&
  983. (permisoLocal.modificado == null ||
  984. permisoApi.modificado!.isAfter(permisoLocal.modificado!))) {
  985. print('Actualizando permiso con ID: ${permisoApi.id}');
  986. await RepoService().guardar(permisoApi);
  987. } else if (permisoLocal.id == null) {
  988. print('Insertando nuevo permiso con ID: ${permisoApi.id}');
  989. await RepoService().guardar(permisoApi);
  990. } else {
  991. //print('Permiso sin cambios: ${permisoApi.id}');
  992. }
  993. }
  994. }
  995. Future<void> sincronizarUsuarios(List<Usuario> usuariosApi,
  996. {bool forzar = false}) async {
  997. var db = await RepoService().db;
  998. var usuariosLocalesQuery = await db!.query('Usuario');
  999. List<Usuario> usuariosLocales =
  1000. usuariosLocalesQuery.map((e) => Usuario.fromJson(e)).toList();
  1001. for (var usuarioApi in usuariosApi) {
  1002. var usuarioLocal = usuariosLocales.firstWhere(
  1003. (usuario) => usuario.id == usuarioApi.id,
  1004. orElse: () => Usuario(),
  1005. );
  1006. // Comprobar si realmente se necesita actualizar el usuario basado en la fecha de modificado
  1007. if (forzar ||
  1008. usuarioLocal.id != 0 &&
  1009. usuarioApi.modificado != null &&
  1010. (usuarioLocal.modificado == null ||
  1011. usuarioApi.modificado!.isAfter(usuarioLocal.modificado!))) {
  1012. print('Actualizando usuario con ID: ${usuarioApi.id}');
  1013. await RepoService().guardar(usuarioApi);
  1014. // Comparar permisos antes de actualizarlos
  1015. await _actualizarPermisosUsuario(
  1016. db, usuarioApi.id!, usuarioApi.permisos!);
  1017. } else if (usuarioLocal.id == 0) {
  1018. print('Insertando nuevo usuario con ID: ${usuarioApi.id}');
  1019. await RepoService().guardar(usuarioApi);
  1020. // Insertar los permisos correspondientes
  1021. await _guardarPermisosUsuario(db, usuarioApi.id!, usuarioApi.permisos!);
  1022. } else {
  1023. //print('Usuario sin cambios: ${usuarioApi.id}');
  1024. }
  1025. }
  1026. }
  1027. Future<void> _actualizarPermisosUsuario(
  1028. Database db, int idUsuario, List<String> permisosApi) async {
  1029. // Obtener los permisos actuales del usuario
  1030. var permisosLocalesQuery = await db.query(
  1031. 'UsuarioPermiso',
  1032. where: 'idUsuario = ?',
  1033. whereArgs: [idUsuario],
  1034. );
  1035. List<String> permisosLocales = permisosLocalesQuery
  1036. .map((permiso) => permiso['idPermiso'] as String)
  1037. .toList();
  1038. // Comparar los permisos del API con los locales
  1039. bool sonIguales = _listasIguales(permisosLocales, permisosApi);
  1040. if (!sonIguales) {
  1041. // Si los permisos no son iguales, actualizarlos
  1042. print('Actualizando permisos del usuario con ID: $idUsuario');
  1043. await _guardarPermisosUsuario(db, idUsuario, permisosApi);
  1044. } else {
  1045. print('Permisos del usuario con ID: $idUsuario no han cambiado.');
  1046. }
  1047. }
  1048. Future<void> _guardarPermisosUsuario(
  1049. Database db, int idUsuario, List<String> permisos) async {
  1050. // Eliminar los permisos actuales solo si hay cambios
  1051. await db.delete('UsuarioPermiso',
  1052. where: 'idUsuario = ?', whereArgs: [idUsuario]);
  1053. // Insertar los nuevos permisos
  1054. for (var idPermiso in permisos) {
  1055. await db.insert('UsuarioPermiso', {
  1056. 'idUsuario': idUsuario,
  1057. 'idPermiso': idPermiso,
  1058. });
  1059. }
  1060. }
  1061. bool _listasIguales(List<String> lista1, List<String> lista2) {
  1062. if (lista1.length != lista2.length) return false;
  1063. lista1.sort();
  1064. lista2.sort();
  1065. for (int i = 0; i < lista1.length; i++) {
  1066. if (lista1[i] != lista2[i]) return false;
  1067. }
  1068. return true;
  1069. }
  1070. Future<String?> obtenerClaveSucursalSeleccionada() async {
  1071. var db = await this.db;
  1072. List<Map<String, dynamic>> queryResult = await db!.query(
  1073. 'Sucursal',
  1074. where: 'seleccionado = ? AND eliminado IS NULL',
  1075. whereArgs: [1],
  1076. limit: 1,
  1077. );
  1078. if (queryResult.isNotEmpty) {
  1079. Sucursal sucursalSeleccionada = Sucursal.fromJson(queryResult.first);
  1080. return sucursalSeleccionada.clave;
  1081. }
  1082. return null;
  1083. }
  1084. Future<int?> obtenerIdSucursalSeleccionada() async {
  1085. var db = await this.db;
  1086. List<Map<String, dynamic>> queryResult = await db!.query(
  1087. 'Sucursal',
  1088. where: 'seleccionado = ? AND eliminado IS NULL',
  1089. whereArgs: [1],
  1090. limit: 1,
  1091. );
  1092. if (queryResult.isNotEmpty) {
  1093. return Sucursal.fromJson(queryResult.first).id;
  1094. }
  1095. return null;
  1096. }
  1097. Future<void> forzarSincronizacion() async {
  1098. String? claveSucursal = await obtenerClaveSucursalSeleccionada();
  1099. try {
  1100. // Sincronizar categorías
  1101. await sincronizarCategorias(
  1102. await fetchCategoriasApi(claveSucursal: claveSucursal),
  1103. forzar: true);
  1104. // Sincronizar productos
  1105. await sincronizarProductos(
  1106. await fetchProductosApi(claveSucursal: claveSucursal),
  1107. forzar: true);
  1108. // Sincronizar toppings de producto
  1109. await sincronizarProductoTopping(
  1110. await fetchProductoToppingApi(claveSucursal: claveSucursal));
  1111. // Sincronizar sucursales
  1112. await sincronizarSucursales(await fetchSucursalesApi(), forzar: true);
  1113. // Sincronizar permisos
  1114. await sincronizarPermisos(await fetchPermisosApi(), forzar: true);
  1115. // Sincronizar usuarios
  1116. await sincronizarUsuarios(await fetchUsuariosApi(), forzar: true);
  1117. print('Sincronización forzosa completada.');
  1118. } catch (e) {
  1119. print('Error en la sincronización forzosa: $e');
  1120. }
  1121. }
  1122. Future<List<CategoriaProducto>> fetchCategoriasApi(
  1123. {String? claveSucursal}) async {
  1124. Map<String, String> parametros = {
  1125. "claveSucursal": claveSucursal!,
  1126. "limite": "-1"
  1127. };
  1128. final response = ApiResponse(
  1129. await BaseService().get('/pos/categoria', queryParameters: parametros));
  1130. return response.isOk && response.resultados != null
  1131. ? response.resultados!
  1132. .map((json) => CategoriaProducto.fromApi(json))
  1133. .toList()
  1134. : [];
  1135. }
  1136. Future<List<Producto>> fetchProductosApi({String? claveSucursal}) async {
  1137. Map<String, String> parametros = {
  1138. "limite": "-1",
  1139. "claveSucursal": claveSucursal!,
  1140. "expand": "media"
  1141. };
  1142. final response = ApiResponse(
  1143. await BaseService().get('/pos/producto', queryParameters: parametros));
  1144. if (response.isOk && response.resultados != null) {
  1145. List<Producto> productosApi =
  1146. response.resultados!.map((json) => Producto.fromApi(json)).toList();
  1147. // Descargar y almacenar cada imagen de producto
  1148. for (var productoApi in productosApi) {
  1149. if (productoApi.media != null && productoApi.media!.isNotEmpty) {
  1150. for (var media in productoApi.media!) {
  1151. // Descargar y guardar la imagen localmente
  1152. String? localImagePath = await downloadAndStoreImage(
  1153. media.ruta!, productoApi.id!, media.nombre!);
  1154. if (localImagePath != null) {
  1155. productoApi.imagen = localImagePath;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. return productosApi;
  1161. }
  1162. return [];
  1163. }
  1164. Future<List<ProductoTopping>> fetchProductoToppingApi(
  1165. {String? claveSucursal}) async {
  1166. Map<String, String> parametros = {
  1167. "limite": "-1",
  1168. "claveSucursal": claveSucursal!,
  1169. };
  1170. final response = ApiResponse(await BaseService()
  1171. .get('/pos/producto-topping', queryParameters: parametros));
  1172. return response.isOk && response.resultados != null
  1173. ? response.resultados!
  1174. .map((json) => ProductoTopping.fromApi(json))
  1175. .toList()
  1176. : [];
  1177. }
  1178. Future<List<Sucursal>> fetchSucursalesApi() async {
  1179. Map<String, String> parametros = {
  1180. "limite": "-1",
  1181. };
  1182. final response = ApiResponse(
  1183. await BaseService().get('/pos/sucursal', queryParameters: parametros));
  1184. return response.isOk && response.resultados != null
  1185. ? response.resultados!.map((json) => Sucursal.fromApi(json)).toList()
  1186. : [];
  1187. }
  1188. Future<List<Permiso>> fetchPermisosApi() async {
  1189. Map<String, String> parametros = {
  1190. "limite": "-1",
  1191. };
  1192. final response = ApiResponse(
  1193. await BaseService().get('/pos/permiso', queryParameters: parametros));
  1194. return response.isOk && response.resultados != null
  1195. ? response.resultados!.map((json) => Permiso.fromJson(json)).toList()
  1196. : [];
  1197. }
  1198. Future<List<Usuario>> fetchUsuariosApi() async {
  1199. Map<String, String> parametros = {
  1200. "limite": "-1",
  1201. "expand": "permisos",
  1202. };
  1203. final response = ApiResponse(
  1204. await BaseService().get('/pos/usuario', queryParameters: parametros));
  1205. return response.isOk && response.resultados != null
  1206. ? response.resultados!.map((json) => Usuario.fromApi(json)).toList()
  1207. : [];
  1208. }
  1209. }