public IHttpActionResult Get([FromUri] parametroData data)
 {
     try
     {
         int codAreaGenerica = Convert.ToInt16(WebConfigurationManager.AppSettings["areaOperativaGenerica"]);
         var areaGenerica    = areaOperativaService.GetSingle(x => x.CA_COD_AREA == codAreaGenerica);
         if (data != null && data.cuenta != null)
         {
             data.cuenta = data.cuenta.Trim();
         }
         List <CuentaContableModel> dfs = service.GetAll(cc => (cc.CO_CUENTA_CONTABLE + cc.CO_COD_AUXILIAR + cc.CO_NUM_AUXILIAR).Contains(data.cuenta == null? cc.CO_CUENTA_CONTABLE + cc.CO_COD_AUXILIAR + cc.CO_NUM_AUXILIAR : data.cuenta) &&
                                                         cc.CE_ID_EMPRESA == data.empresaId &&
                                                         (cc.ca_id_area == data.area || cc.ca_id_area == areaGenerica.CA_ID_AREA));
         if (dfs.Count == 0)
         {
             return(BadRequest("No existen registros de cuentas."));
         }
         foreach (CuentaContableModel reg in dfs)
         {
             reg.CO_CUENTA_CONTABLE = reg.CO_CUENTA_CONTABLE + reg.CO_COD_AUXILIAR + reg.CO_NUM_AUXILIAR;
         }
         return(Ok(dfs));
     }
     catch (Exception ex)
     {
         return(BadRequest("No se puede obtener las cuentas. " + ex.Message));
     }
 }
Exemplo n.º 2
0
        public IHttpActionResult Get(int id)
        {
            List <CatalogoModel> estatusList = catalagoService.GetAll(c => c.CA_TABLA == "sax_estatus", null, c => c.SAX_CATALOGO_DETALLE).ToList();
            AreaOperativaModel   ar          = areaOperativaService.GetSingle(a => a.CA_ID_AREA == id);

            if (ar == null)
            {
                return(NotFound());
            }
            return(Ok(ar));
        }
Exemplo n.º 3
0
        public async Task <IHttpActionResult> GetRegistroControl([FromUri] ParametersRegistroControl parms)
        {
            try
            {
                IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

                var userArea    = usuarioAreaService.GetAll(d => d.US_ID_USUARIO == user.Id && d.UA_ESTATUS == 1, null, includes: c => c.AspNetUsers).ToList();
                var userAreacod = new List <AreaOperativaModel>();
                foreach (var item in userArea)
                {
                    userAreacod.Add(areaOperativaService.GetSingle(d => d.CA_ID_AREA == item.CA_ID_AREA));
                }

                //var rgcont = GetRegistroControlFiltro(parms);


                List <ReporteRegistroControlPartialModel> RegistroControl = GetRegistroControlFiltro(parms);

                var retorno = new List <ReporteRegistroControlPartialModel>();

                foreach (var a in RegistroControl)
                {
                    foreach (var b in userAreacod)
                    {
                        if (a.AreaId == b.CA_ID_AREA)
                        {
                            retorno.Add(a);
                        }
                    }
                }

                var ListRetorno = retorno.Select(c => new
                {
                    Supervisor      = c.Supervisor,
                    NombreOperacion = c.NombreOperacion,
                    Lote            = c.Lote,
                    Capturador      = c.Capturador,
                    TotalRegistro   = c.TotalRegistro,
                    TotalDebito     = c.TotalDebito.ToString("N2"),
                    TotalCredito    = c.TotalCredito.ToString("N2"),
                    Total           = c.Total.ToString("N2"),
                    Status          = c.Status,
                    FechaCreacion   = c.FechaCreacion,
                    HoraCreacion    = c.HoraCreacion
                });

                if (ListRetorno != null)
                {
                    return(Ok(ListRetorno));
                }
                return(NotFound());
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
        public IHttpActionResult GetRegistroControlPorConciliar([FromUri] PagingRegistroControlModel pagingparametermodel)
        {
            var estatusList      = catalagoService.GetAll(c => c.CA_TABLA == "sax_estatus_carga", null, c => c.SAX_CATALOGO_DETALLE).FirstOrDefault();
            var ltsTipoOperacion = catalagoService.GetAll(c => c.CA_TABLA == "sax_tipo_operacion", null, c => c.SAX_CATALOGO_DETALLE).FirstOrDefault();
            int porConciliar     = Convert.ToInt16(BusinessEnumerations.EstatusCarga.POR_CONCILIAR);
            int manual           = Convert.ToInt16(BusinessEnumerations.TipoOperacion.CAPTURA_MANUAL);
            var userId           = User.Identity.GetUserId();
            var userArea         = usuarioAreaService.GetSingle(d => d.US_ID_USUARIO == userId);
            var userAreacod      = areaOperativaService.GetSingle(d => d.CA_ID_AREA == userArea.CA_ID_AREA);
            var source           = service.Query(c => c.RC_ESTATUS_LOTE == porConciliar &&
                                                 (pagingparametermodel.lote == null? c.RC_COD_PARTIDA == c.RC_COD_PARTIDA: c.RC_COD_PARTIDA == (pagingparametermodel.lote.Trim())) &&
                                                 (pagingparametermodel.idCapturador == null ? c.RC_USUARIO_CREACION == c.RC_USUARIO_CREACION : c.RC_USUARIO_CREACION == pagingparametermodel.idCapturador)).OrderBy(c => c.RC_REGISTRO_CONTROL);
            int count        = source.Count();
            int CurrentPage  = pagingparametermodel.pageNumber;
            int PageSize     = pagingparametermodel.pageSize;
            int TotalCount   = count;
            int TotalPages   = (int)Math.Ceiling(count / (double)PageSize);
            var items        = source.Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList();
            var previousPage = CurrentPage > 1 ? "Yes" : "No";
            var nextPage     = CurrentPage < TotalPages ? "Yes" : "No";
            var listItem     = items.Select(x => new
            {
                RC_REGISTRO_CONTROL = x.RC_REGISTRO_CONTROL,
                RC_COD_OPERACION    = GetNameTipoOperacion(x.RC_COD_OPERACION, ref ltsTipoOperacion),
                RC_COD_PARTIDA      = x.RC_COD_PARTIDA,
                RC_ARCHIVO          = x.RC_ARCHIVO,
                RC_TOTAL_REGISTRO   = x.RC_TOTAL_REGISTRO,
                RC_TOTAL_DEBITO     = x.RC_TOTAL_DEBITO,
                RC_TOTAL_CREDITO    = x.RC_TOTAL_CREDITO,
                RC_TOTAL            = x.RC_TOTAL,
                COD_ESTATUS_LOTE    = x.RC_ESTATUS_LOTE,
                RC_ESTATUS_LOTE     = GetStatusRegistroControl(x.RC_ESTATUS_LOTE, estatusList),
                RC_FECHA_CREACION   = x.RC_FECHA_CREACION != null ? x.RC_FECHA_CREACION.ToString("d/M/yyyy") : string.Empty,
                RC_HORA_CREACION    = x.RC_FECHA_CREACION != null ? x.RC_FECHA_CREACION.ToString("hh:mm:tt") : string.Empty,
                RC_COD_USUARIO      = UserName(x.RC_USUARIO_MOD)
            });
            var paginationMetadata = new
            {
                totalCount  = TotalCount,
                pageSize    = PageSize,
                currentPage = CurrentPage,
                totalPages  = TotalPages,
                previousPage,
                nextPage,
                data = listItem
            };

            return(Ok(paginationMetadata));
        }
Exemplo n.º 5
0
        //public HttpResponseMessage GetReporteExcelSaldoContable([FromUri]ParametersSaldoContable parms)
        public async Task <HttpResponseMessage> GetReporteExcelSaldoContable([FromUri] ParametersSaldoContable parms)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest);
            IdentityUser        user     = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            var userArea    = usuarioAreaService.GetAll(d => d.US_ID_USUARIO == user.Id && d.UA_ESTATUS == 1, null, includes: c => c.AspNetUsers).ToList();
            var userAreacod = new List <AreaOperativaModel>();

            foreach (var item in userArea)
            {
                userAreacod.Add(areaOperativaService.GetSingle(d => d.CA_ID_AREA == item.CA_ID_AREA));
            }

            List <ReporteSaldoContablePartialModel> Lista = GetSaldoContableFiltro(parms, user);

            MemoryStream    memoryStream = new MemoryStream();
            List <string[]> header       = new List <string[]>();

            header.Add(new string[] { "A" });
            header.Add(new string[] { "B" });
            header.Add(new string[] { "C" });
            header.Add(new string[] { "D" });
            header.Add(new string[] { "E" });
            byte[] fileExcell    = reportExcelService.CreateReportBinary <ReporteSaldoContablePartialModel>(header, Lista, "Excel1");
            var    contentLength = fileExcell.Length;

            var statuscode = HttpStatusCode.OK;

            response         = Request.CreateResponse(statuscode);
            response.Content = new StreamContent(new MemoryStream(fileExcell));
            response.Content.Headers.ContentType   = new MediaTypeHeaderValue("application/octet-stream");
            response.Content.Headers.ContentLength = contentLength;
            ContentDispositionHeaderValue contentDisposition = null;

            if (ContentDispositionHeaderValue.TryParse("inline; filename=" + "document" + ".xlsx", out contentDisposition))
            {
                response.Content.Headers.ContentDisposition = contentDisposition;
            }
            return(response);
        }
