Exemple #1
0
        public async Task GeneraRecibo(long documento, string usuario)
        {
            CobGeneralCobranza generalCobranzas = await GetGeneralCobranzaPorDocumento(documento);

            // CobGeneralCobranzaDto generalCobranzasDtos = new CobGeneralCobranzaDto();
            CobAdjuntosCobranza Adjunto = new CobAdjuntosCobranza();

            // CobAdjuntosCobranza AdjuntoJpg = new CobAdjuntosCobranza();
            if (generalCobranzas != null)
            {
                ReciboDto recibo = await GeneraReciboDto(documento);

                Metadata geberaPdf = GeneraPdfRecibo(recibo, "_Consultado");
                if (geberaPdf.IsValid)
                {
                    var nombreArchivo = "RC_" + documento.ToString() + "_Consultado" + ".pdf";

                    await _cobAdjuntosCobranzaService.DeleteByNameFile(recibo.CobGeneralCobranzaDto.Documento, nombreArchivo);



                    //ADJUNTAMOS EL RC///////////////////////////////
                    Adjunto.Documento         = documento;
                    Adjunto.IdTipoDocumento   = 20;
                    Adjunto.NombreArchivo     = nombreArchivo;
                    Adjunto.Archivo           = null;
                    Adjunto.IdUsuarioCreacion = usuario;
                    Adjunto.FechaCreacion     = DateTime.Now;
                    Adjunto.Ruta = _paginationOptions.FolderDocumentation + "\\";
                    //CobAdjuntosCobranza cobranzaAdjunto = await _cobAdjuntosCobranzaService.Insert(Adjunto);
                    await _cobAdjuntosCobranzaService.Insert(Adjunto);
                }
            }
        }
Exemple #2
0
        public async Task <Metadata> ValidaUpdateCobranza(CobGeneralCobranza generalCobranza)
        {
            Metadata metadata = new Metadata
            {
                IsValid = true,
                Message = ""
            };
            CobGrabacionCobranzas cambiaRcRu = await _unitOfWork.GeneralCobranzaRepository.RCRUYaTieneCobranzaGrabada(generalCobranza.Documento);

            if (cambiaRcRu != null && generalCobranza.IdTipoTransaccion == "RET")
            {
                //throw new BusinessException("Este cliente ya tiene un RC abierto pendiente por enviar N° " + existenDocumentosPendientes.Documento.ToString() + ".Agregue la cobranza a este RC.Si es necesario grabar otro RC a este cliente, envíe el que está pendiente a la administradora.");
                metadata.IsValid = false;
                metadata.Message = "Este recibo ya tiene cobranza registrada, para cambiarlo a retención debe eliminarla.";
            }

            CobGrabacionCobranzas cambiaRet = await _unitOfWork.GeneralCobranzaRepository.RETYaTieneCobranzaGrabada(generalCobranza.Documento);

            if (cambiaRet != null && generalCobranza.IdTipoTransaccion != "RET")
            {
                //throw new BusinessException("Este cliente ya tiene un RC abierto pendiente por enviar N° " + existenDocumentosPendientes.Documento.ToString() + ".Agregue la cobranza a este RC.Si es necesario grabar otro RC a este cliente, envíe el que está pendiente a la administradora.");
                metadata.IsValid = false;
                metadata.Message = "Este recibo ya tiene retenciones registradas, para cambiarla a cobranza debe eliminarla.";
            }


            return(metadata);
        }
Exemple #3
0
        public string EstatusRecibo(CobGeneralCobranza cobranza)
        {
            string result = "";

            if (cobranza.FlagEnviado == false)
            {
                result = Enum.GetName(typeof(EstatusReciboEnum), EstatusReciboEnum.GRABACION);
            }
            if (cobranza.FlagEnviado == true)
            {
                result = Enum.GetName(typeof(EstatusReciboEnum), EstatusReciboEnum.ENVIADO_ADMINISTRACION);
            }
            if (cobranza.FlagConfirmado == true)
            {
                result = Enum.GetName(typeof(EstatusReciboEnum), EstatusReciboEnum.CONFIRMADO);
            }
            if (cobranza.FlagAprobado == true)
            {
                result = Enum.GetName(typeof(EstatusReciboEnum), EstatusReciboEnum.APROBADO);
            }
            if (cobranza.FlagAnulado == true)
            {
                result = Enum.GetName(typeof(EstatusReciboEnum), EstatusReciboEnum.ANULADO);
            }

            return(result);
        }
