pedido_view_model.dart 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import 'package:flutter/material.dart';
  2. import 'package:intl/intl.dart';
  3. import 'package:sqflite/sqflite.dart';
  4. import '../data/api_response.dart';
  5. import '../models/models.dart';
  6. import '../services/services.dart';
  7. class PedidoViewModel extends ChangeNotifier {
  8. String _busqueda = "";
  9. String get busqueda => _busqueda;
  10. List<Pedido> _pedidos = [];
  11. Pedido? _selectedPedido;
  12. bool _isLoading = false;
  13. int _currentPage = 1;
  14. int _totalPedidos = 0;
  15. int _limit = 10;
  16. int get currentPage => _currentPage;
  17. int get totalPedidos => _totalPedidos;
  18. int get totalPages => (_totalPedidos / _limit).ceil();
  19. List<Pedido> get pedidos => _pedidos;
  20. Pedido? get selectedPedido => _selectedPedido;
  21. bool get isLoading => _isLoading;
  22. void setIsLoading(bool loading) {
  23. _isLoading = loading;
  24. notifyListeners();
  25. }
  26. Future<bool> guardarPedidoLocal({required Pedido pedido}) async {
  27. RepoService<Pedido> repoPedido = RepoService<Pedido>();
  28. int nextFolio = await repoPedido.obtenerProximoFolio();
  29. pedido.folio = nextFolio;
  30. int idPedido = await repoPedido.guardarLocal(pedido);
  31. if (idPedido > 0) {
  32. pedido.id = idPedido;
  33. RepoService<PedidoProducto> repoPedidoProducto =
  34. RepoService<PedidoProducto>();
  35. RepoService<PedidoProductoTopping> repoPedidoProductoTopping =
  36. RepoService<PedidoProductoTopping>();
  37. for (var producto in pedido.productos) {
  38. PedidoProducto pedidoProducto = PedidoProducto(
  39. idPedido: idPedido,
  40. idProducto: producto.idProducto,
  41. cantidad: producto.cantidad,
  42. costoUnitario: producto.costoUnitario,
  43. comentario: producto.comentario,
  44. );
  45. int idPedidoProducto =
  46. await repoPedidoProducto.guardarLocal(pedidoProducto);
  47. for (var topping in producto.toppings) {
  48. PedidoProductoTopping pedidoProductoTopping = PedidoProductoTopping(
  49. idPedidoProducto: idPedidoProducto,
  50. idTopping: topping.idTopping,
  51. );
  52. await repoPedidoProductoTopping.guardarLocal(pedidoProductoTopping);
  53. // Recuperar detalles completos del topping
  54. Producto? toppingInfo = await RepoService<Producto>()
  55. .obtenerProductoPorId(topping.idTopping!);
  56. if (toppingInfo != null) {
  57. topping.topping = toppingInfo;
  58. }
  59. }
  60. }
  61. notifyListeners();
  62. return true;
  63. } else {
  64. return false;
  65. }
  66. }
  67. Future<void> fetchLocalPedidos({int page = 1}) async {
  68. _isLoading = true;
  69. _currentPage = page;
  70. notifyListeners();
  71. RepoService<Pedido> repoPedido = RepoService<Pedido>();
  72. _totalPedidos = await repoPedido.contarPedidos();
  73. int offset = (_limit * (page - 1));
  74. List<Pedido> paginatedPedidos =
  75. await repoPedido.obtenerPedidosPaginados(_limit, offset);
  76. _pedidos = paginatedPedidos;
  77. _isLoading = false;
  78. notifyListeners();
  79. }
  80. void nextPage() {
  81. if (_currentPage < totalPages) {
  82. fetchLocalPedidosForScreen(page: _currentPage + 1);
  83. }
  84. }
  85. void previousPage() {
  86. if (_currentPage > 1) {
  87. fetchLocalPedidosForScreen(page: _currentPage - 1);
  88. }
  89. }
  90. Future<void> fetchLocalPedidosForScreen({int page = 1}) async {
  91. setIsLoading(true);
  92. RepoService<Pedido> repoPedido = RepoService<Pedido>();
  93. _currentPage = page;
  94. var db = await RepoService().db;
  95. int? count = Sqflite.firstIntValue(
  96. await db!.rawQuery('SELECT COUNT(*) FROM Pedido'));
  97. _totalPedidos = count ?? 0;
  98. int offset = (_limit * (page - 1));
  99. List<Pedido> localPedidos =
  100. await repoPedido.obtenerPedidosPaginados(_limit, offset);
  101. _pedidos = localPedidos;
  102. setIsLoading(false);
  103. notifyListeners();
  104. }
  105. Future<List<Pedido>> fetchAllLocalPedidos() async {
  106. setIsLoading(true);
  107. RepoService<Pedido> repoPedido = RepoService<Pedido>();
  108. List<Pedido> allPedidos = await repoPedido.obtenerTodos();
  109. setIsLoading(false);
  110. return allPedidos;
  111. }
  112. Future<List<Pedido>> fetchPedidosPorFechaSinLimit(
  113. DateTime startDate, DateTime endDate) async {
  114. setIsLoading(true);
  115. RepoService<Pedido> repoPedido = RepoService<Pedido>();
  116. List<Pedido> pedidos = await repoPedido.buscarPorFecha(startDate, endDate);
  117. setIsLoading(false);
  118. return pedidos;
  119. }
  120. Future<Pedido?> fetchPedidoConProductos(int idPedido) async {
  121. RepoService<Pedido> repoPedido = RepoService<Pedido>();
  122. Pedido? pedido = await repoPedido.obtenerPorId(idPedido);
  123. if (pedido != null) {
  124. RepoService<PedidoProducto> repoProducto = RepoService<PedidoProducto>();
  125. RepoService<Producto> repoProductoInfo = RepoService<Producto>();
  126. List<PedidoProducto> productos =
  127. await repoProducto.obtenerPorIdPedido(idPedido);
  128. for (var producto in productos) {
  129. Producto? prodInfo =
  130. await repoProductoInfo.obtenerProductoPorId(producto.idProducto!);
  131. if (prodInfo != null) {
  132. producto.producto = prodInfo;
  133. }
  134. RepoService<PedidoProductoTopping> repoTopping =
  135. RepoService<PedidoProductoTopping>();
  136. List<PedidoProductoTopping> toppings =
  137. await repoTopping.obtenerToppingsPorPedidoProducto(producto.id!);
  138. for (var topping in toppings) {
  139. Producto? toppingInfo =
  140. await repoProductoInfo.obtenerProductoPorId(topping.idTopping!);
  141. if (toppingInfo != null) {
  142. topping.topping = toppingInfo;
  143. }
  144. }
  145. producto.toppings = toppings;
  146. }
  147. pedido.productos = productos;
  148. }
  149. return pedido;
  150. }
  151. Future<void> buscarPedidosPorFolio(String folio) async {
  152. setIsLoading(true);
  153. RepoService<Pedido> repoPedido = RepoService<Pedido>();
  154. List<Pedido> localPedidos = await repoPedido.buscarPorFolio(folio);
  155. _pedidos = localPedidos;
  156. setIsLoading(false);
  157. notifyListeners();
  158. }
  159. Future<void> buscarPedidosPorFecha(
  160. DateTime startDate, DateTime endDate) async {
  161. setIsLoading(true);
  162. RepoService<Pedido> repoPedido = RepoService<Pedido>();
  163. List<Pedido> localPedidos =
  164. await repoPedido.buscarPorFecha(startDate, endDate);
  165. _pedidos = localPedidos;
  166. setIsLoading(false);
  167. notifyListeners();
  168. }
  169. Future<List<Pedido>> buscarPorFecha(
  170. DateTime startDate, DateTime endDate) async {
  171. setIsLoading(true);
  172. RepoService<Pedido> repoPedido = RepoService<Pedido>();
  173. List<Pedido> pedidos = await repoPedido.buscarPorFecha(startDate, endDate);
  174. setIsLoading(false);
  175. notifyListeners();
  176. return pedidos;
  177. }
  178. Future<void> cancelarPedido(int idPedido) async {
  179. var db = await RepoService().db;
  180. await db?.update('Pedido', {'estatus': 'CANCELADO'},
  181. where: 'id = ?', whereArgs: [idPedido]);
  182. fetchLocalPedidosForScreen();
  183. }
  184. Future<bool> sincronizarPedidos() async {
  185. List<Pedido> pedidosNoSincronizados =
  186. await fetchAllLocalPedidosOrdenadosPorFecha();
  187. if (pedidosNoSincronizados.isNotEmpty) {
  188. Pedido pedidoNoSincronizado = pedidosNoSincronizados.first;
  189. if (pedidoNoSincronizado.productos.isEmpty) {
  190. pedidoNoSincronizado =
  191. await fetchPedidoConProductos(pedidoNoSincronizado.id) ??
  192. pedidoNoSincronizado;
  193. }
  194. Map<String, dynamic> pedidoJson =
  195. await prepararPedidoParaApi(pedidoNoSincronizado);
  196. print('JSON enviado: $pedidoJson');
  197. var response = ApiResponse(await BaseService()
  198. .post('/pos/pedido/sincronizar', body: pedidoJson));
  199. if (response.isOk && response.detalle != null) {
  200. int idWeb = response.detalle!['id'];
  201. String sincronizado = response.detalle!['sincronizado'];
  202. await actualizarPedidoSincronizado(
  203. pedidoNoSincronizado.id!, idWeb, sincronizado);
  204. await fetchLocalPedidosForScreen();
  205. return true;
  206. } else {
  207. print('Error en la sincronización del pedido: ${response.mensaje}');
  208. return true;
  209. }
  210. } else {
  211. print('No se encontraron pedidos no sincronizados.');
  212. return false;
  213. }
  214. }
  215. Future<void> actualizarPedidoSincronizado(
  216. int idPedido, int idWeb, String sincronizado) async {
  217. var db = await RepoService().db;
  218. await db!.update(
  219. 'Pedido',
  220. {
  221. 'idWeb': idWeb,
  222. 'sincronizado': sincronizado,
  223. },
  224. where: 'id = ?',
  225. whereArgs: [idPedido],
  226. );
  227. }
  228. Future<List<Pedido>> fetchAllLocalPedidosOrdenadosPorFecha() async {
  229. setIsLoading(true);
  230. RepoService<Pedido> repoPedido = RepoService<Pedido>();
  231. List<Pedido> allPedidos =
  232. await repoPedido.obtenerPedidosOrdenadosPorFecha();
  233. setIsLoading(false);
  234. return allPedidos;
  235. }
  236. }
  237. Future<Map<String, dynamic>> prepararPedidoParaApi(Pedido pedido) async {
  238. String? claveSucursal = await obtenerClaveSucursal();
  239. Map<String, dynamic> apiMap = pedido.toApi();
  240. apiMap['claveSucursal'] = claveSucursal;
  241. return apiMap;
  242. }
  243. Future<String?> obtenerClaveSucursal() async {
  244. RepoService<Variable> repoVariable = RepoService<Variable>();
  245. Variable? sucursalVariable = await repoVariable.obtenerPorNombre('Sucursal');
  246. return sucursalVariable?.clave;
  247. }