pedido_screen.dart 23 KB

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