Exemple #4
0
        public async Task <CobGeneralCobranza> InsertGeneralCobranza(CobGeneralCobranza generalCobranza)
        {
            SegUsuario user = await _unitOfWork.SegUsuarioRepository.GetUser(generalCobranza.UsuarioRegistro);

            if (user == null)
            {
                throw new Exception("usuario no existe");
            }

            CobGeneralCobranza existenDocumentosPendientes = await _unitOfWork.GeneralCobranzaRepository.ExisteCobranzaPendienteEnviar(generalCobranza);

            if (existenDocumentosPendientes != null)
            {
                throw new BusinessException("Este cliente ya tiene un RC abierto pendiente por enviar N° " + existenDocumentosPendientes.Documento.ToString() + ".Agregue la cobranza a este RC.Si es necesario grabar otro RC a este cliente, envíe el que está pendiente a la administradora.");
            }
            MtrCliente cliente = await _mtrClienteService.GetByIdAsync(generalCobranza.IdCliente);

            MtrVendedor vendedor = await _mtrVendedorService.GetByIdAsync(cliente.Vendedor1);

            string vIn  = cliente.OficinaVenta;
            short  vOut = Convert.ToInt16(vIn);

            MtrOficina mtrOficina = await _mtrOficinaService.GetOficina(vOut);

            generalCobranza.SearchText   = generalCobranza.IdCliente + "-" + cliente.Nombre + "-" + vendedor.Nombre + "-" + generalCobranza.Documento.ToString() + "-" + mtrOficina.NomOficina.Trim();
            generalCobranza.OficinaVenta = cliente.OficinaVenta;
            await _unitOfWork.GeneralCobranzaRepository.Add(generalCobranza);

            await _unitOfWork.SaveChangesAsync();


            CobGeneralCobranza result = await UpdateGeneralCobranza(generalCobranza);

            return(result);
        }
Exemple #5
0
        public async Task <Metadata> ValidaInsertCobranza(CobGeneralCobranza generalCobranza)
        {
            Metadata metadata = new Metadata();

            SegUsuario user = await _unitOfWork.SegUsuarioRepository.GetUser(generalCobranza.UsuarioRegistro);

            if (user == null)
            {
                metadata.IsValid = false;
                metadata.Message = "usuario no existe";
            }

            CobGeneralCobranza existenDocumentosPendientes = await _unitOfWork.GeneralCobranzaRepository.ExisteCobranzaPendienteEnviar(generalCobranza);

            if (existenDocumentosPendientes != null)
            {
                //throw new BusinessException("Este cliente ya tiene un RC abierto pendiente por enviar N° " + existenDocumentosPendientes.Documento.ToString() + ".Agregue la cobranza a este RC.Si es necesario grabar otro RC a este cliente, envíe el que está pendiente a la administradora.");
                metadata.IsValid = false;
                metadata.Message = "Este cliente ya tiene un RC abierto pendiente por enviar N° " + existenDocumentosPendientes.Documento.ToString() + ".Agregue la cobranza a este RC.Si es necesario grabar otro RC a este cliente, envíe el que está pendiente a la administradora.";
            }
            else
            {
                metadata.IsValid = true;
                metadata.Message = "";
            }


            return(metadata);
        }
Exemple #6
0
        public async Task UpdateSearchText()
        {
            List <CobGeneralCobranza> cobGeneralCobranza = new List <CobGeneralCobranza>();

            cobGeneralCobranza = await _unitOfWork.GeneralCobranzaRepository.GetAllSearchTextBlanco();



            foreach (CobGeneralCobranza item in cobGeneralCobranza)
            {
                CobGeneralCobranza result = await UpdateGeneralCobranza(item);
            }
        }
