Example #1
0
        public ActionResult DeleteConfirmed(string id)
        {
            Usuario usuario = db.Usuarios.Find(id);

            db.Usuarios.Remove(usuario);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #2
0
File: Fn.cs Project: jump720/MMS
        public static void AddLog(string usuario, string evento, string key, object data, string client)
        {
            try
            {
                using (var db = new MMSContext())
                {
                    int?eventoId = db.Evento.FirstOrDefault(e => e.Nombre == evento && e.Activo)?.Id;
                    if (eventoId == null)
                    {
                        return;
                    }

                    var log = new Log()
                    {
                        Fecha    = DateTime.Now,
                        Usuario  = string.IsNullOrWhiteSpace(usuario) ? "Anonymous" : usuario,
                        Data     = Fn.GetJsonString(data),
                        Cliente  = client,
                        EventoId = (int)eventoId,
                        Key      = key
                    };

                    db.Log.Add(log);
                    db.SaveChanges();
                }
            }
            catch { }
        }
Example #3
0
        //[Bind(Include = "RolId,RolNombre")]
        public async Task <ActionResult> Create(RolesViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    db.Roles.Add(model.Rol);
                    db.SaveChanges();
                    await db.SaveChangesAsync();

                    //Objetos
                    foreach (var obj in model.Objetos)
                    {
                        if (obj.Seleccionado)
                        {
                            RolObjeto ao = new RolObjeto();
                            ao.RolId           = model.Rol.RolId;
                            ao.ObjetoId        = obj.ObjetoId;
                            ao.RolObjetoActivo = true;
                            db.RolObjeto.Add(ao);
                        }
                    }

                    //Apps
                    foreach (var app in model.Apps)
                    {
                        if (app.Seleccionado)
                        {
                            RolAplicacion ao = new RolAplicacion();
                            ao.AplicacionId = app.AplicacionId;
                            ao.RolId        = model.Rol.RolId;
                            db.RolAplicaciones.Add(ao);
                        }
                    }

                    if (!ModelState.Values.Any(ms => ms.Errors.Count > 0))
                    {
                        await db.SaveChangesAsync();

                        AddLog("", model.Rol.RolId, model);
                        return(RedirectToAction("Index", GetReturnSearch()));
                    }

                    //Guarda Objetos al rol
                    // guardaRolObjeto(RolObjetoList, rol.RolId);

                    return(RedirectToAction("Index"));
                }
                catch (Exception e)
                {
                    ViewBag.Error = e.ToString();
                }
            }



            return(View(new RolesViewModel {
                Rol = model.Rol, Objetos = model.Objetos, Apps = model.Apps
            }));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            PresupuestoVendedor presupuestoVendedor = db.PresupuestoVendedor.Find(id);

            db.PresupuestoVendedor.Remove(presupuestoVendedor);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #5
0
        public ActionResult DeleteConfirmed(int id)
        {
            Gasto gasto = db.Gasto.Find(id);

            db.Gasto.Remove(gasto);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #6
0
        /*función o metodo que valida los permisos de un rol con los objetos (esto se valida con los datos de la session[Seguridad])*/
        public bool validaSeguridad(Seguridadcll seguridadcll = null, string ObjetoId = "")
        {
            bool Result = false;
            //List<RolUsuario> RolUsuarioList = seguridadcll.RolUsuarioList;
            List <RolObjeto> RolObjetoList = seguridadcll.RolObjetoList;


            var RolObjeto = RolObjetoList
                            .Where(o => o.ObjetoId.ToLower().Trim() == ObjetoId.ToLower().Trim()).FirstOrDefault();

            //Result = (RolObjeto != null) ? true : Result;

            if (RolObjeto != null)//Si tiene permiso
            {
                Result = true;
            }
            else//No tiene permiso
            {
                Result = false;
                /*Crear el objeto si no existe en la BD*/
                var objeto = db.Objeto
                             .Where(o => o.ObjetoId.ToLower().Trim() == ObjetoId.ToLower().Trim())
                             .FirstOrDefault();
                if (objeto == null)
                {
                    Objeto o = new Objeto();
                    o.ObjetoId   = ObjetoId;
                    o.ObjetoDesc = ObjetoId;
                    o.ObjetoMenu = false;

                    db.Objeto.Add(o);
                    db.SaveChanges();
                }
                /*Crear el objeto si no existe en la BD*/
            }


            return(Result);
        }
Example #7
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any())
            {
                return;
            }

            if (actionContext.Request.Headers.Authorization == null)
            {
                HandleUnauthorizedRequest(actionContext);
                return;
            }

            string scheme = actionContext.Request.Headers.Authorization.Scheme;
            string token  = actionContext.Request.Headers.Authorization.Parameter;

            if (string.IsNullOrWhiteSpace(scheme) || string.IsNullOrWhiteSpace(token) || scheme != "Bearer")
            {
                HandleUnauthorizedRequest(actionContext);
                return;
            }

            using (var db = new MMSContext())
            {
                var data = db.UsuarioToken
                           .Include(ut => ut.Usuario)
                           .Include(ut => ut.Usuario.RolUsuarioList)
                           .Where(ut => ut.Usuario.Usuarioactivo && ut.Token == token)
                           .Select(ut => new
                {
                    Usuario      = ut.Usuario,
                    UsuarioToken = ut,
                    RolesId      = ut.Usuario.RolUsuarioList.Select(ru => ru.RolId).ToList()
                })
                           .FirstOrDefault();

                if (data == null || !db.RolObjeto.Where(ro => data.RolesId.Contains(ro.RolId) && ro.ObjetoId == "PerfectStore").Any())
                {
                    HandleUnauthorizedRequest(actionContext);
                    return;
                }

                data.UsuarioToken.FechaUltimoUso = DateTime.Now;

                db.Entry(data.UsuarioToken).State = EntityState.Modified;
                db.SaveChanges();

                HttpContext.Current.Items["__usuario"] = data.Usuario;
            }
        }
