Beispiel #1
0
        public static void probarDocElectronico()
        {
            DocumentoElectronico docElec = null;

            docElec = DocumentoElectronico.crearDocumentoElectronico(2);
            //docElec.calcularTotal();
            anaularDocumento(docElec);

            IOperacionDocSoporte doc = null;

            doc = new FacturaVentaNacional();
            //obtenerFormaPago(doc);

            //MALA PRACTICA (sin polimorfismo)
            FacturaVentaNacional fvn = null;

            fvn = new FacturaVentaNacional();
            //fvn.calcularTotal();
            //
            NotaCredito nc = null;

            nc = new NotaCredito();
            //nc.calcularTotal();
            //
            //para ND
        }
Beispiel #2
0
        public DocumentoElectronico ObtenerXml()
        {
            DocumentoElectronico datos = new DocumentoElectronico();

            XmlDocument xDoc = new XmlDocument();

            //La ruta del documento XML permite rutas relativas
            //respecto del ejecutable!

            xDoc.Load(@"H:\ArchivosXml\RetencionPrueba\IEXT_00000000000000219571_2017821_1540.xml");

            XmlNodeList personas = xDoc.GetElementsByTagName("autorizacion");

            XmlNodeList lista = ((XmlElement)personas[0]).GetElementsByTagName("autorizacion");

            foreach (XmlElement nodo in lista)
            {
                int i = 0;

                XmlNodeList nCodigoDocumento = nodo.GetElementsByTagName("codDoc");

                XmlNodeList nEstablecimiento = nodo.GetElementsByTagName("estab");

                XmlNodeList nPuntoEmision = nodo.GetElementsByTagName("ptoEmi");
                XmlNodeList nSecuencial   = nodo.GetElementsByTagName("secuencial");

                Console.WriteLine("Elemento nombre ... {0} {1} {2} {3}", nCodigoDocumento[i].InnerText, nEstablecimiento[i].InnerText, nPuntoEmision[i++].InnerText, nSecuencial[i].InnerText);
            }
            return(datos);
        }
Beispiel #3
0
        public DocumentoElectronico LeerXML(string ruta)
        {
            DocumentoElectronico _respuesta = new DocumentoElectronico();
            int codigoRetencion             = 0;

            try
            {
                XDocument xdoc = XDocument.Load(ruta);

                var node    = xdoc.DescendantNodes().Single(el => el.NodeType == XmlNodeType.CDATA);
                var content = node.Parent.Value.Trim();

                var xdoc_cdata = XDocument.Parse(content);

                //Run query
                var comp = from info in xdoc_cdata.Descendants("comprobanteRetencion")
                           select new
                {
                    TipoDocumento             = info.Descendants("infoTributaria").Single().Element("codDoc").Value,
                    Autorizacion              = xdoc.Element("autorizacion").Element("numeroAutorizacion").Value,
                    ClaveAcceso               = info.Descendants("infoTributaria").Single().Element("claveAcceso").Value,
                    Establecimiento           = info.Descendants("infoTributaria").Single().Element("estab").Value,
                    PuntoEmision              = info.Descendants("infoTributaria").Single().Element("ptoEmi").Value,
                    FechaEmision              = info.Descendants("infoCompRetencion").Single().Element("fechaEmision").Value,
                    NumeroSecuencia           = info.Descendants("infoTributaria").Single().Element("secuencial").Value,
                    BaseImponibleFuente       = info.Descendants("impuestos").Descendants("impuesto").Where(s => s.Element("codigo").Value == "1" && s.Element("codigoRetencion").Value == "322").Select(t => t.Element("baseImponible").Value).SingleOrDefault(), //impuestos codigo 1
                    BaseImponibleIva          = info.Descendants("impuestos").Descendants("impuesto").Where(s => s.Element("codigo").Value == "2").Select(t => t.Element("baseImponible").Value).SingleOrDefault(),                                                //impuestos codigo 2
                    PorcentajeRetencionFuente = info.Descendants("impuestos").Descendants("impuesto").Where(s => s.Element("codigo").Value == "1" && s.Element("codigoRetencion").Value == "322").Select(t => t.Element("porcentajeRetener").Value).SingleOrDefault(),
                    PorcentajeRetencionIva    = info.Descendants("impuestos").Descendants("impuesto").Where(s => s.Element("codigo").Value == "2").Select(t => t.Element("porcentajeRetener").Value).SingleOrDefault(),
                    ValorRetencionFuente      = info.Descendants("impuestos").Descendants("impuesto").Where(s => s.Element("codigo").Value == "1" && s.Element("codigoRetencion").Value == "322").Select(t => t.Element("valorRetenido").Value).SingleOrDefault(),
                    ValorRetencionIva         = info.Descendants("impuestos").Descendants("impuesto").Where(s => s.Element("codigo").Value == "2").Select(t => t.Element("valorRetenido").Value).SingleOrDefault()
                };

                if (comp != null)
                {
                    _respuesta.TipoDocumento             = int.Parse(comp.Select(x => x.TipoDocumento).FirstOrDefault());
                    _respuesta.Autorizacion              = (comp.Select(x => x.Autorizacion).FirstOrDefault());
                    _respuesta.ClaveAcceso               = (comp.Select(x => x.ClaveAcceso).FirstOrDefault());
                    _respuesta.Establecimiento           = (comp.Select(x => x.Establecimiento).FirstOrDefault());
                    _respuesta.PuntoEmision              = (comp.Select(x => x.PuntoEmision).FirstOrDefault());
                    _respuesta.FechaEmision              = (comp.Select(x => x.FechaEmision).FirstOrDefault());
                    _respuesta.NumeroSecuencia           = (comp.Select(x => x.NumeroSecuencia).FirstOrDefault());
                    _respuesta.BaseImponibleFuente       = (comp.Select(x => x.BaseImponibleFuente).FirstOrDefault() != null ? float.Parse(comp.Select(x => x.BaseImponibleFuente).FirstOrDefault()) : 0);
                    _respuesta.BaseImponibleIva          = (comp.Select(x => x.BaseImponibleIva).FirstOrDefault() != null ? float.Parse(comp.Select(x => x.BaseImponibleIva).FirstOrDefault()) : 0);
                    _respuesta.PorcentajeRetencionFuente = (comp.Select(x => x.PorcentajeRetencionFuente).FirstOrDefault() != null ? float.Parse(comp.Select(x => x.PorcentajeRetencionFuente).FirstOrDefault()) : 0);
                    _respuesta.PorcentajeRetencionIva    = (comp.Select(x => x.PorcentajeRetencionIva).FirstOrDefault() != null ? float.Parse(comp.Select(x => x.PorcentajeRetencionIva).FirstOrDefault()) : 0);
                    _respuesta.ValorRetencionFuente      = (comp.Select(x => x.ValorRetencionFuente).FirstOrDefault() != null ? float.Parse(comp.Select(x => x.ValorRetencionFuente).FirstOrDefault()) : 0);
                    _respuesta.ValorRetencionIva         = (comp.Select(x => x.ValorRetencionIva).FirstOrDefault() != null ? float.Parse(comp.Select(x => x.ValorRetencionIva).FirstOrDefault()) : 0);
                }
            }
            catch (Exception ex)
            {
                using (StreamWriter writer = new StreamWriter("C:\\log_interop.txt", true))
                {
                    writer.WriteLine("Error en la carga del archivo xml " + ex.Message);
                }
            }

            return(_respuesta);
        }
Beispiel #4
0
        public string Create(DocumentoElectronico documento)
        {
            string resultado = "";

            try
            {
                var invoice    = CFacturaXml.Generar(documento);
                var serializer = new XmlSerializer(invoice.GetType());

                using (var memStr = new MemoryStream())
                {
                    using (var stream = new StreamWriter(memStr))
                    {
                        serializer.Serialize(stream, invoice);
                    }
                    resultado = Convert.ToBase64String(memStr.ToArray());
                }

                RutaArchivo = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                           documento.IdDocumento + ".xml");

                File.WriteAllBytes(RutaArchivo, Convert.FromBase64String(resultado));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(resultado);
        }
Beispiel #5
0
        public static MemoryStream generarPDF(string clave)
        {
            var reportStream = new MemoryStream();

            using (var conexion = new DataModelFE())
            {
                string xml     = "";
                string mensaje = "";
                if (clave.Substring(29, 2) == TipoDocumento.PROFORMA)
                {
                    WSRecepcionPOSTProforma dato = conexion.WSRecepcionPOSTProforma.Find(clave);
                    xml     = dato.comprobanteXml;
                    mensaje = dato.mensaje;
                }
                else
                {
                    WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(clave);
                    xml     = dato.comprobanteXml;
                    mensaje = dato.mensaje;
                }

                DocumentoElectronico documento = (DocumentoElectronico)EncodeXML.XMLUtils.getObjetcFromXML(xml);
                Empresa empresa = conexion.Empresa.Find(documento.emisor.identificacion.numero);

                if (empresa != null && "EN".Equals(empresa.idioma))
                {
                    using (RptComprobanteEN report = new RptComprobanteEN())
                    {
                        object dataSource = UtilidadesReporte.cargarObjetoImpresion(documento, mensaje, empresa);
                        report.objectDataSource1.DataSource = dataSource;
                        string enviroment_url = ConfigurationManager.AppSettings["ENVIROMENT_URL"].ToString();
                        report.xrBarCode1.Text = (enviroment_url + documento.clave).ToUpper();
                        if (empresa != null && empresa.logo != null)
                        {
                            report.pbLogo.Image = byteArrayToImage(empresa.logo);
                        }
                        report.CreateDocument();
                        report.ExportToPdf(reportStream);
                    }
                }
                else
                {
                    using (RptComprobante report = new RptComprobante())
                    {
                        object dataSource = UtilidadesReporte.cargarObjetoImpresion(documento, mensaje, empresa);
                        report.objectDataSource1.DataSource = dataSource;
                        string enviroment_url = ConfigurationManager.AppSettings["ENVIROMENT_URL"].ToString();
                        report.xrBarCode1.Text = (enviroment_url + documento.clave).ToUpper();
                        if (empresa != null && empresa.logo != null)
                        {
                            report.pbLogo.Image = byteArrayToImage(empresa.logo);
                        }
                        report.CreateDocument();
                        report.ExportToPdf(reportStream);
                    }
                }
            }
            return(reportStream);
        }
Beispiel #6
0
        public void PostTest()
        {
            var documento = new DocumentoElectronico
            {
                Emisor = new Contribuyente
                {
                    NroDocumento    = "20100070970",
                    TipoDocumento   = "6",
                    Direccion       = "CAL.MORELLI NRO. 181 INT. P-2",
                    Urbanizacion    = "-",
                    Departamento    = "LIMA",
                    Provincia       = "LIMA",
                    Distrito        = "SAN BORJA",
                    NombreComercial = "PLAZA VEA",
                    NombreLegal     = "SUPERMERCADOS PERUANOS SOCIEDAD ANONIMA"
                },
                Receptor = new Contribuyente
                {
                    NroDocumento  = "20100039207",
                    TipoDocumento = "6",
                    NombreLegal   = "RANSA COMERCIAL S.A."
                },
                IdDocumento       = "FF11-001",
                FechaEmision      = DateTime.Today.AddDays(-5).ToString("yyyy-MM-dd"),
                Moneda            = "PEN",
                MontoEnLetras     = "SON CIENTO DIECIOCHO SOLES CON 0/100",
                CalculoIgv        = 0.18m,
                CalculoIsc        = 0.10m,
                CalculoDetraccion = 0.04m,
                TipoDocumento     = "01",
                TotalIgv          = 18,
                TotalVenta        = 118,
                Gravadas          = 100,
                Items             = new List <DetalleDocumento>()
                {
                    new DetalleDocumento
                    {
                        Id                = 1,
                        Cantidad          = 5,
                        PrecioReferencial = 20,
                        PrecioUnitario    = 20,
                        TipoPrecio        = "01",
                        CodigoItem        = "1234234",
                        Descripcion       = "Arroz Costeño",
                        UnidadMedida      = "KG",
                        Impuesto          = 18,
                        TipoImpuesto      = "10", // Gravada
                        TotalVenta        = 100,
                        Suma              = 100
                    }
                }
            };

            var controller = new GenerarFacturaController();

            var response = controller.Post(documento);

            Assert.IsTrue(response.Exito);
        }
        protected async void btnEnvioManual_Click(object sender, EventArgs e)
        {
            try
            {
                if (TipoDocumento.PENDIENTE.ToString().Equals(Session["indEstado"].ToString()) ||
                    TipoDocumento.ENVIADO.ToString().Equals(Session["indEstado"].ToString()))
                {
                    Thread.CurrentThread.CurrentCulture = Utilidades.getCulture();

                    using (var conexion = new DataModelFE())
                    {
                        string               clave     = Session["clave"].ToString();
                        WSRecepcionPOST      dato      = conexion.WSRecepcionPOST.Find(clave);
                        string               xml       = dato.comprobanteXml;
                        DocumentoElectronico documento = (DocumentoElectronico)EncodeXML.XMLUtils.getObjetcFromXML(xml);
                        documento.verificaDatosParaXML();

                        EmisorReceptorIMEC elEmisor     = ((EmisorReceptorIMEC)Session["elEmisor"]);
                        string             responsePost = await Services.enviarDocumentoElectronico(false, documento, elEmisor, dato.tipoDocumento, Session["usuario"].ToString());

                        string correoElectronico = XMLUtils.buscarValorEtiquetaXML("Receptor", "CorreoElectronico", xml);

                        if (responsePost.Equals("Success"))
                        {
                            this.alertMessages.Attributes["class"] = "alert alert-info";
                            this.alertMessages.InnerText           = String.Format("Documento #{0} enviada.", dato.numeroConsecutivo);

                            if (!string.IsNullOrWhiteSpace(correoElectronico))
                            {
                                Utilidades.sendMail(Session["emisor"].ToString(), correoElectronico,
                                                    string.Format("{0} - {1}", dato.numeroConsecutivo, dato.receptor.nombre),
                                                    Utilidades.mensageGenerico(), "Documento Electrónico", xml, dato.numeroConsecutivo, dato.clave, null);
                            }
                        }
                        else if (responsePost.Equals("Error"))
                        {
                            this.alertMessages.Attributes["class"] = "alert alert-danger";
                            this.alertMessages.InnerText           = String.Format("Documento #{0} con errores.", dato.numeroConsecutivo);
                        }
                        else
                        {
                            this.alertMessages.Attributes["class"] = "alert alert-warning";
                            this.alertMessages.InnerText           = String.Format("Documento #{0} pendiente de envío", dato.numeroConsecutivo);
                        }
                    }
                }
                else
                {
                    this.alertMessages.Attributes["class"] = "alert alert-danger";
                    this.alertMessages.InnerText           = String.Format("Documento eléctronico no se encuentra PENDIENTE");
                }
            }
            catch (Exception ex)
            {
                this.alertMessages.InnerText = Utilidades.validarExepcionSQL(ex);
            }
        }