Exemple #7
0
        public async Task <CobGeneralCobranza> UpdateGeneralCobranza(CobGeneralCobranza generalCobranza)
        {
            CobGeneralCobranza cobranza = await GetGeneralCobranzaPorDocumento(generalCobranza.Documento);

            if (cobranza == null)
            {
                throw new Exception("Documento No existe");
            }

            MtrCliente cliente = await _mtrClienteService.GetByIdAsync(generalCobranza.IdCliente);

            MtrVendedor vendedor = await _mtrVendedorService.GetByIdAsync(cliente.Vendedor1);

            string vIn  = cliente.OficinaVenta;
            short  vOut = Convert.ToInt16(vIn);

            MtrOficina mtrOficina = await _mtrOficinaService.GetOficina(vOut);

            string statusString = EstatusRecibo(generalCobranza);

            if (vendedor != null)
            {
                cobranza.SearchText = cobranza.IdCliente + "-" + cliente.Nombre.Trim() + "-" + vendedor.Nombre.Trim() + "-" + cobranza.Documento.ToString() + "-" + statusString + "-Ofic " + mtrOficina.NomOficina.Trim();
            }
            else
            {
                cobranza.SearchText = cobranza.IdCliente + "-" + cliente.Nombre.Trim() + "-" + cobranza.Documento.ToString() + "-" + statusString + "-Ofic " + mtrOficina.NomOficina.Trim();
            }

            cobranza.IdCliente         = generalCobranza.IdCliente;
            cobranza.IdMtrTipoMoneda   = generalCobranza.IdMtrTipoMoneda;
            cobranza.MontoTransaccion  = generalCobranza.MontoTransaccion;
            cobranza.IdTipoTransaccion = generalCobranza.IdTipoTransaccion;
            cobranza.IdBanco           = generalCobranza.IdBanco;
            cobranza.FechaTransaccion  = generalCobranza.FechaTransaccion;
            cobranza.NumReferencia     = generalCobranza.NumReferencia;
            cobranza.EmailCliente      = generalCobranza.EmailCliente;
            cobranza.FechaRegistro     = generalCobranza.FechaRegistro;
            cobranza.UsuarioRegistro   = generalCobranza.UsuarioRegistro;
            cobranza.OficinaVenta      = cliente.OficinaVenta;

            cobranza.TotalDetalleCobrado = cobranza.MontoTransaccion - _cobGrabacionCobranzasService.TotalDetalleRecibo(cobranza.Documento);



            await _unitOfWork.GeneralCobranzaRepository.Update(cobranza);

            await _unitOfWork.SaveChangesAsync();

            return(await GetGeneralCobranzaPorDocumento(generalCobranza.Documento));
        }
Exemple #8
0
        public async Task <bool> DeleteGeneralCobranza(long documento)
        {
            CobGeneralCobranza cobranza = await GetGeneralCobranzaPorDocumento(documento);

            if (cobranza == null)
            {
                throw new Exception("Documento No existe");
            }


            await _unitOfWork.GeneralCobranzaRepository.Delete(documento);

            await _unitOfWork.SaveChangesAsync();

            return(true);
        }
