using compabetov2.database; using compabetov2.database.modelos; using compabetov2.Ventas; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Printing; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox; namespace compabetov2 { public partial class vender : Form { private int numeroPagina = 1; // Variable para rastrear el número de página actual private Point lastPoint; private List productos; public decimal total = 0; private LoginModel loginPrincipal; private Dictionary imagenes = new Dictionary(); private List carrito = new List(); public List importes = new List(); public vender(LoginModel loginPrincipal) { InitializeComponent(); getData(); llenarLayout(); llenarComBox(); this.loginPrincipal = loginPrincipal; } private void InitializeFlowLayout() { // Inicializar el flowLayoutPanel3 (asegúrate de que ya está creado en tu formulario) // Habilitar eventos táctiles simulados flowLayoutPanel3.MouseDown += FlowLayoutPanel3_MouseDown; flowLayoutPanel3.MouseMove += FlowLayoutPanel3_MouseMove; flowLayoutPanel3.MouseUp += FlowLayoutPanel3_MouseUp; } private void FlowLayoutPanel3_MouseDown(object sender, MouseEventArgs e) { lastPoint = new Point(e.X, e.Y); flowLayoutPanel3.Capture = true; } private void FlowLayoutPanel3_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { int deltaX = lastPoint.X - e.X; int deltaY = lastPoint.Y - e.Y; // Ajustar la dirección del desplazamiento flowLayoutPanel3.AutoScrollPosition = new Point(flowLayoutPanel3.AutoScrollPosition.X + deltaX, flowLayoutPanel3.AutoScrollPosition.Y - deltaY); lastPoint = new Point(e.X, e.Y); } } private void FlowLayoutPanel3_MouseUp(object sender, MouseEventArgs e) { lastPoint = new Point(e.X, e.Y); flowLayoutPanel3.Capture = true; } private void llenarComBox() { List empleados = service.conseguirEmpleados(); foreach (Empleado empleado in empleados) { responsablecb.Items.Add(empleado.nombre); } } public void llenarLayout() { flowLayoutPanel3.Controls.Clear(); foreach (Variante producto in productos) { TableLayoutPanel carta = new TableLayoutPanel(); carta.ColumnCount = 1; carta.RowCount = 2; carta.RowStyles.Add(new RowStyle(SizeType.Percent, 80F)); carta.RowStyles.Add(new RowStyle(SizeType.Percent, 20F)); carta.Width = 220; carta.Height = 300; PictureBox pic = new PictureBox(); pic.Dock = DockStyle.Fill; pic.SizeMode = PictureBoxSizeMode.Zoom; if (imagenes.ContainsKey(producto.img)) { pic.Image = imagenes[producto.img]; } else { string rutaImg = Path.Combine(Application.StartupPath, "Resources", producto.img); Image img = Image.FromFile(rutaImg); pic.Image = img; imagenes.Add(producto.img, img); } //hay error aquí pic.BackgroundImageLayout = ImageLayout.Stretch; pic.Tag = producto.idVariante; Label id = new Label(); id.Text = producto.idVariante.ToString(); id.BackColor = Color.FromArgb(82, 82, 82); id.ForeColor = Color.White; id.Width = 35; id.Font = new Font(id.Font, FontStyle.Bold); id.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; pic.Controls.Add(id); Label precio = new Label(); precio.Text = "$" + producto.precio.ToString() + " - " + producto.nombre; precio.BackColor = Color.FromArgb(82, 82, 82); precio.ForeColor = Color.White; precio.Width = 40; precio.Font = new Font(id.Font, FontStyle.Bold); precio.Dock = DockStyle.Bottom; pic.Controls.Add(precio); TableLayoutPanel HUD = new TableLayoutPanel(); HUD.ColumnCount = 3; HUD.RowCount = 1; HUD.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 33F)); HUD.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 33F)); HUD.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 33F)); Label contador = new Label(); contador.Text = "0"; contador.Dock = DockStyle.Fill; contador.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; contador.Font = new Font(contador.Font.FontFamily, 25); Button btnMenos = new Button(); btnMenos.Text = "-"; btnMenos.Width = 25; btnMenos.Height = 25; btnMenos.Font = new Font(btnMenos.Font.FontFamily, 30); btnMenos.ForeColor = Color.White; btnMenos.Dock = DockStyle.Fill; btnMenos.FlatStyle = FlatStyle.Flat; btnMenos.FlatAppearance.BorderSize = 0; btnMenos.BackColor = Color.FromArgb(33, 90, 255); btnMenos.Click += new EventHandler(delegate (object sender, EventArgs e) { int numeroContador = int.Parse(contador.Text.ToString()); // Validar que el contador no sea 0 antes de restar int indexCarrito = estaEnCarrito(producto.nombre); if (indexCarrito != -1) { contador.Text = (numeroContador - 1).ToString(); total -= producto.precio; label1.Text = $"Total: ${total}$"; // Obtener información del Label id y precio decimal precioProducto = producto.precio; // Restar al ticket existente si ya se agregó carrito[indexCarrito].cantidad -= 1; if (carrito[indexCarrito].cantidad == 0) { carrito.RemoveAt(indexCarrito); } RestarDelTicket(producto.idVariante, producto.nombre, precioProducto, 1); } else { MessageBox.Show("No puedes vender menos de 0 cosas", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }); Button btnMas = new Button(); btnMas.Text = "+"; btnMas.Width = 25; btnMas.Height = 25; btnMas.Dock = DockStyle.Fill; btnMas.Font = new Font(btnMas.Font.FontFamily, 30); btnMas.ForeColor = Color.White; btnMas.BackColor = Color.FromArgb(33, 90, 255); btnMas.FlatStyle = FlatStyle.Flat; btnMas.FlatAppearance.BorderSize = 0; btnMas.Click += new EventHandler(delegate (object sender, EventArgs e) { if (int.Parse(contador.Text.ToString()) < 0 && !existeTocket(producto.nombre)) { contador.Text = "0"; } int numeroContador = int.Parse(contador.Text.ToString()); contador.Text = (numeroContador + 1).ToString(); total += producto.precio; label1.Text = $"Total: ${total}:"; // Obtener información del Label id y precio int idProducto = int.Parse(id.Text); decimal precioProducto = producto.precio; // Generar ticket y agregarlo al flowLayoutPanel2 int indexCarrito = estaEnCarrito(producto.nombre); if (indexCarrito != -1) { carrito[indexCarrito].cantidad += 1; } else { carrito.Add(new DetalleVentaModel(1, producto)); } GenerarTicket(idProducto, producto.nombre, producto.precio, int.Parse(contador.Text), total, Path.Combine(Application.StartupPath, "Resources", producto.img)); }); HUD.Controls.Add(btnMenos); HUD.Controls.Add(contador); HUD.Controls.Add(btnMas); carta.Controls.Add(pic, 0, 0); carta.Controls.Add(HUD, 0, 1); flowLayoutPanel3.Controls.Add(carta); } } private int estaEnCarrito(string nombre) { for (int i = 0; i < carrito.Count; i++) { if (carrito[i].producto.nombre.Equals(nombre)) { return i; } } return -1; } private void RestarDelTicket(int idProducto, string nombreProducto, decimal precio, int cantidad) { foreach (var item in flowLayoutPanel2.Controls) { TableLayoutPanel panelProducto = item as TableLayoutPanel; if (panelProducto != null && panelProducto.Controls.Count > 1) { TableLayoutPanel panelInfo = panelProducto.Controls[1] as TableLayoutPanel; if (panelInfo != null && panelInfo.Controls.Count > 2) { Label lbnombre = panelInfo.Controls[0] as Label; if (lbnombre != null) { string textoLb = lbnombre.Text; string[] cadenas = textoLb.Split(':'); string cadena = cadenas[1].Remove(0, 1); if (cadena.Equals(nombreProducto)) { Label Lbcantidad = panelInfo.Controls[2] as Label; Label Lbtotal = panelInfo.Controls[3] as Label; if (Lbcantidad != null && Lbtotal != null) { string textcantidad = Lbcantidad.Text; string[] cantidadCadenas = textcantidad.Split(' '); if (int.Parse(cantidadCadenas[1]) > 0) { int NuevaCantiad = int.Parse(cantidadCadenas[1]) - cantidad; int NuevoTotal = (int)(NuevaCantiad * precio); // Actualizar el ticket existente Lbcantidad.Text = $"Cantidad: {NuevaCantiad}"; Lbtotal.Text = $"Total: ${NuevoTotal}"; // Si la cantidad llega a 0, eliminar el ticket del flowLayoutPanel2 if (NuevaCantiad == 0) { flowLayoutPanel2.Controls.Remove(panelProducto); } break; } else { // Mostrar mensaje de advertencia MessageBox.Show("No puedes vender menos de 0 cosas", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } } } } } } private bool existeTocket(string nombreProducto) { int contador_saltar_2_vueltas = 1; foreach (var item in flowLayoutPanel2.Controls) { if (contador_saltar_2_vueltas <= 3) { contador_saltar_2_vueltas++; continue; } TableLayoutPanel panelProducto = item as TableLayoutPanel; TableLayoutPanel panelInfo = panelProducto.Controls[1] as TableLayoutPanel; Label lbnombre = panelInfo.Controls[0] as Label; string textoLb = lbnombre.Text; string[] cadenas = textoLb.Split(':'); string cadena = cadenas[1].Remove(0, 1); if (cadena.Equals(nombreProducto)) { return true; } } return false; } private void GenerarTicket(int idProducto, string nombreProducto, decimal precio, int cantidad, decimal total, string rutaImg) { bool existeProducto = false; int contador_saltar_2_vueltas = 1; foreach (var item in flowLayoutPanel2.Controls) { if (contador_saltar_2_vueltas <= 3) { contador_saltar_2_vueltas++; continue; } TableLayoutPanel panelProducto = item as TableLayoutPanel; TableLayoutPanel panelInfo = panelProducto.Controls[1] as TableLayoutPanel; Label lbnombre = panelInfo.Controls[0] as Label; string textoLb = lbnombre.Text; string[] cadenas = textoLb.Split(':'); string cadena = cadenas[1].Remove(0, 1); if (cadena.Equals(nombreProducto)) { existeProducto = true; Label Lbcantidad = panelInfo.Controls[2] as Label; Label Lbtotal = panelInfo.Controls[3] as Label; string textcantidad = Lbcantidad.Text; string[] cantidadCadenas = textcantidad.Split(' '); int NuevaCantiad = int.Parse(cantidadCadenas[1]) + 1; int NuevoTotal = (int)(NuevaCantiad * precio); Lbcantidad.Text = $"Cantidad: {NuevaCantiad}"; Lbtotal.Text = $"Total: ${NuevoTotal}"; } } if (!existeProducto) { TableLayoutPanel ticketProducto = new TableLayoutPanel(); ticketProducto.RowCount = 1; ticketProducto.ColumnCount = 2; ticketProducto.Height = 100; ticketProducto.Width = 250; ticketProducto.BackColor = Color.FromArgb(33, 90, 255); PictureBox pic = new PictureBox(); pic.Dock = DockStyle.Fill; pic.SizeMode = PictureBoxSizeMode.Zoom; pic.Image = Image.FromFile(rutaImg);//hay error aquí pic.BackgroundImageLayout = ImageLayout.Stretch; Label id = new Label(); id.Text = idProducto.ToString(); id.BackColor = Color.FromArgb(82, 82, 82); id.ForeColor = Color.White; id.Width = 20; id.Font = new Font(id.Font, FontStyle.Bold); id.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; pic.Controls.Add(id); TableLayoutPanel infoTicket = new TableLayoutPanel(); infoTicket.ColumnCount = 1; infoTicket.RowCount = 4; infoTicket.Dock = DockStyle.Fill; Label lbNombre = new Label(); lbNombre.Dock = DockStyle.Fill; lbNombre.Text = $"producto: {nombreProducto}"; lbNombre.ForeColor = Color.White; Label lbPrecio = new Label(); lbPrecio.Dock = DockStyle.Fill; lbPrecio.Text = $"Precio: ${precio}"; lbPrecio.ForeColor = Color.White; Label lbCantidad = new Label(); lbCantidad.Dock = DockStyle.Fill; lbCantidad.Text = $"Cantidad: {cantidad}"; lbCantidad.ForeColor = Color.White; Label lbTotal = new Label(); lbTotal.Dock = DockStyle.Fill; lbTotal.Text = $"Total: ${cantidad * precio}"; lbTotal.ForeColor = Color.White; infoTicket.Controls.Add(lbNombre, 0, 0); infoTicket.Controls.Add(lbPrecio, 0, 1); infoTicket.Controls.Add(lbCantidad, 0, 2); infoTicket.Controls.Add(lbTotal, 0, 3); ticketProducto.Controls.Add(pic, 0, 0); ticketProducto.Controls.Add(infoTicket, 1, 0); // Agregar el ticket al flowLayoutPanel2 flowLayoutPanel2.Controls.Add(ticketProducto); } } private void getData() { this.productos = service.conseguirVariantes(); } private void vender_Load(object sender, EventArgs e) { bntImprimir.Enabled = false; responsablecb.SelectedIndexChanged += responsablecb_SelectedIndexChanged; } private void lblhora_Click(object sender, EventArgs e) { } private void lblfecha_Click(object sender, EventArgs e) { } private void horafecha_Tick(object sender, EventArgs e) { lblhora.Text = DateTime.Now.ToString("h:mm:ss"); lblfecha.Text = DateTime.Now.ToLongDateString(); } private void cervezasgb_Enter(object sender, EventArgs e) { } private void flowLayoutPanel3_Paint(object sender, PaintEventArgs e) { } private void button1_Click(object sender, EventArgs e) { // Cerrar el formulario de ventas this.Close(); // Verificar si ya hay una instancia del formulario principal MenuPrincipal menuprincipalForm = Application.OpenForms.OfType().FirstOrDefault(); if (menuprincipalForm == null) { // Si no hay una instancia, crear una nueva menuprincipalForm = new MenuPrincipal(loginPrincipal); // Establecer el formulario principal como el formulario MDI padre menuprincipalForm.MdiParent = this.MdiParent; // Mostrar el formulario principal menuprincipalForm.Show(); } else { // Si ya hay una instancia, simplemente llevarlo al frente menuprincipalForm.BringToFront(); } } public void flowLayoutPanel2_Paint(object sender, PaintEventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void bntImprimir_Click(object sender, EventArgs e) { //List detalleVentas = listaProductosVenta(); if (carrito.Count > 0) { DialogResult resultado = MessageBox.Show("¿Quieres hacer esa venta?", "Confirmación de Venta", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (resultado == DialogResult.Yes) { VentaModel ventaModel = new VentaModel(total, -1, "", responsablecb.Text.Equals("") ? loginPrincipal.usuario : responsablecb.Text, 0 ); if (service.crearVentaDAO(ventaModel, carrito, importes)) { MessageBox.Show("Venta hecha"); ImprimirTicket(); eliminarProductosTocket(); llenarLayout(); total = 0; importes.Clear(); } } else { // Si la opción es "NO", mostrar mensaje de venta cancelada MessageBox.Show("Venta cancelada", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { if(importes.Count > 0) { if (total < 0) { DialogResult resultado = MessageBox.Show("¿Quieres hacer la devolucion del importe?", "Confirmación devolucion de importe", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (resultado == DialogResult.Yes) { VentaModel venta = new VentaModel(total,-1,DateTime.Now.ToString(),responsablecb.Text); if (service.devolverImporte(venta, importes)) { MessageBox.Show("Importe devuelto"); llenarLayout(); total = 0; importes.Clear(); } } } else { MessageBox.Show("No puede vender un importe sin seleccionar un producto"); } } else { MessageBox.Show("No hay ningun producto agregado"); } } } private void ImprimirTicket() { using (PrintDocument documentoImpresion = new PrintDocument()) { documentoImpresion.PrintPage += (sender, e) => ImprimirContenido(e); documentoImpresion.PrintController = new StandardPrintController(); // Evita que el documento se imprima automáticamente using (PrintDialog printDialog = new PrintDialog()) { printDialog.Document = documentoImpresion; if (printDialog.ShowDialog() == DialogResult.OK) { // Imprime el documento documentoImpresion.Print(); } } } } private void ImprimirContenido(PrintPageEventArgs e) { string responsable = responsablecb.SelectedItem.ToString(); // Contenido que deseas imprimir string contenido = " Mini Súper\n" + " Compa BETO\n" + " Saturnino Peña #44\n" + " Lomas de la Laguna\n" + " 311 169 2829\n" + $" Fecha: {DateTime.Now.ToString("dd/MM/yyyy")}\n" + $" Hora: {DateTime.Now.ToString("hh:mm:ss")}\n" + $" Atendió:\n " + $" {responsable}\n" + "Producto | Precio | Cantidad\n" + "------------------------------------\n"; contenido += crearContenidoImprimir(); contenido += $"------------------------------------\n" + $" Total: ${total}\n" + "------------------------------------\n" + " Mini Súper\n" + " Compa BETO\n" + " ¡Gracias por su compra!"; // Configuración de la fuente y del área de impresión Font fuente = new Font("Arial", 10); // Ajustar el tamaño de fuente según sea necesario PointF posicion = new PointF(0, e.MarginBounds.Top); // Imprimir el contenido e.Graphics.DrawString(contenido, fuente, Brushes.Black, posicion); // Incrementa el número de página // Tu lógica de impresión actual aquí // Incrementa el número de página numeroPagina++; // Imprime solo dos páginas if (numeroPagina <= 2) { e.HasMorePages = true; } else { e.HasMorePages = false; numeroPagina = 1; // Reinicia el número de página para futuras impresiones } } private string crearContenidoImprimir() { int contador_saltar_2_vueltas = 1; string resultado = ""; foreach (var item in flowLayoutPanel2.Controls) { if (contador_saltar_2_vueltas <= 3) { contador_saltar_2_vueltas++; continue; } TableLayoutPanel panelProducto = item as TableLayoutPanel; TableLayoutPanel panelInfo = panelProducto.Controls[1] as TableLayoutPanel; Label lbnombre = panelInfo.Controls[0] as Label; Label lbPrecio = panelInfo.Controls[1] as Label; Label Lbcantidad = panelInfo.Controls[2] as Label; Label Lbtotal = panelInfo.Controls[3] as Label; //nombre producto string textoLbnombre = lbnombre.Text; string[] cadenas = textoLbnombre.Split(':'); string productoNombre = cadenas[1].Remove(0, 1); //precio string textoLbPrecio = lbPrecio.Text; cadenas = textoLbPrecio.Split('$'); string precioProducto = cadenas[1]; //cantidad string textoLbCantidad = Lbcantidad.Text; cadenas = textoLbCantidad.Split(':'); string cantidadProducto = cadenas[1].Remove(0, 1); //total string textoLbTotal = Lbtotal.Text; cadenas = textoLbTotal.Split('$'); string totalProducto = cadenas[1]; resultado += $"{(productoNombre.Length > 10 ? $"{productoNombre}\n" : $"{productoNombre}")} | ${precioProducto} | {cantidadProducto}\n"; } return resultado; } /*private void button7_Click(object sender, EventArgs e) { List detalleVentas = listaProductosVenta(); if (detalleVentas.Count > 0) { VentaModel ventaModel = new VentaModel(total); if (service.crearVentaDAO(ventaModel, detalleVentas)) { MessageBox.Show("Venta hecha"); } } else { MessageBox.Show("No hay ningun producto agregado"); } } private List listaProductosVenta() { List detalleVentas = new List(); int contador_saltar_2_vueltas = 1; foreach (var item in flowLayoutPanel2.Controls) { if (contador_saltar_2_vueltas <= 3) { contador_saltar_2_vueltas++; continue; } TableLayoutPanel panelProducto = item as TableLayoutPanel; TableLayoutPanel panelInfo = panelProducto.Controls[1] as TableLayoutPanel; PictureBox pic = panelProducto.Controls[0] as PictureBox; Label idLabel = null; foreach (Control control in pic.Controls) { if (control is Label) { idLabel = (Label)control; break; } } int idProducto = int.Parse(idLabel.Text); Variante producto = new Variante(idProducto, "", 0, 0, "", 0); Label Lbcantidad = panelInfo.Controls[2] as Label; string textcantidad = Lbcantidad.Text; string[] cantidadCadenas = textcantidad.Split(' '); int cantidad = int.Parse(cantidadCadenas[1]); DetalleVentaModel detalleVenta = new DetalleVentaModel(cantidad, producto); detalleVentas.Add(detalleVenta); } return detalleVentas; }*/ private void button6_Click(object sender, EventArgs e) { } private void btnFiar_Click(object sender, EventArgs e) { List detallesCuenta = new List(); foreach (DetalleVentaModel detalleVenta in carrito) detallesCuenta.Add(detalleVenta.convertirADetalleCuenta()); if (detallesCuenta.Count > 0) { Cuenta ventaModel = new Cuenta(total); datosCuenta datoCuenta = new datosCuenta(ventaModel, detallesCuenta,importes, this); datoCuenta.Show(); } else { MessageBox.Show("No hay ningun producto agregado"); } } private void responsablecb_SelectedIndexChanged(object sender, EventArgs e) { // Verificar si hay un elemento seleccionado en el ComboBox if (responsablecb.SelectedItem != null) { // Habilitar los botones bntImprimir.Enabled = true; btnFiar.Enabled = true; btnEnviar.Enabled = true; } else { bntImprimir.Enabled = false; btnFiar.Enabled = false; btnEnviar.Enabled = false; } } private void txtbusqueda_TextChanged(object sender, EventArgs e) { if (!txtbusqueda.Text.Equals("")) { productos = service.conseguirProductosFiltrados(txtbusqueda.Text); llenarLayout(); } else { getData(); llenarLayout(); } } private void btnEnviar_Click(object sender, EventArgs e) { List detallesEnvio = new List(); foreach(DetalleVentaModel detalleVenta in carrito) { detallesEnvio.Add(detalleVenta.convertirADetalleEnvio()); } string responsable = responsablecb.Text.Equals("") ? loginPrincipal.usuario : responsablecb.Text; Envio envio = new Envio(-1, DateTime.Now.ToString(), "", "", responsable, "", "", total); if (detallesEnvio.Count > 0) { datosEnvio datosEnvio = new datosEnvio(envio, detallesEnvio,importes ,this); datosEnvio.Show(); } else { MessageBox.Show("No hay ningun producto agregado"); } } public void eliminarProductosTocket() { for (int i = flowLayoutPanel2.Controls.Count - 1; i > 2; i--) { Control c = flowLayoutPanel2.Controls[i]; c.Dispose(); flowLayoutPanel1.Controls.Remove(c); } label1.Text = "Total: 0"; txtbusqueda.Text = ""; carrito.Clear(); } private void button2_Click(object sender, EventArgs e) { Estadiscticas estadiscticas = new Estadiscticas(); estadiscticas.Owner = this; estadiscticas.Show(); } private void btnImporte_Click(object sender, EventArgs e) { Importe1 importe = new Importe1(this); importe.Owner = this; importe.Show(); } public void actualizarImporteTotal() { decimal totalImporte = 0; foreach(DetalleImporte importe in importes) { totalImporte += importe.precioImporte * importe.cantidad; } total += totalImporte; label1.Text = $"Total: ${total}"; } private void button3_Click(object sender, EventArgs e) { } } }