ソースを参照

Avances pedido mesa

ElPoteito 6 ヶ月 前
コミット
f64663efc3

+ 4 - 2
lib/models/mesa_model.dart

@@ -12,6 +12,8 @@ class Mesa extends Basico {
     this.nombre,
     this.clave,
     this.activa,
+    super.creado,
+    super.modificado,
     super.eliminado
   });
 
@@ -21,7 +23,7 @@ class Mesa extends Basico {
       'id': id,
       'nombre': nombre,
       'clave': clave,
-      'activa': activa,
+      'activa': activa == true ? 1 : 0,
     }..addAll(super.toJson());
   }
 
@@ -29,7 +31,7 @@ class Mesa extends Basico {
     super.parseJson(json);
     nombre = Basico.parseString(json['nombre']);
     clave = Basico.parseString(json['clave']);
-    activa = Basico.parseBolean(json['activa']);
+    activa = Basico.parseInt(json['activa']) == 1;
   }
 
   Future<void> guardar() async {

+ 1 - 0
lib/models/pedido_model.dart

@@ -75,6 +75,7 @@ class Pedido extends Basico {
       'cantEfectivo': cantEfectivo,
       'cantTarjeta': cantTarjeta,
       'cantTransferencia': cantTransferencia,
+      'sincronizado': sincronizado,
     }..addAll(super.toJson());
   }
 

+ 39 - 1
lib/services/repo_service.dart

@@ -1,4 +1,5 @@
 import 'dart:convert';
+import 'package:conalep_pos/models/mesa_model.dart';
 import 'package:intl/intl.dart';
 import 'package:path/path.dart';
 import 'package:path_provider/path_provider.dart';