Exemple #9
0
        public async Task <ReciboDto> GeneraReciboDto(long recibo)
        {
            ReciboDto                    result                     = new ReciboDto();
            CobGeneralCobranza           cobGeneralCobranza         = new CobGeneralCobranza();
            List <CobGrabacionCobranzas> listaCobGrabacionCobranzas = new List <CobGrabacionCobranzas>();

            try
            {
                //Crea Objeto General cobranzas
                cobGeneralCobranza = await GetGeneralCobranzaPorDocumento(recibo);

                CobGeneralCobranzaDto generalCobranzasDtos = _mapper.Map <CobGeneralCobranzaDto>(cobGeneralCobranza);

                MtrCliente cliente = await _mtrClienteService.GetByIdAsync(generalCobranzasDtos.IdCliente);

                MtrVendedor vendedor = await _mtrVendedorService.GetByIdAsync(cliente.Vendedor1);

                generalCobranzasDtos.NombreCliente          = cliente.NoRegTribut + " " + cliente.Nombre.Trim();
                generalCobranzasDtos.IdCliente              = generalCobranzasDtos.IdCliente.Trim();
                generalCobranzasDtos.FechaTransaccionString = generalCobranzasDtos.FechaTransaccion.ToShortDateString();
                generalCobranzasDtos.NombreVendedor         = vendedor.Nombre;
                generalCobranzasDtos.vendedor         = vendedor.Codigo;
                generalCobranzasDtos.CorreoVendedor   = vendedor.EMail;
                generalCobranzasDtos.TelefonoVendedor = vendedor.TlfCelular;



                decimal decimalValue = generalCobranzasDtos.MontoTransaccion;
                generalCobranzasDtos.MontoTransaccionString = string.Format("{0:N}", decimalValue); // 1,234,567.00


                //creamos el objeto
                Moneda oMoneda = new Moneda();

                //primer parametro es la cantidad en string
                //segundo parametro es si queremos que sea mayuscula
                //tercer parametro la moneda


                MtrTipoMoneda tipoMoneda = await _mtrTipoMonedaService.GetById((long)cobGeneralCobranza.IdMtrTipoMoneda);

                string MonedaString = tipoMoneda.Descripcion;



                string resultado = oMoneda.Convertir(generalCobranzasDtos.MontoTransaccion.ToString(), true, MonedaString);
                generalCobranzasDtos.MontoLetras = resultado;


                decimal?detalleValue = generalCobranzasDtos.TotalDetalleCobrado;
                generalCobranzasDtos.TotalDetalleCobradoString = string.Format("{0:N}", detalleValue);
                generalCobranzasDtos.Status = EstatusRecibo(cobGeneralCobranza);

                MtrBancos banco = await _mtrBancosService.GetByCodigo(generalCobranzasDtos.IdBanco);

                generalCobranzasDtos.NombreBanco = banco.Nombre;

                CobTipoTransaccion tipoTransaccion = await _cobTipoTransaccionService.GetById(generalCobranzasDtos.IdTipoTransaccion);

                generalCobranzasDtos.NombreTipoTransaccion = tipoTransaccion.NombreTipoTransaccion;
                generalCobranzasDtos.FlagImpuesto          = tipoTransaccion.FlagImpuesto;


                MtrTipoMoneda mtrTipoMoneda = await _mtrTipoMonedaService.GetById((long)generalCobranzasDtos.IdMtrTipoMoneda);

                generalCobranzasDtos.NombreTipoMoneda = mtrTipoMoneda.Descripcion;



                listaCobGrabacionCobranzas = _unitOfWork.CobGrabacionCobranzasRepository.GetByDocumento(recibo);
                listaCobGrabacionCobranzas = listaCobGrabacionCobranzas.Where(x => x.DocumentoSap == "").ToList();

                List <CobGrabacionCobranzaDto> listaCobGrabacionCobranzasDto = _mapper.Map <List <CobGrabacionCobranzaDto> >(listaCobGrabacionCobranzas);

                foreach (CobGrabacionCobranzaDto item in listaCobGrabacionCobranzasDto)
                {
                    item.CuentaBancaria = banco.CodContable;
                    item.Moneda         = mtrTipoMoneda.Descripcion;
                    if (item.Transaccion == "RU")
                    {
                        item.DocAfectaMostrar = item.Cotizacion;
                    }
                    else
                    {
                        item.DocAfectaMostrar = item.DocAfectaSap;
                    }

                    decimalValue      = (decimal)item.Monto;
                    item.MontoMostrar = string.Format("{0:N}", decimalValue); // 1,234,567.00

                    CobEstadoDeCuenta cobEstadoDeCuenta = await _cobEstadoCuentaService.GetEstadoCuentaById(item.DocAfecta);

                    if (cobEstadoDeCuenta != null)
                    {
                        decimalValue              = (decimal)cobEstadoDeCuenta.BaseImponible;
                        item.BaseImponible        = (decimal)cobEstadoDeCuenta.BaseImponible;
                        item.BaseImponibleMostrar = string.Format("{0:N}", decimalValue); // 1,234,567.00
                        decimalValue              = (decimal)cobEstadoDeCuenta.Iva;
                        item.Iva        = (decimal)cobEstadoDeCuenta.Iva;
                        item.IvaMostrar = string.Format("{0:N}", decimalValue); // 1,234,567.00
                        decimalValue    = (decimal)cobEstadoDeCuenta.MontoOriginal;

                        item.MontoOriginalMostrar = string.Format("{0:N}", decimalValue); // 1,234,567.00
                        item.FechaDocumento       = cobEstadoDeCuenta.FechaDocumento;
                        DateTime fechaDocumento = (DateTime)cobEstadoDeCuenta.FechaDocumento;
                        item.FechaDocumentoString = fechaDocumento.ToShortDateString();
                    }

                    //List<CobPagosRetencionesDto> listCobPagosRetencionesDto = new List<CobPagosRetencionesDto>();
                    List <CobPagosRetenciones> listCobPagosRetenciones = _unitOfWork.CobPagosRetencionesRepository.GetByIdCobranzas(item.Id);

                    List <CobPagosRetencionesDto> listCobPagosRetencionesDto = _mapper.Map <List <CobPagosRetencionesDto> >(listCobPagosRetenciones);

                    if (listCobPagosRetencionesDto != null && listCobPagosRetencionesDto.Count > 0)
                    {
                        foreach (CobPagosRetencionesDto itemRet in listCobPagosRetencionesDto)
                        {
                            decimalValue        = itemRet.Monto;
                            itemRet.MontoString = string.Format("{0:N}", decimalValue); // 1,234,567.00

                            CobTransacciones transaccion = await _cobTransaccionesService.GetById(itemRet.IdTransaccion);

                            if (transaccion != null)
                            {
                                itemRet.NombreTransaccion = transaccion.NombreTransaccion;
                                itemRet.TxOrigen          = transaccion.TipoSap;
                            }
                            itemRet.FechaComprobanteString = itemRet.FechaComprobante.ToShortDateString();
                        }
                    }


                    item.CobPagosRetencionesDto = listCobPagosRetencionesDto;
                }



                result.CobGeneralCobranzaDto   = generalCobranzasDtos;
                result.CobGrabacionCobranzaDto = listaCobGrabacionCobranzasDto;

                return(result);
            }
            catch (Exception e)
            {
                string message = e.Message;
                throw;
            }
        }
        public async Task <CobGeneralCobranza> ExisteCobranzaPendienteEnviar(CobGeneralCobranza generalCobranza)
        {
            CobGeneralCobranza row = await _context.CobGeneralCobranza.Where(x => x.IdCliente == generalCobranza.IdCliente && x.FlagEnviado == false && x.FlagAnulado == false).FirstOrDefaultAsync();

            return(row);
        }
        public async Task <CobGeneralCobranza> GetGeneralCobranzaDocumento(long documento)
        {
            CobGeneralCobranza row = await _context.CobGeneralCobranza.Where(x => x.Documento == documento).FirstOrDefaultAsync();

            return(row);
        }
        public async Task Delete(long id)
        {
            CobGeneralCobranza entity = await GetById(id);

            _context.CobGeneralCobranza.Remove(entity);
        }
 public async Task Update(CobGeneralCobranza entity)
 {
     _context.CobGeneralCobranza.Update(entity);
 }
 public async Task Add(CobGeneralCobranza entity)
 {
     await _context.CobGeneralCobranza.AddAsync(entity);
 }
