Beispiel #1
0
        public static string Insertar(int idventa, int idcliente, int idtrabajador, DateTime fecha, string tipo_pago,
            string no_comprobante, string no_crefical, string no_auttarjeta, decimal igv, int estado, DataTable dtDetalles)
        {
            VentaDAL proc = new VentaDAL();
            Venta entidad = new Venta();
            entidad.IDventa = idventa; ;
            entidad.IDTrabajador = idtrabajador;
            entidad.IDCliente = idcliente;
            entidad.Fecha = fecha;
            entidad.Tipo_Pago = tipo_pago;
            entidad.No_Comprobante = no_comprobante;
            entidad.No_Crefiscal = no_crefical;
            entidad.No_Auttarjeta = no_auttarjeta;
            entidad.IGV = igv;
            entidad.Estado = estado;


            List<Detalle_Venta> detalles = new List<Detalle_Venta>();
            foreach (DataRow row in dtDetalles.Rows)
            {
                Detalle_Venta detalle = new Detalle_Venta();
                detalle.IDDetalle_Ingreso = Convert.ToInt32(row["iddetalle_ingreso"].ToString());
                detalle.IDVenta = Convert.ToInt32(row["idventa"].ToString());
                detalle.Cantidad = Convert.ToInt32(row["cantidad"].ToString());
                detalle.Precio_Venta = Convert.ToDecimal(row["precio_venta"].ToString());
                detalle.Descuento = Convert.ToDecimal(row["descuento"].ToString());
                detalles.Add(detalle);
            }


            return proc.Insertar(entidad, detalles);
        }
        private async void btnSaveCompra_Click(object sender, EventArgs e)
        {
            try
            {
                Producto producto;
                producto = obsProducto[prodComboBox.SelectedIndex];

                Detalle_Venta detVenta = new Detalle_Venta();

                detVenta.Producto        = producto;
                detVenta.Venta           = new Venta();
                detVenta.Venta.Empleado  = obsEmpleado[vendComboBox.SelectedIndex];
                detVenta.precio_unitario = 1;
                detVenta.id_producto     = producto.id_producto;
                detVenta.cantidad        = Convert.ToInt32(CantCompraTextBox.Text);
                frmInventario frm = new frmInventario();

                double montoVenta = await frm.GetLastPromedio(Convert.ToInt32(detVenta.id_producto));

                detVenta.monto = (float)montoVenta * detVenta.cantidad;

                listaProducto.Add(detVenta);

                dgvVenta.Rows.Add(new string[] { detVenta.Producto.nombre, detVenta.cantidad.ToString(), dateTimePicker1.Value.ToShortDateString(), detVenta.monto.ToString(), detVenta.Producto.Proveedor.nombre });
            }
            catch (Exception)
            {
                MessageBox.Show("Ah ocurrido un error", "inesperado",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;

                throw;
            }
        }
Beispiel #3
0
        public static string Insertar(int idcliente, int idtrabajador, DateTime fecha,
                                      string tipo_comprobante, string serie, string correlativo, decimal igv,
                                      DataTable dtDetalles)
        {
            Venta  Obj  = new Venta();
            dVenta objv = new dVenta();

            Obj.Idcliente        = idcliente;
            Obj.Idtrabajador     = idtrabajador;
            Obj.Fecha            = fecha;
            Obj.Tipo_Comprobante = tipo_comprobante;
            Obj.Serie            = serie;
            Obj.Correlativo      = correlativo;
            Obj.Igv = igv;
            List <Detalle_Venta> detalles = new List <Detalle_Venta>();

            foreach (DataRow row in dtDetalles.Rows)
            {
                Detalle_Venta detalle = new Detalle_Venta();
                detalle.Iddetalle_ingreso = Convert.ToInt32(row["iddetalle_ingreso"].ToString());
                detalle.Cantidad          = Convert.ToInt32(row["cantidad"].ToString());
                detalle.Precio_Venta      = Convert.ToDecimal(row["precio_venta"].ToString());
                detalle.Descuento         = Convert.ToDecimal(row["descuento"].ToString());
                detalles.Add(detalle);
            }
            return(objv.Insertar(Obj, detalles));
        }
        private void Pantalla_Productos_Load(object sender, EventArgs e)
        {
            txtAyuda.Text     = ClaseCompartida.nombreProducto;
            txtAyuda2.Text    = ClaseCompartida.paterno;
            txtAyuda3.Text    = ClaseCompartida.cantidadVenta;
            DGVayuda.Visible  = false;
            DGVayuda2.Visible = false;
            txtAyuda.Visible  = false;
            txtAyuda2.Visible = false;
            txtAyuda3.Visible = false;

            Producto      pp = new Producto();
            Cliente       cc = new Cliente();
            Detalle_Venta dv = new Detalle_Venta();

            using (ProyectoFarmaciaEntities1 bd = new ProyectoFarmaciaEntities1())
            {
                /*var lstcod = from d in bd.Producto
                 *           where d.Nombre_Producto.Contains(txtAyuda.Text)
                 *           select d;
                 * DGVayuda.DataSource = lstcod.ToList();
                 * txtCodigo.Text = DGVayuda.Rows[DGVayuda.CurrentRow.Index].Cells[0].Value.ToString();
                 * txtNombreP.Text = DGVayuda.Rows[DGVayuda.CurrentRow.Index].Cells[1].Value.ToString();
                 * txtFecha.Text = DGVayuda.Rows[DGVayuda.CurrentRow.Index].Cells[2].Value.ToString();
                 * txtStock.Text = DGVayuda.Rows[DGVayuda.CurrentRow.Index].Cells[3].Value.ToString();
                 * txtPrecio.Text = DGVayuda.Rows[DGVayuda.CurrentRow.Index].Cells[4].Value.ToString();
                 * txtCategoria.Text = DGVayuda.Rows[DGVayuda.CurrentRow.Index].Cells[5].Value.ToString();
                 * txtProveedor.Text = DGVayuda.Rows[DGVayuda.CurrentRow.Index].Cells[6].Value.ToString();
                 * txtDesc.Text = DGVayuda.Rows[DGVayuda.CurrentRow.Index].Cells[7].Value.ToString();
                 * txt.Text = txtAyuda3.Text;
                 */
                var lstcod2 = from f in bd.Cliente
                              where f.Paterno.Contains(txtAyuda2.Text)
                              select f;
                DGVayuda2.DataSource = lstcod2.ToList();

                txtCodigoC.Text   = DGVayuda2.Rows[DGVayuda2.CurrentRow.Index].Cells[0].Value.ToString();
                txtNombre.Text    = DGVayuda2.Rows[DGVayuda2.CurrentRow.Index].Cells[1].Value.ToString();
                txtPaterno.Text   = DGVayuda2.Rows[DGVayuda2.CurrentRow.Index].Cells[2].Value.ToString();
                txtCi.Text        = DGVayuda2.Rows[DGVayuda2.CurrentRow.Index].Cells[3].Value.ToString();
                txtDireccion.Text = DGVayuda2.Rows[DGVayuda2.CurrentRow.Index].Cells[4].Value.ToString();
                txtTelefono.Text  = DGVayuda2.Rows[DGVayuda2.CurrentRow.Index].Cells[5].Value.ToString();

                var max = (from g in bd.Detalle_Venta
                           select g.Codigo_Detalle).Max();
                int maxi = Convert.ToInt32(max);
                txtAyuda4.Text = Convert.ToString(maxi + 1);

                int total = 0, total2 = 0;
                for (int i = 0; i < ClaseCompartida.carrito; i++)
                {
                    pp     = bd.Producto.Find(ClaseCompartida.productos[i, 0]);
                    total2 = (ClaseCompartida.productos[i, 1]) * Convert.ToInt32(pp.Precio_Unitario);
                    total  = total + total2;
                }
                txtAyuda5.Text = Convert.ToString(total);
                CargaDatos();
            }
        }
Beispiel #5
0
        public string Insertar(Detalle_Venta Detalle_Venta,
                               ref SqlConnection SqlCon, ref SqlTransaction SqlTra)
        {
            string rpta = "";

            try
            {
                SqlCommand SqlCmd = new SqlCommand();
                SqlCmd.Connection  = SqlCon;
                SqlCmd.Transaction = SqlTra;
                SqlCmd.CommandText = "spinsertar_detalle_venta";
                SqlCmd.CommandType = CommandType.StoredProcedure;

                SqlParameter ParIddetalle_Venta = new SqlParameter();
                ParIddetalle_Venta.ParameterName = "@iddetalle_venta";
                ParIddetalle_Venta.SqlDbType     = SqlDbType.Int;
                ParIddetalle_Venta.Direction     = ParameterDirection.Output;
                SqlCmd.Parameters.Add(ParIddetalle_Venta);

                SqlParameter ParIdventa = new SqlParameter();
                ParIdventa.ParameterName = "@idventa";
                ParIdventa.SqlDbType     = SqlDbType.Int;
                ParIdventa.Value         = Detalle_Venta.Idventa;
                SqlCmd.Parameters.Add(ParIdventa);

                SqlParameter ParIddetalle_ingreso = new SqlParameter();
                ParIddetalle_ingreso.ParameterName = "@iddetalle_ingreso";
                ParIddetalle_ingreso.SqlDbType     = SqlDbType.Int;
                ParIddetalle_ingreso.Value         = Detalle_Venta.Iddetalle_ingreso;
                SqlCmd.Parameters.Add(ParIddetalle_ingreso);

                SqlParameter ParCantidad = new SqlParameter();
                ParCantidad.ParameterName = "@cantidad";
                ParCantidad.SqlDbType     = SqlDbType.Int;
                ParCantidad.Value         = Detalle_Venta.Cantidad;
                SqlCmd.Parameters.Add(ParCantidad);

                SqlParameter ParPrecioVenta = new SqlParameter();
                ParPrecioVenta.ParameterName = "@precio_venta";
                ParPrecioVenta.SqlDbType     = SqlDbType.Money;
                ParPrecioVenta.Value         = Detalle_Venta.Precio_Venta;
                SqlCmd.Parameters.Add(ParPrecioVenta);

                SqlParameter ParDescuento = new SqlParameter();
                ParDescuento.ParameterName = "@descuento";
                ParDescuento.SqlDbType     = SqlDbType.Money;
                ParDescuento.Value         = Detalle_Venta.Descuento;
                SqlCmd.Parameters.Add(ParDescuento);


                rpta = SqlCmd.ExecuteNonQuery() == 1 ? "OK" : "NO se Ingreso el Registro";
            }
            catch (Exception ex)
            {
                rpta = ex.Message;
            }

            return(rpta);
        }
Beispiel #6
0
 public static int Eliminar(Detalle_Venta detalle_venta)
 {
     SqlParameter[] dbParams = new SqlParameter[]
     {
         FDBHelper.MakeParam("@Id", SqlDbType.VarChar, 0, detalle_venta.Id)
     };
     return(Convert.ToInt32(FDBHelper.ExecuteScalar("usp_Data_Fdetalle_venta_Eliminar", dbParams)));
 }
Beispiel #7
0
 internal static int aumentar_stock(Detalle_Venta dventa)
 {
     SqlParameter[] dbParams = new SqlParameter[]
     {
         FDBHelper.MakeParam("@ProductoId", SqlDbType.Int, 0, dventa.Producto.Id),
         FDBHelper.MakeParam("@Cantidad", SqlDbType.Decimal, 0, dventa.Cantidad),
     };
     return(Convert.ToInt32(FDBHelper.ExecuteScalar("usp_Data_Fdetalle_venta_aumentar_stock", dbParams)));
 }
Beispiel #8
0
        // GET: Detalle_Venta

        public HttpResponseMessage Post(Detalle_Venta item)
        {
            item = c.Post(item);
            if (item == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Los datos del Detalle_Venta no pueden ser nulos"));
            }
            return(Request.CreateResponse(HttpStatusCode.Created, item));
        }
Beispiel #9
0
 public Detalle_Venta Post(Detalle_Venta item)
 {
     if (item == null)
     {
         return(null);
     }
     c.Detalle_Venta.Add(item);
     c.SaveChanges();
     return(item);
 }
Beispiel #10
0
        public void DeleteJuegoID(int idjuego, int idventa)
        {
            TParcialEntities2 tstDb   = new TParcialEntities2();
            Detalle_Venta     detalle = new Detalle_Venta();

            detalle.Id_Juego           = idjuego;
            detalle.Id_Venta           = idventa;
            tstDb.Entry(detalle).State = System.Data.Entity.EntityState.Deleted;
            tstDb.SaveChanges();
        }
Beispiel #11
0
        public HttpResponseMessage GetById(int id)
        {
            Detalle_Venta items = c.GetById(id);

            if (items == null)
            {
                //Construyendo respuesta del servidor
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay ningun Detalle_Venta con el id " + id));
            }
            return(Request.CreateResponse(HttpStatusCode.OK, items));
        }
Beispiel #12
0
 public static int Insertar(Detalle_Venta detalle_venta)
 {
     SqlParameter[] dbParams = new SqlParameter[]
     {
         FDBHelper.MakeParam("@VentaId", SqlDbType.Int, 0, detalle_venta.Venta.Id),
         FDBHelper.MakeParam("@ProductoID", SqlDbType.Int, 0, detalle_venta.Producto.Id),
         FDBHelper.MakeParam("@Cantidad", SqlDbType.Decimal, 0, detalle_venta.Cantidad),
         FDBHelper.MakeParam("@PrecioUnitario", SqlDbType.Decimal, 0, detalle_venta.Precio_unitario),
     };
     return(Convert.ToInt32(FDBHelper.ExecuteScalar("usp_Data_Fdetalle_venta_Insertar", dbParams)));
 }
Beispiel #13
0
        public void AgregarDetalle(int ID_Venta, int ID_Juego, int importe, int Cantidad)
        {
            TParcialEntities2 tstDb = new TParcialEntities2();

            Detalle_Venta DV = new Detalle_Venta
            {
                Id_Juego = ID_Juego,
                Id_Venta = ID_Venta,
                Importe  = importe,
                Cantidad = Cantidad
            };

            tstDb.Detalle_Venta.Add(DV);
            tstDb.SaveChanges();
        }
Beispiel #14
0
        public bool Put(int id, Detalle_Venta item)
        {
            var resp = c.Detalle_Venta.Find(id);

            if (resp == null)
            {
                return(false);
            }
            resp.cantidad        = item.cantidad;
            resp.id_venta        = item.id_venta;
            resp.id_producto     = item.id_producto;
            resp.monto           = item.monto;
            resp.precio_unitario = item.precio_unitario;
            c.Entry(resp).State  = System.Data.Entity.EntityState.Modified;
            c.SaveChanges();
            return(true);
        }
Beispiel #15
0
        //Metodo Put
        public HttpResponseMessage Put(int id, Detalle_Venta Detalle_Venta)
        {
            var item = c.GetById(id);

            if (item == null)
            {
                //Construyendo respuesta del servidor
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "No hay ningun Detalle_Venta con el id " + id + " para actualizar"));
            }
            var isPut = c.Put(id, Detalle_Venta);

            if (!isPut)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotModified, "No ha sido posible la actualizacion"));
            }
            return(Request.CreateResponse(HttpStatusCode.OK, "El registro ha sido actualizado"));
        }
        /// <summary>
        /// metodo para poder insertar el detalle de las ventas
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public static bool insertar(Detalle_Venta d)
        {
            bool isInsert = false;

            using (EleventaNTierLayerV2DbContext Db = new EleventaNTierLayerV2DbContext())
            {
                Db.Detalle_Ventas.Add(d);

                int rowsAffected = Db.SaveChanges();

                if (rowsAffected > 0)
                {
                    isInsert = true;
                }
            }
            return(isInsert);
        }
