1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- import 'dart:convert';
- import 'package:csv/csv.dart';
- import 'package:intl/intl.dart';
- import 'package:path_provider/path_provider.dart';
- import 'dart:io';
- import 'package:path/path.dart' as p;
- import '../../models/models.dart';
- Future<void> exportarPedidosACSV(List<Pedido> pedidos, String fileName) async {
- List<List<dynamic>> rows = [
- [
- "Folio",
- "Cliente",
- "Producto",
- "Cantidad",
- "Precio Unitario",
- "Toppings",
- "Descuento (%)",
- "Estado",
- "Fecha",
- "Total con Descuento",
- "Tipo de Pago",
- "Cantidad Efectivo",
- "Cantidad Tarjeta",
- "Cantidad Transferencia"
- ]
- ];
- for (var pedido in pedidos) {
- for (var producto in pedido.productos) {
- // Convertir toppings a una cadena de texto y calcular el total adicional de los toppings
- double totalToppingsPrecio = 0.0;
- String toppingsText = producto.toppings.isNotEmpty
- ? producto.toppings.map((t) {
- String toppingNombre =
- t.topping?.nombre ?? 'Topping no especificado';
- double toppingPrecio =
- double.tryParse(t.topping?.precio ?? '0') ?? 0.0;
- if (toppingPrecio > 0) {
- toppingNombre += "(+\$${formatCurrency(toppingPrecio)})";
- totalToppingsPrecio += toppingPrecio;
- }
- return toppingNombre;
- }).join(', ')
- : 'Sin toppings';
- // Calcular el total con descuento para este producto
- double precioUnitario =
- double.tryParse(producto.producto?.precio ?? '0') ?? 0.0;
- double subtotal =
- (precioUnitario + totalToppingsPrecio) * (producto.cantidad ?? 1);
- double descuento = pedido.descuento?.toDouble() ?? 0.0;
- double precioDescuento = subtotal * (descuento / 100);
- double totalConDescuento = subtotal - precioDescuento;
- List<dynamic> row = [
- pedido.folio,
- pedido.nombreCliente,
- producto.producto?.nombre ?? 'No especificado',
- producto.cantidad,
- formatCurrency(precioUnitario),
- toppingsText,
- descuento,
- pedido.estatus,
- pedido.peticion ?? '',
- formatCurrency(totalConDescuento),
- pedido.tipoPago ?? 'No especificado',
- formatCurrency(pedido.cantEfectivo ?? 0.0),
- formatCurrency(pedido.cantTarjeta ?? 0.0),
- formatCurrency(pedido.cantTransferencia ?? 0.0),
- ];
- rows.add(row);
- }
- }
- String csv = const ListToCsvConverter().convert(rows);
- final directory = await getApplicationDocumentsDirectory();
- final path = p.join(directory.path, fileName);
- final file = File(path);
- final utf8Csv = utf8.encode('\uFEFF' + csv);
- await file.writeAsBytes(utf8Csv, flush: true);
- print('Archivo CSV guardado en $path');
- }
- String formatCurrency(double amount) {
- final format = NumberFormat("#,##0.00", "es_MX");
- return format.format(amount);
- }
|