@@ -6,7 +7,7 @@ import 'package:sqflite/sqflite.dart';
 import '../models/models.dart';
 
 class RepoService<T> {
-  static int dbVersion = 14;
+  static int dbVersion = 15;
   static String dbName = 'conalepPos7.db';
   static const String id = Basico.identificadorWeb;
   static const String idLocal = Basico.identificadorLocal;
@@ -31,6 +32,7 @@ class RepoService<T> {
   Future<Database> databaseInit() async {
     String dir = (await getApplicationDocumentsDirectory()).path;
     String path = join(dir, dbName);
+    print(path);
     return await openDatabase(
       path,
       version: dbVersion,
@@ -78,6 +80,9 @@ class RepoService<T> {
       if (modelo.runtimeType.toString() == 'Pedido') {
         await db.execute(
             'ALTER TABLE Pedido ADD COLUMN IF NOT EXISTS descuento INTEGER DEFAULT 0');
+
+        await db.execute(
+            'ALTER TABLE Pedido ADD COLUMN IF NOT EXISTS sincronizado TEXT;');
       }
 
       await db.execute('''
@@ -117,6 +122,19 @@ class RepoService<T> {
         eliminado TEXT
       )
     ''');
+
+    await db.execute('''
+          CREATE TABLE Mesa (
+            id INTEGER PRIMARY KEY AUTOINCREMENT,
+            idLocal INTEGER,
+            nombre TEXT,
+            clave TEXT,
+            activa BOOLEAN,
+            creado TEXT,
+            modificado TEXT,
+            eliminado TEXT
+          )
+        ''');
   }
 
   /// Actualiza la version de la base de datos
@@ -310,6 +328,24 @@ class RepoService<T> {
           ''');
 
           break;
+
+        case 14:
+          await db.execute('DROP TABLE IF EXISTS Mesa');
+          //Se tiene que crear nuevamente para que precio sea Double
+          await db.execute('''
+          CREATE TABLE Mesa (
+            id INTEGER PRIMARY KEY AUTOINCREMENT,
+            idLocal INTEGER,
+            nombre TEXT,
+            clave TEXT,
+            activa BOOLEAN,
+            creado TEXT,
+            modificado TEXT,
+            eliminado TEXT
+          )
+        ''');
+
+          break;
       }
       oldVersion++;
     }
@@ -434,6 +470,8 @@ class RepoService<T> {
       return item.toJson();
     } else if (item is Variable) {
       return item.toJson();
+    } else if (item is Mesa) {
+      return item.toJson();
     }
     throw UnsupportedError(
         'Type not supported for serialization: ${item.runtimeType}');

+ 7 - 7
lib/views/pedido_mesa/pedido_mesa_detalle.dart

@@ -7,7 +7,8 @@ import '../pedido/pedido_ticket.dart';
 class PedidoMesaDetalleScreen extends StatelessWidget {
   final Pedido pedido;
 
-  const PedidoMesaDetalleScreen({Key? key, required this.pedido}) : super(key: key);
+  const PedidoMesaDetalleScreen({Key? key, required this.pedido})
+      : super(key: key);
 
   String formatCurrency(double amount) {
     final format = NumberFormat("#,##0.00", "es_MX");
@@ -18,13 +19,12 @@ class PedidoMesaDetalleScreen extends StatelessWidget {
   Widget build(BuildContext context) {
     double totalSinDescuento =
         pedido.productos.fold(0, (previousValue, element) {
-      double productTotal = element.cantidad! *
-          (double.tryParse(element.producto?.precio ?? '') ?? 0.0);
+      double productTotal =
+          element.cantidad! * (element.producto?.precio ?? 0.0);
 
       double toppingsTotal = element.toppings.fold(0, (toppingTotal, topping) {
         return toppingTotal +
-            (double.tryParse(topping.topping?.precio ?? '') ?? 0.0) *
-                element.cantidad!;
+            (topping.topping?.precio ?? 0.0) * element.cantidad!;
       });
 
       return previousValue + productTotal + toppingsTotal;
@@ -124,7 +124,7 @@ class PedidoMesaDetalleScreen extends StatelessWidget {
                                   Expanded(
                                     flex: 2,
                                     child: Text(
-                                      '\$${formatCurrency(double.tryParse(producto.producto?.precio ?? '0.0') ?? 0.0)}',
+                                      '\$${formatCurrency(producto.producto?.precio ?? 0.0)}',
                                       style: TextStyle(
                                           fontWeight: FontWeight.w500,
                                           fontSize: 17),
@@ -153,7 +153,7 @@ class PedidoMesaDetalleScreen extends StatelessWidget {
                                             ),
                                             Spacer(),
                                             Text(
-                                              '\$${formatCurrency(double.tryParse(topping.topping?.precio ?? '0.0') ?? 0.0)}',
+                                              '\$${formatCurrency(producto.producto?.precio ?? 0.0)}',
                                               style: TextStyle(
                                                   fontSize: 15,
                                                   color: Colors.grey[600]),

+ 114 - 10
lib/views/pedido_mesa/pedido_mesa_form.dart

@@ -14,6 +14,10 @@ import 'package:collection/collection.dart';
 import '../../widgets/widgets.dart';
 
 class PedidoMesaForm extends StatefulWidget {
+  final Pedido? pedido;
+
+  const PedidoMesaForm({Key? key, Pedido? this.pedido}) : super(key: key);
+
   @override
   _PedidoMesaFormState createState() => _PedidoMesaFormState();
 }
@@ -29,6 +33,7 @@ class _PedidoMesaFormState extends State<PedidoMesaForm> {
   List<CategoriaProducto> categorias = [];
   List<Producto> productos = [];
   List<ItemCarrito> carrito = [];
+  List<DropdownMenuItem<int>> listaMesas = [];
   Producto? _productoActual;
   bool _estadoBusqueda = false;
   Pedido? pedidoActual;
@@ -53,14 +58,14 @@ class _PedidoMesaFormState extends State<PedidoMesaForm> {
     double total = 0;
 
     for (var item in carrito) {
-      total += double.parse(item.producto.precio!) * item.cantidad;
+      total += item.producto.precio! * item.cantidad;
       item.selectedToppings.forEach((categoryId, selectedToppingIds) {
         for (int toppingId in selectedToppingIds) {
           Producto? topping = item.selectableToppings[categoryId]?.firstWhere(
               (topping) => topping.id == toppingId,
-              orElse: () => Producto(precio: '0'));
+              orElse: () => Producto(precio: 0));
           if (topping != null) {
-            total += (double.tryParse(topping.precio!) ?? 0) * item.cantidad;
+            total += (topping.precio ?? 0.0) * item.cantidad;
           }
         }
       });
@@ -83,6 +88,7 @@ class _PedidoMesaFormState extends State<PedidoMesaForm> {
   @override
   void initState() {
     super.initState();
+    final mvm = Provider.of<MesaViewModel>(context, listen: false);
     cargarCategoriasIniciales().then((_) {
       if (categorias.isNotEmpty) {
         categoriaSeleccionada = categorias.first;
@@ -90,7 +96,37 @@ class _PedidoMesaFormState extends State<PedidoMesaForm> {
       }
     });
 
+    listaMesas = mvm.mesas
+        .map(
+          (mesa) => DropdownMenuItem<int>(
+            value: mesa.id,
+            child: Text(
+              '${mesa.clave} - ${mesa.nombre}',
+              style: const TextStyle(color: Colors.black),
+            ),
+          ),
+        )
+        .toList();
+
+    listaMesas.add(DropdownMenuItem<int>(
+        value: 0,
+        child:
+            Text('Seleccionar', style: const TextStyle(color: Colors.black))));
+
     Provider.of<DescuentoViewModel>(context, listen: false).cargarDescuentos();
+
+    if (widget.pedido != null && widget.pedido!.id != null) {
+      Future(() async {
+        for (var item in widget.pedido!.productos) {
+          Map<int, List<Producto>> toppingsSeleccionables =
+              await obtenerToppingsSeleccionables(item.producto!);
+          carrito.add(ItemCarrito(
+              producto: item.producto!,
+              cantidad: item.cantidad!,
+              selectableToppings: toppingsSeleccionables));
+        }
+      });
+    }
   }
 
   _onSearchChanged(String value) {
@@ -566,7 +602,7 @@ class _PedidoMesaFormState extends State<PedidoMesaForm> {
       return PedidoProducto(
         idProducto: item.producto.id,
         producto: item.producto,
-        costoUnitario: item.producto.precio,
+        costoUnitario: item.producto.precio.toString(),
         cantidad: item.cantidad,
         comentario: comentarios,
         toppings: selectedToppings,
@@ -594,6 +630,74 @@ class _PedidoMesaFormState extends State<PedidoMesaForm> {
     }
   }
 
+  void guardarPedidoActual() async {
+    DateTime now = DateTime.now();
+    String formattedDate = DateFormat('dd-MM-yyyy kk:mm:ss').format(now);
+
+    Pedido nuevoPedido = Pedido(
+      peticion: formattedDate,
+      // nombreCliente: nombreCliente,
+      // comentarios: comentarios,
+      estatus: "EN PROCESO",
+      // totalPedido: totalPedido,
+      descuento: pedidoActual?.descuento,
+      idMesa: selectedMesa
+      // tipoPago: _obtenerTipoPago(),
+      // cantEfectivo:
+      //     efectivoSeleccionado ? double.tryParse(efectivoController.text) : 0,
+      // cantTarjeta:
+      //     tarjetaSeleccionada ? double.tryParse(tarjetaController.text) : 0,
+      // cantTransferencia: transferenciaSeleccionada
+      //     ? double.tryParse(transferenciaController.text)
+      //     : 0,
+    );
+
+    List<PedidoProducto> listaPedidoProducto = carrito.map((item) {
+      List<PedidoProductoTopping> selectedToppings = [];
+
+      item.selectedToppings.forEach((categoryId, selectedToppingIds) {
+        for (int toppingId in selectedToppingIds) {
+          selectedToppings.add(PedidoProductoTopping(
+            idTopping: toppingId,
+          ));
+        }
+      });
+
+      return PedidoProducto(
+        idProducto: item.producto.id,
+        producto: item.producto,
+        costoUnitario: item.producto.precio.toString(),
+        cantidad: item.cantidad,
+        // comentario: comentarios,
+        toppings: selectedToppings,
+      );
+    }).toList();
+
+    nuevoPedido.productos = listaPedidoProducto;
+
+    if (widget.pedido != null && widget.pedido!.id != null) {
+      nuevoPedido.id = widget.pedido!.id;
+    }
+
+    bool result = await Provider.of<PedidoViewModel>(context, listen: false)
+        .guardarPedidoLocal(pedido: nuevoPedido);
+
+    if (!mounted) return;
+
+    if (result) {
+      Pedido? pedidoCompleto =
+          await Provider.of<PedidoViewModel>(context, listen: false)
+              .fetchPedidoConProductos(nuevoPedido.id!);
+
+      if (pedidoCompleto != null) {
+        imprimirTicketsJuntos(context, pedidoCompleto);
+      }
+      Navigator.of(context).pop();
+    } else {
+      print("Error al guardar el pedido");
+    }
+  }
+
   String _obtenerTipoPago() {
     List<String> tiposPago = [];
     if (efectivoSeleccionado) tiposPago.add('Efectivo');
@@ -751,7 +855,8 @@ class _PedidoMesaFormState extends State<PedidoMesaForm> {
                   builder: (context, viewModel, child) {
                     return AppDropdownModel<int>(
                       hint: 'Seleccionar',
-                      items: viewModel.mesas
+                      items:
+                          listaMesas /* viewModel.mesas
                           .map(
                             (mesa) => DropdownMenuItem<int>(
                               value: mesa.id,
@@ -761,7 +866,8 @@ class _PedidoMesaFormState extends State<PedidoMesaForm> {
                               ),
                             ),
                           )
-                          .toList(),
+                          .toList() */
+                      ,
                       selectedValue: selectedMesa,
                       onChanged: (value) {
                         setState(() {
@@ -999,9 +1105,7 @@ class _PedidoMesaFormState extends State<PedidoMesaForm> {
                                             MainAxisAlignment.spaceBetween,
                                         children: [
                                           Text(topping.nombre!),
-                                          if (double.tryParse(
-                                                  topping.precio!) !=
-                                              0.0)
+                                          if (topping.precio != 0.0)
                                             Text(
                                               '+\$${topping.precio}',
                                               style: TextStyle(
@@ -1071,7 +1175,7 @@ class _PedidoMesaFormState extends State<PedidoMesaForm> {
                   Padding(
                     padding: const EdgeInsets.all(8.0),
                     child: ElevatedButton(
-                      onPressed: _finalizeOrder,
+                      onPressed: guardarPedidoActual,
                       style: ElevatedButton.styleFrom(
                         backgroundColor: AppTheme.tertiary,
                         textStyle: const TextStyle(fontSize: 22),

+ 19 - 7
lib/views/pedido_mesa/pedido_mesa_screen.dart

@@ -25,7 +25,8 @@ class _PedidoMesaScreenState extends State<PedidoMesaScreen> {
   void initState() {
     super.initState();
     WidgetsBinding.instance.addPostFrameCallback((_) {
-      Provider.of<PedidoViewModel>(context, listen: false).fetchLocalMesaPedidosForScreen();
+      Provider.of<PedidoViewModel>(context, listen: false)
+          .fetchLocalMesaPedidosForScreen();
     });
   }
 
@@ -75,12 +76,23 @@ class _PedidoMesaScreenState extends State<PedidoMesaScreen> {
         await Provider.of<PedidoViewModel>(context, listen: false)
             .fetchPedidoConProductos(item.id);
     if (pedidoCompleto != null) {
-      Navigator.push(
-        context,
-        MaterialPageRoute(
-          builder: (context) => PedidoMesaDetalleScreen(pedido: pedidoCompleto),
-        ),
-      );
+      if (pedidoCompleto.estatus == 'EN PROCESO') {
+        Navigator.push(
+          context,
+          MaterialPageRoute(
+            builder: (context) =>
+                PedidoMesaForm(pedido: pedidoCompleto),
+          ),
+        );
+      } else {
+        Navigator.push(
+          context,
+          MaterialPageRoute(
+            builder: (context) =>
+                PedidoMesaDetalleScreen(pedido: pedidoCompleto),
+          ),
+        );
+      }
     } else {
       print("Error al cargar el pedido con productos");
     }