Beispiel #17
0
        public string Insertar(Detalle_Venta dve)
        {
            SqlConnection SqlCon = conexion.ConecctionString();
            string        rpta   = "";

            try
            {
                if (SqlCon.State == ConnectionState.Closed)
                {
                    SqlCon.Open();
                }
                SqlCommand SqlCmd = new SqlCommand();
                SqlCmd.Connection  = SqlCon;
                SqlCmd.CommandText = "proc_Detalle_VentaInsert";
                SqlCmd.CommandType = CommandType.StoredProcedure;

                //En esta parte se envian los parametros al procedimiento almacenado

                SqlCmd.Parameters.AddWithValue("@IDDetalleIngreso", dve.IDDetalle_Ingreso);
                SqlCmd.Parameters.AddWithValue("@IDVenta", dve.IDVenta);
                SqlCmd.Parameters.AddWithValue("@Cantidad", dve.Cantidad);
                SqlCmd.Parameters.AddWithValue("@PrecioVenta", dve.Precio_Venta);
                SqlCmd.Parameters.AddWithValue("@Descuento", dve.Descuento);

                //ejecutamos la consulta, en caso de que retorne 1 será OK

                rpta = SqlCmd.ExecuteNonQuery() == 1 ? "OK" : "No se ha posido insertar";
            }
            catch (Exception ex)
            {
                rpta = ex.Message;
            }
            finally
            {
                if (SqlCon.State == ConnectionState.Open)
                {
                    SqlCon.Close();
                }
            }


            return(rpta);
        }
        private void btnProceder_Click(object sender, EventArgs e)
        {
            if (txtAyuda6.Text == "")
            {
                MessageBox.Show("Debe escribir una descripcion para el Detalle");
            }
            else
            {
                Producto emp = new Producto();
                using (ProyectoFarmaciaEntities1 DB = new ProyectoFarmaciaEntities1())
                {
                    for (int i = 0; i < ClaseCompartida.carrito; i++)
                    {
                        emp                 = DB.Producto.Find(ClaseCompartida.productos[i, 0]);
                        emp.Stock           = emp.Stock - ClaseCompartida.productos[i, 1];
                        DB.Entry(emp).State = System.Data.Entity.EntityState.Modified;
                        DB.SaveChanges();
                    }

                    Detalle_Venta emp1 = new Detalle_Venta();
                    emp1.Codigo_Detalle = Convert.ToInt32(txtAyuda4.Text);
                    emp1.Monto_Total    = Convert.ToInt32(txtAyuda5.Text);
                    emp1.Descripcion    = txtAyuda6.Text;
                    DB.Detalle_Venta.Add(emp1);
                    DB.SaveChanges();
                }
                ClaseCompartida.nombreProducto = txtCodigo.Text;
                ClaseCompartida.paterno        = txtCodigoC.Text;
                ClaseCompartida.codigoDetalle  = Convert.ToInt32(txtAyuda4.Text);

                MessageBox.Show("Venta realizada satisfactoriamente");
                Pantalla_Recibo formMenu = new Pantalla_Recibo();
                formMenu.Show();
                this.Close();
            }
        }