Example #8
0
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

            if (HttpContext.Current.Items["__logs"] == null)
            {
                return;
            }

            List <Log> logs = (List <Log>)HttpContext.Current.Items["__logs"];

            using (var db = new MMSContext())
            {
                db.Log.AddRange(logs);
                db.SaveChanges();
            }
        }
Example #9
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (HttpContext.Current.Items["__logs"] == null)
            {
                return;
            }

            List <Log> logs = (List <Log>)HttpContext.Current.Items["__logs"];

            if (logs.Count > 0)
            {
                using (var db = new MMSContext())
                {
                    db.Log.AddRange(logs);
                    db.SaveChanges();
                }
            }
        }
Example #10
0
        public void insertAuditoria(Auditoria modelo)
        {
            MMSContext db = new MMSContext();

            //SqlParameter[] parametters = new SqlParameter[9];
            //int cont = 0;
            try
            {
                System.Web.HttpContext context = HttpContext.Current;
                // System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(context.Request.UserHostAddress);

                modelo.AuditoriaEquipo = "SERVER/HTCL0003";//hostEntry.HostName;

                db.Auditoria.Add(modelo);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw;
            }
        }
Example #11
0
        public ActionResult DeleteConfirmed(string[] ids)
        {
            try
            {
                TipoGasto tipoGasto = db.TipoGastos.Find(ids);
                db.TipoGastos.Remove(tipoGasto);
                db.SaveChanges();

                //Auditoria
                Seguridad.Seguridad seguridad    = new Seguridad.Seguridad();
                Auditoria           auditoria    = new Auditoria();
                Seguridadcll        seguridadcll = (Seguridadcll)Session["seguridad"];

                auditoria.AuditoriaFecha  = System.DateTime.Now;
                auditoria.AuditoriaHora   = System.DateTime.Now.TimeOfDay;
                auditoria.usuarioId       = seguridadcll.Usuario.UsuarioId;
                auditoria.AuditoriaEvento = "Eliminar";
                auditoria.AuditoriaDesc   = "Eliminó TipoGasto: " + tipoGasto.TipoGastoID;
                auditoria.ObjetoId        = RouteData.Values["controller"].ToString() + "/" + RouteData.Values["action"].ToString();

                seguridad.insertAuditoria(auditoria);
                //Auditoria
            }
            catch (Exception e)
            {
                var tipoGastos = db.TipoGastos.Find(ids);
                if (tipoGastos == null)
                {
                    ViewBag.Error = "Advertencia, Registro no encontrado o Invalido " + ids;
                }
                else
                {
                    ViewBag.Error = e.ToString();
                }
            }
            return(RedirectToAction("Index"));
        }
Example #12
0
        public ActionResult Edit(Orden orden, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                //Modifica Cabecera de la orden
                db.Entry(orden).State = EntityState.Modified;
                db.SaveChanges();

                //Modifica Items de la orden
                bool flagMod = ModificaOrdenItems(orden.OrdenId, form);

                if (flagMod)
                {
                    //Afecta cantidad de Productos Inventariables en el Gasto

                    //Reversa Movimiento de salida por la orden
                    List <Movimiento>     movimientoList = db.Movimiento.Where(m => m.OrdenId == orden.OrdenId).ToList();
                    MovimientosController movCtrl        = new MovimientosController();
                    movCtrl.RegresaMovimiento(movimientoList);

                    Seguridadcll seguridadcll = (Seguridadcll)Session["seguridad"];
                    // MovimientosController movCtrl = new MovimientosController();
                    movCtrl.CreaMovimientoXOrden(orden.OrdenId, trnMode.Update, seguridadcll);

                    #region auditoria
                    Seguridad.Seguridad seguridad = new Seguridad.Seguridad();
                    Auditoria           auditoria = new Auditoria();


                    auditoria.AuditoriaFecha  = System.DateTime.Now;
                    auditoria.AuditoriaHora   = System.DateTime.Now.TimeOfDay;
                    auditoria.usuarioId       = seguridadcll.Usuario.UsuarioId;
                    auditoria.AuditoriaEvento = "Edit";
                    auditoria.AuditoriaDesc   = "Se Modifico La Orden: " + orden.OrdenId;
                    auditoria.ObjetoId        = "Ordenes/Edit";

                    seguridad.insertAuditoria(auditoria);
                    #endregion auditoria


                    ////Modifica Cantidades del Movimiento
                    //return RedirectToAction("CreaMovimientoXOrden", "Movimientos", new { OrdenId = orden.OrdenId, mode = trnMode.Update });
                    //Afecta cantidad de Productos Inventariables en el Gasto


                    return(RedirectToAction("Index", GetReturnSearch()));
                }
            }
            db.Configuration.ProxyCreationEnabled = false;
            ViewBag.OrdenItems = db.OrdenItems.Where(o => o.OrdenId == orden.OrdenId).ToList();

            return(View(orden));
        }
