repo_service.dart 49 KB

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