Beispiel #19
0
 {/// <summary>
  /// metodo para validar el regisrto de la insersion de el detalle de las ventas
  /// </summary>
  /// <param name="d"></param>
  /// <returns></returns>
     public static bool insertar(Detalle_Venta d)
     {
         return(DataAccessLayer.Detalle_VentaDAL.insertar(d));
     }
Beispiel #20
0
        private void btnFacturar_Click(object sender, EventArgs e)
        {
            using (VENTASEntities bd = new VENTASEntities())
            {
                Venta    tbV = new Venta();
                Empleado em  = new Empleado();
                Cliente  cli = new Cliente();

                if (txtNombreCliente.Text != "" && txtApellidoCliente.Text != "" && txtTelefono.Text != "" && txtDUI.Text != "" && txtDireccion.Text != "")

                {
                    if (cbFactura.Checked == true && cbTickect.Checked == false)
                    {
                        em = bd.Empleados.Where(idBuscar => idBuscar.nombre_empleado == lblNombreCajero.Text).First();
                        int idEmpleado = em.id_empleado;

                        string buscarCliente = txtDUI.Text;
                        cli = bd.Clientes.Where(idBuscar => idBuscar.dui == buscarCliente).First();


                        tbV.id_documento = 1;
                        tbV.id_cliente   = cli.id_cliente;
                        tbV.id_empleado  = idEmpleado;
                        tbV.total_venta  = Convert.ToDecimal(lblTotal.Text);
                        tbV.fecha        = Convert.ToDateTime(dtpFecha.Text);
                        bd.Ventas.Add(tbV);
                        bd.SaveChanges();
                    }
                    else if (cbTickect.Checked == true && cbFactura.Checked == false)
                    {
                        em = bd.Empleados.Where(idBuscar => idBuscar.nombre_empleado == lblNombreCajero.Text).First();
                        int idEmpleado = em.id_empleado;

                        tbV.id_documento = 2;
                        tbV.id_cliente   = 1;
                        tbV.id_empleado  = idEmpleado;
                        tbV.total_venta  = Convert.ToDecimal(lblTotal.Text);
                        tbV.fecha        = Convert.ToDateTime(dtpFecha.Text);
                        bd.Ventas.Add(tbV);
                        bd.SaveChanges();
                    }


                    Detalle_Venta dete = new Detalle_Venta();


                    for (int i = 0; i < dgvDetalleVenta.RowCount; i++)
                    {
                        string idProducto   = dgvDetalleVenta.Rows[i].Cells[0].Value.ToString();
                        int    idConvertido = Convert.ToInt32(idProducto);

                        string Cantidad           = dgvDetalleVenta.Rows[i].Cells[3].Value.ToString();
                        int    CantidadConvertido = Convert.ToInt32(Cantidad);

                        string  Total           = dgvDetalleVenta.Rows[i].Cells[4].Value.ToString();
                        decimal TotalConvertido = Convert.ToDecimal(Total);


                        dete.id_venta    = Convert.ToInt32(lblIdVenta.Text);
                        dete.id_producto = idConvertido;
                        dete.cantidad    = CantidadConvertido;
                        dete.precio      = TotalConvertido;
                        bd.Detalle_Venta.Add(dete);
                        bd.SaveChanges();
                    }

                    Producto pro = new Producto();

                    for (int i = 0; i < dgvDetalleVenta.RowCount; i++)
                    {
                        //OBTENIENDO DATOS

                        string idProducto   = dgvDetalleVenta.Rows[i].Cells[0].Value.ToString();
                        int    idConvertido = Convert.ToInt32(idProducto);

                        string Cantidad           = dgvDetalleVenta.Rows[i].Cells[3].Value.ToString();
                        int    CantidadConvertido = Convert.ToInt32(Cantidad);

                        pro = bd.Productos.Where(BuscarId => BuscarId.id_producto == idConvertido).First();
                        int existencias = Convert.ToInt32(pro.cantidad);

                        //ELIMINANDO EN INVENTARIO

                        int restar = existencias - CantidadConvertido;

                        pro.cantidad        = restar;
                        bd.Entry(pro).State = System.Data.Entity.EntityState.Modified;
                        bd.SaveChanges();
                    }

                    //IMPRIMIENDO FACTURA

                    pdImprimir = new PrintDocument();
                    PrinterSettings ps = new PrinterSettings();
                    pdImprimir.PrinterSettings = ps;
                    pdImprimir.PrintPage      += Imprimir;
                    pdImprimir.Print();



                    limpiarproducto();
                    LimpiarCliente();
                    dgvDetalleVenta.Rows.Clear();
                    RetornarId();
                    lblTotal.Text = "";
                    MessageBox.Show("Venta Guardada con exito");
                }
                else
                {
                    MessageBox.Show("No se han definido algunos valores");
                }
            }
        }
Beispiel #21
0
        public static void Cobrar_Producto(DataTable dt, string codeBar, int quantity)
        {
            Console.Clear();

            Producto p      = new Producto();
            string   CodBar = string.Empty;
            int      resp;

            do
            {
                Console.Clear();

                Console.Write("\nCodigo de Barras: "); CodBar = Console.ReadLine();

                BuscarProducto(CodBar, dt);

                ExtensionDataTable.PrintToConsole(dt);

                Console.WriteLine("\n");

                ImprimirTabla();

                Console.WriteLine("\n¿Desea Ingresar  otro Articulo?\n"
                                  + "1.- Si\n"
                                  + "2.- No");
                resp = Convert.ToInt32(Console.ReadLine());
            } while (resp == 1);

            if (resp == 2)
            {
                Console.Clear();

                string msgError = string.Empty;

                Venta v = new Venta();

                v.Sucursal            = "Gral Escobedo";
                v.Fecha               = DateTime.Now;
                v.Importe             = total;
                v.CantidadDeArticulos = CantidadDeArticulos;
                v.Caja = "1";

                msgError = BusinessLogicLayer.VentaBLL.RealizarVenta(v);

                if (string.IsNullOrEmpty(msgError))
                {
                    int saleId = BusinessLogicLayer.VentaBLL.UltimoRegistro();

                    if (saleId > 0)
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            Detalle_Venta d = new Detalle_Venta();

                            d.IdVenta    = saleId;
                            d.IdProducto = Convert.ToInt32(BusinessLogicLayer.ProductoBLL.ProductoCodigoId(row["Codigo Barras"].ToString()));
                            d.Cantidad   = Convert.ToInt32(row["Cantidad"].ToString());
                            d.Total      = Convert.ToDouble(row["Total"].ToString());

                            bool isCheked = BusinessLogicLayer.Detalle_VentaBLL.insertar(d);

                            codeBar  = row["Codigo Barras"].ToString();
                            quantity = 1;

                            BusinessLogicLayer.ProductoBLL.ModificarInventarioVenta(codeBar, quantity);

                            if (isCheked)
                            {
                                Console.WriteLine("\n\tCOMPRA REALIZADA");
                                Console.WriteLine("\n\tREGRESE PRONTO LO ESTAREMOS ESPERANDO");
                                Console.WriteLine("");
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine(msgError);
                    Console.ReadLine();
                }
            }
        }
 private void CantCompraTextBox_OnValueChanged(object sender, EventArgs e)
 {
     Detalle_Venta detVenta = new Detalle_Venta();
 }
        public ActionResult FinalizarCompra(string direc, string desc)
        {
            List <CarritoItem> compras = (List <CarritoItem>)Session["carrito"];

            if (compras != null && compras.Count > 0)
            {
                for (int i = 0; i < compras.Count; i++)
                {
                    Detalle_Venta dventa     = new Detalle_Venta();
                    var           maxDetalle = (from g in db.Detalle_Venta
                                                select g.Codigo_Detalle).Max();
                    int maxDetallei = Convert.ToInt32(maxDetalle);

                    dventa.Codigo_Detalle = maxDetallei + 1;
                    dventa.Monto_Total    = compras.Sum(x => x.Producto.Precio_Unitario * x.Cantidad);
                    dventa.Descripcion    = ClaseCompartida.tipoCliente.ToString();

                    Venta nuevaVenta = new Venta();
                    //Sacar el maximo de nuestra tabla Venta
                    var maxVenta = (from g in db.Venta
                                    select g.Codigo_Venta).Max();
                    int maxVentai = Convert.ToInt32(maxVenta);
                    nuevaVenta.Codigo_Venta = maxVentai + 1;// Codigo Venta

                    nuevaVenta.Codigo_Cliente = 10;
                    nuevaVenta.Id_Personas    = 1;

                    nuevaVenta.Codigo_Producto = ClaseCompartida.tipoCliente;


                    //nuevaVenta.Detalle_Venta = (from detalle in compras
                    //                            select new Detalle_Venta
                    //                            {
                    //                                Codigo_Detalle = maxDetallei + 1,
                    //                                Monto_Total = Convert.ToDouble(detalle.Cantidad * detalle.Producto.Precio_Unitario),
                    //                                Descripcion = detalle.Producto.Nombre_Producto
                    //                            });

                    nuevaVenta.Codigo_Detalle_Venta = maxDetallei + 1;
                    nuevaVenta.Cantidad             = compras.Sum(x => x.Cantidad);
                    nuevaVenta.Fecha_Venta          = DateTime.Now;
                    nuevaVenta.Tipo_Venta           = "Linea";


                    Ubicacion_Pedido ubicacion = new Ubicacion_Pedido();
                    var maxUbicacion           = (from g in db.Ubicacion_Pedido
                                                  select g.Codigo_Ubicacion).Max();
                    int maxUbicacion1 = Convert.ToInt32(maxUbicacion);
                    ubicacion.Codigo_Ubicacion = maxUbicacion1 + 1;


                    ubicacion.Descripcion = direc + ", " + desc;

                    Detalle_Pedido detalle_Pedido = new Detalle_Pedido();
                    var            max            = (from g in db.Detalle_Pedido
                                                     select g.Codigo_Detalle).Max();
                    int maxDP1 = Convert.ToInt32(max);
                    detalle_Pedido.Codigo_Detalle = maxDP1 + 1;
                    detalle_Pedido.Estado_Pedido  = "Por entregar";
                    detalle_Pedido.Subtotal       = compras.Sum(x => x.Producto.Precio_Unitario * x.Cantidad);

                    Comprobante comprobante    = new Comprobante();
                    var         maxComprobante = (from g in db.Comprobante
                                                  select g.Numero_Comprobante).Max();
                    int maxComprobante1 = Convert.ToInt32(maxComprobante);
                    comprobante.Numero_Comprobante = maxComprobante1 + 1;
                    comprobante.Fecha_Emision      = DateTime.Now;
                    comprobante.Estado             = "En camino";
                    comprobante.Detalle            = "Compra satisfactoria";

                    pedido pedido    = new pedido();
                    var    maxPedido = (from g in db.pedido
                                        select g.Codigo_Pedido).Max();
                    int maxPedido1 = Convert.ToInt32(maxPedido);
                    pedido.Codigo_Pedido           = maxPedido + 1;
                    pedido.Fecha_Hora_Pedido       = DateTime.Now;
                    pedido.Fecha_Hora_Entrega      = DateTime.Now;
                    pedido.Codigo_Direccion_Pedido = maxUbicacion1 + 1;
                    pedido.Codigo_Personas         = 1;
                    pedido.Codigo_Detalle_Pedido   = maxDP1 + 1;
                    pedido.Codigo_Cliente          = 4;
                    pedido.Codigo_Venta            = maxVentai + 1;
                    pedido.Numero_Comprobante      = maxComprobante1 + 1;

                    db.Detalle_Venta.Add(dventa);
                    db.Venta.Add(nuevaVenta);
                    db.Ubicacion_Pedido.Add(ubicacion);
                    db.Detalle_Pedido.Add(detalle_Pedido);
                    db.Comprobante.Add(comprobante);
                    db.pedido.Add(pedido);


                    db.SaveChanges();
                    Session["carrito"] = new List <CarritoItem>();
                }
            }
            return(View());
        }