pedido_form.dart 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  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: "TERMINADO",
  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. initiallyExpanded: true,
  1054. title: const Text(
  1055. 'Toppings',
  1056. style: TextStyle(
  1057. fontWeight: FontWeight.bold, fontSize: 16),
  1058. ),
  1059. children: item.selectableToppings.entries.map((entry) {
  1060. final categoryId = entry.key;
  1061. final availableToppings = entry.value;
  1062. final categoria =
  1063. categorias.firstWhere((c) => c.id == categoryId);
  1064. return ExpansionTile(
  1065. initiallyExpanded: true,
  1066. title: Text(
  1067. '${categoria.nombre} (Hasta ${categoria.maximo ?? 0})',
  1068. style: const TextStyle(
  1069. fontWeight: FontWeight.bold, fontSize: 16),
  1070. ),
  1071. children: availableToppings.map((topping) {
  1072. bool isSelected = item
  1073. .selectedToppings[categoryId]
  1074. ?.contains(topping.id) ??
  1075. false;
  1076. return CheckboxListTile(
  1077. activeColor: AppTheme.primary,
  1078. title: Row(
  1079. mainAxisAlignment:
  1080. MainAxisAlignment.spaceBetween,
  1081. children: [
  1082. Text(topping.nombre!),
  1083. if (topping.precio != 0.0)
  1084. Text(
  1085. '+\$${topping.precio}',
  1086. style: const TextStyle(
  1087. color: Colors.black,
  1088. fontSize: 13,
  1089. ),
  1090. ),
  1091. ],
  1092. ),
  1093. value: isSelected,
  1094. onChanged: (bool? value) {
  1095. final maximoToppings = categoria.maximo ?? 0;
  1096. setState(() {
  1097. if (value == true) {
  1098. if ((item.selectedToppings[categoryId]
  1099. ?.length ??
  1100. 0) >=
  1101. maximoToppings) {
  1102. item.selectedToppings[categoryId]!
  1103. .remove(item
  1104. .selectedToppings[categoryId]!
  1105. .first);
  1106. }
  1107. item.selectedToppings[categoryId] ??=
  1108. <int>{};
  1109. item.selectedToppings[categoryId]!
  1110. .add(topping.id!);
  1111. } else {
  1112. item.selectedToppings[categoryId]
  1113. ?.remove(topping.id!);
  1114. if (item.selectedToppings[categoryId]
  1115. ?.isEmpty ??
  1116. false) {
  1117. item.selectedToppings
  1118. .remove(categoryId);
  1119. }
  1120. }
  1121. _recalcularTotal();
  1122. });
  1123. },
  1124. );
  1125. }).toList(),
  1126. );
  1127. }).toList(),
  1128. ),
  1129. const Divider(),
  1130. ],
  1131. );
  1132. },
  1133. ),
  1134. ),
  1135. _buildDiscountSection(),
  1136. const Divider(thickness: 5),
  1137. _buildTotalSection(),
  1138. const SizedBox(height: 25),
  1139. Padding(
  1140. padding: const EdgeInsets.all(8.0),
  1141. child: ElevatedButton(
  1142. onPressed: _finalizeOrder,
  1143. style: ElevatedButton.styleFrom(
  1144. backgroundColor: AppTheme.tertiary,
  1145. textStyle: const TextStyle(fontSize: 22),
  1146. fixedSize: const Size(250, 50),
  1147. ),
  1148. child: Text('Finalizar Pedido',
  1149. style: TextStyle(color: AppTheme.quaternary)),
  1150. ),
  1151. ),
  1152. ],
  1153. ),
  1154. );
  1155. }
  1156. void eliminarProductoDelCarrito(int index) {
  1157. setState(() {
  1158. carrito.removeAt(index);
  1159. });
  1160. _recalcularTotal();
  1161. }
  1162. void incrementarProducto(ItemCarrito item) {
  1163. setState(() {
  1164. item.cantidad++;
  1165. });
  1166. _recalcularTotal();
  1167. }
  1168. void quitarProductoDelCarrito(ItemCarrito item) {
  1169. setState(() {
  1170. if (item.cantidad > 1) {
  1171. item.cantidad--;
  1172. } else {
  1173. carrito.remove(item);
  1174. }
  1175. });
  1176. _recalcularTotal();
  1177. }
  1178. Widget _buildProductsSection() {
  1179. return Column(
  1180. children: [
  1181. const SizedBox(height: 5),
  1182. _buildSearchBar(),
  1183. const SizedBox(height: 10),
  1184. _buildCategoryButtons(),
  1185. const SizedBox(height: 15),
  1186. Expanded(
  1187. child: Consumer<ProductoViewModel>(builder: (context, model, child) {
  1188. productos = model.productos;
  1189. return GridView.builder(
  1190. controller: _gridViewController,
  1191. key: ValueKey<int>(categoriaSeleccionada?.id ?? 0),
  1192. gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
  1193. crossAxisCount: 3,
  1194. childAspectRatio: 3 / 2,
  1195. ),
  1196. itemCount: productos.length,
  1197. itemBuilder: (context, index) {
  1198. final producto = productos[index];
  1199. // Si no se está buscando, aplicar el filtro de categoría
  1200. if (!_estadoBusqueda &&
  1201. producto.idCategoria != categoriaSeleccionada?.id) {
  1202. return Container();
  1203. }
  1204. return Card(
  1205. child: InkWell(
  1206. onTap: () => agregarAlCarrito(producto),
  1207. child: Column(
  1208. mainAxisAlignment: MainAxisAlignment.center,
  1209. children: [
  1210. if (producto.imagen != null &&
  1211. File(producto.imagen!).existsSync())
  1212. Image.file(
  1213. File(producto.imagen!),
  1214. height: 120,
  1215. fit: BoxFit.cover,
  1216. )
  1217. else
  1218. const Icon(Icons.fastfood, size: 80),
  1219. const SizedBox(height: 8),
  1220. Padding(
  1221. padding: const EdgeInsets.symmetric(horizontal: 8.0),
  1222. child: Text(
  1223. producto.nombre ?? '',
  1224. style: const TextStyle(
  1225. fontSize: 16,
  1226. fontWeight: FontWeight.bold,
  1227. ),
  1228. textAlign: TextAlign.center,
  1229. ),
  1230. ),
  1231. const SizedBox(height: 8),
  1232. Text(
  1233. '\$${producto.precio}',
  1234. style: const TextStyle(
  1235. fontSize: 16,
  1236. fontWeight: FontWeight.bold,
  1237. color: Color(0xFF008000),
  1238. ),
  1239. ),
  1240. ],
  1241. ),
  1242. ),
  1243. );
  1244. },
  1245. );
  1246. }),
  1247. )
  1248. ],
  1249. );
  1250. }
  1251. Widget _buildCategoryButtons() {
  1252. List<CategoriaProducto> categoriasFiltradas =
  1253. categorias.where((categoria) => categoria.esToping == 0).toList();
  1254. return Container(
  1255. height: 50,
  1256. child: Scrollbar(
  1257. thumbVisibility: true,
  1258. trackVisibility: true,
  1259. interactive: true,
  1260. controller: _categoryScrollController,
  1261. child: ListView.builder(
  1262. controller: _categoryScrollController,
  1263. scrollDirection: Axis.horizontal,
  1264. itemCount: categoriasFiltradas.length,
  1265. itemBuilder: (context, index) {
  1266. final categoria = categoriasFiltradas[index];
  1267. bool isSelected = categoriaSeleccionada?.id == categoria.id;
  1268. return Padding(
  1269. padding: const EdgeInsets.symmetric(horizontal: 4.0),
  1270. child: ElevatedButton(
  1271. onPressed: () {
  1272. cargarProductosPorCategoria(categoria.id);
  1273. setState(() {
  1274. categoriaSeleccionada = categoria;
  1275. });
  1276. },
  1277. style: ElevatedButton.styleFrom(
  1278. backgroundColor: isSelected ? AppTheme.tertiary : Colors.grey,
  1279. foregroundColor:
  1280. isSelected ? AppTheme.quaternary : AppTheme.secondary,
  1281. ),
  1282. child: Text(categoria.nombre!),
  1283. ),
  1284. );
  1285. },
  1286. ),
  1287. ),
  1288. );
  1289. }
  1290. Widget _buildSearchBar() {
  1291. return Padding(
  1292. padding: const EdgeInsets.all(8.0),
  1293. child: TextField(
  1294. controller: _searchController,
  1295. decoration: InputDecoration(
  1296. hintText: 'Buscar producto...',
  1297. prefixIcon: const Icon(Icons.search),
  1298. suffixIcon: IconButton(
  1299. icon: Icon(Icons.clear),
  1300. onPressed: () {
  1301. _searchController.clear();
  1302. _onSearchChanged('');
  1303. },
  1304. ),
  1305. border: OutlineInputBorder(
  1306. borderRadius: BorderRadius.circular(12.0),
  1307. ),
  1308. enabledBorder: OutlineInputBorder(
  1309. borderRadius: BorderRadius.circular(12.0),
  1310. borderSide: BorderSide(width: 1.5)),
  1311. focusedBorder: OutlineInputBorder(
  1312. borderSide: BorderSide(color: Colors.black),
  1313. borderRadius: BorderRadius.circular(12.0),
  1314. ),
  1315. ),
  1316. onChanged: _onSearchChanged,
  1317. ),
  1318. );
  1319. }
  1320. }