pedido_form.dart 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:flutter/foundation.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter/services.dart';
  6. import 'package:intl/intl.dart';
  7. import 'package:provider/provider.dart';
  8. import 'package:yoshi_papas_app/views/pedido/pedido_ticket.dart';
  9. import '../../themes/themes.dart';
  10. import '../../models/models.dart';
  11. import '../../viewmodels/viewmodels.dart';
  12. import 'package:collection/collection.dart';
  13. import '../../widgets/widgets.dart';
  14. class PedidoForm extends StatefulWidget {
  15. @override
  16. _PedidoFormState createState() => _PedidoFormState();
  17. }
  18. class _PedidoFormState extends State<PedidoForm> {
  19. final _busqueda = TextEditingController(text: '');
  20. final TextEditingController _descuentoController = TextEditingController();
  21. CategoriaProductoViewModel cvm = CategoriaProductoViewModel();
  22. ProductoViewModel pvm = ProductoViewModel();
  23. PedidoViewModel pedvm = PedidoViewModel();
  24. bool _isLoading = false;
  25. CategoriaProducto? categoriaSeleccionada;
  26. List<CategoriaProducto> categorias = [];
  27. List<Producto> productos = [];
  28. List<ItemCarrito> carrito = [];
  29. Producto? _productoActual;
  30. bool _estadoBusqueda = false;
  31. Pedido? pedidoActual;
  32. ScrollController _gridViewController = ScrollController();
  33. ScrollController _categoryScrollController = ScrollController();
  34. final _searchController = TextEditingController();
  35. final NumberFormat _numberFormat = NumberFormat.decimalPattern('es_MX');
  36. int? selectedDescuento = 0;
  37. double subtotal = 0;
  38. double precioDescuento = 0;
  39. double totalPedido = 0;
  40. bool efectivoSeleccionado = false;
  41. bool tarjetaSeleccionada = false;
  42. bool transferenciaSeleccionada = false;
  43. TextEditingController efectivoController = TextEditingController();
  44. TextEditingController tarjetaController = TextEditingController();
  45. TextEditingController transferenciaController = TextEditingController();
  46. double cambio = 0.0;
  47. double calcularTotalPedido() {
  48. double total = 0;
  49. for (var item in carrito) {
  50. total += item.producto.precio! * item.cantidad;
  51. item.selectedToppings.forEach((categoryId, selectedToppingIds) {
  52. for (int toppingId in selectedToppingIds) {
  53. Producto? topping = item.selectableToppings[categoryId]?.firstWhere(
  54. (topping) => topping.id == toppingId,
  55. orElse: () => Producto(precio: 0));
  56. if (topping != null) {
  57. total += (topping.precio ?? 0.0) * item.cantidad;
  58. }
  59. }
  60. });
  61. }
  62. return total;
  63. }
  64. double aplicarDescuento(double total, int? descuento) {
  65. if (descuento != null && descuento > 0) {
  66. double totalPedido = total * (1 - descuento / 100);
  67. // print(
  68. // 'Total con descuento: $totalPedido (Descuento aplicado: $descuento%)');
  69. return totalPedido;
  70. }
  71. // print('Sin descuento, total: $total');
  72. return total;
  73. }
  74. @override
  75. void initState() {
  76. super.initState();
  77. cargarCategoriasIniciales().then((_) {
  78. if (categorias.isNotEmpty) {
  79. categoriaSeleccionada = categorias.first;
  80. cargarProductosPorCategoria(categoriaSeleccionada!.id);
  81. }
  82. });
  83. Provider.of<DescuentoViewModel>(context, listen: false).cargarDescuentos();
  84. }
  85. void _onSearchChanged(String value) async {
  86. if (value.isEmpty) {
  87. cargarProductosPorCategoria(
  88. categoriaSeleccionada?.id ?? categorias.first.id);
  89. } else {
  90. setState(() {
  91. _estadoBusqueda = true;
  92. });
  93. await Provider.of<ProductoViewModel>(context, listen: false)
  94. .fetchLocalByName(nombre: value);
  95. setState(() {
  96. productos =
  97. Provider.of<ProductoViewModel>(context, listen: false).productos;
  98. });
  99. }
  100. }
  101. void _recalcularTotal() {
  102. subtotal = calcularTotalPedido();
  103. // print('Subtotal: $subtotal');
  104. // print('Descuento seleccionado: $selectedDescuento%');
  105. precioDescuento = subtotal * (selectedDescuento! / 100);
  106. totalPedido = subtotal - precioDescuento;
  107. setState(() {
  108. pedidoActual = pedidoActual ?? Pedido();
  109. pedidoActual!.totalPedido = totalPedido;
  110. pedidoActual!.descuento = selectedDescuento;
  111. });
  112. // print('Precio descuento: $precioDescuento');
  113. // print('Total con descuento aplicado: $totalPedido');
  114. }
  115. void _finalizeOrder() async {
  116. if (carrito.isEmpty) {
  117. showDialog(
  118. context: context,
  119. builder: (BuildContext context) {
  120. return AlertDialog(
  121. title: const Text('Pedido vacío',
  122. style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22)),
  123. content: const Text(
  124. 'No puedes finalizar un pedido sin productos. Por favor, agrega al menos un producto.',
  125. style: TextStyle(fontWeight: FontWeight.w500, fontSize: 18)),
  126. shape:
  127. RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
  128. actions: <Widget>[
  129. TextButton(
  130. style: TextButton.styleFrom(
  131. padding: EdgeInsets.fromLTRB(30, 20, 30, 20),
  132. foregroundColor: AppTheme.quaternary,
  133. backgroundColor: AppTheme.tertiary),
  134. onPressed: () {
  135. Navigator.of(context).pop();
  136. },
  137. child: const Text('Aceptar', style: TextStyle(fontSize: 18)),
  138. ),
  139. ],
  140. );
  141. },
  142. );
  143. return;
  144. }
  145. await _promptForCustomerName();
  146. }
  147. Future<void> _promptForCustomerName() async {
  148. TextEditingController nombreController = TextEditingController();
  149. TextEditingController comentarioController = TextEditingController();
  150. String errorMessage = '';
  151. double faltante = totalPedido;
  152. bool totalCompletado = false;
  153. bool efectivoCompleto = false;
  154. bool tarjetaCompleto = false;
  155. bool transferenciaCompleto = false;
  156. void _calcularCambio(StateSetter setState) {
  157. double totalPagado = (double.tryParse(efectivoController.text) ?? 0) +
  158. (double.tryParse(tarjetaController.text) ?? 0) +
  159. (double.tryParse(transferenciaController.text) ?? 0);
  160. setState(() {
  161. cambio = totalPagado - totalPedido;
  162. if (cambio < 0) {
  163. faltante = totalPedido - totalPagado;
  164. cambio = 0;
  165. totalCompletado = false;
  166. } else {
  167. faltante = 0;
  168. totalCompletado = true;
  169. }
  170. // Si el total ha sido alcanzado o excedido, desactivar otros métodos de pago
  171. if (totalPagado >= totalPedido) {
  172. if (!efectivoSeleccionado) efectivoSeleccionado = false;
  173. if (!tarjetaSeleccionada) tarjetaSeleccionada = false;
  174. if (!transferenciaSeleccionada) transferenciaSeleccionada = false;
  175. }
  176. });
  177. }
  178. void _validarCantidad(
  179. StateSetter setState, TextEditingController controller) {
  180. double cantidad = double.tryParse(controller.text) ?? 0;
  181. if (cantidad > totalPedido) {
  182. setState(() {
  183. controller.text = totalPedido.toStringAsFixed(2);
  184. });
  185. }
  186. _calcularCambio(setState);
  187. }
  188. bool _isPaymentOptionEnabled(bool isSelected) {
  189. return !totalCompletado || isSelected;
  190. }
  191. bool? shouldSave = await showDialog<bool>(
  192. context: context,
  193. builder: (BuildContext context) {
  194. return StatefulBuilder(
  195. builder: (context, setState) {
  196. return RawKeyboardListener(
  197. focusNode: FocusNode(),
  198. onKey: (RawKeyEvent event) {
  199. if (event.isKeyPressed(LogicalKeyboardKey.enter) &&
  200. totalCompletado) {
  201. Navigator.of(context).pop(true);
  202. }
  203. },
  204. child: AlertDialog(
  205. actionsPadding: EdgeInsets.fromLTRB(50, 10, 50, 30),
  206. title: const Text(
  207. 'Finalizar Pedido',
  208. style: TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
  209. ),
  210. content: Container(
  211. height: 600,
  212. child: Column(
  213. children: [
  214. Expanded(
  215. child: SingleChildScrollView(
  216. child: Column(
  217. children: [
  218. AppTextField(
  219. controller: nombreController,
  220. etiqueta: 'Nombre',
  221. hintText: "Nombre del Cliente",
  222. ),
  223. const SizedBox(height: 10),
  224. AppTextField(
  225. controller: comentarioController,
  226. etiqueta: 'Comentarios (opcional)',
  227. hintText: 'Comentarios',
  228. maxLines: 2,
  229. ),
  230. const SizedBox(height: 10),
  231. Align(
  232. alignment: Alignment.center,
  233. child: Text(
  234. 'Métodos de pago',
  235. style: TextStyle(
  236. fontWeight: FontWeight.bold,
  237. fontSize: 20),
  238. ),
  239. ),
  240. const SizedBox(height: 10),
  241. // Efectivo
  242. GestureDetector(
  243. onTap: () {
  244. if (_isPaymentOptionEnabled(
  245. efectivoSeleccionado)) {
  246. setState(() {
  247. efectivoSeleccionado =
  248. !efectivoSeleccionado;
  249. if (!efectivoSeleccionado) {
  250. efectivoCompleto = false;
  251. efectivoController.clear();
  252. _calcularCambio(setState);
  253. } else if (efectivoCompleto) {
  254. efectivoController.text =
  255. totalPedido.toStringAsFixed(2);
  256. _calcularCambio(setState);
  257. }
  258. });
  259. }
  260. },
  261. child: Row(
  262. mainAxisAlignment:
  263. MainAxisAlignment.spaceBetween,
  264. crossAxisAlignment:
  265. CrossAxisAlignment.center,
  266. children: [
  267. Row(
  268. children: [
  269. Checkbox(
  270. activeColor: AppTheme.primary,
  271. value: efectivoSeleccionado,
  272. onChanged: _isPaymentOptionEnabled(
  273. efectivoSeleccionado)
  274. ? (bool? value) {
  275. setState(() {
  276. efectivoSeleccionado =
  277. value ?? false;
  278. if (!efectivoSeleccionado) {
  279. efectivoCompleto =
  280. false;
  281. efectivoController
  282. .clear();
  283. _calcularCambio(
  284. setState);
  285. } else if (efectivoCompleto) {
  286. efectivoController
  287. .text =
  288. totalPedido
  289. .toStringAsFixed(
  290. 2);
  291. _calcularCambio(
  292. setState);
  293. }
  294. });
  295. }
  296. : null,
  297. ),
  298. const Text(
  299. "Efectivo",
  300. style: TextStyle(
  301. fontSize: 18,
  302. fontWeight: FontWeight.bold),
  303. ),
  304. ],
  305. ),
  306. if (efectivoSeleccionado)
  307. SizedBox(
  308. width: 180,
  309. child: Row(
  310. crossAxisAlignment:
  311. CrossAxisAlignment.start,
  312. children: [
  313. Column(
  314. children: [
  315. const Text('Exacto',
  316. style: TextStyle(
  317. fontSize: 18,
  318. fontWeight:
  319. FontWeight.bold,
  320. color: Colors.black)),
  321. const SizedBox(
  322. height: 17,
  323. ),
  324. Checkbox(
  325. activeColor:
  326. AppTheme.primary,
  327. value: efectivoCompleto,
  328. onChanged:
  329. efectivoSeleccionado
  330. ? (bool? value) {
  331. setState(() {
  332. efectivoCompleto =
  333. value ??
  334. false;
  335. if (efectivoCompleto) {
  336. efectivoController
  337. .text =
  338. totalPedido
  339. .toStringAsFixed(2);
  340. _calcularCambio(
  341. setState);
  342. } else {
  343. efectivoController
  344. .clear();
  345. _calcularCambio(
  346. setState);
  347. }
  348. });
  349. }
  350. : null,
  351. ),
  352. ],
  353. ),
  354. const SizedBox(
  355. width: 5,
  356. ),
  357. Expanded(
  358. child: AppTextField(
  359. controller:
  360. efectivoController,
  361. etiqueta: 'Cantidad',
  362. hintText: '0.00',
  363. keyboardType:
  364. TextInputType.number,
  365. onChanged: (value) =>
  366. _calcularCambio(setState),
  367. ),
  368. ),
  369. ],
  370. ),
  371. ),
  372. ],
  373. ),
  374. ),
  375. const SizedBox(height: 10),
  376. // Tarjeta
  377. GestureDetector(
  378. onTap: () {
  379. if (_isPaymentOptionEnabled(
  380. tarjetaSeleccionada)) {
  381. setState(() {
  382. tarjetaSeleccionada =
  383. !tarjetaSeleccionada;
  384. if (!tarjetaSeleccionada) {
  385. tarjetaController.clear();
  386. _calcularCambio(setState);
  387. }
  388. });
  389. }
  390. },
  391. child: Row(
  392. mainAxisAlignment:
  393. MainAxisAlignment.spaceBetween,
  394. crossAxisAlignment:
  395. CrossAxisAlignment.center,
  396. children: [
  397. Row(
  398. children: [
  399. Checkbox(
  400. activeColor: AppTheme.primary,
  401. value: tarjetaSeleccionada,
  402. onChanged: _isPaymentOptionEnabled(
  403. tarjetaSeleccionada)
  404. ? (bool? value) {
  405. setState(() {
  406. tarjetaSeleccionada =
  407. value ?? false;
  408. if (!tarjetaSeleccionada) {
  409. tarjetaController
  410. .clear();
  411. _calcularCambio(
  412. setState);
  413. }
  414. });
  415. }
  416. : null,
  417. ),
  418. const Text(
  419. "Tarjeta",
  420. style: TextStyle(
  421. fontSize: 18,
  422. fontWeight: FontWeight.bold),
  423. ),
  424. ],
  425. ),
  426. if (tarjetaSeleccionada)
  427. SizedBox(
  428. width: 180,
  429. child: Row(
  430. crossAxisAlignment:
  431. CrossAxisAlignment.start,
  432. children: [
  433. Column(
  434. children: [
  435. const Text('Exacto',
  436. style: TextStyle(
  437. fontSize: 18,
  438. fontWeight:
  439. FontWeight.bold,
  440. color: Colors.black)),
  441. const SizedBox(
  442. height: 17,
  443. ),
  444. Checkbox(
  445. activeColor:
  446. AppTheme.primary,
  447. value: tarjetaCompleto,
  448. onChanged:
  449. tarjetaSeleccionada
  450. ? (bool? value) {
  451. setState(() {
  452. tarjetaCompleto =
  453. value ??
  454. false;
  455. if (tarjetaCompleto) {
  456. tarjetaController
  457. .text =
  458. totalPedido
  459. .toStringAsFixed(2);
  460. _calcularCambio(
  461. setState);
  462. } else {
  463. tarjetaController
  464. .clear();
  465. _calcularCambio(
  466. setState);
  467. }
  468. });
  469. }
  470. : null,
  471. ),
  472. ],
  473. ),
  474. const SizedBox(
  475. width: 5,
  476. ),
  477. Expanded(
  478. child: AppTextField(
  479. controller: tarjetaController,
  480. etiqueta: 'Cantidad',
  481. hintText: '0.00',
  482. keyboardType:
  483. TextInputType.number,
  484. onChanged: (value) {
  485. _validarCantidad(setState,
  486. tarjetaController);
  487. },
  488. ),
  489. ),
  490. ],
  491. ),
  492. ),
  493. ],
  494. ),
  495. ),
  496. const SizedBox(height: 10),
  497. // Transferencia
  498. GestureDetector(
  499. onTap: () {
  500. if (_isPaymentOptionEnabled(
  501. transferenciaSeleccionada)) {
  502. setState(() {
  503. transferenciaSeleccionada =
  504. !transferenciaSeleccionada;
  505. if (!transferenciaSeleccionada) {
  506. transferenciaController.clear();
  507. _calcularCambio(setState);
  508. }
  509. });
  510. }
  511. },
  512. child: Row(
  513. mainAxisAlignment:
  514. MainAxisAlignment.spaceBetween,
  515. crossAxisAlignment:
  516. CrossAxisAlignment.center,
  517. children: [
  518. Row(
  519. children: [
  520. Checkbox(
  521. activeColor: AppTheme.primary,
  522. value: transferenciaSeleccionada,
  523. onChanged: _isPaymentOptionEnabled(
  524. transferenciaSeleccionada)
  525. ? (bool? value) {
  526. setState(() {
  527. transferenciaSeleccionada =
  528. value ?? false;
  529. if (!transferenciaSeleccionada) {
  530. transferenciaController
  531. .clear();
  532. _calcularCambio(
  533. setState);
  534. }
  535. });
  536. }
  537. : null,
  538. ),
  539. const Text(
  540. "Transferencia",
  541. style: TextStyle(
  542. fontSize: 18,
  543. fontWeight: FontWeight.bold),
  544. ),
  545. ],
  546. ),
  547. if (transferenciaSeleccionada)
  548. SizedBox(
  549. width: 180,
  550. child: Row(
  551. crossAxisAlignment:
  552. CrossAxisAlignment.start,
  553. children: [
  554. Column(
  555. children: [
  556. const Text('Exacto',
  557. style: TextStyle(
  558. fontSize: 18,
  559. fontWeight:
  560. FontWeight.bold,
  561. color: Colors.black)),
  562. const SizedBox(
  563. height: 17,
  564. ),
  565. Checkbox(
  566. activeColor:
  567. AppTheme.primary,
  568. value:
  569. transferenciaCompleto,
  570. onChanged:
  571. transferenciaSeleccionada
  572. ? (bool? value) {
  573. setState(() {
  574. transferenciaCompleto =
  575. value ??
  576. false;
  577. if (transferenciaCompleto) {
  578. transferenciaController
  579. .text =
  580. totalPedido
  581. .toStringAsFixed(2);
  582. _calcularCambio(
  583. setState);
  584. } else {
  585. transferenciaController
  586. .clear();
  587. _calcularCambio(
  588. setState);
  589. }
  590. });
  591. }
  592. : null,
  593. ),
  594. ],
  595. ),
  596. const SizedBox(
  597. width: 5,
  598. ),
  599. Expanded(
  600. child: AppTextField(
  601. controller:
  602. transferenciaController,
  603. etiqueta: 'Cantidad',
  604. hintText: '0.00',
  605. keyboardType:
  606. TextInputType.number,
  607. onChanged: (value) {
  608. _validarCantidad(setState,
  609. transferenciaController);
  610. },
  611. ),
  612. ),
  613. ],
  614. ),
  615. ),
  616. ],
  617. ),
  618. ),
  619. const SizedBox(height: 10),
  620. // Mostrar el total del pedido y la cantidad faltante
  621. Align(
  622. alignment: Alignment.centerRight,
  623. child: Column(
  624. crossAxisAlignment:
  625. CrossAxisAlignment.end,
  626. children: [
  627. Text(
  628. 'Total del pedido: \$${totalPedido.toStringAsFixed(2)}',
  629. style: const TextStyle(
  630. fontWeight: FontWeight.bold,
  631. fontSize: 18),
  632. ),
  633. if (faltante > 0)
  634. Text(
  635. 'Faltante: \$${faltante.toStringAsFixed(2)}',
  636. style: const TextStyle(
  637. color: Colors.red,
  638. fontSize: 18,
  639. fontWeight: FontWeight.bold),
  640. )
  641. else if (cambio > 0)
  642. Text(
  643. 'Cambio: \$${cambio.toStringAsFixed(2)}',
  644. style: const TextStyle(
  645. color: Colors.green,
  646. fontSize: 18,
  647. fontWeight: FontWeight.bold)),
  648. ]),
  649. ),
  650. ],
  651. ),
  652. ),
  653. ),
  654. // Aquí mantenemos los botones fijos
  655. Row(
  656. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  657. children: [
  658. TextButton(
  659. child: const Text('Cancelar',
  660. style: TextStyle(fontSize: 18)),
  661. onPressed: () {
  662. Navigator.of(context).pop(false);
  663. },
  664. style: ButtonStyle(
  665. padding: MaterialStatePropertyAll(
  666. EdgeInsets.fromLTRB(30, 20, 30, 20)),
  667. backgroundColor:
  668. MaterialStatePropertyAll(Colors.red),
  669. foregroundColor: MaterialStatePropertyAll(
  670. AppTheme.secondary)),
  671. ),
  672. const SizedBox(width: 100),
  673. TextButton(
  674. child: const Text('Guardar',
  675. style: TextStyle(fontSize: 18)),
  676. onPressed: totalCompletado
  677. ? () {
  678. Navigator.of(context).pop(true);
  679. }
  680. : null,
  681. style: ButtonStyle(
  682. padding: MaterialStatePropertyAll(
  683. EdgeInsets.fromLTRB(30, 20, 30, 20)),
  684. backgroundColor: MaterialStatePropertyAll(
  685. totalCompletado
  686. ? AppTheme.tertiary
  687. : Colors.grey),
  688. foregroundColor: MaterialStatePropertyAll(
  689. AppTheme.quaternary)),
  690. ),
  691. ],
  692. ),
  693. ],
  694. ),
  695. ),
  696. ));
  697. },
  698. );
  699. },
  700. );
  701. if (shouldSave ?? false) {
  702. prepararPedidoActual(nombreController.text, comentarioController.text);
  703. }
  704. }
  705. void prepararPedidoActual(String nombreCliente, String comentarios) async {
  706. String now = DateTime.now().toUtc().toIso8601String();
  707. Pedido nuevoPedido = Pedido(
  708. peticion: now,
  709. nombreCliente: nombreCliente,
  710. comentarios: comentarios,
  711. estatus: "NUEVO",
  712. totalPedido: totalPedido,
  713. descuento: pedidoActual?.descuento,
  714. tipoPago: _obtenerTipoPago(),
  715. cantEfectivo:
  716. efectivoSeleccionado ? double.tryParse(efectivoController.text) : 0,
  717. cantTarjeta:
  718. tarjetaSeleccionada ? double.tryParse(tarjetaController.text) : 0,
  719. cantTransferencia: transferenciaSeleccionada
  720. ? double.tryParse(transferenciaController.text)
  721. : 0,
  722. );
  723. List<PedidoProducto> listaPedidoProducto = carrito.map((item) {
  724. List<PedidoProductoTopping> selectedToppings = [];
  725. item.selectedToppings.forEach((categoryId, selectedToppingIds) {
  726. for (int toppingId in selectedToppingIds) {
  727. selectedToppings.add(PedidoProductoTopping(
  728. idCategoria: categoryId,
  729. idTopping: toppingId,
  730. ));
  731. }
  732. });
  733. return PedidoProducto(
  734. idProducto: item.producto.id,
  735. producto: item.producto,
  736. costoUnitario: item.producto.precio.toString(),
  737. cantidad: item.cantidad,
  738. comentario: comentarios,
  739. toppings: selectedToppings,
  740. );
  741. }).toList();
  742. nuevoPedido.productos = listaPedidoProducto;
  743. bool result = await Provider.of<PedidoViewModel>(context, listen: false)
  744. .guardarPedidoLocal(pedido: nuevoPedido);
  745. if (!mounted) return;
  746. if (result) {
  747. Pedido? pedidoCompleto =
  748. await Provider.of<PedidoViewModel>(context, listen: false)
  749. .fetchPedidoConProductos(nuevoPedido.id!);
  750. if (pedidoCompleto != null) {
  751. imprimirTicketsJuntos(context, pedidoCompleto);
  752. }
  753. Navigator.of(context).pop();
  754. } else {
  755. print("Error al guardar el pedido");
  756. }
  757. }
  758. String _obtenerTipoPago() {
  759. List<String> tiposPago = [];
  760. if (efectivoSeleccionado) tiposPago.add('Efectivo');
  761. if (tarjetaSeleccionada) tiposPago.add('Tarjeta');
  762. if (transferenciaSeleccionada) tiposPago.add('Transferencia');
  763. return tiposPago.join(',');
  764. }
  765. void _limpiarBusqueda() async {
  766. setState(() {
  767. _busqueda.text = '';
  768. _estadoBusqueda = false;
  769. });
  770. await cargarCategoriasIniciales();
  771. }
  772. Future<void> cargarProductosIniciales() async {
  773. setState(() => _isLoading = true);
  774. await Provider.of<ProductoViewModel>(context, listen: false)
  775. .fetchLocalAll();
  776. productos =
  777. Provider.of<ProductoViewModel>(context, listen: false).productos;
  778. setState(() => _isLoading = false);
  779. }
  780. @override
  781. void dispose() {
  782. _gridViewController.dispose();
  783. _searchController.dispose();
  784. _categoryScrollController.dispose();
  785. super.dispose();
  786. }
  787. Future<void> cargarCategoriasIniciales() async {
  788. setState(() => _isLoading = true);
  789. await Provider.of<CategoriaProductoViewModel>(context, listen: false)
  790. .fetchLocalAll();
  791. categorias = Provider.of<CategoriaProductoViewModel>(context, listen: false)
  792. .categoriaProductos;
  793. if (categorias.isNotEmpty) {
  794. categoriaSeleccionada = categorias.first;
  795. cargarProductosPorCategoria(categoriaSeleccionada!.id);
  796. }
  797. setState(() => _isLoading = false);
  798. if (categorias.isNotEmpty) {
  799. categoriaSeleccionada = categorias.first;
  800. }
  801. }
  802. void cargarProductosPorCategoria(int categoriaId) async {
  803. setState(() => _isLoading = true);
  804. await Provider.of<ProductoViewModel>(context, listen: false)
  805. .fetchAllByCategory(categoriaId);
  806. productos =
  807. Provider.of<ProductoViewModel>(context, listen: false).productos;
  808. setState(() => _isLoading = false);
  809. }
  810. void agregarAlCarrito(Producto producto) async {
  811. var existente = carrito.firstWhereOrNull((item) =>
  812. item.producto.id == producto.id &&
  813. mapEquals(item.selectedToppings, {}));
  814. if (existente != null) {
  815. setState(() {
  816. existente.cantidad++;
  817. });
  818. } else {
  819. Map<int, List<Producto>> toppingsSeleccionables =
  820. await obtenerToppingsSeleccionables(producto);
  821. setState(() {
  822. carrito.add(ItemCarrito(
  823. producto: producto,
  824. cantidad: 1,
  825. selectableToppings: toppingsSeleccionables,
  826. ));
  827. });
  828. }
  829. _recalcularTotal();
  830. }
  831. Future<Map<int, List<Producto>>> obtenerToppingsSeleccionables(
  832. Producto producto) async {
  833. Map<int, List<Producto>> toppingsSeleccionables = {};
  834. final toppingCategories =
  835. await pvm.obtenerToppingsPorProducto(producto.id!);
  836. for (int toppingId in toppingCategories) {
  837. Producto? topping = await pvm.obtenerProductoPorId(toppingId);
  838. if (topping != null && topping.idCategoria != null) {
  839. toppingsSeleccionables[topping.idCategoria!] ??= [];
  840. toppingsSeleccionables[topping.idCategoria]!.add(topping);
  841. }
  842. }
  843. return toppingsSeleccionables;
  844. }
  845. void quitarDelCarrito(Producto producto) {
  846. setState(() {
  847. var indice =
  848. carrito.indexWhere((item) => item.producto.id == producto.id);
  849. if (indice != -1) {
  850. if (carrito[indice].cantidad > 1) {
  851. carrito[indice].cantidad--;
  852. } else {
  853. carrito.removeAt(indice);
  854. }
  855. }
  856. });
  857. }
  858. void addToCart(Producto producto) {
  859. var existingIndex = carrito.indexWhere((item) =>
  860. item.producto.id == producto.id &&
  861. mapEquals(item.selectedToppings, {}));
  862. if (existingIndex != -1) {
  863. setState(() {
  864. carrito[existingIndex].cantidad++;
  865. });
  866. } else {
  867. setState(() {
  868. carrito.add(ItemCarrito(producto: producto, cantidad: 1));
  869. });
  870. }
  871. }
  872. void finalizeCustomization() {
  873. if (_productoActual != null) {
  874. addToCart(_productoActual!);
  875. setState(() {
  876. _productoActual = null;
  877. });
  878. }
  879. }
  880. Widget _buildDiscountSection() {
  881. return Padding(
  882. padding: const EdgeInsets.symmetric(horizontal: 8.0),
  883. child: Row(
  884. crossAxisAlignment: CrossAxisAlignment.center,
  885. children: [
  886. const Text(
  887. 'Descuento',
  888. style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
  889. ),
  890. const Spacer(),
  891. ConstrainedBox(
  892. constraints: const BoxConstraints(
  893. maxWidth: 150,
  894. ),
  895. child: Consumer<DescuentoViewModel>(
  896. builder: (context, viewModel, child) {
  897. return AppDropdownModel<int>(
  898. hint: 'Seleccionar',
  899. items: viewModel.descuentos
  900. .map(
  901. (descuento) => DropdownMenuItem<int>(
  902. value: descuento.porcentaje,
  903. child: Text(
  904. '${descuento.porcentaje}%',
  905. style: const TextStyle(color: Colors.black),
  906. ),
  907. ),
  908. )
  909. .toList(),
  910. selectedValue: selectedDescuento,
  911. onChanged: (value) {
  912. setState(() {
  913. selectedDescuento = value;
  914. _recalcularTotal();
  915. });
  916. },
  917. );
  918. },
  919. ),
  920. ),
  921. ],
  922. ),
  923. );
  924. }
  925. Widget _buildTotalSection() {
  926. String formattedsubtotal = _numberFormat.format(subtotal);
  927. String formattedPrecioDescuento = _numberFormat.format(precioDescuento);
  928. String formattedtotalPedido = _numberFormat.format(totalPedido);
  929. return Padding(
  930. padding: const EdgeInsets.symmetric(horizontal: 8.0),
  931. child: Column(
  932. crossAxisAlignment: CrossAxisAlignment.start,
  933. children: [
  934. if (precioDescuento > 0)
  935. Column(
  936. children: [
  937. Row(
  938. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  939. children: [
  940. const Text('Subtotal',
  941. style: TextStyle(
  942. fontWeight: FontWeight.bold, fontSize: 18)),
  943. Text("\$$formattedsubtotal",
  944. style: const TextStyle(
  945. fontWeight: FontWeight.bold, fontSize: 18)),
  946. ],
  947. ),
  948. const SizedBox(height: 10),
  949. Row(
  950. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  951. children: [
  952. const Text('Descuento',
  953. style: TextStyle(
  954. fontWeight: FontWeight.bold, fontSize: 18)),
  955. Text("-\$$formattedPrecioDescuento",
  956. style: const TextStyle(
  957. fontWeight: FontWeight.bold, fontSize: 18)),
  958. ],
  959. ),
  960. ],
  961. ),
  962. const SizedBox(height: 10),
  963. Row(
  964. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  965. children: [
  966. const Text('Total',
  967. style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
  968. Text("\$$formattedtotalPedido",
  969. style: const TextStyle(
  970. fontWeight: FontWeight.bold, fontSize: 18)),
  971. ],
  972. ),
  973. ],
  974. ),
  975. );
  976. }
  977. @override
  978. Widget build(BuildContext context) {
  979. return Scaffold(
  980. appBar: AppBar(
  981. title:
  982. Text("Crear Pedido", style: TextStyle(color: AppTheme.secondary)),
  983. iconTheme: IconThemeData(color: AppTheme.secondary)),
  984. body: Row(
  985. children: [
  986. Flexible(
  987. flex: 3,
  988. child: _buildCartSection(),
  989. ),
  990. SizedBox(width: 35),
  991. Flexible(flex: 7, child: _buildProductsSection()),
  992. ],
  993. ),
  994. );
  995. }
  996. Widget _buildCartSection() {
  997. return Card(
  998. margin: const EdgeInsets.all(8.0),
  999. child: Column(
  1000. children: [
  1001. const Padding(
  1002. padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 16.0),
  1003. child: Row(
  1004. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  1005. children: [
  1006. Text('Producto',
  1007. style:
  1008. TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
  1009. Text('Cantidad',
  1010. style:
  1011. TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
  1012. ],
  1013. ),
  1014. ),
  1015. Expanded(
  1016. child: ListView.builder(
  1017. itemCount: carrito.length,
  1018. itemBuilder: (context, index) {
  1019. final item = carrito[index];
  1020. return Column(
  1021. children: [
  1022. ListTile(
  1023. title: Text(item.producto.nombre!,
  1024. style: const TextStyle(fontWeight: FontWeight.w600)),
  1025. subtitle: Text('\$${item.producto.precio}',
  1026. style: const TextStyle(
  1027. fontWeight: FontWeight.bold,
  1028. color: Color(0xFF008000))),
  1029. trailing: Row(
  1030. mainAxisSize: MainAxisSize.min,
  1031. children: [
  1032. IconButton(
  1033. icon: const Icon(Icons.delete, color: Colors.red),
  1034. onPressed: () =>
  1035. eliminarProductoDelCarrito(index)),
  1036. IconButton(
  1037. icon: const Icon(Icons.remove),
  1038. onPressed: () => quitarProductoDelCarrito(item)),
  1039. const SizedBox(width: 5),
  1040. Text('${item.cantidad}',
  1041. style: const TextStyle(
  1042. fontWeight: FontWeight.bold, fontSize: 14)),
  1043. const SizedBox(width: 5),
  1044. IconButton(
  1045. icon: const Icon(Icons.add),
  1046. onPressed: () => incrementarProducto(item)),
  1047. ],
  1048. ),
  1049. ),
  1050. // ExpansionTile para todos los toppings
  1051. if (item.selectableToppings.isNotEmpty)
  1052. ExpansionTile(
  1053. title: const Text(
  1054. 'Toppings',
  1055. style: TextStyle(
  1056. fontWeight: FontWeight.bold, fontSize: 16),
  1057. ),
  1058. children: item.selectableToppings.entries.map((entry) {
  1059. final categoryId = entry.key;
  1060. final availableToppings = entry.value;
  1061. final categoria =
  1062. categorias.firstWhere((c) => c.id == categoryId);
  1063. return ExpansionTile(
  1064. initiallyExpanded: true,
  1065. title: Text(
  1066. categoria.nombre!,
  1067. style: const TextStyle(
  1068. fontWeight: FontWeight.bold, fontSize: 16),
  1069. ),
  1070. children: availableToppings.map((topping) {
  1071. bool isSelected = item
  1072. .selectedToppings[categoryId]
  1073. ?.contains(topping.id) ??
  1074. false;
  1075. return CheckboxListTile(
  1076. activeColor: AppTheme.primary,
  1077. title: Row(
  1078. mainAxisAlignment:
  1079. MainAxisAlignment.spaceBetween,
  1080. children: [
  1081. Text(topping.nombre!),
  1082. if (topping.precio != 0.0)
  1083. Text(
  1084. '+\$${topping.precio}',
  1085. style: const TextStyle(
  1086. color: Colors.black,
  1087. fontSize: 13,
  1088. ),
  1089. ),
  1090. ],
  1091. ),
  1092. value: isSelected,
  1093. onChanged: (bool? value) {
  1094. final maximoToppings = categoria.maximo ?? 0;
  1095. setState(() {
  1096. if (value == true) {
  1097. if ((item.selectedToppings[categoryId]
  1098. ?.length ??
  1099. 0) >=
  1100. maximoToppings) {
  1101. item.selectedToppings[categoryId]!
  1102. .remove(item
  1103. .selectedToppings[categoryId]!
  1104. .first);
  1105. }
  1106. item.selectedToppings[categoryId] ??=
  1107. <int>{};
  1108. item.selectedToppings[categoryId]!
  1109. .add(topping.id!);
  1110. } else {
  1111. item.selectedToppings[categoryId]
  1112. ?.remove(topping.id!);
  1113. if (item.selectedToppings[categoryId]
  1114. ?.isEmpty ??
  1115. false) {
  1116. item.selectedToppings
  1117. .remove(categoryId);
  1118. }
  1119. }
  1120. _recalcularTotal();
  1121. });
  1122. },
  1123. );
  1124. }).toList(),
  1125. );
  1126. }).toList(),
  1127. ),
  1128. const Divider(),
  1129. ],
  1130. );
  1131. },
  1132. ),
  1133. ),
  1134. _buildDiscountSection(),
  1135. const Divider(thickness: 5),
  1136. _buildTotalSection(),
  1137. const SizedBox(height: 25),
  1138. Padding(
  1139. padding: const EdgeInsets.all(8.0),
  1140. child: ElevatedButton(
  1141. onPressed: _finalizeOrder,
  1142. style: ElevatedButton.styleFrom(
  1143. backgroundColor: AppTheme.tertiary,
  1144. textStyle: const TextStyle(fontSize: 22),
  1145. fixedSize: const Size(250, 50),
  1146. ),
  1147. child: Text('Finalizar Pedido',
  1148. style: TextStyle(color: AppTheme.quaternary)),
  1149. ),
  1150. ),
  1151. ],
  1152. ),
  1153. );
  1154. }
  1155. void eliminarProductoDelCarrito(int index) {
  1156. setState(() {
  1157. carrito.removeAt(index);
  1158. });
  1159. _recalcularTotal();
  1160. }
  1161. void incrementarProducto(ItemCarrito item) {
  1162. setState(() {
  1163. item.cantidad++;
  1164. });
  1165. _recalcularTotal();
  1166. }
  1167. void quitarProductoDelCarrito(ItemCarrito item) {
  1168. setState(() {
  1169. if (item.cantidad > 1) {
  1170. item.cantidad--;
  1171. } else {
  1172. carrito.remove(item);
  1173. }
  1174. });
  1175. _recalcularTotal();
  1176. }
  1177. Widget _buildProductsSection() {
  1178. return Column(
  1179. children: [
  1180. const SizedBox(height: 5),
  1181. _buildSearchBar(),
  1182. const SizedBox(height: 10),
  1183. _buildCategoryButtons(),
  1184. const SizedBox(height: 15),
  1185. Expanded(
  1186. child: Consumer<ProductoViewModel>(builder: (context, model, child) {
  1187. productos = model.productos;
  1188. return GridView.builder(
  1189. controller: _gridViewController,
  1190. key: ValueKey<int>(categoriaSeleccionada?.id ?? 0),
  1191. gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
  1192. crossAxisCount: 3,
  1193. childAspectRatio: 3 / 2,
  1194. ),
  1195. itemCount: productos.length,
  1196. itemBuilder: (context, index) {
  1197. final producto = productos[index];
  1198. // Si no se está buscando, aplicar el filtro de categoría
  1199. if (!_estadoBusqueda &&
  1200. producto.idCategoria != categoriaSeleccionada?.id) {
  1201. return Container();
  1202. }
  1203. return Card(
  1204. child: InkWell(
  1205. onTap: () => agregarAlCarrito(producto),
  1206. child: Column(
  1207. mainAxisAlignment: MainAxisAlignment.center,
  1208. children: [
  1209. if (producto.imagen != null &&
  1210. File(producto.imagen!).existsSync())
  1211. Image.file(
  1212. File(producto.imagen!),
  1213. height: 120,
  1214. fit: BoxFit.cover,
  1215. )
  1216. else
  1217. const Icon(Icons.fastfood, size: 80),
  1218. const SizedBox(height: 8),
  1219. Padding(
  1220. padding: const EdgeInsets.symmetric(horizontal: 8.0),
  1221. child: Text(
  1222. producto.nombre ?? '',
  1223. style: const TextStyle(
  1224. fontSize: 16,
  1225. fontWeight: FontWeight.bold,
  1226. ),
  1227. textAlign: TextAlign.center,
  1228. ),
  1229. ),
  1230. const SizedBox(height: 8),
  1231. Text(
  1232. '\$${producto.precio}',
  1233. style: const TextStyle(
  1234. fontSize: 16,
  1235. fontWeight: FontWeight.bold,
  1236. color: Color(0xFF008000),
  1237. ),
  1238. ),
  1239. ],
  1240. ),
  1241. ),
  1242. );
  1243. },
  1244. );
  1245. }),
  1246. )
  1247. ],
  1248. );
  1249. }
  1250. Widget _buildCategoryButtons() {
  1251. List<CategoriaProducto> categoriasFiltradas =
  1252. categorias.where((categoria) => categoria.esToping == 0).toList();
  1253. return Container(
  1254. height: 50,
  1255. child: Scrollbar(
  1256. thumbVisibility: true,
  1257. trackVisibility: true,
  1258. interactive: true,
  1259. controller: _categoryScrollController,
  1260. child: ListView.builder(
  1261. controller: _categoryScrollController,
  1262. scrollDirection: Axis.horizontal,
  1263. itemCount: categoriasFiltradas.length,
  1264. itemBuilder: (context, index) {
  1265. final categoria = categoriasFiltradas[index];
  1266. bool isSelected = categoriaSeleccionada?.id == categoria.id;
  1267. return Padding(
  1268. padding: const EdgeInsets.symmetric(horizontal: 4.0),
  1269. child: ElevatedButton(
  1270. onPressed: () {
  1271. cargarProductosPorCategoria(categoria.id);
  1272. setState(() {
  1273. categoriaSeleccionada = categoria;
  1274. });
  1275. },
  1276. style: ElevatedButton.styleFrom(
  1277. backgroundColor: isSelected ? AppTheme.tertiary : Colors.grey,
  1278. foregroundColor:
  1279. isSelected ? AppTheme.quaternary : AppTheme.secondary,
  1280. ),
  1281. child: Text(categoria.nombre!),
  1282. ),
  1283. );
  1284. },
  1285. ),
  1286. ),
  1287. );
  1288. }
  1289. Widget _buildSearchBar() {
  1290. return Padding(
  1291. padding: const EdgeInsets.all(8.0),
  1292. child: TextField(
  1293. controller: _searchController,
  1294. decoration: InputDecoration(
  1295. hintText: 'Buscar producto...',
  1296. prefixIcon: const Icon(Icons.search),
  1297. suffixIcon: IconButton(
  1298. icon: Icon(Icons.clear),
  1299. onPressed: () {
  1300. _searchController.clear();
  1301. _onSearchChanged('');
  1302. },
  1303. ),
  1304. border: OutlineInputBorder(
  1305. borderRadius: BorderRadius.circular(12.0),
  1306. ),
  1307. enabledBorder: OutlineInputBorder(
  1308. borderRadius: BorderRadius.circular(12.0),
  1309. borderSide: BorderSide(width: 1.5)),
  1310. focusedBorder: OutlineInputBorder(
  1311. borderSide: BorderSide(color: Colors.black),
  1312. borderRadius: BorderRadius.circular(12.0),
  1313. ),
  1314. ),
  1315. onChanged: _onSearchChanged,
  1316. ),
  1317. );
  1318. }
  1319. }