Example #13
0
        //public bool CambioEstadoGasto(int GastoId = 0, int GastoLinea = 0, EstadoGasto Estado = EstadoGasto.Abierta)
        //public bool CambioEstadoGasto(int GastoId = 0, int GastoLinea = 0, EstadoGasto Estado = EstadoGasto.Abierta)
        //{
        //    bool result = false;
        //    var gasto = db.Gasto.Where(g => g.GastoId == GastoId && g.GastoLinea == GastoLinea).FirstOrDefault();

        //    if (gasto != null)
        //    {
        //        gasto.GastoEstado = Estado;
        //        db.Entry(gasto).State = EntityState.Modified;
        //        db.SaveChanges();
        //        result = true;

        //        #region auditoria
        //        Seguridad.Seguridad seguridad = new Seguridad.Seguridad();
        //        Auditoria auditoria = new Auditoria();
        //        Seguridadcll seguridadcll = (Seguridadcll)Session["seguridad"];

        //        auditoria.AuditoriaFecha = System.DateTime.Now;
        //        auditoria.AuditoriaHora = System.DateTime.Now.TimeOfDay;
        //        auditoria.usuarioId = seguridadcll.Usuario.UsuarioId;
        //        auditoria.AuditoriaEvento = "CambioEstadoGasto";
        //        auditoria.AuditoriaDesc = "Se cambio el estado del gasto: " + GastoId + " Linea: " + GastoLinea + " Estado: " + Estado.ToString();
        //        auditoria.ObjetoId = "Gastos/CambioEstadoGasto";

        //        seguridad.insertAuditoria(auditoria);
        //        #endregion auditoria
        //    }
        //    else
        //    {
        //        result = false;
        //    }

        //    return result;

        //}

        /// <summary>
        /// Steps:
        /// 1. Devuelve lo gastado(aun no ha guarado el gasto)
        /// 2. Afecta el gasto(el gasto ya fue guardado)
        /// </summary>
        /// <param name="gasto"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        public void AfectaPresupuestoXGasto(int gastoId = 0, int step = 0)
        {
            // bool result = true;
            using (var Context = new MMSContext())
            {
                var gastoTemp = Context.Gasto
                                .Include(g => g.actividad)
                                .Where(g => g.GastoId == gastoId && (g.GastoEstado == EstadoGasto.Ejecutado || g.GastoEstado == EstadoGasto.Pagado))
                                .FirstOrDefault();
                decimal ValorGasto = 0;


                if (gastoTemp != null)
                {
                    //var actividad = Context.Actividad.Where(a => a.ActividadId == gastoTemp.ActividadId).FirstOrDefault();
                    ValorGasto = gastoTemp.GastoValor * gastoTemp.GastoCant;
                    //Buscar Prespuesto a Afectar
                    DateTime Date = gastoTemp.actividad.ActividadFecha;

                    int Year     = Date.Year;
                    int Month    = Date.Month;
                    int quartile = 0;

                    if (Month >= 1 && Month <= 3)//Q1
                    {
                        quartile = 1;
                    }
                    else if (Month >= 4 && Month <= 6)//Q2
                    {
                        quartile = 2;
                    }
                    else if (Month >= 7 && Month <= 9)//Q3
                    {
                        quartile = 3;
                    }
                    else if (Month >= 10 && Month <= 12)//Q4
                    {
                        quartile = 4;
                    }//if (Month >= 1 && Month <= 3)

                    var prespuesto = db.PresupuestoVendedor.Where(p => p.PlantaID == gastoTemp.actividad.ClienteID && p.CentroCostoID == gastoTemp.CentroCostoID &&
                                                                  p.PresupuestoVendedorAno == Year).FirstOrDefault();

                    switch (step)
                    {
                    case 1:    //1. Devuelve lo gastado(aun no ha guarado el gasto)
                        if (prespuesto != null)
                        {
                            prespuesto.PresupuestoGasto    -= ValorGasto;
                            Context.Entry(prespuesto).State = EntityState.Modified;
                            Context.SaveChanges();
                        }    //if (prespuesto != null)
                        break;

                    case 2:    //2. Afecta el gasto(el gasto ya fue guardado)
                        if (prespuesto != null)
                        {
                            prespuesto.PresupuestoGasto    += ValorGasto;
                            Context.Entry(prespuesto).State = EntityState.Modified;
                            Context.SaveChanges();
                        }    //if (prespuesto != null)
                        break;
                    }
                }
                else
                {
                }
            }// using (var Context = new MMSContext())
             //return result;
        }