pedido_screen.dart 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. import 'package:flutter/material.dart';
  2. import 'package:intl/intl.dart';
  3. import 'package:omni_datetime_picker/omni_datetime_picker.dart';
  4. import 'package:provider/provider.dart';
  5. import '../pedido/pedido_csv.dart';
  6. import '../pedido/pedido_detalle_screen.dart';
  7. import '../../widgets/widgets.dart';
  8. import '../../themes/themes.dart';
  9. import '../../models/models.dart';
  10. import '../../viewmodels/viewmodels.dart';
  11. import '../../widgets/widgets_components.dart' as clase;
  12. import 'pedido_form.dart';
  13. class PedidoScreen extends StatefulWidget {
  14. const PedidoScreen({Key? key}) : super(key: key);
  15. @override
  16. State<PedidoScreen> createState() => _PedidoScreenState();
  17. }
  18. class _PedidoScreenState extends State<PedidoScreen> {
  19. final _busqueda = TextEditingController(text: '');
  20. DateTime? fechaInicio;
  21. DateTime? fechaFin;
  22. ScrollController horizontalScrollController = ScrollController();
  23. @override
  24. void initState() {
  25. super.initState();
  26. WidgetsBinding.instance.addPostFrameCallback((_) {
  27. Provider.of<PedidoViewModel>(context, listen: false)
  28. .fetchLocalPedidosForScreen();
  29. });
  30. }
  31. void exportCSV() async {
  32. final pedidosViewModel =
  33. Provider.of<PedidoViewModel>(context, listen: false);
  34. List<Pedido> pedidosConProductos = [];
  35. for (Pedido pedido in pedidosViewModel.pedidos) {
  36. Pedido? pedidoConProductos =
  37. await pedidosViewModel.fetchPedidoConProductos(pedido.id);
  38. if (pedidoConProductos != null) {
  39. pedidosConProductos.add(pedidoConProductos);
  40. }
  41. }
  42. if (pedidosConProductos.isNotEmpty) {
  43. String fileName = 'Pedidos_Turquessa_POS';
  44. if (fechaInicio != null && fechaFin != null) {
  45. String startDateStr = DateFormat('dd-MM-yyyy').format(fechaInicio!);
  46. String endDateStr = DateFormat('dd-MM-yyyy').format(fechaFin!);
  47. fileName += '_${startDateStr}_al_${endDateStr}';
  48. }
  49. fileName += '.csv';
  50. await exportarPedidosACSV(pedidosConProductos, fileName);
  51. ScaffoldMessenger.of(context).showSnackBar(SnackBar(
  52. content: Text('Archivo CSV descargado! Archivo: $fileName')));
  53. } else {
  54. ScaffoldMessenger.of(context).showSnackBar(
  55. SnackBar(content: Text('No hay pedidos para exportar.')));
  56. }
  57. }
  58. void clearSearchAndReset() {
  59. setState(() {
  60. _busqueda.clear();
  61. fechaInicio = null;
  62. fechaFin = null;
  63. Provider.of<PedidoViewModel>(context, listen: false)
  64. .fetchLocalPedidosForScreen();
  65. });
  66. }
  67. void go(Pedido item) async {
  68. Pedido? pedidoCompleto =
  69. await Provider.of<PedidoViewModel>(context, listen: false)
  70. .fetchPedidoConProductos(item.id);
  71. if (pedidoCompleto != null) {
  72. Navigator.push(
  73. context,
  74. MaterialPageRoute(
  75. builder: (context) => PedidoDetalleScreen(pedido: pedidoCompleto),
  76. ),
  77. );
  78. } else {
  79. print("Error al cargar el pedido con productos");
  80. }
  81. }
  82. @override
  83. Widget build(BuildContext context) {
  84. final pvm = Provider.of<PedidoViewModel>(context);
  85. double screenWidth = MediaQuery.of(context).size.width;
  86. final isMobile = screenWidth < 1250;
  87. final double? columnSpacing = isMobile ? null : 0;
  88. TextStyle estilo = const TextStyle(fontWeight: FontWeight.bold);
  89. List<DataRow> registros = [];
  90. final permisoViewModel = Provider.of<PermisoViewModel>(context);
  91. List<String> userPermisos = permisoViewModel.userPermisos;
  92. for (Pedido item in pvm.pedidos) {
  93. final sincronizadoStatus =
  94. item.sincronizado == null || item.sincronizado!.isEmpty
  95. ? "No Sincronizado"
  96. : _formatDateTime(item.sincronizado);
  97. registros.add(DataRow(cells: [
  98. DataCell(
  99. Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
  100. PopupMenuButton(
  101. itemBuilder: (context) => [
  102. PopupMenuItem(
  103. child: const Text('Detalle'),
  104. onTap: () => go(item),
  105. ),
  106. if (userPermisos.contains(Usuario.CANCELAR_PEDIDO))
  107. PopupMenuItem(
  108. child: const Text('Cancelar Pedido'),
  109. onTap: () async {
  110. bool confirmado = await showDialog<bool>(
  111. context: context,
  112. builder: (context) {
  113. return AlertDialog(
  114. title: const Text("Cancelar Pedido",
  115. style: TextStyle(
  116. fontWeight: FontWeight.w500,
  117. fontSize: 22)),
  118. content: const Text(
  119. '¿Estás seguro de que deseas cancelar este pedido?',
  120. style: TextStyle(fontSize: 18)),
  121. actions: [
  122. Row(
  123. mainAxisAlignment:
  124. MainAxisAlignment.spaceBetween,
  125. children: [
  126. TextButton(
  127. onPressed: () =>
  128. Navigator.of(context).pop(false),
  129. child: const Text('No',
  130. style: TextStyle(fontSize: 18)),
  131. style: ButtonStyle(
  132. padding: MaterialStatePropertyAll(
  133. EdgeInsets.fromLTRB(
  134. 20, 10, 20, 10)),
  135. backgroundColor:
  136. MaterialStatePropertyAll(
  137. Colors.red),
  138. foregroundColor:
  139. MaterialStatePropertyAll(
  140. AppTheme.secondary)),
  141. ),
  142. TextButton(
  143. onPressed: () =>
  144. Navigator.of(context).pop(true),
  145. child: const Text('Sí',
  146. style: TextStyle(fontSize: 18)),
  147. style: ButtonStyle(
  148. padding: MaterialStatePropertyAll(
  149. EdgeInsets.fromLTRB(
  150. 20, 10, 20, 10)),
  151. backgroundColor:
  152. MaterialStatePropertyAll(
  153. AppTheme.tertiary),
  154. foregroundColor:
  155. MaterialStatePropertyAll(
  156. AppTheme.quaternary)),
  157. ),
  158. ],
  159. )
  160. ],
  161. );
  162. },
  163. ) ??
  164. false;
  165. if (confirmado) {
  166. await Provider.of<PedidoViewModel>(context, listen: false)
  167. .cancelarPedido(item.id);
  168. ScaffoldMessenger.of(context).showSnackBar(SnackBar(
  169. content: Text("Pedido cancelado correctamente")));
  170. }
  171. },
  172. )
  173. ],
  174. icon: const Icon(Icons.more_vert),
  175. )
  176. ])),
  177. DataCell(
  178. Text(item.folio.toString()),
  179. onTap: () => go(item),
  180. ),
  181. DataCell(
  182. Text(item.nombreCliente ?? "Sin nombre"),
  183. onTap: () => go(item),
  184. ),
  185. DataCell(
  186. Text(item.comentarios ?? "Sin comentarios"),
  187. onTap: () => go(item),
  188. ),
  189. DataCell(
  190. Text(item.estatus ?? "Sin Estatus"),
  191. onTap: () => go(item),
  192. ),
  193. DataCell(
  194. Text(_formatDateTime(item.peticion)),
  195. onTap: () => go(item),
  196. ),
  197. DataCell(
  198. Text(sincronizadoStatus),
  199. onTap: () => go(item),
  200. ),
  201. ]));
  202. }
  203. return Scaffold(
  204. appBar: AppBar(
  205. title: Text(
  206. 'Pedidos',
  207. style: TextStyle(
  208. color: AppTheme.secondary, fontWeight: FontWeight.w500),
  209. ),
  210. actions: <Widget>[
  211. if (userPermisos.contains(Usuario.VER_REPORTE))
  212. IconButton(
  213. icon: const Icon(Icons.save_alt),
  214. onPressed: exportCSV,
  215. tooltip: 'Exportar a CSV',
  216. ),
  217. ],
  218. iconTheme: IconThemeData(color: AppTheme.secondary)),
  219. body: Stack(
  220. children: [
  221. Column(
  222. children: [
  223. Expanded(
  224. child: ListView(
  225. padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
  226. children: [
  227. const SizedBox(height: 8),
  228. clase.tarjeta(
  229. Padding(
  230. padding: const EdgeInsets.all(8.0),
  231. child: LayoutBuilder(
  232. builder: (context, constraints) {
  233. if (screenWidth > 1000) {
  234. return Row(
  235. crossAxisAlignment: CrossAxisAlignment.end,
  236. children: [
  237. Expanded(
  238. flex: 7,
  239. child: _buildDateRangePicker(),
  240. ),
  241. const SizedBox(width: 5),
  242. botonBuscar()
  243. ],
  244. );
  245. } else {
  246. return Column(
  247. children: [
  248. Row(
  249. children: [_buildDateRangePicker()],
  250. ),
  251. Row(
  252. children: [botonBuscar()],
  253. ),
  254. ],
  255. );
  256. }
  257. },
  258. ),
  259. ),
  260. ),
  261. const SizedBox(height: 8),
  262. pvm.isLoading
  263. ? const Center(child: CircularProgressIndicator())
  264. : Container(),
  265. clase.tarjeta(
  266. Column(
  267. children: [
  268. LayoutBuilder(builder: (context, constraints) {
  269. return SingleChildScrollView(
  270. scrollDirection: Axis.vertical,
  271. child: Scrollbar(
  272. controller: horizontalScrollController,
  273. interactive: true,
  274. thumbVisibility: true,
  275. thickness: 10.0,
  276. child: SingleChildScrollView(
  277. controller: horizontalScrollController,
  278. scrollDirection: Axis.horizontal,
  279. child: ConstrainedBox(
  280. constraints: BoxConstraints(
  281. minWidth: isMobile
  282. ? constraints.maxWidth
  283. : screenWidth),
  284. child: DataTable(
  285. columnSpacing: columnSpacing,
  286. sortAscending: true,
  287. sortColumnIndex: 1,
  288. columns: [
  289. DataColumn(
  290. label: Text(" ", style: estilo)),
  291. DataColumn(
  292. label:
  293. Text("FOLIO", style: estilo)),
  294. DataColumn(
  295. label:
  296. Text("NOMBRE", style: estilo)),
  297. DataColumn(
  298. label: Text("COMENTARIOS",
  299. style: estilo)),
  300. DataColumn(
  301. label:
  302. Text("ESTATUS", style: estilo)),
  303. DataColumn(
  304. label:
  305. Text("FECHA", style: estilo)),
  306. DataColumn(
  307. label: Text("SINCRONIZADO",
  308. style: estilo)),
  309. ],
  310. rows: registros,
  311. ),
  312. ),
  313. ),
  314. ),
  315. );
  316. }),
  317. ],
  318. ),
  319. ),
  320. const SizedBox(height: 15),
  321. if (!pvm.isLoading)
  322. Row(
  323. mainAxisAlignment: MainAxisAlignment.center,
  324. children: [
  325. TextButton(
  326. onPressed:
  327. pvm.currentPage > 1 ? pvm.previousPage : null,
  328. child: Text('Anterior'),
  329. style: ButtonStyle(
  330. backgroundColor:
  331. MaterialStateProperty.resolveWith<Color?>(
  332. (Set<MaterialState> states) {
  333. if (states.contains(MaterialState.disabled)) {
  334. return Colors.grey;
  335. }
  336. return AppTheme.tertiary;
  337. },
  338. ),
  339. foregroundColor:
  340. MaterialStateProperty.resolveWith<Color?>(
  341. (Set<MaterialState> states) {
  342. if (states.contains(MaterialState.disabled)) {
  343. return Colors.black;
  344. }
  345. return Colors.white;
  346. },
  347. ),
  348. ),
  349. ),
  350. SizedBox(width: 15),
  351. Text(
  352. 'Página ${pvm.currentPage} de ${pvm.totalPages}'),
  353. SizedBox(width: 15),
  354. TextButton(
  355. onPressed: pvm.currentPage < pvm.totalPages
  356. ? pvm.nextPage
  357. : null,
  358. child: Text('Siguiente'),
  359. style: ButtonStyle(
  360. backgroundColor:
  361. MaterialStateProperty.resolveWith<Color?>(
  362. (Set<MaterialState> states) {
  363. if (states.contains(MaterialState.disabled)) {
  364. return Colors.grey;
  365. }
  366. return AppTheme.tertiary;
  367. },
  368. ),
  369. foregroundColor:
  370. MaterialStateProperty.resolveWith<Color?>(
  371. (Set<MaterialState> states) {
  372. if (states.contains(MaterialState.disabled)) {
  373. return Colors.black;
  374. }
  375. return Colors.white;
  376. },
  377. ),
  378. ),
  379. ),
  380. ],
  381. ),
  382. const SizedBox(height: 15),
  383. ],
  384. ),
  385. ),
  386. ],
  387. ),
  388. Positioned(
  389. bottom: 16,
  390. right: 16,
  391. child: FloatingActionButton.extended(
  392. heroTag: 'addPedido',
  393. onPressed: () async {
  394. final corteCajaViewModel =
  395. Provider.of<CorteCajaViewModel>(context, listen: false);
  396. if (corteCajaViewModel.hasOpenCorteCaja()) {
  397. await Navigator.push(
  398. context,
  399. MaterialPageRoute(
  400. builder: (context) => PedidoForm(),
  401. ),
  402. ).then((_) =>
  403. Provider.of<PedidoViewModel>(context, listen: false)
  404. .fetchLocalPedidosForScreen());
  405. } else {
  406. alerta(context,
  407. etiqueta:
  408. 'Solo se pueden realizar pedidos cuando se encuentre la caja abierta.');
  409. }
  410. },
  411. icon: Icon(Icons.add, size: 30, color: AppTheme.quaternary),
  412. label: Text(
  413. "Agregar Pedido",
  414. style: TextStyle(fontSize: 20, color: AppTheme.quaternary),
  415. ),
  416. shape: RoundedRectangleBorder(
  417. borderRadius: BorderRadius.circular(8),
  418. ),
  419. materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
  420. backgroundColor: AppTheme.tertiary,
  421. ),
  422. ),
  423. ],
  424. ),
  425. );
  426. }
  427. Widget _buildDateRangePicker() {
  428. return Row(
  429. children: [
  430. Expanded(
  431. flex: 3,
  432. child: AppTextField(
  433. prefixIcon: const Icon(Icons.search),
  434. etiqueta: 'Búsqueda por folio...',
  435. controller: _busqueda,
  436. hintText: 'Búsqueda por folio...',
  437. ),
  438. ),
  439. const SizedBox(width: 5),
  440. Expanded(
  441. flex: 3,
  442. child: clase.FechaSelectWidget(
  443. fecha: fechaInicio,
  444. onFechaChanged: (d) {
  445. setState(() {
  446. fechaInicio = d;
  447. });
  448. },
  449. etiqueta: "Fecha Inicial",
  450. context: context,
  451. ),
  452. ),
  453. const SizedBox(width: 5),
  454. Expanded(
  455. flex: 3,
  456. child: clase.FechaSelectWidget(
  457. fecha: fechaFin,
  458. onFechaChanged: (d) {
  459. setState(() {
  460. fechaFin = d;
  461. });
  462. },
  463. etiqueta: "Fecha Final",
  464. context: context,
  465. ),
  466. ),
  467. ],
  468. );
  469. }
  470. Widget botonBuscar() {
  471. return Expanded(
  472. flex: 2,
  473. child: Row(
  474. children: [
  475. Expanded(
  476. flex: 2,
  477. child: Padding(
  478. padding: const EdgeInsets.only(bottom: 5),
  479. child: ElevatedButton(
  480. onPressed: clearSearchAndReset,
  481. style: ElevatedButton.styleFrom(
  482. shape: RoundedRectangleBorder(
  483. borderRadius: BorderRadius.circular(20.0),
  484. ),
  485. primary: AppTheme.tertiary,
  486. padding: const EdgeInsets.symmetric(vertical: 25),
  487. ),
  488. child: Text('Limpiar',
  489. style: TextStyle(color: AppTheme.quaternary)),
  490. ),
  491. ),
  492. ),
  493. const SizedBox(width: 8),
  494. Expanded(
  495. flex: 2,
  496. child: Padding(
  497. padding: const EdgeInsets.only(bottom: 5),
  498. child: ElevatedButton(
  499. onPressed: () async {
  500. if (_busqueda.text.isNotEmpty) {
  501. await Provider.of<PedidoViewModel>(context, listen: false)
  502. .buscarPedidosPorFolio(_busqueda.text.trim());
  503. } else if (fechaInicio != null && fechaFin != null) {
  504. DateTime fechaInicioUTC = DateTime(fechaInicio!.year,
  505. fechaInicio!.month, fechaInicio!.day)
  506. .toUtc();
  507. DateTime fechaFinUTC = DateTime(fechaFin!.year,
  508. fechaFin!.month, fechaFin!.day, 23, 59, 59)
  509. .toUtc();
  510. await Provider.of<PedidoViewModel>(context, listen: false)
  511. .buscarPedidosPorFecha(fechaInicioUTC, fechaFinUTC);
  512. } else {
  513. ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
  514. content: Text(
  515. 'Introduce un folio o selecciona un rango de fechas para buscar.')));
  516. }
  517. },
  518. style: ElevatedButton.styleFrom(
  519. shape: RoundedRectangleBorder(
  520. borderRadius: BorderRadius.circular(20.0),
  521. ),
  522. primary: AppTheme.tertiary,
  523. padding: const EdgeInsets.symmetric(vertical: 25),
  524. ),
  525. child: Text('Buscar',
  526. style: TextStyle(color: AppTheme.quaternary)),
  527. ),
  528. ),
  529. ),
  530. ],
  531. ),
  532. );
  533. }
  534. void alertaSync(BuildContext context) {
  535. showDialog(
  536. context: context,
  537. builder: (BuildContext context) {
  538. return AlertDialog(
  539. title: const Text('Confirmación',
  540. style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22)),
  541. content: const Text('¿Deseas sincronizar todos los pedidos de nuevo?',
  542. style: TextStyle(fontSize: 18)),
  543. actions: [
  544. Row(
  545. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  546. children: [
  547. TextButton(
  548. child: const Text('No', style: TextStyle(fontSize: 18)),
  549. style: ButtonStyle(
  550. padding: MaterialStatePropertyAll(
  551. EdgeInsets.fromLTRB(20, 10, 20, 10)),
  552. backgroundColor: MaterialStatePropertyAll(Colors.red),
  553. foregroundColor:
  554. MaterialStatePropertyAll(AppTheme.secondary)),
  555. onPressed: () {
  556. Navigator.of(context).pop();
  557. },
  558. ),
  559. TextButton(
  560. child: const Text('Sí', style: TextStyle(fontSize: 18)),
  561. style: ButtonStyle(
  562. padding: MaterialStatePropertyAll(
  563. EdgeInsets.fromLTRB(20, 10, 20, 10)),
  564. backgroundColor:
  565. MaterialStatePropertyAll(AppTheme.tertiary),
  566. foregroundColor:
  567. MaterialStatePropertyAll(AppTheme.quaternary)),
  568. onPressed: () {
  569. // No hace nada por el momento
  570. Navigator.of(context).pop();
  571. },
  572. ),
  573. ],
  574. )
  575. ],
  576. );
  577. },
  578. );
  579. }
  580. String _formatDateTime(String? dateTimeString) {
  581. if (dateTimeString == null) return "Sin fecha";
  582. DateTime parsedDate = DateTime.parse(dateTimeString);
  583. var formatter = DateFormat('dd-MM-yyyy HH:mm:ss');
  584. return formatter.format(parsedDate.toLocal());
  585. }
  586. }