Exemple #15
0
        public async Task <IActionResult> Update(CobGrabacionCobranzaDto cobGrabacionCobranzaDto)
        {
            CobGrabacionCobranzaDto resultDto = new CobGrabacionCobranzaDto();
            Metadata metadata = new Metadata
            {
                IsValid = true,
                Message = ""
            };



            ApiResponse <CobGrabacionCobranzaDto> response = new ApiResponse <CobGrabacionCobranzaDto>(resultDto);



            CobGrabacionCobranzas cobGrabacionCobranza = _mapper.Map <CobGrabacionCobranzas>(cobGrabacionCobranzaDto);

            CobGeneralCobranza generalCobranza = await _generalCobranzaService.GetGeneralCobranzaPorDocumento((long)cobGrabacionCobranza.Documento);

            MtrTipoMoneda tipomoneda = await _mtrTipoMonedaService.GetById((long)generalCobranza.IdMtrTipoMoneda);

            CobEstadoDeCuenta estadoCuenta = await _cobEstadoCuentaService.GetEstadoCuentaById(cobGrabacionCobranzaDto.DocAfecta);

            if (estadoCuenta != null)
            {
                CobGrabacionCobranzas grabacionActual = await _cobGrabacionCobranzasService.GetById(cobGrabacionCobranzaDto.Id);



                if (cobGrabacionCobranzaDto.Transaccion != "RU")
                {
                    if (generalCobranza.IdTipoTransaccion != "RET")
                    {
                        bool existeMonedaDocumentoMonedaPago = await _cobMatrixMonedaValidaPagoService.ExisteMonedaDocumentoMonedaPago(estadoCuenta.Moneda, tipomoneda.Descripcion);

                        if (!existeMonedaDocumentoMonedaPago)
                        {
                            metadata.IsValid = false;

                            metadata.Message = "Esta intentando grabar cobro en moneda no valida a el Recibo";

                            response.Meta = metadata;
                            return(Ok(response));
                        }
                    }


                    decimal totalAfectadoDocumento = _cobGrabacionCobranzasService.TotalAfectadoDocumento((long)cobGrabacionCobranzaDto.Documento, cobGrabacionCobranzaDto.DocAfecta);


                    decimal totalAfectadoDocumentoResta = totalAfectadoDocumento - (decimal)grabacionActual.Monto;


                    if (totalAfectadoDocumentoResta + (decimal)cobGrabacionCobranzaDto.Monto > (decimal)estadoCuenta.Rpaap)
                    {
                        metadata.IsValid = false;

                        metadata.Message = "Esta intentando grabar monto superior al saldo del documento:" + "Total registrado en recibo: " + totalAfectadoDocumento.ToString() + "Saldo documento: " + estadoCuenta.Rpaap.ToString();

                        response.Meta = metadata;
                        return(Ok(response));
                    }
                }
            }


            CobGrabacionCobranzas grabacionCobranzaActual = await _cobGrabacionCobranzasService.GetById(cobGrabacionCobranzaDto.Id);

            if (grabacionCobranzaActual.DocumentoSap.Length > 1)
            {
                metadata.IsValid = false;

                metadata.Message = "Esta intentando modificar un cobro ya contabilizado";

                response.Meta = metadata;
                return(Ok(response));
            }


            CobGrabacionCobranzas cobranza = await _cobGrabacionCobranzasService.Update(cobGrabacionCobranza);

            if (cobranza != null)
            {
                resultDto        = _mapper.Map <CobGrabacionCobranzaDto>(cobranza);
                metadata.IsValid = true;
                metadata.Message = "Actualizado Satisfactoriamente";
            }
            else
            {
                metadata.IsValid = false;

                metadata.Message = "Registro No actualizado";
            }



            //ApiResponse<CobGrabacionCobranzaDto> response = new ApiResponse<CobGrabacionCobranzaDto>(resultDto)
            //{
            //    Meta = metadata,
            //};
            response.Meta = metadata;
            response.Data = resultDto;
            return(Ok(response));
        }