Exemplo n.º 6
0
        public RegistroControlContent CreateSinglePartidas(RegistroControlModel control, PartidaManualModel partida, int tipoOperacion)
        {
            int    counter       = 1;
            string referencia    = partida.PA_REFERENCIA;
            string conceptoCosto = partida.PA_CONCEPTO_COSTO;

            partida.PA_CONCEPTO_COSTO = string.Empty;
            partida.PA_REFERENCIA     = string.Empty;
            DateTime                   todays          = DateTime.Now.Date;
            var                        counterRecord   = base.Count(c => DbFunctions.TruncateTime(c.RC_FECHA_CREACION) == todays);
            string                     dateFormat      = "yyyyMMdd";
            var                        model           = new List <SAX_PARTIDAS>();
            var                        registroContext = new RegistroControlContent();
            List <PartidasModel>       list            = new List <PartidasModel>();
            PartidasContent            partidas        = new PartidasContent();
            List <MessageErrorPartida> listError       = new List <MessageErrorPartida>();
            var                        empresaUsuario  = empresaUsuarioService.Query(x => x.US_ID_USUARIO == control.RC_COD_USUARIO).Select(x => new UsuarioEmpresaModel
            {
                UE_ID_USUARIO_EMPRESA = x.UE_ID_USUARIO_EMPRESA,
                US_ID_USUARIO         = x.US_ID_USUARIO,
                CE_ID_EMPRESA         = x.CE_ID_EMPRESA,
                UE_ESTATUS            = x.UE_ESTATUS,
                UE_FECHA_CREACION     = x.UE_FECHA_CREACION,
                UE_USUARIO_CREACION   = x.UE_USUARIO_CREACION,
                UE_FECHA_MOD          = x.UE_FECHA_MOD,
                UE_USUARIO_MOD        = x.UE_USUARIO_MOD
            }).ToList();

            var centroCostos = centroCostoService.GetAllFlatten <CentroCostoModel>();
            //var conceptoCostos = conceptoCostoService.GetAllFlatten<ConceptoCostoModel>();
            List <ConceptoCostoModel> conceptoCostos = conceptoCostoService.Query(x => x.CC_ID_CONCEPTO_COSTO == x.CC_ID_CONCEPTO_COSTO).Select(y => new ConceptoCostoModel
            {
                CC_ID_CONCEPTO_COSTO = y.CC_ID_CONCEPTO_COSTO,
                CE_ID_EMPRESA        = y.CE_ID_EMPRESA,
                CC_NUM_CONCEPTO      = y.CC_NUM_CONCEPTO,
                CC_CUENTA_MAYOR      = y.CC_CUENTA_MAYOR,
                CC_ESTATUS           = y.CC_ESTATUS
            }).ToList();
            //var cuentas = ctaService.GetAllFlatten<CuentaContableModel>();
            List <CuentaContableModel> cuentas = ctaService.Query(x => x.CO_ID_CUENTA_CONTABLE == x.CO_ID_CUENTA_CONTABLE).Select(y => new CuentaContableModel
            {
                CO_ID_CUENTA_CONTABLE  = y.CO_ID_CUENTA_CONTABLE,
                CE_ID_EMPRESA          = y.CE_ID_EMPRESA,
                CO_CUENTA_CONTABLE     = y.CO_CUENTA_CONTABLE,
                CO_COD_AUXILIAR        = y.CO_COD_AUXILIAR,
                CO_NUM_AUXILIAR        = y.CO_NUM_AUXILIAR,
                CA_ID_AREA             = y.ca_id_area,
                CO_COD_NATURALEZA      = y.CO_COD_NATURALEZA,
                CO_COD_CONCILIA        = y.CO_COD_CONCILIA,
                CO_NOM_CUENTA_CONTRA   = y.CO_NOM_CUENTA_CONTRA,
                CO_CTA_CONTABLE_CONTRA = y.CO_CTA_CONTABLE_CONTRA,
                CO_ESTATUS             = y.CO_ESTATUS
            }).ToList();
            var empresa                        = empresaService.GetAllFlatten <EmpresaModel>();
            var empresaAreaCentro              = empresaAreaCentroCostoSrv.GetAll();
            var empresaCentro                  = empresaCentroSrv.GetAll();
            List <MonedaModel>  lstMoneda      = monedaService.GetAllFlatten <MonedaModel>();
            CuentaContableModel cuenta_debito  = cuentas.Where(x => x.CO_ID_CUENTA_CONTABLE == partida.EV_CUENTA_DEBITO).FirstOrDefault();
            CuentaContableModel cuenta_credito = cuentas.Where(x => x.CO_ID_CUENTA_CONTABLE == partida.EV_CUENTA_CREDITO).FirstOrDefault();

            var param = paramService.GetSingle();

            DateTime fechaOperativa = this.GetFechaProceso();
            string   codeOperacion  = string.Empty;

            if (tipoOperacion == Convert.ToInt16(BusinessEnumerations.TipoOperacion.CARGA_INICIAL))
            {
                codeOperacion = "I";
            }
            else if (tipoOperacion == Convert.ToInt16(BusinessEnumerations.TipoOperacion.CARGA_MASIVA))
            {
                codeOperacion = "D";
            }
            else if (tipoOperacion == Convert.ToInt16(BusinessEnumerations.TipoOperacion.CAPTURA_MANUAL))
            {
                codeOperacion = "M";
            }


            control.CA_ID_AREA          = control.CA_ID_AREA;
            control.RC_COD_EVENTO       = partida.PA_EVENTO;
            control.EV_COD_EVENTO       = Convert.ToInt16(partida.PA_EVENTO);
            control.RC_COD_OPERACION    = tipoOperacion;
            control.RC_COD_PARTIDA      = fechaOperativa.ToString(dateFormat) + codeOperacion + ((counterRecord + 1).ToString("00000"));
            control.RC_FECHA_APROBACION = null;
            control.RC_FECHA_MOD        = null;
            control.RC_USUARIO_CREACION = control.RC_COD_USUARIO;
            control.RC_ESTATUS_LOTE     = Convert.ToInt16(BusinessEnumerations.EstatusCarga.POR_APROBAR);
            var partidaDebito = partida.CustomMapIgnoreICollection <PartidaManualModel, PartidasModel>();

            if (cuenta_debito != null && !string.IsNullOrEmpty(cuenta_debito.CO_CUENTA_CONTABLE))
            {
                partidaDebito.PA_CTA_CONTABLE = cuenta_debito.CO_CUENTA_CONTABLE.Trim() + cuenta_debito.CO_COD_AUXILIAR.Trim() + cuenta_debito.CO_NUM_AUXILIAR.Trim();
                if (cuenta_debito.CO_COD_CONCILIA.Equals("1"))
                {
                    partidaDebito.PA_REFERENCIA = partida.REFERENCIA_CUENTA_DEBITO;
                }
            }

            if (cuenta_debito.CO_CUENTA_CONTABLE.Trim().Substring(0, 2).Equals("51") || cuenta_debito.CO_CUENTA_CONTABLE.Trim().Substring(0, 2).Equals("52") || cuenta_debito.CO_CUENTA_CONTABLE.Trim().Substring(0, 2).Equals("31") || cuenta_debito.CO_CUENTA_CONTABLE.Trim().Substring(0, 2).Equals("32"))
            {
                partidaDebito.PA_CONCEPTO_COSTO = conceptoCosto;
            }
            partidaDebito.PA_CENTRO_COSTO     = partida.PA_CENTRO_COSTO;
            partidaDebito.PA_FECHA_CARGA      = fechaOperativa.Date;
            partidaDebito.PA_FECHA_TRX        = fechaOperativa.Date;
            partidaDebito.PA_USUARIO_MOD      = null;
            partidaDebito.PA_USUARIO_APROB    = null;
            partidaDebito.PA_FECHA_MOD        = null;
            partidaDebito.PA_FECHA_APROB      = null;
            partidaDebito.PA_FECHA_CREACION   = DateTime.Now;
            partidaDebito.PA_FECHA_CONCILIA   = null;
            partidaDebito.PA_FECHA_ANULACION  = null;
            partidaDebito.PA_USUARIO_CREACION = control.RC_COD_USUARIO;
            var credito = (partida.PA_IMPORTE * -1);
            var debito  = partida.PA_IMPORTE;

            partidaDebito.PA_STATUS_PARTIDA = Convert.ToInt16(BusinessEnumerations.EstatusCarga.POR_APROBAR);
            partidaDebito.PA_IMPORTE        = debito;
            partidaDebito.PA_TIPO_CONCILIA  = 0;
            partidaDebito.PA_CONTADOR       = 1;
            list.Add(partidaDebito);

            var partidaCredito = partida.CustomMapIgnoreICollection <PartidaManualModel, PartidasModel>();

            if (cuenta_credito != null && !string.IsNullOrEmpty(cuenta_credito.CO_CUENTA_CONTABLE))
            {
                partidaCredito.PA_CTA_CONTABLE = cuenta_credito.CO_CUENTA_CONTABLE.Trim() + cuenta_credito.CO_COD_AUXILIAR.Trim() + cuenta_credito.CO_NUM_AUXILIAR.Trim();
                if (cuenta_credito.CO_COD_CONCILIA.Equals("1"))
                {
                    partidaCredito.PA_REFERENCIA = partida.REFERENCIA_CUENTA_CREDITO;
                }
            }
            if (cuenta_credito.CO_CUENTA_CONTABLE.Trim().Substring(0, 2).Equals("51") || cuenta_credito.CO_CUENTA_CONTABLE.Trim().Substring(0, 2).Equals("52") || cuenta_credito.CO_CUENTA_CONTABLE.Trim().Substring(0, 2).Equals("31") || cuenta_credito.CO_CUENTA_CONTABLE.Trim().Substring(0, 2).Equals("32"))
            {
                partidaCredito.PA_CONCEPTO_COSTO = conceptoCosto;
            }
            partidaCredito.PA_FECHA_CARGA      = fechaOperativa.Date;
            partidaCredito.PA_FECHA_TRX        = fechaOperativa.Date;
            partidaCredito.PA_CENTRO_COSTO     = partida.CENTRO_COSTO_CREDITO;
            partidaCredito.PA_FECHA_MOD        = null;
            partidaCredito.PA_FECHA_APROB      = null;
            partidaCredito.PA_FECHA_CONCILIA   = null;
            partidaCredito.PA_FECHA_ANULACION  = null;
            partidaCredito.PA_USUARIO_MOD      = null;
            partidaCredito.PA_USUARIO_APROB    = null;
            partidaCredito.PA_FECHA_CREACION   = DateTime.Now;
            partidaCredito.PA_USUARIO_CREACION = control.RC_COD_USUARIO;
            partidaCredito.PA_STATUS_PARTIDA   = Convert.ToInt16(BusinessEnumerations.EstatusCarga.POR_APROBAR);
            partidaCredito.PA_TIPO_CONCILIA    = 0;
            partidaCredito.PA_IMPORTE          = credito;
            partidaCredito.PA_CONTADOR         = 2;

            list.Add(partidaCredito);

            DateTime today          = DateTime.Now;
            var      counterRecords = partidaService.Count(c => c.PA_FECHA_CARGA.Year == today.Year && c.PA_FECHA_CARGA.Month == today.Month && c.PA_FECHA_CARGA.Day == today.Day);

            control.RC_TOTAL_REGISTRO   = list.Count;
            control.RC_USUARIO_CREACION = control.RC_USUARIO_CREACION;

            control.RC_TOTAL_CREDITO = credito;
            control.RC_TOTAL_DEBITO  = debito;
            control.RC_TOTAL         = credito + debito;

            control.RC_FECHA_CREACION = DateTime.Now;

            control.RC_FECHA_PROCESO = partida.PA_FECHA_TRX;


            var mensaje = string.Empty;

            decimal            montoConsolidado   = 0;
            UsuarioAreaService usuarioAreaService = new UsuarioAreaService();
            var cuenta = string.Empty;

            registroService = registroService ?? new RegistroControlService();
            var consolidatedReference = partidaService.getConsolidaReferencias(list);
            int codAreaGenerica       = Convert.ToInt16(WebConfigurationManager.AppSettings["areaOperativaGenerica"]);
            var areaGenerica          = areaOperativaService.GetSingle(x => x.CA_COD_AREA == codAreaGenerica);

            foreach (var iteminner in list)
            {
                counter++;
                String PA_REFERENCIA             = string.Empty;
                CuentaContableModel singleCuenta = null;
                int rechazado  = Convert.ToInt16(BusinessEnumerations.EstatusCarga.RECHAZADO);
                int conciliaSI = Convert.ToInt16(BusinessEnumerations.Concilia.SI);
                try
                {
                    var referenciaEmbedded = iteminner.PA_REFERENCIA;
                    if (string.IsNullOrEmpty(iteminner.PA_CTA_CONTABLE))
                    {
                        mensaje = $"La cuenta contable no puede estar en blanco.";
                        throw new CuentaContableVaciaException();
                    }
                    else
                    {
                        iteminner.PA_CTA_CONTABLE = iteminner.PA_CTA_CONTABLE.Trim();
                        if (string.IsNullOrEmpty(iteminner.PA_CTA_CONTABLE))
                        {
                            mensaje = $"La cuenta contable no puede estar en blanco.";
                            throw new CuentaContableException();
                        }
                    }
                    cuenta = iteminner.PA_CTA_CONTABLE.Trim().ToUpper();
                    iteminner.PA_COD_EMPRESA = iteminner.PA_COD_EMPRESA == null ? string.Empty : iteminner.PA_COD_EMPRESA;
                    var importe       = iteminner.PA_IMPORTE;
                    var empresaSingle = empresa.FirstOrDefault(x => x.CE_COD_EMPRESA.Trim() == iteminner.PA_COD_EMPRESA.Trim());
                    if (empresaSingle == null)
                    {
                        throw new EmpresaException($"La empresa {iteminner.PA_COD_EMPRESA} no existe en el sistema.");
                    }
                    singleCuenta = cuentas.FirstOrDefault(c => (c.CO_CUENTA_CONTABLE.Trim().ToUpper() + c.CO_COD_AUXILIAR.Trim().ToUpper() + c.CO_NUM_AUXILIAR.Trim().ToUpper()) == cuenta && (c.CA_ID_AREA == control.CA_ID_AREA || c.CA_ID_AREA == areaGenerica.CA_ID_AREA) && c.CE_ID_EMPRESA == empresaSingle.CE_ID_EMPRESA);
                    if (singleCuenta == null)
                    {
                        throw new CuentaContableAreaException($"La cuenta contable {cuenta} no existe en el sistema. Verificar cuenta contable para  empresa y el área indicada.");
                    }
                    var     fechaCarga = iteminner.PA_FECHA_CARGA;
                    decimal monto      = 0;
                    int     tipo_error = 0;
                    if (singleCuenta.CO_COD_CONCILIA != null && singleCuenta.CO_COD_CONCILIA.Equals("1"))
                    {
                        if (string.IsNullOrEmpty(singleCuenta.CO_COD_NATURALEZA))
                        {
                            throw new CodNaturalezaException("La cuenta contable conciliable y no tiene definida naturaleza dentro del catálogo de cuentas.");
                        }
                        if (string.IsNullOrEmpty(singleCuenta.CO_COD_CONCILIA))
                        {
                            throw new CodNaturalezaException("La cuenta contable no tiene definida estatus de conciliación dentro del catálogo de cuentas.");
                        }
                        if (singleCuenta.CO_COD_NATURALEZA.Equals("D") && !String.IsNullOrEmpty(referenciaEmbedded) /*&& importe > 0*/)
                        {
                            if (String.IsNullOrEmpty(referenciaEmbedded))
                            {
                                mensaje = $"La referencia es requerida, cuenta de naturaleza débito con importe negativo. {referenciaEmbedded}";
                                throw new Exception();
                            }
                            var refSummary = consolidatedReference.Where(c => c.Referencia == referenciaEmbedded).FirstOrDefault();
                            montoConsolidado = refSummary == null ? 0 : refSummary.Monto;
                            var referenciaExiste = partidaService.Query(x => x.PA_COD_EMPRESA == iteminner.PA_COD_EMPRESA &&
                                                                        x.PA_COD_MONEDA == iteminner.PA_COD_MONEDA &&
                                                                        x.PA_REFERENCIA == iteminner.PA_REFERENCIA &&
                                                                        x.PA_CTA_CONTABLE.Trim() == iteminner.PA_CTA_CONTABLE.Trim() &&
                                                                        x.PA_CENTRO_COSTO == iteminner.PA_CENTRO_COSTO &&
                                                                        x.PA_STATUS_PARTIDA != rechazado &&
                                                                        x.PA_ESTADO_CONCILIA != conciliaSI);
                            if (referenciaExiste != null && referenciaExiste.Count() == 0)
                            {
                                mensaje = $"La referencia indicada ({referenciaEmbedded}) no coincide en el sistema para la empresa, moneda, cuenta, centro de costo indicado en la partida a cargar.";
                                throw new Exception();
                            }
                            iteminner.PA_ORIGEN_REFERENCIA = Convert.ToInt16(BusinessEnumerations.TipoReferencia.MANUAL);
                        }

                        else if (singleCuenta.CO_COD_NATURALEZA.Equals("C") && !String.IsNullOrEmpty(referenciaEmbedded) /*&& importe > 0 */)
                        {
                            if (String.IsNullOrEmpty(referenciaEmbedded))
                            {
                                mensaje = $"La referencia es requerida, cuenta de naturaleza crédito con importe positivo. {referenciaEmbedded}";
                                throw new Exception();
                            }
                            var refSummary = consolidatedReference.Where(c => c.Referencia == referenciaEmbedded).FirstOrDefault();
                            montoConsolidado = refSummary == null ? 0 : refSummary.Monto;

                            var referenciaExiste = partidaService.Query(x => x.PA_COD_EMPRESA == iteminner.PA_COD_EMPRESA &&
                                                                        x.PA_COD_MONEDA == iteminner.PA_COD_MONEDA &&
                                                                        x.PA_REFERENCIA == iteminner.PA_REFERENCIA &&
                                                                        x.PA_CTA_CONTABLE.Trim() == iteminner.PA_CTA_CONTABLE.Trim() &&
                                                                        x.PA_CENTRO_COSTO == iteminner.PA_CENTRO_COSTO &&
                                                                        x.PA_STATUS_PARTIDA != rechazado &&
                                                                        x.PA_ESTADO_CONCILIA != conciliaSI);
                            if (referenciaExiste != null && referenciaExiste.Count() == 0)
                            {
                                mensaje = $"La referencia indicada ({referenciaEmbedded}) no coincide en el sistema para la empresa, moneda, cuenta, centro de costo indicado en la partida a cargar.";
                                throw new Exception();
                            }
                            iteminner.PA_ORIGEN_REFERENCIA = Convert.ToInt16(BusinessEnumerations.TipoReferencia.MANUAL);
                        }
                        else if ((singleCuenta.CO_COD_NATURALEZA.Equals("C") || singleCuenta.CO_COD_NATURALEZA.Equals("D")) && String.IsNullOrEmpty(referenciaEmbedded))
                        {
                            iteminner.PA_REFERENCIA        = "";
                            iteminner.PA_ORIGEN_REFERENCIA = Convert.ToInt16(BusinessEnumerations.TipoReferencia.AUTOMATICO);
                        }
                        else
                        {
                            mensaje = "No se cumple con una referencia valida por naturaleza ni importe.";
                            throw new Exception();
                        }
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(iteminner.PA_REFERENCIA))
                        {
                            mensaje = $"La cuenta no es conciliable, por lo tanto no puede tener referencia.";
                            throw new Exception();
                        }
                        //La cuenta no es conciliable por lo tanto no es necesario colocarte un tipo de conciliacion
                        //if (string.IsNullOrEmpty(referenciaEmbedded))
                        //    referenciaEmbedded = "NOCONCILIA";
                        //PA_REFERENCIA = referenciaEmbedded;
                        //iteminner.PA_ORIGEN_REFERENCIA = Convert.ToInt16(BusinessEnumerations.TipoReferencia.MANUAL);
                        iteminner.PA_ORIGEN_REFERENCIA = null;
                    }
                }
                catch (Exception e)
                {
                    if (e is CuentaContableException)
                    {
                        listError.Add(new MessageErrorPartida()
                        {
                            Linea = counter, Mensaje = mensaje, Columna = "Cuenta Contable"
                        });
                        mensaje = string.Empty;
                    }

                    if (e is CodNaturalezaException)
                    {
                        mensaje = $"Validar naturaleza de cuenta contable {cuenta}.";
                        listError.Add(new MessageErrorPartida()
                        {
                            Linea = counter, Mensaje = mensaje, Columna = "Referencia"
                        });
                        mensaje = string.Empty;
                    }
                    if (e is CodConciliaException)
                    {
                        mensaje = $"Validar conciliación de cuenta contable {cuenta}.";
                        listError.Add(new MessageErrorPartida()
                        {
                            Linea = counter, Mensaje = mensaje, Columna = "Referencia"
                        });
                        mensaje = string.Empty;
                    }
                    if (e is CuentaContableVaciaException)
                    {
                        //Si la cuenta contable viene vacia o con formato incorrecto (Numero y caracteres especiales)
                        //El error se manejo en la lectura del campo
                    }
                    if (singleCuenta == null)
                    {
                        //mensaje = $"No se puede encontrar la cuenta contable {cuenta}.";
                        //listError.Add(new MessageErrorPartida() { Linea = counter, Mensaje = mensaje, Columna = "PA_REFERENCIA" });
                        mensaje = string.Empty;
                    }
                    if (e is CuentaContableAreaException)
                    {
                        listError.Add(new MessageErrorPartida()
                        {
                            Linea = counter, Mensaje = e.Message, Columna = "Cuenta contable"
                        });
                        mensaje = string.Empty;
                    }
                    if (e is EmpresaException)
                    {
                        listError.Add(new MessageErrorPartida()
                        {
                            Linea = counter, Mensaje = e.Message, Columna = "Empresa"
                        });
                        mensaje = string.Empty;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(mensaje))
                        {
                            listError.Add(new MessageErrorPartida()
                            {
                                Linea = counter, Mensaje = mensaje, Columna = "Referencia"
                            });
                        }
                    }
                }
                fileProvider.ValidaReglasCarga(counter, ref list, ref listError, iteminner, Convert.ToInt16(BusinessEnumerations.TipoOperacion.CAPTURA_MANUAL), centroCostos, conceptoCostos, cuentas, empresa, list, lstMoneda, fechaOperativa, empresaAreaCentro, partida.CA_ID_AREA, empresaCentro, empresaUsuario);
            }
            //Validaciones globales por Saldos Balanceados por Moneda y Empresa
            var  monedaError       = new List <EmpresaMonedaValidationModel>();
            bool validaSaldoMoneda = partidaService.isSaldoValidoMonedaEmpresa(list, ref monedaError);

            if (!validaSaldoMoneda)
            {
                monedaError.ForEach(x =>
                {
                    listError.Add(new MessageErrorPartida {
                        Columna = "global", Linea = counter++, Mensaje = $"Partida desbalanceada en la empresa: {x.DescripcionEmpresa} y moneda {x.DescripcionMoneda}"
                    });
                });
            }

            registroContext.ListPartidas = list;
            registroContext.ListError    = listError;
            control.SAX_PARTIDAS         = list;

            if (listError.Count == 0)
            {
                var modelRegistroTo = Mapper.Map <RegistroControlModel, SAX_REGISTRO_CONTROL>(control);
                var modelPart       = Mapper.Map <List <PartidasModel>, List <SAX_PARTIDAS> >(list);
                modelRegistroTo.SAX_PARTIDAS = modelPart;
                var registro    = registroControl.LoadFileData(modelRegistroTo);
                var returnmodel = Mapper.Map <SAX_REGISTRO_CONTROL, RegistroControlModel>(registro);
            }
            return(registroContext);
        }
        public async Task <IHttpActionResult> GetPartidasAprobadas([FromUri] ParametrosPartidasApr parms)
        {
            try
            {
                var viPaApro = new List <vi_PartidasApr>();

                var PaConc = new List <vi_PartidasApr_Conciliadas>();

                var itemList = new List <ReportePartidasAprModel>();

                var PartidasNat = new List <vi_PartidasApr_Conciliadas>();

                List <ComprobanteModel> model = new List <ComprobanteModel>();
                int tipoComp           = Convert.ToInt16(BusinessEnumerations.TipoOperacion.CONCILIACION);
                int TipoConcMan        = Convert.ToInt16(BusinessEnumerations.TipoOperacion.CONCILIACION_MANUAL);
                int EstatusConc        = Convert.ToInt16(BusinessEnumerations.EstatusCarga.CONCILIADO);
                int ParSConciliado     = Convert.ToInt16(BusinessEnumerations.Concilia.SI);
                int ParTipoConPar      = Convert.ToInt16(BusinessEnumerations.TipoConciliacion.PARCIAL);
                int EstatusPorAproAnul = Convert.ToInt16(BusinessEnumerations.EstatusCarga.POR_ANULAR);
                //int EstatusAn = Convert.ToInt16(BusinessEnumerations.EstatusCarga.ANULADO);

                switch (parms.TipoReporte)
                {
                case 0:
                    viPaApro = PartidasAp(parms);
                    viPaApro.ForEach(c =>
                    {
                        itemList.Add(Extension.CustomMapIgnoreICollection <vi_PartidasApr, ReportePartidasAprModel>(c));
                    });
                    break;

                case 1:
                    PaConc = PartidasConciliadas(parms);
                    PaConc.ToList().ForEach(c =>
                    {
                        itemList.Add(Extension.CustomMapIgnoreICollection <vi_PartidasApr_Conciliadas, ReportePartidasAprModel>(c));
                    });

                    break;

                case 2:     // ParcialmenteConciliadas
                    PaConc = PartidasParcConciliadas(parms);
                    PaConc.ToList().ForEach(c =>
                    {
                        itemList.Add(Extension.CustomMapIgnoreICollection <vi_PartidasApr_Conciliadas, ReportePartidasAprModel>(c));
                    });
                    break;

                case 3:     // No Conciliadas
                    PaConc = PartidasPendConciliar(parms);
                    PaConc.ToList().ForEach(c =>
                    {
                        itemList.Add(Extension.CustomMapIgnoreICollection <vi_PartidasApr_Conciliadas, ReportePartidasAprModel>(c));
                    });
                    break;

                case 4:     // Anuladas
                    PaConc = PartidasAnuladas(parms);
                    PaConc.ToList().ForEach(c =>
                    {
                        itemList.Add(Extension.CustomMapIgnoreICollection <vi_PartidasApr_Conciliadas, ReportePartidasAprModel>(c));
                    });
                    break;
                }



                int count = itemList.Count();
                //viPaApro.Count();

                if (count > 0)
                {
                    IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());


                    model = comprobanteService.GetAll(c => (c.TC_COD_OPERACION == tipoComp || c.TC_COD_OPERACION == TipoConcMan) && (c.TC_ESTATUS == EstatusConc || c.TC_ESTATUS == EstatusPorAproAnul), null, includes: c => c.AspNetUsers).ToList();

                    List <EventosModel> eventos = eventoServ.GetAll(c => c.EV_COD_EVENTO == c.EV_COD_EVENTO, null, includes: c => c.AspNetUsers).ToList();

                    int CurrentPage  = parms.pageNumber;
                    int PageSize     = parms.pageSize;
                    int TotalCount   = count;
                    int TotalPages   = (int)Math.Ceiling(count / (double)PageSize);
                    var previousPage = CurrentPage > 1 ? "Yes" : "No";
                    var nextPage     = CurrentPage < TotalPages ? "Yes" : "No";


                    var itemListxArea    = new List <ReportePartidasAprModel>();
                    var itemListxEmpresa = new List <ReportePartidasAprModel>();
                    var ListaSele        = new List <ReportePartidasAprModel>();
                    //var returnlist = new List<ReportePartidasAprModel>();

                    //var Par = parService.GetSingle();

                    //var FechaP = Par.PA_FECHA_PROCESO;

                    int OrigenAuto = Convert.ToInt16(BusinessEnumerations.TipoReferencia.AUTOMATICO);

                    var FechaCorte = parms.fechaCarga;

                    if (parms.IdEmpresa != null)
                    {
                        itemListxEmpresa = itemList.Where(x => x.PA_COD_EMPRESA == parms.IdEmpresa.ToString()).ToList();
                    }
                    else
                    {
                        List <UsuarioEmpresaModel> listUsuarioEmpresas = new List <UsuarioEmpresaModel>();
                        var listEmpresas = usuarioEmpresaService.GetAll(c => c.US_ID_USUARIO == user.Id, null, c => c.SAX_EMPRESA);
                        if (listEmpresas.Count > 0)
                        {
                            foreach (var emp in listEmpresas)
                            {
                                listUsuarioEmpresas.Add(emp);
                            }
                        }

                        foreach (var j in itemList)
                        {
                            if (listUsuarioEmpresas.Count(x => x.CE_ID_EMPRESA.ToString() == j.PA_COD_EMPRESA) > 0)
                            {
                                itemListxEmpresa.Add(j);
                            }
                        }
                    }


                    if (parms.codArea == null)
                    {
                        var userArea    = usuarioAreaService.GetAll(d => d.US_ID_USUARIO == user.Id && d.UA_ESTATUS == 1, null, includes: c => c.AspNetUsers).ToList();
                        var userAreacod = new List <AreaOperativaModel>();
                        foreach (var item in userArea)
                        {
                            userAreacod.Add(areaOperativaService.GetSingle(d => d.CA_ID_AREA == item.CA_ID_AREA));
                        }
                        userAreacod.Add(areaOperativaService.GetSingle(h => h.CA_NOMBRE.Contains("Generica")));

                        foreach (var b in itemListxEmpresa)
                        {
                            if (userAreacod.Count(v => v.CA_ID_AREA == b.CA_ID_AREA) > 0)
                            {
                                itemListxArea.Add(b);
                            }
                        }
                    }
                    else
                    {
                        itemListxArea = itemListxEmpresa.ToList();
                    }


                    foreach (var c in itemListxArea)
                    {
                        foreach (var j in model)
                        {
                            var compdetalle = j.SAX_COMPROBANTE_DETALLE.Where(v => v.PA_REGISTRO == c.PA_REGISTRO).ToList();
                            if (compdetalle.Count > 0)
                            {
                                c.ComprobanteConciliacion = j.TC_COD_COMPROBANTE;
                                c.Usuario_Conciliador     = j.TC_USUARIO_CREACION;
                                c.Aprobador_Conciliacion  = j.TC_USUARIO_APROBADOR;

                                //if (j.TC_ESTATUS == EstatusPorAproAnul.ToString())
                                //{
                                //    c.PA_USUARIO_ANULACION = "";
                                //    c.PA_FECHA_ANULACION = null;
                                //    c.PA_USUARIO_APROBADOR_ANULACION = "";
                                //}
                            }
                        }

                        if (c.EV_COD_EVENTO != null)
                        {
                            foreach (var ev in eventos)
                            {
                                var ListaEventos = eventos.Where(h => h.EV_COD_EVENTO == c.EV_COD_EVENTO).ToList();
                                if (ListaEventos.Count > 0)
                                {
                                    c.EventoDescripcion = ListaEventos.Select(b => b.EV_DESCRIPCION_EVENTO).SingleOrDefault();
                                }
                            }
                        }

                        if (c.PA_ESTADO_CONCILIA != ParSConciliado)
                        {
                            c.PA_DIAS_ANTIGUEDAD = Convert.ToInt32(parms.fechaCarga.Date.Subtract(c.PA_FECHA_TRX.Value.Date).TotalDays.ToString());

                            if (c.PA_ORIGEN_REFERENCIA == OrigenAuto)
                            {
                                if (c.PA_FECHA_ANULACION == null)
                                {
                                    var partidasConc = partApConcSrv.Query(s => s.PA_REFERENCIA.Length > 0 &&
                                                                           (s.PA_ESTADO_CONCILIA != ParSConciliado ||
                                                                            (s.PA_ESTADO_CONCILIA == ParSConciliado &&
                                                                             s.PA_TIPO_CONCILIA == ParTipoConPar)) &&
                                                                           s.PA_FECHA_ANULACION == null &&
                                                                           s.PA_REFERENCIA == c.PA_REFERENCIA &&
                                                                           s.PA_FECHA_CARGA <= parms.fechaCarga).ToList();
                                    var Referencias = from h in partidasConc
                                                      group h by h.PA_REFERENCIA into y
                                                      select new
                                    {
                                        referencia = y.Key,
                                        importe    = y.Sum(r => r.PA_IMPORTE)
                                    };
                                    if (Referencias.Count() > 0)
                                    {
                                        c.PA_IMPORTE_PENDIENTE = Referencias.SingleOrDefault(k => k.referencia == c.PA_REFERENCIA).importe;
                                    }
                                    //else
                                    //    c.PA_IMPORTE_PENDIENTE
                                }
                                else
                                //calcular importe de acuerdo a la naturaleza excuyendo las que estan en el mismo comprobante
                                {
                                    //var PartidasNat = new List<vi_PartidasApr_Conciliadas>();
                                    if (c.PA_IMPORTE > 0)

                                    {
                                        var PartidasxNat = partApConcSrv.Query(q => q.PA_CTA_CONTABLE == c.PA_CTA_CONTABLE && q.PA_COD_EMPRESA == c.PA_COD_EMPRESA &&
                                                                               q.PA_COD_MONEDA == c.PA_COD_MONEDA && q.PA_CENTRO_COSTO == c.PA_CENTRO_COSTO &&
                                                                               q.PA_FECHA_ANULACION == null &&
                                                                               ((q.PA_ESTADO_CONCILIA == ParSConciliado && q.PA_TIPO_CONCILIA == ParTipoConPar) ||
                                                                                q.PA_ESTADO_CONCILIA != ParSConciliado && q.PA_FECHA_CONCILIA == null) &&
                                                                               q.PA_IMPORTE > 0 &&
                                                                               q.PA_FECHA_CARGA <= parms.fechaCarga
                                                                               ).ToList();
                                        var Referencias = from h in PartidasxNat
                                                          group h by h.PA_REFERENCIA into y
                                                          select new
                                        {
                                            referencia = y.Key,
                                            importe    = y.Sum(r => r.PA_IMPORTE)
                                        };
                                        if (Referencias.Where(k => k.referencia == c.PA_REFERENCIA).Count() > 0)
                                        {
                                            c.PA_IMPORTE_PENDIENTE = c.PA_IMPORTE + Referencias.SingleOrDefault(k => k.referencia == c.PA_REFERENCIA).importe;
                                        }
                                        else
                                        {
                                            c.PA_IMPORTE_PENDIENTE = c.PA_IMPORTE;
                                        }
                                    }
                                    else
                                    {
                                        var PartidasxNat = partApConcSrv.Query(q => q.PA_CTA_CONTABLE == c.PA_CTA_CONTABLE && q.PA_COD_EMPRESA == c.PA_COD_EMPRESA &&
                                                                               q.PA_COD_MONEDA == c.PA_COD_MONEDA && q.PA_CENTRO_COSTO == c.PA_CENTRO_COSTO &&
                                                                               q.PA_FECHA_ANULACION == null &&
                                                                               ((q.PA_ESTADO_CONCILIA == ParSConciliado && q.PA_TIPO_CONCILIA == ParTipoConPar) ||
                                                                                q.PA_ESTADO_CONCILIA != ParSConciliado && q.PA_FECHA_CONCILIA == null) &&
                                                                               q.PA_IMPORTE < 0 &&
                                                                               q.PA_FECHA_CARGA <= parms.fechaCarga
                                                                               ).ToList();
                                        var Referencias = from h in PartidasxNat
                                                          group h by h.PA_REFERENCIA into y
                                                          select new
                                        {
                                            referencia = y.Key,
                                            importe    = y.Sum(r => r.PA_IMPORTE)
                                        };
                                        if (Referencias.Where(k => k.referencia == c.PA_REFERENCIA).Count() > 0)
                                        {
                                            c.PA_IMPORTE_PENDIENTE = c.PA_IMPORTE + Referencias.FirstOrDefault(k => k.referencia == c.PA_REFERENCIA).importe;
                                        }

                                        else
                                        {
                                            c.PA_IMPORTE_PENDIENTE = c.PA_IMPORTE;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    ListaSele = itemListxArea.ToList();

                    if (parms.TipoReporte == 1)
                    {
                        ListaSele = ListaSele.Where(k => k.ComprobanteConciliacion != null).ToList();
                    }

                    if (parms.TipoReporte == 2)
                    {
                        ListaSele = ListaSele.Where(k => k.ComprobanteConciliacion == null).ToList();
                    }


                    var returnlist = ListaSele.Select(x => new
                    {
                        Empresa        = x.EmpresaDesc,
                        FechaCarga     = x.PA_FECHA_CARGA.Value.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture),
                        HoraCarga      = getHora(x.PA_HORA_CREACION),
                        FechaTrx       = x.PA_FECHA_TRX.Value.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture),
                        CuentaContable = x.PA_CTA_CONTABLE,
                        CentroCosto    = x.PA_CENTRO_COSTO,
                        Moneda         = x.PA_COD_MONEDA,
                        Importe        = x.PA_IMPORTE.ToString("N2"),
                        Referencia     = x.PA_REFERENCIA,
                        Explicacion    = x.PA_EXPLICACION,
                        PlanAccion     = x.PA_PLAN_ACCION,
                        ConceptoCosto  = x.PA_CONCEPTO_COSTO,
                        OrigendeAsignacionReferencia = GetNameCodigo(x.PA_ORIGEN_REFERENCIA.ToString(), "sax_tipo_referencia"), //
                        OrigenCarga         = GetNameCodigo(x.RC_COD_OPERACION.ToString(), "sax_tipo_operacion"),               //
                        UsuarioCarga        = x.PA_USUARIO_CREACION != null ? GetNameUser(x.PA_USUARIO_CREACION) : "",
                        UsuarioAprobador    = x.PA_USUARIO_APROB != null ? GetNameUser(x.PA_USUARIO_APROB) : "",                //x.UsuarioAprob_Nombre,
                        Evento              = string.IsNullOrEmpty(x.EV_COD_EVENTO.ToString()) ? "" : (x.EV_COD_EVENTO.ToString() + "-" + x.EventoDescripcion).ToString(),
                        AplicacionOrigen    = x.PA_APLIC_ORIGEN,
                        TipoConciliacion    = GetNameCodigo(x.PA_TIPO_CONCILIA.ToString(), "sax_tipo_conciliacion"), //
                        EstatusConciliacion = GetNameCodigo(x.PA_ESTADO_CONCILIA.ToString(), "sax_concilia"),        //
                        FechaConciliacion   = string.IsNullOrEmpty(x.PA_FECHA_CONCILIA.ToString()) ? "" : x.PA_FECHA_CONCILIA.Value.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture).ToString(),

                        DocumentodeCompensacion = string.IsNullOrEmpty(x.ComprobanteConciliacion) ? "": x.ComprobanteConciliacion,
                        UsuarioConciliador      = string.IsNullOrEmpty(x.Usuario_Conciliador) ? "": GetNameUser(x.Usuario_Conciliador),
                        AprobadorConciliacion   = string.IsNullOrEmpty(x.Aprobador_Conciliacion) ?  "": GetNameUser(x.Aprobador_Conciliacion),

                        ImportePendiente = x.PA_IMPORTE_PENDIENTE.ToString("N2"),

                        FechaAnulacion     = string.IsNullOrEmpty(x.PA_FECHA_ANULACION.ToString()) ? "" : x.PA_FECHA_ANULACION.Value.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture).ToString(),
                        UsuarioAnulacion   = string.IsNullOrEmpty(x.PA_USUARIO_ANULACION) ?"": GetNameUser(x.PA_USUARIO_ANULACION),
                        AprobadorAnulacion = string.IsNullOrEmpty(x.PA_USUARIO_APROBADOR_ANULACION) ? "": GetNameUser(x.PA_USUARIO_APROBADOR_ANULACION),
                        DiasAntigüedad     = x.PA_DIAS_ANTIGUEDAD,



                        Campo1  = string.IsNullOrEmpty(x.PA_CAMPO_1)?"": x.PA_CAMPO_1.ToString(),
                        Campo2  = string.IsNullOrEmpty(x.PA_CAMPO_2) ? "" : x.PA_CAMPO_2.ToString(),
                        Campo3  = string.IsNullOrEmpty(x.PA_CAMPO_3) ? "" : x.PA_CAMPO_3.ToString(),
                        Campo4  = string.IsNullOrEmpty(x.PA_CAMPO_4) ? "" : x.PA_CAMPO_4.ToString(),
                        Campo5  = string.IsNullOrEmpty(x.PA_CAMPO_5) ? "" : x.PA_CAMPO_5.ToString(),
                        Campo6  = string.IsNullOrEmpty(x.PA_CAMPO_6) ? "" : x.PA_CAMPO_6.ToString(),
                        Campo7  = string.IsNullOrEmpty(x.PA_CAMPO_7) ? "" : x.PA_CAMPO_7.ToString(),
                        Campo8  = string.IsNullOrEmpty(x.PA_CAMPO_8) ? "" : x.PA_CAMPO_8.ToString(),
                        Campo9  = string.IsNullOrEmpty(x.PA_CAMPO_9) ? "" : x.PA_CAMPO_9.ToString(),
                        Campo10 = string.IsNullOrEmpty(x.PA_CAMPO_10) ? "" : x.PA_CAMPO_10.ToString(),
                        Campo11 = string.IsNullOrEmpty(x.PA_CAMPO_11) ? "" : x.PA_CAMPO_11.ToString(),
                        Campo12 = string.IsNullOrEmpty(x.PA_CAMPO_12) ? "" : x.PA_CAMPO_12.ToString(),
                        Campo13 = string.IsNullOrEmpty(x.PA_CAMPO_13) ? "" : x.PA_CAMPO_13.ToString(),
                        Campo14 = string.IsNullOrEmpty(x.PA_CAMPO_14) ? "" : x.PA_CAMPO_14.ToString(),
                        Campo15 = string.IsNullOrEmpty(x.PA_CAMPO_15) ? "" : x.PA_CAMPO_15.ToString(),
                        Campo16 = string.IsNullOrEmpty(x.PA_CAMPO_16) ? "" : x.PA_CAMPO_16.ToString(),
                        Campo17 = string.IsNullOrEmpty(x.PA_CAMPO_17) ? "" : x.PA_CAMPO_17.ToString(),
                        Campo18 = string.IsNullOrEmpty(x.PA_CAMPO_18) ? "" : x.PA_CAMPO_18.ToString(),
                        Campo19 = string.IsNullOrEmpty(x.PA_CAMPO_19) ? "" : x.PA_CAMPO_19.ToString(),
                        Campo20 = string.IsNullOrEmpty(x.PA_CAMPO_20) ? "" : x.PA_CAMPO_20.ToString(),
                        Campo21 = string.IsNullOrEmpty(x.PA_CAMPO_21) ? "" : x.PA_CAMPO_21.ToString(),
                        Campo22 = string.IsNullOrEmpty(x.PA_CAMPO_22) ? "" : x.PA_CAMPO_22.ToString(),
                        Campo23 = string.IsNullOrEmpty(x.PA_CAMPO_23) ? "" : x.PA_CAMPO_23.ToString(),
                        Campo24 = string.IsNullOrEmpty(x.PA_CAMPO_24) ? "" : x.PA_CAMPO_24.ToString(),
                        Campo25 = string.IsNullOrEmpty(x.PA_CAMPO_25) ? "" : x.PA_CAMPO_25.ToString(),
                        Campo26 = string.IsNullOrEmpty(x.PA_CAMPO_26) ? "" : x.PA_CAMPO_26.ToString(),
                        Campo27 = string.IsNullOrEmpty(x.PA_CAMPO_27) ? "" : x.PA_CAMPO_27.ToString(),
                        Campo28 = string.IsNullOrEmpty(x.PA_CAMPO_28) ? "" : x.PA_CAMPO_28.ToString(),
                        Campo29 = string.IsNullOrEmpty(x.PA_CAMPO_29) ? "" : x.PA_CAMPO_29.ToString(),
                        Campo30 = string.IsNullOrEmpty(x.PA_CAMPO_30) ? "" : x.PA_CAMPO_30.ToString(),
                        Campo31 = string.IsNullOrEmpty(x.PA_CAMPO_31) ? "" : x.PA_CAMPO_31.ToString(),
                        Campo32 = string.IsNullOrEmpty(x.PA_CAMPO_32) ? "" : x.PA_CAMPO_32.ToString(),
                        Campo33 = string.IsNullOrEmpty(x.PA_CAMPO_33) ? "" : x.PA_CAMPO_33.ToString(),
                        Campo34 = string.IsNullOrEmpty(x.PA_CAMPO_34) ? "" : x.PA_CAMPO_34.ToString(),
                        Campo35 = string.IsNullOrEmpty(x.PA_CAMPO_35) ? "" : x.PA_CAMPO_35.ToString(),
                        Campo36 = string.IsNullOrEmpty(x.PA_CAMPO_36) ? "" : x.PA_CAMPO_36.ToString(),
                        Campo37 = string.IsNullOrEmpty(x.PA_CAMPO_37) ? "" : x.PA_CAMPO_37.ToString(),
                        Campo38 = string.IsNullOrEmpty(x.PA_CAMPO_38) ? "" : x.PA_CAMPO_38.ToString(),
                        Campo39 = string.IsNullOrEmpty(x.PA_CAMPO_39) ? "" : x.PA_CAMPO_39.ToString(),
                        Campo40 = string.IsNullOrEmpty(x.PA_CAMPO_40) ? "" : x.PA_CAMPO_40.ToString(),
                        Campo41 = string.IsNullOrEmpty(x.PA_CAMPO_41) ? "" : x.PA_CAMPO_41.ToString(),
                        Campo42 = string.IsNullOrEmpty(x.PA_CAMPO_42) ? "" : x.PA_CAMPO_42.ToString(),
                        Campo43 = string.IsNullOrEmpty(x.PA_CAMPO_43) ? "" : x.PA_CAMPO_43.ToString(),
                        Campo44 = string.IsNullOrEmpty(x.PA_CAMPO_44) ? "" : x.PA_CAMPO_44.ToString(),
                        Campo45 = string.IsNullOrEmpty(x.PA_CAMPO_45) ? "" : x.PA_CAMPO_45.ToString(),
                        Campo46 = string.IsNullOrEmpty(x.PA_CAMPO_46) ? "" : x.PA_CAMPO_46.ToString(),
                        Campo47 = string.IsNullOrEmpty(x.PA_CAMPO_47) ? "" : x.PA_CAMPO_47.ToString(),
                        Campo48 = string.IsNullOrEmpty(x.PA_CAMPO_48) ? "" : x.PA_CAMPO_48.ToString(),
                        Campo49 = string.IsNullOrEmpty(x.PA_CAMPO_49) ? "" : x.PA_CAMPO_49.ToString(),
                        Campo50 = string.IsNullOrEmpty(x.PA_CAMPO_50) ? "" : x.PA_CAMPO_50.ToString()
                    });
                    var paginationMetadata = new
                    {
                        totalCount  = TotalCount,
                        pageSize    = PageSize,
                        currentPage = CurrentPage,
                        totalPages  = TotalPages,
                        previousPage,
                        nextPage
                    };
                    HttpContext.Current.Response.Headers.Add("Paging-Headers", JsonConvert.SerializeObject(paginationMetadata));
                    return(Ok(returnlist));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }
        }