Beispiel #8
0
 public FrmDocumento()
 {
     InitializeComponent();
     _documento = new DocumentoElectronico
     {
         FechaEmision = DateTime.Today.ToShortDateString(),
         IdDocumento  = "FF11-00001"
     };
     Inicializar();
 }
Beispiel #9
0
 public async Task <IActionResult> Put(string organization, int id, [FromBody] DocumentoElectronico model)
 {
     try
     {
         return(Ok(await _service.Put(organization, model)));
     }
     catch (Exception ex)
     {
         throw new SuperFactException(ex.Message, ex.InnerException);
     }
 }
Beispiel #10
0
        public FrmPercepcion(string nombrereporte, DocumentoElectronico lista)
        {
            try
            {
                InitializeComponent();
                List <Contribuyente>       Emisor     = new List <Contribuyente>();
                ClsDatosReportes           cabecera   = new ClsDatosReportes();
                List <ClsDatosReportes>    valores    = new List <ClsDatosReportes>();
                List <Contribuyente>       Receptor   = new List <Contribuyente>();
                List <DocumentoPercepcion> Percepcion = new List <DocumentoPercepcion>();


                if (lista.DocumentoPercepcion.Moneda == "PEN")
                {
                    cabecera.MonedaLetra = "SOLES";
                    cabecera.Moneda      = "S/";
                }
                else
                {
                    if (lista.DocumentoPercepcion.Moneda == "USD")
                    {
                        cabecera.MonedaLetra = "DOLARES AMERICANOS";
                        cabecera.Moneda      = "$";
                    }
                    else
                    {
                        if (lista.DocumentoPercepcion.Moneda == "EUR")
                        {
                            cabecera.MonedaLetra = "EUROS";
                            cabecera.Moneda      = "€";
                        }
                    }
                }
                cabecera.IdDocumento   = lista.DocumentoPercepcion.IdDocumento;
                cabecera.FechaEmision  = lista.DocumentoPercepcion.FechaEmision;
                cabecera.MontoEnLetras = lista.MontoEnLetras;
                valores.Add(cabecera);
                Emisor.Add(lista.DocumentoPercepcion.Emisor);
                Receptor.Add(lista.DocumentoPercepcion.Receptor);
                Percepcion.Add(lista.DocumentoPercepcion);



                this.rptact   = nombrereporte;
                this.empresa  = Emisor;
                this.general  = valores;
                this.receptor = Receptor;
                this.otros    = valores;
                this.item     = lista.DocumentoPercepcion.DocumentosRelacionados;
                percepcion    = Percepcion;
            }
            catch (Exception a) { MessageBox.Show(a.Message); }
        }
        public async Task <EnviarDocumentoResponse> Generar(string organization, DocumentoElectronico model)
        {
            EmpresaModel empresa = await _repositoryempresa.Get(organization);

            model.Emisor = HelperTo.ToEmisor(empresa);
            IEstructuraXml invoice     = _documentoXml.Generar(model);
            string         XmlSinFirma = await _serializador.GenerarXml(invoice);

            CertificadoDigitalModel certificado = await _repositorycert.GetCertificate(organization);

            FirmadoRequest  firmado       = HelperTo.ToSignedModel(certificado, XmlSinFirma, false);
            FirmadoResponse responseFirma = await _certificador.FirmarXml(firmado);

            ParametroEmpresaModel parametro = await _repositoryparam.GetConfiguration(certificado.Empresa);

            EnviarDocumentoRequest request = HelperTo.ToSendDocument(model, parametro, responseFirma);

            File.WriteAllBytes("invoice.xml", Convert.FromBase64String(responseFirma.TramaXmlFirmado));

            EnviarDocumentoResponse response = new EnviarDocumentoResponse();
            var nombreArchivo = $"{request.Ruc}-{request.TipoDocumento}-{request.IdDocumento}";
            var tramaZip      = await _serializador.GenerarZip(request.TramaXmlFirmado, nombreArchivo);

            _servicioSunatDocumentos.Inicializar(new ParametrosConexion
            {
                Ruc         = request.Ruc,
                UserName    = request.UsuarioSol,
                Password    = request.ClaveSol,
                EndPointUrl = request.EndPointUrl
            });

            RespuestaSincrono resultado = _servicioSunatDocumentos.EnviarDocumento(new DocumentoSunat
            {
                TramaXml      = tramaZip,
                NombreArchivo = $"{nombreArchivo}.zip"
            });

            if (!resultado.Exito)
            {
                response.Exito        = false;
                response.MensajeError = resultado.MensajeError;
            }
            else
            {
                response = await _serializador.GenerarDocumentoRespuesta(resultado.ConstanciaDeRecepcion);

                File.WriteAllBytes("cdr_invoice.zip", Convert.FromBase64String(response.TramaZipCdr));
                // Quitamos la R y la extensión devueltas por el Servicio.
                response.NombreArchivo = nombreArchivo;
            }
            //guardar la respuesta
            return(response);
        }
Beispiel #12
0
        public static EnviarDocumentoRequest ToSendDocument(DocumentoElectronico model, ParametroEmpresaModel parametro, FirmadoResponse responseFirma)
        {
            EnviarDocumentoRequest request = new EnviarDocumentoRequest();

            request.Ruc             = model.Emisor.NroDocumento;
            request.UsuarioSol      = parametro.UsuarioSol;
            request.ClaveSol        = parametro.ClaveSol;
            request.EndPointUrl     = "";
            request.IdDocumento     = model.IdDocumento;
            request.TipoDocumento   = model.TipoDocumento;
            request.TramaXmlFirmado = responseFirma.TramaXmlFirmado;

            return(request);
        }
Beispiel #13
0
        public async Task <HttpResponseMessage> recepcionmesajehacienda()
        {
            string responsePost = "";

            try
            {
                Thread.CurrentThread.CurrentCulture = Utilidades.getCulture();
                string xml = await Request.Content.ReadAsStringAsync();

                DocumentoElectronico documento = (DocumentoElectronico)EncodeXML.XMLUtils.getObjetcFromXML(xml);
                documento.verificaDatosParaXML();

                EmisorReceptorIMEC elEmisor = null;
                using (var conexion = new DataModelFE())
                {
                    long id = long.Parse(documento.emisor.identificacion.numero);
                    elEmisor = conexion.EmisorReceptorIMEC.Find(id.ToString());
                    if (elEmisor == null)
                    {
                        //return "Emisor no registrado!!!";
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Emisor no registrado!!!"));
                        //return Ok("Emisor no registrado!!!");
                    }
                }
                responsePost = await ServicesHacienda.enviarDocumentoElectronico(false, documento, elEmisor, documento.tipoDocumento, Usuario.USUARIO_AUTOMATICO);
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                                    .SelectMany(x => x.ValidationErrors)
                                    .Select(x => x.ErrorMessage);
                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);
                // Throw a new DbEntityValidationException with the improved exception message.
                //return fullErrorMessage;
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, fullErrorMessage));
                //return Ok(fullErrorMessage);
            }
            catch (Exception ex)
            {
                //return ex.Message;
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex.Message));
                //return Ok(ex.Message);
            }
            //return responsePost;
            return(Request.CreateErrorResponse(HttpStatusCode.NotFound, responsePost));
            //return Ok(responsePost);
        }
Beispiel #14
0
        public async Task <IActionResult> Post(string organization, [FromBody] DocumentoElectronico model)
        {
            EnviarDocumentoResponse response = new EnviarDocumentoResponse();

            try
            {
                response = await _service.Generar(organization, model);

                response.Exito = true;
                return(Ok(response));
            }
            catch (Exception ex)
            {
                throw new SuperFactException(ex.Message, ex.InnerException);
            }
        }
        public FrmBoletas(string nombrereporte, DocumentoElectronico lista)
        {
            InitializeComponent();
            List <Contribuyente>    Emisor   = new List <Contribuyente>();
            ClsDatosReportes        cabecera = new ClsDatosReportes();
            List <ClsDatosReportes> valores  = new List <ClsDatosReportes>();
            List <Contribuyente>    Receptor = new List <Contribuyente>();

            if (lista.Moneda == "PEN")
            {
                cabecera.MonedaLetra = "SOLES";
                cabecera.Moneda      = "S/";
            }
            else
            {
                if (lista.Moneda == "USD")
                {
                    cabecera.MonedaLetra = "DOLARES AMERICANOS";
                    cabecera.Moneda      = "$";
                }
            }
            cabecera.IdDocumento    = lista.IdDocumento;
            cabecera.FechaEmision   = lista.FechaEmision;
            cabecera.Gravadas       = lista.Gravadas;
            cabecera.Inafectas      = lista.Inafectas;
            cabecera.Gratuitas      = lista.Gratuitas;
            cabecera.Exoneradas     = lista.Exoneradas;
            cabecera.TotalIgv       = lista.TotalIgv;
            cabecera.TotalVenta     = lista.TotalVenta;
            cabecera.SubTotalVentas = lista.SubTotalVenta;
            cabecera.MontoEnLetras  = lista.MontoEnLetras;

            cabecera.NumeroCajas = lista.Cajas;
            cabecera.Total2      = lista.Total2;
            cabecera.Glosa       = lista.Glosa;

            valores.Add(cabecera);
            Emisor.Add(lista.Emisor);
            Receptor.Add(lista.Receptor);

            this.rptact   = nombrereporte;
            this.lst      = lista.Items;
            this.empresa  = Emisor;
            this.general  = valores;
            this.receptor = Receptor;
            this.otros    = valores;
        }