Exemple #16
0
        public async Task <IActionResult> Insert(CobGrabacionCobranzaDto cobGrabacionCobranzaDto)
        {
            CobGrabacionCobranzaDto resultDto = new CobGrabacionCobranzaDto();

            Metadata metadata = new Metadata
            {
                IsValid = true,
                Message = ""
            };
            ApiResponse <CobGrabacionCobranzaDto> response = new ApiResponse <CobGrabacionCobranzaDto>(resultDto);

            try
            {
                CobGeneralCobranza generalCobranza = await _generalCobranzaService.GetGeneralCobranzaPorDocumento((long)cobGrabacionCobranzaDto.Documento);

                if (cobGrabacionCobranzaDto.Transaccion == "RU" && generalCobranza.FlagPagoMas != true)
                {
                    OfdCotizacion cotizacion = new OfdCotizacion();


                    cotizacion = await _ofdCotizacionService.GetCotizacion(cobGrabacionCobranzaDto.Cotizacion);

                    if (cotizacion != null)
                    {
                        if (cotizacion.IdCliente == generalCobranza.IdCliente)
                        {
                            metadata.IsValid = true;
                            metadata.Message = "";
                        }
                        else
                        {
                            metadata.IsValid = false;
                            metadata.Message = "Cotizacion no pertenece a este cliente!!! " + generalCobranza.IdCliente;
                            response.Meta    = metadata;
                            response.Data    = resultDto;
                            return(Ok(response));
                        }
                    }
                    else
                    {
                        metadata.IsValid = false;
                        metadata.Message = "Cotizacion no existe!!!";
                        response.Meta    = metadata;
                        response.Data    = resultDto;

                        return(Ok(response));
                    }
                }



                CobGrabacionCobranzas cobGrabacionCobranza = _mapper.Map <CobGrabacionCobranzas>(cobGrabacionCobranzaDto);


                MtrTipoMoneda tipomoneda = await _mtrTipoMonedaService.GetById((long)generalCobranza.IdMtrTipoMoneda);

                bool dividirPagoImpuesto       = false;
                CobEstadoDeCuenta estadoCuenta = await _cobEstadoCuentaService.GetEstadoCuentaById(cobGrabacionCobranzaDto.DocAfecta);

                if (estadoCuenta != null)
                {
                    if (cobGrabacionCobranzaDto.Transaccion != "RU")
                    {
                        if (generalCobranza.IdTipoTransaccion != "RET")
                        {
                            bool existeMonedaDocumentoMonedaPago = await _cobMatrixMonedaValidaPagoService.ExisteMonedaDocumentoMonedaPago(estadoCuenta.Moneda, tipomoneda.Descripcion);

                            if (!existeMonedaDocumentoMonedaPago)
                            {
                                metadata.IsValid = false;

                                metadata.Message = "Esta intentando grabar cobro en moneda no valida a el Recibo";

                                response.Meta = metadata;
                                return(Ok(response));
                            }

                            decimal totalAfectadoDocumento = _cobGrabacionCobranzasService.TotalAfectadoDocumento((long)cobGrabacionCobranzaDto.Documento, cobGrabacionCobranzaDto.DocAfecta);
                            if (totalAfectadoDocumento + (decimal)cobGrabacionCobranzaDto.Monto > (decimal)estadoCuenta.Rpaap)
                            {
                                metadata.IsValid = false;

                                metadata.Message = "Esta intentando grabar monto superior al saldo del documento:" + "Total registrado en recibo: " + totalAfectadoDocumento.ToString() + "Saldo documento: " + estadoCuenta.Rpaap.ToString();
                                return(Ok(response));
                            }
                        }
                    }


                    if (cobGrabacionCobranzaDto.Monto > estadoCuenta.BaseImponible && cobGrabacionCobranzaDto.Transaccion != "RE" && tipomoneda.Descripcion == estadoCuenta.Moneda)
                    {
                        dividirPagoImpuesto = true;
                    }
                }

                if (!dividirPagoImpuesto)
                {
                    cobGrabacionCobranza.PagoCorrespondeIva = false;
                    CobGrabacionCobranzas cobranza = await _cobGrabacionCobranzasService.Insert(cobGrabacionCobranza);

                    if (cobranza != null)
                    {
                        resultDto        = _mapper.Map <CobGrabacionCobranzaDto>(cobranza);
                        metadata.IsValid = true;
                        metadata.Message = "Creado Satisfactoriamente";
                    }
                    else
                    {
                        metadata.IsValid = false;

                        metadata.Message = "Registro No actualizado";
                    }
                }
                else
                {
                    CobGrabacionCobranzas cobGrabacionCobranzaImpuesto = _mapper.Map <CobGrabacionCobranzas>(cobGrabacionCobranzaDto);


                    decimal?montoGrabado = cobGrabacionCobranza.Monto;
                    cobGrabacionCobranza.Monto = estadoCuenta.BaseImponible;


                    cobGrabacionCobranza.PagoCorrespondeIva = false;
                    CobGrabacionCobranzas cobranza = await _cobGrabacionCobranzasService.Insert(cobGrabacionCobranza);


                    cobGrabacionCobranzaImpuesto.Monto = montoGrabado - estadoCuenta.BaseImponible;
                    cobGrabacionCobranzaImpuesto.PagoCorrespondeIva = true;
                    CobGrabacionCobranzas cobranzaImpuesto = await _cobGrabacionCobranzasService.Insert(cobGrabacionCobranzaImpuesto);

                    if (cobranza != null)
                    {
                        resultDto        = _mapper.Map <CobGrabacionCobranzaDto>(cobranza);
                        metadata.IsValid = true;
                        metadata.Message = "Creado Satisfactoriamente";
                    }
                    else
                    {
                        metadata.IsValid = false;

                        metadata.Message = "Registro No actualizado";
                    }
                }

                //ApiResponse<CobGrabacionCobranzaDto> response = new ApiResponse<CobGrabacionCobranzaDto>(resultDto)
                //{
                //    Meta = metadata,
                //};
                response.Meta = metadata;
                response.Data = resultDto;

                return(Ok(response));
            }
            catch (Exception ex)
            {
                metadata.IsValid = false;

                metadata.Message = ex.InnerException.Message;

                response.Meta = metadata;
                response.Data = resultDto;
                //ApiResponse<CobGrabacionCobranzaDto> response = new ApiResponse<CobGrabacionCobranzaDto>(resultDto)
                //{
                //    Meta = metadata,
                //};
                return(Ok(response));
            }
        }