public ActionResult Edit(Producto Producto)
        {
            if (ModelState.IsValid)
            {
                var emp = db.Producto.Find(Producto.IdProducto);
                if (emp != null)
                {
                    emp.Nombre = Producto.Nombre;
                    emp.Descripcion = Producto.Descripcion;
                    emp.Marca = Producto.Marca;
                    emp.Stock = Producto.Stock;
                    emp.StockMinimo = Producto.StockMinimo;
                    emp.PrecioVenta = Producto.PrecioVenta;
                    emp.PrecioCosto = Producto.PrecioCosto;
                    emp.Utilidad = Producto.Utilidad;
                    emp.IdCategoria = Producto.IdCategoria;

                    db.Entry(emp).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("", "El Producto no existe");
                    ViewBag.IdCategoria = new SelectList(db.Categoria.ToList(), "IdCategoria", "Descripcion", Producto.IdCategoria);
                    return View(Producto);
                }
            }
            else
            {
                ViewBag.IdCategoria = new SelectList(db.Categoria.ToList(), "IdCategoria", "Descripcion", Producto.IdCategoria);
                return View(Producto);
            }
        }
 public bool updateProducto(Producto producto)
 {
     try
     {
         Utilitarios.Conexion.openConnection();
         command = new SqlCommand("proc_Productos_Update", Utilitarios.Conexion.returnConnection());
         command.CommandType = System.Data.CommandType.StoredProcedure;
         command.Parameters.AddWithValue("@pro_codigo", producto.Codigo);
         command.Parameters.AddWithValue("@pro_descripcion", producto.Descripcion);
         command.Parameters.AddWithValue("@pro_estado", producto.TipoProducto);
         command.Parameters.AddWithValue("@pro_precioreferencial", producto.Precioreferencial);
         command.Parameters.AddWithValue("@pro_stock", producto.Stock);
         command.Parameters.AddWithValue("@me_codigo", producto.MedidaCodigo);
         command.Parameters.AddWithValue("@pre_codigo", producto.PresentacionCodigo);
         command.Parameters.AddWithValue("@pro_observacion", producto.Observacion);
         command.Parameters.AddWithValue("@categoria_codigo", producto.CategoriaCodigo);
         command.Parameters.AddWithValue("@pro_stockMinimo", producto.StockMinimo);
         command.Parameters.AddWithValue("@pro_ubicacionFisica", producto.UbicacionFisica);
         command.Parameters.AddWithValue("@tiex_codigo", producto.TipoExistenciaCodigo);
         if (command.ExecuteNonQuery() > 0)
         {
             Utilitarios.Conexion.closeConnection();
             return true;
         }
         else
         {
             Utilitarios.Conexion.closeConnection();
             return false;
         }
     }
     catch (SqlException e) { MessageBox.Show("Error de Base de datos :" + e.Message); return false; }
 }
Example #3
0
        public virtual JsonResult Crear(Producto entidad)
        {
            var jsonResponse = new JsonResponse { Success = false };

            if (ModelState.IsValid)
            {
                try
                {
                    entidad.UsuarioCreacion = UsuarioActual.IdUsuario.ToString();
                    entidad.UsuarioModificacion = UsuarioActual.IdUsuario.ToString();
                    ProductoBL.Instancia.Add(entidad);

                    jsonResponse.Success = true;
                    jsonResponse.Message = "Se Proceso con éxito";
                }
                catch (Exception ex)
                {
                    logger.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));
                    jsonResponse.Message = "Ocurrio un error, por favor intente de nuevo o más tarde.";
                }
            }
            else
            {
                jsonResponse.Message = "Por favor ingrese todos los campos requeridos";
            }
            return Json(jsonResponse, JsonRequestBehavior.AllowGet);
        }
Example #4
0
    public int Add(String titulo, int idTitulo, int idCategoria, int idSubCategoria, String idAtributos, String descripcion, String IdDescripcion)
    {
        String[] idAttr = idAtributos.Trim().Split(',');
        String[] idDesc = IdDescripcion.Trim().Split(',');
        String[] desc = descripcion.Trim().Split(',');

        int idTit = DAOTitulo.getIDxName(titulo);
        if (idTit != 0)
            idTitulo = idTit;
        else
        {
            DAOTitulo.sqlInsert(new Titulo(titulo));
            idTitulo = DAOTitulo.getLastId();
        }

        int idDescripcion;
        int resultado = 0;
        for (int i = 0; i < idAttr.Length; i++)
        {
            int idD = DAODescripcion.getIDxName(desc[i]);
            if (idD != 0)
                idDescripcion = idD;
            else
            {
                DAODescripcion.sqlInsert(new Descripcion(desc[i]));
                idDescripcion = DAODescripcion.getLastId();
            }
            Producto pr = new Producto(idCategoria, int.Parse(idAttr[i]), idSubCategoria, idDescripcion, idTitulo);
            if (DAOProductos.sqlInsert(pr))
                resultado = 1;
        }
        return resultado;
    }
 public ItemProductoCarrito(Producto producto, int indexProducto)
 {
     InitializeComponent();
     boton.Content = producto.Nombre;
     this.producto = producto;
     this.indexProducto = indexProducto;
 }
Example #6
0
 public void AgregarLinea(Producto producto, int cantidad)
 {
     detalle.Add(new LineaCarroCompras
         {
             Producto=producto,
             Cantidad=cantidad
         });
 }
Example #7
0
        public void FacturaAgregarProductoYConfirmarQueEsteAgregado()
        {
            Factura factura = new Factura();
            Producto producto = new Producto(10);
            factura.AddProducto(producto, 2);

            Assert.IsTrue(factura.Items.Any(i => i.Producto == producto));
        }
 public CalificarPopup(Popup padre, Producto producto)
 {
     if (padre == null) throw new ArgumentNullException("Debe asignar un Popup al controlador");
     this.popup = padre;
     this.InitializeComponent();
     cargarCombo();
     this.producto = producto;
 }
 public DetallePopup(Popup padre, Producto producto)
 {
     this.producto = producto;
     this.cantidadProductoMax = producto.Cantidad;
     if (padre == null) throw new ArgumentNullException("Debe asignar un Popup al controlador");
     this.popup = padre;
     this.InitializeComponent();
     textCantidad.Text = cantidadProducto.ToString();
 }
Example #10
0
        public ItemProducto(int indexProducto, Page padre)
        {
            this.InitializeComponent();
            this.padre = padre;

            producto = ListaProducto.ListaProductos.ElementAt(indexProducto);
            textoNombreProducto.Text = producto.Nombre;
            this.setImagenProducto("http://" + Constante.Ip + ":8080/" + producto.ImagenDetalle);
        }
        public virtual decimal AplicarDescuento(Producto producto)
        {
            decimal total = 0;

            var reglaAplicable = obtenerReglaAplicable(producto);
            total += reglaAplicable.Aplicar(producto);

            return total;
        }
Example #12
0
        public void FacturaConDosProductGetTotal()
        {
            Factura factura = new Factura();
            Producto producto1 = new Producto(10);
            Producto producto2 = new Producto(20);
            factura.AddProducto(producto1, 2);
            factura.AddProducto(producto2, 1);

            Assert.AreEqual(40, factura.GetTotal());
        }
