123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741 |
- import 'dart:typed_data';
- import 'package:flutter/material.dart';
- import 'package:intl/intl.dart';
- import 'package:omni_datetime_picker/omni_datetime_picker.dart';
- import 'package:provider/provider.dart';
- import '../pedido/pedido_csv.dart';
- import '../pedido/pedido_detalle_screen.dart';
- import '../../widgets/widgets.dart';
- import '../../themes/themes.dart';
- import '../../models/models.dart';
- import '../../viewmodels/viewmodels.dart';
- import '../../widgets/widgets_components.dart' as clase;
- import 'pedido_form.dart';
- import 'package:otp/otp.dart';
- import 'package:pdf/widgets.dart' as pw;
- import 'package:timezone/data/latest.dart' as timezone;
- import 'package:timezone/timezone.dart' as timezone;
- import 'pedido_ticket.dart';
- class PedidoScreen extends StatefulWidget {
- const PedidoScreen({Key? key}) : super(key: key);
- @override
- State<PedidoScreen> createState() => _PedidoScreenState();
- }
- class _PedidoScreenState extends State<PedidoScreen> {
- final _busqueda = TextEditingController(text: '');
- DateTime? fechaInicio;
- DateTime? fechaFin;
- ScrollController horizontalScrollController = ScrollController();
- TextEditingController codeController = new TextEditingController();
- bool _isMesasActive = false;
- @override
- void initState() {
- super.initState();
- WidgetsBinding.instance.addPostFrameCallback((_) {
- Provider.of<PedidoViewModel>(context, listen: false)
- .fetchLocalPedidosForScreen();
- Provider.of<MesaViewModel>(context, listen: false)
- .fetchLocalAll(sinLimite: true);
- });
- Future.microtask(() async {
- bool isMesasActive =
- await Provider.of<VariableViewModel>(context, listen: false)
- .isVariableActive('MESAS');
- setState(() {
- _isMesasActive = isMesasActive;
- });
- });
- }
- void exportCSV() async {
- final pedidosViewModel =
- Provider.of<PedidoViewModel>(context, listen: false);
- List<Pedido> pedidosConProductos = [];
- for (Pedido pedido in pedidosViewModel.pedidos) {
- Pedido? pedidoConProductos =
- await pedidosViewModel.fetchPedidoConProductos(pedido.id);
- if (pedidoConProductos != null) {
- pedidosConProductos.add(pedidoConProductos);
- }
- }
- if (pedidosConProductos.isNotEmpty) {
- String fileName = 'Pedidos_Turquessa_POS';
- if (fechaInicio != null && fechaFin != null) {
- String startDateStr = DateFormat('dd-MM-yyyy').format(fechaInicio!);
- String endDateStr = DateFormat('dd-MM-yyyy').format(fechaFin!);
- fileName += '_${startDateStr}_al_${endDateStr}';
- }
- fileName += '.csv';
- await exportarPedidosACSV(pedidosConProductos, fileName);
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text('Archivo CSV descargado! Archivo: $fileName')));
- } else {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(content: Text('No hay pedidos para exportar.')));
- }
- }
- void clearSearchAndReset() {
- setState(() {
- _busqueda.clear();
- fechaInicio = null;
- fechaFin = null;
- Provider.of<PedidoViewModel>(context, listen: false)
- .fetchLocalPedidosForScreen();
- });
- }
- void go(Pedido item, {bool? detalle = false}) async {
- Pedido? pedidoCompleto =
- await Provider.of<PedidoViewModel>(context, listen: false)
- .fetchPedidoConProductos(item.id);
- if (pedidoCompleto != null) {
- if (pedidoCompleto.estatus == 'TERMINADO' ||
- pedidoCompleto.estatus == 'CANCELADO' ||
- !_isMesasActive ||
- detalle!) {
- Navigator.push(
- context,
- MaterialPageRoute(
- builder: (context) => PedidoDetalleScreen(pedido: pedidoCompleto),
- ),
- );
- } else {
- Navigator.push(
- context,
- MaterialPageRoute(
- builder: (context) => PedidoForm(
- pedidoExistente: pedidoCompleto,
- ),
- ),
- ).then((value) async {
- await Provider.of<PedidoViewModel>(context, listen: false)
- .fetchLocalPedidosForScreen();
- });
- }
- } else {
- print("Error al cargar el pedido con productos");
- }
- }
- @override
- Widget build(BuildContext context) {
- final pvm = Provider.of<PedidoViewModel>(context);
- double screenWidth = MediaQuery.of(context).size.width;
- final isMobile = screenWidth < 1250;
- final double? columnSpacing = isMobile ? null : 0;
- TextStyle estilo = const TextStyle(fontWeight: FontWeight.bold);
- List<DataRow> registros = [];
- final permisoViewModel = Provider.of<PermisoViewModel>(context);
- List<String> userPermisos = permisoViewModel.userPermisos;
- for (Pedido item in pvm.pedidos) {
- final sincronizadoStatus =
- item.sincronizado == null || item.sincronizado!.isEmpty
- ? "No Sincronizado"
- : _formatDateTime(item.sincronizado);
- final mesaViewModel = Provider.of<MesaViewModel>(context, listen: false);
- final mesa = mesaViewModel.fetchLocalById(idMesa: item.idMesa);
- registros.add(DataRow(cells: [
- DataCell(
- Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
- PopupMenuButton(
- itemBuilder: (context) => [
- PopupMenuItem(
- child: const Text('Detalle'),
- onTap: () => go(item, detalle: true),
- ),
- PopupMenuItem(
- child: const Text('Estado Ticket'),
- onTap: () async {
- await imprimirEstadoTicket(context, item);
- },
- ),
- if (userPermisos.contains(Usuario.CANCELAR_PEDIDO))
- PopupMenuItem(
- child: const Text('Cancelar Pedido'),
- onTap: () async {
- bool confirmado = await showDialog<bool>(
- context: context,
- builder: (context) {
- return AlertDialog(
- title: const Text("Cancelar Pedido",
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 22)),
- content: const Text(
- '¿Estás seguro de que deseas cancelar este pedido?',
- style: TextStyle(fontSize: 18)),
- actions: [
- Column(
- children: [
- Container(
- padding: EdgeInsets.all(8.0),
- child: TextField(
- controller: codeController,
- decoration: InputDecoration(
- label: Text(
- "Para cancelar debe capturar el código")),
- ),
- ),
- Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- TextButton(
- onPressed: () =>
- Navigator.of(context).pop(false),
- child: const Text('No',
- style: TextStyle(fontSize: 18)),
- style: ButtonStyle(
- padding: MaterialStatePropertyAll(
- EdgeInsets.fromLTRB(
- 20, 10, 20, 10)),
- backgroundColor:
- MaterialStatePropertyAll(
- Colors.red),
- foregroundColor:
- MaterialStatePropertyAll(
- AppTheme.secondary)),
- ),
- TextButton(
- onPressed: () {
- final now = DateTime.now().toUtc();
- timezone.initializeTimeZones();
- final pacificTimeZone =
- timezone.getLocation(
- 'America/Los_Angeles');
- final date =
- timezone.TZDateTime.from(
- now, pacificTimeZone);
- final codigoTotp =
- OTP.generateTOTPCodeString(
- 'TYSNE4CMT5LVLGWS',
- date.millisecondsSinceEpoch,
- algorithm: Algorithm.SHA1,
- isGoogle: true);
- String codigo = codeController.text;
- print(
- "totp: $codigoTotp codigo:$codigo");
- List<String> codigosEstaticos = [
- '172449',
- '827329',
- // Agregar más token fijos
- ];
- bool esCodigoEstatico =
- codigosEstaticos
- .contains(codigo);
- print(
- "¿Es código estático? ${esCodigoEstatico} ${!esCodigoEstatico && codigo != codigoTotp}");
- if (!esCodigoEstatico &&
- codigo != codigoTotp) {
- ScaffoldMessenger.of(context)
- .showSnackBar(SnackBar(
- content: Text(
- 'El código no es correcto'),
- duration: Duration(seconds: 2),
- ));
- return;
- } else {
- codeController.text = '';
- Navigator.of(context).pop(true);
- }
- },
- child: const Text('Sí',
- style: TextStyle(fontSize: 18)),
- style: ButtonStyle(
- padding: MaterialStatePropertyAll(
- EdgeInsets.fromLTRB(
- 20, 10, 20, 10)),
- backgroundColor:
- MaterialStatePropertyAll(
- AppTheme.tertiary),
- foregroundColor:
- MaterialStatePropertyAll(
- AppTheme.quaternary)),
- ),
- ],
- )
- ],
- ),
- ],
- );
- },
- ) ??
- false;
- if (confirmado) {
- await Provider.of<PedidoViewModel>(context, listen: false)
- .cancelarPedido(item.id);
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text("Pedido cancelado correctamente")));
- }
- },
- )
- ],
- icon: const Icon(Icons.more_vert),
- )
- ])),
- if (_isMesasActive)
- DataCell(
- Text(mesa.nombre ?? "Mesa desconocida"),
- onTap: () => go(item),
- ),
- DataCell(
- Text(item.folio.toString()),
- onTap: () => go(item),
- ),
- DataCell(
- Text(item.nombreCliente ?? "Sin nombre"),
- onTap: () => go(item),
- ),
- DataCell(
- Text(item.comentarios ?? "Sin comentarios"),
- onTap: () => go(item),
- ),
- DataCell(
- Text(item.estatus ?? "Sin Estatus"),
- onTap: () => go(item),
- ),
- DataCell(
- Text(_formatDateTime(item.peticion)),
- onTap: () => go(item),
- ),
- DataCell(
- Text(sincronizadoStatus),
- onTap: () => go(item),
- ),
- ]));
- }
- return Scaffold(
- appBar: AppBar(
- title: Text(
- 'Pedidos',
- style: TextStyle(
- color: AppTheme.secondary, fontWeight: FontWeight.w500),
- ),
- actions: <Widget>[
- if (userPermisos.contains(Usuario.VER_REPORTE))
- IconButton(
- icon: const Icon(Icons.save_alt),
- onPressed: exportCSV,
- tooltip: 'Exportar a CSV',
- ),
- ],
- iconTheme: IconThemeData(color: AppTheme.secondary)),
- body: Stack(
- children: [
- Column(
- children: [
- Expanded(
- child: ListView(
- padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
- children: [
- const SizedBox(height: 8),
- clase.tarjeta(
- Padding(
- padding: const EdgeInsets.all(8.0),
- child: LayoutBuilder(
- builder: (context, constraints) {
- if (screenWidth > 1000) {
- return Row(
- crossAxisAlignment: CrossAxisAlignment.end,
- children: [
- Expanded(
- flex: 7,
- child: _buildDateRangePicker(),
- ),
- const SizedBox(width: 5),
- botonBuscar()
- ],
- );
- } else {
- return Column(
- children: [
- Row(
- children: [_buildDateRangePicker()],
- ),
- Row(
- children: [botonBuscar()],
- ),
- ],
- );
- }
- },
- ),
- ),
- ),
- const SizedBox(height: 8),
- pvm.isLoading
- ? const Center(child: CircularProgressIndicator())
- : Container(),
- clase.tarjeta(
- Column(
- children: [
- LayoutBuilder(builder: (context, constraints) {
- return SingleChildScrollView(
- scrollDirection: Axis.vertical,
- child: Scrollbar(
- controller: horizontalScrollController,
- interactive: true,
- thumbVisibility: true,
- thickness: 10.0,
- child: SingleChildScrollView(
- controller: horizontalScrollController,
- scrollDirection: Axis.horizontal,
- child: ConstrainedBox(
- constraints: BoxConstraints(
- minWidth: isMobile
- ? constraints.maxWidth
- : screenWidth),
- child: DataTable(
- columnSpacing: columnSpacing,
- sortAscending: true,
- sortColumnIndex: 1,
- columns: [
- DataColumn(
- label: Text(" ", style: estilo)),
- if (_isMesasActive)
- DataColumn(
- label:
- Text("MESA", style: estilo)),
- DataColumn(
- label:
- Text("FOLIO", style: estilo)),
- DataColumn(
- label:
- Text("NOMBRE", style: estilo)),
- DataColumn(
- label: Text("COMENTARIOS",
- style: estilo)),
- DataColumn(
- label:
- Text("ESTATUS", style: estilo)),
- DataColumn(
- label:
- Text("FECHA", style: estilo)),
- DataColumn(
- label: Text("SINCRONIZADO",
- style: estilo)),
- ],
- rows: registros,
- ),
- ),
- ),
- ),
- );
- }),
- ],
- ),
- ),
- const SizedBox(height: 15),
- if (!pvm.isLoading)
- Row(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- TextButton(
- onPressed:
- pvm.currentPage > 1 ? pvm.previousPage : null,
- child: Text('Anterior'),
- style: ButtonStyle(
- backgroundColor:
- MaterialStateProperty.resolveWith<Color?>(
- (Set<MaterialState> states) {
- if (states.contains(MaterialState.disabled)) {
- return Colors.grey;
- }
- return AppTheme.tertiary;
- },
- ),
- foregroundColor:
- MaterialStateProperty.resolveWith<Color?>(
- (Set<MaterialState> states) {
- if (states.contains(MaterialState.disabled)) {
- return Colors.black;
- }
- return Colors.white;
- },
- ),
- ),
- ),
- SizedBox(width: 15),
- Text(
- 'Página ${pvm.currentPage} de ${pvm.totalPages}'),
- SizedBox(width: 15),
- TextButton(
- onPressed: pvm.currentPage < pvm.totalPages
- ? pvm.nextPage
- : null,
- child: Text('Siguiente'),
- style: ButtonStyle(
- backgroundColor:
- MaterialStateProperty.resolveWith<Color?>(
- (Set<MaterialState> states) {
- if (states.contains(MaterialState.disabled)) {
- return Colors.grey;
- }
- return AppTheme.tertiary;
- },
- ),
- foregroundColor:
- MaterialStateProperty.resolveWith<Color?>(
- (Set<MaterialState> states) {
- if (states.contains(MaterialState.disabled)) {
- return Colors.black;
- }
- return Colors.white;
- },
- ),
- ),
- ),
- ],
- ),
- const SizedBox(height: 15),
- ],
- ),
- ),
- ],
- ),
- Positioned(
- bottom: 16,
- right: 16,
- child: FloatingActionButton.extended(
- heroTag: 'addPedido',
- onPressed: () async {
- final corteCajaViewModel =
- Provider.of<CorteCajaViewModel>(context, listen: false);
- if (corteCajaViewModel.hasOpenCorteCaja()) {
- await Navigator.push(
- context,
- MaterialPageRoute(
- builder: (context) => PedidoForm(),
- ),
- ).then((_) =>
- Provider.of<PedidoViewModel>(context, listen: false)
- .fetchLocalPedidosForScreen());
- } else {
- alerta(context,
- etiqueta:
- 'Solo se pueden realizar pedidos cuando se encuentre la caja abierta.');
- }
- },
- icon: Icon(Icons.add, size: 30, color: AppTheme.quaternary),
- label: Text(
- "Agregar Pedido",
- style: TextStyle(fontSize: 20, color: AppTheme.quaternary),
- ),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(8),
- ),
- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
- backgroundColor: AppTheme.tertiary,
- ),
- ),
- ],
- ),
- );
- }
- Widget _buildDateRangePicker() {
- return Row(
- children: [
- Expanded(
- flex: 3,
- child: AppTextField(
- prefixIcon: const Icon(Icons.search),
- etiqueta: 'Búsqueda por folio...',
- controller: _busqueda,
- hintText: 'Búsqueda por folio...',
- ),
- ),
- const SizedBox(width: 5),
- Expanded(
- flex: 3,
- child: clase.FechaSelectWidget(
- fecha: fechaInicio,
- onFechaChanged: (d) {
- setState(() {
- fechaInicio = d;
- });
- },
- etiqueta: "Fecha Inicial",
- context: context,
- ),
- ),
- const SizedBox(width: 5),
- Expanded(
- flex: 3,
- child: clase.FechaSelectWidget(
- fecha: fechaFin,
- onFechaChanged: (d) {
- setState(() {
- fechaFin = d;
- });
- },
- etiqueta: "Fecha Final",
- context: context,
- ),
- ),
- ],
- );
- }
- Widget botonBuscar() {
- return Expanded(
- flex: 2,
- child: Row(
- children: [
- Expanded(
- flex: 2,
- child: Padding(
- padding: const EdgeInsets.only(bottom: 5),
- child: ElevatedButton(
- onPressed: clearSearchAndReset,
- style: ElevatedButton.styleFrom(
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(20.0),
- ),
- primary: AppTheme.tertiary,
- padding: const EdgeInsets.symmetric(vertical: 25),
- ),
- child: Text('Limpiar',
- style: TextStyle(color: AppTheme.quaternary)),
- ),
- ),
- ),
- const SizedBox(width: 8),
- Expanded(
- flex: 2,
- child: Padding(
- padding: const EdgeInsets.only(bottom: 5),
- child: ElevatedButton(
- onPressed: () async {
- if (_busqueda.text.isNotEmpty) {
- await Provider.of<PedidoViewModel>(context, listen: false)
- .buscarPedidosPorFolio(_busqueda.text.trim());
- } else if (fechaInicio != null && fechaFin != null) {
- DateTime fechaInicioUTC = DateTime(fechaInicio!.year,
- fechaInicio!.month, fechaInicio!.day)
- .toUtc();
- DateTime fechaFinUTC = DateTime(fechaFin!.year,
- fechaFin!.month, fechaFin!.day, 23, 59, 59)
- .toUtc();
- await Provider.of<PedidoViewModel>(context, listen: false)
- .buscarPedidosPorFecha(fechaInicioUTC, fechaFinUTC);
- } else {
- ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
- content: Text(
- 'Introduce un folio o selecciona un rango de fechas para buscar.')));
- }
- },
- style: ElevatedButton.styleFrom(
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(20.0),
- ),
- primary: AppTheme.tertiary,
- padding: const EdgeInsets.symmetric(vertical: 25),
- ),
- child: Text('Buscar',
- style: TextStyle(color: AppTheme.quaternary)),
- ),
- ),
- ),
- ],
- ),
- );
- }
- void alertaSync(BuildContext context) {
- showDialog(
- context: context,
- builder: (BuildContext context) {
- return AlertDialog(
- title: const Text('Confirmación',
- style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22)),
- content: const Text('¿Deseas sincronizar todos los pedidos de nuevo?',
- style: TextStyle(fontSize: 18)),
- actions: [
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- TextButton(
- child: const Text('No', style: TextStyle(fontSize: 18)),
- style: ButtonStyle(
- padding: MaterialStatePropertyAll(
- EdgeInsets.fromLTRB(20, 10, 20, 10)),
- backgroundColor: MaterialStatePropertyAll(Colors.red),
- foregroundColor:
- MaterialStatePropertyAll(AppTheme.secondary)),
- onPressed: () {
- Navigator.of(context).pop();
- },
- ),
- TextButton(
- child: const Text('Sí', style: TextStyle(fontSize: 18)),
- style: ButtonStyle(
- padding: MaterialStatePropertyAll(
- EdgeInsets.fromLTRB(20, 10, 20, 10)),
- backgroundColor:
- MaterialStatePropertyAll(AppTheme.tertiary),
- foregroundColor:
- MaterialStatePropertyAll(AppTheme.quaternary)),
- onPressed: () {
- // No hace nada por el momento
- Navigator.of(context).pop();
- },
- ),
- ],
- )
- ],
- );
- },
- );
- }
- String _formatDateTime(String? dateTimeString) {
- if (dateTimeString == null) return "Sin fecha";
- DateTime parsedDate = DateTime.parse(dateTimeString);
- var formatter = DateFormat('dd-MM-yyyy HH:mm:ss');
- return formatter.format(parsedDate.toLocal());
- }
- Future<void> imprimirEstadoTicket(BuildContext context, Pedido pedido) async {
- if (pedido.productos == null || pedido.productos.isEmpty) {
- pedido = (await Provider.of<PedidoViewModel>(context, listen: false)
- .fetchPedidoConProductos(pedido.id))!;
- if (pedido == null) {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(content: Text('No se pudo cargar el pedido')),
- );
- return;
- }
- }
- final pdf = pw.Document();
- pdf.addPage(generarPaginaSegundoTicket(pedido));
- final pdfBytes = Uint8List.fromList(await pdf.save());
- await printPdf(pdfBytes);
- }
- }
|