Exemplo n.º 1
0
 public VENTA InsertNewVenta(VentaViewModel newVenta)
 {
     try
     {
         using (FeriaVirtualEntities db = new FeriaVirtualEntities())
         {
             VENTA venta = new VENTA
             {
                 IDVENTA                     = DatabaseUtil.GetNextIDVenta(),
                 FECHA                       = newVenta.FECHA,
                 IMPUESTOADUANA              = newVenta.IMPUESTOADUANA,
                 COSTOTRANSPORTE             = newVenta.COSTOTRANSPORTE,
                 COMISIONEMPRESA             = newVenta.COMISIONEMPRESA,
                 PROCESOVENTA_IDPROCESOVENTA = newVenta.PROCESOVENTA_IDPROCESOVENTA,
                 ESTADO                      = "Realizado"
             };
             db.VENTA.Add(venta);
             db.SaveChanges();
             return(venta);
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Carga el producto a la grilla de detalle de ventas
        /// </summary>
        /// <param name="venta"></param>
        /// <param name="producto"></param>
        /// <param name="cantidad"></param>
        /// <returns></returns>
        public static VentaViewModel AgregarProductoALaLista(VentaViewModel venta, ProductoViewModel producto, int cantidad)
        {
            //aca se agrega el producto a la lista, verificar que si el producto ya esta agregado, agregar la cantidad, no el mismo producto
            bool existeProducto = venta.DetalleVenta.Productos.Any(e => e.Id == producto.Id);

            if (existeProducto)
            {
                //si existe el producto, sumo la cantidad
                int indiceProducto = venta.DetalleVenta.Productos.FindIndex(e => e.Id == producto.Id);
                venta.DetalleVenta.Productos[indiceProducto].CantidadPorProducto   += cantidad;
                venta.DetalleVenta.Productos[indiceProducto].PrecioTotalPorProducto =
                    venta.DetalleVenta.Productos[indiceProducto].CantidadPorProducto * venta.DetalleVenta.Productos[indiceProducto].Precio;
            }
            else
            {
                //si no existe el producto, agrego el producto
                venta.DetalleVenta.Productos.Add(new ProductoDetalleViewModel()
                {
                    Id                     = producto.Id,
                    Descripcion            = producto.Descripcion,
                    Precio                 = producto.Precio,
                    CantidadPorProducto    = cantidad,
                    PrecioTotalPorProducto = producto.Precio * cantidad
                });
            }
            //calcular el monto total
            venta.MontoTotal = CalcularMontoTotal(venta);
            return(venta);
        }
Exemplo n.º 3
0
        public ActionResult Add(VentaViewModel model)
        {
            try
            {
                using (BD_MaestroDetalleEntities db = new BD_MaestroDetalleEntities())
                {
                    Venta oVenta = new Venta();
                    oVenta.Fecha   = DateTime.Now;
                    oVenta.Cliente = model.Cliente;
                    db.Venta.Add(oVenta);
                    db.SaveChanges();

                    foreach (var oC in model.Conceptos)
                    {
                        Concepto oConcepto = new Concepto();
                        oConcepto.Cantidad       = oC.Cantidad;
                        oConcepto.Nombre         = oC.Nombre;
                        oConcepto.PrecioUnitario = oC.PrecioUnitario;
                        oConcepto.Total          = oC.Cantidad * oC.PrecioUnitario;
                        oConcepto.IdVenta        = oVenta.IdVenta;
                        db.Concepto.Add(oConcepto);
                    }

                    db.SaveChanges();
                }
                ViewBag.Mesage = "Registro insertado";
                return(View());
            }
            catch (Exception)
            {
                return(View(model));
            }
        }
Exemplo n.º 4
0
        // GET: Venta/Create
        public ActionResult Create()
        {
            VentaViewModel venta = new VentaViewModel();

            venta.Fecha = DateTime.Now;
            return(View(venta));
        }
Exemplo n.º 5
0
 public ActionResult Create(VentaViewModel model, string action)
 {
     if (action.Equals("agregar_producto"))
     {
         model.AgregarItemADetalle();
     }
     return(View(model));
 }
Exemplo n.º 6
0
 public MntVentaForm(ObservableListSource <VentaViewModel> viewModelList)
 {
     InitializeComponent();
     ViewModel     = new VentaViewModel();
     ViewModelList = viewModelList;
     ventaViewModelBindingSource.DataSource = ViewModel;
     CargarCombos();
 }
Exemplo n.º 7
0
 private void InicializarCampos()
 {
     this.venta = new VentaViewModel()
     {
         DetalleVenta = new VentaDetalleViewModel()
         {
             Productos = new List <ProductoDetalleViewModel>()
         }
     };
 }
Exemplo n.º 8
0
        // GET: Ventas/Create
        public ActionResult Create()
        {
            VentaViewModel venta = new VentaViewModel()
            {
                Productos  = new List <Producto>(),
                Clientes   = new List <Cliente>(),
                Comentario = ""
            };

            return(View(venta));
        }
Exemplo n.º 9
0
        public async Task <ActionResult <PromocionViewModel> > GetVigentesVenta(VentaViewModel venta)
        {
            var promociones = await _promocionService.GetVigentesVentaAsync(venta);

            if (promociones == null)
            {
                return(NotFound());
            }

            return(Ok(promociones));
        }
Exemplo n.º 10
0
        public ActionResult IngresarValoresDeVenta(decimal id)
        {
            var venta = new VentaViewModel();

            venta.PROCESOVENTA_IDPROCESOVENTA = id;
            venta.FECHA = DateTime.Now;
            var subastaid = collection.GetSubastaByProcesoVenta(id);
            var costoT    = collection.GetCostoTranporteToVenta(subastaid);

            venta.COSTOTRANSPORTE = costoT;
            return(View(venta));
        }
Exemplo n.º 11
0
        public bool Add(VentaViewModel modelo)
        {
            bool ok = false;

            using (DbContextTransaction transaction = db.Database.BeginTransaction())
            {
                try
                {
                    //Agregar encabezado de venta
                    db.Venta.Add(new Venta
                    {
                        ClienteId  = modelo.VentaCliente.ClienteId,
                        UsuarioId  = modelo.VentaUsuario.UsuarioId,
                        VentaFecha = modelo.Fecha
                    });
                    db.SaveChanges();

                    //Obtener el codigo de la venta ingresada
                    var ventaId = db.Venta.ToList().Select(v => v.VentaId).Max();

                    //Insertar el detalle de la venta
                    foreach (var item in modelo.VentaDetalle)
                    {
                        var ventaDetalle = new VentaDetalle
                        {
                            VentaId              = ventaId,
                            ProductoId           = item.ProductoId,
                            VentaDetalleCantidad = item.Cantidad,
                            VentaDetallePrecio   = item.Precio
                        };
                        db.VentaDetalle.Add(ventaDetalle);
                        db.SaveChanges();

                        //Reducir la existencia del producto
                        var producto = db.Producto.Find(ventaDetalle.ProductoId);
                        producto.ProductoStock = producto.ProductoStock - ventaDetalle.VentaDetalleCantidad;

                        db.Entry(producto).State = EntityState.Modified;
                        db.SaveChanges();
                    }

                    transaction.Commit();
                    ok = true;
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    return(ok);
                }
            }

            return(ok);
        }
Exemplo n.º 12
0
        public ActionResult <VentaViewModel> Get(string codigoV)
        {
            var venta = _ventaService.BuscarxIdentificacion(codigoV);

            if (venta == null)
            {
                return(NotFound());
            }
            var ventaViewModel = new VentaViewModel(venta);

            return(ventaViewModel);
        }
Exemplo n.º 13
0
        public ActionResult Venta(int?searchProductoId, int?MPagoId)
        {
            DetalleVentaViewModel vm  = new DetalleVentaViewModel();
            VentaViewModel        vm1 = new VentaViewModel();

            var lastId = db.Ventas.Select(x => x.VentaId).Max() + 1;

            ViewBag.lastId = lastId;

            var query      = db.Productoes.AsQueryable();
            var query1     = db.Ventas.AsQueryable();
            var ventas     = db.Ventas.OrderByDescending(r => r.VentaId).ToList();
            var productos  = db.Productoes.OrderBy(x => x.ProdutoId).ToList();
            var productos1 = db.Productoes.OrderBy(x => x.ProdutoId).ToList();
            var categorias = db.Categorias.OrderBy(z => z.CategoriaId).ToList();
            var users      = db.Users.OrderBy(s => s.UserId).ToList();
            var mpagos     = db.MPagoes.OrderBy(t => t.MPagoId).ToList();

            vm1.Ventas   = ventas;
            vm.Productos = productos;

            vm.Categorias = categorias;

            if (searchProductoId != null)
            {
                query = query.Where(x => x.ProdutoId == searchProductoId);
            }
            vm.Productos = query.OrderBy(x => x.NombreProducto).ToList();

            if (MPagoId != null)
            {
                query1 = query1.Where(x => x.MPagoId == MPagoId);
            }
            vm1.Ventas = query1.OrderByDescending(x => x.VentaId).ToList();

            vm.Productos1 = productos1;

            foreach (var producto in vm.Productos)
            {
                producto.Categoria = vm.Categorias.FirstOrDefault(x => x.CategoriaId == producto.CategoriaId);
            }

            foreach (var producto1 in vm.Productos)
            {
                producto1.Categoria = vm.Categorias.FirstOrDefault(x => x.CategoriaId == producto1.CategoriaId);
            }

            llenarCBProductos();
            llenarCBMpagos();
            return(View("Venta", vm1));
        }
Exemplo n.º 14
0
        public ActionResult DetalleVenta(VentaViewModel venta)
        {
            DetalleFactura detalle = new DetalleFactura();

            detalle.id_factura  = venta.id_factura;
            detalle.id_producto = venta.id_producto;
            detalle.cantidad    = venta.cantidad;
            detalle.precio      = _db.Producto.FirstOrDefault(x => x.id_producto == venta.id_producto).precio;


            _db.DetalleFactura.Add(detalle);
            _db.SaveChanges();
            return(RedirectToAction("DetalleVenta", new { id = detalle.id_factura }));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Realiza la venta.
        /// </summary>
        /// <param name="venta"></param>
        /// <returns></returns>
        public static bool Vender(VentaViewModel venta)
        {
            bool seVendio;

            try
            {
                VentaDataModel ventaDataModel = Mapper.Map <VentaViewModel, VentaDataModel>(venta);
                seVendio = ventasDao.CreateElement(ventaDataModel);
            }
            catch (System.Exception)
            {
                seVendio = false;
            }
            return(seVendio);
        }
Exemplo n.º 16
0
 public IHttpActionResult Post([FromBody] VentaDTO value)
 {
     if (value.IdVenta == 0 && ModelState.IsValid)
     {
         MaestroVentas mv       = new MaestroVentas();
         double        response = mv.Save(value);
         if (response != -1)
         {
             VentaViewModel vm = new VentaViewModel();
             vm.IdVenta = Convert.ToInt32(response);
             return(Ok(vm));
         }
         return(BadRequest("Entrada Invalida"));
     }
     return(BadRequest("Entrada Invalida"));
 }
Exemplo n.º 17
0
        public ActionResult Actualizar(VentaViewModel venta)
        {
            String url = $"{baseUrl}/{venta.Id}";

            GenericResponseModel <String> responseModel = ApiRequests
                                                          .Put <GenericResponseModel <String>, VentaViewModel, GenericResponseModel <String> >(url, venta, out errorResponse);

            if (errorResponse == null)
            {
                return(Json(responseModel, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(errorResponse, JsonRequestBehavior.AllowGet));
            }
        }
Exemplo n.º 18
0
        public ActionResult Editar(int id)
        {
            var venta = _ventasManager.Find(id);

            if (venta == null)
            {
                // TempData["FlashError"] = MensajesResource.ERROR_MensajesInstitucionales_IdIncorrecto;
                return(RedirectToAction("Index"));
            }

            var ventaModel = new VentaViewModel()
            {
                Descripcion = venta.Descripcion,
            };

            return(View(ventaModel));
        }
Exemplo n.º 19
0
 private void Aceptar()
 {
     try
     {
         if (ventaViewModelBindingSource.Current == null)
         {
             throw new Exception("Debe de seleccionar al menos un registro");
         }
         _VentaViewModel = (VentaViewModel)ventaViewModelBindingSource.Current;
         DialogResult    = DialogResult.OK;
     }
     catch (Exception ex)
     {
         MessageBox.Show(string.Format("Ocurrió un error al agregar, mensaje de error: {0}", ex.Message)
                         , "Agregar", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 20
0
 public IActionResult ListaPromocionesPorVenta([FromBody] VentaViewModel value)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     try
     {
         //return new ObjectResult();
         var promotionsList = _promocionSupervisor.GetPromotionsBySale(value.MediodePago, value.TipoMediodePago,
                                                                       value.EntidadFinanciera, value.CantidadDeCuotas, value.CategoriaProducto);
         return(new ObjectResult(PromocionConverter.ConvertList(promotionsList)));
     }
     catch (Exception ex)
     {
         return(StatusCode(500, ex));
     }
 }
Exemplo n.º 21
0
        public ActionResult Crear(VentaViewModel venta)
        {
            UsuarioViewModel usuario = (UsuarioViewModel)Session["usuario"];

            venta.Trabajador = usuario;

            GenericResponseModel <String> responseModel = ApiRequests
                                                          .Post <GenericResponseModel <String>, VentaViewModel, GenericResponseModel <String> >(baseUrl, venta, out errorResponse);

            if (errorResponse == null)
            {
                return(Json(responseModel, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(errorResponse, JsonRequestBehavior.AllowGet));
            }
        }
Exemplo n.º 22
0
        public IActionResult Update(VentaViewModel oVenta)
        {
            Respuesta oRespuesta = new Respuesta();

            try
            {
                var venta = _miBd.Ventas.Find(oVenta.Id);
                venta.CodigoVenta = oVenta.CodigoVenta;
                venta.ClienteId   = oVenta.ClienteId;
                _miBd.Ventas.Update(venta);
                _miBd.SaveChanges();
                oRespuesta.Exito = 1;
            }
            catch (Exception e)
            {
                oRespuesta.Mensaje = e.Message;
            }
            return(Ok(oRespuesta));
        }
        public ActionResult Registrar(VentaViewModel model, string action)
        {
            if (action == "generar")
            {
                if (!string.IsNullOrEmpty(model.CabeceraIdCliente.ToString()))
                {
                    if (RegistrarVenta(model.ToModel()))
                    {
                        return(Redirect("Index"));
                    }
                }
                else
                {
                    ModelState.AddModelError("cliente", "Debe agregar un cliente para el comprobante");
                }
            }
            else if (action == "agregar_producto")
            {
                // Si no ha pasado nuestra validación, mostramos el mensaje personalizado de error
                if (!model.SeAgregoUnProductoValido())
                {
                    ModelState.AddModelError("producto_agregar", "Solo puede agregar un producto válido al detalle");
                }
                else if (model.ExisteEnDetalle(model.CabeceraIdProducto))
                {
                    ModelState.AddModelError("producto_agregar", "El producto elegido ya existe en el detalle");
                }
                else
                {
                    model.AgregarItemADetalle();
                }
            }
            else if (action == "retirar_producto")
            {
                model.RetirarItemDeDetalle();
            }
            else
            {
                throw new Exception("Acción no definida ..");
            }

            return(View(model));
        }
Exemplo n.º 24
0
        public ActionResult ResumenVenta(VentaViewModel venta)
        {
            var usuario = (USUARIO)Session["usuario"];

            ViewBag.session = usuario.NOMBREUSUARIO;
            var ventaM      = new VentaManager();
            var insertVenta = new VENTA();

            if (venta != null)
            {
                insertVenta = ventaM.InsertNewVenta(venta);
            }
            var ventaDetalle = ventaM.GetAndInsertDetalisVenta(insertVenta);
            var ordenid      = ventaM.GetOrdenIdByProcesoID(venta.PROCESOVENTA_IDPROCESOVENTA);
            var productosOr  = ventaM.GetProductByOrden(ordenid);

            ViewBag.productos = ventaM.GetProductsWithCantidadAndPrecioToResumenVenta(productosOr);
            return(View(ventaDetalle));
        }
Exemplo n.º 25
0
        public ActionResult GuardarVenta(VentaViewModel ventaVM)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Nuevo"));
            }

            var venta = new Models.Ventas()
            {
                ClienteId  = ventaVM.ClienteId,
                EmpleadoId = ventaVM.EmpleadoId,
                Fecha      = DateTime.Now,
            };

            _context.Ventas.Add(venta);

            _context.SaveChanges();

            return(RedirectToAction("AgregarProducto", new { id = _context.Ventas.Max(x => x.Id) }));
        }
Exemplo n.º 26
0
        public ActionResult Editar(int id, VentaViewModel model)
        {
            var venta = _ventasManager.Find(id);

            if (venta == null)
            {
                //TempData["FlashError"] = MensajesResource.ERROR_MensajesInstitucionales_IdIncorrecto;
                return(RedirectToAction("Index"));
            }

            try
            {
                _ventasManager.Actualizar(
                    id,
                    model.Descripcion);

                TempData["FlashSuccess"] = MensajesResource.INFO_Ventas_ActualizadoCorrectamente;
                return(RedirectToAction("Index"));
            }
            catch (BusinessException businessEx)
            {
                ModelState.AddModelError(string.Empty, businessEx.Message);

                return(View(model));
            }
            catch (Exception e)
            {
                var log = CommonManager.BuildMessageLog(
                    TipoMensaje.Error,
                    ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString(),
                    ControllerContext.Controller.ValueProvider.GetValue("action").RawValue.ToString(),
                    e.ToString(), Request);

                CommonManager.WriteAppLog(log, TipoMensaje.Error);

                return(View(model));
            }
        }
Exemplo n.º 27
0
        public ActionResult Crear(VentaViewModel model, FormCollection collection)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                _ventasManager.Crear(
                    model.Descripcion);


                TempData["FlashSuccess"] = MensajesResource.INFO_Ventas_CreadoCorrectamente;
                return(RedirectToAction("Index"));
            }
            catch (BusinessException businessEx)
            {
                ModelState.AddModelError(string.Empty, businessEx.Message);

                return(View(model));
            }
            catch (Exception e)
            {
                var log = CommonManager.BuildMessageLog(
                    TipoMensaje.Error,
                    ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString(),
                    ControllerContext.Controller.ValueProvider.GetValue("action").RawValue.ToString(),
                    e.ToString(), Request);

                CommonManager.WriteAppLog(log, TipoMensaje.Error);

                ModelState.AddModelError(string.Empty, e.Message);
                return(View(model));
            }
        }
Exemplo n.º 28
0
        public ActionResult GenerarVenta(VentaViewModel model)
        {
            llenarCBProductos();
            var user = User.Identity.GetUserId <int>();

            if (ModelState.IsValid)
            {
                var lastId = db.Ventas.Select(x => x.VentaId).Max() + 1;
                var total  = db.DetalleVentas.Where(x => x.VentaId == lastId).ToList();
                var total1 = total.Sum(x => x.DetalleVentaTotal);


                var venta = new Venta();
                venta.VentaMonto   = total1;
                venta.NombreCVenta = model.NombreCVenta;
                venta.UserId       = user;
                venta.MPagoId      = model.MPagoId;
                venta.VentaFecha   = model.VentaFecha;
                venta.VentaHora    = model.VentaHora;
                db.Ventas.Add(venta);
                db.SaveChanges();

                TempData["SuccessMessage"] = "Producto Creado Correctamente";
                return(RedirectToAction("Index", "DetalleVenta"));
            }

            var productos  = db.Productoes.OrderBy(x => x.ProdutoId).ToList();
            var categorias = db.Categorias.OrderBy(z => z.CategoriaId).ToList();



            model.Productos  = productos;
            model.Categorias = categorias;

            return(View("Index", model));
        }
Exemplo n.º 29
0
        public ActionResult DetalleVenta(int id)
        {
            try
            {
                Factura detalleFactura = _db.Factura.FirstOrDefault(p => p.id_factura == id);

                VentaViewModel venta = new VentaViewModel();

                venta.id_factura  = detalleFactura.id_factura;
                venta.id_Cliente  = detalleFactura.Clientes.numeroDocumento;
                venta.id_tipoPago = detalleFactura.TipoPago.nombre;

                ViewBag.Producto = _db.Producto.Select(x => new SelectListItem {
                    Value = x.id_producto.ToString(), Text = x.nombre + " - " + x.precio
                });

                var detalle = _db.DetalleFactura.Where(x => x.id_factura == id).Select(m =>
                                                                                       new VentaViewModel
                {
                    id_producto = m.id_producto,
                    id_Cliente  = m.Factura.Clientes.nombreCliente,
                    id_tipoPago = m.Factura.TipoPago.nombre,
                    cantidad    = m.cantidad,
                    producto    = m.Producto.nombre,
                    precio      = m.precio
                }).ToList();

                ViewBag.listaMascotas = detalle;

                return(View(venta));
            }
            catch (Exception e)
            {
                return(RedirectToAction("Create"));
            }
        }
Exemplo n.º 30
0
        public ActionResult Guardar(VentaViewModel ventaView)
        {
            if (!ModelState.IsValid)
            {
                return(View("Crud", ventaView));
            }


            if (ventaView.Ispublica)
            {
                ventaView.Rut = "0";
            }

            var _consultaCliente = _context.Clientes.Where(x => x.Rut == ventaView.Rut).FirstOrDefault();

            if (_consultaCliente == null)
            {
                ModelState.AddModelError("", "Este cliente no se encuentra registrado");
                return(View("Crud", ventaView));
            }

            var _cestaProductos = (List <AgregarProductoView>)Session["CartVentas"];

            var _TipoProducto = _cestaProductos.First().IdTipoProducto;

            if (User.Identity.GetUserId() == null)
            {
                return(View("Crud", ventaView));
            }

            var _nuevaVenta = new Venta()
            {
                ClienteId      = _consultaCliente.Id,
                DocumentoId    = IdTipoDocumento.Factura,
                Fecha          = DateTime.Now,
                EstadoId       = Estados.Finalizada,
                EmpresaId      = Empresas.Sostel,
                TipoProductoId = _TipoProducto,
                VendedorId     = User.Identity.GetUserId()
            };

            _context.Ventas.Add(_nuevaVenta);

            foreach (var item in _cestaProductos)
            {
                var _nuevoDetalle = new DetalleVenta()
                {
                    VentaId    = _nuevaVenta.Id,
                    ProductoId = item.IdProducto,
                    Cantidad   = item.Cantidad,
                    Precio     = item.Precio
                };
                var _inventario = _context.Inventarios.Where(x => x.ProductoId == item.IdProducto).FirstOrDefault();
                _inventario.Stock -= item.Cantidad;

                _context.DetalleVentas.Add(_nuevoDetalle);
            }
            Session["CartVentas"]   = null;
            Session["ConteoVentas"] = null;
            _context.SaveChanges();

            return(RedirectToAction("Detalles/" + _nuevaVenta.Id, "Ventas"));
        }