Example #13
0
        public ActionResult Create(Producto producto)
        {
            if (ModelState.IsValid)
            {
                db.Producto.Add(producto);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(producto);
        }
Example #14
0
        public LineaPresupuesto AdicionarLinea(Guid id, Producto producto, Cotizacion cotizacion, Decimal cantidad)
        {
            var linea = new LineaPresupuesto(id, this, producto, cotizacion, cantidad);

            linea.PropertyChanged += HandleLineaPresupuestoChanged;

            _lineas.Add(linea);
            OnPropertyChanged("Lineas");
            OnPropertyChanged("MontoTotal");

            return linea;
        }
Example #15
0
 public Cotizacion(Producto producto,
                   Proveedor proveedor,
                   Decimal costoUnitario,
                   DateTime fechaCreacion,
                   DateTime? fechaExpiracion)
 {
     Producto = producto;
     Proveedor = proveedor;
     CostoUnitario = costoUnitario;
     FechaCreacion = fechaCreacion;
     FechaExpiracion = fechaExpiracion;
 }
Example #16
0
 public Producto ConvertirDesdeDTO(ProductoDTO _productoDTO)
 {
     var producto = new Producto()
     {
         ProductoID = _productoDTO.ProductoID,
         ProductoNombre = _productoDTO.ProductoNombre,
         Descripcion = _productoDTO.Descripcion,
         ImagenUbicacion = _productoDTO.ImagenUbicacion,
         PrecioUnitario = _productoDTO.PrecioUnitario,
         CategoriaID = _productoDTO.CategoriaID
     };
     return producto;
 }
Example #17
0
        public LineaPresupuesto(Presupuesto presupuesto,
                                Producto producto,
                                Cotizacion cotizacion,
                                Decimal cantidad)
        {
            if (presupuesto == null)
                throw new ArgumentException("presupuesto");

            _presupuesto = presupuesto;
            Producto = producto;
            Cotizacion = cotizacion;
            Cantidad = cantidad;
        }
 protected async override void OnNavigatedTo(NavigationEventArgs e)
 {
     producto = e.Parameter as Producto;
     textNombre.Text = producto.Nombre;
     textDescripcion.Text = producto.Descripcion;
     textPrecio.Text = "Precio " + producto.Precio.ToString() + " Bs";
     if (producto.Cantidad == 1) 
         textCantidad.Text = producto.Cantidad.ToString() + " unidad disponible";
     else 
         textCantidad.Text = producto.Cantidad.ToString()+" unidades disponibles";
     if (producto.Cantidad == 0)
         textCantidad.Text = "Producto Agotado";
     producto.Calificaciones = await servicioAei.buscarCalificacionProductoAsync(producto.Id);
     cargarComentarios();
     this.setImagenProducto("http://" + Constante.Ip + ":8080/" + producto.ImagenDetalle);
 }
Example #19
0
 public void RaiseWhenProductoRepetido()
 {
     try
     {
         Factura factura = new Factura();
         Producto producto = new Producto(10);
         factura.AddProducto(producto, 2);
         factura.AddProducto(producto, 1);
         Assert.Fail();
     }
     catch (Exception ex)
     {
         Assert.IsInstanceOfType(ex, typeof(InvalidOperationException));
         Assert.AreEqual("Producto Repetido", ex.Message);
     }
 }
Example #20
0
        public ItemCompra(int indexProducto, ListaCompraPage padre, bool isCarrito)
        {
            this.InitializeComponent();
            this.padre = padre;
            this.indexProducto = indexProducto;

            if(isCarrito)
            {
                producto = BufferUsuario.Usuario.Carrito.Productos.ElementAt(indexProducto).Producto;
                detalle = BufferUsuario.Usuario.Carrito.Productos.ElementAt(indexProducto);
            }


            textoNombreProducto.Text = detalle.Cantidad + " " + producto.Nombre;
            this.setImagenProducto("http://" + Constante.Ip + ":8080/" + producto.ImagenDetalle);
        }
Example #21
0
        /**
        Retorna una List con todos los productos existentes en la base de datos**/
        public static List<Producto> select()
        {
            List<Producto> lista = new List<Producto>();
            SqlConnection cn = new SqlConnection();
            try
            {
                cn.ConnectionString = cadenaConex;
                cn.Open();
                string consulta = "SELECT P.nombre as NombreProd, P.precio, P.stock, P.fechaRegistro, P.codigoBarra, CP.nombre as NombreCat, P.aceptaDevolucion FROM Productos P INNER JOIN CategoriasProducto CP ON (P.idCategoriaProducto = CP.idCategoriaProducto)";
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = consulta;
                cmd.Connection = cn;
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Producto p = new Producto();
                    p.Nombre = dr["NombreProd"].ToString();

                    CategoriaProducto cat = new CategoriaProducto();
                    cat.Nombre= (dr["NombreCat"].ToString());

                    p.Categoria = cat;
                    int aceptaDev = (int)dr["aceptaDevolucion"];
                    Boolean acepta = false;
                    if (aceptaDev == 1)
                    {
                        acepta = true;
                    }
                    p.AceptaDevolucion = acepta;
                    p.CodigoBarra = (int)dr["codigoBarra"];
                    p.FechaRegistro = (DateTime)dr["fechaRegistro"];
                    p.Precio = float.Parse(dr["precio"].ToString());
                    p.Stock = (int)dr["stock"];
                    lista.Add(p);
                }
            }
            catch (SqlException ex)
            {
                throw new ApplicationException("Error SQL al obtener los Productos.");
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
            return lista;
        }
Example #22
0
 public void insertaDetalleVenta(Producto prod)
 {
     double cantidad = Convert.ToDouble(numCantidad.Value);
     double precio = Convert.ToDouble(numPrecio.Value);
     int idprod = prod.prod_productoid;
     Guardar(new DetalleVentaBU(), new DetalleVenta
     {
         detve_cantidad = cantidad,
         detve_precio = precio,
         detve_tipocambio = 1,
         Ventas_vent_ventaid = ven.vent_ventaid,
         Producto_prod_productoid = idprod,
         Producto_SubCategoria_subc_subcategoriaid = prod.SubCategoria_subc_subcategoriaid,
         Calidad_cali_calidadid = prod.Calidad_cali_calidadid,
         DetalleGarantia_dega_detallegarantiaid = 1
     });
 }
Example #23
0
 public virtual ActionResult Crear()
 {
     try
     {
         var entidad = new Producto
         {
             PRO_Nombre = string.Empty
         };
         PrepararDatos(ref entidad, "Crear");
         return PartialView("Edit", entidad);
     }
     catch (Exception ex)
     {
         logger.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));
         return new HttpNotFoundWithViewResult("Error");
     }
 }
Example #24
0
        public List<Producto> obtenerListaConStock()
        {
            DataTable dt = obtenerTodosConStock();
            List<Producto> productos = new List<Producto>();

            foreach (DataRow r in dt.Rows)
            {
                Producto p = new Producto();
                p.idProducto = Int32.Parse(r["PRODUCTO_ID"].ToString());
                p.descProducto = r["PRODUCTO_DESC"].ToString();
                p.stockProducto = Int32.Parse(r["PRODUCTO_STOCK"].ToString());
                p.millasProducto = Int32.Parse(r["PRODUCTO_MILLAS"].ToString());

                productos.Add(p);
            }
            return productos;
        }
Example #25
0
        public void FixtureSetup()
        {
            kmMadrid = 800; kmBarcelona = 1100; kmLisboa = 600;
            kgVieira = 50; kgPulpo = 100; kgCentollo = 50;

            Madrid = new Ciudad("Madrid", kmMadrid);
            Barcelona = new Ciudad("Barcelona", kmBarcelona);
            Lisboa = new Ciudad("Lisboa", kmLisboa);

            Vieira = new Producto("Vieira", kgVieira);
            Pulpo = new Producto("Pulpo", kgPulpo);
            Centollo = new Producto("Centollo", kgCentollo);

            furgo = new Furgoneta(200);

            furgo.AddPrecio(Madrid, Vieira, 500);
            furgo.AddPrecio(Madrid, Pulpo, 0);
            furgo.AddPrecio(Madrid, Centollo, 450);

            furgo.AddPrecio(Barcelona, Vieira, 450);
            furgo.AddPrecio(Barcelona, Pulpo, 120);
            furgo.AddPrecio(Barcelona, Centollo, 0);

            furgo.AddPrecio(Lisboa, Vieira, 600);
            furgo.AddPrecio(Lisboa, Pulpo, 100);
            furgo.AddPrecio(Lisboa, Centollo, 500);

            valBrutoProductosEnMadrid = kgVieira * furgo.GetPrecio(Madrid, Vieira) +
                                        kgPulpo * furgo.GetPrecio(Madrid, Pulpo) +
                                        kgCentollo * furgo.GetPrecio(Madrid, Centollo);

            valBrutoProductosEnBarcelona = kgVieira * furgo.GetPrecio(Barcelona, Vieira) +
                                           kgPulpo * furgo.GetPrecio(Barcelona, Pulpo) +
                                           kgCentollo * furgo.GetPrecio(Barcelona, Centollo);

            valBrutoProductosEnLisboa = kgVieira * furgo.GetPrecio(Lisboa, Vieira) +
                                        kgPulpo * furgo.GetPrecio(Lisboa, Pulpo) +
                                        kgCentollo * furgo.GetPrecio(Lisboa, Centollo);

            valGastosIrAMadrid = 5 + (valBrutoProductosEnMadrid * 1 / 100) * kmMadrid / 100 +
                                     (2 * kmMadrid);
            valGastosIrABarcelona = 5 + (valBrutoProductosEnBarcelona * 1 / 100) * kmBarcelona / 100 +
                                        (2 * kmBarcelona);
            valGastosIrALisboa = 5 + (valBrutoProductosEnLisboa * 1 / 100) * kmLisboa / 100 +
                                     (2 * kmLisboa);
        }
