Exemple #1
0
        public int Insertar(VentaSunatInfo ventaSunatInfo)
        {
            int resultado;

            try
            {
                using (var oConnection = new SqlConnection(HelperAccesoDatos.GetCadenaConexion()))
                {
                    var sqlComando = new SqlCommand {
                        Connection = oConnection, CommandText = "InsertarVentaSunat", CommandType = CommandType.StoredProcedure
                    };

                    sqlComando.Parameters.Add("VentaId", SqlDbType.Int).Value             = ventaSunatInfo.VentaId;
                    sqlComando.Parameters.Add("CodigoRespuesta", SqlDbType.VarChar).Value = ventaSunatInfo.CodigoRespuesta;
                    sqlComando.Parameters.Add("Exito", SqlDbType.Int).Value                = ventaSunatInfo.Exito;
                    sqlComando.Parameters.Add("MensajeError", SqlDbType.VarChar).Value     = ventaSunatInfo.MensajeError;
                    sqlComando.Parameters.Add("MensajeRespuesta", SqlDbType.VarChar).Value = ventaSunatInfo.MensajeRespuesta;
                    sqlComando.Parameters.Add("NombreArchivo", SqlDbType.VarChar).Value    = ventaSunatInfo.NombreArchivo;
                    sqlComando.Parameters.Add("Pila", SqlDbType.VarChar).Value             = ventaSunatInfo.Pila;
                    sqlComando.Parameters.Add("TramaZipCdr", SqlDbType.VarChar).Value      = ventaSunatInfo.TramaZipCdr;
                    sqlComando.Parameters.Add("NroTicket", SqlDbType.VarChar).Value        = ventaSunatInfo.NroTicket;
                    sqlComando.Parameters.Add("UsuarioCreacionId", SqlDbType.Int).Value    = ventaSunatInfo.UsuarioCreacionId;

                    oConnection.Open();
                    resultado = Convert.ToInt32(sqlComando.ExecuteScalar());

                    oConnection.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(resultado);
        }
        public int Insertar(VentaSunatInfo ventaSunatInfo)
        {
            int resultado = 0;

            try
            {
                resultado = _ventaSunatAccesoDatos.Insertar(ventaSunatInfo);
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, Constantes.ExcepcionPoliticaLogicaNegocio);
                if (rethrow)
                {
                    throw;
                }
            }
            return(resultado);
        }
Exemple #3
0
        private static VentaSunatInfo CargarVentaSunatInfo(IDataReader dr)
        {
            int colCount = dr.FieldCount;
            var values   = new object[colCount];

            #region Indices
            int indSurtidorId            = dr.GetOrdinal("SurtidorId");
            int indNombre                = dr.GetOrdinal("Nombre");
            int indDescripcion           = dr.GetOrdinal("Descripcion");
            int indCodigo                = dr.GetOrdinal("Codigo");
            int indActivo                = dr.GetOrdinal("Activo");
            int indUsuarioCreacionId     = dr.GetOrdinal("UsuarioCreacionId");
            int indFechaCreacion         = dr.GetOrdinal("FechaCreacion");
            int indUsuarioModificacionId = dr.GetOrdinal("UsuarioModificacionId");
            int indFechaModificacion     = dr.GetOrdinal("FechaModificacion");
            int indNumeroFila            = dr.GetOrdinal("NumeroFila");
            int indTotalFilas            = dr.GetOrdinal("TotalFilas");
            #endregion

            var ventaSunatInfo = new VentaSunatInfo();
            dr.GetValues(values);

            #region Campos
            //ventaSunatInfo.IslaId = Convert.ToInt32(values[indSurtidorId]);
            //ventaSunatInfo.Nombre = Convert.ToString(values[indNombre]);
            //ventaSunatInfo.Descripcion = Convert.ToString(values[indDescripcion]);
            //ventaSunatInfo.Codigo = Convert.ToString(values[indCodigo]);
            //ventaSunatInfo.Activo = Convert.ToInt32(values[indActivo]);
            ventaSunatInfo.UsuarioCreacionId     = Convert.ToInt32(values[indUsuarioCreacionId]);
            ventaSunatInfo.FechaCreacion         = Convert.ToDateTime(values[indFechaCreacion]);
            ventaSunatInfo.UsuarioModificacionId = Convert.ToInt32(values[indUsuarioModificacionId]);
            ventaSunatInfo.FechaModificacion     = Convert.ToDateTime(values[indFechaModificacion]);
            //ventaSunatInfo.NumeroFila = Convert.ToInt32(values[indNumeroFila]);
            //ventaSunatInfo.TotalFilas = Convert.ToInt32(values[indTotalFilas]);
            #endregion

            return(ventaSunatInfo);
        }
Exemple #4
0
        //public static string EnviarSunat(int ventaId)
        public static EnviarDocumentoResponse EnviarSunat(int ventaId)
        {
            var mensaje = String.Empty;

            var usuarioInfo      = ObtenerUsuarioInfo();
            var ventaInfo        = new Negocio.Venta().Listar(ventaId).FirstOrDefault();
            var ventaDetalleInfo = new Negocio.Venta().ListarDetalle(ventaId, 0);
            var empresaInfo      = new Empresa().Listar(usuarioInfo.EmpresaId).FirstOrDefault();
            var clienteInfo      = new Cliente().Listar(ventaInfo.ClienteId).FirstOrDefault();

            _documento = new DocumentoElectronico();

            #region Documento
            _documento.CalculoDetraccion = 0;
            _documento.CalculoIgv        = Decimal.Divide(18, 100);
            _documento.CalculoIsc        = 0;
            _documento.DescuentoGlobal   = ventaInfo.Descuento;

            #region Emisor
            var emisor = new DocumentoElectronico().Emisor;
            emisor.Departamento    = empresaInfo.Departamento;
            emisor.Direccion       = empresaInfo.Direccion;
            emisor.Distrito        = empresaInfo.Distrito;
            emisor.NombreComercial = empresaInfo.RazonSocial;
            emisor.NombreLegal     = empresaInfo.RazonSocial;
            emisor.NroDocumento    = "10421895452";
            emisor.Provincia       = empresaInfo.Provincia;
            emisor.TipoDocumento   = empresaInfo.TipoDocumentoId.ToString();
            emisor.Ubigeo          = empresaInfo.Departamento;
            emisor.Urbanizacion    = empresaInfo.Direccion;
            _documento.Emisor      = emisor;
            #endregion

            _documento.Exoneradas   = 0;
            _documento.FechaEmision = ventaInfo.FechaEmision.ToString("dd/MM/yyyy");
            _documento.Gratuitas    = 0;
            _documento.Gravadas     = ventaInfo.MontoVenta;
            _documento.IdDocumento  = ventaInfo.NumeroSerie + "-" + ventaInfo.NumeroComprobante;
            _documento.Inafectas    = 0;

            #region Items
            var itemId = 1;
            foreach (var vd in ventaDetalleInfo)
            {
                var item = new DetalleDocumento();
                item.Cantidad    = vd.Cantidad;
                item.Descripcion = vd.Producto;
                item.Id          = itemId;
                itemId++;
                item.Impuesto          = vd.Igv;
                item.PrecioUnitario    = vd.PrecioUnitario;
                item.Suma              = vd.SubTotal;
                item.TotalVenta        = vd.MontoTotal;
                item.UnidadMedida      = vd.UnidadMedida;
                item.Descuento         = 0;
                item.ImpuestoSelectivo = 0;
                item.OtroImpuesto      = 0;
                item.PrecioReferencial = 0;
                item.TipoImpuesto      = "10";
                item.TipoPrecio        = "01";
                _documento.Items.Add(item);
            }
            #endregion

            _documento.Moneda          = ventaInfo.MonedaId.Equals(Constantes.MonedaSoles) ? Constantes.MonedaSolesSunat : Constantes.MonedaDolaresSunat;
            _documento.MontoAnticipo   = 0;
            _documento.MontoDetraccion = 0;
            _documento.MontoEnLetras   = Herramientas.NumeroALetras.numeroAletras(ventaInfo.MontoVenta);
            _documento.MontoPercepcion = 0;
            // _documento.PlacaVehiculo = ventaInfo.Placa;

            #region Receptor
            var receptor = new DocumentoElectronico().Receptor;
            receptor.Departamento    = clienteInfo.Departamento;
            receptor.Direccion       = clienteInfo.Direccion;
            receptor.Distrito        = clienteInfo.Distrito;
            receptor.NombreComercial = clienteInfo.RazonSocial;
            receptor.NombreLegal     = clienteInfo.RazonSocial;
            receptor.NroDocumento    = clienteInfo.NumeroDocumento;
            receptor.Provincia       = clienteInfo.Provincia;
            receptor.TipoDocumento   = clienteInfo.TipoDocumentoId.ToString();
            receptor.Ubigeo          = clienteInfo.Departamento;
            receptor.Urbanizacion    = clienteInfo.Direccion;
            _documento.Receptor      = receptor;
            #endregion

            _documento.TipoDocumento      = ventaInfo.TipoComprobanteId;
            _documento.TotalIgv           = ventaInfo.MontoImpuesto;
            _documento.TotalIsc           = 0;
            _documento.TotalOtrosTributos = 0;
            _documento.TotalVenta         = ventaInfo.MontoTotal;
            #endregion

            string metodoApi;
            switch (_documento.TipoDocumento)
            {
            case "07":
                metodoApi = "api/GenerarNotaCredito";
                break;

            case "08":
                metodoApi = "api/GenerarNotaDebito";
                break;

            default:
                metodoApi = "api/GenerarFactura";
                break;
            }


            #region Generando XML
            var client = new RestClient(BaseUrl);

            var requestInvoice = new RestRequest("GenerarFactura", Method.POST)
            {
                RequestFormat = DataFormat.Json
            };

            requestInvoice.AddBody(_documento);

            var documentoResponse = client.Execute <DocumentoResponse>(requestInvoice);

            if (!documentoResponse.Data.Exito)
            {
                throw new ApplicationException(documentoResponse.Data.MensajeError);
            }
            //string rutaXml = HostingEnvironment.MapPath("~/Archivos/Facturacion/XML/" + _documento.IdDocumento + ".xml");
            //File.WriteAllBytes(rutaXml, Convert.FromBase64String(documentoResponse.Data.TramaXmlSinFirma));
            string rutaXml = HostingEnvironment.MapPath("~/Archivos/Facturacion/XML/Cliente/" + clienteInfo.NumeroDocumento);
            if (!Directory.Exists(rutaXml))
            {
                Directory.CreateDirectory(rutaXml);
            }
            File.WriteAllBytes(rutaXml + "/" + _documento.IdDocumento + ".xml", Convert.FromBase64String(documentoResponse.Data.TramaXmlSinFirma));
            #endregion

            #region Firma
            string rutaCertificado = HostingEnvironment.MapPath("~/Archivos/Facturacion/certificado.pfx");
            var    firmado         = new FirmadoRequest
            {
                TramaXmlSinFirma    = documentoResponse.Data.TramaXmlSinFirma,
                CertificadoDigital  = Convert.ToBase64String(File.ReadAllBytes(rutaCertificado)),
                PasswordCertificado = "9dGxdmm5JHKwKsXc",
                UnSoloNodoExtension = false
            };

            var requestFirma = new RestRequest("Firmar", Method.POST)
            {
                RequestFormat = DataFormat.Json
            };
            requestFirma.AddBody(firmado);

            var responseFirma = client.Execute <FirmadoResponse>(requestFirma);

            if (!responseFirma.Data.Exito)
            {
                throw new ApplicationException(responseFirma.Data.MensajeError);
            }
            //string rutaXmlFirmado = HostingEnvironment.MapPath("~/Archivos/Facturacion/XML/" + _documento.IdDocumento + "_Firmado.xml");
            //File.WriteAllBytes(rutaXmlFirmado, Convert.FromBase64String(responseFirma.Data.TramaXmlFirmado));
            string rutaXmlFirmado = HostingEnvironment.MapPath("~/Archivos/Facturacion/XML/Cliente/" + clienteInfo.NumeroDocumento);
            if (!Directory.Exists(rutaXmlFirmado))
            {
                Directory.CreateDirectory(rutaXmlFirmado);
            }
            File.WriteAllBytes(rutaXmlFirmado + "/" + _documento.IdDocumento + "_Firmado.xml", Convert.FromBase64String(responseFirma.Data.TramaXmlFirmado));
            #endregion

            #region Envio SUNAT
            var sendBill = new EnviarDocumentoRequest
            {
                Ruc             = _documento.Emisor.NroDocumento,
                UsuarioSol      = "FACTRC18",
                ClaveSol        = "rcfact2018",
                EndPointUrl     = UrlSunat,
                IdDocumento     = _documento.IdDocumento,
                TipoDocumento   = _documento.TipoDocumento,
                TramaXmlFirmado = responseFirma.Data.TramaXmlFirmado
            };

            var requestSendBill = new RestRequest("EnviarDocumento", Method.POST)
            {
                RequestFormat = DataFormat.Json
            };
            requestSendBill.AddBody(sendBill);

            var responseSendBill = client.Execute <EnviarDocumentoResponse>(requestSendBill);

            if (!responseSendBill.Data.Exito)
            {
                // throw new ApplicationException(responseSendBill.Data.MensajeError);
            }
            else
            {
                string rutaCdr = HostingEnvironment.MapPath("~/Archivos/Facturacion/CDR/" + responseSendBill.Data.NombreArchivo + ".zip");
                File.WriteAllBytes(rutaCdr, Convert.FromBase64String(responseSendBill.Data.TramaZipCdr));
            }

            var data = responseSendBill.Data;
            mensaje = data.Exito ? data.MensajeRespuesta : data.MensajeError;

            var ventaSunatInfo = new VentaSunatInfo();
            ventaSunatInfo.VentaId           = ventaId;
            ventaSunatInfo.CodigoRespuesta   = (data.CodigoRespuesta == null) ? String.Empty : data.CodigoRespuesta;
            ventaSunatInfo.Exito             = data.Exito ? 1 : 0;
            ventaSunatInfo.MensajeError      = (data.MensajeError == null)?String.Empty : data.MensajeError;
            ventaSunatInfo.MensajeRespuesta  = (data.MensajeRespuesta == null) ? String.Empty : data.MensajeRespuesta;
            ventaSunatInfo.NombreArchivo     = (data.NombreArchivo == null) ? String.Empty : data.NombreArchivo;
            ventaSunatInfo.Pila              = (data.Pila == null) ? String.Empty : data.Pila;
            ventaSunatInfo.TramaZipCdr       = (data.TramaZipCdr == null) ? String.Empty : data.TramaZipCdr;
            ventaSunatInfo.UsuarioCreacionId = usuarioInfo.UsuarioId;
            new Negocio.VentaSunat().Insertar(ventaSunatInfo);
            #endregion

            return(data);
        }
Exemple #5
0
        public void EnvioSunat()
        {
            try
            {
                var estadoProceso = Negocio.Helper.ObtenerValorParametro("ESTADO_SERVICIO_WINDOWS").ToString();

                if (estadoProceso.Equals("P"))
                {
                    return;
                }

                if (estadoProceso.Equals("N"))
                {
                    Negocio.Helper.ActualizarColumnasTabla("ParametrosGlobales", new string[] { "ValorParametro" }, new string[] { "P" }, new string[] { "NombreParametro" }, new string[] { "ESTADO_SERVICIO_WINDOWS" });
                    var ventaPendienteListaInfo = new Venta().Listar(0).Where(v => v.Exito.Equals(0)).ToList();

                    foreach (var v in ventaPendienteListaInfo)
                    {
                        //var ventaId = 1;
                        var ventaId = v.VentaId;
                        var mensaje = String.Empty;

                        //var usuarioInfo = ObtenerUsuarioInfo();
                        var usuarioInfo      = new Usuario().Listar(1, "", "", "", 0, 0).FirstOrDefault();
                        var ventaInfo        = new Venta().Listar(ventaId).FirstOrDefault();
                        var ventaDetalleInfo = new Venta().ListarDetalle(ventaId, 0);
                        var empresaInfo      = new Empresa().Listar(usuarioInfo.EmpresaId).FirstOrDefault();
                        var clienteInfo      = new Cliente().Listar(ventaInfo.ClienteId).FirstOrDefault();

                        _documento = new DocumentoElectronico();

                        #region Documento
                        _documento.CalculoDetraccion = 0;
                        _documento.CalculoIgv        = Decimal.Divide(18, 100);
                        _documento.CalculoIsc        = 0;
                        _documento.DescuentoGlobal   = ventaInfo.Descuento;
                        // _documento.DocAnticipo = String.Empty;

                        #region Emisor
                        var emisor = new DocumentoElectronico().Emisor;
                        emisor.Departamento = empresaInfo.Departamento;
                        //emisor.Departamento = "LIMA";
                        emisor.Direccion = empresaInfo.Direccion;
                        //emisor.Direccion = "LADERAS DE CHILLON";
                        emisor.Distrito = empresaInfo.Distrito;
                        //emisor.Distrito = "PUENTE PIEDRA";
                        emisor.NombreComercial = empresaInfo.RazonSocial;
                        emisor.NombreLegal     = empresaInfo.RazonSocial;
                        //emisor.NombreComercial = "ABARCA URBANO";
                        //emisor.NombreLegal = "MIGUEL ABARCA URBANO";
                        //emisor.NroDocumento = empresaInfo.NumeroDocumento;
                        emisor.NroDocumento = "10421895452";
                        emisor.Provincia    = empresaInfo.Provincia;
                        //emisor.Provincia = "LIMA";
                        emisor.TipoDocumento = empresaInfo.TipoDocumentoId.ToString();
                        emisor.Ubigeo        = empresaInfo.Departamento;
                        emisor.Urbanizacion  = empresaInfo.Direccion;
                        //emisor.Urbanizacion = "LADERAS DE CHILLON";
                        _documento.Emisor = emisor;
                        #endregion

                        _documento.Exoneradas   = 0;
                        _documento.FechaEmision = ventaInfo.FechaEmision.ToString("dd/MM/yyyy");
                        //_documento.FechaEmision = "2017-11-27";
                        _documento.Gratuitas = 0;
                        _documento.Gravadas  = ventaInfo.MontoVenta;
                        //_documento.Gravadas = 1000;
                        _documento.IdDocumento = ventaInfo.NumeroSerie + "-" + ventaInfo.NumeroComprobante;
                        _documento.Inafectas   = 0;

                        #region Items
                        var itemId = 1;
                        foreach (var vd in ventaDetalleInfo)
                        {
                            var item = new DetalleDocumento();
                            item.Cantidad = vd.Cantidad;
                            // item.CodigoItem = vd.Codigo;

                            item.Descripcion = vd.Producto;
                            //item.Descuento = vd.Descuento;
                            item.Id = itemId;
                            itemId++;
                            item.Impuesto = vd.Igv;
                            //item.ImpuestoSelectivo = 0;
                            //item.OtroImpuesto = 0;
                            //item.PrecioReferencial = 0;
                            item.PrecioUnitario = vd.PrecioUnitario;
                            item.Suma           = vd.SubTotal;
                            //item.TipoImpuesto = "10";
                            //item.TipoPrecio = "01";
                            item.TotalVenta   = vd.MontoTotal;
                            item.UnidadMedida = vd.UnidadMedida;
                            //item.CodigoItem = "A0001";
                            item.Descuento = 0;
                            //item.Id = 1;
                            item.ImpuestoSelectivo = 0;
                            item.OtroImpuesto      = 0;
                            item.PrecioReferencial = 0;
                            // item.PrecioUnitario = 50;
                            item.TipoImpuesto = "10";
                            item.TipoPrecio   = "01";
                            // item.UnidadMedida = "NIU";
                            _documento.Items.Add(item);
                        }
                        #endregion

                        _documento.Moneda = ventaInfo.MonedaId.Equals(Constantes.MonedaSoles) ? Constantes.MonedaSolesSunat : Constantes.MonedaDolaresSunat;
                        // _documento.MonedaAnticipo = 0.18;
                        _documento.MontoAnticipo   = 0;
                        _documento.MontoDetraccion = 0;
                        _documento.MontoEnLetras   = Herramientas.NumeroALetras.numeroAletras(ventaInfo.MontoVenta);
                        //_documento.MontoEnLetras = "MIL";
                        _documento.MontoPercepcion = 0;
                        // _documento.PlacaVehiculo = ventaInfo.Placa;

                        #region Receptor
                        var receptor = new DocumentoElectronico().Receptor;
                        receptor.Departamento    = clienteInfo.Departamento;
                        receptor.Direccion       = clienteInfo.Direccion;
                        receptor.Distrito        = clienteInfo.Distrito;
                        receptor.NombreComercial = clienteInfo.RazonSocial;
                        receptor.NombreLegal     = clienteInfo.RazonSocial;
                        //receptor.NombreComercial = "RENE ABARCA URBANO";
                        //receptor.NombreLegal = "RENE ABARCA URBANO";
                        //receptor.NroDocumento = clienteInfo.NumeroDocumento;
                        receptor.NroDocumento  = "10415787796";
                        receptor.Provincia     = clienteInfo.Provincia;
                        receptor.TipoDocumento = clienteInfo.TipoDocumentoId.ToString();
                        receptor.Ubigeo        = clienteInfo.Departamento;
                        receptor.Urbanizacion  = clienteInfo.Direccion;
                        _documento.Receptor    = receptor;
                        #endregion

                        // _documento.TipoDocAnticipo = 0;
                        _documento.TipoDocumento = ventaInfo.TipoComprobanteId;
                        // _documento.TipoOperacion = ventaInfo.TipoOperacionId;
                        _documento.TotalIgv = ventaInfo.MontoImpuesto;
                        //_documento.TotalIgv = 180;
                        _documento.TotalIsc           = 0;
                        _documento.TotalOtrosTributos = 0;
                        _documento.TotalVenta         = ventaInfo.MontoTotal;
                        //_documento.TotalVenta = 1180;
                        #endregion

                        //var proxy = new HttpClient { BaseAddress = new Uri(ConfigurationManager.AppSettings["UrlOpenInvoicePeruApi"]) };

                        string metodoApi;
                        switch (_documento.TipoDocumento)
                        {
                        case "07":
                            metodoApi = "api/GenerarNotaCredito";
                            break;

                        case "08":
                            metodoApi = "api/GenerarNotaDebito";
                            break;

                        default:
                            metodoApi = "api/GenerarFactura";
                            break;
                        }

                        //var response = await proxy.PostAsJsonAsync(metodoApi, _documento);
                        //var respuesta = await response.Content.ReadAsAsync<DocumentoResponse>();

                        #region Generando XML
                        var client = new RestClient(BaseUrl);

                        var requestInvoice = new RestRequest("GenerarFactura", Method.POST)
                        {
                            RequestFormat = DataFormat.Json
                        };

                        requestInvoice.AddBody(_documento);

                        var documentoResponse = client.Execute <DocumentoResponse>(requestInvoice);

                        if (!documentoResponse.Data.Exito)
                        {
                            throw new ApplicationException(documentoResponse.Data.MensajeError);
                        }
                        //string rutaXml = HostingEnvironment.MapPath("~/Archivos/Facturacion/XML/" + _documento.IdDocumento + ".xml");
                        string rutaXml = @"D:\ASOLUTIONS\APU\APU.Presentacion\Archivos\Facturacion\XML\" + _documento.IdDocumento + ".xml";
                        File.WriteAllBytes(rutaXml, Convert.FromBase64String(documentoResponse.Data.TramaXmlSinFirma));
                        #endregion

                        #region Firma
                        //string rutaCertificado = HostingEnvironment.MapPath("~/Archivos/Facturacion/certificado.pfx");
                        var rutaCertificado = @"D:\ASOLUTIONS\APU\APU.Presentacion\certificado.pfx";
                        var firmado         = new FirmadoRequest
                        {
                            TramaXmlSinFirma = documentoResponse.Data.TramaXmlSinFirma,
                            //CertificadoDigital = Convert.ToBase64String(File.ReadAllBytes("certificado.pfx")),
                            CertificadoDigital  = Convert.ToBase64String(File.ReadAllBytes(rutaCertificado)),
                            PasswordCertificado = string.Empty,
                            UnSoloNodoExtension = false
                        };

                        var requestFirma = new RestRequest("Firmar", Method.POST)
                        {
                            RequestFormat = DataFormat.Json
                        };
                        requestFirma.AddBody(firmado);

                        var responseFirma = client.Execute <FirmadoResponse>(requestFirma);

                        if (!responseFirma.Data.Exito)
                        {
                            throw new ApplicationException(responseFirma.Data.MensajeError);
                        }
                        //string rutaXmlFirmado = HostingEnvironment.MapPath("~/Archivos/Facturacion/XML/" + _documento.IdDocumento + "_Firmado.xml");
                        string rutaXmlFirmado = @"D:\ASOLUTIONS\APU\APU.Presentacion\Archivos\Facturacion\XML\" + _documento.IdDocumento + "_Firmado.xml";
                        File.WriteAllBytes(rutaXmlFirmado, Convert.FromBase64String(responseFirma.Data.TramaXmlFirmado));
                        #endregion

                        #region Envio SUNAT
                        var sendBill = new EnviarDocumentoRequest
                        {
                            //Ruc = _documento.Emisor.NroDocumento,
                            Ruc = "10421895452",
                            //UsuarioSol = "MODDATOS",
                            UsuarioSol = "MMINSIOT",
                            //ClaveSol = "MODDATOS",
                            ClaveSol        = "saywalcod",
                            EndPointUrl     = UrlSunat,
                            IdDocumento     = _documento.IdDocumento,
                            TipoDocumento   = _documento.TipoDocumento,
                            TramaXmlFirmado = responseFirma.Data.TramaXmlFirmado
                        };

                        var requestSendBill = new RestRequest("EnviarDocumento", Method.POST)
                        {
                            RequestFormat = DataFormat.Json
                        };
                        requestSendBill.AddBody(sendBill);

                        var responseSendBill = client.Execute <EnviarDocumentoResponse>(requestSendBill);

                        if (!responseSendBill.Data.Exito)
                        {
                            // throw new ApplicationException(responseSendBill.Data.MensajeError);
                        }
                        else
                        {
                            //string rutaCdr = HostingEnvironment.MapPath("~/Archivos/Facturacion/CDR/" + responseSendBill.Data.NombreArchivo + ".zip");
                            string rutaCdr = @"D:\ASOLUTIONS\APU\APU.Presentacion\Archivos\Facturacion\CDR\" + responseSendBill.Data.NombreArchivo + ".zip";
                            File.WriteAllBytes(rutaCdr, Convert.FromBase64String(responseSendBill.Data.TramaZipCdr));
                        }

                        //Console.WriteLine("Respuesta de SUNAT:");
                        //Console.WriteLine(responseSendBill.Data.MensajeRespuesta);
                        var data = responseSendBill.Data;
                        mensaje = data.Exito ? data.MensajeRespuesta : data.MensajeError;

                        var ventaSunatInfo = new VentaSunatInfo();
                        ventaSunatInfo.VentaId           = ventaId;
                        ventaSunatInfo.CodigoRespuesta   = (data.CodigoRespuesta == null) ? String.Empty : data.CodigoRespuesta;
                        ventaSunatInfo.Exito             = data.Exito ? 1 : 0;
                        ventaSunatInfo.MensajeError      = (data.MensajeError == null) ? String.Empty : data.MensajeError;
                        ventaSunatInfo.MensajeRespuesta  = (data.MensajeRespuesta == null) ? String.Empty : data.MensajeRespuesta;
                        ventaSunatInfo.NombreArchivo     = (data.NombreArchivo == null) ? String.Empty : data.NombreArchivo;
                        ventaSunatInfo.Pila              = (data.Pila == null) ? String.Empty : data.Pila;
                        ventaSunatInfo.TramaZipCdr       = (data.TramaZipCdr == null) ? String.Empty : data.TramaZipCdr;
                        ventaSunatInfo.UsuarioCreacionId = usuarioInfo.UsuarioId;
                        new VentaSunat().Insertar(ventaSunatInfo);
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                // Console.WriteLine(e);
                System.Diagnostics.EventLog.WriteEntry("MyEventSource", ex.StackTrace, System.Diagnostics.EventLogEntryType.Warning);
            }
        }