Beispiel #16
0
        XtraReport CreateReport(string clave)
        {
            XtraReport report = null;

            using (var conexion = new DataModelFE())
            {
                WSRecepcionPOST dato = conexion.WSRecepcionPOST.Where(x => x.clave == clave).FirstOrDefault();
                string          xml  = dato.comprobanteXml;

                //RptComprobante reportES = new RptComprobante();
                //RptComprobanteEN reportEN = new RptComprobanteEN();

                RptFacturacionElectronicaRollPaper   reportES = new RptFacturacionElectronicaRollPaper();
                RptFacturacionElectronicaRollPaperEN reportEN = new RptFacturacionElectronicaRollPaperEN();

                DocumentoElectronico documento = (DocumentoElectronico)EncodeXML.XMLUtils.getObjetcFromXML(xml);
                Empresa empresa = conexion.Empresa.Find(documento.emisor.identificacion.numero);

                if (empresa != null && "EN".Equals(empresa.idioma))
                {
                    object dataSource = UtilidadesReporte.cargarObjetoImpresion(documento, dato.mensaje, empresa);
                    reportEN.objectDataSource1.DataSource = dataSource;
                    string enviroment_url = ConfigurationManager.AppSettings["ENVIROMENT_URL"].ToString();
                    reportEN.xrBarCode1.Text = (enviroment_url + documento.clave).ToUpper();
                    //if (empresa != null && empresa.logo != null)
                    //{
                    //    reportEN.pbLogo.Image = UtilidadesReporte.byteArrayToImage(empresa.logo);
                    //}
                    reportEN.CreateDocument();
                    report = reportEN;
                }
                else
                {
                    object dataSource = UtilidadesReporte.cargarObjetoImpresion(documento, dato.mensaje, empresa);
                    reportES.objectDataSource1.DataSource = dataSource;
                    string enviroment_url = ConfigurationManager.AppSettings["ENVIROMENT_URL"].ToString();
                    reportES.xrBarCode1.Text = (enviroment_url + documento.clave).ToUpper();
                    //if (empresa != null && empresa.logo != null)
                    //{
                    //    reportES.pbLogo.Image = UtilidadesReporte.byteArrayToImage(empresa.logo);
                    //}
                    reportES.CreateDocument();
                    report = reportES;
                }
            }
            return(report);
        }
Beispiel #17
0
        private static void Prueba_DocElecDIAN()
        {
            short   opcionDocElect     = 0;
            decimal porcentajeComision = 0.0M;
            decimal comision           = 0.0M;
            DocumentoElectronico de    = null;

            Console.Write("Entre tipo Doc Electronico [1-FVN,2-NC]:");
            if (!Int16.TryParse(Console.ReadLine(), out opcionDocElect))
            {
                throw new ArgumentException("Valor para OPCION no valida!");
            }
            Console.Write("Entre % de comision:");
            if (!Decimal.TryParse(Console.ReadLine(), out porcentajeComision))
            {
                throw new ArgumentException("Valor para COMISION no valida!");
            }

            //de = new DocumentoElectronico(); //REMAAAAAL!!!
            //BUENA PRACTICA!
            de       = DocumentoElectronico.CrearDocumentoElctronico(opcionDocElect);
            comision = CalcularTotalComision(de, porcentajeComision);

            //Un RE-JUNIOR, Caso 1°
            FacturaVentaNacional facVenNac   = null;
            NotaCredito          notaCredito = null;

            if (opcionDocElect == 1)  //FVN
            {
                facVenNac = new FacturaVentaNacional();
                facVenNac.CalcularTotal();
                comision = facVenNac.total * 0.20M;
            }
            else if (opcionDocElect == 2)    //NC
            {
                notaCredito = new NotaCredito();
                notaCredito.CalcularTotal();
                comision = notaCredito.total * 0.10M;
            }
            else if (opcionDocElect == 3)    //ND
            {
                notaCredito = new NotaCredito();
                notaCredito.CalcularTotal();
                comision = notaCredito.total * 0.50M;
            }
        }
        public FrmND(string nombrereporte, DocumentoElectronico lista, clsUsuario usuario)
        {
            InitializeComponent();
            List <Contribuyente>    Emisor   = new List <Contribuyente>();
            ClsDatosReportes        cabecera = new ClsDatosReportes();
            List <ClsDatosReportes> valores  = new List <ClsDatosReportes>();
            List <Contribuyente>    Receptor = new List <Contribuyente>();

            if (lista.Moneda == "PEN")
            {
                cabecera.MonedaLetra = "SOLES";
                cabecera.Moneda      = "S/";
            }
            else
            {
                if (lista.Moneda == "USD")
                {
                    cabecera.MonedaLetra = "DOLARES AMERICANOS";
                    cabecera.Moneda      = "$";
                }
            }
            cabecera.IdDocumento    = lista.IdDocumento;
            cabecera.FechaEmision   = lista.FechaEmision + " " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + " " + DateTime.Now.ToString("tt", CultureInfo.InvariantCulture);;
            cabecera.Gravadas       = lista.Gravadas;
            cabecera.Inafectas      = lista.Inafectas;
            cabecera.Gratuitas      = lista.Gratuitas;
            cabecera.Exoneradas     = lista.Exoneradas;
            cabecera.TotalIgv       = lista.TotalIgv;
            cabecera.TotalVenta     = lista.TotalVenta;
            cabecera.MontoEnLetras  = lista.MontoEnLetras;
            cabecera.SubTotalVentas = lista.SubTotalVenta;
            cabecera.Cajero         = usuario.Nombre;
            valores.Add(cabecera);
            Emisor.Add(lista.Emisor);
            Receptor.Add(lista.Receptor);

            //Discrepa.Add();

            this.rptact       = nombrereporte;
            this.lst          = lista.Items;
            this.empresa      = Emisor;
            this.general      = valores;
            this.receptor     = Receptor;
            this.discrepancia = lista.Discrepancias;
            this.otros        = valores;
        }
Beispiel #19
0
        public async Task <DocumentoResponse> Generar([FromBody] DocumentoElectronico documento)
        {
            var response = new DocumentoResponse();

            try {
                var invoice = _documentoXml.Generar(documento);
                response.TramaXmlSinFirma = await _serializador.GenerarXml(invoice);

                response.Exito = true;
            }
            catch (Exception ex) {
                response.MensajeError = ex.Message;
                response.Pila         = ex.StackTrace;
                response.Exito        = false;
            }

            return(response);
        }
        public DocumentoResponse Post(DocumentoElectronico documento, bool sincrono)
        {
            var response = new DocumentoResponse();

            try
            {
                var invoice = _documentoXml.Generar(documento);
                response.TramaXmlSinFirma = _serializador.GenerarXml(invoice, sincrono);
                response.Exito            = true;
            }
            catch (Exception ex)
            {
                response.MensajeError = ex.Message;
                response.Pila         = ex.StackTrace;
                response.Exito        = false;
            }

            return(response);
        }
        public FrmDetalleDocumento(DetalleDocumento detalle, DocumentoElectronico documento)
        {
            InitializeComponent();
            _detalle   = detalle;
            _documento = documento;

            detalleDocumentoBindingSource.DataSource = detalle;
            detalleDocumentoBindingSource.ResetBindings(false);

            Load += (s, e) =>
            {
                using (var ctx = new OpenInvoicePeruDb())
                {
                    tipoImpuestoBindingSource.DataSource = ctx.TipoImpuestos.ToList();
                    tipoImpuestoBindingSource.ResetBindings(false);

                    tipoPrecioBindingSource.DataSource = ctx.TipoPrecios.ToList();
                    tipoPrecioBindingSource.ResetBindings(false);
                }
            };
        }
Beispiel #22
0
        private void btnGenerar_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (_frmDocumento == null)
                {
                    if (string.IsNullOrEmpty(txtNroRuc.Text))
                    {
                        _frmDocumento = new FrmDocumento();
                    }
                    else
                    {
                        var documento = new DocumentoElectronico
                        {
                            Emisor       = { NroDocumento = txtNroRuc.Text },
                            FechaEmision = DateTime.Today.ToShortDateString()
                        };
                        _frmDocumento = new FrmDocumento(documento);
                    }
                }
                var rpta = _frmDocumento.ShowDialog(this);

                if (rpta != DialogResult.OK)
                {
                    return;
                }

                txtSource.Text           = _frmDocumento.RutaArchivo;
                txtSerieCorrelativo.Text = _frmDocumento.IdDocumento;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Beispiel #23
0
        private static decimal CalcularTotalComision(DocumentoElectronico documentoElectronico, decimal porcentajeComsion)
        {
            decimal comision = 0.0M;
            FacturaVentaNacional facVenNac   = null;
            NotaCredito          notaCredito = null;

            documentoElectronico.CalcularTotal();
            comision = documentoElectronico.total * porcentajeComsion;

            if (documentoElectronico.GetType() == typeof(FacturaVentaNacional))
            {
                facVenNac = (FacturaVentaNacional)documentoElectronico;
                facVenNac.CalcularCUFE();
            }
            else if (documentoElectronico.GetType() == typeof(NotaCredito))
            {
                notaCredito = (NotaCredito)documentoElectronico;
                notaCredito.CalcularCUDE();
            }

            return(comision);
        }
        public DocumentoResponse Post([FromBody] DocumentoElectronico documento)
        {
            var response = new DocumentoResponse();

            try
            {
                var notaCredito = Generador.GenerarCreditNote(documento);

                var serializador = new Serializador();

                response.TramaXmlSinFirma = serializador.GenerarXml(notaCredito);
                response.Exito            = true;
            }
            catch (Exception ex)
            {
                response.MensajeError = ex.Message;
                response.Pila         = ex.StackTrace;
                response.Exito        = false;
            }

            return(response);
        }
Beispiel #25
0
        /// <summary>
        /// Encargado de Cargar PDF a documento Electrónico
        /// </summary>
        /// <param name="docCargado"></param>
        /// <param name="respuestaCargaPDF"></param>
        /// <param name="summary"></param>
        /// <param name="attachment"></param>
        /// <param name="mime"></param>
        private void CargarPDF(DocumentoElectronico docCargado, out SVCDocumentosElectronicos.MensajeWCFOfBoolean respuestaCargaPDF, IMessageSummary summary, BodyPartBasic attachment)
        {
            MimePart mime = null;

            this.logger.LogWriter.Write(new LogEntry()
            {
                Message = String.Format("Se encuentra PDF adjunto para documento N°:{0}", docCargado.Id.ToString()), Categories = new List <string> {
                    "General"
                }, Priority = 1, ProcessName = Logger.PROCESS_NAME
            });
            mime = (MimePart)inbox.GetBodyPart(summary.UniqueId, attachment);
            using (MemoryStream stream = new MemoryStream())
            {
                mime.Content.DecodeTo(stream);
                stream.Position   = 0;
                respuestaCargaPDF = documentClient.CargarPDFCompra(docCargado.Id, stream.ToArray(), "pdf", -2);
                if (respuestaCargaPDF.CodigoError != Logger.CODIGO_EXITOSO)
                {
                    this.logger.LogWriter.Write(new LogEntry()
                    {
                        Message = String.Format("Imposible cargar PDF adjunto para documento N°:{0}, error:{1}", docCargado.Id.ToString(), respuestaCargaPDF.MensajeError), Categories = new List <string> {
                            "General"
                        }, Priority = 1, ProcessName = Logger.PROCESS_NAME
                    });
                }
                else
                {
                    this.logger.LogWriter.Write(new LogEntry()
                    {
                        Message = String.Format("PDF adjunto cargado para documento N°:{0}", docCargado.Id.ToString()), Categories = new List <string> {
                            "General"
                        }, Priority = 1, ProcessName = Logger.PROCESS_NAME
                    });
                }
            }
        }
Beispiel #26
0
 public FrmDocumento(DocumentoElectronico documento)
 {
     InitializeComponent();
     _documento = documento;
     Inicializar();
 }