Example #26
0
 public int cambiarCantidadProducto(int idProducto, int cantidad)
 {
     ConexionSqlServer conexion = new ConexionSqlServer();
     SqlDataReader tabla = conexion.consultar("select p.cantidad from producto p where p.id="+idProducto.ToString()+";");
     List<Tag> listaTag = new List<Tag>();
     Producto producto = new Producto();
     while (tabla != null && tabla.Read())
     {
         producto.Cantidad=int.Parse(tabla["CANTIDAD"].ToString());
     }
     conexion.cerrarConexion();
     int respuesta = -1;
     int cant = producto.Cantidad-cantidad;
     if (cantidad<=producto.Cantidad) 
          respuesta=conexion.insertar("UPDATE Producto SET cantidad="+ cant.ToString() +" WHERE ID="+idProducto+"");
     conexion.cerrarConexion();
     return respuesta;
 }
Example #27
0
        public override void CargarDatos(long? entidadId)
        {
            Producto = ObjectFactory.GetInstance<Producto>();
            try
            {
                Producto = productoUWO.ProductoRepositorio.ObtenerPorId(entidadId.Value);

                this.txtCodigoProducto.Text = Producto.Codigo.ToString();
                this.txtDescripcion.Text = Producto.Descripcion;
                this.nudPrecio.Value = Producto.PrecioUnitario;
                this.nudStock.Value = Producto.Stock;
            }
            catch (Exception)
            {

                Mensaje.Mostrar(new Exception("Error al cargar los Datos"),PresentacionBase.Constante.TipoMensaje.Error);

            }
        }
