public async Task <ActionResult> AgregarUnidad(CatDetalleViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    IRepositoryWrapper _repo = new RepositoryWrapper();
                    if (_repo.CatDetalle.Exists(x => x.DepartamentoId == model.DepartamentoId &&
                                                (x.Descripcion.Trim() == model.Descripcion.ToUpper() || x.Clave.Trim().ToUpper() == model.Clave.Trim().ToUpper())))
                    {
                        ViewBag.ErrorMessage = "La clave, descripcion o nombre de la unidad o persona ya existe en el catalogo para ese departamento";
                        return(View(model));
                    }
                    Pre_CatDetalle unidad = new Pre_CatDetalle();
                    unidad.Descripcion    = model.Descripcion;
                    unidad.DepartamentoId = model.DepartamentoId;
                    unidad.Clave          = model.Clave;

                    var result = _repo.CatDetalle.AddUpdate(unidad);
                    if (!result.Item1)
                    {
                        ViewBag.ErrorMessage = string.Join(Environment.NewLine, result.Item2);
                        return(View(model));
                    }


                    //int departamentoId = -1;
                    //if (Request.Params["ClaveDepartamento"] != null)
                    //    int.TryParse("0" + Request.Params["ClaveDepartamento"], out departamentoId);
                    //IRepositoryWrapper _repo = new RepositoryWrapper();
                    var listado = await _repo.CatDetalle.GetCatDetalleByDepartamentoAsync(model.DepartamentoId);

                    return(PartialView("_gvUnidadesViewPartial", listado.OrderBy(s => s.Descripcion)));

                    //return RedirectToAction("Unidades", "Catalogos");
                }

                catch (Exception ex)
                {
                    ViewBag.ErrorMessage = ex.Message;
                }
            }
            else
            {
                ViewBag.ErrorMessage = "La información esta incompleta";
            }
            return(View(model));
        }
        public ActionResult ComboBoxConceptosGastosPartial()
        {
            int departamentoId = -1;

            if (Request.Params["Clave_Departamento"] != null)
            {
                int.TryParse("0" + Request.Params["Clave_Departamento"], out departamentoId);
            }
            int unidadId = -1;

            if (Request.Params["Clave_Unidad"] != null)
            {
                int.TryParse("0" + Request.Params["Clave_Unidad"], out unidadId);
            }

            IRepositoryWrapper _repo = new RepositoryWrapper();
            var catUnidad            = _repo.CatDetalle.FindByFilter(u => u.DepartamentoId == departamentoId && u.Oid == unidadId);

            if (catUnidad == null)
            {
                catUnidad = new Pre_CatDetalle();
            }
            var catConcepto = _repo.CatConceptoGasto.Find(catUnidad.ClaveContable ?? 0);

            if (catConcepto == null)
            {
                catConcepto = new Pre_CatConceptoGasto();
            }
            int subCuenta = catConcepto.SubCuenta;
            int ssCuenta  = catConcepto.SSCuenta;
            var model     = _repo.GastoDetalle
                            .GetConceptos(catConcepto.EmpresaId, subCuenta, ssCuenta, catConcepto.AreaId).ToList();

            if (model.Count == 0)
            {
                model.Add(new ListItemIntKey {
                    ID = 0, Name = "NO APLICA"
                });
            }

            //var model = _repo.CatDetalle.GetCatDetalleByDepartamento(departamentoId);

            return(PartialView("_ComboBoxConceptosGastosPartial", model));
        }
        public async Task <ActionResult> EditarUnidad(CatUnidadViewModel model)
        {
            IRepositoryWrapper _repo = new RepositoryWrapper();

            ViewBag.Departamentos = await _repo.CatDepartamentos.GetDepartamentosAsync();

            ViewBag.Empresas = await _repo.CatDetalle.GetEmpresasAsync();

            ViewBag.Areas = await _repo.CatDetalle.GetAreasAsync();

            ViewBag.SubCuentas = await _repo.CatDetalle.GetSubCuentasAsync();

            ViewBag.SSCuentas = await _repo.CatDetalle.GetSSCuentasAsync(model.EmpresaId, model.AreaId, model.SubCuentaId);

            if (ModelState.IsValid)
            {
                ViewBag.TiposDetalle = await _repo.Configuracion.GetTiposDetalleListItemAsync();

                if (_repo.CatDetalle.Exists(x => x.DepartamentoId == model.DepartamentoId &&
                                            (x.Descripcion.Trim().ToUpper() == model.Descripcion.Trim().ToUpper() || x.Clave.Trim().ToUpper() == model.Clave.Trim().ToUpper()) &&
                                            x.Oid != model.Id))
                {
                    //throw new Exception("La clave o descripcion de la unidad o persona ya existe en el catalogo");
                    ViewBag.ErrorMessage = "La clave o descripcion de la unidad o persona ya existe en el catalogo para el departamento seleccionado";
                    return(View(model));
                }
                // VALIDAR SI CAMBIO EL DEPARTAMENTO
                var _detPaso = _repo.CatDetalle.Find(model.Id);
                if (_detPaso != null)
                {
                    if (_detPaso.DepartamentoId != model.DepartamentoId)
                    {
                        if (_repo.GastoDetalle.Exists(x => x.DepartamentoId == _detPaso.DepartamentoId && x.UnidadId == model.Id))
                        {
                            var porDepto = await _repo.GastoDepartamento.FindByFilterAsync(x => x.DepartamentoId == _detPaso.DepartamentoId);

                            var detMensual = await _repo.GastoDetalle.GetDataAsync(x => x.DepartamentoId == _detPaso.DepartamentoId && x.UnidadId == model.Id);

                            decimal montoTotal = 0m;

                            foreach (var item in detMensual)
                            {
                                montoTotal += item.Monto;
                            }
                            if (montoTotal != 0m)
                            {
                                ViewBag.ErrorMessage = "La unidad o persona ya tiene importes capturados en el departamento anterior, no se puede cambiar."
                                                       + Environment.NewLine + "Es necesario Cambiar los importes capturados a cero para poder hacer el cambio";
                                return(View(model));
                            }
                            var listaBorrar = detMensual.ToList();
                            foreach (var item in listaBorrar)
                            {
                                _repo.GastoDetalle.Remove(item);
                            }
                            var detUnidad = await _repo.GastoUnidad.GetDataAsync(x => x.DepartamentoId == _detPaso.DepartamentoId && x.UnidadId == model.Id);

                            var listaUnidadBorrar = detUnidad.ToList();
                            foreach (var item in listaUnidadBorrar)
                            {
                                _repo.GastoUnidad.Remove(item);
                            }
                        }
                    }
                }
                // VALIDAMOS SI EXISTE UN CONCEPTO CON LOS DATOS CONTABLES PARA DARLO DE ALTA EN SU CASO
                var _concepto = _repo.CatConceptoGasto
                                .FindByFilter(x => x.AreaId == model.AreaId && x.SubCuenta == model.SubCuentaId && x.SSCuenta == model.SSCuentaId && x.EmpresaId == model.EmpresaId);
                string descripcionContable = "";
                if (_concepto == null)
                {
                    var ssCuentas = _repo.CatDetalle.GetSSCuentas(model.EmpresaId, model.AreaId, model.SubCuentaId).ToList();
                    descripcionContable = ssCuentas.Where(x => x.ID == model.SSCuentaId)
                                          .Select(x => x.Name).DefaultIfEmpty("").FirstOrDefault();
                    _concepto = new Pre_CatConceptoGasto
                    {
                        AreaId      = model.AreaId,
                        Descripcion = descripcionContable,
                        EmpresaId   = model.EmpresaId,
                        SSCuenta    = model.SSCuentaId,
                        SubCuenta   = model.SubCuentaId
                    };
                    var resultConcepto = _repo.CatConceptoGasto.AddUpdate(_concepto);
                    if (!resultConcepto.Item1)
                    {
                        ViewBag.ErrorMessage = string.Join(Environment.NewLine, resultConcepto.Item2);
                        return(View(model));
                        //throw new Exception(string.Join(Environment.NewLine, resultConcepto.Item2));
                    }
                }
                Pre_CatDetalle unidad = new Pre_CatDetalle
                {
                    Oid                 = model.Id,
                    Descripcion         = model.Descripcion,
                    Clave               = model.Clave,
                    DepartamentoId      = model.DepartamentoId,
                    ClaveContable       = _concepto.Oid,
                    DescripcionContable = _concepto.Descripcion,
                    TipoDetalle         = model.TipoDetalle
                };
                var result = await _repo.CatDetalle.AddUpdateAsync(unidad);

                if (!result.Item1)
                {
                    ViewBag.ErrorMessage = string.Join(Environment.NewLine, result.Item2);
                    return(View(model));
                }
                // ELIMINAR EL DEPARTAMENTO ACTUAL
                var resulBorrar = await _repo.CatDetalle.DeleteAsync(_detPaso);

                if (!resulBorrar.Item1)
                {
                    ViewBag.ErrorMessage = string.Join(Environment.NewLine, resulBorrar.Item2);
                    return(View(model));
                }
                return(RedirectToAction("Unidades", "Catalogos"));
            }
            else
            {
                ViewBag.ErrorMessage = "La información esta incompleta";
            }
            return(View(model));
        }
        public async Task <ActionResult> AgregarNuevaUnidad(int?departamentoId, string clave, string descripcion, short?areaId, short?subCuentaId, short?ssCuentaId, short?empresaId, string descSSCuenta, string tipoDetalle)
        {
            try
            {
                IRepositoryWrapper _repo = new RepositoryWrapper();
                if (_repo.CatDetalle.Exists(x => x.DepartamentoId == departamentoId &&
                                            (x.Descripcion.Trim() == descripcion.ToUpper() || x.Clave.Trim().ToUpper() == clave.Trim().ToUpper())))
                {
                    ViewBag.ErrorMessage = "La clave, descripcion o nombre de la unidad o persona ya existe en el catalogo para ese departamento";
                    return(View());
                }
                // VALIDAMOS SI EXISTE UN CONCEPTO CON LOS DATOS CONTABLES PARA DARLO DE ALTA EN SU CASO
                var _concepto = _repo.CatConceptoGasto
                                .FindByFilter(x => x.AreaId == areaId && x.SubCuenta == subCuentaId && x.SSCuenta == ssCuentaId && x.EmpresaId == empresaId);
                if (_concepto == null)
                {
                    _concepto = new Pre_CatConceptoGasto
                    {
                        AreaId      = areaId ?? 0,
                        Descripcion = descSSCuenta,
                        EmpresaId   = empresaId ?? 0,
                        SSCuenta    = ssCuentaId ?? 0,
                        SubCuenta   = subCuentaId ?? 0
                    };
                    var resultConcepto = _repo.CatConceptoGasto.AddUpdate(_concepto);
                    if (!resultConcepto.Item1)
                    {
                        throw new Exception(string.Join(Environment.NewLine, resultConcepto.Item2));
                    }
                }

                Pre_CatDetalle unidad = new Pre_CatDetalle();
                unidad.Descripcion         = descripcion;
                unidad.DepartamentoId      = departamentoId ?? 0;
                unidad.Clave               = clave;
                unidad.ClaveContable       = _concepto.Oid;
                unidad.DescripcionContable = _concepto.Descripcion;
                unidad.TipoDetalle         = tipoDetalle;

                if (string.IsNullOrWhiteSpace(descripcion))
                {
                    ViewBag.ErrorMessage = "Debe capturarse la descripcion de la unidad o nombre de la persona";
                    return(View());
                }
                if (string.IsNullOrWhiteSpace(clave))
                {
                    ViewBag.ErrorMessage = "Debe capturarse la clave de la unidad o persona";
                    return(View());
                }
                if ((departamentoId ?? 0) <= 0)
                {
                    ViewBag.ErrorMessage = "Debe seleccionarse un departamento";
                    return(View());
                }
                if (string.IsNullOrWhiteSpace(tipoDetalle))
                {
                    ViewBag.ErrorMessage = "Debe seleccionarse el tipo para detalle del gasto";
                    return(View());
                }

                var result = _repo.CatDetalle.AddUpdate(unidad);
                if (!result.Item1)
                {
                    ViewBag.ErrorMessage = string.Join(Environment.NewLine, result.Item2);
                    return(View());
                }


                //int departamentoId = -1;
                //if (Request.Params["ClaveDepartamento"] != null)
                //    int.TryParse("0" + Request.Params["ClaveDepartamento"], out departamentoId);
                //IRepositoryWrapper _repo = new RepositoryWrapper();
                var listado = await _repo.CatDetalle.GetCatDetalleByDepartamentoAsync(departamentoId ?? 0);

                return(PartialView("_gvUnidadesViewPartial", listado.OrderBy(s => s.Descripcion)));

                //return RedirectToAction("Unidades", "Catalogos");
            }

            catch (Exception ex)
            {
                ViewBag.ErrorMessage = ex.Message;
            }
            return(View());
        }