Beispiel #27
0
        private DocumentoElectronico ArmaDocumentoEnviarWS(DocumentoVentaGP documentoGP)
        {
            DocEnviarWS = new DocumentoElectronico();
            int     i           = 0; // Variable para loopear
            int     correlativo = 1; // Variable para corre de productos;
            Boolean DescItemIGV = true;

            debug_xml = "";

            //Seccion emisor
            DocEnviarWS.emisor = new Emisor();

            DocEnviarWS.emisor.ruc = documentoGP.DocVenta.emisorNroDoc;
            //DocEnviarWS.emisor.nombreComercial = documentoGP.DocVenta.emisorNombre;
            //DocEnviarWS.emisor.lugarExpedicion = documentoGP.DocVenta.emmisor**

            /*DocEnviarWS.emisor.domicilioFiscal = documentoGP.DocVenta.emisorDireccion;
             * DocEnviarWS.emisor.urbanizacion = documentoGP.DocVenta.emisorUrbanizacion;
             * DocEnviarWS.emisor.distrito = documentoGP.DocVenta.emisorDistrito;
             * DocEnviarWS.emisor.provincia = documentoGP.DocVenta.emisorProvincia;
             * DocEnviarWS.emisor.departamento = documentoGP.DocVenta.emisorDepartamento;
             * DocEnviarWS.emisor.codigoPais = documentoGP.DocVenta.emisorCodPais;
             * DocEnviarWS.emisor.ubigeo = documentoGP.DocVenta.emisorUbigeo;*/

            debug_xml = "<EMISOR>" + DocEnviarWS.emisor.ruc + "\r\n";

            // SECCION RECEPTOR
            DocEnviarWS.receptor              = new Receptor();
            DocEnviarWS.receptor.email        = documentoGP.DocVenta.emailTo;
            DocEnviarWS.receptor.notificar    = documentoGP.DocVenta.emailTo.Trim() == string.Empty ? "NO" : "SI";
            DocEnviarWS.receptor.numDocumento = documentoGP.DocVenta.receptorNroDoc;
            DocEnviarWS.receptor.direccion    = documentoGP.DocVenta.receptorDireccion;
            DocEnviarWS.receptor.departamento = documentoGP.DocVenta.receptorCiudad;
            //DocEnviarWS.receptor.distrito = documentoGP.DocVenta.recep
            DocEnviarWS.receptor.pais        = documentoGP.DocVenta.receptorPais;
            DocEnviarWS.receptor.provincia   = documentoGP.DocVenta.receptorProvincia;
            DocEnviarWS.receptor.razonSocial = documentoGP.DocVenta.receptorNombre;
            //     DocEnviarWS.receptor.telefono = documentoGP.DocVenta.
            DocEnviarWS.receptor.tipoDocumento = documentoGP.DocVenta.receptorTipoDoc;
            //    DocEnviarWS.receptor.ubigeo = documentoGP.DocVenta.rece

            debug_xml = debug_xml + "<RECEPTOR>" + DocEnviarWS.receptor.tipoDocumento + ":" + DocEnviarWS.receptor.numDocumento + "\r\n";
            debug_xml = debug_xml + "   <RazonSocial>" + DocEnviarWS.receptor.razonSocial + "\r\n";

            // SECCION COMROBANTE
            if (!string.IsNullOrEmpty(documentoGP.DocVenta.tipoOperacion))
            {
                DocEnviarWS.codigoTipoOperacion = documentoGP.DocVenta.tipoOperacion;
            }
            else
            {
                DocEnviarWS.codigoTipoOperacion = "0101";
            }
            DocEnviarWS.correlativo = documentoGP.DocVenta.numero;
            //DocEnviarWS.correlativo = "10000106"; // se usa para reenviar comprobante.
            DocEnviarWS.fechaEmision     = documentoGP.DocVenta.fechaEmision.ToString("yyyy-MM-dd");
            DocEnviarWS.fechaVencimiento = documentoGP.DocVenta.fechaVencimiento.ToString("yyyy-MM-dd");
            DocEnviarWS.horaEmision      = documentoGP.DocVenta.horaEmision;
            DocEnviarWS.idTransaccion    = documentoGP.DocVenta.idDocumento;
            DocEnviarWS.serie            = documentoGP.DocVenta.serie;
            DocEnviarWS.tipoDocumento    = documentoGP.DocVenta.tipoDocumento;
            {
                debug_xml = debug_xml + "<COMPROBANTE>" + DocEnviarWS.serie + "-" + DocEnviarWS.correlativo + "\r\n";
                debug_xml = debug_xml + "   <tipoDocumento>" + DocEnviarWS.tipoDocumento + "\r\n";
                debug_xml = debug_xml + "   <codigoTipoOperacion>" + DocEnviarWS.codigoTipoOperacion + "\r\n";
                debug_xml = debug_xml + "   <FechaEmisio>" + DocEnviarWS.fechaEmision + "\r\n";
                debug_xml = debug_xml + "   <fechaVencimiento>" + DocEnviarWS.fechaVencimiento + "\r\n";
                debug_xml = debug_xml + "   <horaEmision>" + DocEnviarWS.horaEmision + "\r\n";
                debug_xml = debug_xml + "   <idTransaccion>" + DocEnviarWS.idTransaccion + "\r\n";
                debug_xml = debug_xml + "<FIN COMPROBANTE>" + "\r\n";
            }
            // FIN SECCION COMPROBANTE

            // SECCION Relacionado. VER mas adelante
            debug_xml = debug_xml + "<RELACIONADO NOTAS>" + documentoGP.LDocVentaRelacionados.Count() + "\r\n";
            if (string.IsNullOrEmpty(documentoGP.DocVenta.cRelacionadoTipoDocAfectado))
            {
                debug_xml = debug_xml + "<SIN DOC RELACIONADO>" + "\r\n";
            }
            else
            {
                if (DocEnviarWS.tipoDocumento == "07" || DocEnviarWS.tipoDocumento == "08")
                {
                    var relacionadoN = new RelacionadoNotas();

                    relacionadoN.codigoTipoNota    = documentoGP.DocVenta.infoRelNotasCodigoTipoNota;
                    relacionadoN.observaciones     = documentoGP.DocVenta.infoRelNotasObservaciones;
                    relacionadoN.numeroDocAfectado = documentoGP.DocVenta.cRelacionadoNumDocAfectado.Trim();
                    relacionadoN.tipoDocAfectado   = documentoGP.DocVenta.cRelacionadoTipoDocAfectado;

                    DocEnviarWS.relacionadoNotas = new RelacionadoNotas();
                    DocEnviarWS.relacionadoNotas = relacionadoN;
                    debug_xml = debug_xml + "  <TIPOAFECTADO>" + DocEnviarWS.relacionadoNotas.tipoDocAfectado + "\r\n";
                    debug_xml = debug_xml + "  <DOCAFECTADO>" + DocEnviarWS.relacionadoNotas.numeroDocAfectado + "\r\n";
                    debug_xml = debug_xml + "  <NOTA>" + DocEnviarWS.relacionadoNotas.codigoTipoNota + "\r\n";
                    debug_xml = debug_xml + "  <observaciones>" + DocEnviarWS.relacionadoNotas.observaciones + "\r\n";
                    debug_xml = debug_xml + "<FIN RELACIONADO NOTAS>\r\n";
                }
                else
                {
                    if (DocEnviarWS.tipoDocumento == "01")
                    {
                        var relacionado = new Relacionado();
                        relacionado.numeroDocRelacionado = documentoGP.DocVenta.cRelacionadoNumDocAfectado.Trim();
                        relacionado.tipoDocRelacionado   = documentoGP.DocVenta.cRelacionadoTipoDocAfectado;

                        DocEnviarWS.relacionado    = new Relacionado[1];
                        DocEnviarWS.relacionado[0] = relacionado;

                        debug_xml = debug_xml + "  <TIPOAFECTADO>" + DocEnviarWS.relacionado[0].numeroDocRelacionado + "\r\n";
                        debug_xml = debug_xml + "  <DOCAFECTADO>" + DocEnviarWS.relacionado[0].tipoDocRelacionado + "\r\n";
                        debug_xml = debug_xml + "<FIN RELACIONADO NOTAS>\r\n";
                    }
                }
            }


            // debug_xml = debug_xml + "<RELACIONADO NOTAS>" + documentoGP.LDocVentaRelacionados.Count() + "\r\n";
            foreach (vwCfdiRelacionados relacionado_gp in documentoGP.LDocVentaRelacionados)
            {
                if (DocEnviarWS.tipoDocumento == "07" || DocEnviarWS.tipoDocumento == "08")
                {
                    var relacionadoN = new RelacionadoNotas();

                    relacionadoN.codigoTipoNota    = documentoGP.DocVenta.infoRelNotasCodigoTipoNota;
                    relacionadoN.observaciones     = documentoGP.DocVenta.infoRelNotasObservaciones;
                    relacionadoN.numeroDocAfectado = relacionado_gp.sopnumbeTo.Trim();
                    relacionadoN.tipoDocAfectado   = relacionado_gp.tipoDocumento;

                    DocEnviarWS.relacionadoNotas = new RelacionadoNotas();
                    DocEnviarWS.relacionadoNotas = relacionadoN;

                    debug_xml = debug_xml + "  <TIPOAFECTADO>" + DocEnviarWS.relacionadoNotas.tipoDocAfectado + "\r\n";
                    debug_xml = debug_xml + "  <DOCAFECTADO>" + DocEnviarWS.relacionadoNotas.numeroDocAfectado + "\r\n";
                    debug_xml = debug_xml + "  <NOTA>" + DocEnviarWS.relacionadoNotas.codigoTipoNota + "\r\n";
                    debug_xml = debug_xml + "  <observaciones>" + DocEnviarWS.relacionadoNotas.observaciones + "\r\n";
                    debug_xml = debug_xml + "<FIN RELACIONADO NOTAS>\r\n";
                }
                else
                {
                    if (DocEnviarWS.tipoDocumento == "01")
                    {
                        var relacionado = new Relacionado();
                        relacionado.numeroDocRelacionado = relacionado_gp.sopnumbeTo.Trim();;
                        relacionado.tipoDocRelacionado   = relacionado_gp.tipoDocumento;

                        DocEnviarWS.relacionado    = new Relacionado[1];
                        DocEnviarWS.relacionado[0] = relacionado;

                        debug_xml = debug_xml + "  <TIPOAFECTADO>" + DocEnviarWS.relacionado[0].numeroDocRelacionado + "\r\n";
                        debug_xml = debug_xml + "  <DOCAFECTADO>" + DocEnviarWS.relacionado[0].tipoDocRelacionado + "\r\n";
                        debug_xml = debug_xml + "<FIN RELACIONADO NOTAS>\r\n";
                    }
                }

                //Aumenta contadoresDocEnviarWS.producto[i].
                i++;
                correlativo++;
            }


            // SECCION Producto.
            DocEnviarWS.producto = new Producto[documentoGP.LDocVentaConceptos.Count()];
            debug_xml            = debug_xml + "<CANT PROD>" + DocEnviarWS.producto.Count() + "\r\n";
            i = 0; correlativo = 1;
            foreach (vwCfdiConceptos producto_gp in documentoGP.LDocVentaConceptos)
            {
                var producto = new Producto();

                producto.cantidad                 = producto_gp.cantidad.ToString();
                producto.codigoPLU                = producto_gp.ITEMNMBR;
                producto.codigoPLUSunat           = producto_gp.claveProdSunat.Trim();
                producto.descripcion              = producto_gp.ITEMDESC;
                producto.montoTotalImpuestoItem   = producto_gp.montoIva.ToString("0.00");
                producto.precioVentaUnitarioItem  = producto_gp.precioUniConIva.ToString();
                producto.unidadMedida             = producto_gp.udemSunat;
                producto.valorReferencialUnitario = producto_gp.precioUniConIva.ToString();
                producto.valorUnitarioBI          = producto_gp.valorUni.ToString();
                producto.valorVentaItemQxBI       = string.Format("{0,14:0.00}", producto_gp.importe).Trim();
                producto.numeroOrden              = correlativo.ToString();
                {
                    debug_xml = debug_xml + "<PRODUCTO>" + correlativo + "\r\n";

                    debug_xml = debug_xml + "   <cantidad>" + producto.cantidad + "\r\n";
                    debug_xml = debug_xml + "   <codigoPLU>" + producto.codigoPLU + "\r\n";
                    debug_xml = debug_xml + "   <codigoPLUSunat>" + producto.codigoPLUSunat + "\r\n";
                    debug_xml = debug_xml + "   <descripcion>" + producto.descripcion + "\r\n";
                    debug_xml = debug_xml + "   <montoTotalImpuestoItem>" + producto.montoTotalImpuestoItem + "\r\n";
                    debug_xml = debug_xml + "   <precioVentaUnitarioItem>" + producto.precioVentaUnitarioItem + "\r\n";
                    debug_xml = debug_xml + "   <unidadMedida>" + producto.unidadMedida + "\r\n";
                    debug_xml = debug_xml + "   <valorReferencialUnitario>" + producto.valorReferencialUnitario + "\r\n";
                    debug_xml = debug_xml + "   <valorUnitarioBI>" + producto.valorUnitarioBI + "\r\n";
                    debug_xml = debug_xml + "   <valorVentaItemQxBI>" + producto.valorVentaItemQxBI + "\r\n";
                    debug_xml = debug_xml + "   <numeroOrden>" + producto.numeroOrden + "\r\n";
                }

                // SECCION PRODUCTO IGV
                producto.IGV = new ProductoIGV();
                switch (producto_gp.tipoAfectacion.ToString().Trim())
                {
                case "20":
                    producto.IGV.baseImponible = producto_gp.montoImponibleExonera.ToString("0.00");
                    break;

                case "21":
                    producto.IGV.baseImponible = producto_gp.montoImponibleGratuito.ToString("0.00");
                    break;

                case "30":
                    producto.IGV.baseImponible = producto_gp.montoImponibleInafecto.ToString("0.00");
                    break;

                case "35":
                    producto.IGV.baseImponible = producto_gp.montoImponibleInafecto.ToString("0.00");
                    break;

                case "40":
                    producto.IGV.baseImponible = producto_gp.montoImponibleExporta.ToString("0.00");
                    break;

                default:
                    producto.IGV.baseImponible = producto_gp.montoImponibleIva.ToString("0.00");
                    break;
                }

                producto.IGV.monto = producto_gp.montoIva.ToString("0.00");
                producto.IGV.tipo  = producto_gp.tipoAfectacion.ToString().Trim();

                if (!string.IsNullOrEmpty(documentoGP.DocVenta.infoRelNotasCodigoTipoNota))
                {
                    producto.IGV.porcentaje = string.Format("{0,8:0.00}", producto_gp.porcentajeIva * 100).Trim();
                }
                else
                {
                    producto.IGV.porcentaje = string.Format("{0,8:0.00}", producto_gp.porcentajeIva * 100).Trim();
                }
                {
                    debug_xml = debug_xml + "   <IGV>\r\n";
                    debug_xml = debug_xml + "       <baseImponible>" + producto.IGV.baseImponible + "\r\n";
                    debug_xml = debug_xml + "           <baseImponibleIVA>" + producto_gp.montoImponibleIva.ToString("0.00") + "\r\n";
                    debug_xml = debug_xml + "           <baseImponibleExo>" + producto_gp.montoImponibleExonera.ToString("0.00") + "\r\n";
                    debug_xml = debug_xml + "           <baseImponibleExp>" + producto_gp.montoImponibleExporta.ToString("0.00") + "\r\n";
                    debug_xml = debug_xml + "           <baseImponibleGra>" + producto_gp.montoImponibleGratuito.ToString("0.00") + "\r\n";
                    debug_xml = debug_xml + "           <baseImponibleIna>" + producto_gp.montoImponibleInafecto.ToString("0.00") + "\r\n";
                    debug_xml = debug_xml + "       <porcentaje>" + producto.IGV.porcentaje + "\r\n";
                    debug_xml = debug_xml + "       <monto>" + producto.IGV.monto + "\r\n";
                    debug_xml = debug_xml + "       <tipo>" + producto.IGV.tipo + "\r\n";
                }

                //SECCION PRODUCTO DESCUENTO
                if (producto_gp.descuento != 0)
                {
                    producto.descuento = new ProductoDescuento();
                    producto.descuento.baseImponible = string.Format("{0,14:0.00}", producto_gp.descuentoBaseImponible).Trim();
                    producto.descuento.monto         = string.Format("{0,14:0.00}", producto_gp.descuento).Trim();
                    producto.descuento.porcentaje    = string.Format("{0,8:0.00000}", producto_gp.descuentoPorcentaje * 100).Trim();
                    producto.descuento.codigo        = producto_gp.descuentoCodigo;

                    if (producto_gp.descuentoCodigo == "01")
                    {
                        DescItemIGV = false;
                    }

                    {
                        debug_xml = debug_xml + "   <DESC ITEM>" + "\r\n";
                        debug_xml = debug_xml + "       <baseImponible>" + producto.descuento.baseImponible + "\r\n";
                        debug_xml = debug_xml + "       <monto>" + producto.descuento.monto + "\r\n";
                        debug_xml = debug_xml + "       <porcentaje>" + producto.descuento.porcentaje + "\r\n";
                        debug_xml = debug_xml + "       <codigo>" + producto.descuento.codigo + "\r\n";
                    }
                }

                DocEnviarWS.producto[i] = producto;
                debug_xml = debug_xml + "  <PRODUCTO>" + DocEnviarWS.producto[i].codigoPLU + " Imp:" + DocEnviarWS.producto[i].valorVentaItemQxBI + "\r\n";
                debug_xml = debug_xml + "       IGVporc: " + DocEnviarWS.producto[i].IGV.porcentaje + "\r\n";

                //Aumenta contadoresDocEnviarWS.producto[i].
                i++;
                correlativo++;
            }
            debug_xml = debug_xml + "<FIN PRODUCTOS>\r\n";

            // SECCION Descuentos Globales
            if (documentoGP.DocVenta.descuentoGlobalMonto != 0)
            {
                DocEnviarWS.descuentosGlobales = new DescuentosGlobales();

                DocEnviarWS.descuentosGlobales.baseImponible = documentoGP.DocVenta.descuentoGlobalImponible.ToString("0.00");
                DocEnviarWS.descuentosGlobales.monto         = documentoGP.DocVenta.descuentoGlobalMonto.ToString("0.00");
                if (DescItemIGV)
                {
                    DocEnviarWS.descuentosGlobales.motivo = "02";
                }
                else
                {
                    DocEnviarWS.descuentosGlobales.motivo = "03";
                }
                DocEnviarWS.descuentosGlobales.porcentaje = string.Format("{0,8:0.00000}", documentoGP.DocVenta.descuentoGlobalPorcentaje).Trim();

                {
                    debug_xml = debug_xml + "<DESCUENTOS GLOBALES>" + "\r\n";
                    debug_xml = debug_xml + "    <baseImponible" + DocEnviarWS.descuentosGlobales.baseImponible + "\r\n";
                    debug_xml = debug_xml + "    <porcentaje>" + DocEnviarWS.descuentosGlobales.porcentaje + "\r\n";
                    debug_xml = debug_xml + "    <monto>" + DocEnviarWS.descuentosGlobales.monto + "\r\n";
                    debug_xml = debug_xml + "    <motivo>" + DocEnviarWS.descuentosGlobales.motivo + "\r\n";
                    debug_xml = debug_xml + "<FIN DESCUENTOS GLOBALES>" + "\r\n";
                }
            }
            else
            {
                debug_xml = debug_xml + "<SIN DESCUENTOS GLOBALES>" + "\r\n";
            }

            //SECCION DETRACCIONES
            if (string.IsNullOrEmpty(documentoGP.DocVenta.codigoDetraccion) || documentoGP.DocVenta.codigoDetraccion.Trim() == "00")
            {
                debug_xml = debug_xml + "<SIN DETRACCIONES>" + "\r\n";
            }
            else
            {
                debug_xml = debug_xml + "<DETRACCIONES>" + "\r\n";

                var detracciones = new Detraccion();
                detracciones.codigo = documentoGP.DocVenta.codigoDetraccion.Trim();
                //detracciones.medioPago = documentoGP.DocVenta.medioPagoDetraccion.Trim();
                detracciones.medioPago = "002";
                detracciones.monto     = string.Format("{0,14:0.00}", documentoGP.DocVenta.montoDetraccion).Trim();
                detracciones.numCuentaBancodelaNacion = documentoGP.DocVenta.numCuentaBancoNacion.Trim();
                detracciones.porcentaje = string.Format("{0,8:0.00}", documentoGP.DocVenta.porcentajeDetraccion).Trim();

                DocEnviarWS.detraccion    = new Detraccion[1];
                DocEnviarWS.detraccion[0] = detracciones;

                {
                    debug_xml = debug_xml + "    <codigo>" + DocEnviarWS.detraccion[0].codigo + "\r\n";
                    debug_xml = debug_xml + "    <medioPago>" + DocEnviarWS.detraccion[0].medioPago + "\r\n";
                    debug_xml = debug_xml + "    <monto>" + DocEnviarWS.detraccion[0].monto + "\r\n";
                    debug_xml = debug_xml + "    <numCuentaBancodelaNacion>" + DocEnviarWS.detraccion[0].numCuentaBancodelaNacion + "\r\n";
                    debug_xml = debug_xml + "    <porcentaje>" + DocEnviarWS.detraccion[0].porcentaje + "\r\n";
                }

                debug_xml = debug_xml + "<FIN DETRACCIONES>" + DocEnviarWS.detraccion[0].monto + "\r\n";
            }


            //SECCION TOTALES
            debug_xml           = debug_xml + "<TOTALES>" + "\r\n";
            DocEnviarWS.totales = new Totales();
            DocEnviarWS.totales.importeTotalPagar          = documentoGP.DocVenta.montoTotalVenta.ToString("0.00");
            DocEnviarWS.totales.importeTotalVenta          = documentoGP.DocVenta.montoTotalVenta.ToString("0.00");
            DocEnviarWS.totales.montoTotalImpuestos        = documentoGP.DocVenta.montoTotalImpuestos.ToString("0.00");
            DocEnviarWS.totales.subtotalValorVenta         = string.Format("{0,14:0.00}", documentoGP.DocVenta.montoSubtotalValorVenta).Trim();
            DocEnviarWS.totales.sumaTotalDescuentosporItem = string.Format("{0,14:0.00}", documentoGP.DocVenta.montoTotalDescuentosPorItem).Trim();
            DocEnviarWS.totales.sumatoriaImpuestosOG       = documentoGP.DocVenta.montoTotalImpuOperGratuitas.ToString("0.00");
            DocEnviarWS.totales.totalIGV = documentoGP.DocVenta.montoTotalIgv.ToString("0.00");

            {
                debug_xml = debug_xml + "   <importeTotalPagar>" + DocEnviarWS.totales.importeTotalPagar + "\r\n";
                debug_xml = debug_xml + "   <importeTotalVenta>" + DocEnviarWS.totales.importeTotalVenta + "\r\n";
                debug_xml = debug_xml + "   <montoTotalImpuestos>" + DocEnviarWS.totales.montoTotalImpuestos + "\r\n";
                debug_xml = debug_xml + "   <subtotalValorVenta>" + DocEnviarWS.totales.subtotalValorVenta + "\r\n";
                debug_xml = debug_xml + "   <sumaTotalDescuentosporItem>" + DocEnviarWS.totales.sumaTotalDescuentosporItem + "\r\n";
                debug_xml = debug_xml + "   <sumatoriaImpuestosOG>" + DocEnviarWS.totales.sumatoriaImpuestosOG + "\r\n";
                debug_xml = debug_xml + "   <totalIGV>" + DocEnviarWS.totales.totalIGV + "\r\n";
                debug_xml = debug_xml + "<FIN TOTALES>" + "\r\n";
            }

            //SECCION SUBTOTALES

            DocEnviarWS.totales.subtotal             = new Subtotal();
            DocEnviarWS.totales.subtotal.IGV         = documentoGP.DocVenta.montoSubtotalIvaImponible.ToString("0.00");
            DocEnviarWS.totales.subtotal.exoneradas  = documentoGP.DocVenta.montoSubtotalExonerado.ToString("0.00");
            DocEnviarWS.totales.subtotal.exportacion = documentoGP.DocVenta.montoSubtotalExportacion.ToString("0.00");
            DocEnviarWS.totales.subtotal.gratuitas   = documentoGP.DocVenta.montoSubtotalGratuito.ToString("0.00");
            DocEnviarWS.totales.subtotal.inafectas   = documentoGP.DocVenta.montoSubtotalInafecto.ToString("0.00");
            {
                debug_xml = debug_xml + "   <SUBTOTALES>" + "\r\n";
                debug_xml = debug_xml + "       <IGV>" + DocEnviarWS.totales.subtotal.IGV + "\r\n";
                debug_xml = debug_xml + "       <exoneradas>" + DocEnviarWS.totales.subtotal.exoneradas + "\r\n";
                debug_xml = debug_xml + "       <exportacion>" + DocEnviarWS.totales.subtotal.exportacion + "\r\n";
                debug_xml = debug_xml + "       <gratuitas>" + DocEnviarWS.totales.subtotal.gratuitas + "\r\n";
                debug_xml = debug_xml + "       <inafectas>" + DocEnviarWS.totales.subtotal.inafectas + "\r\n";
                debug_xml = debug_xml + "   <FIN SUBTOTALES>" + "\r\n";
            }

            //SECCION PAGO
            DocEnviarWS.pago             = new Pago();
            DocEnviarWS.pago.moneda      = documentoGP.DocVenta.moneda;
            DocEnviarWS.pago.tipoCambio  = documentoGP.DocVenta.xchgrate.ToString("0.00000");
            DocEnviarWS.pago.fechaInicio = DateTime.Now.ToString("yyyy-MM-dd");
            DocEnviarWS.pago.fechaFin    = DateTime.Now.ToString("yyyy-MM-dd");

            //SECCION PERSONALIZACION PDF
            if (!string.IsNullOrEmpty(documentoGP.LeyendasXml))
            {
                XElement leyendasX   = XElement.Parse(documentoGP.LeyendasXml);
                int      numLeyendas = leyendasX.Elements().Count();
                if (!string.IsNullOrEmpty(leyendasX.Elements().FirstOrDefault().Attribute("S").Value) &&
                    !string.IsNullOrEmpty(leyendasX.Elements().FirstOrDefault().Attribute("T").Value) &&
                    !string.IsNullOrEmpty(leyendasX.Elements().FirstOrDefault().Attribute("V").Value)
                    )
                {
                    DocEnviarWS.personalizacionPDF = new PersonalizacionPDF[numLeyendas];
                    int idx = 0;
                    foreach (XElement child in leyendasX.Elements())
                    {
                        DocEnviarWS.personalizacionPDF[idx]         = new PersonalizacionPDF();
                        DocEnviarWS.personalizacionPDF[idx].seccion = child.Attribute("S").Value;
                        DocEnviarWS.personalizacionPDF[idx].titulo  = child.Attribute("T").Value;
                        DocEnviarWS.personalizacionPDF[idx].valor   = child.Attribute("V").Value;
                        idx++;
                    }
                }
            }
            {
                debug_xml = debug_xml + "<PAGO>" + "\r\n";
                debug_xml = debug_xml + "   <moneda>" + DocEnviarWS.pago.moneda + "\r\n";
                debug_xml = debug_xml + "    <tipoCambio>" + DocEnviarWS.pago.tipoCambio + "\r\n";
                debug_xml = debug_xml + "<FIN PAGO>" + "\r\n";
            }

            debug_xml = debug_xml + "<LLAMADA>";

            return(DocEnviarWS);
        }
        //public static string ImprimirComprobante(int ventaPetroamericaId, int ventaId)
        public static string ImprimirComprobante(string numeroDocumento, string tipoDocumentoId, string serie, string correlativo, string fechaEmision, decimal montoTotalComprobante)
        {
            var mensaje = String.Empty;

            try
            {
                var empresaInfo = new Empresa().Listar(0).FirstOrDefault();
                var agenciaInfo = new Agencia().Listar(0).FirstOrDefault();
                //var ventaInfo = new Negocio.VentaGasolutions().Listar(ventaPetroamericaId).FirstOrDefault();


                var ventaInfoLista = new Negocio.VentaGasolutions().ListarPaginado(0, numeroDocumento, tipoDocumentoId, serie + "-" + correlativo, DateTime.ParseExact(fechaEmision, "dd/MM/yyyy", null), DateTime.ParseExact(fechaEmision, "dd/MM/yyyy", null), 0, 0, 0, 0);
                var ventaGasolutionsDetalleInfoLista = new List <VentaDetalleGasolutionsInfo>();

                //var ventaGasolutionsDetalleInfo = new Negocio.VentaGasolutions().ListarDetalle(ventaPetroamericaId, 0).ToList();
                //var ventaGasolutionsDetalleInfo = new Negocio.VentaGasolutions().ListarDetalle(ventaInfo.VentaGasolutionsId, 0).ToList();

                ventaInfoLista = ventaInfoLista.Where(v => v.TotalVenta.Equals(montoTotalComprobante)).ToList();
                var ventaInfo = new VentaGasolutionsInfo();
                if (ventaInfoLista.Count > 0)
                {
                    ventaInfo = ventaInfoLista.FirstOrDefault();
                    ventaGasolutionsDetalleInfoLista = new Negocio.VentaGasolutions().ListarDetalle(ventaInfo.VentaGasolutionsId, 0);
                }
                else
                {
                    mensaje = "No se ha encontrado el comprobante." + "@" + "" + "@" + ventaInfo.NroDocumentoReceptor;
                    return(mensaje);
                }

                var ventaDetalleInfo = new List <VentaDetalleInfo>();

                _documento = new DocumentoElectronico();

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

                #region Emisor
                var emisor = new DocumentoElectronico().Emisor;
                emisor.Departamento    = ventaInfo.DepartamentoEmisor;
                emisor.Direccion       = ventaInfo.DireccionEmisor;
                emisor.Distrito        = ventaInfo.DistritoEmisor;
                emisor.NombreComercial = ventaInfo.NombreComercialEmisor;
                emisor.NombreLegal     = ventaInfo.NombreLegalEmisor;
                emisor.NroDocumento    = ventaInfo.NroDocumentoEmisor;
                emisor.Provincia       = ventaInfo.ProvinciaEmisor;
                emisor.TipoDocumento   = "6";
                emisor.Ubigeo          = ventaInfo.UbigeoEmisor;
                emisor.Urbanizacion    = "";
                _documento.Emisor      = emisor;
                #endregion

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

                #region Items
                var itemId = 1;
                foreach (var vd in ventaGasolutionsDetalleInfoLista)
                {
                    var item = new DetalleDocumento();
                    item.Cantidad    = vd.Cantidad;
                    item.Descripcion = vd.Descripcion;
                    item.Id          = vd.Id;
                    itemId++;
                    item.Impuesto          = vd.Impuesto;
                    item.PrecioUnitario    = vd.PrecioUnitario;
                    item.Suma              = vd.TotalVenta;
                    item.TotalVenta        = vd.TotalVenta;
                    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.TotalVenta);
                _documento.MontoPercepcion = 0;
                _documento.PlacaVehiculo   = ventaInfo.PlacaVehiculo;

                #region Receptor
                var receptor = new DocumentoElectronico().Receptor;
                receptor.Departamento    = "";
                receptor.Direccion       = ventaInfo.DireccionReceptor;
                receptor.Distrito        = "";
                receptor.NombreComercial = ventaInfo.NombreComercialReceptor;
                receptor.NombreLegal     = ventaInfo.NombreLegalReceptor;
                receptor.NroDocumento    = ventaInfo.NroDocumentoReceptor;
                receptor.Provincia       = "";
                receptor.TipoDocumento   = ventaInfo.TipoDocumentoReceptor;
                receptor.Ubigeo          = "";
                receptor.Urbanizacion    = "";
                _documento.Receptor      = receptor;
                #endregion

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

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

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

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

                var rutaPdfFactura = HostingEnvironment.MapPath("~/Archivos/Documentos/Cliente/" + ventaInfo.NroDocumentoReceptor + "");

                #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 = HostingEnvironment.MapPath("~/Archivos/Documentos/Cliente") + "/" + ventaInfo.NroDocumentoReceptor;
                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/Cliente/" + _documento.IdDocumento + "_Firmado.xml");
                string rutaXmlFirmado = HostingEnvironment.MapPath("~/Archivos/Documentos/Cliente") + "/" + ventaInfo.NroDocumentoReceptor;
                if (!Directory.Exists(rutaXmlFirmado))
                {
                    Directory.CreateDirectory(rutaXmlFirmado);
                }
                File.WriteAllBytes(rutaXmlFirmado + "/" + _documento.IdDocumento + "_Firmado.xml", Convert.FromBase64String(responseFirma.Data.TramaXmlFirmado));
                #endregion

                #region Impresión Comprobante
                var htmlToComprobante        = new NReco.PdfGenerator.HtmlToPdfConverter();
                var nombreArchivoComprobante = String.Empty;
                var comprobanteSB            = new StringBuilder();

                if (ventaInfo.TipoDocumento.Equals(Constantes.TipoComprobanteFactura))
                {
                    //comprobanteSB.Append(Herramientas.Helper.ObtenerTexto("~/Archivos/Plantillas/FacturaPowerGas.html"));
                    comprobanteSB.Append(Herramientas.Helper.ObtenerTexto(PlantillaFactura));
                    #region Factura

                    comprobanteSB.Replace("@EMPRESA_LOGO", HttpContext.Current.Server.MapPath(empresaInfo.Imagen));
                    comprobanteSB.Replace("@EMPRESA_NOMBRE", ventaInfo.NombreComercialEmisor);
                    comprobanteSB.Replace("@EMPRESA_RUC", ventaInfo.NroDocumentoEmisor);
                    comprobanteSB.Replace("@NUMEROCOMPROBANTE", ventaInfo.IdDocumento);
                    comprobanteSB.Replace("@EMPRESA_DIRECCION", ventaInfo.DireccionEmisor);
                    comprobanteSB.Replace("@EMPRESA_TELEFONO", String.Empty);
                    comprobanteSB.Replace("@EMPRESA_FAX", String.Empty);
                    comprobanteSB.Replace("@EMPRESA_PAIS", empresaInfo.Pais);
                    comprobanteSB.Replace("@EMPRESA_DEPARTAMENTO", empresaInfo.Departamento);
                    comprobanteSB.Replace("@EMPRESA_PROVINCIA", empresaInfo.Provincia);
                    comprobanteSB.Replace("@EMPRESA_DISTRITO", empresaInfo.Distrito);
                    comprobanteSB.Replace("@FECHAEMISION", ventaInfo.FechaEmision.ToString("dd/MM/yyyy"));
                    comprobanteSB.Replace("@AGENCIA_DIRECCION", agenciaInfo.Direccion);


                    //var clienteInfo = new Cliente().Listar(ventaInfo.ClienteId).FirstOrDefault();
                    comprobanteSB.Replace("@CLIENTE_NOMBRE", ventaInfo.NombreComercialReceptor);
                    comprobanteSB.Replace("@CLIENTE_DIRECCION", ventaInfo.DireccionReceptor);
                    comprobanteSB.Replace("@CLIENTE_DISTRITO", String.Empty);
                    comprobanteSB.Replace("@CLIENTE_RUC", ventaInfo.NroDocumentoReceptor);
                    comprobanteSB.Replace("@CLIENTE_CODIGO", String.Empty);

                    comprobanteSB.Replace("@MONEDA", ventaInfo.Moneda);

                    var facturaSBDetalle = new StringBuilder("");
                    facturaSBDetalle.Append("<table style=\"width: 100%; border-collapse: collapse;\">");
                    facturaSBDetalle.Append("   <thead>");
                    facturaSBDetalle.Append("       <tr>");
                    facturaSBDetalle.Append("           <td style=\"width: 10%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">ITEM</td>");
                    facturaSBDetalle.Append("           <td style=\"width: 50%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">DESCRIPCI&Oacute;N</td>");
                    facturaSBDetalle.Append("           <td style=\"width: 10%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">CANT</td>");
                    facturaSBDetalle.Append("           <td style=\"width: 10%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">UND</td>");
                    facturaSBDetalle.Append("           <td style=\"width: 10%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">VALOR UNIT</td>");
                    facturaSBDetalle.Append("           <td style=\"width: 10%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">SUBTOTAL</td>");
                    facturaSBDetalle.Append("       </tr>");
                    facturaSBDetalle.Append("   </thead>");

                    var montoGravado       = 0M;
                    var montoImpuestoTotal = 0M;
                    foreach (var vd in ventaGasolutionsDetalleInfoLista)
                    {
                        facturaSBDetalle.Append("   <tr>");
                        facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + vd.CodigoItem + "</td>");
                        facturaSBDetalle.Append("       <td style=\"width: 50%; border: 1px none #0b44e9; text-align: left; vertical-align: top;\" class=\"Estilo8\">" + vd.Descripcion + "</td>");
                        facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + ((vd.TotalVenta - vd.Impuesto) / vd.PrecioUnitario).ToString("N2") + "</td>");
                        facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + vd.UnidadMedida + "</td>");
                        facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + vd.PrecioUnitario.ToString("N2") + "</td>");
                        //facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + (vd.Cantidad * vd.PrecioUnitario).ToString("N2") + "</td>");
                        facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + (vd.TotalVenta - vd.Impuesto).ToString("N2") + "</td>");
                        facturaSBDetalle.Append("   </tr>");

                        montoGravado = montoGravado + vd.TotalVenta;
                    }
                    facturaSBDetalle.Append("</table>");

                    var montoIgv = montoGravado * 0.18M;

                    var montoTotal = montoGravado + montoIgv;

                    comprobanteSB.Replace("@MONTO_GRAVADA", ventaInfo.Gravadas.ToString("N2"));
                    comprobanteSB.Replace("@MONTO_INAFECTA", "0.00");
                    comprobanteSB.Replace("@MONTO_EXONERADA", "0.00");
                    comprobanteSB.Replace("@MONTO_GRATUITA", "0.00");
                    comprobanteSB.Replace("@MONTO_IGV", ventaInfo.TotalIgv.ToString("N2"));
                    comprobanteSB.Replace("@MONTO_TOTAL", ventaInfo.TotalVenta.ToString("N2"));

                    comprobanteSB.Replace("@PRODUCTO_DETALLE", facturaSBDetalle.ToString());
                    #endregion

                    nombreArchivoComprobante = "Factura_" + DateTime.Now.ToString("ddMMyyyyhhmmss"); // + ".pdf";
                }
                if (ventaInfo.TipoDocumento.Equals(Constantes.TipoComprobanteBoletaVenta))
                {
                    //comprobanteSB.Append(Herramientas.Helper.ObtenerTexto("~/Archivos/Plantillas/BoletaPowerGas.html"));
                    comprobanteSB.Append(Herramientas.Helper.ObtenerTexto(PlantillaBoleta));
                    #region Boleta
                    comprobanteSB.Replace("@EMPRESA_LOGO", HttpContext.Current.Server.MapPath(empresaInfo.Imagen));
                    comprobanteSB.Replace("@EMPRESA_NOMBRE", ventaInfo.NombreComercialEmisor);
                    comprobanteSB.Replace("@EMPRESA_RUC", ventaInfo.NroDocumentoEmisor);
                    comprobanteSB.Replace("@NUMEROCOMPROBANTE", ventaInfo.IdDocumento);
                    comprobanteSB.Replace("@EMPRESA_DIRECCION", ventaInfo.DireccionEmisor);
                    comprobanteSB.Replace("@EMPRESA_TELEFONO", String.Empty);
                    comprobanteSB.Replace("@EMPRESA_FAX", String.Empty);
                    comprobanteSB.Replace("@EMPRESA_PAIS", empresaInfo.Pais);
                    comprobanteSB.Replace("@EMPRESA_DEPARTAMENTO", empresaInfo.Departamento);
                    comprobanteSB.Replace("@EMPRESA_PROVINCIA", empresaInfo.Provincia);
                    comprobanteSB.Replace("@EMPRESA_DISTRITO", empresaInfo.Distrito);
                    comprobanteSB.Replace("@FECHAEMISION", ventaInfo.FechaEmision.ToString("dd/MM/yyyy"));
                    comprobanteSB.Replace("@AGENCIA_DIRECCION", agenciaInfo.Direccion);


                    //var clienteInfo = new Cliente().Listar(ventaInfo.ClienteId).FirstOrDefault();
                    comprobanteSB.Replace("@CLIENTE_NOMBRE", ventaInfo.NombreComercialReceptor);
                    comprobanteSB.Replace("@CLIENTE_DIRECCION", ventaInfo.DireccionReceptor);
                    comprobanteSB.Replace("@CLIENTE_DISTRITO", String.Empty);
                    comprobanteSB.Replace("@CLIENTE_RUC", ventaInfo.NroDocumentoReceptor);
                    comprobanteSB.Replace("@CLIENTE_CODIGO", String.Empty);

                    comprobanteSB.Replace("@MONEDA", ventaInfo.Moneda);

                    var facturaSBDetalle = new StringBuilder("");
                    facturaSBDetalle.Append("<table style=\"width: 100%; border-collapse: collapse;\">");
                    facturaSBDetalle.Append("   <thead>");
                    facturaSBDetalle.Append("       <tr>");
                    facturaSBDetalle.Append("           <td style=\"width: 10%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">ITEM</td>");
                    facturaSBDetalle.Append("           <td style=\"width: 50%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">DESCRIPCI&Oacute;N</td>");
                    facturaSBDetalle.Append("           <td style=\"width: 10%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">CANT</td>");
                    facturaSBDetalle.Append("           <td style=\"width: 10%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">UND</td>");
                    facturaSBDetalle.Append("           <td style=\"width: 10%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">VALOR UNIT</td>");
                    facturaSBDetalle.Append("           <td style=\"width: 10%; border-bottom: 1px solid #0b44e9; text-align: center;\" class=\"Estilo67\">SUBTOTAL</td>");
                    facturaSBDetalle.Append("       </tr>");
                    facturaSBDetalle.Append("   </thead>");

                    var montoGravado       = 0M;
                    var montoImpuestoTotal = 0M;
                    foreach (var vd in ventaGasolutionsDetalleInfoLista)
                    {
                        facturaSBDetalle.Append("   <tr>");
                        facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + vd.CodigoItem + "</td>");
                        facturaSBDetalle.Append("       <td style=\"width: 50%; border: 1px none #0b44e9; text-align: left; vertical-align: top;\" class=\"Estilo8\">" + vd.Descripcion + "</td>");
                        facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + ((vd.TotalVenta - vd.Impuesto) / vd.PrecioUnitario).ToString("N2") + "</td>");
                        facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + vd.UnidadMedida + "</td>");
                        facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + vd.PrecioUnitario.ToString("N2") + "</td>");
                        facturaSBDetalle.Append("       <td style=\"width: 10%; border: 1px none #0b44e9; text-align: center; vertical-align: top;\" class=\"Estilo8\">" + (vd.TotalVenta - vd.Impuesto).ToString("N2") + "</td>");
                        facturaSBDetalle.Append("   </tr>");

                        montoGravado = montoGravado + vd.TotalVenta;
                    }
                    facturaSBDetalle.Append("</table>");

                    var montoIgv = montoGravado * 0.18M;

                    var montoTotal = montoGravado + montoIgv;

                    comprobanteSB.Replace("@MONTO_GRAVADA", ventaInfo.Gravadas.ToString("N2"));
                    comprobanteSB.Replace("@MONTO_INAFECTA", "0.00");
                    comprobanteSB.Replace("@MONTO_EXONERADA", "0.00");
                    comprobanteSB.Replace("@MONTO_GRATUITA", "0.00");
                    comprobanteSB.Replace("@MONTO_IGV", ventaInfo.TotalIgv.ToString("N2"));
                    comprobanteSB.Replace("@MONTO_TOTAL", ventaInfo.TotalVenta.ToString("N2"));

                    comprobanteSB.Replace("@PRODUCTO_DETALLE", facturaSBDetalle.ToString());
                    #endregion

                    nombreArchivoComprobante = "Boleta_" + DateTime.Now.ToString("ddMMyyyyhhmmss"); // + ".pdf";
                }

                if (!Directory.Exists(rutaPdfFactura))
                {
                    Directory.CreateDirectory(rutaPdfFactura);
                }

                #region Codigo QR
                var codigoQR = ventaInfo.NroDocumentoReceptor + "|" + ventaInfo.TipoDocumento + "|" + ventaInfo.IdDocumento.Substring(0, 4) + "|" +
                               ventaInfo.IdDocumento.Substring(5, ventaInfo.IdDocumento.Length - 5) + "|" + ventaInfo.TotalIgv + "|" + ventaInfo.TotalVenta + "|" +
                               ventaInfo.FechaEmision + "|" + ventaInfo.TipoDocumentoReceptor + "|" + ventaInfo.NroDocumentoReceptor + "|" +
                               responseFirma.Data.ResumenFirma + "|" + responseFirma.Data.ValorFirma;

                // instantiate a writer object
                var barcodeWriter = new BarcodeWriter();
                // set the barcode format
                barcodeWriter.Format = BarcodeFormat.PDF_417;
                // write text and generate a 2-D barcode as a bitmap
                // barcodeWriter.Write(codigoQR).Save(@"C:\Users\jeremy\Desktop\generated.bmp");
                //barcodeWriter.Write(codigoQR).Save(HostingEnvironment.MapPath("~/Archivos/Documentos/Cliente/" + ventaInfo.NumeroDocumentoCliente + "/" + _documento.IdDocumento + ".bmp"));
                barcodeWriter.Write(codigoQR).Save(rutaPdfFactura + "/" + _documento.IdDocumento + ".bmp");
                #endregion

                comprobanteSB.Replace("@CODIGO_QR", HttpContext.Current.Server.MapPath("~/Archivos/Documentos/Cliente/" + ventaInfo.NroDocumentoReceptor + "/" + _documento.IdDocumento + ".bmp"));
                comprobanteSB.Replace("@MONTO_LETRAS", Herramientas.NumeroALetras.numeroAletras(ventaInfo.TotalVenta));

                comprobanteSB = Herramientas.Helper.EncodeHtml(comprobanteSB);
                //var margins = new PageMargins();
                //margins.Left = 1;
                //htmlToComprobante.Margins = margins;

                var pdfBytesFactura = htmlToComprobante.GeneratePdf(comprobanteSB.ToString());


                // var comprobanteImpreso = rutaPdfFactura + "\\" + nombreArchivoComprobante + ".pdf";
                File.WriteAllBytes(rutaPdfFactura + "/" + nombreArchivoComprobante + ".pdf", pdfBytesFactura);
                File.WriteAllBytes(rutaPdfFactura + "/" + nombreArchivoComprobante + ".xml", Convert.FromBase64String(responseFirma.Data.TramaXmlFirmado));

                Negocio.Helper.ActualizarColumnasTabla("VentaGasolutions", new string[] { "ComprobanteImpreso" }, new string[] { nombreArchivoComprobante + ".pdf" }, new string[] { "VentaGasolutionsId" }, new string[] { ventaInfo.VentaGasolutionsId.ToString() });

                #endregion

                mensaje = "El Comprobante se generó correctamente" + "@" + (nombreArchivoComprobante) + "@" + ventaInfo.NroDocumentoReceptor;
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, Constantes.ExcepcionPoliticaPresentacion);
                mensaje = rethrow ? ex.Message : Constantes.ExcepcionPoliticaPresentacion;
                mensaje = (mensaje + "-" + ex.Source) + "@" + "" + "@" + "";
            }
            return(mensaje);
        }
        public static string ImprimirComprobanteAntes(string numeroDocumento, string tipoDocumentoId, string serie, string correlativo, string fechaEmision, decimal montoTotal)
        {
            var mensaje = String.Empty;

            try
            {
                var fecha = DateTime.ParseExact(fechaEmision, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

                // var ventaInfoLista = new Negocio.VentaPetroamerica().ListarPaginado(0, numeroDocumento.Trim(), tipoDocumentoId, serie, correlativo, fecha, fecha, 0, 0, String.Empty, 0, 0);
                var ventaInfoLista = new Negocio.VentaGasolutions().ListarPaginado(0, String.Empty, tipoDocumentoId, serie + "-" + correlativo, fecha, fecha, 0, 0, 0, 0);
                var ventaGasolutionsDetalleInfo = new VentaDetalleGasolutionsInfo();

                ventaInfoLista = ventaInfoLista.Where(v => v.TotalVenta.Equals(montoTotal)).ToList();
                var ventaInfo = new VentaGasolutionsInfo();
                if (ventaInfoLista.Count > 0)
                {
                    ventaInfo = ventaInfoLista.FirstOrDefault();
                    ventaGasolutionsDetalleInfo = new Negocio.VentaGasolutions().ListarDetalle(ventaInfo.VentaGasolutionsId, 0).FirstOrDefault();
                }
                else
                {
                    mensaje = "No se ha encontrado el comprobante." + "@" + "" + "@" + ventaInfo.NroDocumentoReceptor;
                    return(mensaje);
                }

                var ventaDetalleInfo = new List <VentaDetalleInfo>();

                _documento = new DocumentoElectronico();

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

                #region Emisor
                var emisor = new DocumentoElectronico().Emisor;
                emisor.Departamento    = ventaInfo.DepartamentoEmisor;
                emisor.Direccion       = ventaInfo.DireccionEmisor;
                emisor.Distrito        = ventaInfo.DistritoEmisor;
                emisor.NombreComercial = ventaInfo.NombreComercialEmisor;
                emisor.NombreLegal     = ventaInfo.NombreLegalEmisor;
                emisor.NroDocumento    = ventaInfo.NroDocumentoEmisor;
                emisor.Provincia       = ventaInfo.ProvinciaEmisor;
                emisor.TipoDocumento   = "6";
                emisor.Ubigeo          = ventaInfo.UbigeoEmisor;
                emisor.Urbanizacion    = "";
                _documento.Emisor      = emisor;
                #endregion

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

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

                //item.Descripcion = vd.Producto;
                item.Descripcion = ventaGasolutionsDetalleInfo.Descripcion;
                //item.Id = itemId;
                item.Id = ventaGasolutionsDetalleInfo.Id;
                itemId++;
                //item.Impuesto = vd.Igv;
                item.Impuesto = ventaGasolutionsDetalleInfo.Impuesto;
                //item.PrecioUnitario = vd.PrecioUnitario;
                item.PrecioUnitario = ventaGasolutionsDetalleInfo.PrecioUnitario;
                //item.Suma = vd.SubTotal;
                item.Suma = ventaGasolutionsDetalleInfo.TotalVenta;
                //item.TotalVenta = vd.MontoTotal;
                item.TotalVenta = ventaGasolutionsDetalleInfo.TotalVenta;
                //item.UnidadMedida = vd.UnidadMedida;
                item.UnidadMedida      = ventaGasolutionsDetalleInfo.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.TotalVenta);
                _documento.MontoPercepcion = 0;
                _documento.PlacaVehiculo   = ventaInfo.PlacaVehiculo;

                #region Receptor
                var receptor = new DocumentoElectronico().Receptor;
                receptor.Departamento    = "";
                receptor.Direccion       = ventaInfo.DireccionReceptor;
                receptor.Distrito        = "";
                receptor.NombreComercial = ventaInfo.NombreComercialReceptor;
                receptor.NombreLegal     = ventaInfo.NombreLegalReceptor;
                receptor.NroDocumento    = ventaInfo.NroDocumentoReceptor;
                receptor.Provincia       = "";
                receptor.TipoDocumento   = ventaInfo.TipoDocumentoReceptor;
                receptor.Ubigeo          = "";
                receptor.Urbanizacion    = "";
                _documento.Receptor      = receptor;
                #endregion

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

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

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

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

                var rutaPdfFactura = HostingEnvironment.MapPath("~/Archivos/Documentos/Cliente/" + ventaInfo.NroDocumentoReceptor + "");

                #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 = HostingEnvironment.MapPath("~/Archivos/Facturacion/XML/Cliente");
                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/Cliente/" + _documento.IdDocumento + "_Firmado.xml");
                string rutaXmlFirmado = HostingEnvironment.MapPath("~/Archivos/Facturacion/XML/Cliente");
                if (!Directory.Exists(rutaXmlFirmado))
                {
                    Directory.CreateDirectory(rutaXmlFirmado);
                }
                File.WriteAllBytes(rutaXmlFirmado + "/" + _documento.IdDocumento + "_Firmado.xml", Convert.FromBase64String(responseFirma.Data.TramaXmlFirmado));
                #endregion

                #region Impresión Comprobante
                var htmlToComprobante        = new NReco.PdfGenerator.HtmlToPdfConverter();
                var nombreArchivoComprobante = String.Empty;
                var comprobanteSB            = new StringBuilder();

                if (ventaInfo.TipoDocumento.Equals(Constantes.TipoComprobanteFactura))
                {
                    comprobanteSB.Append(Herramientas.Helper.ObtenerTexto("~/Archivos/Plantillas/FacturaJulcan.html"));
                    #region Factura
                    //comprobanteSB.Replace("@EMPRESA_LOGO", HttpContext.Current.Server.MapPath("~/Imagenes/petroamerica_logo.png"));
                    comprobanteSB.Replace("@EMPRESA_LOGO", String.Empty);
                    comprobanteSB.Replace("@EMPRESA_NOMBRE", ventaInfo.NombreComercialEmisor);
                    comprobanteSB.Replace("@EMPRESA_DIRECCION", ventaInfo.DireccionEmisor);
                    comprobanteSB.Replace("@GRIFO_DIRECCION", String.Empty);
                    comprobanteSB.Replace("@EMPRESA_RUC", ventaInfo.NroDocumentoEmisor);
                    comprobanteSB.Replace("@IMPRESORA", String.Empty);
                    comprobanteSB.Replace("@NUMEROCOMPROBANTE", ventaInfo.IdDocumento);
                    comprobanteSB.Replace("@FECHA", fechaEmision);
                    comprobanteSB.Replace("@FECHA", fechaEmision);

                    comprobanteSB.Replace("@CLIENTE_NOMBRE", ventaInfo.NombreComercialReceptor);
                    comprobanteSB.Replace("@CLIENTE_RUC", ventaInfo.NroDocumentoReceptor);
                    comprobanteSB.Replace("@CLIENTE_PLACA", ventaInfo.PlacaVehiculo);
                    comprobanteSB.Replace("@CLIENTE_DIRECCION", ventaInfo.DireccionReceptor);
                    comprobanteSB.Replace("@CANTIDAD", ventaGasolutionsDetalleInfo.Cantidad.ToString("N2"));
                    comprobanteSB.Replace("@PRECIO", ventaGasolutionsDetalleInfo.PrecioUnitario.ToString("N2"));
                    comprobanteSB.Replace("@MONTO_VENTA", ventaInfo.Gravadas.ToString("N2"));
                    comprobanteSB.Replace("@PRODUCTO", ventaGasolutionsDetalleInfo.Descripcion);
                    comprobanteSB.Replace("@MONEDA_SIMBOLO", ventaInfo.SimboloMoneda);
                    comprobanteSB.Replace("@MONTO_IMPUESTO", ventaInfo.TotalIgv.ToString("N2"));
                    comprobanteSB.Replace("@MONTO_TOTAL", ventaInfo.TotalVenta.ToString("N2"));
                    comprobanteSB.Replace("@VENDEDOR", String.Empty);
                    comprobanteSB.Replace("@CODIGO_HASH", responseFirma.Data.ResumenFirma);

                    comprobanteSB.Replace("@TEXTO_MONTO_TOTAL", NumeroALetras.numeroAletras(ventaInfo.TotalVenta));
                    #endregion

                    nombreArchivoComprobante = "Factura_" + DateTime.Now.ToString("ddMMyyyyhhmmss"); // + ".pdf";
                }
                if (ventaInfo.TipoDocumento.Equals(Constantes.TipoComprobanteBoletaVenta))
                {
                    comprobanteSB.Append(Herramientas.Helper.ObtenerTexto("~/Archivos/Plantillas/BoletaJulcan.html"));
                    #region Boleta
                    //comprobanteSB.Replace("@EMPRESA_LOGO", HttpContext.Current.Server.MapPath("~/Imagenes/petroamerica_logo.png"));
                    comprobanteSB.Replace("@EMPRESA_LOGO", String.Empty);
                    comprobanteSB.Replace("@EMPRESA_NOMBRE", ventaInfo.NombreComercialEmisor);
                    comprobanteSB.Replace("@EMPRESA_DIRECCION", ventaInfo.DireccionEmisor);
                    comprobanteSB.Replace("@GRIFO_DIRECCION", String.Empty);
                    comprobanteSB.Replace("@EMPRESA_RUC", ventaInfo.NroDocumentoEmisor);
                    comprobanteSB.Replace("@IMPRESORA", String.Empty);
                    comprobanteSB.Replace("@NUMEROCOMPROBANTE", ventaInfo.IdDocumento);
                    comprobanteSB.Replace("@FECHA", fechaEmision);
                    comprobanteSB.Replace("@CLIENTE_NOMBRE", ventaInfo.NombreComercialReceptor);
                    comprobanteSB.Replace("@CLIENTE_DIRECCION", ventaInfo.DireccionReceptor);
                    comprobanteSB.Replace("@CANTIDAD", ventaGasolutionsDetalleInfo.Cantidad.ToString("N2"));
                    comprobanteSB.Replace("@PRECIO", ventaGasolutionsDetalleInfo.PrecioUnitario.ToString("N2"));
                    comprobanteSB.Replace("@MONTO_VENTA", ventaInfo.Gravadas.ToString("N2"));
                    comprobanteSB.Replace("@PRODUCTO", ventaGasolutionsDetalleInfo.Descripcion);
                    comprobanteSB.Replace("@MONEDA_SIMBOLO", ventaInfo.SimboloMoneda);
                    comprobanteSB.Replace("@MONTO_IMPUESTO", ventaInfo.TotalIgv.ToString("N2"));
                    comprobanteSB.Replace("@MONTO_TOTAL", ventaInfo.TotalVenta.ToString("N2"));
                    comprobanteSB.Replace("@VENDEDOR", String.Empty);
                    comprobanteSB.Replace("@CODIGO_HASH", responseFirma.Data.ResumenFirma);

                    comprobanteSB.Replace("@TEXTO_MONTO_TOTAL", NumeroALetras.numeroAletras(ventaInfo.TotalVenta));
                    #endregion

                    nombreArchivoComprobante = "Boleta_" + DateTime.Now.ToString("ddMMyyyyhhmmss"); // + ".pdf";
                }

                if (!Directory.Exists(rutaPdfFactura))
                {
                    Directory.CreateDirectory(rutaPdfFactura);
                }

                #region Codigo QR
                var codigoQR = ventaInfo.NroDocumentoReceptor + "|" + ventaInfo.TipoDocumento + "|" + ventaInfo.IdDocumento.Substring(0, 4) + "|" +
                               ventaInfo.IdDocumento.Substring(5, 8) + "|" + ventaInfo.TotalIgv + "|" + ventaInfo.TotalVenta + "|" +
                               ventaInfo.FechaEmision + "|" + ventaInfo.TipoDocumentoReceptor + "|" + ventaInfo.NroDocumentoReceptor + "|" +
                               responseFirma.Data.ResumenFirma + "|" + responseFirma.Data.ValorFirma;

                // instantiate a writer object
                var barcodeWriter = new ZXing.BarcodeWriter();
                // set the barcode format
                barcodeWriter.Format = BarcodeFormat.PDF_417;
                // write text and generate a 2-D barcode as a bitmap
                // barcodeWriter.Write(codigoQR).Save(@"C:\Users\jeremy\Desktop\generated.bmp");
                //barcodeWriter.Write(codigoQR).Save(HostingEnvironment.MapPath("~/Archivos/Documentos/Cliente/" + ventaInfo.NumeroDocumentoCliente + "/" + _documento.IdDocumento + ".bmp"));
                barcodeWriter.Write(codigoQR).Save(rutaPdfFactura + "/" + _documento.IdDocumento + ".bmp");
                #endregion

                comprobanteSB.Replace("@CODIGO_QR", HttpContext.Current.Server.MapPath("~/Archivos/Documentos/Cliente/" + ventaInfo.NroDocumentoReceptor + "/" + _documento.IdDocumento + ".bmp"));


                comprobanteSB = Herramientas.Helper.EncodeHtml(comprobanteSB);
                //var margins = new PageMargins();
                //margins.Left = 1;
                //htmlToComprobante.Margins = margins;

                var pdfBytesFactura = htmlToComprobante.GeneratePdf(comprobanteSB.ToString());


                // var comprobanteImpreso = rutaPdfFactura + "\\" + nombreArchivoComprobante + ".pdf";
                File.WriteAllBytes(rutaPdfFactura + "/" + nombreArchivoComprobante + ".pdf", pdfBytesFactura);
                File.WriteAllBytes(rutaPdfFactura + "/" + nombreArchivoComprobante + ".xml", Convert.FromBase64String(responseFirma.Data.TramaXmlFirmado));
                #endregion

                mensaje = "El Comprobante se generó correctamente" + "@" + nombreArchivoComprobante + "@" + ventaInfo.NroDocumentoReceptor;
            }
            catch (Exception ex)
            {
                bool rethrow = ExceptionPolicy.HandleException(ex, Constantes.ExcepcionPoliticaPresentacion);
                mensaje = rethrow ? ex.Message : Constantes.ExcepcionPoliticaPresentacion;
                // var sex = new SmartException(ex, usuarioInfo.Matricula, codigoOperacion.ToString());
                //RegistrarScript("MostrarMensaje('" + mensaje.Replace("'", "") + "');", "ErrorConsultaComprobante");
                mensaje = (mensaje + "-" + ex.Source) + "@" + "" + "@" + numeroDocumento;
            }
            return(mensaje);
        }
        public FrmFactura2(string nombrereporte, DocumentoElectronico lista)
        {
            InitializeComponent();
            List <Contribuyente>    Emisor   = new List <Contribuyente>();
            ClsDatosReportes        cabecera = new ClsDatosReportes();
            List <ClsDatosReportes> valores  = new List <ClsDatosReportes>();
            List <Contribuyente>    Receptor = new List <Contribuyente>();

            if (lista.Moneda == "PEN")
            {
                cabecera.MonedaLetra = "SOLES";
                cabecera.Moneda      = "S/";
            }
            else
            {
                if (lista.Moneda == "USD")
                {
                    cabecera.MonedaLetra = "DOLARES AMERICANOS";
                    cabecera.Moneda      = "$";
                }
            }
            cabecera.IdDocumento    = lista.IdDocumento;
            cabecera.FechaEmision   = lista.FechaEmision;
            cabecera.Gravadas       = lista.Gravadas;
            cabecera.Inafectas      = lista.Inafectas;
            cabecera.Gratuitas      = lista.Gratuitas;
            cabecera.Exoneradas     = lista.Exoneradas;
            cabecera.TotalIgv       = lista.TotalIgv;
            cabecera.TotalVenta     = lista.TotalVenta;
            cabecera.MontoEnLetras  = lista.MontoEnLetras;
            cabecera.SubTotalVentas = lista.SubTotalVenta;
            cabecera.NumGuia        = lista.NumGuia;

            cabecera.NumeroCajas = lista.Cajas;
            cabecera.Total2      = lista.Total2;
            cabecera.Glosa       = lista.Glosa;

            /*Exportación*/
            cabecera.PuestoOrigen     = lista.PuestoOrigen;
            cabecera.PuestoDestino    = lista.PuestoDestino;
            cabecera.BL               = lista.BL;
            cabecera.Poliza           = lista.Poliza;
            cabecera.CC               = lista.CC;
            cabecera.CondicionVenta   = lista.CondicionVenta;
            cabecera.Asegurado        = lista.Asegurado;
            cabecera.Intermedio       = lista.Intermedio;
            cabecera.PesoNeto         = lista.PesoNeto;
            cabecera.PesoBruto        = lista.PesoBruto;
            cabecera.NumGuia          = lista.NumGuia;
            cabecera.CalculoDetracion = (lista.CalculoDetraccion * 100).ToString("0");
            cabecera.MontoDetracion   = lista.MontoDetraccion.ToString("#0.00");
            cabecera.CalculoDetracion = "(" + cabecera.CalculoDetracion + "%)";
            cabecera.Dracwback        = lista.Drawback;
            cabecera.NumeroCajas      = lista.Cajas;
            cabecera.Booking          = lista.Booking;

            valores.Add(cabecera);
            Emisor.Add(lista.Emisor);
            Receptor.Add(lista.Receptor);

            this.rptact   = nombrereporte;
            this.lst      = lista.Items;
            this.empresa  = Emisor;
            this.general  = valores;
            this.receptor = Receptor;
            this.otros    = valores;
        }