repo_service.dart 40 KB

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