Example #28
0
        public static bool Insertar(Producto producto)
        {
            bool retorno = false;
            try
            {
                using (var db = new MiniSubControlDb())
                {
                    db.Producto.Add(producto);
                    db.SaveChanges();
                    retorno = true;
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

            return retorno;
        }
 public bool deleteProducto(Producto producto)
 {
     try
     {
         Utilitarios.Conexion.openConnection();
         command = new SqlCommand("proc_Productos_Delete", Utilitarios.Conexion.returnConnection());
         command.CommandType = System.Data.CommandType.StoredProcedure;
         command.Parameters.AddWithValue("@pro_codigo", producto.Codigo);
         if (command.ExecuteNonQuery() > 0)
         {
             Utilitarios.Conexion.closeConnection();
             return true;
         }
         else
         {
             Utilitarios.Conexion.closeConnection();
             return false;
         }
     }
     catch (SqlException e) { MessageBox.Show("Error de Base de datos :" + e.Message); return false; }
 }
Example #30
0
 public ActionResult NewProduct(Producto producto)
 {
     //ProductosProcessor processor = new ProductosProcessor();
     //processor.NewProduct(producto);
     return(View());
 }
Example #31
0
 public abstract void SuprimeProducto(Producto producto);
Example #32
0
 public async Task Insert(Producto producto)
 {
     await _context.Producto.AddAsync(producto);
 }
Example #33
0
 public List <Producto> findPrecioProducto(Producto objPrducto)
 {
     return(objProductoDao.findPrecioProducto(objPrducto));
 }
        public ActionResult detalleProducto(string id)
        {
            Producto objP = ListProducto().Where(p => p.ID_PROD == id).FirstOrDefault();

            return(View(objP));
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Producto product = (Producto)myDataGrid.SelectedItem;

            MainWindow.myNavigationFrame.NavigationService.Navigate(new ProductNewOrModify("Modificar usuario", ProductoHandler, product));
        }
Example #36
0
 public List <Producto> findAllProductosPorCategoria(Producto objProducto)
 {
     return(objProductoDao.findAllProductosPorCategoria(objProducto));
 }
        /// <summary>
        /// Consulta los productos existentes.
        /// </summary>
        /// <param name="producto">The producto.</param>
        /// <returns>Lista de los productos existentes.</returns>
        /// <remarks>
        /// Autor: Iván José Pimienta Serrano - INTERGRUPO\Ipimienta.
        /// FechaDeCreacion: 15/02/2013.
        /// UltimaModificacionPor: (Nombre del Autor de la modificación - Usuario del dominio).
        /// FechaDeUltimaModificacion: (dd/MM/yyyy).
        /// EncargadoSoporte: (Nombre del Autor - Usuario del dominio).
        /// Descripción: Consulta los productos existentes.
        /// </remarks>
        public static List <Producto> ConsultarProducto(Producto producto)
        {
            FachadaIntegracion fachada = new FachadaIntegracion();

            return(fachada.ConsultarProducto(producto));
        }
Example #38
0
        private static int OrdenarProductos(Producto p1, Producto p2)
        {
            int retorno = p1.Marca.CompareTo(p2.Marca);

            return(retorno);
        }
Example #39
0
        public List <Producto> ListarProductoPorRubro(Rubro rubro)
        {
            try
            {
                OracleCommand cmd = new OracleCommand();
                // Se le asigna la conexion
                cmd.Connection  = cone.Obtener();
                cmd.CommandText = "SP_SELECT_PRODUCTO_RUBRO";
                cmd.CommandType = CommandType.StoredProcedure;
                //
                cmd.Parameters.Add("p_ID_RUBRO", OracleDbType.Int32).Value       = rubro.IdRubro;
                cmd.Parameters.Add("p_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
                if (cone.Obtener().State == ConnectionState.Closed)
                {
                    cone.Obtener().Open();
                }

                OracleDataReader dr = cmd.ExecuteReader();
                Producto         producto;
                Local            local;
                Estado           estado;
                Rubro            ru;
                List <Producto>  listaPro = new List <Producto>();
                while (dr.Read())
                {
                    producto = new Producto();
                    local    = new Local();
                    estado   = new Estado();
                    ru       = new Rubro();
                    //Producto
                    producto.IdProducto     = dr.GetInt32(0);
                    producto.CodigoProducto = dr.GetInt32(1);
                    producto.Descripcion    = dr.GetString(2);
                    producto.PrecioNormal   = dr.GetInt32(3);
                    producto.PrecioOferta   = dr.GetInt32(4);
                    producto.FechaRegistro  = dr.GetDateTime(5);
                    //Estado
                    estado.IdEstado     = dr.GetInt32(8);
                    estado.NombreEstado = dr.GetString(9);
                    //local
                    local.IdLocal   = dr.GetInt32(6);
                    local.Direccion = dr.GetString(7);
                    //asignacion de objeto a la clase
                    ru.IdRubro          = dr.GetInt32(11);
                    ru.DescripcionRubro = dr.GetString(12);
                    TipoRubro tipo = new TipoRubro();
                    tipo.IdTipoRubro = dr.GetInt32(13);
                    rubro.TipoRubro  = tipo;

                    producto.Rubro  = rubro;
                    producto.Local  = local;
                    producto.Estado = estado;
                    if (producto.Rubro.TipoRubro.IdTipoRubro == 1)
                    {
                        producto.FechaCaducidad = dr.GetDateTime(10);
                    }
                    listaPro.Add(producto);
                }
                cone.Obtener().Close();
                return(listaPro);
            }
            catch
            {
                return(null);
            }
        }
Example #40
0
        private void btn_adicionar_Click(object sender, RoutedEventArgs e)
        {
            var nuevo_producto = new Producto {
                Codigo = tbox_codigo.Text, Descripcion = tbox_descripcion.Text
            };

            using (var db = new TiendaDbContext())
            {
                if (db.Productos.Find(nuevo_producto.Codigo) != null)
                {
                    MessageBox.Show("Ya existe un producto con ese codigo");
                    return;
                }
                if (nuevo_producto.Codigo == "")
                {
                    MessageBox.Show("El codigo no puede ser vacio");
                    return;
                }
                if (nuevo_producto.Descripcion == "")
                {
                    MessageBox.Show("La descripcion no puede estar vacia");
                    return;
                }
                double precioBuenEstado;
                double precioDefectuoso;
                if (!double.TryParse(tbox_precioDefectuoso.Text, out precioDefectuoso) || !double.TryParse(tbox_precioBuenEstado.Text, out precioBuenEstado))
                {
                    MessageBox.Show("Rectifique los precios");
                    return;
                }
                db.Productos.Add(nuevo_producto);
                db.SaveChanges();
                source_productos.Add(nuevo_producto);

                int index = dgrid_productos.SelectedIndex;

                dgrid_productos.ItemsSource   = null;
                dgrid_productos.ItemsSource   = source_productos.Where(s => s.Codigo.ToLower().Contains(codigo_src) && s.Descripcion.ToLower().Contains(descrip_src)).ToList();
                dgrid_productos.SelectedIndex = index;

                var tiendas = db.Tiendas.ToList();
                foreach (var tienda in tiendas)
                {
                    var exist = new Existencia
                    {
                        CantidadBuenEstado = 0,
                        CantidadDefectuoso = 0,
                        Producto           = nuevo_producto,
                        Tienda             = tienda,
                        PrecioBuenEstado   = precioBuenEstado,
                        PrecioDefectuoso   = precioDefectuoso
                    };
                    tienda.Productos.Add(exist);
                    db.Existencias.Add(exist);
                }
                db.SaveChanges();
            }
            tbox_codigo.Text           = "";
            tbox_descripcion.Text      = "";
            tbox_precioBuenEstado.Text = "";
            tbox_precioDefectuoso.Text = "";
        }
Example #41
0
        /// <summary>
        /// Calcular Precio Unitario
        /// </summary>
        private void calcularPrecioUnitario(int tipo)
        {
            if (tipo == 0)
            {
                if (cbxCodigoProducto.SelectedIndex == -1)
                {
                    return;                                        /// Validación
                }
                try
                {
                    if (cbxDescripcion.SelectedIndex == -1)
                    {
                        txtPrecioUnitario.Text = currentProducto.precioCompra;
                    }
                    else
                    {
                        // Buscar presentacion elegida
                        int          idPresentacion   = Convert.ToInt32(cbxDescripcion.SelectedValue);
                        Presentacion findPresentacion = presentaciones.Find(x => x.idPresentacion == idPresentacion);

                        // Realizando el calculo
                        double precioCompra     = double.Parse(currentProducto.precioCompra, CultureInfo.GetCultureInfo("en-US"));
                        double cantidadUnitario = double.Parse(findPresentacion.cantidadUnitaria, CultureInfo.GetCultureInfo("en-US"));
                        double precioUnidatio   = precioCompra * cantidadUnitario;

                        // Imprimiendo valor
                        txtPrecioUnitario.Text = String.Format(CultureInfo.GetCultureInfo("en-US"), formato, precioUnidatio);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message, "determinar precio unitario", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                if (cbxDescripcion.SelectedIndex == -1)
                {
                    return;                                     /// Validación
                }
                try
                {
                    // Buscar presentacion elegida
                    int          idPresentacion   = Convert.ToInt32(cbxDescripcion.SelectedValue);
                    Presentacion findPresentacion = presentaciones.Find(x => x.idPresentacion == idPresentacion);
                    Producto     findProducto     = productos.Find(x => x.idProducto == findPresentacion.idProducto);
                    cbxCodigoProducto.Text = findProducto.codigoProducto;
                    // Realizando el calculo
                    double precioCompra     = double.Parse(findProducto.precioCompra, CultureInfo.GetCultureInfo("en-US"));
                    double cantidadUnitario = double.Parse(findPresentacion.cantidadUnitaria, CultureInfo.GetCultureInfo("en-US"));
                    double precioUnidatio   = precioCompra * cantidadUnitario;

                    // Imprimiendo valor
                    txtPrecioUnitario.Text = String.Format(CultureInfo.GetCultureInfo("en-US"), formato, precioUnidatio);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message, "determinar precio unitario", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Example #42
0
        public ActionResult Nuevo(Producto p)
        {
            productoServices.crearProducto(p);

            return(View());
        }
Example #43
0
        public bool generateExcel(List <List <List <Factura> > > IngresoSemanas, List <List <List <Egreso> > > EgresoSemanas, string folderpath, string fileName, int pYear, int pMonth)
        {
            bool result = true;

            try
            {
                //decimal TotalIngresos = 0;
                //decimal TotalEgresos = 0;
                //decimal Total = 0;
                SLDocument      sl              = new SLDocument();
                List <Producto> productosTable  = new List <Producto>();
                int             dayMonthIngrsos = 1;
                int             dayMonthEgresos = 1;

                decimal lastTotalIngresos = 0;
                decimal lastTotalEgresos  = 0;

                for (int s = 0; s < IngresoSemanas.Count; s++)
                {
                    int     dayWeek     = 1;
                    decimal totalSemana = 0;
                    List <List <Factura> > SemanaIngresos   = IngresoSemanas[s];
                    List <Detfactura>      DetallesSemana   = new List <Detfactura>();
                    List <List <Egreso> >  SemanaEgresos    = EgresoSemanas[s];
                    List <Egreso>          ConceptosEgresos = new List <Egreso>();

                    productosTable.Clear();
                    //procesando ingresos
                    sl.AddWorksheet("Week " + (s + 1));
                    sl.MergeWorksheetCells(2, 2, 2, SemanaIngresos.Count + 3, BorderStyleValues.Thin);
                    sl.MergeWorksheetCells("C3", "C4");

                    //set height for each column
                    sl.SetRowHeight(1, 25);
                    sl.SetRowHeight(2, 25);
                    sl.SetRowHeight(3, 25);
                    sl.SetRowHeight(4, 25);

                    //set width for each header cell
                    sl.SetColumnWidth(2, 20);
                    sl.SetColumnWidth(3, 17);

                    sl.SetCellValue("B2", "INGRESOS");

                    SLStyle styleTitle = sl.CreateStyle();

                    styleTitle.Fill.SetPattern(PatternValues.Solid, System.Drawing.Color.LightGray, System.Drawing.Color.Black);
                    styleTitle.SetVerticalAlignment(VerticalAlignmentValues.Center);
                    styleTitle.SetHorizontalAlignment(HorizontalAlignmentValues.Center);
                    styleTitle.Font.Bold     = true;
                    styleTitle.Font.FontSize = 11;
                    sl.SetCellStyle(2, 2, styleTitle);

                    SLStyle styleProducto = sl.CreateStyle();
                    styleProducto.SetBottomBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleProducto.SetTopBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleProducto.SetLeftBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleProducto.SetRightBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleProducto.SetVerticalAlignment(VerticalAlignmentValues.Center);
                    styleProducto.SetHorizontalAlignment(HorizontalAlignmentValues.Left);
                    styleProducto.Font.Bold     = false;
                    styleProducto.Font.FontSize = 10;

                    SLStyle styleDiaIngreso = sl.CreateStyle();
                    styleDiaIngreso.SetBottomBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleDiaIngreso.SetTopBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleDiaIngreso.SetLeftBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleDiaIngreso.SetRightBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleDiaIngreso.SetVerticalAlignment(VerticalAlignmentValues.Center);
                    styleDiaIngreso.SetHorizontalAlignment(HorizontalAlignmentValues.Right);
                    styleDiaIngreso.Font.Bold     = false;
                    styleDiaIngreso.Font.FontSize = 10;

                    SLStyle styleDates = sl.CreateStyle();
                    styleDates.SetBottomBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleDates.SetTopBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleDates.SetLeftBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleDates.SetRightBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleDates.SetVerticalAlignment(VerticalAlignmentValues.Center);
                    styleDates.SetHorizontalAlignment(HorizontalAlignmentValues.Center);
                    styleDates.Font.Bold     = true;
                    styleDates.Font.FontSize = 10;
                    styleDates.SetWrapText(true);

                    SLStyle styleIndexes = sl.CreateStyle();
                    styleIndexes.SetBottomBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleIndexes.SetTopBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleIndexes.SetLeftBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleIndexes.SetRightBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleIndexes.SetVerticalAlignment(VerticalAlignmentValues.Center);
                    styleIndexes.SetHorizontalAlignment(HorizontalAlignmentValues.Left);
                    styleIndexes.Font.Bold     = true;
                    styleIndexes.Font.FontSize = 10;

                    SLStyle styleTotalIngresos = sl.CreateStyle();

                    styleTotalIngresos.SetVerticalAlignment(VerticalAlignmentValues.Center);
                    styleTotalIngresos.SetHorizontalAlignment(HorizontalAlignmentValues.Center);
                    styleTotalIngresos.Font.FontSize  = 10;
                    styleTotalIngresos.Font.FontColor = System.Drawing.Color.Green;

                    SLStyle styleSubTotalIngresos = sl.CreateStyle();
                    styleSubTotalIngresos.SetBottomBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleSubTotalIngresos.SetTopBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleSubTotalIngresos.SetLeftBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleSubTotalIngresos.SetRightBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);

                    styleSubTotalIngresos.SetVerticalAlignment(VerticalAlignmentValues.Center);
                    styleSubTotalIngresos.SetHorizontalAlignment(HorizontalAlignmentValues.Right);
                    styleSubTotalIngresos.Font.FontSize  = 10;
                    styleSubTotalIngresos.Font.FontColor = System.Drawing.Color.Green;

                    SLStyle styleTotalEgresos = sl.CreateStyle();
                    styleTotalEgresos.SetVerticalAlignment(VerticalAlignmentValues.Center);
                    styleTotalEgresos.SetHorizontalAlignment(HorizontalAlignmentValues.Center);
                    styleTotalEgresos.Font.FontSize  = 10;
                    styleTotalEgresos.Font.FontColor = System.Drawing.Color.Red;

                    SLStyle styleSubTotalEgresos = sl.CreateStyle();
                    styleSubTotalEgresos.SetBottomBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleSubTotalEgresos.SetTopBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleSubTotalEgresos.SetLeftBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);
                    styleSubTotalEgresos.SetRightBorder(BorderStyleValues.Thin, System.Drawing.Color.Black);

                    styleSubTotalEgresos.SetVerticalAlignment(VerticalAlignmentValues.Center);
                    styleSubTotalEgresos.SetHorizontalAlignment(HorizontalAlignmentValues.Right);
                    styleSubTotalEgresos.Font.FontSize  = 10;
                    styleSubTotalEgresos.Font.FontColor = System.Drawing.Color.Red;

                    sl.SetCellValue("B4", "DETALLES");
                    sl.SetCellStyle(3, 2, styleIndexes);
                    sl.SetCellStyle(4, 2, styleIndexes);

                    sl.SetCellValue("C3", "GANANCIAS DE LA SEMANA PASADA");
                    sl.SetCellStyle(3, 3, styleDates);
                    foreach (List <Factura> Dia in SemanaIngresos)
                    {
                        foreach (Factura ingreso in Dia)
                        {
                            foreach (Detfactura det in ingreso.DetsFactura)
                            {
                                if (productosTable.Where(a => a.Id == det.IdProducto).FirstOrDefault() == null)
                                {
                                    productosTable.Add(det.Producto);

                                    sl.SetCellValue(4 + productosTable.Count, dayWeek + 3, "DETALLES");
                                }
                            }
                        }
                    }
                    for (int d = 0; d < SemanaIngresos.Count; d++)
                    {
                        sl.SetCellValue("B3", new DateTime(pYear, pMonth, 1).ToString("MMMM", new CultureInfo("es-ES")).ToUpper());
                        List <Factura> Dia = SemanaIngresos[d];
                        sl.SetColumnWidth(dayWeek + 3, 12);

                        sl.SetCellValue(3, dayWeek + 3, new DateTime(pYear, pMonth, dayMonthIngrsos).ToShortDateString());
                        sl.SetCellStyle(3, dayWeek + 3, styleDates);

                        sl.SetCellValue(4, dayWeek + 3, new DateTime(pYear, pMonth, dayMonthIngrsos).DayOfWeek.ToString());
                        sl.SetCellStyle(4, dayWeek + 3, styleDates);

                        foreach (Factura ingreso in Dia)
                        {
                            foreach (Detfactura det in ingreso.DetsFactura)
                            {
                                DetallesSemana.Add(det);
                            }
                        }


                        for (int prod = 0; prod < productosTable.Count; prod++)
                        {
                            Producto       producto           = productosTable[prod];
                            decimal        ingresoDiaProducto = 0;
                            List <Factura> ingresoInDia       = new List <Factura>();
                            if (Dia.Where(a => Convert.ToDateTime(a.FhRegistro).Day == dayMonthIngrsos && a.DetsFactura.Where(dt => dt.IdProducto == producto.Id).Count() > 0).Count() > 0)
                            {
                                ingresoInDia = Dia.Where(a => Convert.ToDateTime(a.FhRegistro).Day == dayMonthIngrsos && a.DetsFactura.Where(dt => dt.IdProducto == producto.Id).Count() > 0).ToList();
                            }

                            foreach (Factura fact in ingresoInDia)
                            {
                                foreach (Detfactura det in fact.DetsFactura.Where(a => a.IdProducto == productosTable[prod].Id))
                                {
                                    ingresoDiaProducto += (det.Total - det.Descuento);
                                    totalSemana        += (det.Total - det.Descuento);
                                }
                            }
                            sl.SetCellValue(5 + prod, dayWeek + 3, ingresoDiaProducto == 0 ? "" : "$" + Decimal.Round(ingresoDiaProducto, 2).ToString());
                            sl.SetCellStyle(5 + prod, dayWeek + 3, styleDiaIngreso);
                            sl.SetCellStyle(5 + prod, 3, styleProducto);
                        }
                        sl.SetCellValue("C" + 5, "$" + Decimal.Round(lastTotalIngresos, 2));

                        //MessageBox.Show(new DateTime(2019,3,1).DayOfWeek.ToString());
                        decimal        ingresoDia      = 0;
                        List <Factura> ingresoInDiaSub = new List <Factura>();
                        if (Dia.Where(a => Convert.ToDateTime(a.FhRegistro).Day == dayMonthIngrsos).Count() > 0)
                        {
                            ingresoInDiaSub = Dia.Where(a => Convert.ToDateTime(a.FhRegistro).Day == dayMonthIngrsos).ToList();
                        }

                        foreach (Factura fact in ingresoInDiaSub)
                        {
                            foreach (Detfactura det in fact.DetsFactura)
                            {
                                ingresoDia += (det.Total - det.Descuento);
                            }
                        }
                        sl.SetCellValue("B" + (productosTable.Count + 5), "SUBTOTAL DE INGRESOS");
                        sl.SetCellStyle((productosTable.Count + 5), 2, styleIndexes);
                        sl.SetRowHeight(productosTable.Count + 5, 30);

                        sl.SetCellStyle((productosTable.Count + 5), dayWeek + 3, styleSubTotalIngresos);
                        sl.SetCellValue((productosTable.Count + 5), dayWeek + 3, "$" + Decimal.Round(ingresoDia, 2).ToString());

                        dayWeek++;
                        dayMonthIngrsos++;
                    }
                    for (int p = 0; p < productosTable.Count; p++)
                    {
                        sl.SetCellValue("B" + (p + 5), productosTable[p].Nombre);
                        sl.SetCellStyle(p + 5, 2, styleProducto);
                        sl.SetRowHeight(p + 5, 30);
                    }
                    sl.MergeWorksheetCells(5, 3, productosTable.Count + 5, 3, BorderStyleValues.Thin);
                    sl.MergeWorksheetCells(productosTable.Count + 6, 3, productosTable.Count + 6, SemanaIngresos.Count + 3, BorderStyleValues.Thin);
                    sl.SetCellValue("B" + (productosTable.Count + 6), "TOTAL SEMANA");
                    sl.SetCellStyle((productosTable.Count + 6), 2, styleIndexes);
                    sl.SetRowHeight(productosTable.Count + 6, 30);
                    sl.SetCellStyle((productosTable.Count + 6), 3, styleTotalIngresos);
                    sl.SetCellStyle(5, 3, styleDates);
                    sl.SetCellStyle((productosTable.Count + 5), 3, styleDates);

                    sl.SetCellValue("C" + (productosTable.Count + 6), "$" + Decimal.Round(totalSemana, 2));

                    //procesando egresos

                    sl.MergeWorksheetCells(3 + productosTable.Count + 5, 2, 3 + productosTable.Count + 5, SemanaIngresos.Count + 3, BorderStyleValues.Thin);
                    sl.MergeWorksheetCells("C" + (3 + productosTable.Count + 6), "C" + (3 + productosTable.Count + 7));

                    sl.SetCellValue("B" + (3 + productosTable.Count + 5), "EGRESOS");
                    sl.SetCellStyle((3 + productosTable.Count + 5), 2, styleTitle);

                    sl.SetRowHeight(3 + productosTable.Count + 2, 25);
                    sl.SetRowHeight(3 + productosTable.Count + 2 + 1, 25);
                    sl.SetRowHeight(3 + productosTable.Count + 2 + 2, 25);
                    sl.SetRowHeight(3 + productosTable.Count + 2 + 3, 25);
                    sl.SetRowHeight(3 + productosTable.Count + 2 + 4, 25);
                    sl.SetRowHeight(3 + productosTable.Count + 2 + 5, 25);

                    sl.SetCellValue("B" + (3 + productosTable.Count + 6), new DateTime(pYear, pMonth, 1).ToString("MMMM", new CultureInfo("es-ES")).ToUpper());
                    sl.SetCellValue("B" + (3 + productosTable.Count + 7), "DETALLES");
                    sl.SetCellStyle((3 + productosTable.Count + 6), 2, styleDates);
                    sl.SetCellStyle((3 + productosTable.Count + 7), 2, styleIndexes);

                    sl.SetCellValue("C" + (3 + productosTable.Count + 6), "EGRESOS DE LA SEMANA PASADA");
                    sl.SetCellStyle((3 + productosTable.Count + 6), 3, styleDates);
                    dayWeek = 1;

                    decimal totalSemanaEgr = 0;
                    ConceptosEgresos.Clear();

                    for (int d = 0; d < SemanaEgresos.Count; d++)
                    {
                        foreach (Egreso egreso in SemanaEgresos[d])
                        {
                            if (ConceptosEgresos.Where(a => a.Nombre.ToUpper().Trim() == egreso.Nombre.ToUpper().Trim()).FirstOrDefault() == null)
                            {
                                ConceptosEgresos.Add(egreso);
                            }
                        }
                    }
                    sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 8), 2, styleIndexes);

                    for (int d = 0; d < SemanaEgresos.Count; d++)
                    {
                        List <Egreso> Dia            = SemanaEgresos[d];
                        decimal       TotalEgresoDia = 0;

                        sl.SetCellValue("B" + (3 + productosTable.Count + 6), new DateTime(pYear, pMonth, 1).ToString("MMMM", new CultureInfo("es-ES")).ToUpper());
                        sl.SetCellValue((3 + productosTable.Count + 6), dayWeek + 3, new DateTime(pYear, pMonth, dayMonthEgresos).ToShortDateString());
                        sl.SetCellStyle((3 + productosTable.Count + 6), dayWeek + 3, styleDates);

                        sl.SetCellValue((3 + productosTable.Count + 7), dayWeek + 3, new DateTime(pYear, pMonth, dayMonthEgresos).DayOfWeek.ToString());
                        sl.SetCellStyle((3 + productosTable.Count + 7), dayWeek + 3, styleDates);

                        for (int egr = 0; egr < ConceptosEgresos.Count; egr++)
                        {
                            decimal       EgresoDia   = 0;
                            Egreso        egreso      = ConceptosEgresos[egr];
                            List <Egreso> egresoInDia = new List <Egreso>();
                            if (Dia.Where(a => Convert.ToDateTime(a.FhRegistro).Day == dayMonthEgresos).Count() > 0)
                            {
                                egresoInDia = Dia.Where(a => Convert.ToDateTime(a.FhRegistro).Day == dayMonthEgresos && a.Nombre.ToUpper().Trim() == egreso.Nombre.ToUpper().Trim()).ToList();
                            }

                            foreach (Egreso fact in egresoInDia)
                            {
                                EgresoDia      += (fact.Total);
                                TotalEgresoDia += fact.Total;
                                totalSemanaEgr += (fact.Total);
                            }
                            sl.SetCellValue((3 + productosTable.Count + 8) + egr, dayWeek + 3, EgresoDia == 0 ? "" : "$" + Decimal.Round(EgresoDia, 2).ToString());
                            sl.SetCellStyle((3 + productosTable.Count + 8) + egr, 3, styleDiaIngreso);
                            sl.SetCellStyle((3 + productosTable.Count + 8) + egr, dayWeek + 3, styleDiaIngreso);
                        }
                        for (int p = 0; p < ConceptosEgresos.Count; p++)
                        {
                            sl.SetCellValue("B" + ((3 + productosTable.Count + 8) + p), ConceptosEgresos[p].Nombre);
                            sl.SetCellStyle(((3 + productosTable.Count + 8) + p), 2, styleProducto);

                            sl.SetRowHeight(((3 + productosTable.Count + 8) + p), 30);
                        }
                        sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 8), dayWeek + 3, styleSubTotalEgresos);
                        sl.SetCellValue((3 + productosTable.Count + ConceptosEgresos.Count + 8), dayWeek + 3, "$" + Decimal.Round(TotalEgresoDia, 2).ToString());

                        dayMonthEgresos++;
                        dayWeek++;
                    }
                    sl.MergeWorksheetCells((3 + productosTable.Count + 8), 3, (3 + productosTable.Count + ConceptosEgresos.Count + 8), 3, BorderStyleValues.Thin);

                    sl.MergeWorksheetCells((3 + productosTable.Count + ConceptosEgresos.Count + 9), 3, (3 + productosTable.Count + ConceptosEgresos.Count + 9), 3 + SemanaEgresos.Count, BorderStyleValues.Thin);


                    sl.SetCellValue("B" + (3 + productosTable.Count + ConceptosEgresos.Count + 8), "SUBTOTAL EGRESOS SEMANA");
                    sl.SetCellValue("B" + (3 + productosTable.Count + ConceptosEgresos.Count + 9), "TOTAL SEMANA");
                    sl.SetRowHeight((3 + productosTable.Count + ConceptosEgresos.Count + 8), 30);
                    sl.SetCellValue("C" + (3 + productosTable.Count + 8), "$" + Decimal.Round(lastTotalEgresos, 2));
                    sl.SetCellStyle((3 + productosTable.Count + 8), 3, styleDates);

                    sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 9), 2, styleIndexes);
                    sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 9), 3, styleTotalEgresos);
                    sl.SetRowHeight((3 + productosTable.Count + ConceptosEgresos.Count + 9), 30);
                    sl.SetCellValue("C" + (3 + productosTable.Count + ConceptosEgresos.Count + 9), "$" + Decimal.Round(totalSemanaEgr, 2));
                    //lastTotalIngresos -= lastTotalEgresos;
                    //resumen
                    sl.MergeWorksheetCells((3 + productosTable.Count + ConceptosEgresos.Count + 11), 2, (3 + productosTable.Count + ConceptosEgresos.Count + 11), 3 + SemanaEgresos.Count, BorderStyleValues.Thin);
                    sl.MergeWorksheetCells((3 + productosTable.Count + ConceptosEgresos.Count + 12), 3, (3 + productosTable.Count + ConceptosEgresos.Count + 12), 3 + SemanaEgresos.Count, BorderStyleValues.Thin);
                    sl.MergeWorksheetCells((3 + productosTable.Count + ConceptosEgresos.Count + 13), 3, (3 + productosTable.Count + ConceptosEgresos.Count + 13), 3 + SemanaEgresos.Count, BorderStyleValues.Thin);
                    sl.MergeWorksheetCells((3 + productosTable.Count + ConceptosEgresos.Count + 14), 3, (3 + productosTable.Count + ConceptosEgresos.Count + 14), 3 + SemanaEgresos.Count, BorderStyleValues.Thin);

                    sl.SetRowHeight((3 + productosTable.Count + ConceptosEgresos.Count + 10), 25);
                    sl.SetRowHeight((3 + productosTable.Count + ConceptosEgresos.Count + 11), 25);
                    sl.SetRowHeight((3 + productosTable.Count + ConceptosEgresos.Count + 12), 25);
                    sl.SetRowHeight((3 + productosTable.Count + ConceptosEgresos.Count + 13), 25);
                    sl.SetRowHeight((3 + productosTable.Count + ConceptosEgresos.Count + 14), 25);

                    sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 11), 2, styleTitle);
                    sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 12), 2, styleDates);
                    sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 13), 2, styleDates);
                    sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 14), 2, styleDates);

                    sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 12), 3, styleTotalIngresos);
                    sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 13), 3, styleTotalEgresos);
                    sl.SetCellStyle((3 + productosTable.Count + ConceptosEgresos.Count + 14), 3, (Decimal.Round((totalSemana - totalSemanaEgr) + (lastTotalIngresos), 2)) == 0 ? styleDates : (Decimal.Round((totalSemana - totalSemanaEgr) + (lastTotalIngresos), 2)) < 0 ? styleTotalEgresos : styleTotalIngresos);

                    sl.SetCellValue("B" + (3 + productosTable.Count + ConceptosEgresos.Count + 11), "RESUMEN FINAL DE SEMANA ENTREGADO AL ADMINISTRADOR");
                    sl.SetCellValue("B" + (3 + productosTable.Count + ConceptosEgresos.Count + 12), "INGRESOS");
                    sl.SetCellValue("B" + (3 + productosTable.Count + ConceptosEgresos.Count + 13), "GASTOS");
                    sl.SetCellValue("B" + (3 + productosTable.Count + ConceptosEgresos.Count + 14), "TOTAL");

                    sl.SetCellValue("C" + (3 + productosTable.Count + ConceptosEgresos.Count + 12), "$" + Decimal.Round(totalSemana, 2));
                    sl.SetCellValue("C" + (3 + productosTable.Count + ConceptosEgresos.Count + 13), "$" + Decimal.Round(totalSemanaEgr, 2));
                    sl.SetCellValue("C" + (3 + productosTable.Count + ConceptosEgresos.Count + 14), "$" + Decimal.Round((totalSemana - totalSemanaEgr) + (lastTotalIngresos), 2));

                    lastTotalEgresos  = totalSemanaEgr;
                    lastTotalIngresos = lastTotalIngresos + (totalSemana - totalSemanaEgr);
                    //lastTotalIngresos = totalSemana==0? lastTotalIngresos: (totalSemana - totalSemanaEgr) + (lastTotalIngresos);

                    // lastTotalIngresos = totalSemana == 0? lastTotalIngresos:(lastTotalIngresos -= lastTotalEgresos);
                    // MessageBox.Show(lastTotalIngresos.ToString());
                }

                sl.DeleteWorksheet("Sheet1");
                if (!Directory.Exists(folderpath))
                {
                    DirectoryInfo di = Directory.CreateDirectory(folderpath);
                    sl.SaveAs(folderpath + "\\" + fileName);
                }
                else
                {
                    sl.SaveAs(folderpath + "\\" + fileName);
                }
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            return(result);
        }
