feat: terminados 4 de 7 forms
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
using Controladora;
|
||||
using Entidades;
|
||||
using Modelo;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
@@ -16,134 +15,76 @@ namespace Vista
|
||||
{
|
||||
public partial class FrmFactura : Form
|
||||
{
|
||||
private Factura factura;
|
||||
private Cliente clienteSeleccionado;
|
||||
private List<Lote> carrito; // Lista para almacenar los lotes en el carrito
|
||||
|
||||
public FrmFactura(Factura? factura = null)
|
||||
private Factura factura = new Factura();
|
||||
private int detalleid;
|
||||
public FrmFactura()
|
||||
{
|
||||
InitializeComponent();
|
||||
ConfigurarDataGridView();
|
||||
ConfigurarDataGridViewCarrito(); // Nueva configuración del DataGridView para el carrito
|
||||
ActualizarGrilla();
|
||||
CargarClientes();
|
||||
carrito = new List<Lote>(); // Inicializar la lista del carrito
|
||||
|
||||
cmbCliente.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
|
||||
|
||||
// Para el primer control NumericUpDown
|
||||
numid.Maximum = int.MaxValue; // Esto permitirá IDs muy grandes
|
||||
|
||||
// Para el segundo control NumericUpDown
|
||||
numtotal.Maximum = decimal.MaxValue; // Esto permitirá totales muy grandes
|
||||
numtotal.Enabled = false; // Deshabilitar el control para que no se pueda modificar
|
||||
|
||||
// Configurar NumericUpDown para unidades
|
||||
numericUpDown1.Maximum = int.MaxValue; // Configurar el máximo valor permitido
|
||||
CargarDatos();
|
||||
|
||||
cmbCliente.DisplayMember = "Cliente";
|
||||
cmbCliente.SelectedIndex = -1;
|
||||
|
||||
if (factura != null)
|
||||
{
|
||||
this.factura = factura;
|
||||
this.Text = "Modificar Factura";
|
||||
CargarDatos();
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Text = "Agregar Factura";
|
||||
}
|
||||
}
|
||||
|
||||
private void ConfigurarDataGridView()
|
||||
private void ActualizarGrilla()
|
||||
{
|
||||
dataGridView1.AutoGenerateColumns = false;
|
||||
dgvProductos.DataSource = null;
|
||||
dgvProductos.DataSource = ControladoraProductos.Instance.Listar();
|
||||
|
||||
dgvDetalles.AutoGenerateColumns = false;
|
||||
|
||||
// Definir las columnas manualmente
|
||||
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
|
||||
dgvDetalles.Columns.Add(new DataGridViewTextBoxColumn
|
||||
{
|
||||
DataPropertyName = "Id",
|
||||
HeaderText = "ID",
|
||||
DataPropertyName = "Id", // Usa la propiedad NombreProducto
|
||||
HeaderText = "Id",
|
||||
Name = "Id"
|
||||
});
|
||||
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
|
||||
dgvDetalles.Columns.Add(new DataGridViewTextBoxColumn
|
||||
{
|
||||
DataPropertyName = "Nombre",
|
||||
HeaderText = "Nombre",
|
||||
Name = "Nombre"
|
||||
});
|
||||
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
|
||||
{
|
||||
DataPropertyName = "Precio",
|
||||
HeaderText = "Precio",
|
||||
Name = "Precio"
|
||||
});
|
||||
}
|
||||
|
||||
private void ConfigurarDataGridViewCarrito()
|
||||
{
|
||||
dataGridView2.AutoGenerateColumns = false;
|
||||
|
||||
// Definir las columnas manualmente
|
||||
dataGridView2.Columns.Add(new DataGridViewTextBoxColumn
|
||||
{
|
||||
DataPropertyName = "NombreProducto", // Usa la propiedad NombreProducto
|
||||
DataPropertyName = "Producto", // Usa la propiedad NombreProducto
|
||||
HeaderText = "Producto",
|
||||
Name = "Producto"
|
||||
});
|
||||
dataGridView2.Columns.Add(new DataGridViewTextBoxColumn
|
||||
dgvDetalles.Columns.Add(new DataGridViewTextBoxColumn
|
||||
{
|
||||
DataPropertyName = "CantidadDeProductos",
|
||||
HeaderText = "Cantidad",
|
||||
Name = "CantidadDeProductos"
|
||||
});
|
||||
dgvDetalles.Columns.Add(new DataGridViewTextBoxColumn
|
||||
{
|
||||
DataPropertyName = "PrecioUnitario",
|
||||
HeaderText = "PrecioUnitario"
|
||||
});
|
||||
dgvDetalles.Columns.Add(new DataGridViewTextBoxColumn
|
||||
{
|
||||
DataPropertyName = "Subtotal",
|
||||
HeaderText = "Subtotal"
|
||||
});
|
||||
|
||||
// Asignar la lista de lotes al DataGridView
|
||||
dataGridView2.DataSource = carrito;
|
||||
}
|
||||
|
||||
|
||||
private void ActualizarGrilla()
|
||||
{
|
||||
dataGridView1.DataSource = null;
|
||||
dataGridView1.DataSource = ControladoraProductos.Instance.Listar();
|
||||
}
|
||||
|
||||
private void CargarClientes()
|
||||
{
|
||||
// Obtener la lista de clientes desde el repositorio
|
||||
ReadOnlyCollection<Cliente> clientes = RepositorioClientes.Instance.Listar();
|
||||
|
||||
// Asignar la lista de clientes como origen de datos para el ComboBox
|
||||
cmbCliente.DataSource = clientes;
|
||||
|
||||
// Establecer la propiedad para mostrar el nombre del cliente en el ComboBox
|
||||
cmbCliente.DisplayMember = "NombreCompleto";
|
||||
}
|
||||
|
||||
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
clienteSeleccionado = (Cliente)cmbCliente.SelectedItem;
|
||||
}
|
||||
|
||||
private void CargarDatos()
|
||||
{
|
||||
numid.Value = factura.Id;
|
||||
numtotal.Value = (decimal)factura.Total;
|
||||
datepick.Value = factura.Fecha;
|
||||
// Asignar la lista de clientes como origen de datos para el ComboBox
|
||||
cmbCliente.DataSource = ControladoraClientes.Instance.Listar();
|
||||
|
||||
// Asignar el cliente seleccionado en el ComboBox
|
||||
if (factura.Cliente != null)
|
||||
{
|
||||
cmbCliente.SelectedItem = factura.Cliente;
|
||||
}
|
||||
// Establecer la propiedad para mostrar el nombre del cliente en el ComboBox
|
||||
cmbCliente.DisplayMember = "NombreCompleto";
|
||||
|
||||
var listdetalle = ControladoraFacturas.Instance.Listar();
|
||||
numid.Value = (listdetalle.Count > 0) ?
|
||||
listdetalle.Max(x => x.Id + 1) :
|
||||
0;
|
||||
|
||||
numid.Enabled = false; // Deshabilitar el control para que no se pueda modificar
|
||||
|
||||
numtotal.Enabled = false; // Deshabilitar el control para que no se pueda modificar
|
||||
|
||||
// Recuperar los lotes asociados a la factura y actualizar el DataGridView
|
||||
carrito = ControladoraLotes.Instance.ListarPorFacturaId(factura.Id).ToList() ?? new List<Lote>();
|
||||
|
||||
dataGridView2.DataSource = null;
|
||||
dataGridView2.DataSource = carrito;
|
||||
// var listaDetalles = ControladoraFacturas.Instance.ListarDetallesFactura(factura);
|
||||
|
||||
// Actualizar el total
|
||||
ActualizarTotal();
|
||||
@@ -153,9 +94,9 @@ namespace Vista
|
||||
{
|
||||
// Recalcular el total de la factura
|
||||
decimal total = 0;
|
||||
foreach (var lote in carrito)
|
||||
foreach (var detalle in factura.MostrarDetalles())
|
||||
{
|
||||
total += (decimal)(lote.Producto.Precio * lote.CantidadDeProductos);
|
||||
total += (decimal)(detalle.Producto.Precio * detalle.Cantidad);
|
||||
}
|
||||
numtotal.Value = total;
|
||||
}
|
||||
@@ -165,7 +106,7 @@ namespace Vista
|
||||
string devolucion = "";
|
||||
|
||||
if (string.IsNullOrEmpty(numid.Text)) devolucion += "El ID no puede ser nulo o vacío\n";
|
||||
if (clienteSeleccionado == null) devolucion += "Debe seleccionar un cliente\n";
|
||||
if (cmbCliente.SelectedIndex == -1) devolucion += "Debe seleccionar un cliente\n";
|
||||
|
||||
if (devolucion == "")
|
||||
{
|
||||
@@ -178,153 +119,120 @@ namespace Vista
|
||||
}
|
||||
}
|
||||
|
||||
private void button1_Click(object sender, EventArgs e)
|
||||
private void btnAceptar_Click(object sender, EventArgs e)
|
||||
{
|
||||
// Validar los datos antes de continuar
|
||||
if (ValidarDatos())
|
||||
{
|
||||
try
|
||||
factura.Total = Convert.ToDouble(numtotal.Value);
|
||||
factura.Fecha = datepick.Value;
|
||||
factura.Id = Convert.ToInt32(numid.Value);
|
||||
factura.Cliente = ControladoraClientes.Instance.Listar().First(x => x.NombreCompleto == cmbCliente.SelectedValue.ToString());
|
||||
|
||||
string mensaje = ControladoraFacturas.Instance.Añadir(factura);
|
||||
MessageBox.Show(mensaje, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
private void btnAddDetalle_Click(object sender, EventArgs e)
|
||||
{
|
||||
// Validar los datos antes de crear el detalle
|
||||
if (ValidarDatosdetalle()) return;
|
||||
if (dgvProductos.SelectedRows.Count > 0)
|
||||
{
|
||||
foreach (DataGridViewRow selectedRow in dgvProductos.SelectedRows)
|
||||
{
|
||||
// Verificar si la ID de la factura ya está en uso
|
||||
if (RepositorioFactura.Instance.ExistePorId((int)numid.Value) && factura == null)
|
||||
Producto producto = (Producto)selectedRow.DataBoundItem;
|
||||
var checkcolicion = factura.MostrarDetalles().Count(x => x.Producto.Id == producto.Id);
|
||||
if (checkcolicion != 0)
|
||||
{
|
||||
MessageBox.Show("La ID de la factura ya está en uso. Por favor, elija una ID diferente.", "ID en Uso", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
MessageBox.Show("El Producto ya fue cargado");
|
||||
return;
|
||||
}
|
||||
|
||||
if (factura == null)
|
||||
factura.AñadirDetalle(new DetalleFactura
|
||||
{
|
||||
// Crear una nueva factura con los datos proporcionados
|
||||
factura = new Factura
|
||||
{
|
||||
Id = (int)numid.Value,
|
||||
Total = (double)numtotal.Value,
|
||||
Fecha = datepick.Value,
|
||||
Cliente = (Cliente)cmbCliente.SelectedItem
|
||||
};
|
||||
// Agregar la factura a la colección
|
||||
ControladoraFacturas.Instance.Añadir(factura);
|
||||
|
||||
// Guardar los lotes asociados a la factura
|
||||
foreach (var lote in carrito)
|
||||
{
|
||||
lote.Id = factura.Id; // Usar la ID de la factura
|
||||
lote.Fecha = factura.Fecha; // Usar la fecha de la factura
|
||||
ControladoraLotes.Instance.Añadir(lote);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Actualizar los datos de la factura existente
|
||||
factura.Id = (int)numid.Value;
|
||||
factura.Total = (double)numtotal.Value;
|
||||
factura.Fecha = datepick.Value;
|
||||
factura.Cliente = (Cliente)cmbCliente.SelectedItem;
|
||||
// Modificar la factura en la colección
|
||||
ControladoraFacturas.Instance.Modificar(factura);
|
||||
|
||||
// Actualizar los lotes asociados a la factura
|
||||
ControladoraLotes.Instance.EliminarPorFacturaId(factura.Id); // Eliminar lotes antiguos
|
||||
foreach (var lote in carrito)
|
||||
{
|
||||
lote.Id = factura.Id; // Usar la ID de la factura
|
||||
lote.Fecha = factura.Fecha; // Usar la fecha de la factura
|
||||
ControladoraLotes.Instance.Añadir(lote);
|
||||
}
|
||||
}
|
||||
MessageBox.Show("Operación realizada con éxito", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
Close();
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Captura cualquier otra excepción que pueda ocurrir
|
||||
MessageBox.Show("Ocurrió un error inesperado: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
Id = int.Parse(detalleid++.ToString()),
|
||||
Cantidad = (int)numCantidad.Value,
|
||||
IdFactura = factura.Id,
|
||||
Producto = ControladoraProductos.Instance.Listar().First(x => x.Id == producto.Id),
|
||||
Subtotal = producto.Precio * Convert.ToInt32(numCantidad.Value),
|
||||
});
|
||||
ActualizarGrillaDetalles();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void button2_Click(object sender, EventArgs e)
|
||||
private void ActualizarGrillaDetalles()
|
||||
{
|
||||
this.Close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void button3_Click(object sender, EventArgs e)
|
||||
{
|
||||
// Validar los datos antes de crear el lote
|
||||
if (ValidarDatos() && ValidarDatosLote())
|
||||
var detalles = factura.MostrarDetalles();
|
||||
dgvDetalles.DataSource = null;
|
||||
if (detalles.Any())
|
||||
{
|
||||
// Verifica si hay una fila seleccionada en el DataGridView
|
||||
if (dataGridView1.CurrentRow != null)
|
||||
var loteDatos = detalles.Select(detalle => new
|
||||
{
|
||||
// Deshabilitar los controles para ID, fecha, y cliente
|
||||
numid.Enabled = false;
|
||||
datepick.Enabled = false;
|
||||
cmbCliente.Enabled = false;
|
||||
Id = detalle.Id,
|
||||
Producto = detalle.Producto.Nombre,
|
||||
CantidadDeProductos = detalle.Cantidad,
|
||||
Subtotal = detalle.Subtotal,
|
||||
PrecioUnitario = detalle.Producto.Precio,
|
||||
}).ToList();
|
||||
|
||||
// Crear un nuevo lote con los datos proporcionados
|
||||
var lote = new Lote
|
||||
{
|
||||
Id = (int)numid.Value, // Usar la misma ID que la de la factura
|
||||
Fecha = datepick.Value, // Usar la misma fecha que la de la factura
|
||||
Producto = (Producto)dataGridView1.CurrentRow.DataBoundItem,
|
||||
CantidadDeProductos = (long)numericUpDown1.Value, // Usar el valor de unidades del NumericUpDown
|
||||
Habilitado = true // Asignar un valor por defecto o según tus necesidades
|
||||
};
|
||||
|
||||
// Añadir el lote al carrito
|
||||
carrito.Add(lote);
|
||||
|
||||
// Actualizar el total de la factura
|
||||
ActualizarTotal();
|
||||
|
||||
// Actualizar el DataGridView para reflejar los cambios
|
||||
dataGridView2.DataSource = null;
|
||||
dataGridView2.DataSource = carrito;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Mostrar un mensaje si no se ha seleccionado ninguna fila
|
||||
MessageBox.Show("Por favor, seleccione un producto en el carrito antes de añadir.", "Selección Requerida", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
}
|
||||
dgvDetalles.DataSource = loteDatos;
|
||||
numtotal.Value = (Decimal)loteDatos.Sum(x => x.Subtotal);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Función actualizada para validar los datos del lote
|
||||
private bool ValidarDatosLote()
|
||||
// metodo para validar los datos del detalle
|
||||
private bool ValidarDatosdetalle()
|
||||
{
|
||||
string devolucion = "";
|
||||
|
||||
// Validar la selección del producto
|
||||
if (dataGridView1.CurrentRow == null)
|
||||
if (dgvProductos.CurrentRow == null)
|
||||
devolucion += "Debe seleccionar un producto para añadir al lote\n";
|
||||
|
||||
// Validar la cantidad de productos
|
||||
if (numericUpDown1.Value <= 0)
|
||||
if (numCantidad.Value <= 0)
|
||||
devolucion += "La cantidad de productos debe ser mayor que cero\n";
|
||||
|
||||
if (devolucion == "")
|
||||
{
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show(devolucion, "Errores de Validación", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void datepick_ValueChanged(object sender, EventArgs e)
|
||||
private void btnCerrar_Click(object sender, EventArgs e)
|
||||
{
|
||||
this.Close();
|
||||
}
|
||||
|
||||
private void btnEliminar_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (dgvDetalles.SelectedRows.Count > 0)
|
||||
{
|
||||
foreach (DataGridViewRow selectedRow in dgvDetalles.SelectedRows)
|
||||
{
|
||||
DetalleFactura det = new DetalleFactura
|
||||
{
|
||||
Id = Convert.ToInt32(selectedRow.Cells["Id"].Value),
|
||||
};
|
||||
var detalleAborrar = factura.MostrarDetalles().First(x => x.Id == det.Id);
|
||||
factura.EliminarDetalle(detalleAborrar);
|
||||
ActualizarGrillaDetalles();
|
||||
detalleid--;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Por favor, selecciona una fila para eliminar Proveedor del producto.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user