pedido_screen.dart 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. import 'pedido_sync.dart';
  14. class PedidoScreen extends StatefulWidget {
  15. const PedidoScreen({Key? key}) : super(key: key);
  16. @override
  17. State<PedidoScreen> createState() => _PedidoScreenState();
  18. }
  19. class _PedidoScreenState extends State<PedidoScreen> {
  20. final _busqueda = TextEditingController(text: '');
  21. DateTime? fechaInicio;
  22. DateTime? fechaFin;
  23. ScrollController horizontalScrollController = ScrollController();
  24. @override
  25. void initState() {
  26. super.initState();
  27. WidgetsBinding.instance.addPostFrameCallback((_) {
  28. Provider.of<PedidoViewModel>(context, listen: false)
  29. .fetchLocalPedidosForScreen();
  30. });
  31. }
  32. void exportCSV() async {
  33. final pedidosViewModel =
  34. Provider.of<PedidoViewModel>(context, listen: false);
  35. List<Pedido> pedidosConProductos = [];
  36. for (Pedido pedido in pedidosViewModel.pedidos) {
  37. Pedido? pedidoConProductos =
  38. await pedidosViewModel.fetchPedidoConProductos(pedido.id);
  39. if (pedidoConProductos != null) {
  40. pedidosConProductos.add(pedidoConProductos);
  41. }
  42. }
  43. if (pedidosConProductos.isNotEmpty) {
  44. String fileName = 'Pedidos_OlivaMia_POS';
  45. if (fechaInicio != null && fechaFin != null) {
  46. String startDateStr = DateFormat('dd-MM-yyyy').format(fechaInicio!);
  47. String endDateStr = DateFormat('dd-MM-yyyy').format(fechaFin!);
  48. fileName += '_${startDateStr}_al_${endDateStr}';
  49. }
  50. fileName += '.csv';
  51. await exportarPedidosACSV(pedidosConProductos, fileName);
  52. ScaffoldMessenger.of(context).showSnackBar(SnackBar(
  53. content: Text('Archivo CSV descargado! Archivo: $fileName')));
  54. } else {
  55. ScaffoldMessenger.of(context).showSnackBar(
  56. SnackBar(content: Text('No hay pedidos para exportar.')));
  57. }
  58. }
  59. void clearSearchAndReset() {
  60. setState(() {
  61. _busqueda.clear();
  62. fechaInicio = null;
  63. fechaFin = null;
  64. Provider.of<PedidoViewModel>(context, listen: false)
  65. .fetchLocalPedidosForScreen();
  66. });
  67. }
  68. void go(Pedido item) async {
  69. Pedido? pedidoCompleto =
  70. await Provider.of<PedidoViewModel>(context, listen: false)
  71. .fetchPedidoConProductos(item.id);
  72. if (pedidoCompleto != null) {
  73. Navigator.push(
  74. context,
  75. MaterialPageRoute(
  76. builder: (context) => PedidoDetalleScreen(pedido: pedidoCompleto),
  77. ),
  78. );
  79. } else {
  80. print("Error al cargar el pedido con productos");
  81. }
  82. }
  83. @override
  84. Widget build(BuildContext context) {
  85. final pvm = Provider.of<PedidoViewModel>(context);
  86. double screenWidth = MediaQuery.of(context).size.width;
  87. final isMobile = screenWidth < 1250;
  88. final double? columnSpacing = isMobile ? null : 0;
  89. TextStyle estilo = const TextStyle(fontWeight: FontWeight.bold);
  90. List<DataRow> registros = [];
  91. for (Pedido item in pvm.pedidos) {
  92. final sincronizadoStatus = item.sincronizado?.isEmpty ?? true
  93. ? "No Sincronizado"
  94. : 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(item.peticion ?? "Sin fecha"),
  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. Positioned(
  411. bottom: 16,
  412. left: 16,
  413. child: FloatingActionButton.extended(
  414. heroTag: 'sincronizacion',
  415. onPressed: () {
  416. alerta(context, etiqueta: "Sincronización Empezada");
  417. PedidoSync().startSync(
  418. Provider.of<PedidoViewModel>(context, listen: false));
  419. },
  420. icon: Icon(Icons.sync, size: 30, color: AppTheme.quaternary),
  421. label: Text(
  422. "Sincronización",
  423. style: TextStyle(fontSize: 20, color: AppTheme.quaternary),
  424. ),
  425. shape: RoundedRectangleBorder(
  426. borderRadius: BorderRadius.circular(8),
  427. ),
  428. materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
  429. backgroundColor: AppTheme.tertiary,
  430. ),
  431. ),
  432. ],
  433. ),
  434. );
  435. }
  436. Widget _buildDateRangePicker() {
  437. return Row(
  438. children: [
  439. Expanded(
  440. flex: 3,
  441. child: AppTextField(
  442. prefixIcon: const Icon(Icons.search),
  443. etiqueta: 'Búsqueda por folio...',
  444. controller: _busqueda,
  445. hintText: 'Búsqueda por folio...',
  446. ),
  447. ),
  448. const SizedBox(width: 5),
  449. Expanded(
  450. flex: 3,
  451. child: clase.FechaSelectWidget(
  452. fecha: fechaInicio,
  453. onFechaChanged: (d) {
  454. setState(() {
  455. fechaInicio = d;
  456. });
  457. },
  458. etiqueta: "Fecha Inicial",
  459. context: context,
  460. ),
  461. ),
  462. const SizedBox(width: 5),
  463. Expanded(
  464. flex: 3,
  465. child: clase.FechaSelectWidget(
  466. fecha: fechaFin,
  467. onFechaChanged: (d) {
  468. setState(() {
  469. fechaFin = d;
  470. });
  471. },
  472. etiqueta: "Fecha Final",
  473. context: context,
  474. ),
  475. ),
  476. ],
  477. );
  478. }
  479. Widget botonBuscar() {
  480. return Expanded(
  481. flex: 2,
  482. child: Row(
  483. children: [
  484. Expanded(
  485. flex: 2,
  486. child: Padding(
  487. padding: const EdgeInsets.only(bottom: 5),
  488. child: ElevatedButton(
  489. onPressed: clearSearchAndReset,
  490. style: ElevatedButton.styleFrom(
  491. shape: RoundedRectangleBorder(
  492. borderRadius: BorderRadius.circular(20.0),
  493. ),
  494. primary: AppTheme.tertiary,
  495. padding: const EdgeInsets.symmetric(vertical: 25),
  496. ),
  497. child: Text('Limpiar',
  498. style: TextStyle(color: AppTheme.quaternary)),
  499. ),
  500. ),
  501. ),
  502. const SizedBox(width: 8),
  503. Expanded(
  504. flex: 2,
  505. child: Padding(
  506. padding: const EdgeInsets.only(bottom: 5),
  507. child: ElevatedButton(
  508. onPressed: () async {
  509. if (_busqueda.text.isNotEmpty) {
  510. await Provider.of<PedidoViewModel>(context, listen: false)
  511. .buscarPedidosPorFolio(_busqueda.text.trim());
  512. } else if (fechaInicio != null && fechaFin != null) {
  513. await Provider.of<PedidoViewModel>(context, listen: false)
  514. .buscarPedidosPorFecha(fechaInicio!, fechaFin!);
  515. } else {
  516. ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
  517. content: Text(
  518. 'Introduce un folio o selecciona un rango de fechas para buscar.')));
  519. }
  520. },
  521. style: ElevatedButton.styleFrom(
  522. shape: RoundedRectangleBorder(
  523. borderRadius: BorderRadius.circular(20.0),
  524. ),
  525. primary: AppTheme.tertiary,
  526. padding: const EdgeInsets.symmetric(vertical: 25),
  527. ),
  528. child: Text('Buscar',
  529. style: TextStyle(color: AppTheme.quaternary)),
  530. ),
  531. ),
  532. ),
  533. ],
  534. ));
  535. }
  536. }