Example #44
0
 public LineaMovimiento(int pCantidad, float pPrecioUnitario, Movimiento pMovimiento, Producto pProducto)
 {
     this.cantidad       = pCantidad;
     this.precioUnitario = pPrecioUnitario;
     this.movimiento     = pMovimiento;
     this.producto       = pProducto;
 }
Example #45
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,NombreProducto,TipoProducto,Precio,Cantidad,ProfileImage")] ProductoViewModel vm, string listTipoProducto)
        {
            if (vm.Cantidad > 0)
            {
                string stringFileName = UploadFile(vm);
                var    producto       = new Producto
                {
                    Id             = vm.Id,
                    NombreProducto = vm.NombreProducto,
                    TipoProducto   = listTipoProducto,
                    Precio         = vm.Precio,
                    Cantidad       = vm.Cantidad,
                    ProfileImage   = stringFileName
                };

                //if (id != vm.Id)
                //{
                //    return NotFound();
                //}

                //if (ModelState.IsValid)
                //{
                //    try
                //    {
                //        Context.Update(producto);
                //        Context.SaveChanges();
                //    }
                //    catch (DbUpdateConcurrencyException)
                //    {
                //        if (!ProductoExists(producto.Id))
                //        {
                //            return NotFound();
                //        }
                //        else
                //        {

                //            throw;
                //        }
                //    }
                //    return RedirectToAction(nameof(Index));
                //}
                //return View(producto);

                if (id != producto.Id)
                {
                    return(NotFound());
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        using (var cl = new HttpClient())
                        {
                            cl.BaseAddress = new Uri(baseURL);
                            var content     = JsonConvert.SerializeObject(producto);
                            var buffer      = System.Text.Encoding.UTF8.GetBytes(content);
                            var byteContent = new ByteArrayContent(buffer);
                            byteContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                            HttpResponseMessage res = await cl.PutAsync("api/Producto/" + id, byteContent);

                            if (res.IsSuccessStatusCode)
                            {
                                return(RedirectToAction(nameof(Index)));
                            }
                        }
                    }
                    catch (Exception ee)
                    {
                        var temp = await GetProducto(id);

                        if (temp == null)
                        {
                            return(NotFound());
                        }
                        else
                        {
                            throw;
                        }
                    }
                    return(RedirectToAction(nameof(Index)));
                }
                return(View(producto));
            }
            else
            {
                ViewBag.Lista            = Context.TipoProducto.ToList();
                TempData["errorMensaje"] = "La cantidad de unidades ingresadas debe ser mayor que 0.";
                return(View(vm));
            }
        }
 internal void ColocarProductoSeleccionado(Producto productoSeleccionado)
 {
     LineaActual.Producto = productoSeleccionado;
     LineaActual.ActualizarSubTotal();
 }
 public async Task ActualizarProducto(int id, Producto producto)
 {
     _context.Entry(producto).State = EntityState.Modified;
     _context.Update(producto);
     await _context.SaveChangesAsync();
 }
 public EditarProductoVenta(Producto producto)
 {
     InitializeComponent();
     productoCargar = producto;
     CargarCampos();
 }
