repo_service.dart 41 KB

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