pedido_screen.dart 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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_JoshiPapas_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. await Navigator.push(
  395. context,
  396. MaterialPageRoute(
  397. builder: (context) => PedidoForm(),
  398. ),
  399. ).then((_) =>
  400. Provider.of<PedidoViewModel>(context, listen: false)
  401. .fetchLocalPedidosForScreen());
  402. },
  403. icon: Icon(Icons.add, size: 30, color: AppTheme.quaternary),
  404. label: Text(
  405. "Agregar Pedido",
  406. style: TextStyle(fontSize: 20, color: AppTheme.quaternary),
  407. ),
  408. shape: RoundedRectangleBorder(
  409. borderRadius: BorderRadius.circular(8),
  410. ),
  411. materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
  412. backgroundColor: AppTheme.tertiary,
  413. ),
  414. ),
  415. ],
  416. ),
  417. );
  418. }
  419. Widget _buildDateRangePicker() {
  420. return Row(
  421. children: [
  422. Expanded(
  423. flex: 3,
  424. child: AppTextField(
  425. prefixIcon: const Icon(Icons.search),
  426. etiqueta: 'Búsqueda por folio...',
  427. controller: _busqueda,
  428. hintText: 'Búsqueda por folio...',
  429. ),
  430. ),
  431. const SizedBox(width: 5),
  432. Expanded(
  433. flex: 3,
  434. child: clase.FechaSelectWidget(
  435. fecha: fechaInicio,
  436. onFechaChanged: (d) {
  437. setState(() {
  438. fechaInicio = d;
  439. });
  440. },
  441. etiqueta: "Fecha Inicial",
  442. context: context,
  443. ),
  444. ),
  445. const SizedBox(width: 5),
  446. Expanded(
  447. flex: 3,
  448. child: clase.FechaSelectWidget(
  449. fecha: fechaFin,
  450. onFechaChanged: (d) {
  451. setState(() {
  452. fechaFin = d;
  453. });
  454. },
  455. etiqueta: "Fecha Final",
  456. context: context,
  457. ),
  458. ),
  459. ],
  460. );
  461. }
  462. Widget botonBuscar() {
  463. return Expanded(
  464. flex: 2,
  465. child: Row(
  466. children: [
  467. Expanded(
  468. flex: 2,
  469. child: Padding(
  470. padding: const EdgeInsets.only(bottom: 5),
  471. child: ElevatedButton(
  472. onPressed: clearSearchAndReset,
  473. style: ElevatedButton.styleFrom(
  474. shape: RoundedRectangleBorder(
  475. borderRadius: BorderRadius.circular(20.0),
  476. ),
  477. primary: AppTheme.tertiary,
  478. padding: const EdgeInsets.symmetric(vertical: 25),
  479. ),
  480. child: Text('Limpiar',
  481. style: TextStyle(color: AppTheme.quaternary)),
  482. ),
  483. ),
  484. ),
  485. const SizedBox(width: 8),
  486. Expanded(
  487. flex: 2,
  488. child: Padding(
  489. padding: const EdgeInsets.only(bottom: 5),
  490. child: ElevatedButton(
  491. onPressed: () async {
  492. if (_busqueda.text.isNotEmpty) {
  493. await Provider.of<PedidoViewModel>(context, listen: false)
  494. .buscarPedidosPorFolio(_busqueda.text.trim());
  495. } else if (fechaInicio != null && fechaFin != null) {
  496. DateTime fechaInicioUTC = DateTime(fechaInicio!.year,
  497. fechaInicio!.month, fechaInicio!.day)
  498. .toUtc();
  499. DateTime fechaFinUTC = DateTime(fechaFin!.year,
  500. fechaFin!.month, fechaFin!.day, 23, 59, 59)
  501. .toUtc();
  502. await Provider.of<PedidoViewModel>(context, listen: false)
  503. .buscarPedidosPorFecha(fechaInicioUTC, fechaFinUTC);
  504. } else {
  505. ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
  506. content: Text(
  507. 'Introduce un folio o selecciona un rango de fechas para buscar.')));
  508. }
  509. },
  510. style: ElevatedButton.styleFrom(
  511. shape: RoundedRectangleBorder(
  512. borderRadius: BorderRadius.circular(20.0),
  513. ),
  514. primary: AppTheme.tertiary,
  515. padding: const EdgeInsets.symmetric(vertical: 25),
  516. ),
  517. child: Text('Buscar',
  518. style: TextStyle(color: AppTheme.quaternary)),
  519. ),
  520. ),
  521. ),
  522. ],
  523. ),
  524. );
  525. }
  526. void alertaSync(BuildContext context) {
  527. showDialog(
  528. context: context,
  529. builder: (BuildContext context) {
  530. return AlertDialog(
  531. title: const Text('Confirmación',
  532. style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22)),
  533. content: const Text('¿Deseas sincronizar todos los pedidos de nuevo?',
  534. style: TextStyle(fontSize: 18)),
  535. actions: [
  536. Row(
  537. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  538. children: [
  539. TextButton(
  540. child: const Text('No', style: TextStyle(fontSize: 18)),
  541. style: ButtonStyle(
  542. padding: MaterialStatePropertyAll(
  543. EdgeInsets.fromLTRB(20, 10, 20, 10)),
  544. backgroundColor: MaterialStatePropertyAll(Colors.red),
  545. foregroundColor:
  546. MaterialStatePropertyAll(AppTheme.secondary)),
  547. onPressed: () {
  548. Navigator.of(context).pop();
  549. },
  550. ),
  551. TextButton(
  552. child: const Text('Sí', style: TextStyle(fontSize: 18)),
  553. style: ButtonStyle(
  554. padding: MaterialStatePropertyAll(
  555. EdgeInsets.fromLTRB(20, 10, 20, 10)),
  556. backgroundColor:
  557. MaterialStatePropertyAll(AppTheme.tertiary),
  558. foregroundColor:
  559. MaterialStatePropertyAll(AppTheme.quaternary)),
  560. onPressed: () {
  561. // No hace nada por el momento
  562. Navigator.of(context).pop();
  563. },
  564. ),
  565. ],
  566. )
  567. ],
  568. );
  569. },
  570. );
  571. }
  572. String _formatDateTime(String? dateTimeString) {
  573. if (dateTimeString == null) return "Sin fecha";
  574. DateTime parsedDate = DateTime.parse(dateTimeString);
  575. var formatter = DateFormat('dd-MM-yyyy HH:mm:ss');
  576. return formatter.format(parsedDate.toLocal());
  577. }
  578. }