Example #49
0
 public bool find(Producto objProducto)
 {
     return(objProductoDao.find(objProducto));
 }
Example #50
0
 public List <Producto> findAllProductos(Producto objProducto)
 {
     return(objProductoDao.findAllProductos(objProducto));
 }
Example #51
0
        public void update(Producto objProducto)
        {
            bool verificacion = true;

            //inicio verificacion de nombre estado=2
            string nombre = objProducto.Nombre;

            if (nombre == null)
            {
                objProducto.Estado = 20;
                return;
            }
            else
            {
                nombre       = objProducto.Nombre.Trim();
                verificacion = nombre.Length > 0 && nombre.Length <= 30;
                if (!verificacion)
                {
                    objProducto.Estado = 2;
                    return;
                }
            }
            //fin verificacion de codigo

            //inicio verificacion de precioUnitario estado=3
            string  precioUni = objProducto.PrecioUnitario.ToString();
            decimal preUni    = 0;

            if (nombre == null)
            {
                objProducto.Estado = 30;
                return;
            }
            else
            {
                try
                {
                    preUni       = Convert.ToDecimal(objProducto.PrecioUnitario);
                    verificacion = preUni > 0 && preUni <= 9999999;
                    if (!verificacion)
                    {
                        objProducto.Estado = 3;
                        return;
                    }
                }
                catch (Exception)
                {
                    objProducto.Estado = 300;
                    return;
                }
            }
            //fin verificacion de precioUnitario

            //inicio verificacion de categoria estado=4
            string categoria = objProducto.Categoria;

            if (categoria == null)
            {
                objProducto.Estado = 40;
                return;
            }
            else
            {
                categoria    = objProducto.Categoria.Trim();
                verificacion = categoria.Length > 0 && categoria.Length <= 5;
                if (!verificacion)
                {
                    objProducto.Estado = 4;
                    return;
                }
            }
            //fin verificacion de categoria

            //todo bien
            objProducto.Estado = 99;
            objProductoDao.update(objProducto);
            return;
        }
 public async Task CreateProducto(Producto producto)
 {
     _context.Add(producto);
     await _context.SaveChangesAsync();
 }
        private void btnModificarNC_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                bandera = true;
                int idnotacredito = (int)ltsNC.SelectedValue;
                productosAmodificar.Clear();
                String iva      = txtIVA.Text;
                String subtotal = txtSubtotal.Text;
                String cambio   = txtTipoCambio.Text;
                String total    = txtTotal.Text;

                String idf       = "SELECT FK_idfacturas FROM notacreditosalida WHERE idNotaCredito = '" + ltsNC.SelectedValue + "'";
                String idFactura = conexion.ValorEnVariable(idf);

                String productosFatura = "SELECT DISTINCT t1.subtotal, t2.nombre ,t2.precioUnitario,t2.idProductos,t3.cantidad from productos_has_facturassalida t1, productos_has_notacreditosalida t3 inner join productos t2 where t1.FK_idProductos = t2.idProductos and t1.FK_idfacturas = '" + idFactura + "' and  t3.FK_idNotaCredito = '" + ltsNC.SelectedValue + "'";
                productos = conexion.ConsultaParametrizada(productosFatura, ltsNC.SelectedValue);


                for (int i = 0; i < productos.Rows.Count; i++)
                {
                    producto = new Producto(productos.Rows[i].ItemArray[1].ToString(), (int)productos.Rows[i].ItemArray[3], (int)productos.Rows[i].ItemArray[4], (float)productos.Rows[i].ItemArray[0], (float)productos.Rows[i].ItemArray[2]);

                    productosAmodificar.Add(producto);
                }



                var newW = new windowAgregarNCFactura(subtotal, total, iva, cambio, productosAmodificar, idFactura, idnotacredito, 1);
                newW.Title = "Modificar Nota de Crédito";
                newW.ShowDialog();

                if (newW.DialogResult == true)
                {
                    String subm          = newW.subtotalmodificar;
                    String totalm        = newW.totalmodificar;
                    int    idnotaCredito = newW.idnota;
                    itemsNC.Clear();
                    foreach (Producto p in newW.itemsNC)
                    {
                        String nombre    = p.nombre;
                        int    cantidad  = p.cantidad;
                        float  totalp    = p.total;
                        float  precioUni = p.precioUnitario;
                        int    idp       = p.id;

                        Producto pr = new Producto(nombre, idp, cantidad, totalp, precioUni);
                        itemsNC.Add(p);

                        String updateNC = "UPDATE notacreditosalida SET total =  '" + totalm + "', subtotal = '" + subm + "' WHERE idNotaCredito = '" + idnotaCredito + "'";
                        conexion.operaciones(updateNC);

                        String updateProductosNC = "UPDATE productos_has_notacreditosalida SET FK_idNotaCredito = '" + idnotaCredito + "', FK_idProductos = '" + idp + "', cantidad = '" + cantidad + "', precioUnitario = '" + precioUni + "' WHERE FK_idNotaCredito = '" + idnotaCredito + "' AND FK_idProductos = '" + idp + "'";
                        conexion.operaciones(updateProductosNC);

                        foreach (var producto in newW.itemsFact)
                        {
                            String sql = "UPDATE productos_has_facturassalida SET CrNotaCredito = '" + producto.cantidad + "' where FK_idProductos = '" + producto.id + "' and FK_idfacturas = '" + idFactura + "'";
                            conexion.operaciones(sql);
                        }
                        foreach (var item in newW.itemsNCAntiguos)
                        {
                            String updatestock = "UPDATE productos SET stock = stock-'" + item.cantidad + "' where idProductos = '" + item.id + "'";
                            conexion.operaciones(updatestock);
                        }
                        //update stock
                        foreach (var item in newW.itemsNC)
                        {
                            String updatestock = "UPDATE productos SET stock = stock +'" + item.cantidad + "' where idProductos = '" + item.id + "'";
                            conexion.operaciones(updatestock);
                        }
                    }
                    LoadDgvNC();
                    loadLtsNotaCredito();

                    bandera = false;
                    ltsNC.Items.MoveCurrentToLast();
                    MessageBox.Show("Se modifico correctamente", "Información", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("Seleccione una factura a modificar", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #54
0
        public void create(Producto objProducto)
        {
            bool verificacion = true;
            //inicio verificacion de codigo estado=1
            string codigo = objProducto.IdProducto;

            if (codigo == null)
            {
                objProducto.Estado = 10;
                return;
            }
            else
            {
                codigo       = objProducto.IdProducto.Trim();
                verificacion = codigo.Length > 0 && codigo.Length <= 7;
                if (!verificacion)
                {
                    objProducto.Estado = 1;
                    return;
                }
            }
            //fin verificacion de codigo

            //inicio verificacion de nombre estado=2
            string nombre = objProducto.Nombre;

            if (nombre == null)
            {
                objProducto.Estado = 20;
                return;
            }
            else
            {
                nombre       = objProducto.Nombre.Trim();
                verificacion = nombre.Length > 0 && nombre.Length <= 30;
                if (!verificacion)
                {
                    objProducto.Estado = 2;
                    return;
                }
            }
            //fin verificacion de codigo

            //inicio verificacion de precioUnitario estado=3
            string precioUni = objProducto.PrecioUnitario.ToString();
            double preUni    = 0;

            if (nombre == null)
            {
                objProducto.Estado = 30;
                return;
            }
            else
            {
                try
                {
                    preUni       = Convert.ToDouble(objProducto.PrecioUnitario);
                    verificacion = preUni > 0 && preUni <= 9999999;
                    if (!verificacion)
                    {
                        objProducto.Estado = 3;
                        return;
                    }
                }
                catch (Exception)
                {
                    objProducto.Estado = 300;
                    return;
                }
            }
            //fin verificacion de precioUnitario

            //inicio verificacion de categoria estado=4
            string categoria = objProducto.Categoria;

            if (categoria == null)
            {
                objProducto.Estado = 40;
                return;
            }
            else
            {
                categoria    = objProducto.Categoria.Trim();
                verificacion = categoria.Length > 0 && categoria.Length <= 30;
                if (!verificacion)
                {
                    objProducto.Estado = 4;
                    return;
                }
            }
            //fin verificacion de categoria

            //verificacion de duplicidad estado=5
            Producto objProductoAux = new Producto();

            objProductoAux.IdProducto = objProducto.IdProducto;
            verificacion = !objProductoDao.find(objProductoAux);
            if (!verificacion)
            {
                objProducto.Estado = 5;
                return;
            }
            //fin verificacion duplicidad

            //todo bien
            objProducto.Estado = 99;
            objProductoDao.create(objProducto);
            return;
        }
 public async Task EliminarProducto(Producto producto)
 {
     producto.Activo = 0;
     _context.Entry(producto).State = EntityState.Modified;
     await _context.SaveChangesAsync();
 }
Example #56
0
 public void ActualizarProducto(Producto producto)
 {
     db.Update(producto);
 }
Example #57
0
 public void InsertarProducto(Producto producto)
 {
     db.Insert(producto);
 }
        private void btnAgregar_Click(object sender, RoutedEventArgs e)
        {
            bandera = true;
            itemsNC.Clear();
            int index = ltsNC.SelectedIndex;

            Console.WriteLine("idindex parametro  " + index);
            var newW = new windowAgregarNCFactura(1);

            newW.ShowDialog();
            DateTime hoy = DateTime.Today;


            if (newW.DialogResult == true)
            {
                idFactura = newW.idFactura;
                String totall    = newW.txtTotal.Text;
                String subtotall = newW.txtSubtotal.Text;
                String insertNC  = "INSERT INTO notacreditosalida (total, subtotal,FK_idFacturas, fecha) VALUES ( '" + totall + "', '" + subtotall + "','" + idFactura + "','" + hoy.ToString("yyyy/MM/dd") + "')";
                conexion.operaciones(insertNC);


                string ultimoId = "Select last_insert_id()";
                lastid = conexion.ValorEnVariable(ultimoId);

                foreach (Producto p in newW.itemsNC)
                {
                    String nombre    = p.nombre;
                    int    cantidad  = p.cantidad;
                    float  totalp    = p.total;
                    float  precioUni = p.precioUnitario;
                    int    idp       = p.id;

                    Producto pr = new Producto(nombre, idp, cantidad, totalp, precioUni);
                    itemsNC.Add(p);

                    String productostNC = "INSERT INTO productos_has_notacreditosalida (FK_idNotaCredito, FK_idProductos, cantidad, precioUnitario) VALUES ('" + lastid + "','" + idp + "', '" + cantidad + "', '" + precioUni + "')";
                    conexion.operaciones(productostNC);

                    String updatestock = "UPDATE productos SET stock = stock+'" + p.cantidad + "' where idProductos = '" + p.id + "'";
                    conexion.operaciones(updatestock);
                }

                foreach (var producto in newW.itemsFact)
                {
                    String sql = "UPDATE productos_has_facturassalida SET CrNotaCredito = '" + producto.cantidad + "' where FK_idProductos = '" + producto.id + "' and FK_idfacturas = '" + idFactura + "'";
                    conexion.operaciones(sql);
                }
                String updateestadoOC = "UPDATE ordencomprasalida SET estadoNC = '" + 2 + "' where idOrdenCompra = '" + newW.idOC + "'";
                conexion.operaciones(updateestadoOC);

                LoadDgvNC();
                loadLtsNotaCredito();

                bandera = false;

                MessageBox.Show("Se agrego correctamente", "Información", MessageBoxButton.OK, MessageBoxImage.Information);
                ltsNC.SelectedIndex = -1;
                ltsNC.SelectedIndex = 0;
            }
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="productoSeleccionado">Producto seleccionado por el usuario en la lista del principalForm.</param>
 public ModificarProductoForm(Producto productoSeleccionado)
 {
     InitializeComponent();
     this.productoSeleccionado = productoSeleccionado;
 }
Example #60
-1
        public void FacturaConUnProductGetTotal()
        {
            Factura factura = new Factura();
            Producto producto = new Producto(10);
            factura.AddProducto(producto, 2);

            Assert.AreEqual(20, factura.GetTotal());
        }