Просмотр исходного кода

Sincronizacion productos y categorias

OscarGil03 месяцев назад: 6
Родитель
Сommit
2d0a024042

+ 12 - 11
lib/services/repo_service.dart

@@ -6,7 +6,7 @@ import 'package:sqflite/sqflite.dart';
 import '../models/models.dart';
 
 class RepoService<T> {
-  static int dbVersion = 16;
+  static int dbVersion = 14;
   static String dbName = 'conalepPos7.db';
   static const String id = Basico.identificadorWeb;
   static const String idLocal = Basico.identificadorLocal;
@@ -262,7 +262,7 @@ class RepoService<T> {
         // ''');
         //   break;
 
-        case 14:
+        case 12:
           await db.execute('''
           update Pedido set sincronizado = null, peticion = strftime('%Y-%m-%dT%H:%M:%S',
                 datetime(substr(peticion, 7, 4) || '-' ||
@@ -277,7 +277,7 @@ class RepoService<T> {
         ''');
           break;
 
-        case 15:
+        case 13:
           await db.execute('DROP TABLE IF EXISTS Producto');
 
           //Se tiene que crear nuevamente para que precio sea Double
@@ -569,17 +569,18 @@ class RepoService<T> {
       DateTime startDate, DateTime endDate) async {
     var dbClient = await db;
 
-    String startDateString =
-        DateFormat('yyyy-MM-dd 00:00:00').format(startDate);
-    String endDateString = DateFormat('yyyy-MM-dd 23:59:59').format(endDate);
+    String startDateString = startDate.toIso8601String();
+    String endDateString = endDate.toIso8601String();
+
+    print(
+        'Ejecutando consulta: SELECT * FROM Pedido WHERE peticion BETWEEN $startDateString AND $endDateString');
 
     List<Map<String, dynamic>> maps = await dbClient!.rawQuery('''
     SELECT * FROM Pedido 
-    WHERE 
-      (datetime(substr(peticion, 7, 4) || '-' || substr(peticion, 4, 2) || '-' || substr(peticion, 1, 2) || ' ' || substr(peticion, 12)) BETWEEN ? AND ?)
-    OR 
-      (datetime(substr(peticion, 7, 4) || '-' || substr(peticion, 1, 2) || '-' || substr(peticion, 4, 2) || ' ' || substr(peticion, 12)) BETWEEN ? AND ?)
-  ''', [startDateString, endDateString, startDateString, endDateString]);
+    WHERE peticion BETWEEN ? AND ?
+  ''', [startDateString, endDateString]);
+
+    print('Resultado de la consulta: ${maps.length} pedidos encontrados.');
 
     return maps.map((map) => Pedido.fromJson(map)).toList();
   }

+ 8 - 0
lib/viewmodels/pedido_view_model.dart

@@ -209,7 +209,15 @@ class PedidoViewModel extends ChangeNotifier {
       DateTime startDate, DateTime endDate) async {
     setIsLoading(true);
     RepoService<Pedido> repoPedido = RepoService<Pedido>();
+
+    print('Consulta SQL de pedidos desde: $startDate hasta: $endDate');
+
     List<Pedido> pedidos = await repoPedido.buscarPorFecha(startDate, endDate);
+
+    print('Pedidos obtenidos desde la base de datos: ${pedidos.length}');
+    pedidos.forEach((pedido) => print(
+        'Pedido Folio: ${pedido.folio}, Estatus: ${pedido.estatus}, Total: ${pedido.totalPedido}'));
+
     setIsLoading(false);
     notifyListeners();
     return pedidos;

+ 23 - 18
lib/viewmodels/producto_view_model.dart

@@ -1,8 +1,11 @@
 import 'package:flutter/material.dart';
 import 'package:sqflite/sqflite.dart';
+
 import '../data/api_response.dart';
+import '../services/base_service.dart';
 import '../models/models.dart';
 import '../services/services.dart';
+import '../services/repo_service.dart';
 
 class ProductoViewModel<T> extends ChangeNotifier {
   String _busqueda = "";
@@ -82,7 +85,6 @@ class ProductoViewModel<T> extends ChangeNotifier {
 
   Future<void> fetchLocalByName({required String nombre}) async {
     var db = await RepoService().db;
-    // Realiza la búsqueda sin filtrar por categoría
     var query = await db!.query(
       'Producto',
       where: 'nombre LIKE ?',
@@ -176,23 +178,6 @@ class ProductoViewModel<T> extends ChangeNotifier {
     return null;
   }
 
-  void setIsLoading(bool loading) {
-    _isLoading = loading;
-    notifyListeners();
-  }
-
-  void nextPage() {
-    if (_currentPage < totalPages) {
-      fetchLocalAll(page: _currentPage + 1);
-    }
-  }
-
-  void previousPage() {
-    if (_currentPage > 1) {
-      fetchLocalAll(page: _currentPage - 1);
-    }
-  }
-
   Future<bool> sincronizarCategorias() async {
     try {
       final response = ApiResponse(await BaseService().get('/pos/categoria'));
@@ -239,15 +224,18 @@ class ProductoViewModel<T> extends ChangeNotifier {
   }
 
   Future<void> sincronizarProductosYCategorias() async {
+    print('Sincronizando productos');
     setIsLoading(true);
     try {
       bool categoriasSincronizadas = await sincronizarCategorias();
+      print('Categorias sincronizadas: $categoriasSincronizadas');
 
       if (categoriasSincronizadas) {
         bool productosSincronizados = await sincronizarProductos();
         if (productosSincronizados) {
           await fetchLocalAll();
         }
+        print('Productos sincronizados: $productosSincronizados');
       }
       notifyListeners();
     } catch (e, stackTrace) {
@@ -258,4 +246,21 @@ class ProductoViewModel<T> extends ChangeNotifier {
       setIsLoading(false);
     }
   }
+
+  void setIsLoading(bool loading) {
+    _isLoading = loading;
+    notifyListeners();
+  }
+
+  void nextPage() {
+    if (_currentPage < totalPages) {
+      fetchLocalAll(page: _currentPage + 1);
+    }
+  }
+
+  void previousPage() {
+    if (_currentPage > 1) {
+      fetchLocalAll(page: _currentPage - 1);
+    }
+  }
 }

+ 13 - 11
lib/views/categoria_producto/categoria_producto_screen.dart

@@ -16,6 +16,7 @@ class CategoriaProductoScreen extends StatefulWidget {
 class _CategoriaProductoScreenState extends State<CategoriaProductoScreen> {
   final _busqueda = TextEditingController(text: '');
   ScrollController horizontalScrollController = ScrollController();
+  int _versionTapCount = 0;
 
   @override
   void initState() {
@@ -184,18 +185,19 @@ class _CategoriaProductoScreenState extends State<CategoriaProductoScreen> {
       appBar: AppBar(
         title: GestureDetector(
           onTap: () async {
-            final productoViewModel =
-                Provider.of<ProductoViewModel>(context, listen: false);
+            _versionTapCount++;
+            if (_versionTapCount == 5) {
+              final productoViewModel =
+                  Provider.of<ProductoViewModel>(context, listen: false);
 
-            try {
-              // Iniciar la sincronización
-              await productoViewModel.sincronizarProductosYCategorias();
-              // Mostrar resultado de éxito en el modal
-              _mostrarResultado(
-                  context, 'La sincronización se completó exitosamente.', true);
-            } catch (e) {
-              // Mostrar el error detallado en el modal
-              _mostrarResultado(context, e.toString(), false);
+              try {
+                await productoViewModel.sincronizarProductosYCategorias();
+                _mostrarResultado(context,
+                    'La sincronización se completó exitosamente.', true);
+              } catch (e) {
+                _mostrarResultado(context, e.toString(), false);
+              }
+              _versionTapCount = 0;
             }
           },
           child: Text(