12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388 |
- import 'dart:async';
- import 'dart:io';
- import 'package:flutter/foundation.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
- import 'package:intl/intl.dart';
- import 'package:provider/provider.dart';
- import 'package:yoshi_papas_app/views/pedido/pedido_ticket.dart';
- import '../../themes/themes.dart';
- import '../../models/models.dart';
- import '../../viewmodels/viewmodels.dart';
- import 'package:collection/collection.dart';
- import '../../widgets/widgets.dart';
- class PedidoForm extends StatefulWidget {
- @override
- _PedidoFormState createState() => _PedidoFormState();
- }
- class _PedidoFormState extends State<PedidoForm> {
- final _busqueda = TextEditingController(text: '');
- final TextEditingController _descuentoController = TextEditingController();
- CategoriaProductoViewModel cvm = CategoriaProductoViewModel();
- ProductoViewModel pvm = ProductoViewModel();
- PedidoViewModel pedvm = PedidoViewModel();
- bool _isLoading = false;
- CategoriaProducto? categoriaSeleccionada;
- List<CategoriaProducto> categorias = [];
- List<Producto> productos = [];
- List<ItemCarrito> carrito = [];
- Producto? _productoActual;
- bool _estadoBusqueda = false;
- Pedido? pedidoActual;
- ScrollController _gridViewController = ScrollController();
- ScrollController _categoryScrollController = ScrollController();
- final _searchController = TextEditingController();
- final NumberFormat _numberFormat = NumberFormat.decimalPattern('es_MX');
- int? selectedDescuento = 0;
- double subtotal = 0;
- double precioDescuento = 0;
- double totalPedido = 0;
- bool efectivoSeleccionado = false;
- bool tarjetaSeleccionada = false;
- bool transferenciaSeleccionada = false;
- TextEditingController efectivoController = TextEditingController();
- TextEditingController tarjetaController = TextEditingController();
- TextEditingController transferenciaController = TextEditingController();
- double cambio = 0.0;
- double calcularTotalPedido() {
- double total = 0;
- for (var item in carrito) {
- 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));
- if (topping != null) {
- total += (topping.precio ?? 0.0) * item.cantidad;
- }
- }
- });
- }
- return total;
- }
- double aplicarDescuento(double total, int? descuento) {
- if (descuento != null && descuento > 0) {
- double totalPedido = total * (1 - descuento / 100);
- // print(
- // 'Total con descuento: $totalPedido (Descuento aplicado: $descuento%)');
- return totalPedido;
- }
- // print('Sin descuento, total: $total');
- return total;
- }
- @override
- void initState() {
- super.initState();
- cargarCategoriasIniciales().then((_) {
- if (categorias.isNotEmpty) {
- categoriaSeleccionada = categorias.first;
- cargarProductosPorCategoria(categoriaSeleccionada!.id);
- }
- });
- Provider.of<DescuentoViewModel>(context, listen: false).cargarDescuentos();
- }
- void _onSearchChanged(String value) async {
- if (value.isEmpty) {
- cargarProductosPorCategoria(
- categoriaSeleccionada?.id ?? categorias.first.id);
- } else {
- setState(() {
- _estadoBusqueda = true;
- });
- await Provider.of<ProductoViewModel>(context, listen: false)
- .fetchLocalByName(nombre: value);
- setState(() {
- productos =
- Provider.of<ProductoViewModel>(context, listen: false).productos;
- });
- }
- }
- void _recalcularTotal() {
- subtotal = calcularTotalPedido();
- // print('Subtotal: $subtotal');
- // print('Descuento seleccionado: $selectedDescuento%');
- precioDescuento = subtotal * (selectedDescuento! / 100);
- totalPedido = subtotal - precioDescuento;
- setState(() {
- pedidoActual = pedidoActual ?? Pedido();
- pedidoActual!.totalPedido = totalPedido;
- pedidoActual!.descuento = selectedDescuento;
- });
- // print('Precio descuento: $precioDescuento');
- // print('Total con descuento aplicado: $totalPedido');
- }
- void _finalizeOrder() async {
- if (carrito.isEmpty) {
- showDialog(
- context: context,
- builder: (BuildContext context) {
- return AlertDialog(
- title: const Text('Pedido vacío',
- style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22)),
- content: const Text(
- 'No puedes finalizar un pedido sin productos. Por favor, agrega al menos un producto.',
- style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18)),
- shape:
- RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- actions: <Widget>[
- TextButton(
- style: TextButton.styleFrom(
- padding: EdgeInsets.fromLTRB(30, 20, 30, 20),
- foregroundColor: AppTheme.quaternary,
- backgroundColor: AppTheme.tertiary),
- onPressed: () {
- Navigator.of(context).pop();
- },
- child: const Text('Aceptar', style: TextStyle(fontSize: 18)),
- ),
- ],
- );
- },
- );
- return;
- }
- await _promptForCustomerName();
- }
- Future<void> _promptForCustomerName() async {
- TextEditingController nombreController = TextEditingController();
- TextEditingController comentarioController = TextEditingController();
- String errorMessage = '';
- double faltante = totalPedido;
- bool totalCompletado = false;
- bool efectivoCompleto = false;
- bool tarjetaCompleto = false;
- bool transferenciaCompleto = false;
- void _calcularCambio(StateSetter setState) {
- double totalPagado = (double.tryParse(efectivoController.text) ?? 0) +
- (double.tryParse(tarjetaController.text) ?? 0) +
- (double.tryParse(transferenciaController.text) ?? 0);
- setState(() {
- cambio = totalPagado - totalPedido;
- if (cambio < 0) {
- faltante = totalPedido - totalPagado;
- cambio = 0;
- totalCompletado = false;
- } else {
- faltante = 0;
- totalCompletado = true;
- }
- // Si el total ha sido alcanzado o excedido, desactivar otros métodos de pago
- if (totalPagado >= totalPedido) {
- if (!efectivoSeleccionado) efectivoSeleccionado = false;
- if (!tarjetaSeleccionada) tarjetaSeleccionada = false;
- if (!transferenciaSeleccionada) transferenciaSeleccionada = false;
- }
- });
- }
- void _validarCantidad(
- StateSetter setState, TextEditingController controller) {
- double cantidad = double.tryParse(controller.text) ?? 0;
- if (cantidad > totalPedido) {
- setState(() {
- controller.text = totalPedido.toStringAsFixed(2);
- });
- }
- _calcularCambio(setState);
- }
- bool _isPaymentOptionEnabled(bool isSelected) {
- return !totalCompletado || isSelected;
- }
- bool? shouldSave = await showDialog<bool>(
- context: context,
- builder: (BuildContext context) {
- return StatefulBuilder(
- builder: (context, setState) {
- return RawKeyboardListener(
- focusNode: FocusNode(),
- onKey: (RawKeyEvent event) {
- if (event.isKeyPressed(LogicalKeyboardKey.enter) &&
- totalCompletado) {
- Navigator.of(context).pop(true);
- }
- },
- child: AlertDialog(
- actionsPadding: EdgeInsets.fromLTRB(50, 10, 50, 30),
- title: const Text(
- 'Finalizar Pedido',
- style: TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
- ),
- content: Container(
- height: 600,
- child: Column(
- children: [
- Expanded(
- child: SingleChildScrollView(
- child: Column(
- children: [
- AppTextField(
- controller: nombreController,
- etiqueta: 'Nombre',
- hintText: "Nombre del Cliente",
- ),
- const SizedBox(height: 10),
- AppTextField(
- controller: comentarioController,
- etiqueta: 'Comentarios (opcional)',
- hintText: 'Comentarios',
- maxLines: 2,
- ),
- const SizedBox(height: 10),
- Align(
- alignment: Alignment.center,
- child: Text(
- 'Métodos de pago',
- style: TextStyle(
- fontWeight: FontWeight.bold,
- fontSize: 20),
- ),
- ),
- const SizedBox(height: 10),
- // Efectivo
- GestureDetector(
- onTap: () {
- if (_isPaymentOptionEnabled(
- efectivoSeleccionado)) {
- setState(() {
- efectivoSeleccionado =
- !efectivoSeleccionado;
- if (!efectivoSeleccionado) {
- efectivoCompleto = false;
- efectivoController.clear();
- _calcularCambio(setState);
- } else if (efectivoCompleto) {
- efectivoController.text =
- totalPedido.toStringAsFixed(2);
- _calcularCambio(setState);
- }
- });
- }
- },
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- crossAxisAlignment:
- CrossAxisAlignment.center,
- children: [
- Row(
- children: [
- Checkbox(
- activeColor: AppTheme.primary,
- value: efectivoSeleccionado,
- onChanged: _isPaymentOptionEnabled(
- efectivoSeleccionado)
- ? (bool? value) {
- setState(() {
- efectivoSeleccionado =
- value ?? false;
- if (!efectivoSeleccionado) {
- efectivoCompleto =
- false;
- efectivoController
- .clear();
- _calcularCambio(
- setState);
- } else if (efectivoCompleto) {
- efectivoController
- .text =
- totalPedido
- .toStringAsFixed(
- 2);
- _calcularCambio(
- setState);
- }
- });
- }
- : null,
- ),
- const Text(
- "Efectivo",
- style: TextStyle(
- fontSize: 18,
- fontWeight: FontWeight.bold),
- ),
- ],
- ),
- if (efectivoSeleccionado)
- SizedBox(
- width: 180,
- child: Row(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Column(
- children: [
- const Text('Exacto',
- style: TextStyle(
- fontSize: 18,
- fontWeight:
- FontWeight.bold,
- color: Colors.black)),
- const SizedBox(
- height: 17,
- ),
- Checkbox(
- activeColor:
- AppTheme.primary,
- value: efectivoCompleto,
- onChanged:
- efectivoSeleccionado
- ? (bool? value) {
- setState(() {
- efectivoCompleto =
- value ??
- false;
- if (efectivoCompleto) {
- efectivoController
- .text =
- totalPedido
- .toStringAsFixed(2);
- _calcularCambio(
- setState);
- } else {
- efectivoController
- .clear();
- _calcularCambio(
- setState);
- }
- });
- }
- : null,
- ),
- ],
- ),
- const SizedBox(
- width: 5,
- ),
- Expanded(
- child: AppTextField(
- controller:
- efectivoController,
- etiqueta: 'Cantidad',
- hintText: '0.00',
- keyboardType:
- TextInputType.number,
- onChanged: (value) =>
- _calcularCambio(setState),
- ),
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 10),
- // Tarjeta
- GestureDetector(
- onTap: () {
- if (_isPaymentOptionEnabled(
- tarjetaSeleccionada)) {
- setState(() {
- tarjetaSeleccionada =
- !tarjetaSeleccionada;
- if (!tarjetaSeleccionada) {
- tarjetaController.clear();
- _calcularCambio(setState);
- }
- });
- }
- },
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- crossAxisAlignment:
- CrossAxisAlignment.center,
- children: [
- Row(
- children: [
- Checkbox(
- activeColor: AppTheme.primary,
- value: tarjetaSeleccionada,
- onChanged: _isPaymentOptionEnabled(
- tarjetaSeleccionada)
- ? (bool? value) {
- setState(() {
- tarjetaSeleccionada =
- value ?? false;
- if (!tarjetaSeleccionada) {
- tarjetaController
- .clear();
- _calcularCambio(
- setState);
- }
- });
- }
- : null,
- ),
- const Text(
- "Tarjeta",
- style: TextStyle(
- fontSize: 18,
- fontWeight: FontWeight.bold),
- ),
- ],
- ),
- if (tarjetaSeleccionada)
- SizedBox(
- width: 180,
- child: Row(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Column(
- children: [
- const Text('Exacto',
- style: TextStyle(
- fontSize: 18,
- fontWeight:
- FontWeight.bold,
- color: Colors.black)),
- const SizedBox(
- height: 17,
- ),
- Checkbox(
- activeColor:
- AppTheme.primary,
- value: tarjetaCompleto,
- onChanged:
- tarjetaSeleccionada
- ? (bool? value) {
- setState(() {
- tarjetaCompleto =
- value ??
- false;
- if (tarjetaCompleto) {
- tarjetaController
- .text =
- totalPedido
- .toStringAsFixed(2);
- _calcularCambio(
- setState);
- } else {
- tarjetaController
- .clear();
- _calcularCambio(
- setState);
- }
- });
- }
- : null,
- ),
- ],
- ),
- const SizedBox(
- width: 5,
- ),
- Expanded(
- child: AppTextField(
- controller: tarjetaController,
- etiqueta: 'Cantidad',
- hintText: '0.00',
- keyboardType:
- TextInputType.number,
- onChanged: (value) {
- _validarCantidad(setState,
- tarjetaController);
- },
- ),
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 10),
- // Transferencia
- GestureDetector(
- onTap: () {
- if (_isPaymentOptionEnabled(
- transferenciaSeleccionada)) {
- setState(() {
- transferenciaSeleccionada =
- !transferenciaSeleccionada;
- if (!transferenciaSeleccionada) {
- transferenciaController.clear();
- _calcularCambio(setState);
- }
- });
- }
- },
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- crossAxisAlignment:
- CrossAxisAlignment.center,
- children: [
- Row(
- children: [
- Checkbox(
- activeColor: AppTheme.primary,
- value: transferenciaSeleccionada,
- onChanged: _isPaymentOptionEnabled(
- transferenciaSeleccionada)
- ? (bool? value) {
- setState(() {
- transferenciaSeleccionada =
- value ?? false;
- if (!transferenciaSeleccionada) {
- transferenciaController
- .clear();
- _calcularCambio(
- setState);
- }
- });
- }
- : null,
- ),
- const Text(
- "Transferencia",
- style: TextStyle(
- fontSize: 18,
- fontWeight: FontWeight.bold),
- ),
- ],
- ),
- if (transferenciaSeleccionada)
- SizedBox(
- width: 180,
- child: Row(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Column(
- children: [
- const Text('Exacto',
- style: TextStyle(
- fontSize: 18,
- fontWeight:
- FontWeight.bold,
- color: Colors.black)),
- const SizedBox(
- height: 17,
- ),
- Checkbox(
- activeColor:
- AppTheme.primary,
- value:
- transferenciaCompleto,
- onChanged:
- transferenciaSeleccionada
- ? (bool? value) {
- setState(() {
- transferenciaCompleto =
- value ??
- false;
- if (transferenciaCompleto) {
- transferenciaController
- .text =
- totalPedido
- .toStringAsFixed(2);
- _calcularCambio(
- setState);
- } else {
- transferenciaController
- .clear();
- _calcularCambio(
- setState);
- }
- });
- }
- : null,
- ),
- ],
- ),
- const SizedBox(
- width: 5,
- ),
- Expanded(
- child: AppTextField(
- controller:
- transferenciaController,
- etiqueta: 'Cantidad',
- hintText: '0.00',
- keyboardType:
- TextInputType.number,
- onChanged: (value) {
- _validarCantidad(setState,
- transferenciaController);
- },
- ),
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 10),
- // Mostrar el total del pedido y la cantidad faltante
- Align(
- alignment: Alignment.centerRight,
- child: Column(
- crossAxisAlignment:
- CrossAxisAlignment.end,
- children: [
- Text(
- 'Total del pedido: \$${totalPedido.toStringAsFixed(2)}',
- style: const TextStyle(
- fontWeight: FontWeight.bold,
- fontSize: 18),
- ),
- if (faltante > 0)
- Text(
- 'Faltante: \$${faltante.toStringAsFixed(2)}',
- style: const TextStyle(
- color: Colors.red,
- fontSize: 18,
- fontWeight: FontWeight.bold),
- )
- else if (cambio > 0)
- Text(
- 'Cambio: \$${cambio.toStringAsFixed(2)}',
- style: const TextStyle(
- color: Colors.green,
- fontSize: 18,
- fontWeight: FontWeight.bold)),
- ]),
- ),
- ],
- ),
- ),
- ),
- // Aquí mantenemos los botones fijos
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- TextButton(
- child: const Text('Cancelar',
- style: TextStyle(fontSize: 18)),
- onPressed: () {
- Navigator.of(context).pop(false);
- },
- style: ButtonStyle(
- padding: MaterialStatePropertyAll(
- EdgeInsets.fromLTRB(30, 20, 30, 20)),
- backgroundColor:
- MaterialStatePropertyAll(Colors.red),
- foregroundColor: MaterialStatePropertyAll(
- AppTheme.secondary)),
- ),
- const SizedBox(width: 100),
- TextButton(
- child: const Text('Guardar',
- style: TextStyle(fontSize: 18)),
- onPressed: totalCompletado
- ? () {
- Navigator.of(context).pop(true);
- }
- : null,
- style: ButtonStyle(
- padding: MaterialStatePropertyAll(
- EdgeInsets.fromLTRB(30, 20, 30, 20)),
- backgroundColor: MaterialStatePropertyAll(
- totalCompletado
- ? AppTheme.tertiary
- : Colors.grey),
- foregroundColor: MaterialStatePropertyAll(
- AppTheme.quaternary)),
- ),
- ],
- ),
- ],
- ),
- ),
- ));
- },
- );
- },
- );
- if (shouldSave ?? false) {
- prepararPedidoActual(nombreController.text, comentarioController.text);
- }
- }
- void prepararPedidoActual(String nombreCliente, String comentarios) async {
- String now = DateTime.now().toUtc().toIso8601String();
- Pedido nuevoPedido = Pedido(
- peticion: now,
- nombreCliente: nombreCliente,
- comentarios: comentarios,
- estatus: "NUEVO",
- totalPedido: totalPedido,
- descuento: pedidoActual?.descuento,
- 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(
- idCategoria: categoryId,
- 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;
- 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');
- if (tarjetaSeleccionada) tiposPago.add('Tarjeta');
- if (transferenciaSeleccionada) tiposPago.add('Transferencia');
- return tiposPago.join(',');
- }
- void _limpiarBusqueda() async {
- setState(() {
- _busqueda.text = '';
- _estadoBusqueda = false;
- });
- await cargarCategoriasIniciales();
- }
- Future<void> cargarProductosIniciales() async {
- setState(() => _isLoading = true);
- await Provider.of<ProductoViewModel>(context, listen: false)
- .fetchLocalAll();
- productos =
- Provider.of<ProductoViewModel>(context, listen: false).productos;
- setState(() => _isLoading = false);
- }
- @override
- void dispose() {
- _gridViewController.dispose();
- _searchController.dispose();
- _categoryScrollController.dispose();
- super.dispose();
- }
- Future<void> cargarCategoriasIniciales() async {
- setState(() => _isLoading = true);
- await Provider.of<CategoriaProductoViewModel>(context, listen: false)
- .fetchLocalAll();
- categorias = Provider.of<CategoriaProductoViewModel>(context, listen: false)
- .categoriaProductos;
- if (categorias.isNotEmpty) {
- categoriaSeleccionada = categorias.first;
- cargarProductosPorCategoria(categoriaSeleccionada!.id);
- }
- setState(() => _isLoading = false);
- if (categorias.isNotEmpty) {
- categoriaSeleccionada = categorias.first;
- }
- }
- void cargarProductosPorCategoria(int categoriaId) async {
- setState(() => _isLoading = true);
- await Provider.of<ProductoViewModel>(context, listen: false)
- .fetchAllByCategory(categoriaId);
- productos =
- Provider.of<ProductoViewModel>(context, listen: false).productos;
- setState(() => _isLoading = false);
- }
- void agregarAlCarrito(Producto producto) async {
- var existente = carrito.firstWhereOrNull((item) =>
- item.producto.id == producto.id &&
- mapEquals(item.selectedToppings, {}));
- if (existente != null) {
- setState(() {
- existente.cantidad++;
- });
- } else {
- Map<int, List<Producto>> toppingsSeleccionables =
- await obtenerToppingsSeleccionables(producto);
- setState(() {
- carrito.add(ItemCarrito(
- producto: producto,
- cantidad: 1,
- selectableToppings: toppingsSeleccionables,
- ));
- });
- }
- _recalcularTotal();
- }
- Future<Map<int, List<Producto>>> obtenerToppingsSeleccionables(
- Producto producto) async {
- Map<int, List<Producto>> toppingsSeleccionables = {};
- final toppingCategories =
- await pvm.obtenerToppingsPorProducto(producto.id!);
- for (int toppingId in toppingCategories) {
- Producto? topping = await pvm.obtenerProductoPorId(toppingId);
- if (topping != null && topping.idCategoria != null) {
- toppingsSeleccionables[topping.idCategoria!] ??= [];
- toppingsSeleccionables[topping.idCategoria]!.add(topping);
- }
- }
- return toppingsSeleccionables;
- }
- void quitarDelCarrito(Producto producto) {
- setState(() {
- var indice =
- carrito.indexWhere((item) => item.producto.id == producto.id);
- if (indice != -1) {
- if (carrito[indice].cantidad > 1) {
- carrito[indice].cantidad--;
- } else {
- carrito.removeAt(indice);
- }
- }
- });
- }
- void addToCart(Producto producto) {
- var existingIndex = carrito.indexWhere((item) =>
- item.producto.id == producto.id &&
- mapEquals(item.selectedToppings, {}));
- if (existingIndex != -1) {
- setState(() {
- carrito[existingIndex].cantidad++;
- });
- } else {
- setState(() {
- carrito.add(ItemCarrito(producto: producto, cantidad: 1));
- });
- }
- }
- void finalizeCustomization() {
- if (_productoActual != null) {
- addToCart(_productoActual!);
- setState(() {
- _productoActual = null;
- });
- }
- }
- Widget _buildDiscountSection() {
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 8.0),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- const Text(
- 'Descuento',
- style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
- ),
- const Spacer(),
- ConstrainedBox(
- constraints: const BoxConstraints(
- maxWidth: 150,
- ),
- child: Consumer<DescuentoViewModel>(
- builder: (context, viewModel, child) {
- return AppDropdownModel<int>(
- hint: 'Seleccionar',
- items: viewModel.descuentos
- .map(
- (descuento) => DropdownMenuItem<int>(
- value: descuento.porcentaje,
- child: Text(
- '${descuento.porcentaje}%',
- style: const TextStyle(color: Colors.black),
- ),
- ),
- )
- .toList(),
- selectedValue: selectedDescuento,
- onChanged: (value) {
- setState(() {
- selectedDescuento = value;
- _recalcularTotal();
- });
- },
- );
- },
- ),
- ),
- ],
- ),
- );
- }
- Widget _buildTotalSection() {
- String formattedsubtotal = _numberFormat.format(subtotal);
- String formattedPrecioDescuento = _numberFormat.format(precioDescuento);
- String formattedtotalPedido = _numberFormat.format(totalPedido);
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 8.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- if (precioDescuento > 0)
- Column(
- children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- const Text('Subtotal',
- style: TextStyle(
- fontWeight: FontWeight.bold, fontSize: 18)),
- Text("\$$formattedsubtotal",
- style: const TextStyle(
- fontWeight: FontWeight.bold, fontSize: 18)),
- ],
- ),
- const SizedBox(height: 10),
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- const Text('Descuento',
- style: TextStyle(
- fontWeight: FontWeight.bold, fontSize: 18)),
- Text("-\$$formattedPrecioDescuento",
- style: const TextStyle(
- fontWeight: FontWeight.bold, fontSize: 18)),
- ],
- ),
- ],
- ),
- const SizedBox(height: 10),
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- const Text('Total',
- style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
- Text("\$$formattedtotalPedido",
- style: const TextStyle(
- fontWeight: FontWeight.bold, fontSize: 18)),
- ],
- ),
- ],
- ),
- );
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title:
- Text("Crear Pedido", style: TextStyle(color: AppTheme.secondary)),
- iconTheme: IconThemeData(color: AppTheme.secondary)),
- body: Row(
- children: [
- Flexible(
- flex: 3,
- child: _buildCartSection(),
- ),
- SizedBox(width: 35),
- Flexible(flex: 7, child: _buildProductsSection()),
- ],
- ),
- );
- }
- Widget _buildCartSection() {
- return Card(
- margin: const EdgeInsets.all(8.0),
- child: Column(
- children: [
- const Padding(
- padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 16.0),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text('Producto',
- style:
- TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
- Text('Cantidad',
- style:
- TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
- ],
- ),
- ),
- Expanded(
- child: ListView.builder(
- itemCount: carrito.length,
- itemBuilder: (context, index) {
- final item = carrito[index];
- return Column(
- children: [
- ListTile(
- title: Text(item.producto.nombre!,
- style: const TextStyle(fontWeight: FontWeight.w600)),
- subtitle: Text('\$${item.producto.precio}',
- style: const TextStyle(
- fontWeight: FontWeight.bold,
- color: Color(0xFF008000))),
- trailing: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- IconButton(
- icon: const Icon(Icons.delete, color: Colors.red),
- onPressed: () =>
- eliminarProductoDelCarrito(index)),
- IconButton(
- icon: const Icon(Icons.remove),
- onPressed: () => quitarProductoDelCarrito(item)),
- const SizedBox(width: 5),
- Text('${item.cantidad}',
- style: const TextStyle(
- fontWeight: FontWeight.bold, fontSize: 14)),
- const SizedBox(width: 5),
- IconButton(
- icon: const Icon(Icons.add),
- onPressed: () => incrementarProducto(item)),
- ],
- ),
- ),
- // ExpansionTile para todos los toppings
- if (item.selectableToppings.isNotEmpty)
- ExpansionTile(
- title: const Text(
- 'Toppings',
- style: TextStyle(
- fontWeight: FontWeight.bold, fontSize: 16),
- ),
- children: item.selectableToppings.entries.map((entry) {
- final categoryId = entry.key;
- final availableToppings = entry.value;
- final categoria =
- categorias.firstWhere((c) => c.id == categoryId);
- return ExpansionTile(
- initiallyExpanded: true,
- title: Text(
- categoria.nombre!,
- style: const TextStyle(
- fontWeight: FontWeight.bold, fontSize: 16),
- ),
- children: availableToppings.map((topping) {
- bool isSelected = item
- .selectedToppings[categoryId]
- ?.contains(topping.id) ??
- false;
- return CheckboxListTile(
- activeColor: AppTheme.primary,
- title: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(topping.nombre!),
- if (topping.precio != 0.0)
- Text(
- '+\$${topping.precio}',
- style: const TextStyle(
- color: Colors.black,
- fontSize: 13,
- ),
- ),
- ],
- ),
- value: isSelected,
- onChanged: (bool? value) {
- final maximoToppings = categoria.maximo ?? 0;
- setState(() {
- if (value == true) {
- if ((item.selectedToppings[categoryId]
- ?.length ??
- 0) >=
- maximoToppings) {
- item.selectedToppings[categoryId]!
- .remove(item
- .selectedToppings[categoryId]!
- .first);
- }
- item.selectedToppings[categoryId] ??=
- <int>{};
- item.selectedToppings[categoryId]!
- .add(topping.id!);
- } else {
- item.selectedToppings[categoryId]
- ?.remove(topping.id!);
- if (item.selectedToppings[categoryId]
- ?.isEmpty ??
- false) {
- item.selectedToppings
- .remove(categoryId);
- }
- }
- _recalcularTotal();
- });
- },
- );
- }).toList(),
- );
- }).toList(),
- ),
- const Divider(),
- ],
- );
- },
- ),
- ),
- _buildDiscountSection(),
- const Divider(thickness: 5),
- _buildTotalSection(),
- const SizedBox(height: 25),
- Padding(
- padding: const EdgeInsets.all(8.0),
- child: ElevatedButton(
- onPressed: _finalizeOrder,
- style: ElevatedButton.styleFrom(
- backgroundColor: AppTheme.tertiary,
- textStyle: const TextStyle(fontSize: 22),
- fixedSize: const Size(250, 50),
- ),
- child: Text('Finalizar Pedido',
- style: TextStyle(color: AppTheme.quaternary)),
- ),
- ),
- ],
- ),
- );
- }
- void eliminarProductoDelCarrito(int index) {
- setState(() {
- carrito.removeAt(index);
- });
- _recalcularTotal();
- }
- void incrementarProducto(ItemCarrito item) {
- setState(() {
- item.cantidad++;
- });
- _recalcularTotal();
- }
- void quitarProductoDelCarrito(ItemCarrito item) {
- setState(() {
- if (item.cantidad > 1) {
- item.cantidad--;
- } else {
- carrito.remove(item);
- }
- });
- _recalcularTotal();
- }
- Widget _buildProductsSection() {
- return Column(
- children: [
- const SizedBox(height: 5),
- _buildSearchBar(),
- const SizedBox(height: 10),
- _buildCategoryButtons(),
- const SizedBox(height: 15),
- Expanded(
- child: Consumer<ProductoViewModel>(builder: (context, model, child) {
- productos = model.productos;
- return GridView.builder(
- controller: _gridViewController,
- key: ValueKey<int>(categoriaSeleccionada?.id ?? 0),
- gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: 3,
- childAspectRatio: 3 / 2,
- ),
- itemCount: productos.length,
- itemBuilder: (context, index) {
- final producto = productos[index];
- // Si no se está buscando, aplicar el filtro de categoría
- if (!_estadoBusqueda &&
- producto.idCategoria != categoriaSeleccionada?.id) {
- return Container();
- }
- return Card(
- child: InkWell(
- onTap: () => agregarAlCarrito(producto),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- if (producto.imagen != null &&
- File(producto.imagen!).existsSync())
- Image.file(
- File(producto.imagen!),
- height: 120,
- fit: BoxFit.cover,
- )
- else
- const Icon(Icons.fastfood, size: 80),
- const SizedBox(height: 8),
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 8.0),
- child: Text(
- producto.nombre ?? '',
- style: const TextStyle(
- fontSize: 16,
- fontWeight: FontWeight.bold,
- ),
- textAlign: TextAlign.center,
- ),
- ),
- const SizedBox(height: 8),
- Text(
- '\$${producto.precio}',
- style: const TextStyle(
- fontSize: 16,
- fontWeight: FontWeight.bold,
- color: Color(0xFF008000),
- ),
- ),
- ],
- ),
- ),
- );
- },
- );
- }),
- )
- ],
- );
- }
- Widget _buildCategoryButtons() {
- List<CategoriaProducto> categoriasFiltradas =
- categorias.where((categoria) => categoria.esToping == 0).toList();
- return Container(
- height: 50,
- child: Scrollbar(
- thumbVisibility: true,
- trackVisibility: true,
- interactive: true,
- controller: _categoryScrollController,
- child: ListView.builder(
- controller: _categoryScrollController,
- scrollDirection: Axis.horizontal,
- itemCount: categoriasFiltradas.length,
- itemBuilder: (context, index) {
- final categoria = categoriasFiltradas[index];
- bool isSelected = categoriaSeleccionada?.id == categoria.id;
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 4.0),
- child: ElevatedButton(
- onPressed: () {
- cargarProductosPorCategoria(categoria.id);
- setState(() {
- categoriaSeleccionada = categoria;
- });
- },
- style: ElevatedButton.styleFrom(
- backgroundColor: isSelected ? AppTheme.tertiary : Colors.grey,
- foregroundColor:
- isSelected ? AppTheme.quaternary : AppTheme.secondary,
- ),
- child: Text(categoria.nombre!),
- ),
- );
- },
- ),
- ),
- );
- }
- Widget _buildSearchBar() {
- return Padding(
- padding: const EdgeInsets.all(8.0),
- child: TextField(
- controller: _searchController,
- decoration: InputDecoration(
- hintText: 'Buscar producto...',
- prefixIcon: const Icon(Icons.search),
- suffixIcon: IconButton(
- icon: Icon(Icons.clear),
- onPressed: () {
- _searchController.clear();
- _onSearchChanged('');
- },
- ),
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(12.0),
- ),
- enabledBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(12.0),
- borderSide: BorderSide(width: 1.5)),
- focusedBorder: OutlineInputBorder(
- borderSide: BorderSide(color: Colors.black),
- borderRadius: BorderRadius.circular(12.0),
- ),
- ),
- onChanged: _onSearchChanged,
- ),
- );
- }
- }
|